tygr 0.3.0

Define your grammar once as Rust types and get a parser, printer, and EBNF presentation for free.
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
#[cfg(feature = "trace_one_node")]
use core::str;
#[cfg(feature = "trace_pos")]
use std::cmp::Ordering;
use std::{fmt::Display, marker::PhantomData};

/// Threaded parse state: the error `History` and the call-stack `Context`.
/// Both are behind feature flags, so `State` is a ZST when nothing is traced.
#[doc(hidden)]
pub struct State<'a> {
    #[cfg(feature = "trace_pos")]
    history: &'a mut History,
    #[cfg(feature = "trace_one_node")]
    context: Context<'a>,
    _marker: PhantomData<&'a ()>,
}

impl<'a> State<'a> {
    pub(crate) fn new(
        #[cfg(feature = "trace_pos")] history: &'a mut History,
        #[cfg(feature = "trace_one_node")] context: Context<'a>,
    ) -> Self {
        Self {
            #[cfg(feature = "trace_pos")]
            history,
            #[cfg(feature = "trace_one_node")]
            context,
            _marker: PhantomData,
        }
    }

    /// Reborrow for a nested call. `State` isn't `Copy` because it holds `&mut`.
    pub fn reborrow(&mut self) -> State<'_> {
        State {
            #[cfg(feature = "trace_pos")]
            history: &mut *self.history,
            #[cfg(feature = "trace_one_node")]
            context: self.context,
            _marker: PhantomData,
        }
    }

    /// Push a rule frame onto the context path (a no-op unless `context` is on).
    pub fn node(
        &mut self,
        #[allow(unused_variables)] node: &'static str,
        #[allow(unused_variables)] pos: usize,
    ) -> State<'_> {
        State {
            #[cfg(feature = "trace_pos")]
            history: &mut *self.history,
            #[cfg(feature = "trace_one_node")]
            context: self.context.node(node, pos),
            _marker: PhantomData,
        }
    }

    /// Record a failed expectation at `other_pos` (a no-op unless tracing).
    #[cfg(feature = "trace_pos")]
    #[inline]
    pub fn expect(
        &mut self,
        other_pos: usize,
        #[cfg(feature = "trace_one_node")] expectation: Expectation,
    ) {
        self.history.expect(
            #[cfg(feature = "trace_one_node")]
            self.context,
            other_pos,
            #[cfg(feature = "trace_one_node")]
            expectation,
        );
    }

    /// Probe with a throwaway history so a match or miss during lookahead
    /// doesn't pollute the real error trace.
    pub fn probe<R>(&mut self, f: impl FnOnce(State<'_>) -> R) -> R {
        #[cfg(feature = "trace_pos")]
        let mut scratch = History::new();
        f(State::new(
            #[cfg(feature = "trace_pos")]
            &mut scratch,
            #[cfg(feature = "trace_one_node")]
            self.context,
        ))
    }
}

#[cfg(feature = "trace_pos")]
#[derive(std::fmt::Debug, Default)]
pub(crate) struct History {
    #[cfg(feature = "trace_one_node")]
    traces: Vec<Trace>,
    #[cfg(feature = "trace_pos")]
    pos: usize,
}

#[cfg(feature = "trace_pos")]
impl History {
    pub(crate) fn new() -> Self {
        History::default()
    }

    pub(crate) fn into_error(self) -> Error {
        #[cfg(feature = "trace_one_node")]
        let traces = {
            let mut traces = self.traces;
            for trace in &mut traces {
                trace.context.reverse()
            }
            traces
        };
        Error {
            #[cfg(feature = "trace_one_node")]
            traces,
            #[cfg(feature = "trace_pos")]
            pos: self.pos,
        }
    }
}

/// One candidate for what would have matched at a [`Trace`]'s recorded position.
#[derive(std::fmt::Debug, PartialEq, Eq)]
pub enum Expectation {
    /// A case-sensitive literal (from `StringEq!`) didn't match.
    StringEq(String),
    /// A case-insensitive literal (from `StringEqCI!`) didn't match.
    StringEqCI(String),
    /// No character satisfying this [`CharClass`](crate::CharClass) was found.
    CharClass(&'static str),
    /// A `#[grammar(validated)]` type parsed successfully but
    /// [`Validate::validate`](crate::Validate::validate) rejected it.
    Valid {
        /// The rejected type's own [`GrammarRule::NAME`](crate::GrammarRule::NAME).
        node: &'static str,
        /// The raw text that was parsed and then rejected.
        text: String,
        /// The rejection message from [`Validation::be_valid`](crate::Validation::be_valid).
        be_valid: &'static str,
    },
    /// A `GrammarFromStr`/`GrammarFromOther`/`GrammarTryFromOther`-derived
    /// type matched its source grammar but failed to convert.
    GrammarFrom {
        /// The raw text that matched the source grammar but failed to convert.
        from: String,
        /// The target type's own [`GrammarRule::NAME`](crate::GrammarRule::NAME).
        into: &'static str,
        /// The conversion error's `Display` text.
        fail: String,
    },
}

#[cfg(feature = "trace_one_node")]
fn escape_string(s: &str) -> String {
    s.chars()
        .map(|char| match char {
            '\t' => "\\t".to_string(),
            '\n' => "\\n".to_string(),
            '\r' => "\\r".to_string(),
            '"' => "\\\"".to_string(),
            char => char.to_string(),
        })
        .collect()
}

#[cfg(feature = "trace_one_node")]
impl Display for Expectation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Expectation::StringEq(s) => write!(f, "\"{}\"", escape_string(s)),
            Expectation::StringEqCI(s) => {
                write!(f, "\"{}\" (case-insensitive)", escape_string(s))
            }
            Expectation::CharClass(c) => write!(f, "Char of {c}"),
            Expectation::Valid {
                node,
                text,
                be_valid,
            } => write!(
                f,
                "The proceeding {node} \"{}\" to {be_valid}",
                escape_string(text)
            ),
            Expectation::GrammarFrom { from, into, fail } => {
                write!(f, "From {from} to {into}: {fail}")
            }
        }
    }
}

/// One recorded parse attempt at [`Error::pos`] — a rule call chain and what
/// it expected to find there. Multiple `Trace`s at the same position are
/// candidates: any one of them matching would have let the parse continue.
#[derive(std::fmt::Debug, PartialEq, Eq)]
pub struct Trace {
    /// The nearest enclosing named rule(s), outermost first. Only ever more
    /// than one element with `trace_all_nodes` enabled.
    pub context: Vec<Frame>,
    /// What was expected at this position.
    pub expectation: Expectation,
}

#[cfg(feature = "trace_pos")]
impl History {
    pub fn expect(
        &mut self,
        #[cfg(feature = "trace_one_node")] context: Context<'_>,
        other_pos: usize,
        #[cfg(feature = "trace_one_node")] expectation: Expectation,
    ) {
        #[cfg(feature = "trace_one_node")]
        let trace = || Trace {
            context: context.to_vec(),
            expectation,
        };
        match self.pos.cmp(&other_pos) {
            Ordering::Equal => {
                #[cfg(feature = "trace_one_node")]
                {
                    self.traces.push(trace())
                }
            }
            Ordering::Less => {
                self.pos = other_pos;
                #[cfg(feature = "trace_one_node")]
                {
                    self.traces = vec![trace()];
                }
            }
            Ordering::Greater => (),
        }
    }
}

/// Immutable call-stack path threaded by value; a ZST unless `context` is on.
#[doc(hidden)]
#[derive(Clone, Copy, Default)]
pub struct Context<'a>(
    #[cfg(feature = "trace_one_node")] Option<ContextNode<'a>>,
    PhantomData<&'a ()>,
);

#[cfg(feature = "trace_one_node")]
#[derive(Clone, Copy)]
struct ContextNode<'a> {
    first: Frame,
    #[cfg(feature = "trace_one_node")]
    _marker: PhantomData<&'a ()>,
    #[cfg(feature = "trace_all_nodes")]
    remaining: &'a Context<'a>,
}

impl<'a> Context<'a> {
    #[cfg(feature = "trace_one_node")]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    #[cfg(feature = "trace_one_node")]
    fn to_vec(self) -> Vec<Frame> {
        #[cfg(feature = "trace_all_nodes")]
        {
            let mut result = vec![];
            let mut cursor = self;
            while let Some(node) = cursor.0 {
                result.push(node.first);
                cursor = *node.remaining;
            }
            result
        }
        #[cfg(not(feature = "trace_all_nodes"))]
        {
            self.0.map(|node| vec![node.first]).unwrap_or_default()
        }
    }

    #[cfg(feature = "trace_one_node")]
    fn node(&'a self, node: &'static str, pos: usize) -> Context<'a> {
        Context(
            Some(ContextNode {
                first: Frame { node, pos },
                #[cfg(feature = "trace_one_node")]
                _marker: PhantomData,
                #[cfg(feature = "trace_all_nodes")]
                remaining: self,
            }),
            PhantomData,
        )
    }
}

/// One named rule call in a [`Trace`]'s [`context`](Trace::context).
#[derive(Clone, Copy, std::fmt::Debug, PartialEq, Eq)]
pub struct Frame {
    /// The rule's name, as in [`GrammarRule::NAME`](crate::GrammarRule::NAME).
    pub node: &'static str,
    /// The position this rule was entered at.
    pub pos: usize,
}

/// A parse failure. Carries no detail unless the relevant `trace_*` feature
/// is enabled (see the crate-level feature flag table); use [`Error::pos`]
/// and [`Error::traces`] to inspect it rather than the fields directly, since
/// those degrade gracefully across feature configurations.
#[derive(PartialEq, Eq)]
pub struct Error {
    #[cfg(feature = "trace_one_node")]
    #[doc(hidden)]
    pub traces: Vec<Trace>,
    #[cfg(feature = "trace_pos")]
    #[doc(hidden)]
    pub pos: usize,
}

/// Build the parse `Error`. When `history` is off, `Error` carries no data.
pub(crate) fn make_error(#[cfg(feature = "trace_pos")] history: History) -> Error {
    #[cfg(feature = "trace_pos")]
    {
        history.into_error()
    }
    #[cfg(not(feature = "trace_pos"))]
    {
        Error {}
    }
}

impl Error {
    /// The candidate expectations recorded at the deepest position reached.
    /// Empty unless `trace_one_node` is enabled.
    pub fn traces(&self) -> &[Trace] {
        #[cfg(feature = "trace_one_node")]
        {
            &self.traces
        }
        #[cfg(not(feature = "trace_one_node"))]
        {
            &[]
        }
    }

    /// The deepest byte offset the parser reached before giving up. `0`
    /// unless `trace_pos` is enabled.
    pub fn pos(&self) -> usize {
        #[cfg(feature = "trace_pos")]
        {
            self.pos
        }
        #[cfg(not(feature = "trace_pos"))]
        {
            0
        }
    }
}

impl Display for Error {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "parse error")?;
        #[cfg(feature = "trace_pos")]
        write!(f, " at byte {}", self.pos)?;
        #[cfg(feature = "trace_one_node")]
        {
            let mut lines: Vec<String> = self
                .traces
                .iter()
                .map(
                    |Trace {
                         context,
                         expectation,
                     }| {
                        if let Some(frame) = context.last()
                            && frame.pos == self.pos
                        {
                            frame.node.to_string()
                        } else {
                            format!("{expectation}")
                        }
                    },
                )
                .collect();
            lines.sort();
            lines.dedup();
            if !lines.is_empty() {
                writeln!(f, ", expected:")?;
                for line in lines {
                    writeln!(f, "\t- {line}")?;
                }
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for Error {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        #[cfg(feature = "trace_one_node")]
        {
            writeln!(f, ":{}", self.pos)?;
            writeln!(f, "Looking for")?;
            for trace in &self.traces {
                writeln!(
                    f,
                    "\t- {}!{}",
                    trace
                        .context
                        .iter()
                        .map(|Frame { node, pos }| { format!("{node}@:{pos}") })
                        .collect::<Vec<String>>()
                        .join("/"),
                    trace.expectation
                )?;
            }
        }
        Ok(())
    }
}