Skip to main content

drawlang_syntax/
lib.rs

1//! Lexer, parser, lossless-enough syntax tree, and formatter for drawlang.
2//!
3//! Design requirements (see docs/DESIGN.md):
4//! - Error recovery: report *all* errors in a file, never stop at the first.
5//! - Every token and node carries a span; diagnostics point at exact source.
6//! - Statements carry their comments so `drawlang fmt` round-trips them.
7
8pub mod ast;
9pub mod diag;
10pub mod fmt;
11pub mod lexer;
12pub mod parser;
13pub mod span;
14
15pub use diag::{Diagnostic, Severity};
16pub use span::{SourceFile, Span};
17
18pub struct Parsed {
19    pub file: ast::File,
20    pub diagnostics: Vec<Diagnostic>,
21}
22
23impl Parsed {
24    pub fn has_errors(&self) -> bool {
25        self.diagnostics
26            .iter()
27            .any(|d| d.severity == Severity::Error)
28    }
29}
30
31/// Lex + parse. Always returns an AST (possibly partial) plus every
32/// diagnostic found, sorted by source position.
33pub fn parse_source(src: &str) -> Parsed {
34    let lexed = lexer::lex(src);
35    let parsed = parser::parse(src, lexed.tokens);
36    let mut diagnostics = lexed.diagnostics;
37    diagnostics.extend(parsed.diagnostics);
38    diagnostics.sort_by_key(|d| {
39        (
40            d.primary_span().map(|s| s.start).unwrap_or(usize::MAX),
41            d.code,
42        )
43    });
44    Parsed {
45        file: parsed.file,
46        diagnostics,
47    }
48}