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
14use oxdock_diagnostics::{Diagnostic, Span};
15
16/// Backwards compatible result alias for parser entrypoints.
17/// Public functions return `ParseResult` directly instead of erasing
18/// into `anyhow::Error`, so downstream crates match statically.
19pub type ParseResult<T> = std::result::Result<T, ParseError>;
20
21/// Machine readable classification of a parse failure.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum ParseErrorKind {
24    /// Low-level syntax failure: the input never reached lowering
25    /// (lexer rejection or token-level structural failure).
26    Syntax,
27    /// First word is a known command or structural keyword, but the
28    /// rest of the line is malformed. Never report these as unknown.
29    InvalidSyntax { command: String },
30    /// First word matches no known command or keyword in any case.
31    /// Reserved strictly for truly unknown names.
32    UnknownCommand { name: String },
33    /// Guard, block, scope, or structural keyword failure
34    /// (`WITH_IO`, `LET`, `FOR`, `IF`, `{{`, `}}`, guards).
35    Structural { rule: String },
36    /// Arity, flag, or static argument type failure for a known command.
37    Validation { command: String },
38}
39
40/// Location and diagnostic context threaded through lowering.
41///
42/// String parsers fill `col_start`, `col_end`, and `source_line` from
43/// lexer spans. Token stream parsers leave `source_line` as `None`;
44/// macro call sites keep their own `proc_macro2::Span` for
45/// `syn::Error` conversion (a span handle is not `Send`/`Sync`, so it
46/// never lives inside `ParseError`, which must stay convertible into
47/// `anyhow::Error`). Integer coordinates extracted from the span are
48/// attached here instead.
49#[derive(Debug, Clone, Default)]
50pub struct SpanContext<'a> {
51    /// 1-based line number. Always populated on the string path.
52    pub line: usize,
53    /// 1-based start column. `None` on token stream paths without locations.
54    pub col_start: Option<usize>,
55    /// 1-based end column (inclusive). `None` on token stream paths.
56    pub col_end: Option<usize>,
57    /// Raw source line text. `None` on token stream paths.
58    pub source_line: Option<String>,
59    /// Full script text (borrowed, zero copy). Lets span refinement
60    /// resolve the exact source line for any line number, including
61    /// multi-line bodies, without ever faking text. `None` on token
62    /// stream paths and bare line fallbacks.
63    pub source: Option<&'a str>,
64    /// Compiler span for macro contexts, kept at the call site for
65    /// `syn::Error` conversion. Gated on the same feature as
66    /// `macro_input.rs` to avoid new mandatory parser dependencies.
67    /// Never transferred into `ParseError`.
68    #[cfg(feature = "proc-macro-api")]
69    pub compiler_span: Option<proc_macro2::Span>,
70    /// Zero-based step index in the parsed script, when known.
71    pub step_index: Option<usize>,
72}
73
74impl<'a> SpanContext<'a> {
75    /// Bare line context. Used only where no span is available
76    /// (direct `lower_command` calls, end of script errors).
77    pub fn line_only(line: usize) -> Self {
78        Self {
79            line,
80            ..Self::default()
81        }
82    }
83
84    /// Full string path context with column span and source text.
85    pub fn full(line: usize, col_start: usize, col_end: usize, source_line: String) -> Self {
86        Self {
87            line,
88            col_start: Some(col_start),
89            col_end: Some(col_end),
90            source_line: Some(source_line),
91            source: None,
92            #[cfg(feature = "proc-macro-api")]
93            compiler_span: None,
94            step_index: None,
95        }
96    }
97
98    /// Attach the full script text for multi-line span resolution.
99    pub fn with_source(mut self, source: &'a str) -> Self {
100        if self.source_line.is_none() {
101            self.source_line = source
102                .lines()
103                .nth(self.line.saturating_sub(1))
104                .map(str::to_string);
105        }
106        self.source = Some(source);
107        self
108    }
109
110    /// Token stream context: coordinates without source text.
111    /// The caller keeps the span handle for `syn::Error` conversion;
112    /// only the integer coordinates travel in the context.
113    #[cfg(feature = "proc-macro-api")]
114    pub fn from_compiler_span(
115        line: usize,
116        col_start: Option<usize>,
117        col_end: Option<usize>,
118        span: proc_macro2::Span,
119    ) -> Self {
120        Self {
121            line,
122            col_start,
123            col_end,
124            source_line: None,
125            source: None,
126            compiler_span: Some(span),
127            step_index: None,
128        }
129    }
130
131    /// Borrowed compiler span for `syn::Error` conversion at the call site.
132    #[cfg(feature = "proc-macro-api")]
133    pub fn compiler_span(&self) -> Option<&proc_macro2::Span> {
134        self.compiler_span.as_ref()
135    }
136
137    /// Attach a step index (builder style).
138    pub fn with_step(mut self, step_index: usize) -> Self {
139        self.step_index = Some(step_index);
140        self
141    }
142}
143
144/// Typed parse error with structured diagnostics and a
145/// backwards compatible `Display` rendering.
146///
147/// Diagnostic detail lives behind a `Box` so `ParseResult` stays small
148/// in `Result` returns (cold path allocation only).
149#[derive(Debug, Clone)]
150pub struct ParseError {
151    kind: ParseErrorKind,
152    line: usize,
153    detail: Box<ErrorDetail>,
154}
155
156/// Heap stored diagnostic detail for [`ParseError`].
157#[derive(Debug, Clone)]
158struct ErrorDetail {
159    col_start: Option<usize>,
160    col_end: Option<usize>,
161    source_line: Option<String>,
162    step_index: Option<usize>,
163    found: Option<String>,
164    expected: Vec<String>,
165    hint: Option<String>,
166    /// Legacy message body. `Display` appends the location block,
167    /// so existing `expect_error_contains` assertions keep passing.
168    message: String,
169    /// Owning keyed diagnostic, when this error was built through
170    /// [`ParseError::from_diagnostic`]. Carries the stable key and
171    /// structured fields; `message` mirrors its rendered text so
172    /// `Display` output is unchanged during migration.
173    diagnostic: Option<Diagnostic>,
174}
175
176/// Build the transport [`Span`] for a [`SpanContext`]. Returns `None`
177/// when the line is unknown (`0`), so direct `lower_command` errors
178/// stay spanless until [`ParseError::with_span`] enrichment.
179fn span_from_ctx(ctx: &SpanContext) -> Option<Span> {
180    if ctx.line == 0 {
181        return None;
182    }
183    match (ctx.col_start, ctx.col_end, ctx.source_line.clone()) {
184        (Some(start), Some(end), Some(line_text)) => {
185            Some(Span::full(ctx.line, start, end, line_text))
186        }
187        _ => Some(Span::line_only(ctx.line)),
188    }
189}
190
191impl ParseError {
192    fn new(
193        kind: ParseErrorKind,
194        line: usize,
195        ctx: &SpanContext,
196        found: Option<String>,
197        expected: Vec<String>,
198        hint: Option<String>,
199        message: String,
200    ) -> Self {
201        Self {
202            kind,
203            line,
204            detail: Box::new(ErrorDetail {
205                col_start: ctx.col_start,
206                col_end: ctx.col_end,
207                source_line: ctx.source_line.clone(),
208                step_index: ctx.step_index,
209                found,
210                expected,
211                hint,
212                message,
213                diagnostic: None,
214            }),
215        }
216    }
217    /// Low-level syntax failure. `message` must already contain the
218    /// `parse error (expected: ...)` header; the location block is
219    /// appended by `Display` unless already present.
220    pub fn syntax(
221        message: String,
222        expected: Vec<String>,
223        hint: Option<String>,
224        ctx: &SpanContext,
225    ) -> Self {
226        Self::new(
227            ParseErrorKind::Syntax,
228            ctx.line,
229            ctx,
230            None,
231            expected,
232            hint,
233            message,
234        )
235    }
236
237    /// Known command or keyword with malformed arguments.
238    pub fn invalid_syntax(
239        command: &str,
240        message: String,
241        found: Option<String>,
242        expected: Vec<String>,
243        hint: Option<String>,
244        ctx: &SpanContext,
245    ) -> Self {
246        Self::new(
247            ParseErrorKind::InvalidSyntax {
248                command: command.to_string(),
249            },
250            ctx.line,
251            ctx,
252            found,
253            expected,
254            hint,
255            message,
256        )
257    }
258
259    /// Truly unknown command name. Callers must ensure `classify`
260    /// sent keyword led lines to `invalid_syntax` instead.
261    pub fn unknown_command(
262        name: &str,
263        message: String,
264        hint: Option<String>,
265        ctx: &SpanContext,
266    ) -> Self {
267        Self::new(
268            ParseErrorKind::UnknownCommand {
269                name: name.to_string(),
270            },
271            ctx.line,
272            ctx,
273            Some(name.to_string()),
274            Vec::new(),
275            hint,
276            message,
277        )
278    }
279
280    /// Structural failure (guards, blocks, `WITH_IO`, `LET`, `FOR`, `IF`).
281    pub fn structural(rule: &str, message: String, ctx: &SpanContext) -> Self {
282        Self::new(
283            ParseErrorKind::Structural {
284                rule: rule.to_string(),
285            },
286            ctx.line,
287            ctx,
288            None,
289            Vec::new(),
290            None,
291            message,
292        )
293    }
294
295    /// Arity, flag, or static type failure for a known command.
296    pub fn validation(command: &str, message: String, ctx: &SpanContext) -> Self {
297        Self::new(
298            ParseErrorKind::Validation {
299                command: command.to_string(),
300            },
301            ctx.line,
302            ctx,
303            None,
304            Vec::new(),
305            None,
306            message,
307        )
308    }
309
310    /// Build from an owning keyed [`Diagnostic`]. The diagnostic's
311    /// rendered message becomes the legacy body (so `Display` output
312    /// is unchanged) and its hint is forwarded when the diagnostic
313    /// carries one. The `ctx` span is synced onto both the error and
314    /// the embedded diagnostic, so `err.diagnostic().span()` matches
315    /// the error's span; later [`ParseError::with_span`] enrichment
316    /// keeps them in sync the same way.
317    pub fn from_diagnostic(
318        kind: ParseErrorKind,
319        diagnostic: Diagnostic,
320        ctx: &SpanContext,
321    ) -> Self {
322        let message = diagnostic.message().to_string();
323        let hint = diagnostic.hint().map(str::to_string);
324        let diagnostic = match span_from_ctx(ctx) {
325            Some(span) => diagnostic.with_span(span),
326            None => diagnostic,
327        };
328        let mut err = Self::new(kind, ctx.line, ctx, None, Vec::new(), hint, message);
329        err.detail.diagnostic = Some(diagnostic);
330        err
331    }
332
333    /// Owning keyed diagnostic, when built via [`ParseError::from_diagnostic`].
334    pub fn diagnostic(&self) -> Option<&Diagnostic> {
335        self.detail.diagnostic.as_ref()
336    }
337
338    /// Stable dotted key of the owning diagnostic, when present.
339    pub fn key(&self) -> Option<&'static str> {
340        self.detail.diagnostic.as_ref().map(Diagnostic::key)
341    }
342
343    /// Enrich an error produced without span context (e.g. from a
344    /// direct `lower_command` call) with the caller's location.
345    /// Existing span fields are only overwritten when the current
346    /// value is `None`, so lexer spans are never clobbered. The
347    /// embedded diagnostic (when present) is synced the same way:
348    /// a span is attached only while it has none.
349    pub fn with_span(mut self, ctx: &SpanContext) -> Self {
350        if self.line == 0 {
351            self.line = ctx.line;
352        }
353        let detail = &mut self.detail;
354        if detail.col_start.is_none() {
355            detail.col_start = ctx.col_start;
356        }
357        if detail.col_end.is_none() {
358            detail.col_end = ctx.col_end;
359        }
360        if detail.source_line.is_none() {
361            detail.source_line = ctx.source_line.clone();
362        }
363        if detail.step_index.is_none() {
364            detail.step_index = ctx.step_index;
365        }
366        if detail
367            .diagnostic
368            .as_ref()
369            .is_some_and(|d| d.span().is_none())
370            && let Some(span) = span_from_ctx(ctx)
371            && let Some(d) = detail.diagnostic.take()
372        {
373            detail.diagnostic = Some(d.with_span(span));
374        }
375        self
376    }
377
378    /// Attach a step index (builder style).
379    pub fn with_step(mut self, step_index: usize) -> Self {
380        self.detail.step_index = Some(step_index);
381        self
382    }
383
384    /// Attach the found text (builder style). Used by the
385    /// `invalid_syntax` path, whose helper computes it alongside the
386    /// diagnostic.
387    pub fn with_found(mut self, found: Option<String>) -> Self {
388        self.detail.found = found;
389        self
390    }
391
392    /// Attach expected syntax alternatives (builder style). Used by
393    /// the `invalid_syntax` path to keep `expected()` informative
394    /// through the diagnostic migration.
395    pub fn with_expected(mut self, expected: Vec<String>) -> Self {
396        self.detail.expected = expected;
397        self
398    }
399
400    /// Attach the hint (builder style). Used by the `invalid_syntax`
401    /// and `unknown_command` paths: the hint rides inline in the
402    /// diagnostic message for legacy `Display` parity, and here so
403    /// the `hint()` accessor keeps working.
404    pub fn with_hint(mut self, hint: Option<String>) -> Self {
405        self.detail.hint = hint;
406        self
407    }
408
409    /// Machine readable kind.
410    pub fn kind(&self) -> &ParseErrorKind {
411        &self.kind
412    }
413
414    /// 1-based line number (`0` means unknown, direct calls only).
415    pub fn line(&self) -> usize {
416        self.line
417    }
418
419    /// 1-based start column, when known.
420    pub fn col_start(&self) -> Option<usize> {
421        self.detail.col_start
422    }
423
424    /// 1-based end column (inclusive), when known.
425    pub fn col_end(&self) -> Option<usize> {
426        self.detail.col_end
427    }
428
429    /// Raw source line text, when available.
430    pub fn source_line(&self) -> Option<&str> {
431        self.detail.source_line.as_deref()
432    }
433
434    /// Zero-based step index, when known.
435    pub fn step_index(&self) -> Option<usize> {
436        self.detail.step_index
437    }
438
439    /// What was found (command name or rendered args), when known.
440    pub fn found(&self) -> Option<&str> {
441        self.detail.found.as_deref()
442    }
443
444    /// Expected syntax alternatives.
445    pub fn expected(&self) -> &[String] {
446        &self.detail.expected
447    }
448
449    /// Concrete hint with an example, when known.
450    pub fn hint(&self) -> Option<&str> {
451        self.detail.hint.as_deref()
452    }
453
454    /// Render the caret block for the stored span, if complete.
455    fn caret_block(&self) -> Option<String> {
456        let (start, end) = match (self.detail.col_start, self.detail.col_end) {
457            (Some(s), Some(e)) => (s, e),
458            _ => return None,
459        };
460        let line_text = self.detail.source_line.as_deref()?;
461        if self.line == 0 || start == 0 {
462            return None;
463        }
464        let width = end.saturating_sub(start).saturating_add(1).max(1);
465        let pad = " ".repeat(start.saturating_sub(1));
466        let carets = "^".repeat(width.min(80));
467        Some(format!(
468            "\n  --> line {line}, col {start}-{end}\n  {line} | {line_text}\n    | {pad}{carets}",
469            line = self.line,
470        ))
471    }
472}
473
474impl fmt::Display for ParseError {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476        write!(f, "{}", self.detail.message)?;
477        if let Some(block) = self.caret_block() {
478            // Messages already ending with the caret block do not duplicate it.
479            if !self.detail.message.contains("--> line") {
480                write!(f, "{block}")?;
481            }
482        } else if self.line > 0 && !self.detail.message.contains(&format!("line {}", self.line)) {
483            write!(f, "\n  --> line {}", self.line)?;
484        }
485        Ok(())
486    }
487}
488
489impl std::error::Error for ParseError {}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494
495    #[test]
496    fn from_diagnostic_syncs_span_onto_both() {
497        let ctx = SpanContext::full(3, 2, 5, "WRITE $x".to_string());
498        let diag = crate::diagnostics::missing_argument("WRITE", "path");
499        let err = ParseError::from_diagnostic(
500            ParseErrorKind::Validation {
501                command: "WRITE".to_string(),
502            },
503            diag,
504            &ctx,
505        );
506        assert_eq!(err.line(), 3);
507        let span = err
508            .diagnostic()
509            .expect("payload")
510            .span()
511            .expect("span synced");
512        assert_eq!(span.line, 3);
513        assert_eq!(span.col_start, Some(2));
514        assert_eq!(span.col_end, Some(5));
515        assert_eq!(span.source_line.as_deref(), Some("WRITE $x"));
516    }
517
518    #[test]
519    fn with_span_enrichment_reaches_embedded_diagnostic() {
520        let diag = crate::diagnostics::unknown_flag("WRITE", "--nope");
521        let err = ParseError::from_diagnostic(
522            ParseErrorKind::Validation {
523                command: "WRITE".to_string(),
524            },
525            diag,
526            &SpanContext::line_only(0),
527        );
528        assert!(err.diagnostic().expect("payload").span().is_none());
529        let ctx = SpanContext::full(7, 1, 4, "WRITE --nope".to_string());
530        let err = err.with_span(&ctx);
531        assert_eq!(err.line(), 7);
532        let span = err
533            .diagnostic()
534            .expect("payload")
535            .span()
536            .expect("span synced");
537        assert_eq!(span.line, 7);
538        assert_eq!(span.col_start, Some(1));
539    }
540}