Skip to content

Commit

Permalink
ISLE: run rustfmt on generated code
Browse files Browse the repository at this point in the history
  • Loading branch information
fitzgen committed Nov 5, 2021
1 parent 4ee093f commit 47bdf2f
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion cranelift/codegen/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,44 @@ fn rebuild_isle(crate_dir: &std::path::Path) -> Result<(), Box<dyn std::error::E
impl std::error::Error for DebugReport {}
})?;

let code = rustfmt(&code).unwrap_or_else(|e| {
println!(
"cargo:warning=Failed to run `rustfmt` on ISLE-generated code: {:?}",
e
);
code
});

println!("Writing ISLE-generated Rust code to {}", out_file.display());
std::fs::write(out_file, code)?;
}

Ok(())
return Ok(());

fn rustfmt(code: &str) -> std::io::Result<String> {
use std::io::Write;

let mut rustfmt = std::process::Command::new("rustfmt")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()?;

let mut stdin = rustfmt.stdin.take().unwrap();
stdin.write_all(code.as_bytes())?;
drop(stdin);

let mut stdout = rustfmt.stdout.take().unwrap();
let mut data = vec![];
stdout.read_to_end(&mut data)?;

let status = rustfmt.wait()?;
if !status.success() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("`rustfmt` exited with status {}", status),
));
}

Ok(String::from_utf8(data).expect("rustfmt always writs utf-8 to stdout"))
}
}

0 comments on commit 47bdf2f

Please sign in to comment.