cairo_lang_executable/
compile.rs1use 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
28pub struct CompiledFunction {
30 pub program: CairoProgram,
32 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 pub allow_syscalls: bool,
62
63 pub unsafe_panic: bool,
66
67 pub builtin_list: Option<Vec<BuiltinName>>,
70}
71
72pub struct CompileExecutableResult<'db> {
76 pub compiled_function: CompiledFunction,
78 pub builder: RunnableBuilder,
80 pub debug_info: SierraProgramDebugInfo<'db>,
82}
83
84pub 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
102pub 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
124pub 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
157pub 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
178pub 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
197pub 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 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 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 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}