grammar-kit 0.8.0

Runtime support library for parsers generated by syn-grammar.
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
#![doc = include_str!("../README.md")]

#[cfg(feature = "syn")]
use proc_macro2::Span;
use std::collections::HashSet;
#[cfg(feature = "syn")]
use syn::parse::discouraged::Speculative;
#[cfg(feature = "syn")]
use syn::parse::ParseStream;
#[cfg(feature = "syn")]
use syn::Result;

#[cfg(feature = "testing")]
pub mod testing;

/// Generic symbol table that tracks variable definitions in nested scopes.
#[derive(Clone, Default)]
pub struct ScopeStack {
    scopes: Vec<HashSet<String>>,
}

impl ScopeStack {
    pub fn new() -> Self {
        Self {
            scopes: vec![HashSet::new()],
        }
    }

    pub fn enter_scope(&mut self) {
        self.scopes.push(HashSet::new());
    }

    pub fn exit_scope(&mut self) {
        if self.scopes.len() > 1 {
            self.scopes.pop();
        }
    }

    pub fn define(&mut self, name: impl Into<String>) {
        if let Some(scope) = self.scopes.last_mut() {
            scope.insert(name.into());
        }
    }

    pub fn is_defined(&self, name: &str) -> bool {
        for scope in self.scopes.iter().rev() {
            if scope.contains(name) {
                return true;
            }
        }
        false
    }

    pub fn scopes(&self) -> &Vec<HashSet<String>> {
        &self.scopes
    }
}

#[cfg(all(feature = "rt", feature = "syn"))]
#[derive(Clone)]
struct ErrorState {
    err: syn::Error,
    is_deep: bool,
}

/// Holds the state for backtracking and error reporting.
/// This must be passed mutably through the parsing chain.
#[cfg(feature = "rt")]
#[derive(Clone)]
pub struct ParseContext {
    is_fatal: bool,
    #[cfg(feature = "syn")]
    best_error: Option<ErrorState>,
    pub scopes: ScopeStack,
    rule_stack: Vec<String>,
    #[cfg(feature = "syn")]
    pub last_span: Option<Span>,
}

#[cfg(feature = "rt")]
impl ParseContext {
    pub fn new() -> Self {
        Self {
            is_fatal: false,
            #[cfg(feature = "syn")]
            best_error: None,
            scopes: ScopeStack::new(),
            rule_stack: Vec::new(),
            #[cfg(feature = "syn")]
            last_span: None,
        }
    }

    pub fn set_fatal(&mut self, fatal: bool) {
        self.is_fatal = fatal;
    }

    pub fn check_fatal(&self) -> bool {
        self.is_fatal
    }

    pub fn enter_rule(&mut self, name: &str) {
        self.rule_stack.push(name.to_string());
    }

    pub fn exit_rule(&mut self) {
        self.rule_stack.pop();
    }

    /// Records an error if it is "deeper" than the current best error.
    #[cfg(feature = "syn")]
    pub fn record_error(&mut self, err: syn::Error, start_span: Span) {
        // Heuristic: Compare the error location to the start of the attempt.
        let is_deep = err.span().start() != start_span.start();

        // Enrich error with rule name if available
        let err = if let Some(rule_name) = self.rule_stack.last() {
            let msg = format!("Error in rule '{}': {}", rule_name, err);
            syn::Error::new(err.span(), msg)
        } else {
            err
        };

        match &mut self.best_error {
            None => {
                self.best_error = Some(ErrorState { err, is_deep });
            }
            Some(existing) => {
                // If new is deep and existing is shallow -> Overwrite
                if is_deep && !existing.is_deep {
                    self.best_error = Some(ErrorState { err, is_deep });
                }
            }
        }
    }

    #[cfg(feature = "syn")]
    pub fn take_best_error(&mut self) -> Option<syn::Error> {
        self.best_error.take().map(|s| s.err)
    }

    // --- Span Tracking ---

    #[cfg(feature = "syn")]
    pub fn record_span(&mut self, span: Span) {
        self.last_span = Some(span);
    }

    #[cfg(feature = "syn")]
    pub fn check_whitespace(&self, next_span: Span) -> bool {
        if let Some(last) = self.last_span {
            // Check if they are NOT adjacent (end != start)
            last.end() != next_span.start()
        } else {
            // No previous token? Treat as valid (start of file)
            true
        }
    }

    // --- Symbol Table Methods ---

    pub fn enter_scope(&mut self) {
        self.scopes.enter_scope();
    }

    pub fn exit_scope(&mut self) {
        self.scopes.exit_scope();
    }

    pub fn define(&mut self, name: impl Into<String>) {
        self.scopes.define(name);
    }

    pub fn is_defined(&self, name: &str) -> bool {
        self.scopes.is_defined(name)
    }

    // --- Inspection Methods ---

    pub fn scopes(&self) -> &Vec<HashSet<String>> {
        self.scopes.scopes()
    }

    pub fn rule_stack(&self) -> &Vec<String> {
        &self.rule_stack
    }
}

#[cfg(feature = "rt")]
impl Default for ParseContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Encapsulates a speculative parse attempt.
/// Requires passing the ParseContext to manage error state.
#[cfg(all(feature = "rt", feature = "syn"))]
#[inline]
pub fn attempt<T, F>(input: ParseStream, ctx: &mut ParseContext, parser: F) -> Result<Option<T>>
where
    F: FnOnce(ParseStream, &mut ParseContext) -> Result<T>,
{
    let was_fatal = ctx.check_fatal();
    ctx.set_fatal(false);

    // Snapshot symbol table, rule stack, and last_span
    let scopes_snapshot = ctx.scopes.clone();
    let rule_stack_snapshot = ctx.rule_stack.clone();
    let last_span_snapshot = ctx.last_span;

    let start_span = input.span();
    let fork = input.fork();

    // Pass ctx into the closure
    let res = parser(&fork, ctx);

    let is_now_fatal = ctx.check_fatal();

    match res {
        Ok(val) => {
            input.advance_to(&fork);
            ctx.set_fatal(was_fatal);
            // We KEEP the last_span updated by the successful attempt
            Ok(Some(val))
        }
        Err(e) => {
            if is_now_fatal {
                // Restore state
                ctx.scopes = scopes_snapshot;
                ctx.rule_stack = rule_stack_snapshot;
                ctx.last_span = last_span_snapshot;

                ctx.set_fatal(true);
                Err(e)
            } else {
                ctx.set_fatal(was_fatal);
                // Record error BEFORE restoring state to capture inner rule context
                ctx.record_error(e, start_span);

                // Restore state
                ctx.scopes = scopes_snapshot;
                ctx.rule_stack = rule_stack_snapshot;
                ctx.last_span = last_span_snapshot;

                Ok(None)
            }
        }
    }
}

/// Executes a parser on a fork, returning the result but NEVER advancing the input.
/// Restores ParseContext state (scopes, last_span) to what it was before.
#[cfg(all(feature = "rt", feature = "syn"))]
#[inline]
pub fn peek<T, F>(input: ParseStream, ctx: &mut ParseContext, parser: F) -> Result<T>
where
    F: FnOnce(ParseStream, &mut ParseContext) -> Result<T>,
{
    let fork = input.fork();

    // Snapshot state
    let scopes_snapshot = ctx.scopes.clone();
    let rule_stack_snapshot = ctx.rule_stack.clone();
    let last_span_snapshot = ctx.last_span;

    let res = parser(&fork, ctx);

    // Always restore state because we are peeking (state side effects should not persist)
    ctx.scopes = scopes_snapshot;
    ctx.rule_stack = rule_stack_snapshot;
    ctx.last_span = last_span_snapshot;

    res
}

/// Executes a parser on a fork.
/// If it SUCCEEDS, returns Err("unexpected match").
/// If it FAILS, returns Ok(()).
/// Never advances input. Restores state.
#[cfg(all(feature = "rt", feature = "syn"))]
#[inline]
pub fn not_check<T, F>(input: ParseStream, ctx: &mut ParseContext, parser: F) -> Result<()>
where
    F: FnOnce(ParseStream, &mut ParseContext) -> Result<T>,
{
    let fork = input.fork();

    // Snapshot state
    let scopes_snapshot = ctx.scopes.clone();
    let rule_stack_snapshot = ctx.rule_stack.clone();
    let last_span_snapshot = ctx.last_span;

    // Disable fatal errors for the check to allow backtracking/failure
    let was_fatal = ctx.check_fatal();
    ctx.set_fatal(false);

    let res = parser(&fork, ctx);

    // Restore fatal flag
    ctx.set_fatal(was_fatal);

    // Restore state
    ctx.scopes = scopes_snapshot;
    ctx.rule_stack = rule_stack_snapshot;
    ctx.last_span = last_span_snapshot;

    match res {
        Ok(_) => Err(syn::Error::new(input.span(), "unexpected match")),
        Err(_) => Ok(()),
    }
}

/// Wrapper around attempt used specifically for recovery blocks.
#[cfg(all(feature = "rt", feature = "syn"))]
#[inline]
pub fn attempt_recover<T, F>(
    input: ParseStream,
    ctx: &mut ParseContext,
    parser: F,
) -> Result<Option<T>>
where
    F: FnOnce(ParseStream, &mut ParseContext) -> Result<T>,
{
    let was_fatal = ctx.check_fatal();
    ctx.set_fatal(false);

    // Snapshot symbol table and rule stack
    let scopes_snapshot = ctx.scopes.clone();
    let rule_stack_snapshot = ctx.rule_stack.clone();
    let last_span_snapshot = ctx.last_span;

    let start_span = input.span();
    let fork = input.fork();

    let res = parser(&fork, ctx);

    // Always restore fatal state, ignoring whatever happened inside.
    ctx.set_fatal(was_fatal);

    match res {
        Ok(val) => {
            input.advance_to(&fork);
            // Keep last_span
            Ok(Some(val))
        }
        Err(e) => {
            // Record error BEFORE restoring state
            ctx.record_error(e, start_span);

            // Restore state
            ctx.scopes = scopes_snapshot;
            ctx.rule_stack = rule_stack_snapshot;
            ctx.last_span = last_span_snapshot;

            Ok(None)
        }
    }
}

// --- Stateless Helpers (No Context Needed) ---

#[cfg(all(feature = "rt", feature = "syn"))]
#[inline]
pub fn parse_ident(input: ParseStream) -> Result<syn::Ident> {
    input.parse()
}

#[cfg(all(feature = "rt", feature = "syn"))]
#[inline]
pub fn parse_int<T: std::str::FromStr>(input: ParseStream) -> Result<T>
where
    T::Err: std::fmt::Display,
{
    input.parse::<syn::LitInt>()?.base10_parse()
}

#[cfg(all(feature = "rt", feature = "syn"))]
pub fn skip_until(input: ParseStream, predicate: impl Fn(ParseStream) -> bool) -> Result<()> {
    while !input.is_empty() && !predicate(input) {
        if input.parse::<proc_macro2::TokenTree>().is_err() {
            break;
        }
    }
    Ok(())
}

#[cfg(all(test, feature = "rt", feature = "syn"))]
mod tests {
    use super::*;

    #[test]
    fn test_rule_name_in_error() {
        let mut ctx = ParseContext::new();
        ctx.enter_rule("test_rule");

        let err = syn::Error::new(Span::call_site(), "expected something");
        ctx.record_error(err, Span::call_site());

        let final_err = ctx.take_best_error().unwrap();
        assert_eq!(
            final_err.to_string(),
            "Error in rule 'test_rule': expected something"
        );
    }

    #[test]
    fn test_nested_rule_name_in_error() {
        let mut ctx = ParseContext::new();
        ctx.enter_rule("outer");
        ctx.enter_rule("inner");

        let err = syn::Error::new(Span::call_site(), "fail");
        ctx.record_error(err, Span::call_site());

        let final_err = ctx.take_best_error().unwrap();
        assert_eq!(final_err.to_string(), "Error in rule 'inner': fail");
    }

    #[test]
    fn test_attempt_captures_rule_context() {
        use syn::parse::Parser;

        let mut ctx = ParseContext::new();

        let parser = |input: ParseStream| {
            ctx.enter_rule("outer");

            // We simulate an attempt that fails.
            // attempt returns Result<Option<T>>.
            // If the closure returns Err, attempt records it and returns Ok(None) (if not fatal).
            let _: Option<()> = attempt(input, &mut ctx, |_input, _ctx| {
                Err(syn::Error::new(Span::call_site(), "parse failed"))
            })?;

            ctx.exit_rule();
            Ok(())
        };

        // We parse an empty string. The attempt fails immediately.
        // The outer parser returns Ok(()).
        // But we check ctx.best_error.
        let _ = parser.parse_str("");

        let err = ctx.take_best_error().expect("Error should be recorded");
        assert_eq!(err.to_string(), "Error in rule 'outer': parse failed");
    }
}