logicaffeine_kernel/error.rs
1//! Error types for the kernel type checker.
2
3use std::fmt;
4
5/// Errors that can occur during type checking.
6#[derive(Debug)]
7pub enum KernelError {
8 /// Reference to an undefined variable.
9 UnboundVariable(String),
10
11 /// Attempted to apply a non-function term.
12 NotAFunction(String),
13
14 /// Expected a type (something with type Sort), got something else.
15 NotAType(String),
16
17 /// Type mismatch: expected one type, found another.
18 TypeMismatch { expected: String, found: String },
19
20 /// Attempted to match on a non-inductive type.
21 NotAnInductive(String),
22
23 /// Invalid motive in match expression.
24 InvalidMotive(String),
25
26 /// Wrong number of cases in match expression.
27 WrongNumberOfCases { expected: usize, found: usize },
28
29 /// Error during proof certification.
30 CertificationError(String),
31
32 /// A checked declaration violates a semantic kernel invariant.
33 ///
34 /// Unlike CertificationError, this is a rejection, not a resource limit or
35 /// unsupported operation. Callers must not classify inconclusive reduction
36 /// failures as invalid declarations.
37 InvalidDeclaration(String),
38
39 /// Recursive call does not decrease structurally.
40 ///
41 /// This error prevents infinite loops in proofs.
42 /// A fixpoint must recurse on a structurally smaller argument.
43 TerminationViolation { fix_name: String, reason: String },
44
45 /// Inductive type appears in negative position in constructor.
46 ///
47 /// This error prevents logical paradoxes (Russell's paradox, etc).
48 /// An inductive must appear strictly positively in its constructors.
49 PositivityViolation {
50 inductive: String,
51 constructor: String,
52 reason: String,
53 },
54
55 /// Cannot infer the type of a hole without context.
56 ///
57 /// Holes (implicit arguments) need to be checked against an expected type,
58 /// not inferred standalone.
59 CannotInferHole,
60
61 /// A declaration would change what a registered name means while declarations outside the
62 /// name's own declaration unit depend on that meaning.
63 ///
64 /// Every dependent was checked against the current meaning, so the change would leave each
65 /// one certified for a statement it no longer states. Lean's environment is append-only;
66 /// LOGOS accepts a redeclaration while nothing relies on the name, and an identical one
67 /// always. `dependents` names every dependent by the declaration it belongs to (a derived
68 /// equation lemma by its definition, a constructor by its inductive), sorted.
69 StableMeaningViolation {
70 name: String,
71 change: MeaningChange,
72 dependents: Vec<String>,
73 },
74
75 /// The independent kernel ([`crate::recheck`](mod@crate::recheck)) did not confirm a declaration this kernel
76 /// accepted: it refuted it, or reached no verdict — [`crate::recheck::Incomplete`] says why,
77 /// a construct it does not cover or a resource bound that stopped it. `subject` names what
78 /// was being certified.
79 IndependentRecheck {
80 subject: String,
81 error: crate::recheck::ReCheckError,
82 },
83}
84
85/// How a refused declaration would have changed a registered name's meaning.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum MeaningChange {
88 /// A different type, body, sort, parameter list or constructor list under the same name, or
89 /// the name taken over by a declaration of another kind.
90 Redeclared,
91 /// A constructor added to an inductive whose constructor set something already relies on.
92 Extended,
93}
94
95impl fmt::Display for MeaningChange {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.write_str(match self {
98 MeaningChange::Redeclared => "redeclared with a different meaning",
99 MeaningChange::Extended => "extended with a constructor",
100 })
101 }
102}
103
104impl fmt::Display for KernelError {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 match self {
107 KernelError::UnboundVariable(v) => {
108 write!(f, "Unbound variable: {}", v)
109 }
110 KernelError::NotAFunction(t) => {
111 write!(f, "Not a function: {}", t)
112 }
113 KernelError::NotAType(t) => {
114 write!(f, "Not a type: {}", t)
115 }
116 KernelError::TypeMismatch { expected, found } => {
117 write!(f, "Type mismatch: expected {}, found {}", expected, found)
118 }
119 KernelError::NotAnInductive(t) => {
120 write!(f, "Not an inductive type: {}", t)
121 }
122 KernelError::InvalidMotive(t) => {
123 write!(f, "Invalid motive: {}", t)
124 }
125 KernelError::WrongNumberOfCases { expected, found } => {
126 write!(
127 f,
128 "Wrong number of cases: expected {}, found {}",
129 expected, found
130 )
131 }
132 KernelError::CertificationError(msg) => {
133 write!(f, "Certification error: {}", msg)
134 }
135 KernelError::InvalidDeclaration(msg) => {
136 write!(f, "Invalid declaration: {}", msg)
137 }
138 KernelError::TerminationViolation { fix_name, reason } => {
139 write!(f, "Termination violation in '{}': {}", fix_name, reason)
140 }
141 KernelError::PositivityViolation {
142 inductive,
143 constructor,
144 reason,
145 } => {
146 write!(
147 f,
148 "Positivity violation: constructor '{}' of '{}': {}",
149 constructor, inductive, reason
150 )
151 }
152 KernelError::CannotInferHole => {
153 write!(
154 f,
155 "Cannot infer type of implicit argument (_) without context"
156 )
157 }
158 KernelError::IndependentRecheck { subject, error } => {
159 write!(f, "Certification error: {subject}: {error:?}")
160 }
161 KernelError::StableMeaningViolation {
162 name,
163 change,
164 dependents,
165 } => {
166 const SHOWN: usize = 3;
167 let shown = dependents
168 .iter()
169 .take(SHOWN)
170 .map(|dependent| format!("`{dependent}`"))
171 .collect::<Vec<_>>()
172 .join(", ");
173 let more = dependents.len().saturating_sub(SHOWN);
174 let tail = if more == 0 {
175 String::new()
176 } else {
177 format!(" and {more} more")
178 };
179 let verb = if dependents.len() == 1 { "was" } else { "were" };
180 write!(
181 f,
182 "Stable meaning violation: `{name}` cannot be {change}: {shown}{tail} {verb} \
183 checked against its current meaning, and a declared name never changes \
184 meaning under what depends on it (declare a new name instead)"
185 )
186 }
187 }
188 }
189}
190
191impl std::error::Error for KernelError {}
192
193/// Result type for kernel operations.
194pub type KernelResult<T> = Result<T, KernelError>;