Skip to main content

oxdock_parser/
error.rs

1//! Typed parse errors for the OxDock DSL (issue #143).
2//!
3//! Beginners must always learn WHAT they did wrong: line and column,
4//! what was found, what was expected, and a concrete example. A syntax
5//! error must never surface as a bare `unknown command: X`.
6//!
7//! String and file parsers populate line, column span, and source line
8//! from lexer spans. Token stream parsers (`macro_input.rs`) set
9//! `source_line` to `None` and forward the compiler span instead, since
10//! `proc_macro2::Span` carries coordinates but not source text.
11
12use std::fmt;
13
14/// Backwards compatible result alias for parser entrypoints.
15/// Public functions return `ParseResult` directly instead of erasing
16/// into `anyhow::Error`, so downstream crates match statically.
17pub type ParseResult<T> = std::result::Result<T, ParseError>;
18
19/// Machine readable classification of a parse failure.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum ParseErrorKind {
22    /// Low-level syntax failure: the input never reached lowering
23    /// (lexer rejection or token-level structural failure).
24    Syntax,
25    /// First word is a known command or structural keyword, but the
26    /// rest of the line is malformed. Never report these as unknown.
27    InvalidSyntax { command: String },
28    /// First word matches no known command or keyword in any case.
29    /// Reserved strictly for truly unknown names.
30    UnknownCommand { name: String },
31    /// Guard, block, scope, or structural keyword failure
32    /// (`WITH_IO`, `LET`, `FOR`, `IF`, `{{`, `}}`, guards).
33    Structural { rule: String },
34    /// Arity, flag, or static argument type failure for a known command.
35    Validation { command: String },
36}
37
38/// Location and diagnostic context threaded through lowering.
39///
40/// String parsers fill `col_start`, `col_end`, and `source_line` from
41/// lexer spans. Token stream parsers leave `source_line` as `None`;
42/// macro call sites keep their own `proc_macro2::Span` for
43/// `syn::Error` conversion (a span handle is not `Send`/`Sync`, so it
44/// never lives inside `ParseError`, which must stay convertible into
45/// `anyhow::Error`). Integer coordinates extracted from the span are
46/// attached here instead.
47#[derive(Debug, Clone, Default)]
48pub struct SpanContext<'a> {
49    /// 1-based line number. Always populated on the string path.
50    pub line: usize,
51    /// 1-based start column. `None` on token stream paths without locations.
52    pub col_start: Option<usize>,
53    /// 1-based end column (inclusive). `None` on token stream paths.
54    pub col_end: Option<usize>,
55    /// Raw source line text. `None` on token stream paths.
56    pub source_line: Option<String>,
57    /// Full script text (borrowed, zero copy). Lets span refinement
58    /// resolve the exact source line for any line number, including
59    /// multi-line bodies, without ever faking text. `None` on token
60    /// stream paths and bare line fallbacks.
61    pub source: Option<&'a str>,
62    /// Compiler span for macro contexts, kept at the call site for
63    /// `syn::Error` conversion. Gated on the same feature as
64    /// `macro_input.rs` to avoid new mandatory parser dependencies.
65    /// Never transferred into `ParseError`.
66    #[cfg(feature = "proc-macro-api")]
67    pub compiler_span: Option<proc_macro2::Span>,
68    /// Zero-based step index in the parsed script, when known.
69    pub step_index: Option<usize>,
70}
71
72impl<'a> SpanContext<'a> {
73    /// Bare line context. Used only where no span is available
74    /// (direct `lower_command` calls, end of script errors).
75    pub fn line_only(line: usize) -> Self {
76        Self {
77            line,
78            ..Self::default()
79        }
80    }
81
82    /// Full string path context with column span and source text.
83    pub fn full(line: usize, col_start: usize, col_end: usize, source_line: String) -> Self {
84        Self {
85            line,
86            col_start: Some(col_start),
87            col_end: Some(col_end),
88            source_line: Some(source_line),
89            source: None,
90            #[cfg(feature = "proc-macro-api")]
91            compiler_span: None,
92            step_index: None,
93        }
94    }
95
96    /// Attach the full script text for multi-line span resolution.
97    pub fn with_source(mut self, source: &'a str) -> Self {
98        if self.source_line.is_none() {
99            self.source_line = source
100                .lines()
101                .nth(self.line.saturating_sub(1))
102                .map(str::to_string);
103        }
104        self.source = Some(source);
105        self
106    }
107
108    /// Token stream context: coordinates without source text.
109    /// The caller keeps the span handle for `syn::Error` conversion;
110    /// only the integer coordinates travel in the context.
111    #[cfg(feature = "proc-macro-api")]
112    pub fn from_compiler_span(
113        line: usize,
114        col_start: Option<usize>,
115        col_end: Option<usize>,
116        span: proc_macro2::Span,
117    ) -> Self {
118        Self {
119            line,
120            col_start,
121            col_end,
122            source_line: None,
123            source: None,
124            compiler_span: Some(span),
125            step_index: None,
126        }
127    }
128
129    /// Borrowed compiler span for `syn::Error` conversion at the call site.
130    #[cfg(feature = "proc-macro-api")]
131    pub fn compiler_span(&self) -> Option<&proc_macro2::Span> {
132        self.compiler_span.as_ref()
133    }
134
135    /// Attach a step index (builder style).
136    pub fn with_step(mut self, step_index: usize) -> Self {
137        self.step_index = Some(step_index);
138        self
139    }
140}
141
142/// Typed parse error with structured diagnostics and a
143/// backwards compatible `Display` rendering.
144///
145/// Diagnostic detail lives behind a `Box` so `ParseResult` stays small
146/// in `Result` returns (cold path allocation only).
147#[derive(Debug, Clone)]
148pub struct ParseError {
149    kind: ParseErrorKind,
150    line: usize,
151    detail: Box<ErrorDetail>,
152}
153
154/// Heap stored diagnostic detail for [`ParseError`].
155#[derive(Debug, Clone)]
156struct ErrorDetail {
157    col_start: Option<usize>,
158    col_end: Option<usize>,
159    source_line: Option<String>,
160    step_index: Option<usize>,
161    found: Option<String>,
162    expected: Vec<String>,
163    hint: Option<String>,
164    /// Legacy message body. `Display` appends the location block,
165    /// so existing `expect_error_contains` assertions keep passing.
166    message: String,
167}
168
169impl ParseError {
170    fn new(
171        kind: ParseErrorKind,
172        line: usize,
173        ctx: &SpanContext,
174        found: Option<String>,
175        expected: Vec<String>,
176        hint: Option<String>,
177        message: String,
178    ) -> Self {
179        Self {
180            kind,
181            line,
182            detail: Box::new(ErrorDetail {
183                col_start: ctx.col_start,
184                col_end: ctx.col_end,
185                source_line: ctx.source_line.clone(),
186                step_index: ctx.step_index,
187                found,
188                expected,
189                hint,
190                message,
191            }),
192        }
193    }
194    /// Low-level syntax failure. `message` must already contain the
195    /// `parse error (expected: ...)` header; the location block is
196    /// appended by `Display` unless already present.
197    pub fn syntax(
198        message: String,
199        expected: Vec<String>,
200        hint: Option<String>,
201        ctx: &SpanContext,
202    ) -> Self {
203        Self::new(
204            ParseErrorKind::Syntax,
205            ctx.line,
206            ctx,
207            None,
208            expected,
209            hint,
210            message,
211        )
212    }
213
214    /// Known command or keyword with malformed arguments.
215    pub fn invalid_syntax(
216        command: &str,
217        message: String,
218        found: Option<String>,
219        expected: Vec<String>,
220        hint: Option<String>,
221        ctx: &SpanContext,
222    ) -> Self {
223        Self::new(
224            ParseErrorKind::InvalidSyntax {
225                command: command.to_string(),
226            },
227            ctx.line,
228            ctx,
229            found,
230            expected,
231            hint,
232            message,
233        )
234    }
235
236    /// Truly unknown command name. Callers must ensure `classify`
237    /// sent keyword led lines to `invalid_syntax` instead.
238    pub fn unknown_command(
239        name: &str,
240        message: String,
241        hint: Option<String>,
242        ctx: &SpanContext,
243    ) -> Self {
244        Self::new(
245            ParseErrorKind::UnknownCommand {
246                name: name.to_string(),
247            },
248            ctx.line,
249            ctx,
250            Some(name.to_string()),
251            Vec::new(),
252            hint,
253            message,
254        )
255    }
256
257    /// Structural failure (guards, blocks, `WITH_IO`, `LET`, `FOR`, `IF`).
258    pub fn structural(rule: &str, message: String, ctx: &SpanContext) -> Self {
259        Self::new(
260            ParseErrorKind::Structural {
261                rule: rule.to_string(),
262            },
263            ctx.line,
264            ctx,
265            None,
266            Vec::new(),
267            None,
268            message,
269        )
270    }
271
272    /// Arity, flag, or static type failure for a known command.
273    pub fn validation(command: &str, message: String, ctx: &SpanContext) -> Self {
274        Self::new(
275            ParseErrorKind::Validation {
276                command: command.to_string(),
277            },
278            ctx.line,
279            ctx,
280            None,
281            Vec::new(),
282            None,
283            message,
284        )
285    }
286
287    /// Enrich an error produced without span context (e.g. from a
288    /// direct `lower_command` call) with the caller's location.
289    /// Existing span fields are only overwritten when the current
290    /// value is `None`, so lexer spans are never clobbered.
291    pub fn with_span(mut self, ctx: &SpanContext) -> Self {
292        if self.line == 0 {
293            self.line = ctx.line;
294        }
295        let detail = &mut self.detail;
296        if detail.col_start.is_none() {
297            detail.col_start = ctx.col_start;
298        }
299        if detail.col_end.is_none() {
300            detail.col_end = ctx.col_end;
301        }
302        if detail.source_line.is_none() {
303            detail.source_line = ctx.source_line.clone();
304        }
305        if detail.step_index.is_none() {
306            detail.step_index = ctx.step_index;
307        }
308        self
309    }
310
311    /// Attach a step index (builder style).
312    pub fn with_step(mut self, step_index: usize) -> Self {
313        self.detail.step_index = Some(step_index);
314        self
315    }
316
317    /// Machine readable kind.
318    pub fn kind(&self) -> &ParseErrorKind {
319        &self.kind
320    }
321
322    /// 1-based line number (`0` means unknown, direct calls only).
323    pub fn line(&self) -> usize {
324        self.line
325    }
326
327    /// 1-based start column, when known.
328    pub fn col_start(&self) -> Option<usize> {
329        self.detail.col_start
330    }
331
332    /// 1-based end column (inclusive), when known.
333    pub fn col_end(&self) -> Option<usize> {
334        self.detail.col_end
335    }
336
337    /// Raw source line text, when available.
338    pub fn source_line(&self) -> Option<&str> {
339        self.detail.source_line.as_deref()
340    }
341
342    /// Zero-based step index, when known.
343    pub fn step_index(&self) -> Option<usize> {
344        self.detail.step_index
345    }
346
347    /// What was found (command name or rendered args), when known.
348    pub fn found(&self) -> Option<&str> {
349        self.detail.found.as_deref()
350    }
351
352    /// Expected syntax alternatives.
353    pub fn expected(&self) -> &[String] {
354        &self.detail.expected
355    }
356
357    /// Concrete hint with an example, when known.
358    pub fn hint(&self) -> Option<&str> {
359        self.detail.hint.as_deref()
360    }
361
362    /// Render the caret block for the stored span, if complete.
363    fn caret_block(&self) -> Option<String> {
364        let (start, end) = match (self.detail.col_start, self.detail.col_end) {
365            (Some(s), Some(e)) => (s, e),
366            _ => return None,
367        };
368        let line_text = self.detail.source_line.as_deref()?;
369        if self.line == 0 || start == 0 {
370            return None;
371        }
372        let width = end.saturating_sub(start).saturating_add(1).max(1);
373        let pad = " ".repeat(start.saturating_sub(1));
374        let carets = "^".repeat(width.min(80));
375        Some(format!(
376            "\n  --> line {line}, col {start}-{end}\n  {line} | {line_text}\n    | {pad}{carets}",
377            line = self.line,
378        ))
379    }
380}
381
382impl fmt::Display for ParseError {
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        write!(f, "{}", self.detail.message)?;
385        if let Some(block) = self.caret_block() {
386            // Messages already ending with the caret block do not duplicate it.
387            if !self.detail.message.contains("--> line") {
388                write!(f, "{block}")?;
389            }
390        } else if self.line > 0 && !self.detail.message.contains(&format!("line {}", self.line)) {
391            write!(f, "\n  --> line {}", self.line)?;
392        }
393        Ok(())
394    }
395}
396
397impl std::error::Error for ParseError {}