Skip to main content

logicaffeine_language/
error.rs

1//! Error types and display formatting for parse errors.
2//!
3//! This module provides structured error types for the lexer and parser,
4//! with rich diagnostic output including:
5//!
6//! - Source location with line/column numbers
7//! - Syntax-highlighted error messages
8//! - Socratic explanations for common mistakes
9//! - Spelling suggestions for unknown words
10//!
11//! # Error Display
12//!
13//! Errors can be displayed with source context using [`ParseError::display_with_source`],
14//! which produces rustc-style error output with underlined spans.
15
16use crate::style::Style;
17use crate::suggest::{find_similar, KNOWN_WORDS};
18use crate::token::{Span, TokenType};
19use logicaffeine_base::Interner;
20
21/// A parse error with location information.
22#[derive(Debug, Clone)]
23pub struct ParseError {
24    pub kind: ParseErrorKind,
25    pub span: Span,
26}
27
28impl ParseError {
29    pub fn display_with_source(&self, source: &str) -> String {
30        let (line_num, line_start, line_content) = self.find_context(source);
31        let col = self.span.start.saturating_sub(line_start);
32        let len = (self.span.end - self.span.start).max(1);
33
34        // Window very long lines around the error column — a generated
35        // 20,000-character expression must not flood the terminal with its
36        // own excerpt.
37        const EXCERPT_MAX: usize = 160;
38        let (line_content, col, len) = if line_content.chars().count() > EXCERPT_MAX {
39            let chars: Vec<char> = line_content.chars().collect();
40            let col_chars = line_content
41                .char_indices()
42                .take_while(|(i, _)| *i < col)
43                .count();
44            let from = col_chars.saturating_sub(EXCERPT_MAX / 2).min(chars.len());
45            let to = (from + EXCERPT_MAX).min(chars.len());
46            let mut windowed: String = chars[from..to].iter().collect();
47            if from > 0 {
48                windowed = format!("…{windowed}");
49            }
50            if to < chars.len() {
51                windowed.push('…');
52            }
53            let new_col = col_chars - from + usize::from(from > 0);
54            (
55                std::borrow::Cow::Owned(windowed),
56                new_col,
57                len.min(EXCERPT_MAX / 2),
58            )
59        } else {
60            (std::borrow::Cow::Borrowed(line_content), col, len)
61        };
62        let line_content: &str = &line_content;
63        let underline = format!("{}{}", " ".repeat(col), "^".repeat(len));
64
65        let error_label = Style::bold_red("error");
66        let kind_str = self.kind.headline().replace('\n', " ");
67        let line_num_str = Style::blue(&format!("{:4}", line_num));
68        let pipe = Style::blue("|");
69        let underline_colored = Style::red(&underline);
70
71        let mut result = format!(
72            "{}: {}\n\n{} {} {}\n     {} {}",
73            error_label, kind_str, line_num_str, pipe, line_content, pipe, underline_colored
74        );
75
76        if let Some(suggestion) = self.suggestion(source) {
77            let hint = Style::cyan("help");
78            result.push_str(&format!(
79                "\n     {} {}: did you mean '{}'?",
80                pipe,
81                hint,
82                Style::green(suggestion)
83            ));
84        }
85
86        result
87    }
88
89    /// The "did you mean" word for this error's span, when the error is about the word under it
90    /// (`is_about_a_word`) and the span covers an alphabetic word within edit distance 2 of a
91    /// known word. The caret renderer and the `logos-diagnostic/1` JSON surface share this one
92    /// suggester so their hints can never disagree.
93    pub fn suggestion(&self, source: &str) -> Option<&'static str> {
94        if !is_about_a_word(&self.kind) {
95            return None;
96        }
97        let word = self.extract_word(source)?;
98        find_similar(word, KNOWN_WORDS, 2)
99    }
100
101    fn extract_word<'a>(&self, source: &'a str) -> Option<&'a str> {
102        if self.span.start < source.len() && self.span.end <= source.len() {
103            let word = &source[self.span.start..self.span.end];
104            if !word.is_empty() && word.chars().all(|c| c.is_alphabetic()) {
105                return Some(word);
106            }
107        }
108        None
109    }
110
111    /// The structured pieces of a caret diagnostic — the Socratic message, the source
112    /// line, the caret column + length, and the optional "did you mean". Shared by the
113    /// terminal renderer and the browser build-error overlay so the two can never drift.
114    /// (`socratic_explanation` ignores its interner, so a fresh one is fine here.)
115    pub fn diagnostic_parts(&self, source: &str) -> DiagnosticParts {
116        let (line_num, line_start, line_content) = self.find_context(source);
117        DiagnosticParts {
118            line_num,
119            line: line_content.to_string(),
120            column: self.span.start.saturating_sub(line_start),
121            caret_len: (self.span.end - self.span.start).max(1),
122            message: socratic_explanation(self, &Interner::new()),
123            suggestion: self.suggestion(source),
124        }
125    }
126
127    fn find_context<'a>(&self, source: &'a str) -> (usize, usize, &'a str) {
128        let mut line_num = 1;
129        let mut line_start = 0;
130
131        for (i, c) in source.char_indices() {
132            if i >= self.span.start {
133                break;
134            }
135            if c == '\n' {
136                line_num += 1;
137                line_start = i + 1;
138            }
139        }
140
141        let line_end = source[line_start..]
142            .find('\n')
143            .map(|off| line_start + off)
144            .unwrap_or(source.len());
145
146        (line_num, line_start, &source[line_start..line_end])
147    }
148}
149
150/// Whether `kind` is about the word under its span — the parser expected a word of some class
151/// there and found this one, so a nearby known word is a likely intended spelling. Every other
152/// kind is about a construct, a type, a name the program declares, or the discourse, and the word
153/// under its span is spelled as the author meant it.
154fn is_about_a_word(kind: &ParseErrorKind) -> bool {
155    use ParseErrorKind::*;
156    match kind {
157        UnexpectedToken { .. }
158        | ExpectedContentWord { .. }
159        | ExpectedCopula
160        | UnknownQuantifier { .. }
161        | UnknownModal { .. }
162        | ExpectedVerb { .. }
163        | ExpectedTemporalAdverb
164        | ExpectedPresuppositionTrigger
165        | ExpectedFocusParticle
166        | ExpectedScopalAdverb
167        | ExpectedSuperlativeAdjective
168        | ExpectedComparativeAdjective
169        | ExpectedThan
170        | ExpectedNumber
171        | ExpectedStatement
172        | ExpectedKeyword { .. }
173        | ExpectedExpression
174        | ExpectedIdentifier
175        | TrailingTokens { .. } => true,
176        EmptyRestriction
177        | GappingResolutionFailed
178        | StativeProgressiveConflict
179        | UndefinedVariable { .. }
180        | UseAfterMove { .. }
181        | IsValueEquality { .. }
182        | ZeroIndex
183        | RespectivelyLengthMismatch { .. }
184        | TypeMismatch { .. }
185        | TypeMismatchDetailed { .. }
186        | InfiniteType { .. }
187        | ArityMismatch { .. }
188        | FieldNotFound { .. }
189        | NotAFunction { .. }
190        | InvalidRefinementPredicate
191        | GrammarError(_)
192        | ScopeViolation(_)
193        | UnresolvedPronoun { .. }
194        | AstTooDeep { .. }
195        | Custom(_) => false,
196    }
197}
198
199/// The structured pieces a caret-style diagnostic needs — produced by
200/// [`ParseError::diagnostic_parts`] and shared by every renderer (terminal, browser
201/// overlay) so their line, caret, message, and hint can never disagree.
202#[derive(Debug, Clone)]
203pub struct DiagnosticParts {
204    /// 1-based line number of the error.
205    pub line_num: usize,
206    /// The full source line containing the error.
207    pub line: String,
208    /// Byte column of the caret within `line` (0-based).
209    pub column: usize,
210    /// Number of `^` carets under the offending span (≥1).
211    pub caret_len: usize,
212    /// The Socratic explanation of what went wrong.
213    pub message: String,
214    /// An optional "did you mean '…'?" spelling suggestion.
215    pub suggestion: Option<&'static str>,
216}
217
218#[derive(Debug, Clone)]
219pub enum ParseErrorKind {
220    UnexpectedToken {
221        expected: TokenType,
222        found: TokenType,
223    },
224    ExpectedContentWord {
225        found: TokenType,
226    },
227    ExpectedCopula,
228    UnknownQuantifier {
229        found: TokenType,
230    },
231    UnknownModal {
232        found: TokenType,
233    },
234    ExpectedVerb {
235        found: TokenType,
236    },
237    ExpectedTemporalAdverb,
238    ExpectedPresuppositionTrigger,
239    ExpectedFocusParticle,
240    ExpectedScopalAdverb,
241    ExpectedSuperlativeAdjective,
242    ExpectedComparativeAdjective,
243    ExpectedThan,
244    ExpectedNumber,
245    EmptyRestriction,
246    GappingResolutionFailed,
247    StativeProgressiveConflict,
248    UndefinedVariable {
249        name: String,
250    },
251    UseAfterMove {
252        name: String,
253    },
254    IsValueEquality {
255        variable: String,
256        value: String,
257    },
258    ZeroIndex,
259    ExpectedStatement,
260    ExpectedKeyword {
261        keyword: String,
262    },
263    ExpectedExpression,
264    ExpectedIdentifier,
265    /// Subject and object lists have different lengths in a "respectively" construction.
266    RespectivelyLengthMismatch {
267        subject_count: usize,
268        object_count: usize,
269    },
270    /// Type mismatch during static type checking.
271    TypeMismatch {
272        expected: String,
273        found: String,
274    },
275    /// Type mismatch with context (e.g., "in argument 2 of 'compute'").
276    TypeMismatchDetailed {
277        expected: String,
278        found: String,
279        context: String,
280    },
281    /// A type variable would occur in its own definition (e.g., `T = List<T>`).
282    InfiniteType {
283        var_description: String,
284        type_description: String,
285    },
286    /// Wrong number of arguments in a function call.
287    ArityMismatch {
288        function: String,
289        expected: usize,
290        found: usize,
291    },
292    /// A field name does not exist on the struct type.
293    FieldNotFound {
294        type_name: String,
295        field_name: String,
296        available: Vec<String>,
297    },
298    /// Tried to call something that is not a function.
299    NotAFunction {
300        found_type: String,
301    },
302    /// Invalid refinement predicate in a dependent type.
303    InvalidRefinementPredicate,
304    /// Grammar error (e.g., "its" vs "it's").
305    GrammarError(String),
306    /// DRS scope violation (pronoun trapped in negation, disjunction, etc.).
307    ScopeViolation(String),
308    /// Unresolved pronoun in discourse mode - no accessible antecedent found.
309    UnresolvedPronoun {
310        gender: crate::drs::Gender,
311        number: crate::drs::Number,
312    },
313    /// The parser finished a sentence with input left over — accepting it
314    /// would silently drop the remainder's meaning.
315    TrailingTokens {
316        found: TokenType,
317    },
318    /// The program's AST nests deeper than every downstream walker
319    /// (optimizer, codegen, interpreter, VM compiler) can safely recurse —
320    /// the depth gate rejects it here so no surface ever stack-overflows.
321    AstTooDeep {
322        /// The measured (or exceeded) nesting depth.
323        depth: usize,
324        /// The enforced limit ([`crate::ast_depth::max_ast_depth`]).
325        max_depth: usize,
326    },
327    /// Custom error message (used for escape analysis, zone errors, etc.).
328    Custom(String),
329}
330
331/// A human reading of a token for error prose — never the raw `Debug` name.
332/// "a comma (',')" teaches; "Comma" is compiler debris.
333pub fn describe_token(token: &TokenType) -> String {
334    let simple = |s: &str| s.to_string();
335    match token {
336        TokenType::Period => simple("a period ('.')"),
337        TokenType::Comma => simple("a comma (',')"),
338        TokenType::Colon => simple("a colon (':')"),
339        TokenType::Newline => simple("a line break"),
340        TokenType::Indent => simple("an indent"),
341        TokenType::Dedent => simple("the end of an indented block"),
342        TokenType::EOF => simple("the end of the input"),
343        TokenType::Noun(_) => simple("a noun"),
344        TokenType::Verb { .. } => simple("a verb"),
345        TokenType::Adjective(_) | TokenType::NonIntersectiveAdjective(_) => simple("an adjective"),
346        TokenType::Adverb(_) | TokenType::ScopalAdverb(_) | TokenType::TemporalAdverb(_) => {
347            simple("an adverb")
348        }
349        TokenType::ProperName(_) => simple("a name"),
350        TokenType::Identifier => simple("an identifier"),
351        TokenType::Number(_) => simple("a number"),
352        TokenType::StringLiteral(_) | TokenType::InterpolatedString(_) => simple("a string"),
353        TokenType::CharLiteral(_) => simple("a character literal"),
354        TokenType::MoneyLiteral { .. } => simple("a money amount"),
355        TokenType::DurationLiteral { .. }
356        | TokenType::DateLiteral { .. }
357        | TokenType::TimeLiteral { .. } => simple("a time literal"),
358        TokenType::CalendarUnit(_) => simple("a calendar unit"),
359        TokenType::Pronoun { .. } => simple("a pronoun"),
360        TokenType::Article(_) => simple("an article"),
361        TokenType::Preposition(_) => simple("a preposition"),
362        TokenType::Particle(_) => simple("a particle"),
363        TokenType::Comparative(_) => simple("a comparative"),
364        TokenType::Superlative(_) => simple("a superlative"),
365        TokenType::Auxiliary(_) => simple("an auxiliary verb"),
366        TokenType::Performative(_) => simple("a performative verb"),
367        TokenType::BlockHeader { .. } => simple("a '##' block header"),
368        TokenType::EscapeBlock(_) => simple("an escape block"),
369        TokenType::Ambiguous { primary, .. } => describe_token(primary),
370        TokenType::Possessive => simple("a possessive ('s)"),
371        TokenType::LParen => simple("'('"),
372        TokenType::RParen => simple("')'"),
373        TokenType::LBracket => simple("'['"),
374        TokenType::RBracket => simple("']'"),
375        TokenType::LBrace => simple("'{'"),
376        TokenType::RBrace => simple("'}'"),
377        TokenType::Plus => simple("'+'"),
378        TokenType::Minus => simple("'-'"),
379        TokenType::Star => simple("'*'"),
380        TokenType::Slash => simple("'/'"),
381        TokenType::Percent => simple("'%'"),
382        TokenType::PlusEq => simple("'+='"),
383        TokenType::MinusEq => simple("'-='"),
384        TokenType::StarEq => simple("'*='"),
385        TokenType::SlashEq => simple("'/='"),
386        TokenType::PercentEq => simple("'%='"),
387        TokenType::StarStar => simple("'**'"),
388        TokenType::SlashSlash => simple("'//'"),
389        TokenType::Lt => simple("'<'"),
390        TokenType::Gt => simple("'>'"),
391        TokenType::LtEq => simple("'<='"),
392        TokenType::GtEq => simple("'>='"),
393        TokenType::EqEq => simple("'=='"),
394        TokenType::NotEq => simple("'!='"),
395        TokenType::Arrow => simple("'->'"),
396        TokenType::Assign => simple("'='"),
397        TokenType::Amp => simple("'&'"),
398        TokenType::VBar => simple("'|'"),
399        TokenType::Tilde => simple("'~'"),
400        TokenType::Caret => simple("'^'"),
401        TokenType::Dot => simple("'.'"),
402        other => format!("the word '{}'", format!("{other:?}").to_lowercase()),
403    }
404}
405
406/// The surface pronoun a gender/number pair names, quoted for prose.
407pub(crate) fn pronoun_word(
408    gender: &crate::drs::Gender,
409    number: &crate::drs::Number,
410) -> &'static str {
411    use crate::drs::{Gender, Number};
412    match (number, gender) {
413        (Number::Plural, _) | (Number::Singular, Gender::Unknown) => "'they'",
414        (Number::Singular, Gender::Female) => "'she'",
415        (Number::Singular, Gender::Male) => "'he'",
416        (Number::Singular, Gender::Neuter) => "'it'",
417    }
418}
419
420#[cold]
421pub fn socratic_explanation(error: &ParseError, _interner: &Interner) -> String {
422    match &error.kind {
423        ParseErrorKind::UnexpectedToken { expected, found } => {
424            let expected = describe_token(expected);
425            format!(
426                "I was following your sentence but stumbled here: I expected {expected}, \
427                and found {} instead. The structure so far commits me to {expected} next. \
428                Is a word missing just before this, or did two thoughts run together? \
429                Splitting the sentence in two often shows which.",
430                describe_token(found)
431            )
432        }
433        ParseErrorKind::ExpectedContentWord { found } => {
434            format!(
435                "This spot needs a content word — a noun, a verb, or an adjective — but I \
436                found {} instead. Content words carry the meaning; the little words only \
437                arrange them. What thing, action, or quality did you mean to name here? \
438                Put that word in and the sentence grounds itself.",
439                describe_token(found)
440            )
441        }
442        ParseErrorKind::ExpectedCopula => "The subject here is waiting for 'is' or 'are' to \
443            link it to its predicate. English predication runs through a copula — without \
444            one, the two halves never connect. What is the subject supposed to BE? Write it \
445            as 'X is Y' ('are' for plurals)."
446            .to_string(),
447        ParseErrorKind::UnknownQuantifier { found } => {
448            format!(
449                "I needed a quantifier here — a word like 'all', 'some', or 'no' — but found \
450                {}. Quantifiers say how many things the sentence talks about, and that choice \
451                decides the whole logical shape. How many did you mean: every one, at least \
452                one, or none? Lead with the word that says so.",
453                describe_token(found)
454            )
455        }
456        ParseErrorKind::UnknownModal { found } => {
457            format!(
458                "I needed a modal here — 'must', 'can', 'may', 'should' — but found {}. \
459                Modals set the strength of the claim: necessity, possibility, permission, \
460                obligation. Which strength did you mean? Pick the modal that carries it and \
461                the logic follows.",
462                describe_token(found)
463            )
464        }
465        ParseErrorKind::ExpectedVerb { found } => {
466            format!(
467                "Every sentence needs a verb, and this one's verb should appear here — I \
468                found {} instead. The verb names the action or state everything else hangs \
469                on. What is the subject doing (or being)? Give the sentence that verb.",
470                describe_token(found)
471            )
472        }
473        ParseErrorKind::ExpectedTemporalAdverb => "I expected a time word here — 'yesterday', \
474            'tomorrow', 'always'. Temporal adverbs anchor the sentence on the timeline, and \
475            this construction promised one. When does this happen? Say it with a temporal \
476            adverb, or drop the construction that required one."
477            .to_string(),
478        ParseErrorKind::ExpectedPresuppositionTrigger => "I expected a presupposition trigger \
479            here — a word like 'stopped', 'realized', or 'regrets'. These verbs quietly \
480            assume something was already true; that hidden assumption is what this \
481            construction works with. What background fact is being taken for granted? The \
482            trigger word is what carries it."
483            .to_string(),
484        ParseErrorKind::ExpectedFocusParticle => "I expected a focus particle here — 'only', \
485            'even', 'just'. Focus particles single out one part of the sentence against its \
486            alternatives. Which word should the emphasis land on? Put the particle directly \
487            before it."
488            .to_string(),
489        ParseErrorKind::ExpectedScopalAdverb => "I expected a scopal adverb here — a word \
490            like 'necessarily' or 'possibly' that comments on the whole claim rather than \
491            the verb alone. Is the adverb meant to cover the entire sentence? If it only \
492            describes the action, it belongs next to the verb instead."
493            .to_string(),
494        ParseErrorKind::ExpectedSuperlativeAdjective => "I expected a superlative here — \
495            'tallest', 'fastest', the '-est' form. A superlative ranks one thing against all \
496            the others, and that is the comparison this sentence set up. Are you comparing \
497            against everything, or just one other thing? Use '-est' for everything, '-er \
498            than' for one."
499            .to_string(),
500        ParseErrorKind::ExpectedComparativeAdjective => "I expected a comparative here — \
501            'taller', 'faster', the '-er' form. A comparative weighs exactly two things \
502            against each other. What quality are the two compared on? Name it in its '-er' \
503            form and follow with 'than'."
504            .to_string(),
505        ParseErrorKind::ExpectedThan => "A comparative opened a comparison, and 'than' \
506            introduces the other side — but it is missing here. Taller than what, exactly? \
507            Add 'than' plus the thing being compared against."
508            .to_string(),
509        ParseErrorKind::ExpectedNumber => "This measure phrase needs a number — '2', '3.14' \
510            — and none appeared. A measure without a quantity measures nothing. How much, \
511            exactly? Put the number in front of the unit."
512            .to_string(),
513        ParseErrorKind::EmptyRestriction => "This relative clause is empty — 'the X that \
514            ...' with nothing after 'that'. A restriction narrows the noun down, so an empty \
515            one narrows nothing. Which ones did you mean? State the property that picks them \
516            out, or drop the 'that' entirely."
517            .to_string(),
518        ParseErrorKind::GappingResolutionFailed => "This reads like a gapped construction — \
519            '... and Mary, a pear' — where the verb is borrowed from the previous clause, \
520            but I found no verb there to borrow. What is the second subject doing? Either \
521            repeat the verb outright, or make sure the first clause states it plainly."
522            .to_string(),
523        ParseErrorKind::StativeProgressiveConflict => "A stative verb like 'know' or 'love' \
524            is in the progressive here, and states do not run in progress — they simply hold \
525            or they don't. Is this a state or an ongoing activity? States take the simple \
526            form ('knows'); only activities take '-ing'."
527            .to_string(),
528        ParseErrorKind::UndefinedVariable { name } => {
529            format!(
530                "I found '{name}', but nothing has declared it. Every variable starts life \
531                in a Let — reading a name before it exists gives me no value to read. Where \
532                should '{name}' get its first value? Add 'Let {name} be ...' above this \
533                line, or check the spelling against the name you declared."
534            )
535        }
536        ParseErrorKind::UseAfterMove { name } => {
537            format!(
538                "Cannot use '{name}' after giving it away. 'Give {name} to ...' transferred \
539                ownership — '{name}' belongs to the receiver now, and this later use has \
540                nothing left to hold. Who really needs to own '{name}' here? To lend it and \
541                keep it, 'Show {name}'; to hand over a duplicate, give 'a copy of {name}'."
542            )
543        }
544        ParseErrorKind::IsValueEquality { variable, value } => {
545            format!(
546                "'{variable} is {value}' reads as a type or predicate claim — 'is' asks what \
547                something IS, not which value it holds. Value comparison is spelled \
548                'equals'. Are you asking what '{variable}' is, or whether it holds {value}? \
549                For the value question, write '{variable} equals {value}'."
550            )
551        }
552        ParseErrorKind::ZeroIndex => "This asks for item 0, but LOGOS indices start at 1 — \
553            in English, 'the 1st item' is the first one; there is no item 0. Which element \
554            did you want? The first is 'item 1 of xs' — the zero-based habit is the only \
555            thing to unlearn."
556            .to_string(),
557        ParseErrorKind::ExpectedStatement => "I expected a statement here — a sentence that \
558            does something, like 'Let', 'Set', 'Show', or 'Return'. What should happen at \
559            this point in the program? Start the line with the verb that does it, and end \
560            with a period."
561            .to_string(),
562        ParseErrorKind::ExpectedKeyword { keyword } => {
563            format!(
564                "This construction needs the word '{keyword}' here to complete its shape. \
565                Statement forms have fixed connecting words — they are the joints of the \
566                sentence. Which form did you start? Insert '{keyword}' where I stopped, or \
567                compare your line against that form's example."
568            )
569        }
570        ParseErrorKind::ExpectedExpression => "I expected an expression here — a value: a \
571            number, a variable, a call, or a computation. Something just before this (a \
572            'be', a 'to', an operator) promised a value that never arrived. What value \
573            should flow into this spot? Write it, or remove the connector that promised it."
574            .to_string(),
575        ParseErrorKind::ExpectedIdentifier => "I expected a name here — an identifier for a \
576            variable, function, or field. This position says which thing the statement acts \
577            on, so a keyword or symbol cannot stand in. What is the thing called? Use its \
578            declared name, or declare it first with Let."
579            .to_string(),
580        ParseErrorKind::RespectivelyLengthMismatch {
581            subject_count,
582            object_count,
583        } => {
584            format!(
585                "'Respectively' pairs the two lists one-to-one, but the subject side has \
586                {subject_count} element(s) and the object side has {object_count}. With \
587                uneven lists, something ends up with no partner. Which pairing did you \
588                intend? Even the lists out, or split the sentence so each pairing is \
589                explicit."
590            )
591        }
592        ParseErrorKind::TypeMismatch { expected, found } => {
593            format!(
594                "This slot is typed '{expected}', but the value here is '{found}'. LOGOS \
595                holds every value to its declared type — that agreement is what the later \
596                guarantees stand on. Which side is right, the annotation or the value? \
597                Change the one that is lying."
598            )
599        }
600        ParseErrorKind::TypeMismatchDetailed {
601            expected,
602            found,
603            context,
604        } => {
605            let ctx_note = if context.is_empty() {
606                String::new()
607            } else {
608                format!(" ({context})")
609            };
610            format!(
611                "I expected '{expected}' here but found '{found}'{ctx_note}. The two sides \
612                of this position must agree on one type. Which side has it right? Adjust \
613                the annotation or the value so they tell the same story."
614            )
615        }
616        ParseErrorKind::InfiniteType {
617            var_description,
618            type_description,
619        } => {
620            format!(
621                "This would make an infinite type: {var_description} would have to equal \
622                {type_description}, which contains it — a type inside itself, forever. This \
623                usually means a value is being folded into its own container. Did you mean \
624                to push into the collection rather than rebuild it? A named struct or one \
625                level of indirection breaks the cycle."
626            )
627        }
628        ParseErrorKind::ArityMismatch {
629            function,
630            expected,
631            found,
632        } => {
633            format!(
634                "'{function}' takes {expected} argument(s), but this call passes {found}. A \
635                call must fill every parameter — each one is a promise the function body \
636                relies on. Which parameter went missing, or which extra snuck in? Line the \
637                call up against the function's '## To' header."
638            )
639        }
640        ParseErrorKind::FieldNotFound {
641            type_name,
642            field_name,
643            available,
644        } => {
645            if available.is_empty() {
646                format!(
647                    "'{type_name}' has no field named '{field_name}'. A struct's fields are \
648                    fixed at its definition — reads cannot invent new ones. Did you mean \
649                    another field, or should the '## A {type_name} has:' definition grow a \
650                    '{field_name}'?"
651                )
652            } else {
653                format!(
654                    "'{type_name}' has no field named '{field_name}'. A struct's fields are \
655                    fixed at its definition — reads cannot invent new ones. Available \
656                    fields: {}. Did you mean one of those, or should the '## A {type_name} \
657                    has:' definition grow a '{field_name}'?",
658                    available.join(", ")
659                )
660            }
661        }
662        ParseErrorKind::NotAFunction { found_type } => {
663            format!(
664                "This tries to call a value of type '{found_type}', but only functions and \
665                closures can be called. Parentheses after a name mean 'invoke this'. Did \
666                you want a function with a similar name, or is this variable shadowing the \
667                function you meant?"
668            )
669        }
670        ParseErrorKind::InvalidRefinementPredicate => "This refinement predicate is not one \
671            I can check — refinements are comparisons over the declared name, like 'x > 0' \
672            or 'n < 100'. What must always be true of this value? State it as a simple \
673            comparison; anything richer belongs in an Assert."
674            .to_string(),
675        ParseErrorKind::GrammarError(msg) => {
676            format!(
677                "Grammar: {msg}. Small grammar slips change the logical reading, so I stop \
678                rather than guess. Which meaning did you intend? Adjust the wording — the \
679                right form usually reads aloud correctly."
680            )
681        }
682        ParseErrorKind::ScopeViolation(msg) => {
683            format!(
684                "Scope problem: {msg}. A pronoun can only reach referents its clause can \
685                see — things introduced under a negation or inside an 'or' are walled off \
686                from later sentences. Who is the pronoun meant to point at? Name the \
687                referent outright, or introduce it outside the wall."
688            )
689        }
690        ParseErrorKind::UnresolvedPronoun { gender, number } => {
691            let word = pronoun_word(gender, number);
692            format!(
693                "This pronoun ({word}) has nothing to refer to — no earlier sentence \
694                introduced a matching referent this clause can reach. Pronouns only look \
695                backward through accessible discourse. Who is {word} here? Introduce that \
696                referent in an earlier sentence, or use the name directly."
697            )
698        }
699        ParseErrorKind::TrailingTokens { found } => {
700            format!(
701                "I understood the sentence up to here, but the rest — beginning with {} — \
702                does not fit the structure I built. Accepting it would silently drop that \
703                meaning, and LOGOS never drops meaning. Is a connective missing, or are two \
704                sentences sharing one period? End the first thought with '.' and start \
705                fresh.",
706                describe_token(found)
707            )
708        }
709        ParseErrorKind::AstTooDeep { depth, max_depth } => {
710            format!(
711                "This program nests expressions or blocks {depth} levels deep, past the \
712                current {max_depth}-level limit — a tower this tall usually comes from \
713                generated code, and every downstream walker would overflow on it. Could \
714                each layer land in its own 'Let'? Intermediate bindings reset the depth to \
715                one; or raise the gate with LOGOS_MAX_AST_DEPTH={suggested} if your stacks \
716                are deep.",
717                suggested = (depth + depth / 4).next_power_of_two()
718            )
719        }
720        ParseErrorKind::Custom(msg) => msg.clone(),
721    }
722}
723
724#[cfg(test)]
725#[path = "../../logicaffeine_tests/unit/logicaffeine_language/error/tests.rs"]
726mod tests;