parsuna 0.1.0

Parsuna: recoverable, pull-based parsers with precise errors
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
use std::fmt::Write;
use std::path::PathBuf;

use crate::codegen::common::pascal;
use crate::codegen::EmittedFile;
use crate::lowering::{DispatchLeaf, DispatchTree, Op, StateTable};

pub fn emit(st: &StateTable) -> Vec<EmittedFile> {
    let mut s = String::new();

    emit_header(&mut s, st);
    emit_constants(&mut s, st);
    emit_dfa(&mut s, st);
    emit_tables(&mut s, st);
    emit_drive(&mut s, st);
    emit_public_api(&mut s, st);

    let stem = if st.grammar_name.is_empty() {
        "parser".to_string()
    } else {
        st.grammar_name.clone()
    };
    vec![EmittedFile {
        path: PathBuf::from(format!("{}.go", stem)),
        contents: s,
    }]
}

fn emit_header(s: &mut String, st: &StateTable) {
    let name = if st.grammar_name.is_empty() {
        "parser"
    } else {
        st.grammar_name.as_str()
    };

    writeln!(s, "// Code generated by parsuna; DO NOT EDIT.").unwrap();
    writeln!(s, "//").unwrap();
    writeln!(
        s,
        "// Pull-based, recoverable parser. Call one of the ParseXxx entry points"
    )
    .unwrap();
    writeln!(
        s,
        "// and repeatedly call NextEvent on the returned *parsunart.Parser to walk"
    )
    .unwrap();
    writeln!(s, "// the parse as a flat Event stream.").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "package {}", name).unwrap();
    writeln!(s).unwrap();
    writeln!(s, "import (").unwrap();
    writeln!(s, "\t\"io\"").unwrap();
    writeln!(s).unwrap();
    writeln!(s, "\trt \"parsuna.dev/parsuna-rt-go\"").unwrap();
    writeln!(s, ")").unwrap();
    writeln!(s).unwrap();
    // Re-export commonly used runtime types so callers don't need to
    // import parsuna-rt directly for the basic event-stream API.
    writeln!(s, "// Event types re-exported from the runtime.").unwrap();
    writeln!(s, "type Pos = rt.Pos").unwrap();
    writeln!(s, "type Span = rt.Span").unwrap();
    writeln!(s, "type Token = rt.Token").unwrap();
    writeln!(s, "type ParseError = rt.ParseError").unwrap();
    writeln!(s, "type Event = rt.Event").unwrap();
    writeln!(s, "type EventTag = rt.EventTag").unwrap();
    writeln!(s, "const (").unwrap();
    writeln!(s, "\tEvEnter = rt.EvEnter").unwrap();
    writeln!(s, "\tEvExit  = rt.EvExit").unwrap();
    writeln!(s, "\tEvToken = rt.EvToken").unwrap();
    writeln!(s, "\tEvError = rt.EvError").unwrap();
    writeln!(s, ")").unwrap();
    writeln!(s).unwrap();
}

fn emit_constants(s: &mut String, st: &StateTable) {
    writeln!(s, "// TokenKind enumerates every token this grammar can emit.").unwrap();
    writeln!(
        s,
        "// TkEof marks end-of-input and TkError is produced by the lexer when"
    )
    .unwrap();
    writeln!(s, "// no pattern matches at the current position.").unwrap();
    writeln!(s, "type TokenKind int16").unwrap();
    writeln!(s, "const (").unwrap();
    writeln!(s, "\tTkEof   TokenKind = 0").unwrap();
    writeln!(s, "\tTkError TokenKind = -1").unwrap();
    for t in &st.tokens {
        writeln!(s, "\tTk{} TokenKind = {}", pascal(&t.name), t.kind).unwrap();
    }
    writeln!(s, ")").unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "// TokenKindName returns the grammar-declared name of a token kind,"
    )
    .unwrap();
    writeln!(s, "// or \"?\" if the kind is not recognised.").unwrap();
    writeln!(s, "func TokenKindName(k TokenKind) string {{").unwrap();
    writeln!(s, "\tswitch k {{").unwrap();
    writeln!(s, "\tcase TkEof: return \"EOF\"").unwrap();
    writeln!(s, "\tcase TkError: return \"ERROR\"").unwrap();
    for t in &st.tokens {
        writeln!(s, "\tcase Tk{}: return \"{}\"", pascal(&t.name), t.name).unwrap();
    }
    writeln!(s, "\t}}").unwrap();
    writeln!(s, "\treturn \"?\"").unwrap();
    writeln!(s, "}}").unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "// RuleKind enumerates this grammar's non-fragment rules."
    )
    .unwrap();
    writeln!(s, "type RuleKind uint16").unwrap();
    writeln!(s, "const (").unwrap();
    for (i, n) in st.rule_kinds.iter().enumerate() {
        writeln!(s, "\tRk{} RuleKind = {}", pascal(n), i).unwrap();
    }
    writeln!(s, ")").unwrap();
    writeln!(s).unwrap();
    writeln!(
        s,
        "// RuleKindName returns the grammar-declared name of a rule kind,"
    )
    .unwrap();
    writeln!(s, "// or \"?\" if the kind is not recognised.").unwrap();
    writeln!(s, "func RuleKindName(k RuleKind) string {{").unwrap();
    writeln!(s, "\tswitch k {{").unwrap();
    for n in &st.rule_kinds {
        writeln!(s, "\tcase Rk{}: return \"{}\"", pascal(n), n).unwrap();
    }
    writeln!(s, "\t}}").unwrap();
    writeln!(s, "\treturn \"?\"").unwrap();
    writeln!(s, "}}").unwrap();
    writeln!(s).unwrap();
}

fn token_const(st: &StateTable, kind: i16) -> String {
    if kind == 0 {
        return "TkEof".to_string();
    }
    if kind == -1 {
        return "TkError".to_string();
    }
    match st.tokens.iter().find(|t| t.kind == kind) {
        Some(t) => format!("Tk{}", pascal(&t.name)),
        None => panic!("unknown token id {} while emitting Go backend", kind),
    }
}

fn rule_const(st: &StateTable, kind: u16) -> String {
    let name = st
        .rule_kinds
        .get(kind as usize)
        .unwrap_or_else(|| panic!("unknown rule kind id {} while emitting Go backend", kind));
    format!("Rk{}", pascal(name))
}

fn emit_dfa(s: &mut String, st: &StateTable) {
    let dfa = &st.lexer_dfa;
    writeln!(s, "var dfaTrans = [...]uint32{{").unwrap();
    for state in &dfa.states {
        write!(s, "\t").unwrap();
        for (j, t) in state.trans.iter().enumerate() {
            if j == 255 {
                write!(s, "{},", t).unwrap();
            } else {
                write!(s, "{}, ", t).unwrap();
            }
        }
        writeln!(s).unwrap();
    }
    writeln!(s, "}}").unwrap();
    writeln!(s, "var dfaAccept = [...]uint16{{").unwrap();
    write!(s, "\t").unwrap();
    for (i, state) in dfa.states.iter().enumerate() {
        let v = state.accept.unwrap_or(0);
        if i == dfa.states.len() - 1 {
            write!(s, "{},", v).unwrap();
        } else {
            write!(s, "{}, ", v).unwrap();
        }
    }
    writeln!(s).unwrap();
    writeln!(s, "}}").unwrap();
    writeln!(
        s,
        "var lexerConfig = rt.DfaConfig{{Start: {}, Trans: dfaTrans[:], Accept: dfaAccept[:]}}",
        dfa.start
    )
    .unwrap();
    writeln!(s).unwrap();
    write!(s, "var skipKinds = map[int16]struct{{}}{{").unwrap();
    let skips: Vec<String> = st
        .tokens
        .iter()
        .filter(|t| t.skip)
        .map(|t| format!("int16({}): {{}}", token_const(st, t.kind)))
        .collect();
    s.push_str(&skips.join(", "));
    writeln!(s, "}}").unwrap();
    writeln!(s, "func isSkip(k int16) bool {{ _, ok := skipKinds[k]; return ok }}").unwrap();
    writeln!(s).unwrap();
}

fn emit_tables(s: &mut String, st: &StateTable) {
    writeln!(s, "const K = {}", st.k).unwrap();
    for (name, id) in &st.entry_states {
        writeln!(s, "const entry{} = {}", capitalize(name), id).unwrap();
    }
    writeln!(s).unwrap();

    writeln!(s, "var (").unwrap();
    for (i, f) in st.first_sets.iter().enumerate() {
        let seqs: Vec<String> = f
            .iter()
            .map(|seq| {
                format!(
                    "{{{}}}",
                    seq.iter()
                        .map(|t| format!("int16({})", token_const(st, *t)))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect();
        writeln!(s, "\tfirst_{} = [][]int16{{{}}}", i, seqs.join(", ")).unwrap();
    }
    for (i, f) in st.sync_sets.iter().enumerate() {
        writeln!(
            s,
            "\tsync_{} = []int16{{{}}}",
            i,
            f.iter()
                .map(|t| format!("int16({})", token_const(st, *t)))
                .collect::<Vec<_>>()
                .join(", ")
        )
        .unwrap();
    }
    writeln!(s, ")").unwrap();
    writeln!(s).unwrap();
}

fn emit_drive(s: &mut String, st: &StateTable) {
    writeln!(s, "func drive(p *rt.Parser) {{").unwrap();
    writeln!(s, "\tcur := p.State()").unwrap();
    writeln!(s, "\tfor p.QueueIsEmpty() && cur != rt.Terminated {{").unwrap();
    writeln!(s, "\t\tswitch cur {{").unwrap();
    for state in st.states.values() {
        writeln!(s, "\t\tcase {}: // {}", state.id, state.label).unwrap();
        for op in &state.ops {
            emit_op(s, st, op, state.id);
        }
    }
    writeln!(s, "\t\t}}").unwrap();
    writeln!(s, "\t}}").unwrap();
    writeln!(s, "\tp.SetState(cur)").unwrap();
    writeln!(s, "}}").unwrap();
    writeln!(s).unwrap();
}

fn emit_op(s: &mut String, st: &StateTable, op: &Op, self_id: u32) {
    match op {
        Op::Enter(k) => {
            writeln!(
                s,
                "\t\t\tp.Enter(uint16({}))",
                rule_const(st, *k)
            )
            .unwrap();
        }
        Op::Exit(k) => {
            writeln!(
                s,
                "\t\t\tp.Exit(uint16({}))",
                rule_const(st, *k)
            )
            .unwrap();
        }
        Op::Expect {
            kind,
            token_name,
            sync,
        } => {
            writeln!(
                s,
                "\t\t\tp.TryConsume(int16({}), sync_{}, {:?})",
                token_const(st, *kind),
                sync,
                token_name
            )
            .unwrap();
        }
        Op::PushRet(r) => {
            writeln!(s, "\t\t\tp.PushRet({})", r).unwrap();
        }
        Op::Jump(n) => {
            writeln!(s, "\t\t\tcur = {}", n).unwrap();
        }
        Op::Ret => {
            writeln!(s, "\t\t\tcur = p.PopRet()").unwrap();
        }
        Op::Star { first, body, next } => {
            writeln!(s, "\t\t\tif p.MatchesFirst(first_{}) {{ p.PushRet({}); cur = {} }} else {{ cur = {} }}", first, self_id, body, next).unwrap();
        }
        Op::Opt { first, body, next } => {
            writeln!(s, "\t\t\tif p.MatchesFirst(first_{}) {{ p.PushRet({}); cur = {} }} else {{ cur = {} }}", first, next, body, next).unwrap();
        }
        Op::Dispatch { tree, sync, next } => {
            emit_dispatch_tree(s, st, tree, *sync, *next, "\t\t\t");
        }
    }
}

fn emit_dispatch_tree(
    s: &mut String,
    st: &StateTable,
    tree: &DispatchTree,
    sync: u32,
    next: u32,
    ind: &str,
) {
    match tree {
        DispatchTree::Leaf(leaf) => {
            write!(s, "{}", ind).unwrap();
            emit_leaf_inline(s, leaf, sync, next);
            writeln!(s).unwrap();
        }
        DispatchTree::Switch {
            depth,
            arms,
            default,
        } => {
            writeln!(s, "{}switch p.Look({}).Kind {{", ind, depth).unwrap();
            let inner = format!("{}\t", ind);
            let body_ind = format!("{}\t", inner);
            for (kind, sub) in arms {
                writeln!(
                    s,
                    "{}case int16({}):",
                    inner,
                    token_const(st, *kind)
                )
                .unwrap();
                match sub {
                    DispatchTree::Leaf(leaf) => {
                        write!(s, "{}", body_ind).unwrap();
                        emit_leaf_inline(s, leaf, sync, next);
                        writeln!(s).unwrap();
                    }
                    _ => emit_dispatch_tree(s, st, sub, sync, next, &body_ind),
                }
            }
            writeln!(s, "{}default:", inner).unwrap();
            write!(s, "{}", body_ind).unwrap();
            emit_leaf_inline(s, default, sync, next);
            writeln!(s).unwrap();
            writeln!(s, "{}}}", ind).unwrap();
        }
    }
}

fn emit_leaf_inline(s: &mut String, leaf: &DispatchLeaf, sync: u32, next: u32) {
    match leaf {
        DispatchLeaf::Arm(t) => {
            write!(s, "p.PushRet({}); cur = {}", next, t).unwrap();
        }
        DispatchLeaf::Fallthrough => {
            write!(s, "cur = {}", next).unwrap();
        }
        DispatchLeaf::Error => {
            write!(
                s,
                "cur = {}; p.ErrorHere(\"unexpected token\"); p.RecoverTo(sync_{})",
                next, sync
            )
            .unwrap();
        }
    }
}

fn emit_public_api(s: &mut String, st: &StateTable) {
    writeln!(
        s,
        "var parserConfig = rt.Config{{K: K, EofKind: int16(TkEof), IsSkip: isSkip, Drive: drive}}"
    )
    .unwrap();
    writeln!(s).unwrap();
    for (name, _) in &st.entry_states {
        writeln!(
            s,
            "// Parse{cap} returns a Parser that parses the `{name}` rule from r.",
            cap = capitalize(name),
            name = name,
        )
        .unwrap();
        writeln!(
            s,
            "func Parse{cap}(r io.Reader) *rt.Parser {{",
            cap = capitalize(name)
        )
        .unwrap();
        writeln!(
            s,
            "\tlex := rt.NewLexer(r, &lexerConfig, int16(TkEof), int16(TkError))"
        )
        .unwrap();
        writeln!(
            s,
            "\treturn rt.NewParser(lex, entry{}, parserConfig)",
            capitalize(name)
        )
        .unwrap();
        writeln!(s, "}}").unwrap();
        writeln!(s).unwrap();
    }
}

fn capitalize(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut first = true;
    for c in s.chars() {
        if first {
            out.extend(c.to_uppercase());
            first = false;
        } else {
            out.push(c);
        }
    }
    out
}