Skip to main content

cairo_lang_executable/
compile.rs

1use std::path::Path;
2
3use anyhow::Result;
4use cairo_lang_compiler::db::RootDatabase;
5use cairo_lang_compiler::diagnostics::DiagnosticsReporter;
6use cairo_lang_compiler::project::setup_project;
7use cairo_lang_compiler::{ensure_diagnostics, get_sierra_program_for_functions};
8use cairo_lang_debug::debug::DebugWithDb;
9use cairo_lang_executable_plugin::{
10    EXECUTABLE_PREFIX, EXECUTABLE_RAW_ATTR, executable_plugin_suite,
11};
12use cairo_lang_filesystem::cfg::{Cfg, CfgSet};
13use cairo_lang_filesystem::ids::{CrateId, CrateInput};
14use cairo_lang_lowering::ids::ConcreteFunctionWithBodyId;
15use cairo_lang_runnable_utils::builder::{
16    CasmProgramWrapperInfo, EntryCodeConfig, RunnableBuilder,
17};
18use cairo_lang_sierra_generator::db::SierraGenGroup;
19use cairo_lang_sierra_generator::debug_info::SierraProgramDebugInfo;
20use cairo_lang_sierra_generator::executables::find_executable_function_ids;
21use cairo_lang_sierra_generator::program_generator::SierraProgramWithDebug;
22use cairo_lang_sierra_to_casm::compiler::CairoProgram;
23use cairo_lang_utils::CloneableDatabase;
24use cairo_vm::types::builtin_name::BuiltinName;
25use itertools::Itertools;
26use salsa::Database;
27
28/// The CASM compilation result.
29pub struct CompiledFunction {
30    /// The compiled CASM program.
31    pub program: CairoProgram,
32    /// The wrapper information for the program.
33    pub wrapper: CasmProgramWrapperInfo,
34}
35impl std::fmt::Display for CompiledFunction {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        write!(f, "// builtins:")?;
38        if !self.wrapper.builtins.is_empty() {
39            write!(f, " {}", self.wrapper.builtins.iter().map(|b| b.to_str()).format(", "))?;
40        }
41        writeln!(f)?;
42        writeln!(f, "// header")?;
43        for instruction in &self.wrapper.header {
44            writeln!(f, "{instruction};")?;
45        }
46        writeln!(f, "// sierra based code")?;
47        write!(f, "{}", self.program)?;
48        writeln!(f, "// footer")?;
49        for instruction in &self.wrapper.footer {
50            writeln!(f, "{instruction};")?;
51        }
52        Ok(())
53    }
54}
55
56#[derive(Debug, Clone, Default)]
57pub struct ExecutableConfig {
58    /// If true, will allow syscalls in the program.
59    ///
60    /// In general, syscalls are not allowed in executables, as they are currently not verified.
61    pub allow_syscalls: bool,
62
63    /// Replace the panic flow with an unprovable opcode, this reduces code size but might make it
64    /// more difficult to debug.
65    pub unsafe_panic: bool,
66
67    /// An optional list of builtins to use in the entry code (if its none the builtins will be
68    /// inferred from the param_types).
69    pub builtin_list: Option<Vec<BuiltinName>>,
70}
71
72/// Represents the output of compiling an executable.
73///
74/// Includes the `CompiledFunction` along with supplementary objects useful for profiling.
75pub struct CompileExecutableResult<'db> {
76    /// The compiled function.
77    pub compiled_function: CompiledFunction,
78    /// A runnable builder with the program corresponding to the compiled function.
79    pub builder: RunnableBuilder,
80    /// The debug info for the Sierra program in the builder.
81    pub debug_info: SierraProgramDebugInfo<'db>,
82}
83
84/// Prepares a `RootDatabase` configured for compiling `#[executable]` functions.
85///
86/// This only builds the database; use `setup_project` and the compilation helpers
87/// on top of it to actually compile code.
88pub fn prepare_db(config: &ExecutableConfig) -> Result<RootDatabase> {
89    let mut builder = RootDatabase::builder();
90    builder
91        .skip_auto_withdraw_gas()
92        .with_cfg(CfgSet::from_iter([Cfg::kv("gas", "disabled")]))
93        .detect_corelib()
94        .with_default_plugin_suite(executable_plugin_suite());
95    if config.unsafe_panic {
96        builder.with_unsafe_panic();
97    }
98
99    builder.build()
100}
101
102/// Compile the function given by path.
103/// Errors if there is ambiguity.
104pub fn compile_executable<'db>(
105    db: &'db mut dyn CloneableDatabase,
106    path: &Path,
107    executable_path: Option<&str>,
108    diagnostics_reporter: DiagnosticsReporter<'_>,
109    config: ExecutableConfig,
110) -> Result<CompileExecutableResult<'db>> {
111    let main_crate_inputs = setup_project(db, path)?;
112    let diagnostics_reporter = diagnostics_reporter.with_crates(&main_crate_inputs);
113    let main_crate_ids = CrateInput::into_crate_ids(db, main_crate_inputs);
114
115    compile_executable_in_prepared_db(
116        db,
117        executable_path,
118        main_crate_ids,
119        diagnostics_reporter,
120        config,
121    )
122}
123
124/// Runs compiler on the specified executable function.
125/// If no executable was specified, verify that there is only one.
126/// Otherwise, return an error.
127pub fn compile_executable_in_prepared_db<'db>(
128    db: &'db dyn CloneableDatabase,
129    executable_path: Option<&str>,
130    main_crate_ids: Vec<CrateId<'db>>,
131    mut diagnostics_reporter: DiagnosticsReporter<'_>,
132    config: ExecutableConfig,
133) -> Result<CompileExecutableResult<'db>> {
134    ensure_diagnostics(db, &mut diagnostics_reporter)?;
135
136    let executables = find_executable_functions(db, main_crate_ids, executable_path);
137
138    match executables.iter().exactly_one() {
139        Ok(executable) => compile_executable_function_in_prepared_db(db, *executable, config),
140        Err(_) if executables.is_empty() => {
141            anyhow::bail!("Requested `#[executable]` not found.");
142        }
143        Err(_) => {
144            let executable_names = executables
145                .into_iter()
146                .map(|executable| originating_function_path(db, executable))
147                .join("\n  ");
148            anyhow::bail!(
149                "More than one executable found in the main crate: \n  {}\nUse --executable to \
150                 specify which to compile.",
151                executable_names
152            );
153        }
154    }
155}
156
157/// Search crates identified by `main_crate_ids` for executable functions.
158/// If `executable_path` is provided, only functions with exactly the same path will be returned.
159pub fn find_executable_functions<'db>(
160    db: &'db dyn Database,
161    main_crate_ids: Vec<CrateId<'db>>,
162    executable_path: Option<&str>,
163) -> Vec<ConcreteFunctionWithBodyId<'db>> {
164    let mut executables: Vec<_> = find_executable_function_ids(db, main_crate_ids)
165        .into_iter()
166        .filter_map(|(id, labels)| {
167            labels.into_iter().any(|ssid| ssid.long(db) == EXECUTABLE_RAW_ATTR).then_some(id)
168        })
169        .collect();
170
171    if let Some(executable_path) = executable_path {
172        executables
173            .retain(|executable| originating_function_path(db, *executable) == executable_path);
174    };
175    executables
176}
177
178/// Returns the path to the function that the executable is wrapping.
179///
180/// If the executable is not wrapping a function, returns the full path of the executable.
181pub fn originating_function_path<'db>(
182    db: &'db dyn Database,
183    wrapper: ConcreteFunctionWithBodyId<'db>,
184) -> String {
185    let semantic = wrapper.base_semantic_function(db);
186    let wrapper_name = semantic.name(db).long(db).as_str();
187    let wrapper_full_path = semantic.full_path(db);
188    let Some(wrapped_name) = wrapper_name.strip_prefix(EXECUTABLE_PREFIX) else {
189        return wrapper_full_path;
190    };
191    let Some(wrapper_path_to_module) = wrapper_full_path.strip_suffix(wrapper_name) else {
192        return wrapper_full_path;
193    };
194    format!("{wrapper_path_to_module}{wrapped_name}")
195}
196
197/// Runs the executable compiler on the specified function in a prepared database.
198///
199/// Diagnostics are expected to have been checked by the caller (for example via
200/// [`compile_executable_in_prepared_db`]).
201///
202/// # Arguments
203/// * `db` - Preloaded compilation database.
204/// * `executable` - The [`ConcreteFunctionWithBodyId`] to compile.
205/// * `config` - Configuration for executables (e.g. syscall allowance and panic behavior).
206/// # Returns
207/// * `Ok(CompileExecutableResult<'db>)` - The compiled CASM program and associated metadata.
208/// * `Err(anyhow::Error)` - Compilation failed.
209pub fn compile_executable_function_in_prepared_db<'db>(
210    db: &'db dyn CloneableDatabase,
211    executable: ConcreteFunctionWithBodyId<'db>,
212    config: ExecutableConfig,
213) -> Result<CompileExecutableResult<'db>> {
214    let SierraProgramWithDebug { program: sierra_program, debug_info } =
215        get_sierra_program_for_functions(db, vec![executable])?;
216    if !config.allow_syscalls {
217        // Finding if any syscall libfuncs are used in the program.
218        // If any are found, the compilation will fail, as syscalls are not proved in executables.
219        for libfunc in &sierra_program.libfunc_declarations {
220            if libfunc.long_id.generic_id.0.ends_with("_syscall") {
221                anyhow::bail!(
222                    "The function is using libfunc `{}`. Syscalls are not supported in \
223                     `#[executable]`.",
224                    libfunc.long_id.generic_id
225                );
226            }
227        }
228    }
229
230    // Since we build the entry point asking for a single function - we know it will be first, and
231    // that it will be available.
232    let executable_func = sierra_program.funcs[0].clone();
233    assert_eq!(executable_func.id, db.intern_sierra_function(executable.function_id(db).unwrap()));
234    let builder = RunnableBuilder::new(sierra_program.clone(), None).map_err(|err| {
235        let mut locs = vec![];
236        for stmt_idx in err.stmt_indices() {
237            if let Some(loc) =
238                debug_info.statements_locations.statement_diagnostic_location(db, stmt_idx)
239            {
240                locs.push(format!("#{stmt_idx} {:?}", loc.debug(db)))
241            }
242        }
243        anyhow::anyhow!("Failed to create runnable builder: {}\n{}", err, locs.join("\n"))
244    })?;
245
246    // If syscalls are allowed it means we allow for unsound programs.
247    let allow_unsound = config.allow_syscalls;
248    let wrapper = builder.create_wrapper_info(
249        &executable_func,
250        EntryCodeConfig::executable(allow_unsound, config.builtin_list),
251    )?;
252    let compiled_function = CompiledFunction { program: builder.casm_program().clone(), wrapper };
253    Ok(CompileExecutableResult { compiled_function, builder, debug_info: debug_info.clone() })
254}