1pub(crate) mod binding;
2mod cell_store;
3mod compile_eval;
4pub(in crate::compiler) mod control;
5mod definition;
6mod defstruct;
7pub(in crate::compiler::special) mod iteration;
8mod labels;
9mod lambda;
10mod macros;
11mod setf_place;
12pub(in crate::compiler) mod setf_scan;
13mod structure;
14
15use tracing::debug;
16
17use crate::ast::{Expr, Place};
18use crate::error::{Error, Result};
19use crate::reserved::reject_reserved;
20use crate::runtime::SymbolTable;
21
22use crate::ast::WasmType;
23
24use super::context::CompileContext;
25use super::emit::FunctionEmitter;
26
27pub(in crate::compiler) use binding::shared::{
28 MacroStores, expanded_function, fully_macro_expanded, is_closure_factory_call, labels_shadowed,
29 macro_stores, mentions_expanded, needs_cell, param_names, reads_free, unescaped,
30 used_as_function,
31};
32pub(in crate::compiler) use binding::{allocate_instances, calls_form_bound};
33pub(in crate::compiler) use binding::{bind_lambda_closure, record_closure_result};
34pub(in crate::compiler) use cell_store::{
35 compile_into_home, compile_store_value, literal_arm, reject_captured_assignment, store_arm,
36};
37pub(in crate::compiler) use control::{
38 ExpectingForm, apply_const_test, compile_test_condition, form_diverges_scratch,
39 in_runtime_branch, is_runtime_test,
40};
41pub(in crate::compiler) use defstruct::struct_function_names;
42pub(in crate::compiler) use lambda::monomorph::lookup_or_emit_monomorph;
43pub(in crate::compiler) use lambda::{
44 closure_for_stack, compute_captures, has_type_evidence, has_v1_param_shape, infer_params,
45 is_capture_free, non_v1_lambda_error, reject_non_v1_lambda, try_emit_lambda_for_host_iter,
46 try_emit_lambda_for_value,
47};
48pub(in crate::compiler) use setf_place::{compound_setf_call, expand_macro_places};
49pub(in crate::compiler) use structure::set_place as setf_set_place;
50pub(in crate::compiler) use structure::{compile_const_place_setf_rhs, promoted_place};
51
52pub(super) type EvalFn = fn(&mut SymbolTable, &[Expr]) -> Result<Expr>;
53pub(super) type CompileFn =
54 fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<()>;
55pub(super) type StackFn =
56 fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<WasmType>;
57
58pub(super) struct SpecialFormSpec {
65 pub name: &'static str,
66 pub eval: EvalFn,
67 pub compile: CompileFn,
68 pub stack: Option<StackFn>,
69 pub effect: Option<CompileFn>,
70}
71
72const DOMAINS: &[&[SpecialFormSpec]] = &[
73 control::FORMS,
74 control::CASE_FORMS,
75 binding::FORMS,
76 lambda::FORMS,
77 macros::FORMS,
78 compile_eval::FORMS,
79 iteration::FORMS,
80 labels::FORMS,
81 structure::FORMS,
82];
83
84#[cfg(test)]
87pub(in crate::compiler) fn registered_names() -> impl Iterator<Item = &'static str> {
88 DOMAINS.iter().flat_map(|d| d.iter()).map(|spec| spec.name)
89}
90
91fn lookup(name: &str) -> Option<&'static SpecialFormSpec> {
92 DOMAINS
93 .iter()
94 .flat_map(|d| d.iter())
95 .find(|s| s.name == name)
96}
97
98pub(in crate::compiler) fn is_special_form(name: &str) -> bool {
103 lookup(name).is_some()
104}
105
106pub(in crate::compiler) fn is_eval_only_special_form(name: &str) -> bool {
118 lookup(name).is_some_and(|spec| spec.stack.is_none() && spec.effect.is_none())
119}
120
121pub(in crate::compiler) fn reject_definition_under_runtime_guard(
138 symbols: &SymbolTable,
139 form_name: &str,
140) -> Result<()> {
141 if !symbols.is_under_any_runtime_guard()
142 && !symbols.in_skippable_region()
143 && symbols.function_owner().is_none()
144 {
145 return Ok(());
146 }
147 Err(definition_not_static(form_name))
148}
149
150pub(in crate::compiler) fn reject_definition_after_exit(
153 symbols: &SymbolTable,
154 form_name: &str,
155 name: &str,
156 args: &[Expr],
157) -> Result<()> {
158 match symbols.skipping_region(args) {
159 Some(region) => Err(Error::Compile(format!(
160 "{form_name} {name} follows a form that may leave this {region}; move it \
161 before that form or out of the block"
162 ))),
163 None => Ok(()),
164 }
165}
166
167pub(in crate::compiler) fn definition_not_static(form_name: &str) -> Error {
171 Error::Compile(format!(
172 "{form_name}: a definition must be statically executable; this one runs only when a \
173 runtime branch, loop or GO reaches it"
174 ))
175}
176
177const DEFINITION_FORMS: &[&str] = &["DEFUN", "DEFMACRO", "DEFVAR", "DEFPARAMETER", "DEFSTRUCT"];
178
179pub(in crate::compiler) fn reject_compile_time_setf_under_runtime_guard(
186 symbols: &SymbolTable,
187) -> Result<()> {
188 if !symbols.is_under_any_runtime_guard() {
189 return Ok(());
190 }
191 Err(Error::Compile(
192 "SETF on a compile-time (non-runtime-backed) place under a runtime \
193 IF/COND/AND/OR/HANDLER-CASE branch is not supported: the store has no corresponding runtime-conditional \
194 bytecode, so it would apply unconditionally regardless of the guard's actual outcome. \
195 Move the SETF outside the runtime-conditional branch."
196 .to_string(),
197 ))
198}
199
200pub(in crate::compiler) fn mark_cell_store(
202 emit: &mut FunctionEmitter,
203 symbols: &SymbolTable,
204 place: &Expr,
205 target: Place,
206) {
207 let (Expr::Symbol(name), Place::Global(_)) = (place, target) else {
208 return;
209 };
210 if let Some(flag) = symbols.cell_flag(name) {
211 emit.i32_const(1);
212 emit.global_set(flag);
213 }
214}
215
216pub(in crate::compiler) fn reject_uncarried_global_store(
220 symbols: &SymbolTable,
221 place: &Expr,
222) -> Result<()> {
223 let Expr::Symbol(name) = place else {
224 return Ok(());
225 };
226 reject_reserved(symbols, name)?;
227 let global = !symbols.is_macro_expansion()
228 && !symbols.is_lexical_variable(name)
229 && symbols
230 .lookup(name)
231 .is_none_or(|symbol| symbol.value().is_none_or(|value| !value.is_wasm_runtime()));
232 match global {
233 true => Err(Error::Compile(format!(
234 "{name}: a store the unit cannot carry; the store reaches {name} through a form \
235 the store scan could not read, so it would be lost; store to {name} where the \
236 unit can see it"
237 ))),
238 false => Ok(()),
239 }
240}
241
242fn through_rewrite<T>(
246 symbols: &mut SymbolTable,
247 name: &str,
248 args: &[Expr],
249 run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
250) -> Result<Option<T>> {
251 if let Some((name, args)) = binding::rewrite_binder(symbols, name, args)? {
252 return one_level(symbols, name, &args, run).map(Some);
253 }
254 let Some(looped) = control::wrapped_loop(symbols, name, args) else {
255 return Ok(None);
256 };
257 let block = [Expr::Nil, looped.clone()];
258 symbols
259 .with_loop_block(looped, |symbols| one_level(symbols, "BLOCK", &block, run))
260 .map(Some)
261}
262
263fn one_level<T>(
264 symbols: &mut SymbolTable,
265 name: &'static str,
266 args: &[Expr],
267 run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
268) -> Result<T> {
269 symbols.enter_shared_recursion()?;
270 let done = run(symbols, name, args);
271 let exited = symbols.exit_shared_recursion();
272 let value = done?;
273 exited?;
274 Ok(value)
275}
276
277pub fn call(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
278 debug!(special_form = %name, args = args.len(), "calling special form");
279 if let Some(value) = through_rewrite(symbols, name, args, call)? {
280 return Ok(value);
281 }
282 match lookup(name) {
283 Some(spec) => (spec.eval)(symbols, args),
284 None => Err(Error::Compile(format!(
285 "special form '{name}' not yet implemented"
286 ))),
287 }
288}
289
290pub(super) fn compile(
291 ctx: &mut CompileContext,
292 emit: &mut FunctionEmitter,
293 symbols: &mut SymbolTable,
294 name: &str,
295 args: &[Expr],
296) -> Result<()> {
297 debug!(special_form = %name, args = args.len(), "compiling special form");
298 let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
299 compile(ctx, emit, symbols, name, args)
300 })?;
301 if let Some(value) = rewritten {
302 return Ok(value);
303 }
304 match lookup(name) {
305 Some(spec) => run(ctx, emit, symbols, name, args, spec.compile),
306 None => Err(Error::Compile(format!(
307 "special form '{name}' not yet implemented"
308 ))),
309 }
310}
311
312fn run(
315 ctx: &mut CompileContext,
316 emit: &mut FunctionEmitter,
317 symbols: &mut SymbolTable,
318 name: &str,
319 args: &[Expr],
320 compile: CompileFn,
321) -> Result<()> {
322 match DEFINITION_FORMS.contains(&name) {
323 true => definition::compile_definition(ctx, emit, symbols, name, args, compile),
324 false => compile(ctx, emit, symbols, args),
325 }
326}
327
328pub(super) fn compile_for_effect(
329 ctx: &mut CompileContext,
330 emit: &mut FunctionEmitter,
331 symbols: &mut SymbolTable,
332 name: &str,
333 args: &[Expr],
334) -> Result<()> {
335 let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
336 compile_for_effect(ctx, emit, symbols, name, args)
337 })?;
338 if let Some(value) = rewritten {
339 return Ok(value);
340 }
341 match lookup(name) {
342 Some(spec) => run(
343 ctx,
344 emit,
345 symbols,
346 name,
347 args,
348 spec.effect.unwrap_or(spec.compile),
349 ),
350 None => Err(Error::Compile(format!(
351 "special form '{name}' not yet implemented"
352 ))),
353 }
354}
355
356fn cannot_produce_stack(name: &str) -> Error {
357 Error::Compile(format!("special form '{name}' cannot produce stack value"))
358}
359
360pub(super) fn compile_for_stack(
361 ctx: &mut CompileContext,
362 emit: &mut FunctionEmitter,
363 symbols: &mut SymbolTable,
364 name: &str,
365 args: &[Expr],
366) -> Result<WasmType> {
367 let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
368 compile_for_stack(ctx, emit, symbols, name, args)
369 })?;
370 if let Some(value) = rewritten {
371 return Ok(value);
372 }
373 match lookup(name) {
374 Some(spec) => match spec.stack {
375 Some(f) => f(ctx, emit, symbols, args),
376 None if DEFINITION_FORMS.contains(&name) => {
377 binding::reject_lexical_definition(symbols, name, args)?;
378 reject_definition_under_runtime_guard(symbols, name)?;
379 Err(cannot_produce_stack(name))
380 }
381 None => Err(cannot_produce_stack(name)),
382 },
383 None => Err(Error::Compile(format!(
384 "special form '{name}' not yet implemented"
385 ))),
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392 use std::collections::HashSet;
393
394 #[test]
395 fn registry_names_unique() {
396 let mut seen = HashSet::new();
397 for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
398 assert!(
399 seen.insert(spec.name),
400 "duplicate special-form registration: {}",
401 spec.name
402 );
403 }
404 }
405
406 #[test]
407 fn registry_lookup_covers_every_entry() {
408 for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
409 assert!(
410 lookup(spec.name).is_some(),
411 "lookup({}) returned None",
412 spec.name
413 );
414 }
415 }
416
417 #[test]
418 fn set_place_rejects_a_new_builtin_global() {
419 let mut symbols = SymbolTable::new();
420 let place = Expr::Symbol("LIST".to_string());
421 let result = setf_set_place(&mut symbols, &place, Expr::Nil);
422 assert!(matches!(result, Err(Error::Compile(msg)) if msg.contains("built-in")));
423 assert!(symbols.lookup("LIST").is_none());
424 }
425
426 #[test]
427 fn set_place_defines_a_new_plain_global_and_updates_it() {
428 let mut symbols = SymbolTable::new();
429 let place = Expr::Symbol("G".to_string());
430 assert!(matches!(
431 setf_set_place(&mut symbols, &place, Expr::Nil),
432 Ok(Expr::Nil)
433 ));
434 assert!(symbols.lookup("G").is_some());
435 assert!(matches!(
436 setf_set_place(&mut symbols, &place, Expr::Nil),
437 Ok(Expr::Nil)
438 ));
439 }
440}