Skip to content

Commit

Permalink
analyze: additional rewriter output options
Browse files Browse the repository at this point in the history
  • Loading branch information
spernsteiner committed Mar 16, 2024
1 parent 35d8394 commit ee7b6b9
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 11 deletions.
13 changes: 10 additions & 3 deletions c2rust-analyze/src/analyze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1581,9 +1581,16 @@ fn run(tcx: TyCtxt) {

// Apply rewrite to all functions at once.
let mut update_files = rewrite::UpdateFiles::No;
if let Ok(val) = env::var("C2RUST_ANALYZE_REWRITE_IN_PLACE") {
if val == "1" {
update_files = rewrite::UpdateFiles::Yes;
if let Ok(val) = env::var("C2RUST_ANALYZE_REWRITE_MODE") {
match val.as_str() {
"none" => {}
"inplace" => {
update_files = rewrite::UpdateFiles::InPlace;
}
"alongside" => {
update_files = rewrite::UpdateFiles::Alongside;
}
_ => panic!("bad value {:?} for C2RUST_ANALYZE_REWRITE_MODE", val),
}
}
rewrite::apply_rewrites(tcx, all_rewrites, annotations, update_files);
Expand Down
44 changes: 38 additions & 6 deletions c2rust-analyze/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ use analyze::AnalysisCallbacks;
use anyhow::anyhow;
use anyhow::ensure;
use anyhow::Context;
use clap::{ArgAction, Parser};
use clap::{ArgAction, Parser, ValueEnum};
use rustc_driver::RunCompiler;
use rustc_driver::TimePassesCallbacks;
use rustc_session::config::CrateType;
Expand Down Expand Up @@ -78,10 +78,16 @@ struct Args {
/// from this list will be marked non-rewritable (`FIXED`).
#[clap(long, action(ArgAction::Append))]
rewrite_paths: Vec<OsString>,
/// Rewrite source files on disk. The default is to print the rewritten source code to stdout
/// as part of the tool's debug output.
#[clap(long)]

/// Whether to rewrite source files on disk. The default is to print the rewritten source code
/// to stdout as part of the tool's debug output.
#[clap(long, value_enum)]
rewrite_mode: Option<RewriteMode>,

/// Synonym for `--rewrite-mode inplace`, kept around for backward compatibility.
#[clap(long, hide(true), conflicts_with("rewrite_mode"))]
rewrite_in_place: bool,

/// Use `todo!()` placeholders in shims for casts that must be implemented manually.
///
/// When a function requires a shim, and the shim requires a cast that can't be generated
Expand Down Expand Up @@ -114,6 +120,19 @@ struct InterceptedCargoArgs {
extra_args: Vec<OsString>,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum RewriteMode {
/// Do not write rewritten code to disk.
#[value(name = "none")]
None,
/// Apply rewrites to the original source files in-place.
#[value(name = "inplace")]
InPlace,
/// Save rewritten code to a separate file alongside each source file.
#[value(name = "alongside")]
Alongside,
}

fn exit_with_status(status: ExitStatus) {
process::exit(status.code().unwrap_or(1))
}
Expand Down Expand Up @@ -353,6 +372,7 @@ fn cargo_wrapper(rustc_wrapper: &Path) -> anyhow::Result<()> {
let Args {
rustflags,
rewrite_paths,
mut rewrite_mode,
rewrite_in_place,
use_manual_shims,
fixed_defs_list,
Expand All @@ -369,6 +389,13 @@ fn cargo_wrapper(rustc_wrapper: &Path) -> anyhow::Result<()> {
let manifest_path = manifest_path.as_deref();
let _manifest_dir = manifest_path.and_then(|path| path.parent());

if rewrite_in_place {
// `rewrite_in_place` and `rewrite_mode` are annotated as conflicting options, so if both
// are set, `Args::parse()` should have exited with an error.
assert!(rewrite_mode.is_none());
rewrite_mode = Some(RewriteMode::InPlace);
}

set_rust_toolchain()?;

// Resolve the sysroot once in the [`cargo_wrapper`]
Expand Down Expand Up @@ -401,8 +428,13 @@ fn cargo_wrapper(rustc_wrapper: &Path) -> anyhow::Result<()> {
cmd.env("C2RUST_ANALYZE_REWRITE_PATHS", rewrite_paths);
}

if rewrite_in_place {
cmd.env("C2RUST_ANALYZE_REWRITE_IN_PLACE", "1");
if let Some(rewrite_mode) = rewrite_mode {
let val = match rewrite_mode {
RewriteMode::None => "none",
RewriteMode::InPlace => "inplace",
RewriteMode::Alongside => "alongside",
};
cmd.env("C2RUST_ANALYZE_REWRITE_MODE", val);
}

if use_manual_shims {
Expand Down
10 changes: 8 additions & 2 deletions c2rust-analyze/src/rewrite/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,8 @@ fn add_annotations(
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum UpdateFiles {
No,
Yes,
InPlace,
Alongside,
}

pub fn apply_rewrites(
Expand All @@ -331,10 +332,15 @@ pub fn apply_rewrites(
}
println!(" ===== END {:?} =====", filename);

if update_files == UpdateFiles::Yes {
if matches!(update_files, UpdateFiles::InPlace | UpdateFiles::Alongside) {
let mut path_ok = false;
if let FileName::Real(ref rfn) = filename {
if let Some(path) = rfn.local_path() {
let path = match update_files {
UpdateFiles::InPlace => path.to_owned(),
UpdateFiles::Alongside => path.with_extension("new.rs"),
_ => unreachable!(),
};
fs::write(path, src).unwrap();
path_ok = true;
}
Expand Down

0 comments on commit ee7b6b9

Please sign in to comment.