1use std::fmt;
13
14use oxdock_diagnostics::{Diagnostic, Span};
15
16pub type ParseResult<T> = std::result::Result<T, ParseError>;
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum ParseErrorKind {
24 Syntax,
27 InvalidSyntax { command: String },
30 UnknownCommand { name: String },
33 Structural { rule: String },
36 Validation { command: String },
38}
39
40#[derive(Debug, Clone, Default)]
50pub struct SpanContext<'a> {
51 pub line: usize,
53 pub col_start: Option<usize>,
55 pub col_end: Option<usize>,
57 pub source_line: Option<String>,
59 pub source: Option<&'a str>,
64 #[cfg(feature = "proc-macro-api")]
69 pub compiler_span: Option<proc_macro2::Span>,
70 pub step_index: Option<usize>,
72}
73
74impl<'a> SpanContext<'a> {
75 pub fn line_only(line: usize) -> Self {
78 Self {
79 line,
80 ..Self::default()
81 }
82 }
83
84 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 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 #[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 #[cfg(feature = "proc-macro-api")]
133 pub fn compiler_span(&self) -> Option<&proc_macro2::Span> {
134 self.compiler_span.as_ref()
135 }
136
137 pub fn with_step(mut self, step_index: usize) -> Self {
139 self.step_index = Some(step_index);
140 self
141 }
142}
143
144#[derive(Debug, Clone)]
150pub struct ParseError {
151 kind: ParseErrorKind,
152 line: usize,
153 detail: Box<ErrorDetail>,
154}
155
156#[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 message: String,
169 diagnostic: Option<Diagnostic>,
174}
175
176fn 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 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 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 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 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 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 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 pub fn diagnostic(&self) -> Option<&Diagnostic> {
335 self.detail.diagnostic.as_ref()
336 }
337
338 pub fn key(&self) -> Option<&'static str> {
340 self.detail.diagnostic.as_ref().map(Diagnostic::key)
341 }
342
343 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 pub fn with_step(mut self, step_index: usize) -> Self {
380 self.detail.step_index = Some(step_index);
381 self
382 }
383
384 pub fn with_found(mut self, found: Option<String>) -> Self {
388 self.detail.found = found;
389 self
390 }
391
392 pub fn with_expected(mut self, expected: Vec<String>) -> Self {
396 self.detail.expected = expected;
397 self
398 }
399
400 pub fn with_hint(mut self, hint: Option<String>) -> Self {
405 self.detail.hint = hint;
406 self
407 }
408
409 pub fn kind(&self) -> &ParseErrorKind {
411 &self.kind
412 }
413
414 pub fn line(&self) -> usize {
416 self.line
417 }
418
419 pub fn col_start(&self) -> Option<usize> {
421 self.detail.col_start
422 }
423
424 pub fn col_end(&self) -> Option<usize> {
426 self.detail.col_end
427 }
428
429 pub fn source_line(&self) -> Option<&str> {
431 self.detail.source_line.as_deref()
432 }
433
434 pub fn step_index(&self) -> Option<usize> {
436 self.detail.step_index
437 }
438
439 pub fn found(&self) -> Option<&str> {
441 self.detail.found.as_deref()
442 }
443
444 pub fn expected(&self) -> &[String] {
446 &self.detail.expected
447 }
448
449 pub fn hint(&self) -> Option<&str> {
451 self.detail.hint.as_deref()
452 }
453
454 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 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}