rantlr-core 0.1.0

Rantlr core: .gr lexer, parser, linter, and in-process runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! In-process interpreter: run a validated [`Grammar`] against test input.
//! Powers the Tauri playground without requiring generated host-language code.

use std::collections::BTreeMap;

use regex::Regex;
use serde::Serialize;

use crate::ast::{Expr, Grammar, GrammarItem, RuleDecl, TokenBody};
use crate::error::RantlrError;
use crate::span::Span;
use crate::token::BuiltinType;
use crate::{analyze, Diagnostic};

#[derive(Debug, Clone, Serialize)]
pub struct ParseTree {
    pub kind: String,
    pub text: String,
    pub children: Vec<ParseTree>,
}

#[derive(Debug, Clone, Serialize)]
pub struct AnalyzeResult {
    pub grammar_name: String,
    pub tree: ParseTree,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticJson {
    pub severity: String,
    pub kind: String,
    pub line: usize,
    pub column: usize,
    pub end_line: usize,
    pub end_column: usize,
    pub message: String,
    pub help: Option<String>,
    /// Stable code for code actions, e.g. `left-recursion`.
    pub code: Option<String>,
    pub fix_hint: Option<crate::FixHint>,
}

/// Parse + lint a `.gr` source; return structured diagnostics (empty = ok).
pub fn diagnose(source: &str) -> Vec<DiagnosticJson> {
    match crate::parser::parse(source) {
        Err(err) => vec![diagnostic_from_error(source, &err)],
        Ok(grammar) => {
            let mut out = Vec::new();
            for diag in crate::linter::lint_all(source, &grammar) {
                out.push(diagnostic_from_diag(source, &diag));
            }
            out
        }
    }
}

/// Validate grammar, then parse `test_input` with an in-process RD interpreter.
pub fn analyze_and_parse(source: &str, test_input: &str) -> Result<AnalyzeResult, RantlrError> {
    let grammar = analyze(source)?;
    let tree = parse_input(&grammar, test_input)?;
    Ok(AnalyzeResult {
        grammar_name: grammar.name,
        tree,
    })
}

pub fn parse_input(grammar: &Grammar, input: &str) -> Result<ParseTree, RantlrError> {
    let engine = Engine::from_grammar(grammar).map_err(|msg| {
        RantlrError::parse(input, msg, Span::from_offsets(0, 0))
    })?;
    engine.parse(input)
}

fn diagnostic_from_error(_source: &str, err: &RantlrError) -> DiagnosticJson {
    let end_col = err.column.saturating_add(1);
    DiagnosticJson {
        severity: "Error".into(),
        kind: format!("{:?}", err.kind),
        line: err.line,
        column: err.column,
        end_line: err.line,
        end_column: end_col,
        message: err.message.clone(),
        help: err.help.clone(),
        code: err.code.clone(),
        fix_hint: err.fix_hint.clone(),
    }
}

fn diagnostic_from_diag(source: &str, diag: &Diagnostic) -> DiagnosticJson {
    let (line, column) = diag.span.line_col(source);
    let end = diag.span.end.as_usize().min(source.len());
    let (end_line, end_column) = Span::from_offsets(end, end).line_col(source);
    DiagnosticJson {
        severity: format!("{:?}", diag.severity),
        kind: format!("{:?}", diag.kind),
        line,
        column,
        end_line,
        end_column: end_column.max(column + 1),
        message: diag.message.clone(),
        help: diag.help.clone(),
        code: diag.code.clone(),
        fix_hint: diag.fix.clone(),
    }
}

struct TokDef {
    name: String,
    re: Regex,
    skip: bool,
}

struct Engine<'g> {
    rules: BTreeMap<String, &'g RuleDecl>,
    start: String,
    tokens: Vec<TokDef>,
}

#[derive(Clone)]
struct LexTok {
    name: String,
    text: String,
}

struct Parser<'a> {
    tokens: &'a [LexTok],
    pos: usize,
    rules: &'a BTreeMap<String, &'a RuleDecl>,
}

impl<'g> Engine<'g> {
    fn from_grammar(grammar: &'g Grammar) -> Result<Self, String> {
        let mut rules = BTreeMap::new();
        let mut start = None;
        let mut declared = Vec::new();

        for item in &grammar.items {
            match item {
                GrammarItem::Rule(r) => {
                    if start.is_none() {
                        start = Some(r.name.clone());
                    }
                    rules.insert(r.name.clone(), r);
                }
                GrammarItem::Token(t) => {
                    declared.push((t.name.clone(), pattern_for_body(&t.body)?, t.skip));
                }
                _ => {}
            }
        }

        let start = start.ok_or_else(|| "grammar has no rules".to_string())?;

        let mut inferred: BTreeMap<String, String> = BTreeMap::new();
        for rule in rules.values() {
            collect_literals(&rule.body, &mut inferred);
        }

        let mut tokens = Vec::new();
        for (name, pat, skip) in declared {
            tokens.push(TokDef {
                name,
                re: Regex::new(&format!("^{pat}")).map_err(|e| e.to_string())?,
                skip,
            });
        }
        for (lit, name) in inferred {
            if tokens.iter().any(|t| t.name == name) {
                continue;
            }
            let pat = regex_escape(&lit);
            tokens.push(TokDef {
                name,
                re: Regex::new(&format!("^{pat}")).map_err(|e| e.to_string())?,
                skip: false,
            });
        }

        tokens.sort_by(|a, b| {
            // Prefer longer fixed literals; builtins last among equals.
            b.re.as_str().len().cmp(&a.re.as_str().len())
        });

        Ok(Self {
            rules,
            start,
            tokens,
        })
    }

    fn parse(&self, input: &str) -> Result<ParseTree, RantlrError> {
        let lexed = self.tokenize(input)?;
        let mut parser = Parser {
            tokens: &lexed,
            pos: 0,
            rules: &self.rules,
        };
        let tree = parser.parse_rule(&self.start)?;
        if !parser.at_end() {
            let t = parser.peek();
            return Err(RantlrError::parse(
                input,
                format!("unexpected trailing input (`{}`)", t.name),
                Span::from_offsets(0, 0),
            ));
        }
        Ok(tree)
    }

    fn tokenize(&self, input: &str) -> Result<Vec<LexTok>, RantlrError> {
        let mut out = Vec::new();
        let mut i = 0;
        let bytes = input.as_bytes();
        while i < input.len() {
            let rest = &input[i..];
            let mut best: Option<(usize, &TokDef)> = None;
            for tok in &self.tokens {
                if let Some(m) = tok.re.find(rest) {
                    if m.start() == 0 {
                        let len = m.end();
                        if best.map(|(l, _)| len > l).unwrap_or(true) {
                            best = Some((len, tok));
                        }
                    }
                }
            }
            let Some((len, tok)) = best else {
                let (line, col) = Span::from_offsets(i, i).line_col(input);
                return Err(RantlrError {
                    kind: crate::error::ErrorKind::Parse,
                    message: format!(
                        "unexpected character `{}`",
                        input[i..].chars().next().unwrap_or('?')
                    ),
                    line,
                    column: col,
                    snippet: crate::error::context_snippet(input, Span::from_offsets(i, i + 1)),
                    help: None,
                    code: None,
                    fix_hint: None,
                });
            };
            if !tok.skip {
                out.push(LexTok {
                    name: tok.name.clone(),
                    text: input[i..i + len].to_string(),
                });
            }
            i += len;
            let _ = bytes; // silence
        }
        out.push(LexTok {
            name: "EOF".into(),
            text: String::new(),
        });
        Ok(out)
    }
}

impl<'a> Parser<'a> {
    fn at_end(&self) -> bool {
        self.peek().name == "EOF"
    }

    fn peek(&self) -> &LexTok {
        &self.tokens[self.pos.min(self.tokens.len() - 1)]
    }

    fn mark(&self) -> usize {
        self.pos
    }

    fn reset(&mut self, m: usize) {
        self.pos = m;
    }

    fn expect_token(&mut self, name: &str) -> Result<ParseTree, RantlrError> {
        let tok = self.peek().clone();
        if tok.name == name {
            if tok.name != "EOF" {
                self.pos += 1;
            }
            return Ok(ParseTree {
                kind: name.into(),
                text: tok.text,
                children: vec![],
            });
        }
        Err(self.err(format!("expected `{name}`, found `{}`", tok.name)))
    }

    fn parse_rule(&mut self, name: &str) -> Result<ParseTree, RantlrError> {
        let rule = self
            .rules
            .get(name)
            .copied()
            .ok_or_else(|| self.err(format!("unknown rule `{name}`")))?;
        let children = self.parse_expr(&rule.body)?;
        let text = children.iter().map(|c| c.text.as_str()).collect::<String>();
        Ok(ParseTree {
            kind: name.into(),
            text,
            children,
        })
    }

    fn parse_expr(&mut self, expr: &Expr) -> Result<Vec<ParseTree>, RantlrError> {
        match expr {
            Expr::Seq { items } => {
                let mut out = Vec::new();
                for item in items {
                    out.extend(self.parse_expr(item)?);
                }
                Ok(out)
            }
            Expr::Group { body } => self.parse_expr(body),
            Expr::Ref { name, .. } => {
                if self.rules.contains_key(name) {
                    Ok(vec![self.parse_rule(name)?])
                } else {
                    Ok(vec![self.expect_token(name)?])
                }
            }
            Expr::Literal { value, .. } => {
                let tok_name = literal_token_name(value);
                Ok(vec![self.expect_token(&tok_name)?])
            }
            Expr::Optional { body } => {
                let m = self.mark();
                match self.parse_expr(body) {
                    Ok(nodes) => Ok(nodes),
                    Err(_) => {
                        self.reset(m);
                        Ok(vec![])
                    }
                }
            }
            Expr::Repeat { min, max, body } => {
                let mut out = Vec::new();
                let mut n = 0u64;
                loop {
                    if let Some(max) = *max {
                        if n >= max {
                            break;
                        }
                    }
                    let m = self.mark();
                    match self.parse_expr(body) {
                        Ok(nodes) => {
                            out.extend(nodes);
                            n += 1;
                        }
                        Err(_) => {
                            self.reset(m);
                            break;
                        }
                    }
                }
                if let Some(min) = *min {
                    if n < min {
                        return Err(self.err(format!("expected at least {min} repetitions")));
                    }
                }
                Ok(out)
            }
            Expr::Match { arms } | Expr::Alt { alts: arms } => {
                let mut last_err = None;
                for arm in arms {
                    let m = self.mark();
                    match self.parse_expr(arm) {
                        Ok(nodes) => return Ok(nodes),
                        Err(e) => {
                            self.reset(m);
                            last_err = Some(e);
                        }
                    }
                }
                Err(last_err.unwrap_or_else(|| self.err("no alternative matched")))
            }
        }
    }

    fn err(&self, message: impl Into<String>) -> RantlrError {
        RantlrError {
            kind: crate::error::ErrorKind::Parse,
            message: message.into(),
            line: 1,
            column: 1,
            snippet: String::new(),
            help: Some(format!("at token `{}`", self.peek().name)),
            code: None,
            fix_hint: None,
        }
    }
}

fn pattern_for_body(body: &TokenBody) -> Result<String, String> {
    Ok(match body {
        TokenBody::Literal(s) => regex_escape(s),
        TokenBody::Builtin(b) => builtin_regex(*b).to_string(),
    })
}

fn builtin_regex(b: BuiltinType) -> &'static str {
    match b {
        BuiltinType::Number => r"[0-9]+(?:\.[0-9]+)?",
        BuiltinType::QuotedString => r#"(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')"#,
        BuiltinType::Email => r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}",
        BuiltinType::Url => r"https?://[^\s]+",
        BuiltinType::DateTime => r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}:\d{2})?",
    }
}

fn regex_escape(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        if matches!(
            c,
            '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|'
        ) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

fn collect_literals(expr: &Expr, out: &mut BTreeMap<String, String>) {
    match expr {
        Expr::Alt { alts } | Expr::Seq { items: alts } | Expr::Match { arms: alts } => {
            for e in alts {
                collect_literals(e, out);
            }
        }
        Expr::Repeat { body, .. } | Expr::Optional { body } | Expr::Group { body } => {
            collect_literals(body, out);
        }
        Expr::Literal { value, .. } => {
            out.entry(value.clone())
                .or_insert_with(|| literal_token_name(value));
        }
        Expr::Ref { .. } => {}
    }
}

fn literal_token_name(lit: &str) -> String {
    let mapped: String = lit
        .chars()
        .map(|c| match c {
            '+' => "Plus".into(),
            '-' => "Minus".into(),
            '*' => "Star".into(),
            '/' => "Slash".into(),
            '(' => "LParen".into(),
            ')' => "RParen".into(),
            c if c.is_ascii_alphanumeric() => c.to_string(),
            _ => format!("U{:04X}", c as u32),
        })
        .collect();
    format!("Lit_{mapped}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn interprets_calculator() {
        let src = include_str!("../testdata/calculator.gr");
        let result = analyze_and_parse(src, "1+2*3").unwrap();
        assert_eq!(result.grammar_name, "Calculator");
        assert_eq!(result.tree.kind, "prog");
        assert_eq!(result.tree.text, "1+2*3");
    }

    #[test]
    fn diagnose_left_recursion() {
        let src = include_str!("../testdata/left_recursive.gr");
        let diags = diagnose(src);
        assert_eq!(diags.len(), 1);
        assert_eq!(diags[0].code.as_deref(), Some("left-recursion"));
    }
}