logicaffeine_kernel/interface/error.rs
1//! Error types for the Vernacular interface.
2
3use crate::KernelError;
4use std::fmt;
5
6/// Errors that can occur in the interface layer.
7#[derive(Debug)]
8pub enum InterfaceError {
9 /// Parse error in command or term syntax.
10 Parse(ParseError),
11
12 /// Error from the kernel (type checking, etc.)
13 Kernel(KernelError),
14
15 /// A tactic script's step that did not apply, with the goal it ran on.
16 Tactic(crate::tactics::ScriptError),
17}
18
19/// Parse errors for the Vernacular.
20#[derive(Debug, Clone)]
21pub enum ParseError {
22 /// Unexpected end of input.
23 UnexpectedEof,
24
25 /// Unknown command keyword.
26 UnknownCommand(String),
27
28 /// Expected a specific token.
29 Expected { expected: String, found: String },
30
31 /// Invalid identifier.
32 InvalidIdent(String),
33
34 /// One short name, two or more declared constants, at the same resolution priority.
35 ///
36 /// ★ AN AMBIGUOUS NAME IS REPORTED, NEVER PICKED. This is the failure mode the audit called the
37 /// dangerous one: the prelude already owns `Nat`, `Zero`, `Succ`, `Eq`, `True`, `False` and
38 /// forty more, so a short name written under an `open` did not fail to resolve — it resolved to
39 /// the PRELUDE's constant and nothing said a word. Both readings type-check and they are
40 /// different theorems. Lean errors here; we error here and name BOTH candidates, because
41 /// "ambiguous" without the list is a puzzle rather than a diagnosis.
42 AmbiguousName {
43 written: String,
44 candidates: Vec<String>,
45 },
46
47 /// A document ended in a different scope than it started in.
48 ///
49 /// ★ A DOCUMENT IS BALANCED. `Namespace N.` with no `End N.` is the quietest failure this
50 /// surface has: every declaration after it is written into `N`, nothing is reported, and the
51 /// file still checks. 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. It is
52 /// stated as BALANCE and not as "empty at the end", so a caller that was already
53 /// inside a namespace when it handed the door a document is not punished for it — and a
54 /// document that closes a scope it did not open is the same mistake pointing the other way.
55 UnbalancedDocument {
56 /// Scopes the document opened and never closed, outermost first.
57 unclosed: Vec<String>,
58 /// How many of the CALLER's scopes the document closed.
59 overclosed: usize,
60 },
61
62 /// `Open Typo.` where nothing has ever been declared into `Typo`.
63 ///
64 /// An `open` that brings in NOTHING is indistinguishable from one that worked, and every short
65 /// name written under it then quietly denotes the root's constant. Lean refuses an unknown
66 /// namespace; so do we.
67 UnknownNamespace(String),
68
69 /// Invalid number literal.
70 InvalidNumber(String),
71
72 /// Missing required component.
73 Missing(String),
74
75 /// A complete term was parsed but input remained after it.
76 ///
77 /// ★ THE KERNEL MUST NOT ACCEPT A PREFIX. Parsing one term and discarding whatever followed
78 /// meant `Check Nat -> Nat garbage here` checked `Nat -> Nat` and reported success about a
79 /// claim nobody made. Every other component here can afford leniency and be merely wrong;
80 /// this is the one that answers "is this proved".
81 TrailingInput { at: usize, rest: String },
82
83 /// A macro expansion did not reach a fixpoint within the step budget.
84 ///
85 /// A recursive `macro_rules` whose base case is unreachable must FAIL, loudly and at a stated
86 /// limit, rather than spin — an expander that hangs is indistinguishable from a kernel that
87 /// is thinking hard.
88 MacroDepth { limit: usize },
89
90 /// A construct the vernacular REFUSES by name, with the reason.
91 ///
92 /// The distinction that matters is refused-versus-MISPARSED. `Inductive Colour := red :
93 /// Colour deriving BEq.` used to be accepted, registering `red` at type
94 /// `((Colour deriving) BEq)` — a constructor whose declared type applies the inductive to two
95 /// globals that are not in the context at all. That is strictly worse than rejecting the
96 /// file: it is a declaration that names things which do not exist.
97 Unsupported { what: String, why: String },
98
99 // ============================================================
100 // Literate Syntax Errors
101 // ============================================================
102 /// Missing "is either" clause in inductive definition.
103 MissingEitherClause,
104
105 /// Missing variant name in inductive definition.
106 MissingVariantName,
107
108 /// Invalid Consider/When/Yield syntax.
109 InvalidConsiderSyntax(String),
110
111 /// Missing Yield in function body.
112 MissingYield,
113
114 /// Missing When clause in Consider block.
115 MissingWhenClause,
116
117 /// Unclosed Consider block.
118 UnclosedConsiderBlock,
119}
120
121impl fmt::Display for InterfaceError {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 match self {
124 InterfaceError::Parse(e) => write!(f, "Parse error: {}", e),
125 InterfaceError::Kernel(e) => write!(f, "Kernel error: {}", e),
126 InterfaceError::Tactic(e) => write!(f, "Tactic error: {}", e),
127 }
128 }
129}
130
131impl fmt::Display for ParseError {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 match self {
134 ParseError::UnexpectedEof => write!(f, "Unexpected end of input"),
135 ParseError::UnknownCommand(cmd) => write!(f, "Unknown command: {}", cmd),
136 ParseError::Expected { expected, found } => {
137 write!(f, "Expected {}, found {}", expected, found)
138 }
139 ParseError::TrailingInput { at, rest } => write!(
140 f,
141 "Unexpected input after the end of the term, at byte {}: {:?}. A term is read \
142 whole — if you meant two things, they need two commands.",
143 at, rest
144 ),
145 ParseError::InvalidIdent(s) => write!(f, "Invalid identifier: {}", s),
146 ParseError::AmbiguousName {
147 written,
148 candidates,
149 } => write!(
150 f,
151 "the name `{}` is ambiguous — it denotes {} at the same priority, and picking one \
152 silently would change what this says. Write the one you mean in full, or \
153 `_root_.{}` for the top-level name.",
154 written,
155 candidates
156 .iter()
157 .map(|c| format!("`{c}`"))
158 .collect::<Vec<_>>()
159 .join(" and "),
160 written
161 ),
162 ParseError::UnbalancedDocument {
163 unclosed,
164 overclosed,
165 } if !unclosed.is_empty() => {
166 write!(
167 f,
168 "this document ends inside {} \u{2014} a scope it opened and never closed. Every \
169 declaration written after it would land in that scope and nothing would say \
170 so, so the document is refused rather than read half in it. Close it with \
171 `End{}.`",
172 unclosed
173 .iter()
174 .map(|s| format!("`{s}`"))
175 .collect::<Vec<_>>()
176 .join(", inside "),
177 // An ANONYMOUS section has no name to close it by, so the advice must not tell
178 // the reader to write one — a bare `End.` is what closes it.
179 match unclosed.last().expect("non-empty").as_str() {
180 crate::interface::surface::ANONYMOUS_SECTION => "".to_string(),
181 named => format!(" {named}"),
182 }
183 )?;
184 if *overclosed > 0 {
185 write!(f, " (and it closed {overclosed} scope(s) it did not open)")?;
186 }
187 Ok(())
188 }
189 ParseError::UnbalancedDocument { overclosed, .. } => write!(
190 f,
191 "this document closed {overclosed} scope(s) it did not open. A document may leave \
192 the scope it was handed, and may not unwind past it \u{2014} the caller's later \
193 declarations would silently change where they land."
194 ),
195 ParseError::UnknownNamespace(ns) => write!(
196 f,
197 "there is no namespace `{ns}` — nothing has been declared into it. An `open` that \
198 brings in no names looks exactly like one that worked, so it is refused here \
199 rather than left to change what every short name under it means."
200 ),
201 ParseError::InvalidNumber(s) => write!(f, "Invalid number literal: {}", s),
202 ParseError::Missing(what) => write!(f, "Missing {}", what),
203 ParseError::Unsupported { what, why } => {
204 write!(f, "{} is not supported: {}", what, why)
205 }
206 ParseError::MacroDepth { limit } => write!(
207 f,
208 "macro expansion did not terminate within {} steps — a recursive rule is not \
209 reaching its base case",
210 limit
211 ),
212 // Literate syntax errors
213 ParseError::MissingEitherClause => {
214 write!(f, "Missing 'is either' clause in type definition")
215 }
216 ParseError::MissingVariantName => write!(f, "Missing variant name in type definition"),
217 ParseError::InvalidConsiderSyntax(msg) => write!(f, "Invalid Consider syntax: {}", msg),
218 ParseError::MissingYield => write!(f, "Missing 'Yield' in function body"),
219 ParseError::MissingWhenClause => write!(f, "Missing 'When' clause in Consider block"),
220 ParseError::UnclosedConsiderBlock => write!(f, "Unclosed Consider block"),
221 }
222 }
223}
224
225impl std::error::Error for InterfaceError {}
226impl std::error::Error for ParseError {}
227
228impl From<crate::tactics::ScriptError> for InterfaceError {
229 fn from(e: crate::tactics::ScriptError) -> Self {
230 InterfaceError::Tactic(e)
231 }
232}
233
234impl From<ParseError> for InterfaceError {
235 fn from(e: ParseError) -> Self {
236 InterfaceError::Parse(e)
237 }
238}
239
240impl From<KernelError> for InterfaceError {
241 fn from(e: KernelError) -> Self {
242 InterfaceError::Kernel(e)
243 }
244}