logicaffeine_kernel/interface/mod.rs
1//! Vernacular interface for the Kernel.
2//!
3//! Provides a text-based command interface for interacting with the kernel:
4//! - `Definition name : type := term.` - Add a definition
5//! - `Check term.` - Print the type of a term
6//! - `Eval term.` - Normalize and print a term
7//! - `Inductive Name := C1 : T1 | C2 : T2.` - Define an inductive type
8//!
9//! # Surface extensions (they declare a SPELLING, never a global)
10//!
11//! - `Notation "a ⊕ b" := ((myOp a) b).` - Mixfix notation; identifier pieces are holes
12//! - `Infixl 65 "⋄" := f.` / `Infixr` / `Prefix "∽" := neg.` / `Postfix "‼" := bang.`
13//! - `Macro "twice $e" := ….` / `MacroRules "list![$x, $xs]" := ….` - Pattern rewriting
14//! - `Section Name.` … `End Name.` - Scope a `Local Notation` to a section
15//! - `/-- doc -/`, `/-! module doc -/`, `-- line comment` - Prose, which declares nothing
16//!
17//! # Doors
18//!
19//! [`Repl::execute`] reads ONE command and refuses a prefix; [`Repl::execute_document`] reads a
20//! whole document and stops at the first block that does not check.
21//!
22//! [`parse_command`] and `parse_command_in` read a command from TEXT ALONE. One surface cannot
23//! be read from text alone — a literate `Consider`'s equation set has to be compiled against the
24//! discriminant's inductive, and the constructor list, its order and its arities live in the
25//! kernel context — so [`parse_command_in_ctx`] is the door that has one.
26//!
27//! # Literate Syntax (English-like alternative)
28//!
29//! - `A Bool is either Yes or No.` - Define an inductive type
30//! - `## To add (n: Nat) and (m: Nat) -> Nat:` - Define a function
31//! - `Consider x: When Zero: Yield m.` - Pattern matching
32
33mod command;
34mod command_parser;
35mod error;
36#[cfg(feature = "lean")]
37pub mod lean;
38pub mod literate_parser;
39pub mod match_compile;
40pub mod printer;
41pub(crate) mod raw_match;
42mod repl;
43pub mod surface;
44mod term_parser;
45
46pub use command::{Command, InductiveMember};
47pub use command_parser::{parse_command, parse_command_prefix_in};
48pub use error::{InterfaceError, ParseError};
49pub use match_compile::{
50 compile_clauses, compile_clauses_reporting, Clause, CompileReport, Pattern,
51};
52pub use printer::{print_command, print_term, print_term_in, PrintError};
53pub use repl::Repl;
54pub use surface::{Assoc, OperatorForm, Surface, SurfaceDecl};
55pub use term_parser::{BinderKind, BinderSurface, DeclarationSurface, TermParser};
56
57/// Every name a term SPELLS, collected into `out`.
58///
59/// ★ THIS IS WHAT "FRESH" HAS TO BE CHECKED AGAINST. Two places in this module introduce a name
60/// of their own — the equation compiler's field binders (`#fld0`, `#fld1`, …) and the literate
61/// surface's eigenvariables (`n#eig`) — and both used to argue freshness from the LEXER: "`#`
62/// cannot occur in an identifier, so a generated name can collide with nothing a user wrote".
63/// The argument is false. `«#fld0»` and `«n#eig»` are `«quoted names»`, which `scan_name`
64/// accepts everywhere an identifier is read, so both names are writable — and a collision is a
65/// captured binder, which is a well-typed term denoting a different function, or an
66/// eigenvariable the statement can NAME, which is ∀-introduction over a constant that is not
67/// arbitrary. Neither is reported by anything.
68///
69/// So freshness is CHECKED. A generated name is compared against this set and stepped until it
70/// is outside it, which stays true of any lexer, any escape and any quoting rule added later.
71/// Binders are collected as well as occurrences: a generated name that shadowed a binder would
72/// be just as wrong as one that captured a variable.
73pub(super) fn spelled_names(term: &crate::Term, out: &mut std::collections::HashSet<String>) {
74 use crate::Term;
75 match term {
76 Term::Var(n) | Term::Global(n) => {
77 out.insert(n.clone());
78 }
79 Term::Const { name, .. } => {
80 out.insert(name.clone());
81 }
82 Term::Pi {
83 param,
84 param_type,
85 body_type,
86 } => {
87 out.insert(param.clone());
88 spelled_names(param_type, out);
89 spelled_names(body_type, out);
90 }
91 Term::Lambda {
92 param,
93 param_type,
94 body,
95 } => {
96 out.insert(param.clone());
97 spelled_names(param_type, out);
98 spelled_names(body, out);
99 }
100 Term::App(f, x) => {
101 spelled_names(f, out);
102 spelled_names(x, out);
103 }
104 Term::Match {
105 discriminant,
106 motive,
107 cases,
108 } => {
109 spelled_names(discriminant, out);
110 spelled_names(motive, out);
111 for c in cases {
112 spelled_names(c, out);
113 }
114 }
115 Term::Fix { name, body } => {
116 out.insert(name.clone());
117 spelled_names(body, out);
118 }
119 Term::MutualFix { defs, .. } => {
120 for (n, b) in defs {
121 out.insert(n.clone());
122 spelled_names(b, out);
123 }
124 }
125 Term::Let {
126 name,
127 ty,
128 value,
129 body,
130 } => {
131 out.insert(name.clone());
132 spelled_names(ty, out);
133 spelled_names(value, out);
134 spelled_names(body, out);
135 }
136 Term::Annotated { term, .. } => spelled_names(term, out),
137 Term::Sort(_) | Term::Lit(_) | Term::Hole => {}
138 }
139}
140
141/// ★ ONE NAME GRAMMAR, EVERY DECLARATION DOOR — the name a declaration may be keyed at.
142///
143/// The kernel `Context` is a map of FLAT keys, so a declaration name is only useful if two things
144/// hold, and neither implies the other:
145///
146/// * a TERM can spell it — [`surface::Name::is_spelled_by`] hands the spelling to the term door
147/// and requires this same name back, so the invariant is checked against the grammar rather
148/// than restated beside it and left to drift. `end` scans clean as a component and is a
149/// reserved word to the term door, so declaring it mints a global no `Check` can ever name;
150/// * its flat key READS BACK as itself — `«a.b»` is one component keying at `a.b`, which reads
151/// back as the two-component `a.b`, so the two names share one key and each answers to the
152/// other's spelling with nothing reported.
153///
154/// A name failing either is WRITE-ONLY: the context holds it and no later command can reach it.
155///
156/// This is the parent module's function because BOTH doors declare names —
157/// `command_parser`'s `Definition`/`Inductive` and [`literate_parser`]'s `## To`,
158/// `## Theorem:`, `Let … be` and `A … is either` — and a rule about what a declaration may be
159/// keyed at that only one door applied would not be a rule, it would be a door's habit.
160/// `M_equations_extra::every_literate_declaration_door_refuses_a_write_only_name` pins the
161/// literate side and `vernacular_extra::a_declarable_name_is_always_a_referenceable_one` the
162/// vernacular one, on the same grid.
163pub(super) fn declaration_name(raw: &str) -> Result<surface::Name, ParseError> {
164 let raw = raw.trim();
165 if raw.is_empty() {
166 return Err(ParseError::Missing("declaration name".to_string()));
167 }
168 match surface::Name::scan(raw) {
169 Some((name, len)) if len == raw.len() && !name.is_spelled_by(raw) => {
170 Err(ParseError::InvalidIdent(format!(
171 "{raw:?} \u{2014} a declaration name must be one a TERM can spell, and no term can \
172 spell this one. A component after a `.` must be a plain identifier, and a \
173 reserved word (`fun`, `forall`, `fix`, `match`, `let`, `in`, `with`, `return`, \
174 `end`, `by`, `Type`, `Prop`) is not a name at all \u{2014} declaring one would key the \
175 context at a name nothing could ever refer to"
176 )))
177 }
178 Some((name, len)) if len == raw.len() && name.key_reads_back() => Ok(name),
179 Some((name, len)) if len == raw.len() => Err(ParseError::InvalidIdent(format!(
180 "{raw:?} \u{2014} this name is keyed at {:?}, which reads back as the different name \
181 {:?}. A quoted component may not contain `.`: the kernel context is a map of flat \
182 keys, so the two names would collide and each would answer to the other's spelling",
183 name.key(),
184 surface::Name::parse(&name.key())
185 .map(|n| n.parts().join(" \u{b7} "))
186 .unwrap_or_default()
187 ))),
188 _ => Err(ParseError::InvalidIdent(format!(
189 "{raw:?} \u{2014} a declaration name must be one a term can spell: an identifier \
190 (letters, digits, `_`, `'`), a \u{ab}quoted name\u{bb}, or those joined by `.` into a \
191 hierarchical name"
192 ))),
193 }
194}
195
196/// Parse ONE command off the FRONT of `input` with the kernel CONTEXT available, returning it
197/// with the number of bytes consumed.
198///
199/// This is the primitive the context-aware doors are built from, exactly as
200/// `command_parser::parse_command_prefix_in` is the primitive the text-only ones are built from:
201/// [`parse_command_in_ctx`] adds "and nothing followed", and a document splitter loops it.
202///
203/// One surface cannot be read from text alone. A literate `Consider`'s equation set has to be
204/// compiled against the discriminant's inductive, and the constructor list, its REGISTRATION
205/// ORDER and their arities live in the kernel context; a parser holding only a `&str` can only
206/// push one case per clause in SOURCE order — which silently computes a different function for
207/// every equal-arity inductive, and cannot express a nested pattern or a catch-all at all.
208///
209/// `## Theorem:` is routed too, for the other fact text cannot carry: how many constructors
210/// `Proof: induction <v>.` is eliminating over, so a bullet-count mistake is reported as one.
211///
212/// Both literate doors read their names in the surface's NAMESPACE SCOPE and through the
213/// context's shadow table — the resolution every other door gets from the REPL — because they
214/// must know what a name MEANS while they read: a clause is compiled against the constructors of
215/// the inductive its discriminant really has, and a `## Theorem`'s statement is reflected into
216/// syntax naming the constants it really mentions. What they hand back is re-spelled
217/// (`surface::respell_names`), so the REPL's own resolution of it changes nothing.
218///
219/// Every other surface is routed to the context-free door untouched: this is a pre-dispatch on
220/// two prefixes, not a second copy of the dispatcher. [`Repl`] reads every command through this
221/// door when it runs it; the document splitter only measures, through
222/// `measure_command_prefix`, since a block cannot be read against the context the blocks before
223/// it have not built yet.
224pub fn parse_command_prefix_in_ctx(
225 ctx: &crate::Context,
226 surface: &Surface,
227 input: &str,
228) -> Result<(Command, usize), ParseError> {
229 let lead = input.len() - input.trim_start().len();
230 let rest = &input[lead..];
231 // The two prefixes are spelled EXACTLY as `command_parser`'s own dispatch spells them. A door
232 // that recognised one more spelling than the other would be a second dispatcher wearing a
233 // pre-dispatch's clothes, and the difference would only ever show up as one door accepting a
234 // command the other refuses.
235 type Door =
236 fn(&crate::Context, &surface::Namespaces, &str) -> Result<(Command, usize), ParseError>;
237 let literate: Option<Door> = if rest.starts_with("## To ") {
238 Some(literate_parser::parse_definition_scoped)
239 } else if rest.starts_with("## Theorem:") {
240 Some(literate_parser::parse_theorem_scoped)
241 } else {
242 None
243 };
244 match literate {
245 Some(parse) => {
246 let (cmd, n) = parse(ctx, surface.namespaces(), rest)?;
247 Ok((cmd, lead + with_terminator(rest, n)))
248 }
249 None => command_parser::parse_command_prefix_in(surface, input),
250 }
251}
252
253/// Run `f` with the environment every name a session reads is resolved against: the keys the
254/// context declares (a universe-polymorphic definition is keyed in its own table, which
255/// `get_global` does not read), the keys in `pending` — what the command being run is about to
256/// declare — and the context's shadow table. One construction, so no door can come to resolve
257/// against a different environment than another.
258pub(crate) fn with_env<R>(
259 ctx: &crate::Context,
260 pending: &[String],
261 f: impl FnOnce(&surface::Env<'_>) -> R,
262) -> R {
263 let known = |key: &str| {
264 pending.iter().any(|p| p == key)
265 || ctx.get_global(key).is_some()
266 || ctx.poly_declaration(key).is_some()
267 };
268 let shadow = |written: &str| ctx.shadow_of(written);
269 f(&surface::Env {
270 known: &known,
271 shadow: &shadow,
272 })
273}
274
275/// The EXTENT of the command at the front of `input`: the bytes it occupies, read from its syntax
276/// alone and never from what its names mean. The document splitter's door — a document is split
277/// before any block of it runs, so no block can be read against the context the blocks before it
278/// will build (`literate_parser::measure_theorem`). Coq-style sentences are measured by the
279/// context-free door, as every door measures them.
280pub(crate) fn measure_command_prefix(surface: &Surface, input: &str) -> Result<usize, ParseError> {
281 let lead = input.len() - input.trim_start().len();
282 let rest = &input[lead..];
283 let literate: Option<fn(&str) -> Result<usize, ParseError>> = if rest.starts_with("## To ") {
284 Some(literate_parser::measure_definition)
285 } else if rest.starts_with("## Theorem:") {
286 Some(literate_parser::measure_theorem)
287 } else {
288 None
289 };
290 match literate {
291 Some(measure) => Ok(lead + with_terminator(rest, measure(rest)?)),
292 None => command_parser::parse_command_prefix_in(surface, input).map(|(_, n)| n),
293 }
294}
295
296/// A literate block's extent INCLUDES the sentence terminator that closes it, if one is written.
297///
298/// This is the same rule `command_parser::with_terminator` applies to the text-only doors, and
299/// `the_two_doors_measure_a_command_the_same_way` pins the two against each other over every
300/// surface they share — a command whose extent the two doors disagreed about would split a
301/// document differently depending on whether its caller happened to hold a context.
302fn with_terminator(rest: &str, n: usize) -> usize {
303 let tail = &rest[n..];
304 let spaces = tail.len() - tail.trim_start_matches([' ', '\t']).len();
305 if tail[spaces..].starts_with('.') {
306 n + spaces + 1
307 } else {
308 n
309 }
310}
311
312/// Parse ONE command with the kernel CONTEXT available, and require it to be the whole input.
313///
314/// [`parse_command_prefix_in_ctx`] plus "and nothing followed" — the context-aware counterpart of
315/// `parse_command`, and what [`Repl::execute`] should read its command through.
316pub fn parse_command_in_ctx(
317 ctx: &crate::Context,
318 surface: &Surface,
319 input: &str,
320) -> Result<Command, ParseError> {
321 let (cmd, consumed) = parse_command_prefix_in_ctx(ctx, surface, input)?;
322 let rest = input[consumed..].trim();
323 if !rest.is_empty() {
324 return Err(ParseError::TrailingInput {
325 at: consumed,
326 rest: rest.to_string(),
327 });
328 }
329 Ok(cmd)
330}
331
332/// A context of its own for a REPL or a document to extend: a copy-on-write clone of the process's
333/// one standard library registration, [`crate::prelude::StandardLibrary::context`].
334///
335/// Measured on the bench box, optimized: registering the prelude takes 315 ms, a clone of the
336/// registered context about 1 µs.
337///
338/// What comes back is an independent value the caller may mutate freely; it shares the prelude's
339/// tables until it writes, and a write copies exactly the table it touches.
340/// `the_cached_prelude_is_indistinguishable_from_a_fresh_one` pins it against a freshly registered
341/// one, and `Repl::new` starts from it.
342pub fn standard_context() -> crate::Context {
343 crate::prelude::StandardLibrary::context().clone()
344}