logicaffeine_compile/extraction/codegen.rs
1//! Rust code generation from kernel terms.
2//!
3//! Converts verified kernel terms to executable Rust source code while
4//! preserving the structural properties of the proof.
5//!
6//! # Code Generation Strategy
7//!
8//! | Kernel Term | Rust Output |
9//! |-------------|-------------|
10//! | Inductive | `enum Name { Ctor(Args...) }` |
11//! | Fix + Lambda | `fn name(args) -> Ret { body }` |
12//! | Lambda | `fn name(args) -> Ret { body }` |
13//! | Const | `const NAME: Ty = val;` |
14//! | Match | `match disc { Name::Ctor(vars) => body }` |
15//! | App | `func(arg)` |
16//!
17//! # Recursive Types
18//!
19//! Recursive inductive types (like `Nat`) have their recursive fields
20//! wrapped in `Box<T>` to ensure finite size:
21//!
22//! ```text
23//! Kernel: Inductive Nat := Zero | Succ (Nat)
24//! Rust: enum Nat { Zero, Succ(Box<Nat>) }
25//! ```
26
27use super::error::ExtractError;
28use crate::kernel::{Context, Literal, Term};
29use std::collections::{HashMap, HashSet};
30
31/// Context for code generation within a term.
32struct TermGenCtx<'a> {
33 /// The name of the definition being emitted
34 def_name: &'a str,
35 /// The name of the recursive reference (from Fix)
36 rec_name: &'a str,
37 /// Variables that need to be dereferenced (boxed in match patterns)
38 deref_vars: &'a HashSet<String>,
39 /// Variables referenced more than once in the body. The kernel's semantics
40 /// are non-linear (a value may be used any number of times), but Rust moves
41 /// by default, so each use of such a variable is emitted as `x.clone()`.
42 multi_use: &'a HashSet<String>,
43 /// Kernel binder name → the Rust identifier it is emitted as, for the binders
44 /// whose kernel spelling `rustc` would reject. See [`rust_locals`]. Keyed by the
45 /// KERNEL name, which is also how `deref_vars` and `multi_use` are keyed, so the
46 /// renaming is a property of the OUTPUT and nothing upstream has to know about it.
47 renames: &'a HashMap<String, String>,
48}
49
50impl TermGenCtx<'_> {
51 /// The Rust identifier for a kernel local — [`rust_local`] against this walk's map.
52 fn local(&self, name: &str) -> String {
53 rust_local(self.renames, name)
54 }
55}
56
57/// Code generator for extracting Rust from kernel terms.
58pub struct CodeGen<'a> {
59 ctx: &'a Context,
60 output: String,
61 emitted: HashSet<String>,
62 /// Binder name → the INDUCTIVE type it was declared at, for the definition currently being
63 /// emitted. Rebuilt per definition from its Pi telescope; empty outside one.
64 binder_inductives: HashMap<String, String>,
65}
66
67impl<'a> CodeGen<'a> {
68 /// Create a new code generator.
69 pub fn new(ctx: &'a Context) -> Self {
70 Self {
71 ctx,
72 output: String::new(),
73 emitted: HashSet::new(),
74 binder_inductives: HashMap::new(),
75 }
76 }
77
78 /// Get the generated Rust code.
79 pub fn finish(self) -> String {
80 self.output
81 }
82
83 /// Emit an inductive type as a Rust enum.
84 pub fn emit_inductive(&mut self, name: &str) -> Result<(), ExtractError> {
85 if self.emitted.contains(name) {
86 return Ok(());
87 }
88 self.emitted.insert(name.to_string());
89
90 let ctors = distinct_constructors(self.ctx, name);
91 if ctors.is_empty() {
92 return Err(ExtractError::NotFound(name.to_string()));
93 }
94
95 // Type parameters of a polymorphic inductive (e.g. `A` in `MyList (A : Type)`)
96 // are encoded as leading Π-binders on the sort and on each constructor type;
97 // they become Rust generics, NOT data fields.
98 let params = type_params(self.ctx, name);
99 let generics = if params.is_empty() {
100 String::new()
101 } else {
102 format!("<{}>", params.join(", "))
103 };
104
105 // Clone: non-linear use needs `.clone()`. Debug/PartialEq: the
106 // self-verifying demo `main` prints values (`{:?}`) and `assert_eq!`s them
107 // against the kernel-computed result.
108 let rust_name = rust_global(self.ctx, name);
109 self.output.push_str("#[derive(Clone, Debug, PartialEq)]\n");
110 self.output
111 .push_str(&format!("pub enum {}{} {{\n", rust_name, generics));
112 for (ctor_name, ctor_ty) in &ctors {
113 let fields = extract_ctor_fields(self.ctx, ctor_ty, name, params.len());
114 let variant = rust_global(self.ctx, ctor_name);
115 if fields.is_empty() {
116 self.output.push_str(&format!(" {},\n", variant));
117 } else {
118 self.output
119 .push_str(&format!(" {}({}),\n", variant, fields.join(", ")));
120 }
121 }
122 self.output.push_str("}\n\n");
123
124 // For a non-generic inductive, also emit a CONSTRUCTOR API + Display impl so
125 // IMPERATIVE LOGOS can build, pass, and `Show` proven values by name through
126 // `use proven::*;` (e.g. `MSucc(MSucc(MZero))`) with no codegen changes:
127 // * nullary ctor → `pub const Z: Nat = Nat::Z;` (a value, not a fn)
128 // * n-ary ctor → `pub fn S(a0: Nat) -> Nat { Nat::S(Box::new(a0)) }`
129 // (recursive fields boxed to match the tuple-variant shape)
130 // * `impl Display` via Debug, since imperative `Show` formats with `{}`.
131 // Generic inductives are skipped (their values aren't constructible from the
132 // imperative side without type arguments).
133 if params.is_empty() {
134 self.output.push_str(&format!(
135 "impl std::fmt::Display for {n} {{\n \
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{ write!(f, \"{{:?}}\", self) }}\n}}\n\n",
137 n = rust_name,
138 ));
139 for (ctor_key, ctor_ty) in &ctors {
140 let ctor_name = rust_global(self.ctx, ctor_key);
141 // A ctor named after a std prelude value (`Some`/`None`/`Ok`/`Err`)
142 // gets NO free wrapper: under `use proven::*;` it would silently shadow
143 // the prelude in the imperative half. The qualified variant still works.
144 if matches!(ctor_name.as_str(), "Some" | "None" | "Ok" | "Err") {
145 continue;
146 }
147 let cps = ctor_params(self.ctx, ctor_ty, 0, name);
148 if cps.is_empty() {
149 self.output.push_str(&format!(
150 "pub const {c}: {n} = {n}::{c};\n",
151 c = ctor_name,
152 n = rust_name,
153 ));
154 } else {
155 let sig: Vec<String> = cps
156 .iter()
157 .enumerate()
158 .map(|(i, (t, _))| format!("a{i}: {t}"))
159 .collect();
160 let args: Vec<String> = cps
161 .iter()
162 .enumerate()
163 .map(|(i, (_, rec))| {
164 if *rec {
165 format!("Box::new(a{i})")
166 } else {
167 format!("a{i}")
168 }
169 })
170 .collect();
171 self.output.push_str(&format!(
172 "pub fn {c}({sig}) -> {n} {{ {n}::{c}({args}) }}\n",
173 c = ctor_name,
174 n = rust_name,
175 sig = sig.join(", "),
176 args = args.join(", "),
177 ));
178 }
179 }
180 self.output.push('\n');
181 }
182 Ok(())
183 }
184
185 /// Emit a definition as a Rust function or constant.
186 pub fn emit_definition(&mut self, name: &str) -> Result<(), ExtractError> {
187 if self.emitted.contains(name) {
188 return Ok(());
189 }
190 self.emitted.insert(name.to_string());
191
192 let body = self
193 .ctx
194 .get_definition_body(name)
195 .ok_or_else(|| ExtractError::NotFound(name.to_string()))?;
196 let ty = self
197 .ctx
198 .get_definition_type(name)
199 .ok_or_else(|| ExtractError::NotFound(name.to_string()))?;
200
201 // Check if it's a fixpoint (recursive function)
202 if let Term::Fix {
203 name: rec_name,
204 body: fix_body,
205 } = body
206 {
207 self.emit_fix_as_fn(name, rec_name, fix_body, ty)?;
208 } else if is_lambda(body) {
209 self.emit_lambda_as_fn(name, body, ty)?;
210 } else {
211 // A value definition. Emitted as a nullary function rather than a
212 // `const` because constructor values allocate (`Box::new`), which is
213 // not allowed in `const` context.
214 self.emit_value_fn(name, body, ty)?;
215 }
216 Ok(())
217 }
218
219 /// Emit a fixpoint as a recursive Rust function.
220 fn emit_fix_as_fn(
221 &mut self,
222 def_name: &str,
223 rec_name: &str,
224 fix_body: &Term,
225 ty: &Term,
226 ) -> Result<(), ExtractError> {
227 let def_name = rust_global(self.ctx, def_name);
228 let def_name = def_name.as_str();
229 // Extract parameters from nested lambdas
230 let (params, inner_body) = extract_lambda_params(fix_body);
231
232 // Extract parameter types from the Pi type
233 let param_types = extract_pi_params(ty);
234
235 // Record each parameter's INDUCTIVE type for this definition, so a match whose
236 // discriminant is a parameter can be resolved from its binder rather than from the
237 // motive (which, for a non-dependent match, is the return type and not the scrutinee's).
238 let binder_inductives: HashMap<String, String> = params
239 .iter()
240 .enumerate()
241 .filter_map(|(i, (pname, _))| {
242 let (_, t) = param_types.get(i)?;
243 head_inductive(self.ctx, t).map(|n| (pname.clone(), n))
244 })
245 .collect();
246 self.binder_inductives = binder_inductives;
247
248 // Get return type
249 let ret_ty = extract_return_type(ty);
250
251 // One renaming for the WHOLE definition (signature and body), so a parameter
252 // spelled unrepresentably in Rust is the same identifier in both.
253 let renames = rust_locals(fix_body);
254
255 // Build function signature
256 self.output.push_str(&format!("pub fn {}(", def_name));
257 for (i, (param_name, _)) in params.iter().enumerate() {
258 if i > 0 {
259 self.output.push_str(", ");
260 }
261 let param_ty = param_types
262 .get(i)
263 .map(|(_, t)| type_to_rust(self.ctx, t))
264 .unwrap_or_else(|| "()".to_string());
265 self.output.push_str(&format!(
266 "{}: {}",
267 rust_local(&renames, param_name),
268 param_ty
269 ));
270 }
271 self.output
272 .push_str(&format!(") -> {} {{\n", type_to_rust(self.ctx, &ret_ty)));
273
274 // Generate body, replacing recursive calls
275 let body_code = self.term_to_rust(inner_body, def_name, rec_name, &renames);
276 self.output.push_str(&format!(" {}\n", body_code));
277 self.output.push_str("}\n\n");
278
279 Ok(())
280 }
281
282 /// Emit a non-recursive lambda as a Rust function.
283 fn emit_lambda_as_fn(
284 &mut self,
285 def_name: &str,
286 body: &Term,
287 ty: &Term,
288 ) -> Result<(), ExtractError> {
289 let def_name = rust_global(self.ctx, def_name);
290 let def_name = def_name.as_str();
291 // Extract parameters from nested lambdas
292 let (params, inner_body) = extract_lambda_params(body);
293
294 // Extract parameter types from the Pi type
295 let param_types = extract_pi_params(ty);
296
297 // Record each parameter's INDUCTIVE type for this definition, so a match whose
298 // discriminant is a parameter can be resolved from its binder rather than from the
299 // motive (which, for a non-dependent match, is the return type and not the scrutinee's).
300 let binder_inductives: HashMap<String, String> = params
301 .iter()
302 .enumerate()
303 .filter_map(|(i, (pname, _))| {
304 let (_, t) = param_types.get(i)?;
305 head_inductive(self.ctx, t).map(|n| (pname.clone(), n))
306 })
307 .collect();
308 self.binder_inductives = binder_inductives;
309
310 // Get return type
311 let ret_ty = extract_return_type(ty);
312
313 let renames = rust_locals(body);
314
315 // Build function signature
316 self.output.push_str(&format!("pub fn {}(", def_name));
317 for (i, (param_name, _)) in params.iter().enumerate() {
318 if i > 0 {
319 self.output.push_str(", ");
320 }
321 let param_ty = param_types
322 .get(i)
323 .map(|(_, t)| type_to_rust(self.ctx, t))
324 .unwrap_or_else(|| "()".to_string());
325 self.output.push_str(&format!(
326 "{}: {}",
327 rust_local(&renames, param_name),
328 param_ty
329 ));
330 }
331 self.output
332 .push_str(&format!(") -> {} {{\n", type_to_rust(self.ctx, &ret_ty)));
333
334 // Generate body (no recursive name replacement)
335 let body_code = self.term_to_rust(inner_body, def_name, "", &renames);
336 self.output.push_str(&format!(" {}\n", body_code));
337 self.output.push_str("}\n\n");
338
339 Ok(())
340 }
341
342 /// Emit a value definition as a nullary function.
343 ///
344 /// `Definition one : Nat := Succ Zero` becomes `fn one() -> Nat { … }`. A
345 /// function (not a `const`) because the body may allocate (`Box::new`).
346 fn emit_value_fn(&mut self, name: &str, body: &Term, ty: &Term) -> Result<(), ExtractError> {
347 let name = rust_global(self.ctx, name);
348 let name = name.as_str();
349 let ty_str = type_to_rust(self.ctx, ty);
350 let body_str = self.term_to_rust(body, name, "", &rust_locals(body));
351 self.output.push_str(&format!(
352 "pub fn {}() -> {} {{\n {}\n}}\n\n",
353 name, ty_str, body_str
354 ));
355 Ok(())
356 }
357
358 /// Convert a kernel term to Rust code.
359 fn term_to_rust(
360 &self,
361 term: &Term,
362 def_name: &str,
363 rec_name: &str,
364 renames: &HashMap<String, String>,
365 ) -> String {
366 self.term_to_rust_forced(term, def_name, rec_name, &HashSet::new(), renames)
367 }
368
369 /// As [`Self::term_to_rust`], but `force_clone` names are `.clone()`d at every
370 /// use even if they appear once — used when a value is shared across separately
371 /// emitted sub-terms (e.g. both sides of a property `lhs == rhs`).
372 fn term_to_rust_forced(
373 &self,
374 term: &Term,
375 def_name: &str,
376 rec_name: &str,
377 force_clone: &HashSet<String>,
378 renames: &HashMap<String, String>,
379 ) -> String {
380 let empty_deref = HashSet::new();
381 // Variables used more than once must be cloned at each use (Rust moves by
382 // default; the kernel's lambda calculus does not).
383 let mut counts: HashMap<String, usize> = HashMap::new();
384 count_vars(term, &mut counts);
385 let mut multi_use: HashSet<String> = counts
386 .into_iter()
387 .filter(|(_, c)| *c > 1)
388 .map(|(name, _)| name)
389 .collect();
390 multi_use.extend(force_clone.iter().cloned());
391 let ctx = TermGenCtx {
392 def_name,
393 rec_name,
394 deref_vars: &empty_deref,
395 multi_use: &multi_use,
396 renames,
397 };
398 self.term_to_rust_ctx(term, &ctx)
399 }
400
401 /// Convert a kernel term to Rust code with context for dereferencing.
402 fn term_to_rust_ctx(&self, term: &Term, tctx: &TermGenCtx) -> String {
403 match term {
404 // A universe-polymorphic reference extracts by its name; universe arguments
405 // carry no runtime content.
406 Term::Const { name, .. } => rust_global(self.ctx, name),
407 Term::Var(name) => {
408 // Check if this is a reference to the recursive function
409 if name == tctx.rec_name && !tctx.rec_name.is_empty() {
410 tctx.def_name.to_string()
411 } else {
412 // Dereference boxed bindings from recursive match patterns.
413 let ident = tctx.local(name);
414 let base = if tctx.deref_vars.contains(name) {
415 format!("(*{})", ident)
416 } else {
417 ident
418 };
419 // Clone variables used more than once so non-linear use type-checks.
420 if tctx.multi_use.contains(name) {
421 format!("{}.clone()", base)
422 } else {
423 base
424 }
425 }
426 }
427 Term::Global(name) => {
428 // Check if it's a constructor
429 if self.ctx.is_constructor(name) {
430 if let Some(ind) = self.ctx.constructor_inductive(name) {
431 return format!(
432 "{}::{}",
433 rust_global(self.ctx, ind),
434 rust_global(self.ctx, name)
435 );
436 }
437 }
438 // Check if it's the recursive reference
439 if name == tctx.rec_name && !tctx.rec_name.is_empty() {
440 return tctx.def_name.to_string();
441 }
442 // A value definition is emitted as a nullary `fn`, so reference it
443 // by calling it.
444 if is_value_def(self.ctx, name) {
445 return format!("{}()", rust_global(self.ctx, name));
446 }
447 rust_global(self.ctx, name)
448 }
449 Term::App(_, _) => {
450 // Collect the head function and all arguments
451 let (head, args) = collect_app_chain(term);
452 let args_strs: Vec<String> = args
453 .iter()
454 .map(|a| self.term_to_rust_ctx(a, tctx))
455 .collect();
456
457 // Check if the head is a constructor
458 if let Term::Global(name) = head {
459 if self.ctx.is_constructor(name) {
460 if let Some(ind) = self.ctx.constructor_inductive(name) {
461 // Erase the leading type arguments (they correspond to
462 // the inductive's type parameters) and box each field
463 // whose type is recursive.
464 let n_params = type_params(self.ctx, ind).len();
465 let value_args: &[String] = if args_strs.len() >= n_params {
466 &args_strs[n_params..]
467 } else {
468 &args_strs
469 };
470 let rec = ctor_field_recursion(
471 self.ctx,
472 self.ctx.get_global(name),
473 ind,
474 n_params,
475 );
476 let fields: Vec<String> = value_args
477 .iter()
478 .enumerate()
479 .map(|(i, a)| {
480 if rec.get(i).copied().unwrap_or(false) {
481 format!("Box::new({})", a)
482 } else {
483 a.clone()
484 }
485 })
486 .collect();
487 let (ind, name) =
488 (rust_global(self.ctx, ind), rust_global(self.ctx, name));
489 if fields.is_empty() {
490 return format!("{}::{}", ind, name);
491 } else {
492 return format!("{}::{}({})", ind, name, fields.join(", "));
493 }
494 }
495 }
496 }
497
498 // Arithmetic builtins (`add`/`sub`/`mul`/`div`/`mod` : Int -> Int ->
499 // Int) are opaque kernel declarations whose computational behavior IS
500 // the Rust integer operator — their kernel laws (add_comm/add_assoc/
501 // add_zero, …) are exactly `+`'s. Emit the operator so primitive proven
502 // functions (`fun n => add n n`) extract to real, runnable Rust rather
503 // than a call to an undefined `add`. CRITICAL: only the BUILTIN (a
504 // bodyless declaration) maps to an operator — a user-defined function
505 // that happens to be named `add` (e.g. Peano `add : Num -> Num -> Num`,
506 // which HAS a body) is extracted as a real `fn` and must be CALLED.
507 if let Term::Global(name) = head {
508 if let Some(op) = arith_builtin_operator(self.ctx, name) {
509 if args_strs.len() == 2 {
510 return format!("({} {} {})", args_strs[0], op, args_strs[1]);
511 }
512 }
513 }
514
515 // Check if head is a Var that should be renamed (recursive call)
516 let head_str = if let Term::Var(name) = head {
517 if name == tctx.rec_name && !tctx.rec_name.is_empty() {
518 tctx.def_name.to_string()
519 } else {
520 tctx.local(name)
521 }
522 } else {
523 self.term_to_rust_ctx(head, tctx)
524 };
525
526 // Regular function call with all arguments comma-separated
527 format!("{}({})", head_str, args_strs.join(", "))
528 }
529 Term::Lambda {
530 param,
531 param_type,
532 body,
533 } => {
534 let param_ty = type_to_rust(self.ctx, param_type);
535 let body_str = self.term_to_rust_ctx(body, tctx);
536 format!("|{}: {}| {}", tctx.local(param), param_ty, body_str)
537 }
538 Term::Let {
539 name, value, body, ..
540 } => {
541 let value_str = self.term_to_rust_ctx(value, tctx);
542 let body_str = self.term_to_rust_ctx(body, tctx);
543 format!(
544 "{{ let {} = {}; {} }}",
545 tctx.local(name),
546 value_str,
547 body_str
548 )
549 }
550 Term::MutualFix { defs, index } => {
551 // Extract the definition this occurrence denotes (best-effort: mutual recursion
552 // is emitted as the selected body; a full extraction would hoist all defs).
553 match defs.get(*index) {
554 Some((_, body)) => self.term_to_rust_ctx(body, tctx),
555 None => "()".to_string(),
556 }
557 }
558 Term::Match {
559 discriminant,
560 motive,
561 cases,
562 } => {
563 let disc_str = self.term_to_rust_ctx(discriminant, tctx);
564
565 // Get the inductive type from the motive (λx:T. ReturnType)
566 // The param_type of the motive lambda gives us the inductive
567 let ind_name = self
568 .infer_inductive_from_motive(motive)
569 .or_else(|| self.infer_inductive_type(discriminant));
570
571 let mut result = format!("match {} {{\n", disc_str);
572 if let Some(ind) = &ind_name {
573 let ctors = distinct_constructors(self.ctx, ind);
574 let n_params = type_params(self.ctx, ind).len();
575
576 for (i, (ctor_name, ctor_ty)) in ctors.iter().enumerate() {
577 if i < cases.len() {
578 let case = &cases[i];
579 // Type parameters are erased, so they are not pattern fields.
580 let ctor_arity = count_ctor_args(ctor_ty).saturating_sub(n_params);
581
582 result.push_str(&format!(
583 " {}::{}",
584 rust_global(self.ctx, ind),
585 rust_global(self.ctx, ctor_name)
586 ));
587 if ctor_arity > 0 {
588 // Generate pattern with bindings
589 let (bindings, case_body) = extract_case_bindings(case, ctor_arity);
590 result.push_str("(");
591 for (j, binding) in bindings.iter().enumerate() {
592 if j > 0 {
593 result.push_str(", ");
594 }
595 result.push_str(&tctx.local(binding));
596 }
597 result.push_str(")");
598
599 // Only bindings for BOXED fields are dereferenced in the
600 // body — a per-field mask (not all-or-nothing), so a
601 // non-recursive field (e.g. an `Int` beside a recursive
602 // field) is not wrongly `(*x)`-derefed, and mutual-
603 // recursion's boxed cross-fields ARE.
604 let box_mask =
605 ctor_field_recursion(self.ctx, Some(ctor_ty), ind, n_params);
606 let case_deref_vars: HashSet<String> = bindings
607 .iter()
608 .enumerate()
609 .filter(|(j, _)| box_mask.get(*j).copied().unwrap_or(false))
610 .map(|(_, b)| b.clone())
611 .collect();
612 let case_tctx = TermGenCtx {
613 def_name: tctx.def_name,
614 rec_name: tctx.rec_name,
615 deref_vars: &case_deref_vars,
616 multi_use: tctx.multi_use,
617 renames: tctx.renames,
618 };
619 let body_str = self.term_to_rust_ctx(&case_body, &case_tctx);
620 result.push_str(&format!(" => {},\n", body_str));
621 } else {
622 let case_str = self.term_to_rust_ctx(case, tctx);
623 result.push_str(&format!(" => {},\n", case_str));
624 }
625 }
626 }
627 }
628 result.push_str(" }");
629 result
630 }
631 Term::Fix { name, body } => {
632 // Inline fixpoints are tricky - for now, just extract the body
633 let fix_tctx = TermGenCtx {
634 def_name: tctx.def_name,
635 rec_name: name,
636 deref_vars: tctx.deref_vars,
637 multi_use: tctx.multi_use,
638 renames: tctx.renames,
639 };
640 self.term_to_rust_ctx(body, &fix_tctx)
641 }
642 Term::Lit(lit) => match lit {
643 Literal::Int(n) => format!("{}i64", n),
644 Literal::BigInt(n) => format!("{}i128 /* bigint */", n),
645 Literal::Nat(n) => format!("{}u64 /* nat */", n),
646 Literal::Float(f) => format!("{}f64", f),
647 Literal::Text(s) => format!("{:?}", s),
648 Literal::Duration(nanos) => format!("{}i64 /* nanos */", nanos),
649 Literal::Date(days) => format!("{}i32 /* days since epoch */", days),
650 Literal::Moment(nanos) => format!("{}i64 /* nanos since epoch */", nanos),
651 },
652 Term::Pi { .. } => "/* type */".to_string(),
653 Term::Sort(_) => "/* sort */".to_string(),
654 Term::Hole => "_".to_string(), // Type placeholder
655 // An annotation carries no runtime content: the term under it is what is extracted.
656 Term::Annotated { term, .. } => self.term_to_rust_ctx(term, tctx),
657 }
658 }
659
660 /// Extract the inductive type from a match motive.
661 ///
662 /// The motive is typically `λx:T. ReturnType` where T is the inductive.
663 fn infer_inductive_from_motive(&self, motive: &Term) -> Option<String> {
664 // ★ A MOTIVE COMES IN TWO SHAPES AND THIS KNEW ONLY ONE.
665 //
666 // The dependent form is `λx:T. ReturnType`, and the inductive is the binder's type. But a
667 // NON-dependent match carries its motive as the return type alone — for `my_add` the kernel
668 // hands us `Global("MyNat")` directly, with no lambda to look inside. This matched only the
669 // lambda, returned `None` for the bare form, and the caller's `if let Some(ind)` then skipped
670 // the entire arm loop and emitted `match n { }` — with `cases` sitting right there, populated.
671 // Valid Rust to us, a non-exhaustive-match error in the code we hand the user. MEASURED at the
672 // failure: `disc="n" ind_name=None cases=2 motive=Global("MyNat")`.
673 //
674 // Both spellings of a declared name are accepted (`Global(n)` and the universe-instantiated
675 // `Const { name, .. }`), because a site asking "which declaration is this?" that knows only one
676 // of them stops recognising the name the moment it is instantiated.
677 // ONLY the dependent form names the discriminant's type. `λx:T. ReturnType` binds the
678 // inductive as `T`; a NON-dependent match carries its motive as the return type ALONE, and
679 // that is a different type whenever the function changes type — `is_zero : MyNat -> MyBool`
680 // has motive `Global("MyBool")` over a discriminant of `MyNat`. Reading the bare motive as
681 // the inductive emits `MyBool` arms for a `MyNat` scrutinee, which is why the bare case is
682 // resolved from the DISCRIMINANT's binder instead (see `binder_inductives`).
683 if let Term::Lambda { param_type, .. } = motive {
684 if let Some(name) = global_or_const_name(param_type.as_ref()) {
685 if self.ctx.is_inductive(name) {
686 return Some(name.to_string());
687 }
688 }
689 }
690 None
691 }
692
693 /// Try to infer the inductive type from a term.
694 fn infer_inductive_type(&self, term: &Term) -> Option<String> {
695 match term {
696 Term::Var(name) => {
697 // A bare `Var` carries no type, but the binder that introduced it does: the
698 // enclosing definition's Pi telescope gives each parameter's type, and a
699 // non-dependent match's discriminant is one of them. Without this the only
700 // remaining source is the motive, which for a non-dependent match is the RETURN
701 // type — a different type, and emitting its constructors produced arms that did
702 // not typecheck against the scrutinee.
703 self.binder_inductives.get(name).cloned()
704 }
705 Term::Global(name) | Term::Const { name, .. } => {
706 if self.ctx.is_constructor(name) {
707 self.ctx.constructor_inductive(name).map(|s| s.to_string())
708 } else if self.ctx.is_inductive(name) {
709 Some(name.clone())
710 } else {
711 None
712 }
713 }
714 Term::App(f, _) => self.infer_inductive_type(f),
715 Term::Hole => None, // Holes are type placeholders
716 _ => None,
717 }
718 }
719}
720
721/// A kernel binder name → the Rust identifier it is emitted as, for the binders of `term`
722/// whose kernel spelling `rustc` would reject. Names Rust already accepts are ABSENT, so
723/// ordinary code is emitted byte-identically and only an unrepresentable name is touched.
724///
725/// The two name spaces are not the same one. The kernel's `scan_name` accepts a quoted name,
726/// and its own passes mint names that are deliberately outside the ordinary identifier space
727/// so they cannot be captured: the equation compiler's field binders are `#fld0`, `#fld1`, …
728/// (`interface::match_compile`), a self-recursive definition's binder carries `✧`, an
729/// induction hypothesis' variable carries `#eq`. Emitting one verbatim produces Rust that does
730/// not PARSE — `MyNat::MSucc(#fld0) => …` — which is the one failure mode extraction must not
731/// have, because output that does not compile is not extraction.
732///
733/// The rename is collision-free by CHECK, not by hope. A character-level escape alone is not:
734/// `#fld0` and a user's own `_fld0` both escape to `_fld0`, and the two would silently become
735/// one variable — a term that compiles and computes something else. So every name the term
736/// can spell is collected first, and a candidate is stepped with a numeric suffix until it is
737/// outside that set and outside the names already handed out. This is the same discipline
738/// `match_compile::State::next_name` uses on the other side of the wall.
739fn rust_locals(term: &Term) -> HashMap<String, String> {
740 let mut spelled = HashSet::new();
741 let mut binders = Vec::new();
742 collect_names(term, &mut spelled, &mut binders);
743
744 let mut renames = HashMap::new();
745 let mut handed_out: HashSet<String> = HashSet::new();
746 for name in binders {
747 if is_rust_ident(&name) || renames.contains_key(&name) {
748 continue;
749 }
750 let base = escape_to_ident(&name);
751 let mut candidate = base.clone();
752 let mut n = 2;
753 while spelled.contains(&candidate) || handed_out.contains(&candidate) {
754 candidate = format!("{}_{}", base, n);
755 n += 1;
756 }
757 handed_out.insert(candidate.clone());
758 renames.insert(name, candidate);
759 }
760 renames
761}
762
763/// The Rust identifier a kernel local is emitted as, given a [`rust_locals`] map.
764fn rust_local(renames: &HashMap<String, String>, name: &str) -> String {
765 renames
766 .get(name)
767 .cloned()
768 .unwrap_or_else(|| name.to_string())
769}
770
771/// Every name `term` SPELLS (into `spelled`) and every name it BINDS (into `binders`, in
772/// traversal order so the renaming is deterministic). Exhaustive over [`Term`]: a variant
773/// added without an arm here would leak an unrepresentable binder into the output.
774fn collect_names(term: &Term, spelled: &mut HashSet<String>, binders: &mut Vec<String>) {
775 match term {
776 Term::Var(name) => {
777 spelled.insert(name.clone());
778 }
779 Term::Global(name) | Term::Const { name, .. } => {
780 spelled.insert(name.clone());
781 }
782 Term::App(f, a) => {
783 collect_names(f, spelled, binders);
784 collect_names(a, spelled, binders);
785 }
786 Term::Lambda {
787 param,
788 param_type,
789 body,
790 }
791 | Term::Pi {
792 param,
793 param_type,
794 body_type: body,
795 } => {
796 spelled.insert(param.clone());
797 binders.push(param.clone());
798 collect_names(param_type, spelled, binders);
799 collect_names(body, spelled, binders);
800 }
801 Term::Let {
802 name,
803 ty,
804 value,
805 body,
806 } => {
807 spelled.insert(name.clone());
808 binders.push(name.clone());
809 collect_names(ty, spelled, binders);
810 collect_names(value, spelled, binders);
811 collect_names(body, spelled, binders);
812 }
813 Term::Fix { name, body } => {
814 spelled.insert(name.clone());
815 collect_names(body, spelled, binders);
816 }
817 Term::MutualFix { defs, .. } => {
818 for (name, body) in defs {
819 spelled.insert(name.clone());
820 collect_names(body, spelled, binders);
821 }
822 }
823 Term::Match {
824 discriminant,
825 motive,
826 cases,
827 } => {
828 collect_names(discriminant, spelled, binders);
829 collect_names(motive, spelled, binders);
830 for case in cases {
831 collect_names(case, spelled, binders);
832 }
833 }
834 Term::Annotated { term, .. } => collect_names(term, spelled, binders),
835 Term::Sort(_) | Term::Lit(_) | Term::Hole => {}
836 }
837}
838
839/// Whether `name` can be emitted as a Rust identifier as written. ASCII only (the kernel's
840/// marks are not `XID_Continue` anyway, and a conservative answer only ever renames), and a
841/// Rust KEYWORD is not one either — `Definition f := fun match : Nat => match` is a perfectly
842/// good LOGOS declaration and `fn f(match: Nat)` is not Rust.
843fn is_rust_ident(name: &str) -> bool {
844 let mut chars = name.chars();
845 let Some(first) = chars.next() else {
846 return false;
847 };
848 (first.is_ascii_alphabetic() || first == '_')
849 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
850 && !crate::codegen::is_rust_keyword(name)
851}
852
853/// The character-level part of the rename: every character Rust will not take becomes `_`, a
854/// leading digit gains a `_`, and a keyword gains a trailing `_`. [`rust_locals`] is what makes
855/// the result unique; this only makes it well-formed.
856fn escape_to_ident(name: &str) -> String {
857 let mut out: String = name
858 .chars()
859 .map(|c| {
860 if c.is_ascii_alphanumeric() || c == '_' {
861 c
862 } else {
863 '_'
864 }
865 })
866 .collect();
867 if out.chars().next().is_none_or(|c| c.is_ascii_digit()) {
868 out.insert(0, '_');
869 }
870 if crate::codegen::is_rust_keyword(&out) {
871 out.push('_');
872 }
873 out
874}
875
876/// Count how many times each variable is referenced in a term.
877///
878/// Used to decide which bindings must be `.clone()`d at their use sites: a value
879/// used more than once cannot be moved each time under Rust's ownership rules.
880fn count_vars(term: &Term, counts: &mut HashMap<String, usize>) {
881 match term {
882 Term::Const { .. } => {}
883 Term::Var(name) => {
884 *counts.entry(name.clone()).or_insert(0) += 1;
885 }
886 Term::App(f, a) => {
887 count_vars(f, counts);
888 count_vars(a, counts);
889 }
890 Term::Lambda {
891 param_type, body, ..
892 } => {
893 count_vars(param_type, counts);
894 count_vars(body, counts);
895 }
896 Term::Let {
897 ty, value, body, ..
898 } => {
899 count_vars(ty, counts);
900 count_vars(value, counts);
901 count_vars(body, counts);
902 }
903 Term::MutualFix { defs, .. } => {
904 for (_, body) in defs {
905 count_vars(body, counts);
906 }
907 }
908 Term::Pi {
909 param_type,
910 body_type,
911 ..
912 } => {
913 count_vars(param_type, counts);
914 count_vars(body_type, counts);
915 }
916 Term::Fix { body, .. } => count_vars(body, counts),
917 Term::Match {
918 discriminant,
919 motive,
920 cases,
921 } => {
922 count_vars(discriminant, counts);
923 count_vars(motive, counts);
924 for case in cases {
925 count_vars(case, counts);
926 }
927 }
928 Term::Annotated { term, .. } => count_vars(term, counts),
929 Term::Sort(_) | Term::Global(_) | Term::Lit(_) | Term::Hole => {}
930 }
931}
932
933/// Emit a (normalized) data-value `Term` as a Rust expression — used by the
934/// self-verifying demo `main` to write the kernel-computed expected result.
935pub fn emit_value(ctx: &Context, term: &Term) -> String {
936 CodeGen::new(ctx).term_to_rust(term, "", "", &rust_locals(term))
937}
938
939/// Emit a runnable property check `fn check_<name>(params) -> bool { … }` from a
940/// theorem's PROPOSITION (its kernel type), or `None` if the statement isn't a
941/// finite, executable property over extractable functions. A proven theorem like
942/// `∀n. Eq Nat (add Zero n) n` becomes `fn check_…(n: Nat) -> bool { add(Nat::Zero, n) == n }`.
943pub fn emit_property_check(ctx: &Context, name: &str, prop: &Term) -> Option<String> {
944 // Peel `forall` (Pi) binders into parameters over data types.
945 let mut params: Vec<(String, String)> = Vec::new();
946 let mut cur = prop;
947 while let Term::Pi {
948 param,
949 param_type,
950 body_type,
951 } = cur
952 {
953 if !prop_type_is_data(ctx, param_type) {
954 return None; // quantifies over Prop/opaque — not runnable
955 }
956 params.push((param.clone(), type_to_rust(ctx, param_type)));
957 cur = body_type;
958 }
959 if params.is_empty() {
960 // No quantifier — only worthwhile when it's a closed equation; allow it.
961 }
962 let param_names: HashSet<String> = params.iter().map(|(n, _)| n.clone()).collect();
963 // One renaming for the whole proposition, so a quantified binder the kernel spells
964 // unrepresentably (`x#eq`, a fixpoint's `f✧`) is the SAME identifier in the signature
965 // and on both sides of the equation.
966 let renames = rust_locals(prop);
967 let body = emit_prop_body(ctx, cur, ¶m_names, &renames)?;
968 let sig: Vec<String> = params
969 .iter()
970 .map(|(n, t)| format!("{}: {}", rust_local(&renames, n), t))
971 .collect();
972 Some(format!(
973 "/// Runnable property from the proven theorem `{}`.\n\
974 pub fn check_{}({}) -> bool {{\n {}\n}}\n\n",
975 ctx.written_name(name),
976 rust_global(ctx, name),
977 sig.join(", "),
978 body
979 ))
980}
981
982/// A concrete data type (mapped primitive, or user inductive with constructors).
983fn prop_type_is_data(ctx: &Context, ty: &Term) -> bool {
984 match ty {
985 Term::Global(n) => {
986 matches!(
987 n.as_str(),
988 "Int" | "Float" | "Text" | "Bool" | "Duration" | "Date" | "Moment"
989 ) || (ctx.is_inductive(n) && !ctx.get_constructors(n).is_empty())
990 }
991 Term::App(_, _) => {
992 let (h, args) = collect_app_chain(ty);
993 prop_type_is_data(ctx, h) && args.iter().all(|a| prop_type_is_data(ctx, a))
994 }
995 _ => false,
996 }
997}
998
999/// A proposition body → a Rust `bool` expression (`Eq`→`==`, `And`/`Or`/`Not`),
1000/// or `None` if not a finitely-checkable shape.
1001fn emit_prop_body(
1002 ctx: &Context,
1003 p: &Term,
1004 params: &HashSet<String>,
1005 renames: &HashMap<String, String>,
1006) -> Option<String> {
1007 let (head, args) = collect_app_chain(p);
1008 if let Term::Global(h) = head {
1009 match (h.as_str(), args.len()) {
1010 ("Eq", 3) => {
1011 // `Eq A l r` is runnable only when `A` is DATA — a type with a Rust value and
1012 // a `==`. It is not for a FUNCTION (`add = λn. λm. …`, the definitional
1013 // equation every definition now carries) and not for a PROOF
1014 // (`lemma = λn. refl …`, the equation of a proof term): the first emits a
1015 // comparison of an `fn` item against a closure, the second a comparison of
1016 // proof objects that have no runtime form at all. Both are true statements
1017 // with no finite check, which is exactly what this function returns `None` for.
1018 if !prop_type_is_data(ctx, args[0]) {
1019 return None;
1020 }
1021 let lhs = emit_checkable_term(ctx, args[1], params, renames)?;
1022 let rhs = emit_checkable_term(ctx, args[2], params, renames)?;
1023 return Some(format!("({} == {})", lhs, rhs));
1024 }
1025 ("And", 2) => {
1026 return Some(format!(
1027 "({} && {})",
1028 emit_prop_body(ctx, args[0], params, renames)?,
1029 emit_prop_body(ctx, args[1], params, renames)?
1030 ))
1031 }
1032 ("Or", 2) => {
1033 return Some(format!(
1034 "({} || {})",
1035 emit_prop_body(ctx, args[0], params, renames)?,
1036 emit_prop_body(ctx, args[1], params, renames)?
1037 ))
1038 }
1039 ("Not", 1) => {
1040 return Some(format!(
1041 "(!{})",
1042 emit_prop_body(ctx, args[0], params, renames)?
1043 ))
1044 }
1045 _ => {}
1046 }
1047 }
1048 None
1049}
1050
1051/// One side of an equation → Rust, requiring it reference only extractable things
1052/// (so the check compiles), with quantified `params` cloned (shared across sides).
1053fn emit_checkable_term(
1054 ctx: &Context,
1055 term: &Term,
1056 params: &HashSet<String>,
1057 renames: &HashMap<String, String>,
1058) -> Option<String> {
1059 let mut refs = Vec::new();
1060 super::collector::collect_globals(term, &mut refs);
1061 if !refs
1062 .iter()
1063 .all(|g| g == "_" || crate::extraction::is_extractable(ctx, g))
1064 {
1065 return None;
1066 }
1067 Some(CodeGen::new(ctx).term_to_rust_forced(term, "", "", params, renames))
1068}
1069
1070/// Constructors of an inductive, de-duplicated by name (keeping the first of each).
1071///
1072/// Redefining an inductive that already exists (e.g. the StandardLibrary `Nat`)
1073/// appends its constructors again to the registration order; emitting those
1074/// verbatim would produce an enum with duplicate variants. Dedup by name so the
1075/// extracted enum is valid.
1076/// The declared NAME a term refers to, however the kernel happens to spell it.
1077///
1078/// `Global(n)` and `Const { name, .. }` are the SAME reference — the second simply carries a universe
1079/// instance. Every site that asks "which declaration is this?" must accept both, or it silently stops
1080/// recognising a name the moment it is instantiated.
1081fn global_or_const_name(t: &Term) -> Option<&str> {
1082 match t {
1083 Term::Global(n) => Some(n.as_str()),
1084 Term::Const { name, .. } => Some(name.as_str()),
1085 _ => None,
1086 }
1087}
1088
1089/// The INDUCTIVE a type expression is headed by, if any.
1090///
1091/// A parameter's declared type is either the inductive itself (`MyNat`) or an application of one
1092/// (`TList A`), so the head is what names the type. Type ARGUMENTS are erased in extraction, which
1093/// is why only the head matters here.
1094fn head_inductive(ctx: &Context, ty: &Term) -> Option<String> {
1095 let mut cur = ty;
1096 loop {
1097 match cur {
1098 Term::App(f, _) => cur = f.as_ref(),
1099 other => {
1100 let n = global_or_const_name(other)?;
1101 return ctx.is_inductive(n).then(|| n.to_string());
1102 }
1103 }
1104 }
1105}
1106
1107fn distinct_constructors<'a>(ctx: &'a Context, inductive: &str) -> Vec<(&'a str, &'a Term)> {
1108 let mut seen = HashSet::new();
1109 ctx.get_constructors(inductive)
1110 .into_iter()
1111 .filter(|(n, _)| seen.insert(n.to_string()))
1112 .collect()
1113}
1114
1115/// The type parameter names of an inductive (e.g. `["A"]` for `MyList (A : Type)`).
1116///
1117/// They are encoded as leading Π-binders over a `Sort` on the inductive's own
1118/// type, so we read them off the inductive's sort.
1119fn type_params(ctx: &Context, inductive: &str) -> Vec<String> {
1120 let mut names = Vec::new();
1121 let mut current = match ctx.get_global(inductive) {
1122 Some(ty) => ty,
1123 None => return names,
1124 };
1125 while let Term::Pi {
1126 param,
1127 param_type,
1128 body_type,
1129 } = current
1130 {
1131 // Only leading `: Type` binders are type parameters (→ Rust generics).
1132 if matches!(param_type.as_ref(), Term::Sort(_)) {
1133 names.push(param.clone());
1134 current = body_type;
1135 } else {
1136 break;
1137 }
1138 }
1139 names
1140}
1141
1142/// Extract a constructor's Rust field types, skipping the `skip` leading type
1143/// parameters and boxing any field whose type is recursive (mentions the
1144/// inductive) to keep the enum finitely sized.
1145/// Collect the inductive-type names referenced anywhere in a (field) type term.
1146fn collect_inductive_globals(ctx: &Context, term: &Term, out: &mut Vec<String>) {
1147 match term {
1148 Term::Global(n) => {
1149 if ctx.is_inductive(n) {
1150 out.push(n.clone());
1151 }
1152 }
1153 Term::App(f, a) => {
1154 collect_inductive_globals(ctx, f, out);
1155 collect_inductive_globals(ctx, a, out);
1156 }
1157 Term::Pi {
1158 param_type,
1159 body_type,
1160 ..
1161 } => {
1162 collect_inductive_globals(ctx, param_type, out);
1163 collect_inductive_globals(ctx, body_type, out);
1164 }
1165 _ => {}
1166 }
1167}
1168
1169/// The inductive types referenced by a constructor's FIELDS (its Pi params after the
1170/// inductive's leading type parameters) — the out-edges of an inductive in the type
1171/// graph.
1172fn ctor_field_inductives(ctx: &Context, ctor_ty: &Term, skip: usize, out: &mut Vec<String>) {
1173 let mut cur = ctor_ty;
1174 for _ in 0..skip {
1175 if let Term::Pi { body_type, .. } = cur {
1176 cur = body_type;
1177 } else {
1178 break;
1179 }
1180 }
1181 while let Term::Pi {
1182 param_type,
1183 body_type,
1184 ..
1185 } = cur
1186 {
1187 collect_inductive_globals(ctx, param_type, out);
1188 cur = body_type;
1189 }
1190}
1191
1192/// Whether inductive `from` can reach `to` by following constructor-field references
1193/// (`X → Y` iff a constructor of `X` has a field referencing inductive `Y`). Self- and
1194/// mutual-recursion both show up as `reaches(T, T)` / mutual reachability.
1195fn inductive_reaches(ctx: &Context, from: &str, to: &str) -> bool {
1196 let mut visited: HashSet<String> = HashSet::new();
1197 let mut stack = vec![from.to_string()];
1198 while let Some(x) = stack.pop() {
1199 let skip = type_params(ctx, &x).len();
1200 for (_, cty) in distinct_constructors(ctx, &x) {
1201 let mut refs = Vec::new();
1202 ctor_field_inductives(ctx, cty, skip, &mut refs);
1203 for r in refs {
1204 if r == to {
1205 return true;
1206 }
1207 if visited.insert(r.clone()) {
1208 stack.push(r);
1209 }
1210 }
1211 }
1212 }
1213 false
1214}
1215
1216/// Whether a constructor field of type `field_type` (inside inductive `enclosing`)
1217/// must be `Box`ed: it references some inductive that reaches back to `enclosing`,
1218/// closing a recursion cycle — self-recursion OR a mutual-recursion group. Acyclic
1219/// inductive fields stay unboxed (no over-boxing), so single-recursion output is
1220/// unchanged; only genuine cycles (incl. mutual recursion) gain the needed `Box`.
1221fn field_boxed(ctx: &Context, field_type: &Term, enclosing: &str) -> bool {
1222 let mut refs = Vec::new();
1223 collect_inductive_globals(ctx, field_type, &mut refs);
1224 refs.iter().any(|t| inductive_reaches(ctx, t, enclosing))
1225}
1226
1227fn extract_ctor_fields(ctx: &Context, ty: &Term, inductive: &str, skip: usize) -> Vec<String> {
1228 let mut current = ty;
1229 for _ in 0..skip {
1230 if let Term::Pi { body_type, .. } = current {
1231 current = body_type;
1232 } else {
1233 break;
1234 }
1235 }
1236
1237 let mut fields = Vec::new();
1238 while let Term::Pi {
1239 param_type,
1240 body_type,
1241 ..
1242 } = current
1243 {
1244 let field_ty = type_to_rust(ctx, param_type);
1245 if field_boxed(ctx, param_type, inductive) {
1246 fields.push(format!("Box<{}>", field_ty));
1247 } else {
1248 fields.push(field_ty);
1249 }
1250 current = body_type;
1251 }
1252 fields
1253}
1254
1255/// Which of a constructor's value fields are recursive (mention the inductive),
1256/// after skipping `skip` leading type parameters. Parallel to the field list
1257/// produced by [`extract_ctor_fields`] — used to decide where to `Box::new`.
1258/// A constructor's parameters as `(unboxed_rust_type, is_recursive)`, after skipping
1259/// the inductive's leading type parameters. Used to emit constructor-wrapper fns: the
1260/// wrapper takes the UNBOXED field type and boxes recursive fields itself.
1261fn ctor_params(ctx: &Context, ty: &Term, skip: usize, inductive: &str) -> Vec<(String, bool)> {
1262 let mut current = ty;
1263 for _ in 0..skip {
1264 if let Term::Pi { body_type, .. } = current {
1265 current = body_type;
1266 } else {
1267 break;
1268 }
1269 }
1270 let mut out = Vec::new();
1271 while let Term::Pi {
1272 param_type,
1273 body_type,
1274 ..
1275 } = current
1276 {
1277 out.push((
1278 type_to_rust(ctx, param_type),
1279 field_boxed(ctx, param_type, inductive),
1280 ));
1281 current = body_type;
1282 }
1283 out
1284}
1285
1286fn ctor_field_recursion(
1287 ctx: &Context,
1288 ty: Option<&Term>,
1289 inductive: &str,
1290 skip: usize,
1291) -> Vec<bool> {
1292 let mut flags = Vec::new();
1293 let mut current = match ty {
1294 Some(t) => t,
1295 None => return flags,
1296 };
1297 for _ in 0..skip {
1298 if let Term::Pi { body_type, .. } = current {
1299 current = body_type;
1300 } else {
1301 break;
1302 }
1303 }
1304 while let Term::Pi {
1305 param_type,
1306 body_type,
1307 ..
1308 } = current
1309 {
1310 flags.push(field_boxed(ctx, param_type, inductive));
1311 current = body_type;
1312 }
1313 flags
1314}
1315
1316/// A value definition is one whose body is data (not a function): it is emitted
1317/// as a nullary `fn` and referenced by calling it.
1318fn is_value_def(ctx: &Context, name: &str) -> bool {
1319 ctx.get_definition_body(name)
1320 .map(|b| !matches!(b, Term::Lambda { .. } | Term::Fix { .. }))
1321 .unwrap_or(false)
1322}
1323
1324/// The canonical kernel-primitive → Rust-type bridge: the SINGLE source of truth
1325/// for how the seven opaque kernel primitives lower to Rust. Both the extractor and
1326/// any caller that reasons about extractable types consult this, so they can never
1327/// disagree on a primitive's Rust type — the soundness contract that lets imperative
1328/// code call a bundled proven function over primitives. `None` means the name is not
1329/// a primitive (it may still be a user inductive or a generic type variable). These
1330/// are registered in the StandardLibrary as constructorless inductives, so they have
1331/// no enum form and are represented directly by their Rust counterpart.
1332pub fn primitive_rust_type(name: &str) -> Option<&'static str> {
1333 Some(match name {
1334 "Int" => "i64",
1335 "Float" => "f64",
1336 "Text" => "String",
1337 "Bool" => "bool",
1338 "Duration" => "i64",
1339 "Date" => "i32",
1340 "Moment" => "i64",
1341 _ => return None,
1342 })
1343}
1344
1345/// Whether every use of an arithmetic builtin in `term` is a full BINARY application
1346/// — the only form that lowers to a Rust operator. A bare or partially-applied builtin
1347/// (`add`, `add n`) has no Rust definition to call, so a definition containing one is
1348/// NOT cleanly extractable (it would emit a call to an undefined `add`). `term_to_rust`
1349/// only handles the 2-arg case; this gate keeps such definitions out of extraction.
1350pub(crate) fn arith_uses_well_formed(ctx: &Context, term: &Term) -> bool {
1351 match term {
1352 // A builtin appearing anywhere except as the head of a 2-arg application.
1353 Term::Global(name) => arith_builtin_operator(ctx, name).is_none(),
1354 Term::App(_, _) => {
1355 let (head, args) = collect_app_chain(term);
1356 if let Term::Global(name) = head {
1357 if arith_builtin_operator(ctx, name).is_some() {
1358 // Head is a builtin: require exactly 2 args, and they must be clean.
1359 return args.len() == 2 && args.iter().all(|a| arith_uses_well_formed(ctx, a));
1360 }
1361 }
1362 // Non-builtin head: head and every arg must be clean.
1363 arith_uses_well_formed(ctx, head) && args.iter().all(|a| arith_uses_well_formed(ctx, a))
1364 }
1365 Term::Lambda {
1366 param_type, body, ..
1367 } => arith_uses_well_formed(ctx, param_type) && arith_uses_well_formed(ctx, body),
1368 Term::Pi {
1369 param_type,
1370 body_type,
1371 ..
1372 } => arith_uses_well_formed(ctx, param_type) && arith_uses_well_formed(ctx, body_type),
1373 Term::Fix { body, .. } => arith_uses_well_formed(ctx, body),
1374 Term::Match {
1375 discriminant,
1376 motive,
1377 cases,
1378 } => {
1379 arith_uses_well_formed(ctx, discriminant)
1380 && arith_uses_well_formed(ctx, motive)
1381 && cases.iter().all(|c| arith_uses_well_formed(ctx, c))
1382 }
1383 _ => true,
1384 }
1385}
1386
1387/// The Rust operator for the kernel's arithmetic builtin `name` **as registered in `ctx`** —
1388/// the only form of the question extraction may ask.
1389///
1390/// The spelling alone does not identify the builtin. `add` is the prelude's `Int -> Int -> Int`
1391/// arithmetic, whose computational content IS Rust's `+`; a user's own
1392/// `Definition add : Nat -> Nat -> Nat` is a different function that happens to share the name,
1393/// is extracted as a real `fn`, and must be CALLED. The two were told apart by asking whether
1394/// the global had a BODY — true while the prelude's arithmetic was an opaque declaration, and
1395/// false the moment `Int` became a real inductive and `add` became the definition
1396/// `Int_add`. Every arithmetic use then stopped lowering to an operator and started dragging
1397/// the structural integer tower into the output.
1398///
1399/// The type is what actually decides it, and it is what the operator mapping is faithful to:
1400/// `Int -> Int -> Int`, where `Int` is the primitive that extracts to `i64`. Anything else at
1401/// that name is user code.
1402pub(crate) fn arith_builtin_operator(ctx: &Context, name: &str) -> Option<&'static str> {
1403 let op = arith_operator(name)?;
1404 let ty = ctx.get_global(name)?;
1405 if !is_int_binop(ty) {
1406 return None;
1407 }
1408 // …and it must be the PRELUDE'S declaration. The type narrows the question but does not
1409 // settle it: `Definition add : Int -> Int -> Int := fun a => fun b => mul a b` is a user's
1410 // own function at exactly that signature, and lowering it to `+` would silently compile a
1411 // different program. Comparing against the prelude as REGISTERED is the same discipline
1412 // `ui_bridge::Baseline` uses to tell a user declaration from a prelude one.
1413 match (prelude_arith_body(name), ctx.get_definition_body(name)) {
1414 // Still an opaque declaration (as `add` was before `Int` became an inductive).
1415 (None, None) => Some(op),
1416 (Some(prelude), Some(here)) if prelude == here => Some(op),
1417 _ => None,
1418 }
1419}
1420
1421/// The body the STANDARD LIBRARY gives one of the five arithmetic names, read once per process
1422/// from a cached prelude (`interface::standard_context` hands out a copy-on-write clone, so this
1423/// is one registration, not one per call).
1424fn prelude_arith_body(name: &str) -> Option<&'static Term> {
1425 static BODIES: std::sync::OnceLock<HashMap<&'static str, Option<Term>>> =
1426 std::sync::OnceLock::new();
1427 let bodies = BODIES.get_or_init(|| {
1428 let prelude = crate::kernel::interface::standard_context();
1429 ["add", "sub", "mul", "div", "mod"]
1430 .into_iter()
1431 .map(|n| (n, prelude.get_definition_body(n).cloned()))
1432 .collect()
1433 });
1434 bodies.get(name)?.as_ref()
1435}
1436
1437/// Whether `ty` is exactly `Int -> Int -> Int` (binder names irrelevant).
1438fn is_int_binop(ty: &Term) -> bool {
1439 fn is_int(t: &Term) -> bool {
1440 matches!(t, Term::Global(n) if n == "Int")
1441 }
1442 let Term::Pi {
1443 param_type,
1444 body_type,
1445 ..
1446 } = ty
1447 else {
1448 return false;
1449 };
1450 if !is_int(param_type) {
1451 return false;
1452 }
1453 let Term::Pi {
1454 param_type,
1455 body_type,
1456 ..
1457 } = body_type.as_ref()
1458 else {
1459 return false;
1460 };
1461 is_int(param_type) && is_int(body_type)
1462}
1463
1464/// The Rust integer operator for a kernel arithmetic builtin NAME. Callers that have a
1465/// [`Context`] must use [`arith_builtin_operator`], which also checks the type; this is the
1466/// name table it is built on.
1467pub(crate) fn arith_operator(name: &str) -> Option<&'static str> {
1468 Some(match name {
1469 "add" => "+",
1470 "sub" => "-",
1471 "mul" => "*",
1472 "div" => "/",
1473 "mod" => "%",
1474 _ => return None,
1475 })
1476}
1477
1478/// The Rust identifier the kernel constant `key` is emitted as.
1479///
1480/// A key is its own identifier, except where a SHADOW is involved (`Context::shadows`, the ruling
1481/// of 2026-09-24). A declaration registered under a fresh identity (`add_zero✝⟨1⟩`), which no
1482/// Rust identifier can spell, is emitted as the name its author wrote for as long as that name
1483/// denotes it — so the author's `add_zero` extracts to `check_add_zero`, the function an
1484/// imperative `Require that check_add_zero().` calls — and as `<name>_shadowed<n>` once a later
1485/// declaration has taken the name. A declaration a live shadow hides is emitted as `<key>_root`,
1486/// so it never meets the shadow under one Rust name. A constant derived from an identity follows
1487/// it.
1488pub fn rust_global(ctx: &Context, key: &str) -> String {
1489 if let Some(identity) = ctx.shadow_root(key) {
1490 let origin = ctx.shadow_origin(&identity).unwrap_or(identity.as_str());
1491 let name = if ctx.is_live_shadow(&identity) {
1492 origin.to_string()
1493 } else {
1494 let minted = identity
1495 .rsplit('\u{27e8}')
1496 .next()
1497 .and_then(|tail| tail.strip_suffix('\u{27e9}'))
1498 .unwrap_or_default();
1499 format!("{origin}_shadowed{minted}")
1500 };
1501 return key.replacen(identity.as_str(), &name, 1);
1502 }
1503 if ctx.shadow_of(key).is_some() {
1504 return format!("{key}_root");
1505 }
1506 key.to_string()
1507}
1508
1509/// Convert a kernel type to a Rust type string.
1510fn type_to_rust(ctx: &Context, ty: &Term) -> String {
1511 match ty {
1512 // A type variable (an inductive's type parameter) → a Rust generic.
1513 Term::Var(name) => name.clone(),
1514 Term::Global(name) => primitive_rust_type(name)
1515 .map(str::to_string)
1516 .unwrap_or_else(|| rust_global(ctx, name)),
1517 Term::Pi {
1518 param_type,
1519 body_type,
1520 ..
1521 } => {
1522 // Non-dependent function type: A -> B
1523 let arg = type_to_rust(ctx, param_type);
1524 let ret = type_to_rust(ctx, body_type);
1525 format!("fn({}) -> {}", arg, ret)
1526 }
1527 Term::App(_, _) => {
1528 // A generic instantiation like `MyList Nat` or `MyPair A B`. Flatten
1529 // the application chain into `Head<arg0, arg1, …>`.
1530 let (head, args) = collect_app_chain(ty);
1531 let head_str = type_to_rust(ctx, head);
1532 let arg_strs: Vec<String> = args.iter().map(|a| type_to_rust(ctx, a)).collect();
1533 format!("{}<{}>", head_str, arg_strs.join(", "))
1534 }
1535 Term::Sort(_) => "()".to_string(),
1536 Term::Lit(_) => "()".to_string(), // Literals shouldn't appear as types
1537 _ => "()".to_string(),
1538 }
1539}
1540
1541/// Check if a term is a lambda.
1542fn is_lambda(term: &Term) -> bool {
1543 matches!(term, Term::Lambda { .. })
1544}
1545
1546/// Extract parameters from nested lambdas.
1547fn extract_lambda_params(term: &Term) -> (Vec<(String, Term)>, &Term) {
1548 let mut params = Vec::new();
1549 let mut current = term;
1550
1551 while let Term::Lambda {
1552 param,
1553 param_type,
1554 body,
1555 } = current
1556 {
1557 params.push((param.clone(), (**param_type).clone()));
1558 current = body;
1559 }
1560
1561 (params, current)
1562}
1563
1564/// Extract parameter types from a Pi type.
1565fn extract_pi_params(ty: &Term) -> Vec<(String, Term)> {
1566 let mut params = Vec::new();
1567 let mut current = ty;
1568
1569 while let Term::Pi {
1570 param,
1571 param_type,
1572 body_type,
1573 } = current
1574 {
1575 params.push((param.clone(), (**param_type).clone()));
1576 current = body_type;
1577 }
1578
1579 params
1580}
1581
1582/// Extract the return type from a (possibly nested) Pi type.
1583fn extract_return_type(ty: &Term) -> Term {
1584 let mut current = ty;
1585 while let Term::Pi { body_type, .. } = current {
1586 current = body_type;
1587 }
1588 current.clone()
1589}
1590
1591/// Count the number of arguments a constructor takes.
1592fn count_ctor_args(ty: &Term) -> usize {
1593 let mut count = 0;
1594 let mut current = ty;
1595 while let Term::Pi { body_type, .. } = current {
1596 count += 1;
1597 current = body_type;
1598 }
1599 count
1600}
1601
1602/// Extract bindings from a case (which is typically a lambda).
1603fn extract_case_bindings(case: &Term, arity: usize) -> (Vec<String>, Term) {
1604 let mut bindings = Vec::new();
1605 let mut current = case;
1606
1607 for _ in 0..arity {
1608 if let Term::Lambda { param, body, .. } = current {
1609 bindings.push(param.clone());
1610 current = body;
1611 } else {
1612 break;
1613 }
1614 }
1615
1616 (bindings, current.clone())
1617}
1618
1619/// Collect the head and all arguments from a chain of applications.
1620///
1621/// For `((f a) b) c`, returns `(f, [a, b, c])`.
1622fn collect_app_chain(term: &Term) -> (&Term, Vec<&Term>) {
1623 let mut args = Vec::new();
1624 let mut current = term;
1625
1626 while let Term::App(f, a) = current {
1627 args.push(a.as_ref());
1628 current = f.as_ref();
1629 }
1630
1631 // Reverse to get args in application order
1632 args.reverse();
1633 (current, args)
1634}
1635
1636/// Check if a term is a constructor application.
1637#[allow(dead_code)]
1638fn is_constructor_app(term: &Term, ctx: &Context) -> bool {
1639 match term {
1640 Term::Global(name) => ctx.is_constructor(name),
1641 Term::App(f, _) => is_constructor_app(f, ctx),
1642 _ => false,
1643 }
1644}