1pub(crate) mod binder_key;
2pub(crate) mod budget;
3mod context;
4pub(crate) mod datum;
5mod emit;
6pub(crate) mod expr;
7pub(crate) mod join;
8mod layout;
9mod native;
10mod observations;
11mod recompile;
12mod settle;
13pub mod special;
14pub(crate) mod stats;
15
16use tracing::debug;
17
18use crate::ast::{Expr, Program, WasmType};
19use crate::error::{Error, Result};
20use crate::host_fn::HostFnSpec;
21use crate::runtime::SymbolTable;
22
23pub(crate) use native::registered_names as native_names;
24
25use context::CompileContext;
26pub use context::{PROLOGUE_DONE_EXPORT, global_export_name, instance_export_name};
27use emit::FunctionEmitter;
28use stats::CompileStats;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum CompileMode {
39 Script,
40 Eval,
41}
42
43pub struct Compiler {
44 host_fns: Vec<HostFnSpec>,
45 stats: CompileStats,
46}
47
48impl Compiler {
49 #[must_use]
50 pub fn new() -> Self {
51 Self::with_host_fns(Vec::new())
52 }
53
54 #[must_use]
58 pub fn with_host_fns(host_fns: Vec<HostFnSpec>) -> Self {
59 Self {
60 host_fns,
61 stats: CompileStats::default(),
62 }
63 }
64
65 pub fn compile(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
66 self.compile_with_mode(program, symbols, CompileMode::Script)
67 }
68
69 pub fn compile_with_mode(
70 &mut self,
71 program: &Program,
72 symbols: &mut SymbolTable,
73 mode: CompileMode,
74 ) -> Result<Vec<u8>> {
75 debug!(expr_count = program.exprs.len(), ?mode, "compilation start");
76 match mode {
77 CompileMode::Script => self.compile_script(program, symbols),
78 CompileMode::Eval => self.compile_eval(program, symbols),
79 }
80 }
81
82 fn compile_script(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
83 self.settle(
84 program,
85 symbols,
86 CompileContext::new_with_host_fns,
87 |this, ctx, program, symbols| this.lower_script(ctx, program, symbols),
88 )
89 .map(|(wasm, ())| wasm)
90 }
91
92 fn settle<T>(
94 &mut self,
95 program: &Program,
96 symbols: &mut SymbolTable,
97 new_ctx: fn(&[HostFnSpec]) -> Result<CompileContext>,
98 lower: impl Fn(&Self, &mut CompileContext, &Program, &mut SymbolTable) -> Result<T>,
99 ) -> Result<(Vec<u8>, T)> {
100 self.stats = CompileStats::default();
101 symbols.reset_budget();
102 settle::settle_homes(symbols, |symbols| {
103 symbols.reset_measurements();
104 symbols.forget_unit_closures();
105 let mut ctx = new_ctx(&self.host_fns)?;
106 let lowered = lower(self, &mut ctx, program, symbols);
107 self.record_stats(ctx.compile_stats(), symbols);
108 let value = lowered?;
109 let closures = ctx.take_closure_sources();
110 let wasm = ctx.finish();
111 validate_module(&wasm)?;
112 symbols.finish_unit(closures);
113 debug!(wasm_size = wasm.len(), "compilation complete");
114 Ok((wasm, value))
115 })
116 }
117
118 fn lower_script(
119 &self,
120 ctx: &mut CompileContext,
121 program: &Program,
122 symbols: &mut SymbolTable,
123 ) -> Result<()> {
124 let bootstrap_helper_count = ctx.pending_helper_count();
133
134 let mut process = FunctionEmitter::new();
135
136 ctx.emit_boundary_wrapper(&mut process, None, |ctx, emit| {
140 emit.call(ctx.ids.get_output_offset()?);
142 emit.local_set(expr::LOCAL_OUTPUT_BASE);
143 expr::compile_program(ctx, emit, symbols, program)
144 })?;
145
146 let process_locals = ctx.build_locals_declaration()?;
147 ctx.reset_locals(symbols);
148
149 let should_apply = self.build_should_apply(ctx, symbols)?;
150 expr::fill_any_call_helpers(ctx)?;
151 ctx.add_should_apply(should_apply, bootstrap_helper_count);
152 ctx.add_process(process.finish(&process_locals)?);
153 Ok(())
154 }
155
156 fn compile_eval(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
157 let (wasm, _ty) = self.compile_eval_with_type(program, symbols)?;
158 Ok(wasm)
159 }
160
161 pub fn compile_eval_with_type(
167 &mut self,
168 program: &Program,
169 symbols: &mut SymbolTable,
170 ) -> Result<(Vec<u8>, Option<WasmType>)> {
171 self.settle(
172 program,
173 symbols,
174 CompileContext::new_eval_with_host_fns,
175 |_, ctx, program, symbols| Self::lower_eval(ctx, program, symbols),
176 )
177 }
178
179 fn lower_eval(
180 ctx: &mut CompileContext,
181 program: &Program,
182 symbols: &mut SymbolTable,
183 ) -> Result<Option<WasmType>> {
184 let mut emit = FunctionEmitter::new();
185
186 let mut result_ty: Option<WasmType> = None;
191 ctx.emit_boundary_wrapper(&mut emit, Some(WasmType::AnyRef), |ctx, emit| {
192 if program.exprs.is_empty() {
193 expr::prepare_unit(symbols, &program.exprs, CompileMode::Eval)?;
194 emit.ref_null_any();
195 return Ok(());
196 }
197 expr::begin_unit(ctx, emit, symbols, &program.exprs, CompileMode::Eval)?;
198 result_ty = Self::compile_eval_forms(ctx, emit, symbols, program)?;
199 Ok(())
200 })?;
201
202 let locals = ctx.build_locals_declaration()?;
203 ctx.reset_locals(symbols);
204 expr::fill_any_call_helpers(ctx)?;
205 ctx.add_nomi_eval(emit.finish(&locals)?);
206 Ok(result_ty)
207 }
208
209 fn compile_eval_forms(
212 ctx: &mut CompileContext,
213 emit: &mut FunctionEmitter,
214 symbols: &mut SymbolTable,
215 program: &Program,
216 ) -> Result<Option<WasmType>> {
217 let Some((last, init)) = program.exprs.split_last() else {
218 return Err(Error::Compile("empty eval unit".into()));
219 };
220 for expr in init {
221 expr::compile_for_effect(ctx, emit, symbols, expr)?;
222 }
223 if is_definition_form(last) {
224 expr::compile_for_effect(ctx, emit, symbols, last)?;
225 emit.ref_null_any();
226 return Ok(None);
227 }
228 let ty = expr::compile_for_stack(ctx, emit, symbols, last)?;
229 emit_to_anyref(ctx, emit, ty);
230 Ok(Some(ty))
231 }
232
233 fn record_stats(&mut self, stats: CompileStats, symbols: &SymbolTable) {
236 let measured = symbols.measurements();
237 let (stored_globals, possibly_storing, opaque_macro_uses) = measured.store_scan();
238 self.stats = self.stats.after_attempt(CompileStats {
239 folds: measured.folds(),
240 probe_walks: measured.walks(),
241 macro_bodies_reading_globals: measured.macro_global_reads(),
242 stored_globals,
243 possibly_storing,
244 opaque_macro_uses,
245 ..stats
246 });
247 debug!(
248 folds = self.stats.folds,
249 macro_bodies_reading_globals = self.stats.macro_bodies_reading_globals,
250 "compile stats"
251 );
252 }
253
254 fn build_should_apply(
255 &self,
256 ctx: &mut CompileContext,
257 symbols: &mut SymbolTable,
258 ) -> Result<wasm_encoder::Function> {
259 let body = symbols
260 .lookup("SHOULD-APPLY")
261 .and_then(|s| s.function().cloned());
262
263 let Some(Expr::Lambda(params, body)) = body else {
264 return Ok(CompileContext::default_should_apply());
265 };
266
267 if !params.required.is_empty() {
268 return Err(Error::Compile(
269 "SHOULD-APPLY must take no parameters".to_string(),
270 ));
271 }
272
273 debug!("compiling custom should-apply");
274 let mut emit = FunctionEmitter::new();
275 let mut symbols = symbols.clone();
276 symbols.enter_function_body(binder_key::function_owner(&symbols, None, &body));
277 symbols.drop_runtime_locals();
278 let symbols = &mut symbols;
279
280 ctx.emit_boundary_wrapper(&mut emit, Some(WasmType::I32), |ctx, emit| {
283 ctx.call_instances_init(emit)?;
284 let ty = expr::compile_for_stack(ctx, emit, symbols, &body)?;
285 match ty {
286 WasmType::I32 | WasmType::Bool => Ok(()),
290 WasmType::Ratio => {
291 emit.struct_get(ctx.ids.ty_ratio, 0);
292 emit.i64_const(0);
293 emit.i64_ne();
294 Ok(())
295 }
296 _ => Err(Error::Compile(
297 "SHOULD-APPLY must return a boolean or numeric value".to_string(),
298 )),
299 }
300 })?;
301
302 let locals = ctx.build_locals_declaration()?;
303 ctx.reset_locals(symbols);
304 emit.finish(&locals)
305 }
306}
307
308fn emit_to_anyref(ctx: &CompileContext, emit: &mut FunctionEmitter, ty: WasmType) {
316 match ty {
317 WasmType::I32 => {
318 emit.i64_extend_i32_s();
319 emit.call(ctx.ids.ratio_from_i64);
320 }
321 WasmType::Bool => expr::emit_box_anyref(ctx, emit, ty),
322 WasmType::Ratio
323 | WasmType::Commodity
324 | WasmType::StringRef
325 | WasmType::SymbolRef
326 | WasmType::PairRef(_)
327 | WasmType::EntityRef(_)
328 | WasmType::StructRef(_)
329 | WasmType::Closure(_)
330 | WasmType::AnyRef => {}
331 }
332}
333
334#[must_use]
343pub fn wasm_validation_features() -> wasmparser::WasmFeatures {
344 use wasmparser::WasmFeatures;
345
346 WasmFeatures::default()
347 | WasmFeatures::GC
348 | WasmFeatures::REFERENCE_TYPES
349 | WasmFeatures::FUNCTION_REFERENCES
350 | WasmFeatures::EXCEPTIONS
351}
352
353fn validate_module(wasm: &[u8]) -> Result<()> {
359 wasmparser::Validator::new_with_features(wasm_validation_features())
360 .validate_all(wasm)
361 .map_err(|e| Error::Compile(format!("emitted module failed wasm validation: {e}")))?;
362 Ok(())
363}
364
365fn is_definition_form(expr: &Expr) -> bool {
366 let Expr::List(elems) = expr else {
367 return false;
368 };
369 let Some(Expr::Symbol(name)) = elems.first() else {
370 return false;
371 };
372 matches!(
373 name.as_str(),
374 "DEFUN" | "DEFVAR" | "DEFMACRO" | "DEFPARAMETER" | "DEFSTRUCT"
375 )
376}
377
378impl Default for Compiler {
379 fn default() -> Self {
380 Self::new()
381 }
382}
383
384#[cfg(test)]
385#[path = "mod_tests.rs"]
386mod tests;
387
388#[cfg(test)]
389mod behaviour_oracle;
390
391#[cfg(test)]
392mod behaviour_snapshot;
393
394#[cfg(test)]
395impl Compiler {
396 pub(crate) fn stats(&self) -> CompileStats {
398 self.stats
399 }
400}
401
402#[cfg(test)]
403mod unit_budget_tests;