logicaffeine_kernel/interface/repl.rs
1//! REPL for the Vernacular interface.
2//!
3//! Orchestrates command parsing and kernel execution.
4
5use super::command::Command;
6use super::error::{InterfaceError, ParseError};
7use super::parse_command_in_ctx;
8use super::surface::{fill_defaults, resolve_names_in, Name, Resolution, Surface};
9use super::term_parser::{BinderKind, BinderSurface, TermParser};
10use super::with_env;
11use crate::{
12 auto_bind_implicits, bind_self_recursion, fill_match_motives, infer_type, normalize,
13 surface_elaborate, surface_elaborate_against, Context, KernelError, Term,
14};
15use std::borrow::Cow;
16
17/// The Vernacular REPL.
18///
19/// Maintains a kernel context and executes commands against it.
20pub struct Repl {
21 ctx: Context,
22 /// The SURFACE: the notation, fixity and macros this session has declared. It sits beside the
23 /// kernel context and never inside it — a way of spelling a declaration is not a declaration.
24 surface: Surface,
25 /// How many commands this session has run under the shadowing snapshot
26 /// ([`Repl::shadow_snapshots`]).
27 snapshots: usize,
28}
29
30/// A declaration elaborated against its declared type — what every checked declaration door
31/// hands to its kernel gateway.
32struct Elaborated {
33 ty: Term,
34 body: Term,
35 binders: Vec<BinderSurface>,
36 implicit_count: usize,
37}
38
39impl Repl {
40 /// Create a new REPL with the standard library loaded.
41 pub fn new() -> Self {
42 Self {
43 ctx: super::standard_context(),
44 surface: Surface::new(),
45 snapshots: 0,
46 }
47 }
48
49 /// Execute a command string.
50 ///
51 /// Returns the output string (for Check/Eval) or empty string (for Definition/Inductive).
52 pub fn execute(&mut self, input: &str) -> Result<String, InterfaceError> {
53 // A declaration's terms are resolved and elaborated by recursive walks, so the whole
54 // command runs on a stack sized for the text — a printed declaration of the deepest term
55 // the kernel admits reads, checks and registers on an ordinary caller's thread.
56 let depth = super::term_parser::syntactic_depth(input);
57 super::term_parser::on_stack_for(depth, move || {
58 let cmd = parse_command_in_ctx(&self.ctx, &self.surface, input)?;
59 let declared = self.declared_keys(&cmd);
60 if !self.redeclares(&declared) {
61 return self.run(cmd);
62 }
63 // A retry READS THE COMMAND AGAIN: a door that resolves names as it parses (the literate
64 // one) must see the shadow the refusal just recorded.
65 let mut parsed = Some(cmd);
66 self.shadowing(&declared, |repl| {
67 let cmd = match parsed.take() {
68 Some(cmd) => cmd,
69 None => parse_command_in_ctx(&repl.ctx, &repl.surface, input)?,
70 };
71 repl.run(cmd)
72 })
73 })
74 }
75
76 /// Whether a command declaring the written names `declared` names anything this environment
77 /// already holds — the only way it can meet the stable-meaning gate, and so the only case
78 /// [`shadowing`](Self::shadowing) is asked to handle. A command that declares only fresh names
79 /// runs straight through, without the context snapshot a retry needs: taking one makes the
80 /// command's first write to every table it touches copy that whole table, which a document of
81 /// thousands of fresh declarations must not pay.
82 fn redeclares(&self, declared: &[String]) -> bool {
83 declared.iter().any(|written| {
84 let key = self
85 .ctx
86 .shadow_of(written)
87 .unwrap_or_else(|| written.clone());
88 self.ctx.get_global(&key).is_some() || self.ctx.poly_declaration(&key).is_some()
89 })
90 }
91
92 /// The absolute WRITTEN names `cmd` declares here, its constructors included — the current
93 /// namespace applied, a shadow not: these are what a shadow is keyed by. A constructor is keyed
94 /// in the scope its inductive's own name opens, as registration keys it.
95 fn declared_keys(&mut self, cmd: &Command) -> Vec<String> {
96 match cmd {
97 Command::Inductive {
98 name, constructors, ..
99 } => self.member_keys(name, constructors.iter().map(|(c, _)| c.as_str())),
100 Command::InductiveBlock { members } => {
101 let mut keys = Vec::new();
102 for member in members {
103 keys.extend(self.member_keys(
104 &member.name,
105 member.constructors.iter().map(|(c, _)| c.as_str()),
106 ));
107 }
108 keys
109 }
110 Command::Universes { inner, .. }
111 | Command::Protected(inner)
112 | Command::OpenIn { inner, .. } => self.declared_keys(inner),
113 other => declared_names(other)
114 .iter()
115 .map(|name| self.written_key(name))
116 .collect(),
117 }
118 }
119
120 /// An inductive's written key and its constructors', read in the scope its name opens.
121 fn member_keys<'n>(
122 &mut self,
123 name: &str,
124 constructors: impl Iterator<Item = &'n str>,
125 ) -> Vec<String> {
126 let (key, mark) = match Name::parse(name) {
127 Some(declared) => self.surface.enter_declaration(&declared),
128 None => (name.to_string(), self.surface.namespaces().mark()),
129 };
130 let mut keys = vec![key];
131 keys.extend(constructors.map(|c| self.written_key(c)));
132 self.surface.namespaces_mut().rewind(mark);
133 keys
134 }
135
136 /// The absolute written name a declaration name written HERE declares — no shadow applied.
137 fn written_key(&self, written: &str) -> String {
138 match Name::parse(written) {
139 Some(n) => self.surface.namespaces().declaration_key(&n),
140 None => written.to_string(),
141 }
142 }
143
144 /// Run one declaring step under the shadowing rule: a declaration the stable-meaning gate refuses
145 /// because its name already means something others were checked against is registered under a
146 /// FRESH IDENTITY instead, and its written name denotes that identity from then on.
147 ///
148 /// The gate stays the only judge. `attempt` runs exactly as it always did; when the kernel
149 /// answers `StableMeaningViolation` for a name the step declares, the context is restored to
150 /// what it was before the step, the written name is recorded as denoting a freshly minted
151 /// identity, and the step runs again — READ again, so every name in it, its own included,
152 /// resolves through the new shadow. A second refusal names a second declared name (an
153 /// inductive's constructor, after the inductive itself), so the loop mints once per name and
154 /// ends. Anything else the step answers is its answer — a refusal of a name the step does not
155 /// declare (`declared`, the written absolute names) included: that is not the step's name to
156 /// shadow. An identical redeclaration is kept by the gate, and a name nothing depends on is
157 /// replaced in place, so neither mints anything.
158 fn shadowing<T>(
159 &mut self,
160 declared: &[String],
161 mut attempt: impl FnMut(&mut Self) -> Result<T, InterfaceError>,
162 ) -> Result<T, InterfaceError> {
163 let before = self.ctx.clone();
164 self.snapshots += 1;
165 let mut minted: Vec<(String, String)> = Vec::new();
166 loop {
167 let refused = match attempt(self) {
168 Err(InterfaceError::Kernel(KernelError::StableMeaningViolation {
169 name,
170 change,
171 dependents,
172 })) => (name, change, dependents),
173 outcome => return self.settle(before, &minted, outcome),
174 };
175 let written = self
176 .ctx
177 .spelled_by(&refused.0)
178 .unwrap_or_else(|| refused.0.clone());
179 if !declared.contains(&written) || minted.iter().any(|(w, _)| *w == written) {
180 let (name, change, dependents) = refused;
181 let violation = KernelError::StableMeaningViolation {
182 name,
183 change,
184 dependents,
185 };
186 return self.settle(before, &minted, Err(InterfaceError::Kernel(violation)));
187 }
188 self.ctx = before.clone();
189 let identity = self.ctx.mint_shadow_identity(&written);
190 minted.push((written, identity));
191 for (written, identity) in &minted {
192 self.ctx.record_shadow(written, identity);
193 }
194 }
195 }
196
197 /// A shadowing step's outcome. A step that minted identities and still failed leaves nothing
198 /// behind: the identities and the partial registration its retry made are taken back with it.
199 fn settle<T>(
200 &mut self,
201 before: Context,
202 minted: &[(String, String)],
203 outcome: Result<T, InterfaceError>,
204 ) -> Result<T, InterfaceError> {
205 if outcome.is_err() && !minted.is_empty() {
206 self.ctx = before;
207 }
208 outcome
209 }
210
211 /// Resolve every name written in `term` against the namespace scope, BEFORE any elaboration
212 /// sees it. Lean's staging: `resolveGlobalName` runs to completion before a term reaches the
213 /// kernel, which is why the kernel needs to know nothing about namespaces at all.
214 ///
215 /// `pending` are the keys this very command is about to declare — a recursive definition refers
216 /// to itself by its short name from inside its own namespace, and a constructor's type names the
217 /// inductive it belongs to; neither is in the context yet. `locals` shields names that are BOUND
218 /// rather than global (an inductive's type parameters arrive from the parser as `Global`s and
219 /// only become `Var`s at registration).
220 ///
221 /// Then every OMITTED DEFAULT ARGUMENT is filled, in the same pass and for the same reason:
222 /// `withDefault 1` is a spelling of `withDefault 1 3` exactly as `token` under `open Alpha` is
223 /// a spelling of `Alpha.token`, and both are expansions the elaborator must never have to know
224 /// about. Resolution runs FIRST — a default is recorded under the declaration's absolute key,
225 /// so the head has to be the key before it can be looked up.
226 ///
227 /// Borrows when nothing needed resolving, so an empty scope costs one read-only walk.
228 fn resolve<'t>(
229 &self,
230 term: &'t Term,
231 pending: &[String],
232 locals: &mut Vec<String>,
233 ) -> Result<Cow<'t, Term>, InterfaceError> {
234 let resolved = with_env(&self.ctx, pending, |env| {
235 resolve_names_in(self.surface.namespaces(), env, locals, term)
236 })?;
237 Ok(fill_defaults(&self.surface, resolved))
238 }
239
240 /// The absolute key a declaration written here gets, and the scope its body elaborates in.
241 /// Restore the returned mark once the body is done, whatever the outcome.
242 ///
243 /// A name no TERM can spell gets no namespace treatment: it keeps the flat key it arrived with
244 /// and opens nothing. That is not a concession, it is the honest reading — a name that cannot be
245 /// written cannot be written RELATIVELY either, so there is nothing for a namespace to do with
246 /// it. The Coq-style door already refuses such a name (`declaration_name` shares the term
247 /// grammar); this is the guarantee that whatever a literate surface produces keeps behaving
248 /// exactly as it did.
249 ///
250 /// The key is the one the written name DENOTES: a name a shadow redirects declares at the
251 /// shadow's identity, exactly as a reference to it resolves there.
252 fn enter_declaration(&mut self, written: &str) -> (String, super::surface::ScopeMark) {
253 let (key, mark) = match Name::parse(written) {
254 Some(declared) => self.surface.enter_declaration(&declared),
255 None => (written.to_string(), self.surface.namespaces().mark()),
256 };
257 (self.ctx.shadow_of(&key).unwrap_or(key), mark)
258 }
259
260 /// Execute ONE already-parsed command.
261 ///
262 /// Split out from [`execute`] because `Open … in <command>` is CONTROL FLOW: it has to bracket
263 /// the execution of the command it scopes and wind the scope back afterwards, which a body that
264 /// parses and then matches cannot do.
265 fn run(&mut self, cmd: Command) -> Result<String, InterfaceError> {
266 match cmd {
267 Command::Surface(decl) => {
268 // ★ A SCOPE FORM IS A SCOPE IN BOTH STACKS. `Section`/`End` and `Namespace`/`End`
269 // moved the SURFACE's scope — which notation is in force — and left the KERNEL's at
270 // zero, so a `section` scoped how things were SPELLED and nothing about what was in
271 // force inside it: a `local` instance, coercion, simp rule, hint or reducibility
272 // edit made inside one never left at its `end`. Lean scopes `local` at both forms,
273 // and so does this.
274 //
275 // The two depths are MIRRORED, never restated: the surface already counts its own
276 // open scopes and the kernel is moved to agree with that count, so a third scope
277 // form added later is one in the kernel too without a line here, and the two can
278 // never drift into disagreeing about how many are open.
279 self.surface.declare(decl)?;
280 self.match_kernel_scopes();
281 Ok(String::new()) // a way of spelling something is not a declaration
282 }
283
284 Command::Open(clauses) => {
285 // All or nothing: a list with one clause that does not check opens none of them, so
286 // a typo cannot leave half a scope behind.
287 let mark = self.surface.namespaces().mark();
288 match self.apply_opens(clauses) {
289 Ok(()) => Ok(String::new()), // an opening is a spelling, not a declaration
290 Err(e) => {
291 self.surface.namespaces_mut().rewind(mark);
292 Err(e)
293 }
294 }
295 }
296
297 Command::OpenIn { opens, inner } => {
298 let mark = self.surface.namespaces().mark();
299 let out = match self.apply_opens(opens) {
300 Ok(()) => self.run(*inner),
301 Err(e) => Err(e),
302 };
303 // Wound back on FAILURE too: a refused command must not leave its opening behind,
304 // or the next command reads names in a scope nobody wrote.
305 self.surface.namespaces_mut().rewind(mark);
306 out
307 }
308
309 Command::Definition { .. }
310 | Command::Theorem { .. }
311 | Command::TheoremBy { .. }
312 | Command::Opaque { .. }
313 | Command::Axiom { .. }
314 | Command::InductiveBlock { .. }
315 | Command::Quotient { .. } => self.declare(None, cmd),
316
317 Command::Universes { params, inner } => self.declare(Some(params), *inner),
318
319 Command::Export { namespace, names } => {
320 // The environment is the whole point: an alias to a name the source namespace does
321 // not declare, or one the current namespace already declares, is refused here
322 // because only here can it be SEEN.
323 let Repl { ctx, surface, .. } = self;
324 let known = |key: &str| ctx.get_global(key).is_some();
325 surface
326 .namespaces_mut()
327 .export(&namespace, &names, &known)?;
328 Ok(String::new()) // an alias is a spelling, and a spelling is not a declaration
329 }
330
331 Command::Protected(inner) => {
332 // The key the inner command will land at, read BEFORE it runs — the declaration's
333 // own namespace frame comes off again, so afterwards the current namespace no
334 // longer says where it went.
335 let declared = declared_names(inner.as_ref());
336 if declared.is_empty() {
337 return Err(ParseError::Unsupported {
338 what: "`Protected` on a command that declares nothing".to_string(),
339 why:
340 "`protected` changes which SHORT NAME reaches a declaration, so there \
341 has to be one. Write it on a `Definition`, `Theorem`, `Opaque`, \
342 `Axiom` or `Inductive`"
343 .to_string(),
344 }
345 .into());
346 }
347 // The WRITTEN absolute key, and not the identity a shadow gives it: `protected`
348 // decides which short name reaches a written name, and a shadow is reached through
349 // exactly that written name.
350 let keys: Vec<String> = declared
351 .into_iter()
352 .map(|declared| match Name::parse(&declared) {
353 Some(name) => self.surface.namespaces().declaration_key(&name),
354 None => declared,
355 })
356 .collect();
357 let out = self.run(*inner)?;
358 // Marked only on SUCCESS: a declaration that did not check protects nothing.
359 for key in &keys {
360 self.surface.namespaces_mut().record_protected(key);
361 }
362 Ok(out)
363 }
364
365 Command::PrintAxioms(written) => {
366 // A REFERENCE, so it reads in the scope it is written in — the same resolution a
367 // term's name gets, asked of the same door.
368 let Repl { ctx, surface, .. } = self;
369 let key =
370 match with_env(ctx, &[], |env| env.resolve(surface.namespaces(), &written)) {
371 Resolution::Found(key) => key,
372 Resolution::Unresolved(key) => key,
373 Resolution::Ambiguous {
374 written,
375 candidates,
376 } => {
377 return Err(ParseError::AmbiguousName {
378 written,
379 candidates,
380 }
381 .into())
382 }
383 };
384 // ONE implementation, three surfaces. `axiom_dependencies_of` is what the
385 // re-check gate and the trusted-base census already read; a second closure written
386 // here could disagree with them about what a proof rests on, and the whole value of
387 // the report is that it cannot.
388 match crate::axiom_dependencies_of(ctx, &key) {
389 Some(usage) => Ok(usage.render(&key)),
390 None => Err(InterfaceError::Kernel(crate::KernelError::UnboundVariable(
391 key,
392 ))),
393 }
394 }
395
396 Command::Comment => Ok(String::new()), // prose declares nothing
397
398 Command::Structure {
399 inductive,
400 projections,
401 } => {
402 let key = |repl: &Self, written: String| -> Result<String, InterfaceError> {
403 let reference = Term::Global(written);
404 match repl.resolve(&reference, &[], &mut Vec::new())?.into_owned() {
405 Term::Global(key) => Ok(key),
406 other => Ok(other.to_string()),
407 }
408 };
409 let inductive = key(self, inductive)?;
410 let projections = projections
411 .into_iter()
412 .map(|p| key(self, p))
413 .collect::<Result<Vec<_>, _>>()?;
414 self.ctx
415 .register_structure_checked(&inductive, &projections)
416 .map_err(|e| {
417 InterfaceError::Kernel(crate::KernelError::InvalidDeclaration(
418 e.to_string(),
419 ))
420 })?;
421 Ok(String::new())
422 }
423
424 Command::Check(term) => {
425 let term = self.resolve(&term, &[], &mut Vec::new())?.into_owned();
426 // Infer `match` motives, insert implicit arguments, then infer the type.
427 let term = fill_match_motives(&self.ctx, &term, None)?;
428 let term = surface_elaborate(&self.ctx, &term)?;
429 let ty = infer_type(&self.ctx, &term)?;
430 Ok(format!("{} : {}", self.written(&term), self.written(&ty)))
431 }
432
433 Command::Eval(term) => {
434 let term = self.resolve(&term, &[], &mut Vec::new())?.into_owned();
435 // Infer `match` motives, insert implicits, type check, then normalize.
436 let term = fill_match_motives(&self.ctx, &term, None)?;
437 let term = surface_elaborate(&self.ctx, &term)?;
438 let _ = infer_type(&self.ctx, &term)?;
439 let result = normalize(&self.ctx, &term);
440 Ok(format!("{}", self.written(&result)))
441 }
442
443 Command::Inductive {
444 name,
445 params,
446 sort,
447 constructors,
448 } => {
449 let (key, mark) = self.enter_declaration(&name);
450 let out = self.register_inductive(key, params, sort, constructors);
451 self.surface.namespaces_mut().rewind(mark);
452 out
453 }
454 }
455 }
456
457 /// Execute one DECLARATION, bound by `universes` when a telescope was written on it.
458 ///
459 /// The telescope is a wrapper around the declaration it binds (`Command::Universes`), and this
460 /// is the one place it is taken apart, so every declaration door receives it the same way and a
461 /// telescope on anything that declares nothing is refused here rather than ignored.
462 fn declare(
463 &mut self,
464 universes: Option<Vec<String>>,
465 cmd: Command,
466 ) -> Result<String, InterfaceError> {
467 let telescope = |universes: Option<Vec<String>>| universes.unwrap_or_default();
468 match cmd {
469 Command::Definition {
470 name,
471 ty,
472 body,
473 is_hint,
474 implicit_count,
475 proof_goal,
476 } => {
477 let (key, mark) = self.enter_declaration(&name);
478 let out = self.define(
479 key,
480 universes,
481 ty,
482 body,
483 is_hint,
484 implicit_count,
485 proof_goal,
486 );
487 self.surface.namespaces_mut().rewind(mark);
488 out
489 }
490 Command::Theorem { name, ty, proof } => {
491 let (key, mark) = self.enter_declaration(&name);
492 let out = self.declare_opaque(key, telescope(universes), ty, proof, true);
493 self.surface.namespaces_mut().rewind(mark);
494 out
495 }
496 Command::TheoremBy { name, ty, script } => {
497 let (key, mark) = self.enter_declaration(&name);
498 let out = self.prove_by_script(key, telescope(universes), ty, &script);
499 self.surface.namespaces_mut().rewind(mark);
500 out
501 }
502 Command::Opaque { name, ty, value } => {
503 let (key, mark) = self.enter_declaration(&name);
504 let out = self.declare_opaque(key, telescope(universes), ty, value, false);
505 self.surface.namespaces_mut().rewind(mark);
506 out
507 }
508 Command::Axiom { name, ty } => {
509 let (key, mark) = self.enter_declaration(&name);
510 let out = self.declare_axiom(key, telescope(universes), ty);
511 self.surface.namespaces_mut().rewind(mark);
512 out
513 }
514 Command::InductiveBlock { members } => self.register_block(universes, members),
515 Command::Quotient { kind, equality } => {
516 let Some(params) = universes else {
517 return Err(ParseError::Missing(format!(
518 "the universe parameters of the quotient primitive `{}` \u{2014} written \
519 `.{{u}}` after its name",
520 kind.name()
521 ))
522 .into());
523 };
524 let equality = match equality {
525 Some(written) => {
526 let reference = Term::Global(written);
527 let resolved = self.resolve(&reference, &[], &mut Vec::new())?.into_owned();
528 match resolved {
529 Term::Global(key) => key,
530 other => other.to_string(),
531 }
532 }
533 None => String::new(),
534 };
535 crate::quotient::install(&mut self.ctx, kind, params, &equality)
536 .map_err(InterfaceError::Kernel)?;
537 self.surface
538 .namespaces_mut()
539 .record_declaration(kind.name());
540 Ok(String::new())
541 }
542 other => Err(ParseError::Unsupported {
543 what: format!(
544 "a universe telescope on {}",
545 match other {
546 Command::Universes { .. } => "a declaration that already has one",
547 Command::Inductive { .. } => "the undeclared-arity `Inductive` form",
548 _ => "a command that declares nothing",
549 }
550 ),
551 why: "universe parameters bind over ONE declaration \u{2014} a `Definition`, \
552 `Theorem`, `Opaque`, `Axiom`, or an `Inductive` that declares its arity"
553 .to_string(),
554 }
555 .into()),
556 }
557 }
558
559 /// Register an inductive BLOCK exactly as declared, through the kernel's checked block door —
560 /// `Context::add_mutual_inductives`, or `add_universe_poly_inductives` under a telescope — the
561 /// door the Lean importer registers its inductives through.
562 ///
563 /// Unlike the legacy `Inductive` path, nothing is inferred: each member's parameter count is
564 /// the number of parameters written, the rest of its declared arity is indices, and the block
565 /// is one mutual block because the writer said so, not because its members happen to mention
566 /// one another. Then the declaration-time family (`{I}_rec`, `{I}_casesOn`, …) is derived for
567 /// every member, as the mutual path already does.
568 fn register_block(
569 &mut self,
570 universes: Option<Vec<String>>,
571 members: Vec<super::command::InductiveMember>,
572 ) -> Result<String, InterfaceError> {
573 let mut keys: Vec<(String, Vec<String>)> = Vec::with_capacity(members.len());
574 for member in &members {
575 let (key, mark) = self.enter_declaration(&member.name);
576 let ctors: Vec<String> = member
577 .constructors
578 .iter()
579 .map(|(cn, _)| self.declaration_key(cn))
580 .collect();
581 self.surface.namespaces_mut().rewind(mark);
582 keys.push((key, ctors));
583 }
584 let mut pending: Vec<String> = Vec::new();
585 for (key, ctors) in &keys {
586 pending.push(key.clone());
587 pending.extend(ctors.iter().cloned());
588 }
589 let mut block = Vec::with_capacity(members.len());
590 for (member, (key, ctor_keys)) in members.iter().zip(&keys) {
591 let (_, mark) = self.enter_declaration(&member.name);
592 let resolved = (|| -> Result<crate::context::MutualInductive, InterfaceError> {
593 let mut locals: Vec<String> =
594 member.params.iter().map(|(p, _)| p.clone()).collect();
595 let resolve = |t: &Term, locals: &mut Vec<String>| {
596 self.resolve(t, &pending, locals).map(Cow::into_owned)
597 };
598 let params: Vec<(String, Term)> = member
599 .params
600 .iter()
601 .map(|(p, t)| resolve(t, &mut locals).map(|t| (p.clone(), t)))
602 .collect::<Result<_, _>>()?;
603 let arity = resolve(&member.sort, &mut locals)?;
604 // A RESTATED telescope is registered exactly as written: its binders bind the
605 // parameters, so nothing is converted and nothing is prepended.
606 let constructors: Vec<(String, Term)> = ctor_keys
607 .iter()
608 .zip(&member.constructors)
609 .map(|(ck, (_, cty))| {
610 if member.full_constructors {
611 resolve(cty, &mut Vec::new()).map(|t| (ck.clone(), t))
612 } else {
613 resolve(cty, &mut locals)
614 .map(|t| (ck.clone(), parameter_telescope(¶ms, t)))
615 }
616 })
617 .collect::<Result<_, _>>()?;
618 Ok(crate::context::MutualInductive {
619 name: key.clone(),
620 sort: parameter_telescope(¶ms, arity),
621 num_params: params.len(),
622 constructors,
623 })
624 })();
625 self.surface.namespaces_mut().rewind(mark);
626 block.push(resolved?);
627 }
628 match &universes {
629 Some(levels) => self.ctx.add_universe_poly_inductives(levels, &block),
630 None => self.ctx.add_mutual_inductives(&block),
631 }
632 .map_err(InterfaceError::Kernel)?;
633 for member in &block {
634 self.surface
635 .namespaces_mut()
636 .record_declaration(&member.name);
637 for (cn, _) in &member.constructors {
638 self.surface.namespaces_mut().record_declaration(cn);
639 }
640 }
641 // The declaration-time family, through the door that records its PROVENANCE, so a derived
642 // constant is known as derived (`Context::is_derived_aux`) and a later re-derivation
643 // replaces its own generation rather than refusing to touch a "hand-written" one.
644 for member in &block {
645 self.ctx.regenerate_auxiliaries(&member.name);
646 }
647 Ok(String::new())
648 }
649
650 /// How many SCOPES the surface has open — sections plus namespaces, which are the two forms
651 /// Lean scopes `local` at. The kernel's [`Context::scope_depth`] tracks this number.
652 fn open_scopes(&self) -> usize {
653 self.surface.section_depth() + self.surface.namespaces().depth()
654 }
655
656 /// Move the kernel's scope depth to whatever the surface's is NOW.
657 ///
658 /// Stated absolutely rather than as a delta, and that is not a detail: the document door winds
659 /// the surface back wholesale on a refusal, so a command that opened a scope and a document
660 /// that abandoned three both arrive here as "the surface has N open, make the kernel agree".
661 /// A delta would have to be computed by whichever path did the winding, which is exactly the
662 /// bookkeeping that drifts.
663 ///
664 /// The REPL owns [`Context::scope_depth`] for as long as it owns the context.
665 fn match_kernel_scopes(&mut self) {
666 let want = self.open_scopes();
667 while self.ctx.scope_depth() > want {
668 self.ctx.pop_scope();
669 }
670 while self.ctx.scope_depth() < want {
671 self.ctx.push_scope();
672 }
673 }
674
675 /// Apply a list of `open` clauses against the ENVIRONMENT.
676 ///
677 /// A clause that names members (`Open Alpha (a b).`, `Open Alpha hiding (a).`) can only be
678 /// checked here: a name the namespace does not declare narrows the opening to nothing and reads
679 /// exactly like a clause that worked. The caller winds the scope back on failure, so a list
680 /// whose second clause is wrong opens neither.
681 fn apply_opens(
682 &mut self,
683 clauses: Vec<super::surface::OpenClause>,
684 ) -> Result<(), InterfaceError> {
685 let Repl { ctx, surface, .. } = self;
686 let known = |key: &str| ctx.get_global(key).is_some();
687 for clause in clauses {
688 surface.namespaces_mut().open_clause(clause, &known)?;
689 }
690 Ok(())
691 }
692
693 /// Register one `Definition` at the ABSOLUTE key `name`, with the namespace scope its body
694 /// elaborates in already entered by the caller. `universes` is its universe telescope when one
695 /// was written (`Definition name.{u} …`), and then it registers through the kernel's
696 /// universe-polymorphic door, which refuses a level variable the telescope does not bind.
697 #[allow(clippy::too_many_arguments)]
698 fn define(
699 &mut self,
700 name: String,
701 universes: Option<Vec<String>>,
702 ty: Option<Term>,
703 body: Term,
704 is_hint: bool,
705 implicit_count: usize,
706 proof_goal: Option<Term>,
707 ) -> Result<String, InterfaceError> {
708 let pending = [name.clone()];
709 let Elaborated {
710 ty,
711 body,
712 binders,
713 implicit_count,
714 } = self.elaborate_declaration(&name, ty, body, implicit_count)?;
715 let proof_goal = match proof_goal {
716 Some(g) => Some(self.resolve(&g, &pending, &mut Vec::new())?.into_owned()),
717 None => None,
718 };
719 // Soundness gate for literate tactic proofs (`## Theorem … Proof: <tactic>.`).
720 // The body is a reflected `Derivation`; `infer_type` only confirms it is WELL-FORMED,
721 // and a FAILED tactic still yields a well-typed *error* derivation. So type-checking
722 // alone would accept a false theorem. `proof_goal` carries the goal the derivation
723 // must establish: require `concludes body` to reduce to exactly that goal. A failed
724 // or malformed tactic concludes to the `SName "Error"` sentinel instead, and is
725 // rejected here. (Only literate theorem proofs set `proof_goal`; a raw
726 // `d : Derivation := …` has `None` and is left untouched.)
727 if let Some(goal_syntax) = &proof_goal {
728 let concluded = normalize(
729 &self.ctx,
730 &Term::App(
731 Box::new(Term::Global("concludes".to_string())),
732 Box::new(body.clone()),
733 ),
734 );
735 let want = normalize(&self.ctx, goal_syntax);
736 if concluded != want {
737 let name = self.ctx.written_name(&name);
738 return Err(InterfaceError::Kernel(
739 crate::KernelError::CertificationError(format!(
740 "tactic proof of `{name}` did not certify: the tactic did not \
741 establish the stated goal"
742 )),
743 ));
744 }
745 }
746
747 // Add definition to context
748 match universes {
749 Some(params) => self
750 .ctx
751 .declare_universe_poly(&name, params, ty, body)
752 .map_err(InterfaceError::Kernel)?,
753 None => self
754 .ctx
755 .declare(&name, ty, body)
756 .map_err(InterfaceError::Kernel)?,
757 }
758 self.record_declaration_surface(&name, binders, implicit_count);
759
760 // Register as hint if marked
761 if is_hint {
762 self.ctx.add_hint(&name);
763 }
764
765 Ok(String::new()) // Silent success
766 }
767
768 /// Elaborate a declaration's body against its declared type, exactly as every checked
769 /// declaration door does: split the declared surface off the kernel type, resolve names in the
770 /// scope the declaration is written in, bind the free type variables Lean's `autoImplicit`
771 /// would, recover a recursive body's `fix`, infer match motives, insert implicit arguments, and
772 /// check the body's type against the declared one.
773 ///
774 /// ONE implementation for `Definition`, `Theorem` and `Opaque`, so the three cannot come to
775 /// disagree about what a body written in the vernacular MEANS — they differ only in which
776 /// kernel door the elaborated pair then goes through.
777 fn elaborate_declaration(
778 &mut self,
779 name: &str,
780 ty: Option<Term>,
781 body: Term,
782 implicit_count: usize,
783 ) -> Result<Elaborated, InterfaceError> {
784 // ★ THE DECLARED TYPE ARRIVES WITH ITS SURFACE STILL ON IT, and the two must part here.
785 // `Definition f : Int -> (m : Int := 3) -> Int` parses to a `Pi` whose parameter type is a
786 // reserved marker application carrying the default; registering THAT is what used to hand
787 // the kernel an unbound global with a `⟨default⟩` in its name. `declaration_surface` splits
788 // it into the kernel type the context is keyed at and the per-parameter surface a CALL SITE
789 // needs, which is the only thing either half is for.
790 let (ty, body, mut binders) = match ty {
791 Some(t) => {
792 let declared = TermParser::declaration_surface(&t);
793 (Some(declared.kernel_type), body, declared.binders)
794 }
795 None => {
796 let declared = TermParser::declaration_surface(&body);
797 (None, declared.kernel_type, declared.binders)
798 }
799 };
800 // Commands built without parser markers still carry their leading implicit count.
801 for binder in binders.iter_mut().take(implicit_count) {
802 binder.kind = BinderKind::Implicit;
803 }
804 let declared_implicits = implicit_count;
805 // A recursive definition refers to itself by the short name it is being given, so
806 // its own key resolves before the context holds it.
807 let pending = [name.to_string()];
808 let ty = match ty {
809 Some(t) => Some(self.resolve(&t, &pending, &mut Vec::new())?.into_owned()),
810 None => None,
811 };
812 let body = self.resolve(&body, &pending, &mut Vec::new())?.into_owned();
813 // ★ IN LOGOS THE PARAMETER NAMES ARE IN THE BODY. `A -> B -> C` is the only spelling of a
814 // non-dependent signature and it names nothing, so a default that mentions an earlier
815 // parameter (`(m : Int := mul n 2)`) can only be closed once the body's own λ-telescope has
816 // said which position `n` is. Without this the default is inlined as an OPEN TERM with a
817 // free `n` in it, which is a silent wrong answer rather than an error.
818 TermParser::name_anonymous_binders(&mut binders, &body);
819 // A default is SOURCE, written in the scope the declaration is written in, so it resolves
820 // like any other term — with the parameter names shielded, because a parameter reference is
821 // not a global and must not be resolved against the namespace scope.
822 if binders.iter().any(|b| b.default.is_some()) {
823 let param_names: Vec<String> = binders.iter().map(|b| b.name.clone()).collect();
824 for index in 0..binders.len() {
825 let Some(value) = binders[index].default.clone() else {
826 continue;
827 };
828 let mut locals = param_names.clone();
829 let resolved = self.resolve(&value, &pending, &mut locals)?.into_owned();
830 binders[index].default = Some(resolved);
831 }
832 }
833 // Auto-bind free type variables (`id : A -> A`) as leading implicits, then
834 // elaborate the body against its declared type — implicit arguments are
835 // filled from the body's own arguments AND from the expected type.
836 let (ty, body, implicit_count) = match ty {
837 Some(t) => {
838 let (t, b, k) = auto_bind_implicits(&self.ctx, &t, &body, implicit_count);
839 (Some(self.elaborate_type(&t)?), b, k)
840 }
841 None => (None, body, implicit_count),
842 };
843 // An auto-bound implicit is a binder the SOURCE never wrote, prepended to the telescope —
844 // so the recorded surface has to grow at the front by exactly as many, or every later
845 // position is off by that many and the alignment above is wrong again. They are anonymous
846 // on purpose: nothing may substitute for a binder whose argument the elaborator invents.
847 let invented = implicit_count.saturating_sub(declared_implicits);
848 if invented > 0 && !binders.is_empty() {
849 let mut telescope: Vec<BinderSurface> = (0..invented)
850 .map(|_| BinderSurface {
851 name: "_".to_string(),
852 kind: BinderKind::Implicit,
853 declared: Term::Hole,
854 default: None,
855 auto: None,
856 })
857 .collect();
858 telescope.append(&mut binders);
859 binders = telescope;
860 }
861 // Recursive-definition sugar: a body that calls the definition by name is
862 // bound with a `fix` (the kernel's termination guard certifies it).
863 let body = bind_self_recursion(name, &body);
864 let body = fill_match_motives(&self.ctx, &body, ty.as_ref())?;
865 let body = surface_elaborate_against(&self.ctx, &body, ty.as_ref())?;
866 let inferred_ty = infer_type(&self.ctx, &body)?;
867
868 // A DECLARED type is a CLAIM, and a claim must be checked. `infer_type` above only
869 // says the body is well-formed *somehow* — it says nothing about the type the user
870 // wrote. Taking the declared type on faith let the REPL stamp any term with any
871 // type:
872 //
873 // Definition oops : False := I. => Ok("") ; Check oops => "oops : False"
874 //
875 // i.e. a `False` inhabitant from the ordinary user surface, and from a proof of a
876 // false proposition everything follows. `surface_elaborate_against` elaborates the
877 // body against the declared type but returns `Ok` on a leaf it cannot reconcile, so
878 // it is not a substitute for this comparison.
879 let ty = match ty {
880 Some(declared) => {
881 if !crate::is_subtype(&self.ctx, &inferred_ty, &declared) {
882 return Err(InterfaceError::Kernel(crate::KernelError::TypeMismatch {
883 expected: declared.to_string(),
884 found: inferred_ty.to_string(),
885 }));
886 }
887 declared
888 }
889 None => inferred_ty,
890 };
891
892 Ok(Elaborated {
893 ty,
894 body,
895 binders,
896 implicit_count,
897 })
898 }
899
900 /// Elaborate a DECLARED TYPE, as Lean's `elabType` does before the body is looked at: match
901 /// motives are inferred, implicit arguments inserted, and a numeral is built at the carrier its
902 /// position asks for. `Theorem t : Eq Nat 2 2` states an equation between two `Nat`s; left
903 /// unelaborated its numerals are the `Int`s they are read as, the statement is not a
904 /// proposition about `Nat` at all, and no proof of it could check.
905 fn elaborate_type(&self, ty: &Term) -> Result<Term, InterfaceError> {
906 let ty = fill_match_motives(&self.ctx, ty, None)?;
907 Ok(surface_elaborate(&self.ctx, &ty)?)
908 }
909
910 /// Record how a declaration may be SPELLED at a call site — its namespace, its binder kinds,
911 /// its defaults and its leading-implicit count — once the kernel has accepted it.
912 fn record_declaration_surface(
913 &mut self,
914 name: &str,
915 binders: Vec<BinderSurface>,
916 implicit_count: usize,
917 ) {
918 // The namespaces this key's prefixes name now EXIST, so they can be opened.
919 self.surface.namespaces_mut().record_declaration(name);
920 // …and how this declaration may be SPELLED at a call site. A redeclaration replaces the
921 // entry and a redeclaration without defaults removes it, so a stale default can never fill
922 // an argument the current declaration does not offer.
923 if binders
924 .iter()
925 .any(|binder| binder.kind != BinderKind::Explicit)
926 {
927 self.ctx.set_binder_kinds(
928 name,
929 binders
930 .iter()
931 .map(|binder| binder.kind.as_param_kind())
932 .collect(),
933 );
934 }
935 self.surface.record_defaults(name, binders);
936
937 // Record how many leading arguments are implicit, so later uses of this
938 // global (`name 0`) get them inserted and inferred.
939 if implicit_count > 0 {
940 self.ctx.set_implicit_args(name, implicit_count);
941 }
942 }
943
944 /// Register a `Theorem` (`theorem` true) or an `Opaque` at the ABSOLUTE key `name`.
945 ///
946 /// The body is elaborated exactly as a `Definition`'s, then handed to the checked gateway the
947 /// Lean importer uses for the same kind — `Context::declare_theorem_checked` for a theorem,
948 /// `Context::declare_opaque_checked` for an `Opaque` — which checks the type and the body in
949 /// BOTH kernels, requires the body's type to be the declared type by conversion in both
950 /// directions (not the cumulative subtyping a `Definition` is allowed), refuses a hole or an
951 /// open term and records what the proof rests on. A theorem then unfolds as Lean's kernel
952 /// unfolds one; an `Opaque` keeps only its header.
953 fn declare_opaque(
954 &mut self,
955 name: String,
956 universes: Vec<String>,
957 ty: Term,
958 value: Term,
959 theorem: bool,
960 ) -> Result<String, InterfaceError> {
961 let leading = TermParser::binder_kinds_of(&ty)
962 .iter()
963 .take_while(|k| **k == BinderKind::Implicit)
964 .count();
965 let Elaborated {
966 ty,
967 body,
968 binders,
969 implicit_count,
970 } = self.elaborate_declaration(&name, Some(ty), value, leading)?;
971 if theorem {
972 // A theorem STATES A PROPOSITION. Lean refuses `theorem` at a type that is not a
973 // `Prop` and so does the importer; data that must stay sealed is `Opaque`.
974 let sort = crate::normalize(&self.ctx, &infer_type(&self.ctx, &ty)?);
975 let is_prop = matches!(&sort, Term::Sort(u) if u.equiv(&crate::Universe::Prop));
976 if !is_prop {
977 let (name, ty, sort) = (
978 self.ctx.written_name(&name),
979 self.written(&ty),
980 self.written(&sort),
981 );
982 return Err(InterfaceError::Kernel(
983 crate::KernelError::CertificationError(format!(
984 "`{name}` is stated as a theorem, but its statement `{ty}` lives in `{sort}`, \
985 not in `Prop` \u{2014} a theorem states a proposition. Seal data with \
986 `Opaque {name} : {ty} := \u{2026}.`"
987 )),
988 ));
989 }
990 }
991 // A document read a second time meets its own declarations: the one already registered
992 // here, identically, IS this declaration, and the append-only door is not asked again.
993 if self
994 .ctx
995 .holds_checked_declaration(&name, &universes, &ty, &body, theorem)
996 {
997 return Ok(String::new());
998 }
999 let published = if theorem {
1000 self.ctx.declare_theorem_checked(&name, universes, ty, body)
1001 } else {
1002 self.ctx.declare_opaque_checked(&name, universes, ty, body)
1003 };
1004 published.map_err(InterfaceError::Kernel)?;
1005 self.record_declaration_surface(&name, binders, implicit_count);
1006 Ok(String::new())
1007 }
1008
1009 /// Prove `ty` by `script` over the kernel's own goals, then publish the finished proof term as
1010 /// a [`Command::Theorem`]'s proof is published. Each step's terms are resolved in the scope the
1011 /// statement is, with the focused goal's hypotheses bound, so `exact h` names the hypothesis
1012 /// and `exact Nat.zero_le` the global.
1013 fn prove_by_script(
1014 &mut self,
1015 name: String,
1016 universes: Vec<String>,
1017 ty: Term,
1018 script: &[crate::tactics::TacticStep],
1019 ) -> Result<String, InterfaceError> {
1020 use crate::tactics::{GoalState, ScriptError, TacticStep};
1021 let declared = TermParser::declaration_surface(&ty);
1022 let statement = self
1023 .resolve(&declared.kernel_type, &[], &mut Vec::new())?
1024 .into_owned();
1025 let statement = self.elaborate_type(&statement)?;
1026 let mut state = GoalState::new(&self.ctx, &statement).map_err(|error| ScriptError {
1027 step: 0,
1028 tactic: None,
1029 error,
1030 })?;
1031 for (i, step) in script.iter().enumerate() {
1032 let mut hyps: Vec<String> = state
1033 .goals()
1034 .first()
1035 .map(|g| g.hyps.iter().map(|(n, _)| n.clone()).collect())
1036 .unwrap_or_default();
1037 let mut resolve = |t: &Term| -> Result<Term, InterfaceError> {
1038 Ok(self.resolve(t, &[], &mut hyps)?.into_owned())
1039 };
1040 let step = match step {
1041 TacticStep::Exact(t) => TacticStep::Exact(resolve(t)?),
1042 TacticStep::Apply(t) => TacticStep::Apply(resolve(t)?),
1043 TacticStep::Exists(t) => TacticStep::Exists(resolve(t)?),
1044 TacticStep::Change(t) => TacticStep::Change(resolve(t)?),
1045 TacticStep::Have(n, t) => TacticStep::Have(n.clone(), resolve(t)?),
1046 TacticStep::Rewrite(t, reverse) => TacticStep::Rewrite(resolve(t)?, *reverse),
1047 other => other.clone(),
1048 };
1049 state.step(&step).map_err(|error| ScriptError {
1050 step: i,
1051 tactic: Some(step.clone()),
1052 error,
1053 })?;
1054 }
1055 let proof = state.qed().map_err(|error| ScriptError {
1056 step: script.len(),
1057 tactic: None,
1058 error,
1059 })?;
1060 self.declare_opaque(name, universes, ty, proof, true)
1061 }
1062
1063 /// Register an `Axiom` at the ABSOLUTE key `name`, through `Context::add_universe_poly_declaration`
1064 /// — the importer's axiom door: the type must be a type, every level variable must be in the
1065 /// telescope, and no existing declaration may be replaced. It has no body, so `Print Axioms`
1066 /// reports it on itself and on everything that rests on it.
1067 fn declare_axiom(
1068 &mut self,
1069 name: String,
1070 universes: Vec<String>,
1071 ty: Term,
1072 ) -> Result<String, InterfaceError> {
1073 let declared = TermParser::declaration_surface(&ty);
1074 let ty = self
1075 .resolve(&declared.kernel_type, &[], &mut Vec::new())?
1076 .into_owned();
1077 let ty = self.elaborate_type(&ty)?;
1078 if self.ctx.holds_assumption(&name, &universes, &ty) {
1079 return Ok(String::new());
1080 }
1081 self.ctx
1082 .add_universe_poly_declaration(&name, universes, ty)
1083 .map_err(InterfaceError::Kernel)?;
1084 let implicit_count = declared.leading_implicits();
1085 self.record_declaration_surface(&name, declared.binders, implicit_count);
1086 Ok(String::new())
1087 }
1088
1089 /// Register one `Inductive` at the ABSOLUTE key `name`, with the namespace scope its
1090 /// constructors are declared in already entered by the caller.
1091 ///
1092 /// Constructors are declared in the namespace the COMMAND is written in — `Namespace N.
1093 /// Inductive Foo := Mk.` gives `N.Foo` and `N.Mk`. Lean puts a constructor inside the
1094 /// inductive's own namespace (`Nat.succ`), which is a nicer spelling and a different
1095 /// convention; ours is the one that is byte-identical to today's flat registration whenever no
1096 /// namespace is open, and that continuity is worth more than the spelling.
1097 fn register_inductive(
1098 &mut self,
1099 name: String,
1100 params: Vec<(String, Term)>,
1101 sort: Term,
1102 constructors: Vec<(String, Term)>,
1103 ) -> Result<String, InterfaceError> {
1104 // The inductive's own key and every constructor key resolve before the context
1105 // holds any of them: a constructor type names the type it builds.
1106 let ctor_keys: Vec<String> = constructors
1107 .iter()
1108 .map(|(cn, _)| self.declaration_key(cn))
1109 .collect();
1110 let mut pending = vec![name.clone()];
1111 pending.extend(ctor_keys.iter().cloned());
1112 // Type parameters arrive as `Global`s and become `Var`s only at registration, so
1113 // they are shielded from resolution by hand.
1114 let mut locals: Vec<String> = params.iter().map(|(p, _)| p.clone()).collect();
1115 let params: Vec<(String, Term)> = params
1116 .iter()
1117 .map(|(p, t)| {
1118 self.resolve(t, &pending, &mut locals)
1119 .map(|r| (p.clone(), r.into_owned()))
1120 })
1121 .collect::<Result<_, _>>()?;
1122 let constructors: Vec<(String, Term)> = ctor_keys
1123 .iter()
1124 .zip(constructors.iter())
1125 .map(|(key, (_, cty))| {
1126 self.resolve(cty, &pending, &mut locals)
1127 .map(|r| (key.clone(), r.into_owned()))
1128 })
1129 .collect::<Result<_, _>>()?;
1130
1131 // Build polymorphic sort: Π(p1:T1). Π(p2:T2). ... Type
1132 let poly_sort = build_polymorphic_sort(¶ms, sort);
1133
1134 // Register the inductive type with its polymorphic sort
1135 self.ctx.declare_inductive(&name, poly_sort)?;
1136 self.surface.namespaces_mut().record_declaration(&name);
1137
1138 // Register constructors with prepended parameters
1139 for (ctor_name, ctor_ty) in constructors {
1140 // Prepend params to constructor type:
1141 // If ctor_ty = A -> List A -> List A
1142 // And params = [(A, Type)]
1143 // Result = Π(A:Type). A -> List A -> List A
1144 let poly_ctor_ty = build_polymorphic_constructor(¶ms, ctor_ty);
1145 // Strict positivity is enforced on the trusted, user-facing
1146 // registration path: a negative-recursive constructor (e.g.
1147 // `Cons : (Bad -> False) -> Bad`) would let one inhabit `False`.
1148 self.ctx
1149 .add_constructor_checked(&ctor_name, &name, poly_ctor_ty)?;
1150 self.surface.namespaces_mut().record_declaration(&ctor_name);
1151 }
1152
1153 // ★ NOTHING IS DERIVED HERE, AND THAT IS THE FIX. `add_constructor_checked` — the door
1154 // every constructor above went through — synthesises the whole declaration-time family
1155 // (`{I}_rec`, `{I}_noConfusionType`, `{I}_noConfusion`, `{C}_inj`, `{I}_below`,
1156 // `{I}_brecOn`, `decEq{I}`), each one kernel-checked and provenance-keyed so a
1157 // re-derivation replaces its own prior generation and never a hand-written constant. This
1158 // used to re-derive `{I}_rec` by hand afterwards and register it with `add_definition`,
1159 // which paid for a second derivation of a constant that already existed AND disowned the
1160 // generated one — after which `{I}_below` and `{I}_brecOn` were the only members of the
1161 // family the user-facing door did not hand back.
1162 Ok(String::new()) // Silent success
1163 }
1164
1165 /// Register one genuine mutual cycle of a run: resolve the whole block at once, register it
1166 /// through the trusted mutual door, record its names, and derive every member's family. The
1167 /// mutual door registers through `add_constructor`, the BULK door, which queues synthesis
1168 /// rather than paying for it per constructor — so unlike the single path (where
1169 /// `add_constructor_checked` has already done it) the block has to ask. Asking per member rather
1170 /// than `seal()`ing is deliberate: a seal would also synthesise everything the PRELUDE queued,
1171 /// which is a second of work for tables this declaration did not ask for.
1172 fn register_mutual_component(
1173 &mut self,
1174 run: &[(&str, &Command)],
1175 comp: &[usize],
1176 ) -> Result<(), InterfaceError> {
1177 // Namespace resolution has to see the WHOLE block at once: every member's key and every
1178 // constructor's key is pending together, because a mutual block's whole point is that its
1179 // constructors name each other's types before any of them exists.
1180 let block = self.resolve_mutual_block(run, comp)?;
1181 self.ctx
1182 .add_mutual_inductives(&block)
1183 .map_err(InterfaceError::Kernel)?;
1184 for member in &block {
1185 self.surface
1186 .namespaces_mut()
1187 .record_declaration(&member.name);
1188 for (cn, _) in &member.constructors {
1189 self.surface.namespaces_mut().record_declaration(cn);
1190 }
1191 }
1192 for member in &block {
1193 for aux in crate::recursor::derive_auxiliaries(&self.ctx, &member.name) {
1194 self.ctx.add_definition(aux.name, aux.ty, aux.term);
1195 }
1196 }
1197 Ok(())
1198 }
1199
1200 /// Namespace-resolve one mutual-inductive component into the block the trusted machinery takes.
1201 ///
1202 /// Two passes, because a mutual block is exactly the case where nothing is in the context yet:
1203 /// first every member's absolute key and every constructor's absolute key, then each member's
1204 /// parameter and constructor types resolved with ALL of those keys pending. Each member is
1205 /// resolved inside the scope its own declaration name spells, exactly as the single path does,
1206 /// and the scope is wound back whether it succeeds or fails.
1207 fn resolve_mutual_block(
1208 &mut self,
1209 run: &[(&str, &Command)],
1210 comp: &[usize],
1211 ) -> Result<Vec<crate::context::MutualInductive>, InterfaceError> {
1212 let members: Vec<(&String, &Vec<(String, Term)>, &Term, &Vec<(String, Term)>)> = comp
1213 .iter()
1214 .map(|&node| match run[node].1 {
1215 Command::Inductive {
1216 name,
1217 params,
1218 sort,
1219 constructors,
1220 } => (name, params, sort, constructors),
1221 _ => unreachable!("a component holds only Inductive commands"),
1222 })
1223 .collect();
1224
1225 let mut keys: Vec<(String, Vec<String>)> = Vec::with_capacity(members.len());
1226 for (name, _, _, constructors) in &members {
1227 let (key, mark) = self.enter_declaration(name);
1228 let ctors: Vec<String> = constructors
1229 .iter()
1230 .map(|(cn, _)| self.declaration_key(cn))
1231 .collect();
1232 self.surface.namespaces_mut().rewind(mark);
1233 keys.push((key, ctors));
1234 }
1235 let mut pending: Vec<String> = Vec::new();
1236 for (key, ctors) in &keys {
1237 pending.push(key.clone());
1238 pending.extend(ctors.iter().cloned());
1239 }
1240
1241 let mut block = Vec::with_capacity(members.len());
1242 for ((name, params, sort, constructors), (key, ctor_keys)) in members.iter().zip(&keys) {
1243 let (_, mark) = self.enter_declaration(name);
1244 let resolved = (|| -> Result<crate::context::MutualInductive, InterfaceError> {
1245 let mut locals: Vec<String> = params.iter().map(|(p, _)| p.clone()).collect();
1246 let params: Vec<(String, Term)> = params
1247 .iter()
1248 .map(|(p, t)| {
1249 self.resolve(t, &pending, &mut locals)
1250 .map(|r| (p.clone(), r.into_owned()))
1251 })
1252 .collect::<Result<_, _>>()?;
1253 let ctors: Vec<(String, Term)> = ctor_keys
1254 .iter()
1255 .zip(constructors.iter())
1256 .map(|(ck, (_, cty))| {
1257 self.resolve(cty, &pending, &mut locals).map(|r| {
1258 (
1259 ck.clone(),
1260 build_polymorphic_constructor(¶ms, r.into_owned()),
1261 )
1262 })
1263 })
1264 .collect::<Result<_, _>>()?;
1265 Ok(crate::context::MutualInductive {
1266 name: key.clone(),
1267 sort: build_polymorphic_sort(¶ms, (*sort).clone()),
1268 num_params: params.len(),
1269 constructors: ctors,
1270 })
1271 })();
1272 self.surface.namespaces_mut().rewind(mark);
1273 block.push(resolved?);
1274 }
1275 Ok(block)
1276 }
1277
1278 /// The absolute key a name written HERE declares — the current namespace, then the name. A name
1279 /// no term can spell keeps its flat key, for the reason [`enter_declaration`](Self::enter_declaration)
1280 /// gives.
1281 fn declaration_key(&self, written: &str) -> String {
1282 let key = self.written_key(written);
1283 self.ctx.shadow_of(&key).unwrap_or(key)
1284 }
1285
1286 /// Execute a batch of Vernacular commands, recovering mutual-inductive grouping.
1287 ///
1288 /// [`execute`](Self::execute) registers each `Inductive` independently, so a forward
1289 /// reference between two separately-declared inductives — `Tree` whose `Node`
1290 /// constructor mentions `Forest`, declared next — fails: `Forest` is not yet in scope
1291 /// when `Tree`'s constructor is universe-checked. True mutual inductives must be
1292 /// registered together, through the trusted [`Context::add_mutual_inductives`], which
1293 /// runs whole-block positivity and a header-first universe check.
1294 ///
1295 /// This entry point recovers that grouping from a flat statement sequence: a maximal
1296 /// run of consecutive `Inductive` commands is split into strongly-connected components
1297 /// of the "a constructor mentions sibling `b`" graph. A genuine cycle (`Tree`↔`Forest`)
1298 /// is registered as one mutual block; an acyclic reference (`Leafy` → `Bare`) becomes
1299 /// two singletons registered dependency-first (`Bare`, then `Leafy`) through the
1300 /// ordinary single-inductive path. Every non-inductive command — and every inductive
1301 /// with no forward reference — runs exactly as `execute` would, in source order, so a
1302 /// batch without forward references is byte-identical to running the statements singly.
1303 pub fn execute_batch(&mut self, inputs: &[String]) -> Vec<Result<String, InterfaceError>> {
1304 self.run_batch(inputs, false)
1305 }
1306
1307 /// Execute a whole DOCUMENT: every command in it, in order, stopping at the first failure.
1308 ///
1309 /// [`execute`](Self::execute) is a single-command door and refuses a prefix, which is what
1310 /// stops a second `## Theorem` block from being discarded in silence. This is the other half:
1311 /// the door that actually reads a document. It is fail-loud and fail-EARLY — a block that does
1312 /// not check aborts the run, so nothing after a refused theorem is registered and the caller
1313 /// gets the error rather than a success that covered a smaller set of blocks than it was
1314 /// handed. Mutual-inductive grouping is the same as [`Self::execute_batch`]'s.
1315 ///
1316 /// It is also BALANCED: a document must leave the scope stack exactly as it found it. A
1317 /// `Namespace N.` with no `End N.` would write every LATER command into `N` with nothing said,
1318 /// and a document that closes a scope the caller opened moves the caller's later declarations
1319 /// somewhere nobody wrote. Lean does NOT refuse one — measured on lean 4.14.0, a file that ends inside `namespace N` compiles without a word, because a Lean MODULE's scopes close at its end and the next file starts clean. A document here is not a module: it is handed to a live session that goes on executing commands after it, so an unclosed `Namespace N.` keys every later one into `N` and says nothing. The balance rule is therefore ours and deliberate, and the reason is the session rather than Lean.
1320 /// A refused document has its namespace scope wound back to where the caller handed it over.
1321 pub fn execute_document(&mut self, input: &str) -> Result<Vec<String>, InterfaceError> {
1322 let entry_scope = self.surface.namespaces().mark();
1323 let entry_namespaces = self.surface.namespaces().depth();
1324 let entry_sections = self.surface.section_depth();
1325
1326 let mut outcome = self.read_document(input);
1327
1328 // \u{2605} A DOCUMENT IS BALANCED. `Namespace N.` with no `End N.` is the quietest failure this
1329 // surface has: every later declaration lands in `N`, nothing is reported, and the file
1330 // still checks. Lean itself does NOT refuse one (measured: a file ending inside
1331 // `namespace N` compiles) — a MODULE's scopes close at its end, and a document handed to a
1332 // live session has no such end. Balance, rather than "empty
1333 // at the end", is the right statement of it \u{2014} a caller already inside a namespace when it
1334 // hands the door a document is not doing anything wrong, and a document that unwinds PAST
1335 // the scope it was handed is the same mistake pointing the other way.
1336 if outcome.is_ok() {
1337 let frames = self.surface.namespaces().frame_names();
1338 let sections = self.surface.section_names();
1339 let unclosed: Vec<String> = frames
1340 .iter()
1341 .skip(entry_namespaces)
1342 .chain(sections.iter().skip(entry_sections))
1343 .cloned()
1344 .collect();
1345 let overclosed = entry_namespaces.saturating_sub(frames.len())
1346 + entry_sections.saturating_sub(sections.len());
1347 if !unclosed.is_empty() || overclosed > 0 {
1348 outcome = Err(ParseError::UnbalancedDocument {
1349 unclosed,
1350 overclosed,
1351 }
1352 .into());
1353 }
1354 }
1355
1356 // A refused document must not leave its scope behind, for the same reason a refused
1357 // `Open \u{2026} in <command>` must not: the NEXT command would read its names in a scope nobody
1358 // wrote. The namespace scope is restored exactly; a section the document closed took its
1359 // notations with it and is reported above rather than pretended back into existence.
1360 if outcome.is_err() {
1361 self.surface.namespaces_mut().rewind(entry_scope);
1362 self.surface.close_sections_to(entry_sections);
1363 // The KERNEL scope is wound back with it. A refused document that left one open would
1364 // have the next document's `local` registrations owned by a depth nobody wrote, and
1365 // nothing would ever revert them.
1366 self.match_kernel_scopes();
1367 }
1368 outcome
1369 }
1370
1371 /// [`execute_document`](Self::execute_document) without the balance rule: split the document
1372 /// and run every block, fail-early.
1373 fn read_document(&mut self, input: &str) -> Result<Vec<String>, InterfaceError> {
1374 let blocks = split_document(&self.surface, input)?;
1375 let mut out = Vec::with_capacity(blocks.len());
1376 for result in self.run_batch(&blocks, true) {
1377 out.push(result?);
1378 }
1379 Ok(out)
1380 }
1381
1382 /// The shared engine of [`execute_batch`] and [`execute_document`]: run each input in source
1383 /// order, grouping maximal runs of `Inductive` commands so mutual cycles register together.
1384 /// `stop_on_error` decides whether a failure aborts the rest (a document) or is recorded and
1385 /// the run continues (a batch).
1386 fn run_batch(
1387 &mut self,
1388 inputs: &[String],
1389 stop_on_error: bool,
1390 ) -> Vec<Result<String, InterfaceError>> {
1391 let parsed: Vec<Option<Command>> = inputs
1392 .iter()
1393 .map(|s| parse_command_in_ctx(&self.ctx, &self.surface, s).ok())
1394 .collect();
1395 let mut out: Vec<Option<Result<String, InterfaceError>>> =
1396 (0..inputs.len()).map(|_| None).collect();
1397 let mut i = 0;
1398 while i < inputs.len() {
1399 if !matches!(parsed[i], Some(Command::Inductive { .. })) {
1400 let r = self.execute(&inputs[i]);
1401 let failed = r.is_err();
1402 out[i] = Some(r);
1403 i += 1;
1404 if failed && stop_on_error {
1405 break;
1406 }
1407 continue;
1408 }
1409 // A maximal run of consecutive inductive commands, registered as a group.
1410 let start = i;
1411 while i < inputs.len() && matches!(parsed[i], Some(Command::Inductive { .. })) {
1412 i += 1;
1413 }
1414 let run: Vec<(&str, &Command)> = (start..i)
1415 .map(|k| (inputs[k].as_str(), parsed[k].as_ref().unwrap()))
1416 .collect();
1417 let mut failed = false;
1418 for (k, r) in (start..i).zip(self.register_inductive_run(&run)) {
1419 failed |= r.is_err();
1420 out[k] = Some(r);
1421 }
1422 if failed && stop_on_error {
1423 break;
1424 }
1425 }
1426 // A document that stopped early leaves the untouched tail unreported: it was never run,
1427 // and calling it `Ok("")` would be a success nobody earned.
1428 out.into_iter().flatten().collect()
1429 }
1430
1431 /// Register one maximal run of `Inductive` commands, grouping mutual cycles into
1432 /// blocks and registering acyclic references dependency-first. See [`execute_batch`].
1433 fn register_inductive_run(
1434 &mut self,
1435 run: &[(&str, &Command)],
1436 ) -> Vec<Result<String, InterfaceError>> {
1437 use std::collections::{BTreeSet, HashMap};
1438 let n = run.len();
1439 let names: Vec<&str> = run
1440 .iter()
1441 .map(|(_, c)| match c {
1442 Command::Inductive { name, .. } => name.as_str(),
1443 _ => unreachable!("run holds only Inductive commands"),
1444 })
1445 .collect();
1446 let name_idx: HashMap<&str, usize> =
1447 names.iter().enumerate().map(|(k, &nm)| (nm, k)).collect();
1448
1449 // Dependency edges: `a → b` iff a constructor of member `a` mentions sibling `b`
1450 // (b ≠ a; a self-reference is handled inside single/mutual registration).
1451 let mut deps: Vec<BTreeSet<usize>> = (0..n).map(|_| BTreeSet::new()).collect();
1452 for (a, (_, cmd)) in run.iter().enumerate() {
1453 if let Command::Inductive { constructors, .. } = cmd {
1454 let mut mentioned = BTreeSet::new();
1455 for (_, cty) in constructors.iter() {
1456 collect_global_names(cty, &mut mentioned);
1457 }
1458 for name in &mentioned {
1459 if let Some(&b) = name_idx.get(name.as_str()) {
1460 if b != a {
1461 deps[a].insert(b);
1462 }
1463 }
1464 }
1465 }
1466 }
1467
1468 let comps = tarjan_scc(&deps);
1469 let mut comp_of = vec![0usize; n];
1470 for (cid, comp) in comps.iter().enumerate() {
1471 for &node in comp {
1472 comp_of[node] = cid;
1473 }
1474 }
1475 // Condensation edges: which components each component references.
1476 let mut comp_deps: Vec<BTreeSet<usize>> =
1477 (0..comps.len()).map(|_| BTreeSet::new()).collect();
1478 for (a, edges) in deps.iter().enumerate() {
1479 for &b in edges {
1480 if comp_of[a] != comp_of[b] {
1481 comp_deps[comp_of[a]].insert(comp_of[b]);
1482 }
1483 }
1484 }
1485 // Emit components dependency-first (a referenced component before its referrer),
1486 // tie-breaking by earliest source position so independent inductives keep order.
1487 let mut emitted = vec![false; comps.len()];
1488 let mut order: Vec<usize> = Vec::with_capacity(comps.len());
1489 while order.len() < comps.len() {
1490 let mut pick: Option<usize> = None;
1491 for c in 0..comps.len() {
1492 if emitted[c] || !comp_deps[c].iter().all(|d| emitted[*d]) {
1493 continue;
1494 }
1495 let earliest = *comps[c].iter().min().unwrap();
1496 match pick {
1497 Some(p) if earliest >= *comps[p].iter().min().unwrap() => {}
1498 _ => pick = Some(c),
1499 }
1500 }
1501 let c = pick.expect("an SCC condensation is a DAG — a ready component exists");
1502 emitted[c] = true;
1503 order.push(c);
1504 }
1505
1506 let mut results: Vec<Result<String, InterfaceError>> =
1507 (0..n).map(|_| Ok(String::new())).collect();
1508 for &cid in &order {
1509 let comp = &comps[cid];
1510 if comp.len() == 1 {
1511 // Singleton (including a self-recursive inductive): the ordinary path, which
1512 // also derives the recursor. Its dependencies are already registered.
1513 let node = comp[0];
1514 results[node] = self.execute(run[node].0);
1515 } else {
1516 // A genuine mutual cycle → one block through the trusted mutual machinery.
1517 let mut declared = Vec::new();
1518 for &node in comp {
1519 declared.extend(self.declared_keys(run[node].1));
1520 }
1521 let outcome = if self.redeclares(&declared) {
1522 self.shadowing(&declared, |repl| repl.register_mutual_component(run, comp))
1523 } else {
1524 self.register_mutual_component(run, comp)
1525 };
1526 let outcome = outcome.map_err(|e| match e {
1527 InterfaceError::Kernel(e) => {
1528 format!("mutual inductive block failed to register: {e}")
1529 }
1530 e => format!("mutual inductive block failed to register: {e}"),
1531 });
1532 if let Err(msg) = outcome {
1533 for &node in comp {
1534 results[node] = Err(InterfaceError::Kernel(
1535 crate::KernelError::CertificationError(msg.clone()),
1536 ));
1537 }
1538 }
1539 }
1540 }
1541 results
1542 }
1543
1544 /// The names this session shadows, as `(written name, kernel identity)` pairs: a written name
1545 /// in this table denotes the session's own declaration at that identity, and the environment's
1546 /// declaration under the same name keeps its meaning.
1547 pub fn shadows(&self) -> Vec<(String, String)> {
1548 self.ctx.shadows().to_vec()
1549 }
1550
1551 /// How many commands this session has run under the shadowing snapshot — exactly the commands
1552 /// that redeclared a name the environment already held. The snapshot is what makes the retry
1553 /// possible and is not free: while it lives, a command's first write to each table it touches
1554 /// copies the whole table. A command declaring only fresh names never takes one, and this count
1555 /// is how that is held.
1556 pub fn shadow_snapshots(&self) -> usize {
1557 self.snapshots
1558 }
1559
1560 /// `term` with every constant named as it is WRITTEN in this session
1561 /// ([`Context::written_name`]) — what `Check` and `Eval` print, so a shadowing declaration
1562 /// prints as the name its author wrote and never as its kernel identity.
1563 fn written<'t>(&self, term: &'t Term) -> Cow<'t, Term> {
1564 if self.ctx.shadows().is_empty() {
1565 return Cow::Borrowed(term);
1566 }
1567 Cow::Owned(rename_constants(term, &|key| self.ctx.written_name(key)))
1568 }
1569
1570 /// Get a reference to the surface environment — the notation and macros in scope.
1571 pub fn surface(&self) -> &Surface {
1572 &self.surface
1573 }
1574
1575 /// Get a reference to the underlying context.
1576 pub fn context(&self) -> &Context {
1577 &self.ctx
1578 }
1579
1580 /// Get a mutable reference to the underlying context.
1581 pub fn context_mut(&mut self) -> &mut Context {
1582 &mut self.ctx
1583 }
1584}
1585
1586impl Default for Repl {
1587 fn default() -> Self {
1588 Self::new()
1589 }
1590}
1591
1592/// Split a document into its commands, in source order.
1593///
1594/// Each block is the exact source text its command occupies (`super::measure_command_prefix`),
1595/// so a literate theorem keeps its indented `Statement:`/`Proof:` lines and a Coq-style sentence
1596/// keeps its terminating period. A block is MEASURED here, from its syntax, and read for its
1597/// meaning only when it runs — against the context every block before it built. A syntax error
1598/// anywhere aborts the split: a document is read whole or not at all.
1599fn split_document(surface: &Surface, input: &str) -> Result<Vec<String>, ParseError> {
1600 let mut blocks = Vec::new();
1601 let mut offset = 0;
1602 while !input[offset..].trim().is_empty() {
1603 let consumed = super::measure_command_prefix(surface, &input[offset..])?;
1604 if consumed == 0 {
1605 return Err(ParseError::Missing(
1606 "a command — the document parser made no progress".to_string(),
1607 ));
1608 }
1609 let text = input[offset..offset + consumed].trim();
1610 if !text.is_empty() {
1611 blocks.push(text.to_string());
1612 }
1613 offset += consumed;
1614 }
1615 Ok(blocks)
1616}
1617
1618/// Build a polymorphic sort from type parameters.
1619///
1620/// For params = [(A, Type), (B, Type)] and base_sort = Type,
1621/// produces: Π(A:Type). Π(B:Type). Type
1622fn build_polymorphic_sort(params: &[(String, Term)], base_sort: Term) -> Term {
1623 // Fold right to build nested Pi types
1624 params
1625 .iter()
1626 .rev()
1627 .fold(base_sort, |body, (name, ty)| Term::Pi {
1628 param: name.clone(),
1629 param_type: Box::new(ty.clone()),
1630 body_type: Box::new(body),
1631 })
1632}
1633
1634/// Build a polymorphic constructor type by prepending parameters.
1635///
1636/// For params = [(A, Type)] and ctor_ty = A -> List A -> List A,
1637/// produces: Π(A:Type). A -> List A -> List A
1638///
1639/// The kernel uses named variables (Var(String)), so we convert
1640/// Global("A") to Var("A") for parameters.
1641fn build_polymorphic_constructor(params: &[(String, Term)], ctor_ty: Term) -> Term {
1642 if params.is_empty() {
1643 return ctor_ty;
1644 }
1645
1646 // Convert Global(param_name) to Var(param_name) for all parameters
1647 let param_names: Vec<&str> = params.iter().map(|(n, _)| n.as_str()).collect();
1648 let body = substitute_globals_with_vars(&ctor_ty, ¶m_names);
1649
1650 // Wrap with Pi bindings (fold right to build nested Pi)
1651 params.iter().rev().fold(body, |body, (name, ty)| Term::Pi {
1652 param: name.clone(),
1653 param_type: Box::new(ty.clone()),
1654 body_type: Box::new(body),
1655 })
1656}
1657
1658/// `Π(p₀ : T₀). … Π(pₙ : Tₙ). body` over a block member's written parameters, each parameter's
1659/// references turned from the `Global` the text-only parser read into the `Var` its binder binds —
1660/// in the LATER parameters' types as well as in `body`, so a dependent telescope
1661/// (`(A : Type) (x : A)`) binds what it says. A parameter shadows a global of the same spelling,
1662/// exactly as a binder does.
1663fn parameter_telescope(params: &[(String, Term)], body: Term) -> Term {
1664 let names: Vec<&str> = params.iter().map(|(n, _)| n.as_str()).collect();
1665 let body = substitute_globals_with_vars(&body, &names);
1666 params
1667 .iter()
1668 .enumerate()
1669 .rev()
1670 .fold(body, |body, (i, (name, ty))| Term::Pi {
1671 param: name.clone(),
1672 param_type: Box::new(substitute_globals_with_vars(ty, &names[..i])),
1673 body_type: Box::new(body),
1674 })
1675}
1676
1677/// The keys a declaring command WRITES — what a `Protected` in front of it protects.
1678fn declared_names(cmd: &Command) -> Vec<String> {
1679 match cmd {
1680 Command::Definition { name, .. }
1681 | Command::Inductive { name, .. }
1682 | Command::Theorem { name, .. }
1683 | Command::TheoremBy { name, .. }
1684 | Command::Opaque { name, .. }
1685 | Command::Axiom { name, .. } => vec![name.clone()],
1686 Command::InductiveBlock { members } => members.iter().map(|m| m.name.clone()).collect(),
1687 Command::Universes { inner, .. }
1688 | Command::Protected(inner)
1689 | Command::OpenIn { inner, .. } => declared_names(inner),
1690 _ => Vec::new(),
1691 }
1692}
1693
1694/// `term` with every constant — a `Global` or a `Const` — renamed by `name`; binders, literals and
1695/// every other node are kept as they are.
1696fn rename_constants(term: &Term, name: &dyn Fn(&str) -> String) -> Term {
1697 let go = |t: &Term| Box::new(rename_constants(t, name));
1698 match term {
1699 Term::Global(n) => Term::Global(name(n)),
1700 Term::Const { name: n, levels } => Term::Const {
1701 name: name(n),
1702 levels: levels.clone(),
1703 },
1704 Term::Var(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => term.clone(),
1705 Term::App(f, a) => Term::App(go(f), go(a)),
1706 Term::Lambda {
1707 param,
1708 param_type,
1709 body,
1710 } => Term::Lambda {
1711 param: param.clone(),
1712 param_type: go(param_type),
1713 body: go(body),
1714 },
1715 Term::Pi {
1716 param,
1717 param_type,
1718 body_type,
1719 } => Term::Pi {
1720 param: param.clone(),
1721 param_type: go(param_type),
1722 body_type: go(body_type),
1723 },
1724 Term::Fix { name: n, body } => Term::Fix {
1725 name: n.clone(),
1726 body: go(body),
1727 },
1728 Term::MutualFix { defs, index } => Term::MutualFix {
1729 defs: defs
1730 .iter()
1731 .map(|(n, b)| (n.clone(), rename_constants(b, name)))
1732 .collect(),
1733 index: *index,
1734 },
1735 Term::Match {
1736 discriminant,
1737 motive,
1738 cases,
1739 } => Term::Match {
1740 discriminant: go(discriminant),
1741 motive: go(motive),
1742 cases: cases.iter().map(|c| rename_constants(c, name)).collect(),
1743 },
1744 Term::Let {
1745 name: n,
1746 ty,
1747 value,
1748 body,
1749 } => Term::Let {
1750 name: n.clone(),
1751 ty: go(ty),
1752 value: go(value),
1753 body: go(body),
1754 },
1755 Term::Annotated { annotation, term } => Term::Annotated {
1756 annotation: annotation.clone(),
1757 term: go(term),
1758 },
1759 }
1760}
1761
1762/// Convert Global(name) to Var(name) for names in the param list.
1763/// This makes parameter references in constructor types into bound variables.
1764fn substitute_globals_with_vars(term: &Term, param_names: &[&str]) -> Term {
1765 match term {
1766 Term::Global(n) if param_names.contains(&n.as_str()) => Term::Var(n.clone()),
1767 Term::Global(n) => Term::Global(n.clone()),
1768 Term::Const { .. } => term.clone(),
1769 Term::Var(n) => Term::Var(n.clone()),
1770 Term::Sort(u) => Term::Sort(u.clone()),
1771 Term::Lit(l) => Term::Lit(l.clone()),
1772 Term::App(f, a) => Term::App(
1773 Box::new(substitute_globals_with_vars(f, param_names)),
1774 Box::new(substitute_globals_with_vars(a, param_names)),
1775 ),
1776 Term::Lambda {
1777 param,
1778 param_type,
1779 body,
1780 } => Term::Lambda {
1781 param: param.clone(),
1782 param_type: Box::new(substitute_globals_with_vars(param_type, param_names)),
1783 body: Box::new(substitute_globals_with_vars(body, param_names)),
1784 },
1785 Term::Pi {
1786 param,
1787 param_type,
1788 body_type,
1789 } => Term::Pi {
1790 param: param.clone(),
1791 param_type: Box::new(substitute_globals_with_vars(param_type, param_names)),
1792 body_type: Box::new(substitute_globals_with_vars(body_type, param_names)),
1793 },
1794 Term::Fix { name, body } => Term::Fix {
1795 name: name.clone(),
1796 body: Box::new(substitute_globals_with_vars(body, param_names)),
1797 },
1798 Term::MutualFix { defs, index } => Term::MutualFix {
1799 defs: defs
1800 .iter()
1801 .map(|(n, b)| (n.clone(), substitute_globals_with_vars(b, param_names)))
1802 .collect(),
1803 index: *index,
1804 },
1805 Term::Match {
1806 discriminant,
1807 motive,
1808 cases,
1809 } => Term::Match {
1810 discriminant: Box::new(substitute_globals_with_vars(discriminant, param_names)),
1811 motive: Box::new(substitute_globals_with_vars(motive, param_names)),
1812 cases: cases
1813 .iter()
1814 .map(|c| substitute_globals_with_vars(c, param_names))
1815 .collect(),
1816 },
1817 Term::Let {
1818 name,
1819 ty,
1820 value,
1821 body,
1822 } => Term::Let {
1823 name: name.clone(),
1824 ty: Box::new(substitute_globals_with_vars(ty, param_names)),
1825 value: Box::new(substitute_globals_with_vars(value, param_names)),
1826 body: Box::new(substitute_globals_with_vars(body, param_names)),
1827 },
1828 Term::Hole => Term::Hole, // Holes are unchanged
1829 Term::Annotated { annotation, term } => Term::Annotated {
1830 annotation: annotation.clone(),
1831 term: Box::new(substitute_globals_with_vars(term, param_names)),
1832 },
1833 }
1834}
1835
1836/// Collect the names of every `Global`/`Const` referenced anywhere in a term — used to
1837/// find which sibling inductives a constructor mentions.
1838fn collect_global_names(term: &Term, out: &mut std::collections::BTreeSet<String>) {
1839 match term {
1840 Term::Global(n) => {
1841 out.insert(n.clone());
1842 }
1843 Term::Const { name, .. } => {
1844 out.insert(name.clone());
1845 }
1846 Term::App(f, a) => {
1847 collect_global_names(f, out);
1848 collect_global_names(a, out);
1849 }
1850 Term::Pi {
1851 param_type,
1852 body_type,
1853 ..
1854 } => {
1855 collect_global_names(param_type, out);
1856 collect_global_names(body_type, out);
1857 }
1858 Term::Lambda {
1859 param_type, body, ..
1860 } => {
1861 collect_global_names(param_type, out);
1862 collect_global_names(body, out);
1863 }
1864 Term::Match {
1865 discriminant,
1866 motive,
1867 cases,
1868 } => {
1869 collect_global_names(discriminant, out);
1870 collect_global_names(motive, out);
1871 for c in cases {
1872 collect_global_names(c, out);
1873 }
1874 }
1875 Term::Fix { body, .. } => collect_global_names(body, out),
1876 Term::MutualFix { defs, .. } => {
1877 for (_, b) in defs {
1878 collect_global_names(b, out);
1879 }
1880 }
1881 Term::Let {
1882 ty, value, body, ..
1883 } => {
1884 collect_global_names(ty, out);
1885 collect_global_names(value, out);
1886 collect_global_names(body, out);
1887 }
1888 Term::Annotated { term, .. } => collect_global_names(term, out),
1889 Term::Var(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => {}
1890 }
1891}
1892
1893/// Tarjan's strongly-connected components over a small adjacency list. Each returned
1894/// vector is one SCC (node indices, ascending); a self-referential singleton is its own
1895/// SCC of size one. Runs are tiny (a handful of adjacent inductives), so recursion is safe.
1896fn tarjan_scc(adj: &[std::collections::BTreeSet<usize>]) -> Vec<Vec<usize>> {
1897 struct State<'a> {
1898 adj: &'a [std::collections::BTreeSet<usize>],
1899 index: Vec<usize>,
1900 low: Vec<usize>,
1901 on_stack: Vec<bool>,
1902 stack: Vec<usize>,
1903 counter: usize,
1904 sccs: Vec<Vec<usize>>,
1905 }
1906 impl State<'_> {
1907 fn connect(&mut self, v: usize) {
1908 self.index[v] = self.counter;
1909 self.low[v] = self.counter;
1910 self.counter += 1;
1911 self.stack.push(v);
1912 self.on_stack[v] = true;
1913 let neighbors: Vec<usize> = self.adj[v].iter().copied().collect();
1914 for w in neighbors {
1915 if self.index[w] == usize::MAX {
1916 self.connect(w);
1917 self.low[v] = self.low[v].min(self.low[w]);
1918 } else if self.on_stack[w] {
1919 self.low[v] = self.low[v].min(self.index[w]);
1920 }
1921 }
1922 if self.low[v] == self.index[v] {
1923 let mut comp = Vec::new();
1924 loop {
1925 let w = self.stack.pop().unwrap();
1926 self.on_stack[w] = false;
1927 comp.push(w);
1928 if w == v {
1929 break;
1930 }
1931 }
1932 comp.sort_unstable();
1933 self.sccs.push(comp);
1934 }
1935 }
1936 }
1937 let n = adj.len();
1938 let mut st = State {
1939 adj,
1940 index: vec![usize::MAX; n],
1941 low: vec![0; n],
1942 on_stack: vec![false; n],
1943 stack: Vec::new(),
1944 counter: 0,
1945 sccs: Vec::new(),
1946 };
1947 for v in 0..n {
1948 if st.index[v] == usize::MAX {
1949 st.connect(v);
1950 }
1951 }
1952 st.sccs
1953}
1954
1955#[cfg(test)]
1956#[path = "../../../logicaffeine_tests/unit/logicaffeine_kernel/interface/repl/mutual_batch_tests.rs"]
1957mod mutual_batch_tests;
1958
1959#[cfg(test)]
1960#[path = "../../../logicaffeine_tests/unit/logicaffeine_kernel/interface/repl/shared_prelude_controls.rs"]
1961mod shared_prelude_controls;