Skip to main content

charon_driver/
main.rs

1//! The Charon driver, which calls Rustc with callbacks to compile some Rust
2//! crate to LLBC.
3// For rustdoc: prevents overflows
4#![recursion_limit = "256"]
5#![feature(rustc_private)]
6#![allow(clippy::arc_with_non_send_sync)]
7#![allow(clippy::borrowed_box)]
8#![allow(clippy::derivable_impls)]
9#![allow(clippy::field_reassign_with_default)]
10#![allow(clippy::manual_map)]
11#![allow(clippy::mem_replace_with_default)]
12#![allow(clippy::useless_format)]
13#![feature(deref_patterns)]
14#![feature(iter_array_chunks)]
15#![feature(iterator_try_collect)]
16#![feature(macro_metavar_expr)]
17#![feature(sized_hierarchy)]
18#![feature(trait_alias)]
19#![feature(type_changing_struct_update)]
20
21extern crate rustc_abi;
22extern crate rustc_apfloat;
23extern crate rustc_ast;
24extern crate rustc_ast_pretty;
25extern crate rustc_attr_ir;
26extern crate rustc_const_eval;
27extern crate rustc_data_structures;
28extern crate rustc_driver;
29extern crate rustc_error_messages;
30extern crate rustc_errors;
31extern crate rustc_hashes;
32extern crate rustc_hir;
33extern crate rustc_hir_analysis;
34extern crate rustc_index;
35extern crate rustc_infer;
36extern crate rustc_interface;
37extern crate rustc_lexer;
38extern crate rustc_middle;
39extern crate rustc_mir_build;
40extern crate rustc_mir_transform;
41extern crate rustc_session;
42extern crate rustc_span;
43extern crate rustc_target;
44extern crate rustc_trait_selection;
45extern crate rustc_type_ir;
46
47#[macro_use]
48extern crate charon_lib;
49
50mod driver;
51#[macro_use]
52pub mod hax;
53mod translate;
54
55use charon_lib::{export, logger, transform::run_transformation_passes};
56use std::{fmt, panic};
57
58pub enum CharonFailure {
59    /// The usize is the number of errors.
60    CharonError(usize),
61    RustcError,
62    Panic,
63    Serialize,
64}
65
66impl fmt::Display for CharonFailure {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            CharonFailure::RustcError => write!(f, "Code failed to compile")?,
70            CharonFailure::CharonError(err_count) => write!(
71                f,
72                "Charon failed to translate this code ({err_count} errors)"
73            )?,
74            CharonFailure::Panic => write!(f, "Compilation panicked")?,
75            CharonFailure::Serialize => write!(f, "Could not serialize output file")?,
76        }
77        Ok(())
78    }
79}
80
81/// Run charon. Returns the number of warnings generated.
82fn run_charon() -> Result<usize, CharonFailure> {
83    // Run the driver machinery.
84    let Some((mut ctx, options)) = driver::run_rustc_driver()? else {
85        // We didn't run charon.
86        return Ok(0);
87    };
88
89    // The bulk of the translation is done, we no longer need to interact with rustc internals. We
90    // run several passes that simplify the items and cleanup the bodies.
91    run_transformation_passes(&options, &mut ctx);
92
93    let error_count = ctx.errors.borrow().error_count;
94
95    // # Final step: generate the files.
96    let targets = options.targets(&ctx.translated.crate_name);
97    trace!("Targets: {:?}", targets);
98    export::CrateData::new(ctx)
99        .serialize_to_files(targets)
100        .map_err(|()| CharonFailure::Serialize)?;
101
102    if options.error_on_warnings && error_count != 0 {
103        return Err(CharonFailure::CharonError(error_count));
104    }
105
106    Ok(error_count)
107}
108
109fn main() {
110    // Initialize the logger
111    logger::initialize_logger();
112
113    // Catch any and all panics coming from charon to display a clear error.
114    let res = panic::catch_unwind(run_charon)
115        .map_err(|_| CharonFailure::Panic)
116        .and_then(|x| x);
117
118    match res {
119        Ok(warn_count) => {
120            if warn_count != 0 {
121                let msg = format!("The extraction generated {} warnings", warn_count);
122                eprintln!("warning: {}", msg);
123            }
124        }
125        Err(err) => {
126            log::error!("{err}");
127            let exit_code = match err {
128                CharonFailure::CharonError(_) | CharonFailure::Serialize => 1,
129                CharonFailure::RustcError => 2,
130                // This is a real panic, exit with the standard rust panic error code.
131                CharonFailure::Panic => 101,
132            };
133            std::process::exit(exit_code);
134        }
135    }
136}