Skip to content

Commit

Permalink
feat: compile scarb contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
enitrat committed Sep 23, 2024
1 parent 0e96dff commit d1d89d6
Showing 1 changed file with 49 additions and 5 deletions.
54 changes: 49 additions & 5 deletions src/bin/scarb-native-dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,15 @@ fn main() -> anyhow::Result<()> {
let native_context = NativeContext::new();
for package in metadata.packages.iter() {
for target in &package.targets {
let file_path = target_dir.join(format!("{}.sierra.json", target.name.clone()));
let lib_file_path = target_dir.join(format!("{}.sierra.json", target.name.clone()));
println!("Compiling {:?}", lib_file_path);

if file_path.exists() {
if lib_file_path.exists() {
let compiled = serde_json::from_str::<VersionedProgram>(
&fs::read_to_string(file_path.clone())
.with_context(|| format!("failed to read file: {file_path}"))?,
&fs::read_to_string(lib_file_path.clone())
.with_context(|| format!("failed to read file: {lib_file_path}"))?,
)
.with_context(|| format!("failed to deserialize compiled file: {file_path}"))?;
.with_context(|| format!("failed to deserialize compiled file: {lib_file_path}"))?;

// Compile the sierra program into a MLIR module.
let native_module = native_context
Expand All @@ -50,6 +51,49 @@ fn main() -> anyhow::Result<()> {
&output_str,
)?;
}

let contract_files = fs::read_dir(&target_dir)
.with_context(|| format!("failed to read directory: {}", target_dir.display()))?
.filter_map(Result::ok)
.filter(|entry| entry.file_type().map(|ft| ft.is_file()).unwrap_or(false))
.filter_map(|entry| {
let path = entry.path();
path.extension()
.and_then(|ext| ext.to_str())
.filter(|&ext| ext == "json")
.and_then(|_| path.file_name())
.and_then(|name| name.to_str())
.filter(|name| name.starts_with(&target.name) && name.ends_with(".contract_class.json"))
.map(|_| path)
});


for contract_file_path in contract_files {
let sierra_contract_class: cairo_lang_starknet_classes::contract_class::ContractClass = serde_json::from_str(
&fs::read_to_string(&contract_file_path)
.with_context(|| format!("failed to read file: {}", contract_file_path.display()))?,
)
.with_context(|| format!("failed to deserialize compiled file: {}", contract_file_path.display()))?;

let sierra_program = sierra_contract_class.extract_sierra_program()?;

// Compile the sierra program into a MLIR module.
let native_module = native_context
.compile(&sierra_program, false)
.unwrap();

// Write the output.
let output_str = native_module.module().as_operation().to_string_with_flags(
OperationPrintingFlags::new().enable_debug_info(true, false),
)?;

let output_file_name = contract_file_path.file_name().unwrap().to_str().unwrap()
.replace(".json", ".mlir");
fs::write(
target_dir.join(output_file_name),
&output_str,
)?;
}
}
}

Expand Down

0 comments on commit d1d89d6

Please sign in to comment.