tabnas-alchemy 0.4.1

The alchemy grammar plugin and language for the tabnas parsing engine (declarative streaming transducers and renderers), and the types tabnas transducers and renderers share.
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
//! `ParserEvents/1`: the parser's rule passes, as a transducer part reads
//! them, and the tokens the parser did not take.
//!
//! A source over a tabnas parse (transduce's `ParserEventSource`) relays
//! each rule pass the engine reports to its `rule_done` subscribers as
//! one [`ParserEvent`]: an [`Open`](ParserEvent::Open) when a rule's open
//! pass has run, a [`Close`](ParserEvent::Close) when its close pass has,
//! and one [`End`](ParserEvent::End) after the last pass, only once the
//! engine has returned the parse's value, so a document is complete only
//! when it validated. A pass made inside a probe (the engine's
//! `RuleDone::probe`) is speculative, and the source drops it.
//!
//! A sink that asks for them ([`ParserSink::wants_tokens`]) also gets a
//! [`Token`](ParserEvent::Token) for each token the lexer gave and the
//! parser did not take, one of the grammar's ignored tokens (white space,
//! a line break, a comment), in source order among the passes: before
//! the first pass that consumed a token after it, and those still held
//! when the parse returns before the `End`. A sink that does not ask gets
//! none, and the source subscribes to no lexer event for it. Every token,
//! a pass's and a token item alike, carries its byte offset: where it
//! starts, in UTF-8 bytes from the document's start, the same in every
//! runtime.
//!
//! Containers never travel in parser events: a rule's node is handed on
//! only as a scalar ([`RulePass::value`]), so a transducer that wants a
//! container emits its start and end from the passes that open and close
//! it, and nothing in the stream grows with the document.
//!
//! The fixture encoding ([`ParserEvent::to_json`]) follows the JSON
//! events' encoding: an array whose first element names the event,
//! `["open", {"name": "map", "d": 1, "i": 3, "alt": {"p": "pair", "r": "",
//! "b": 0, "g": ["map", "json"]}, "tokens": [["#OB", "{", "{", 1, 1, 0]],
//! "forced": false, "n": {"pk": 0}}]`, a pass's token being `[name, val,
//! src, row, col, offset]`; `["token", {"name": "#SP", "val": null, "src":
//! " ", "row": 1, "col": 2, "offset": 1}]`; and `["end"]`. A field that is
//! absent (`alt` when the state declared no alternates, `value` when the
//! node is not a scalar or the pass is an open) is left out, so `"value":
//! null` is always a null scalar.

use crate::shared::datum::Datum;
use crate::shared::error::Fail;
use crate::shared::sink::Flow;

/// One item of `ParserEvents/1`.
#[derive(Clone, Debug, PartialEq)]
pub enum ParserEvent {
    /// A rule's open pass completed.
    Open(RulePass),
    /// A rule's close pass completed.
    Close(RulePass),
    /// A token the lexer gave and the parser did not take: one of the
    /// grammar's ignored tokens (white space, a line break, a comment).
    /// Only a sink that asks for them gets them
    /// ([`ParserSink::wants_tokens`]).
    Token(PassToken),
    /// The parse returned its value. Exactly one, after the last pass.
    End,
}

/// What one rule pass reports.
#[derive(Clone, Debug, PartialEq)]
pub struct RulePass {
    /// The rule's name (`map`, `pair`, `val`).
    pub name: Box<str>,
    /// The rule's depth on the stack: one more than the rule that pushed
    /// it, the same as the rule it replaced.
    pub d: u64,
    /// The rule's instance number in the parse.
    pub i: u64,
    /// The alternate that matched; `None` when the state declared none.
    pub alt: Option<PassAlt>,
    /// The tokens the pass consumed.
    pub tokens: Vec<PassToken>,
    /// A close synthesized by recovery.
    pub forced: bool,
    /// The rule's named counters, by name.
    pub n: Vec<(Box<str>, i64)>,
    /// The node's value, when it is a scalar at a close pass.
    pub value: Option<Datum>,
}

/// The alternate a pass matched.
#[derive(Clone, Debug, PartialEq)]
pub struct PassAlt {
    /// The rule it pushed, or empty.
    pub p: Box<str>,
    /// The rule it replaced the current one with, or empty.
    pub r: Box<str>,
    /// How many tokens it gave back.
    pub b: u64,
    /// Its groups.
    pub g: Vec<Box<str>>,
}

/// A token a pass consumed, or one a [`ParserEvent::Token`] carries.
#[derive(Clone, Debug, PartialEq)]
pub struct PassToken {
    /// The token's name (`#OB`, `#ST`, `#NR`).
    pub name: Box<str>,
    /// The token's value: a string's contents, a number's value.
    pub val: Datum,
    /// The source text the token was lexed from.
    pub src: Box<str>,
    pub row: u64,
    pub col: u64,
    /// Where the token starts: its offset in UTF-8 bytes from the
    /// document's start, the same in every runtime.
    pub offset: u64,
}

/// A consumer of `ParserEvents/1`: what a transducer part's head is, and
/// what a source pushes each rule pass into, synchronously, on the thread
/// that parses. As with [`crate::shared::Sink`], an `Err` aborts the run
/// and [`Flow::Stop`] asks the source to stop the parse.
pub trait ParserSink {
    fn event(&mut self, ev: &ParserEvent) -> Result<Flow, Fail>;

    /// Whether this sink takes [`ParserEvent::Token`] items. A source asks
    /// once, before the parse, and sends them only to a sink that answers
    /// `true`: a sink that does not ask gets the rule passes alone, and the
    /// source does none of the work token items take.
    fn wants_tokens(&self) -> bool {
        false
    }
}

impl ParserSink for Vec<ParserEvent> {
    fn event(&mut self, ev: &ParserEvent) -> Result<Flow, Fail> {
        self.push(ev.clone());
        Ok(Flow::Continue)
    }
}

impl<S: ParserSink + ?Sized> ParserSink for &mut S {
    fn event(&mut self, ev: &ParserEvent) -> Result<Flow, Fail> {
        (**self).event(ev)
    }

    fn wants_tokens(&self) -> bool {
        (**self).wants_tokens()
    }
}

impl<S: ParserSink + ?Sized> ParserSink for Box<S> {
    fn event(&mut self, ev: &ParserEvent) -> Result<Flow, Fail> {
        (**self).event(ev)
    }

    fn wants_tokens(&self) -> bool {
        (**self).wants_tokens()
    }
}

impl ParserEvent {
    /// The event's name in the encoding: `open`, `close`, `token` or `end`.
    pub fn name(&self) -> &'static str {
        match self {
            ParserEvent::Open(_) => "open",
            ParserEvent::Close(_) => "close",
            ParserEvent::Token(_) => "token",
            ParserEvent::End => "end",
        }
    }

    /// The pass an `Open` or a `Close` reports.
    pub fn pass(&self) -> Option<&RulePass> {
        match self {
            ParserEvent::Open(pass) | ParserEvent::Close(pass) => Some(pass),
            ParserEvent::Token(_) | ParserEvent::End => None,
        }
    }

    /// The fixture encoding: `["open", {...}]`, `["close", {...}]`,
    /// `["token", {...}]` or `["end"]`.
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::{json, Map, Value};
        if let ParserEvent::Token(t) = self {
            return json!([
                self.name(),
                {
                    "name": &*t.name,
                    "val": t.val.to_json(),
                    "src": &*t.src,
                    "row": t.row,
                    "col": t.col,
                    "offset": t.offset,
                }
            ]);
        }
        let Some(pass) = self.pass() else {
            return json!([self.name()]);
        };
        let mut rule = Map::new();
        rule.insert("name".into(), Value::from(&*pass.name));
        rule.insert("d".into(), Value::from(pass.d));
        rule.insert("i".into(), Value::from(pass.i));
        if let Some(alt) = &pass.alt {
            rule.insert(
                "alt".into(),
                json!({
                    "p": &*alt.p,
                    "r": &*alt.r,
                    "b": alt.b,
                    "g": alt.g.iter().map(|g| &**g).collect::<Vec<_>>(),
                }),
            );
        }
        rule.insert(
            "tokens".into(),
            Value::Array(
                pass.tokens
                    .iter()
                    .map(|t| json!([&*t.name, t.val.to_json(), &*t.src, t.row, t.col, t.offset]))
                    .collect(),
            ),
        );
        rule.insert("forced".into(), Value::Bool(pass.forced));
        rule.insert(
            "n".into(),
            Value::Object(
                pass.n
                    .iter()
                    .map(|(k, v)| (k.to_string(), Value::from(*v)))
                    .collect(),
            ),
        );
        if let Some(value) = &pass.value {
            rule.insert("value".into(), value.to_json());
        }
        json!([self.name(), Value::Object(rule)])
    }

    /// An event from its fixture encoding, or what is wrong with it.
    pub fn from_json(value: &serde_json::Value) -> Result<ParserEvent, String> {
        use serde_json::Value;
        let items = value
            .as_array()
            .ok_or_else(|| format!("a parser event is an array, not {value}"))?;
        let name = items
            .first()
            .and_then(Value::as_str)
            .ok_or_else(|| format!("a parser event starts with its name: {value}"))?;
        match (name, items.len()) {
            ("end", 1) => return Ok(ParserEvent::End),
            ("open" | "close", 2) => {}
            ("token", 2) => return token_from_json(&items[1], value).map(ParserEvent::Token),
            _ => return Err(format!("not a parser event: {value}")),
        }
        let rule = items[1]
            .as_object()
            .ok_or_else(|| format!("a rule pass is an object: {value}"))?;
        let text = |key: &str| -> Result<Box<str>, String> {
            rule.get(key)
                .and_then(Value::as_str)
                .map(Box::from)
                .ok_or_else(|| format!("a rule pass's :{key} is a string: {value}"))
        };
        let count = |v: Option<&Value>, key: &str| -> Result<u64, String> {
            v.and_then(Value::as_u64)
                .ok_or_else(|| format!("a rule pass's :{key} is a count: {value}"))
        };
        let alt = match rule.get("alt") {
            None => None,
            Some(alt) => {
                let field = |key: &str| -> Result<Box<str>, String> {
                    alt.get(key)
                        .and_then(Value::as_str)
                        .map(Box::from)
                        .ok_or_else(|| format!("an alternate's :{key} is a string: {value}"))
                };
                let g = alt
                    .get("g")
                    .and_then(Value::as_array)
                    .ok_or_else(|| format!("an alternate's :g is a vector: {value}"))?
                    .iter()
                    .map(|g| g.as_str().map(Box::from))
                    .collect::<Option<Vec<_>>>()
                    .ok_or_else(|| format!("an alternate's groups are strings: {value}"))?;
                Some(PassAlt {
                    p: field("p")?,
                    r: field("r")?,
                    b: count(alt.get("b"), "b")?,
                    g,
                })
            }
        };
        let tokens = rule
            .get("tokens")
            .and_then(Value::as_array)
            .ok_or_else(|| format!("a rule pass's :tokens is a vector: {value}"))?
            .iter()
            .map(|t| match t.as_array().map(Vec::as_slice) {
                Some([name, val, src, row, col, offset]) => Some(PassToken {
                    name: name.as_str()?.into(),
                    val: Datum::from_json(val),
                    src: src.as_str()?.into(),
                    row: row.as_u64()?,
                    col: col.as_u64()?,
                    offset: offset.as_u64()?,
                }),
                _ => None,
            })
            .collect::<Option<Vec<_>>>()
            .ok_or_else(|| format!("a token is [name, val, src, row, col, offset]: {value}"))?;
        let n = rule
            .get("n")
            .and_then(Value::as_object)
            .ok_or_else(|| format!("a rule pass's :n is a record: {value}"))?
            .iter()
            .map(|(k, v)| v.as_i64().map(|v| (Box::from(k.as_str()), v)))
            .collect::<Option<Vec<_>>>()
            .ok_or_else(|| format!("a rule pass's counters are integers: {value}"))?;
        let pass = RulePass {
            name: text("name")?,
            d: count(rule.get("d"), "d")?,
            i: count(rule.get("i"), "i")?,
            alt,
            tokens,
            forced: rule
                .get("forced")
                .and_then(Value::as_bool)
                .ok_or_else(|| format!("a rule pass's :forced is a boolean: {value}"))?,
            n,
            value: rule.get("value").map(Datum::from_json),
        };
        Ok(match name {
            "open" => ParserEvent::Open(pass),
            _ => ParserEvent::Close(pass),
        })
    }
}

/// A token item's record, `{"name", "val", "src", "row", "col", "offset"}`,
/// or what is wrong with it.
fn token_from_json(
    token: &serde_json::Value,
    value: &serde_json::Value,
) -> Result<PassToken, String> {
    use serde_json::Value;
    let record = token
        .as_object()
        .ok_or_else(|| format!("a token item is an object: {value}"))?;
    let text = |key: &str| -> Result<Box<str>, String> {
        record
            .get(key)
            .and_then(Value::as_str)
            .map(Box::from)
            .ok_or_else(|| format!("a token item's :{key} is a string: {value}"))
    };
    let count = |key: &str| -> Result<u64, String> {
        record
            .get(key)
            .and_then(Value::as_u64)
            .ok_or_else(|| format!("a token item's :{key} is a count: {value}"))
    };
    Ok(PassToken {
        name: text("name")?,
        val: Datum::from_json(record.get("val").unwrap_or(&Value::Null)),
        src: text("src")?,
        row: count("row")?,
        col: count("col")?,
        offset: count("offset")?,
    })
}

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

    #[test]
    fn the_encoding_round_trips_and_leaves_absent_fields_out() {
        let open = r##"["open",{"name":"map","d":1,"i":3,"alt":{"p":"pair","r":"","b":0,"g":["map","json"]},"tokens":[["#OB","{","{",1,1,0]],"forced":false,"n":{"pk":0}}]"##;
        let close =
            r#"["close",{"name":"val","d":2,"i":4,"tokens":[],"forced":true,"n":{},"value":null}]"#;
        let token = r##"["token",{"name":"#CM","val":"/* é */","src":"/* é */","row":2,"col":3,"offset":7}]"##;
        for text in [open, close, token, r#"["end"]"#] {
            let json: serde_json::Value = serde_json::from_str(text).unwrap();
            let event = ParserEvent::from_json(&json).unwrap();
            assert_eq!(event.to_json().to_string(), text);
        }
        let ParserEvent::Open(pass) =
            ParserEvent::from_json(&serde_json::from_str(open).unwrap()).unwrap()
        else {
            panic!("an open");
        };
        assert_eq!(pass.value, None, "an open pass has no value");
        assert_eq!(pass.alt.unwrap().p.as_ref(), "pair");
        assert_eq!(pass.tokens[0].offset, 0);
        let ParserEvent::Token(t) =
            ParserEvent::from_json(&serde_json::from_str(token).unwrap()).unwrap()
        else {
            panic!("a token item");
        };
        assert_eq!((t.name.as_ref(), t.offset), ("#CM", 7));
        assert_eq!(
            ParserEvent::Token(t).pass(),
            None,
            "a token item is no pass"
        );
    }

    #[test]
    fn a_sink_takes_no_token_items_unless_it_asks() {
        struct Asks;
        impl ParserSink for Asks {
            fn event(&mut self, _: &ParserEvent) -> Result<Flow, Fail> {
                Ok(Flow::Continue)
            }
            fn wants_tokens(&self) -> bool {
                true
            }
        }
        fn asks_for(sink: impl ParserSink) -> bool {
            sink.wants_tokens()
        }
        assert!(!Vec::<ParserEvent>::new().wants_tokens());
        let mut asks = Asks;
        assert!(asks_for(&mut asks), "a reference forwards the question");
        let boxed: Box<dyn ParserSink> = Box::new(Asks);
        assert!(boxed.wants_tokens(), "a box forwards the question");
    }

    #[test]
    fn a_malformed_event_says_what_is_wrong() {
        for text in [
            r#"{"open":1}"#,
            r#"["start"]"#,
            r#"["open"]"#,
            r#"["close",{"name":"x","d":-1,"i":0,"tokens":[],"forced":false,"n":{}}]"#,
            r##"["close",{"name":"x","d":1,"i":0,"tokens":[["#ST"]],"forced":false,"n":{}}]"##,
            r##"["close",{"name":"x","d":1,"i":0,"tokens":[["#ST","a","a",1,1]],"forced":false,"n":{}}]"##,
            r#"["token"]"#,
            r##"["token",{"name":"#SP","val":" ","src":" ","row":1,"col":1}]"##,
            r##"["token",{"name":"#SP","val":" ","src":" ","row":1,"col":1,"offset":-1}]"##,
        ] {
            let json: serde_json::Value = serde_json::from_str(text).unwrap();
            assert!(ParserEvent::from_json(&json).is_err(), "{text}");
        }
    }
}