dbt-antlr-codegen 0.10.0

ANTLR v4 grammar compiler and Rust source generator
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! serde-serializable output model for the dbt emission layer.
//!
//! The structs mirror the Java tool's `org.antlr.v4.codegen.model` classes
//! (`OutputFile`, `LexerFile`, `Lexer`, `ParserFile`, `Parser`, `Recognizer`,
//! `RuleFunction`, `CodeBlockForAlt`, the `Choice` hierarchy, the `srcop`
//! and `decl` classes, `RuleActionFunction`, `RuleSempredFunction`,
//! `SerializedATN`). Field names serialize in the camelCase shape the
//! `Rust.stg` templates use (`lexer.name`, `lexer.escapedName`,
//! `file.grammarFileName`, ...), so template expressions read like the
//! original STG attribute references.
//!
//! Where the Java model exposes a `Map` keyed by name (`tokens`,
//! `actionFuncs`, `sempredFuncs`), the structs here use a list of key/value
//! pairs, which is what minijinja iterates naturally. Heterogeneous model
//! children (block ops, choice alternatives, declarations) are
//! internally-tagged enums consumed by the template's `Op`/`Getter`
//! dispatcher macros, mirroring the Java `OutputModelWalker`'s
//! template-by-class-name dispatch.

use std::collections::BTreeMap;

use serde::Serialize;

use crate::optimization::StaticLexerTables;

/// Root render context: the formal arguments of the `LexerFile` template.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LexerFileContext {
    pub lexer_file: OutputFileModel,
    pub lexer: LexerModel,
    pub named_actions: NamedActionsModel,
}

/// Mirrors `OutputFile` (the parts the lexer templates read).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OutputFileModel {
    /// Grammar file name as shown in the `fileHeader` comment.
    pub grammar_file_name: String,
    /// Version string of the Java tool the templates imitate
    /// (`Tool.VERSION` of the dbt fork).
    #[serde(rename = "ANTLRVersion")]
    pub antlr_version: String,
}

/// Named actions (`@header`, `@members`, ...) spliced into the output.
///
/// Fields are `None` when the grammar does not define the action; the
/// templates treat them as empty.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NamedActionsModel {
    pub header: Option<String>,
    pub init: Option<String>,
    pub fields: Option<String>,
    pub members: Option<String>,
    pub definitions: Option<String>,
    pub extend: Option<String>,
    /// Rule-level `@after` action (parser rule functions only).
    pub after: Option<String>,
}
/// The translated rule-level named actions (`@init`, `@after`) of one rule
/// function: Java `RuleFunction.namedActions`, whose values are `Action`
/// models (translated chunks).
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleNamedActionsModel {
    pub init: Option<Vec<ActionChunkModel>>,
    pub after: Option<Vec<ActionChunkModel>>,
}

/// One entry of the Java `Recognizer.tokens` map (`name -> token type`).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenConstantModel {
    pub key: String,
    pub value: i32,
}

/// One numbered embedded action or sempred: the `index -> text` pairs of the
/// Java `RuleActionFunction.actions` map.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedActionModel {
    pub index: usize,
    pub chunks: Vec<ActionChunkModel>,
}

/// Mirrors `RuleActionFunction`/`RuleSempredFunction`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleActionFunctionModel {
    pub name: String,
    pub escaped_name: String,
    pub ctx_type: String,
    pub rule_index: usize,
    /// The `r.factory.g.lexer` check of the `RuleSempredFunction` template.
    pub is_lexer: bool,
    pub actions: Vec<IndexedActionModel>,
}

/// Root render context: the formal arguments of the `ListenerFile` and
/// `BaseListenerFile` templates.
///
/// The `kind` tag selects the template, like the `Op` dispatcher's
/// class-name dispatch (`BaseListenerFile` reuses the `ListenerFile` model
/// in the Java tool).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListenerFileContext {
    /// Template selector: `ListenerFile` or `BaseListenerFile`.
    pub kind: &'static str,
    pub file: ListenerFileModel,
    /// The grammar-level `@header` action body (scope-less only).
    pub header: Option<String>,
    pub named_actions: NamedActionsModel,
}

/// Mirrors `ListenerFile`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListenerFileModel {
    pub grammar_file_name: String,
    #[serde(rename = "ANTLRVersion")]
    pub antlr_version: String,
    pub grammar_name: String,
    /// Recognizer name, for example `CSVParser`.
    pub parser_name: String,
    /// The `listenerNames` set: rule names, or the alt labels for rules with
    /// alt-specific contexts, in the Java tool's iteration order.
    pub listener_names: Vec<String>,
    /// The `listenerLabelRuleNames` map: alt label to its defining rule.
    pub listener_label_rule_names: BTreeMap<String, String>,
}

/// Root render context: the formal arguments of the `VisitorFile` and
/// `BaseVisitorFile` templates. The `kind` tag selects the template.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VisitorFileContext {
    /// Template selector: `VisitorFile` or `BaseVisitorFile`.
    pub kind: &'static str,
    pub file: VisitorFileModel,
    /// The grammar-level `@header` action body (scope-less only).
    pub header: Option<String>,
    pub named_actions: NamedActionsModel,
}

/// Mirrors `VisitorFile`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VisitorFileModel {
    pub grammar_file_name: String,
    #[serde(rename = "ANTLRVersion")]
    pub antlr_version: String,
    pub grammar_name: String,
    /// Recognizer name, for example `CSVParser`.
    pub parser_name: String,
    /// The `visitorNames` set (same construction as `listenerNames`).
    pub visitor_names: Vec<String>,
    /// The `visitorLabelRuleNames` map: alt label to its defining rule.
    pub visitor_label_rule_names: BTreeMap<String, String>,
}

/// Mirrors `SerializedATN`.
///
/// The words are serialized from the compiled runtime ATN at emission time, not
/// during compilation.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SerializedAtnModel {
    /// Java-format serialized ATN words.
    pub serialized: Vec<i32>,
}

/// Static lexer DFA table payload of a `--static-lexer-dfa` lexer build.
///
/// Materialized through the emission templates as the `_STATIC_LEXER_TABLE_*`
/// statics and, when `omit_atn` is true (set when every mode fully resolves, no
/// escape edges), elide the `_serializedATN`/`_ATN` statics entirely.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StaticLexerTablesModel {
    /// Word stream of the `static_dfa_build` format (version 1).
    pub words: Vec<u32>,
    /// Whether the generated lexer needs no ATN at runtime.
    pub omit_atn: bool,
}

impl StaticLexerTablesModel {
    pub(crate) fn from_pass(tables: &StaticLexerTables) -> Self {
        Self {
            words: tables.words.clone(),
            omit_atn: tables.omit_atn,
        }
    }
}

/// Packed parser-ATN words of the vendored packed format (`PATN` v3).
///
/// This intentionally replaces the Java `SerializedATN` model for parsers:
/// generated parsers embed the packed u32 words and decode them with
/// `dbt_antlr_runtime::atn_packed_deserializer::PackedATNDeserializer`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PackedAtnModel {
    /// Packed parser ATN words.
    pub serialized: Vec<u32>,
    /// Static parser DFA tables of a `--static-parser-dfa` build, `None` when
    /// the parser has no table.
    pub static_tables: Option<StaticParserTablesModel>,
}

/// Static parser DFA table payload of a `--static-parser-dfa` parser build.
///
/// Materialized through the emission templates as the `_STATIC_PARSER_TABLE_*`
/// statics, which the simulator manager attaches beside the ATN.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StaticParserTablesModel {
    /// The packed image words of the tables.
    pub words: Vec<u32>,
}

/// Root render context: the formal arguments of the `ParserFile` template.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ParserFileContext {
    pub file: ParserFileModel,
    pub parser: ParserModel,
    pub named_actions: NamedActionsModel,
    pub context_super_class: Option<String>,
}

/// Mirrors `ParserFile` (plus the `OutputFile` base fields the templates
/// read).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ParserFileModel {
    pub grammar_file_name: String,
    #[serde(rename = "ANTLRVersion")]
    pub antlr_version: String,
    /// Grammar name (`CSV`), used for the listener/visitor `use` lines and
    /// the `TreeWalker` name.
    pub grammar_name: String,
    pub gen_listener: bool,
    pub gen_visitor: bool,
}

/// One entry of the Java `Parser.rules` collection (`name` + `index`),
/// rendered as the `RULE_<name>` constants.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleRefModel {
    pub name: String,
    pub index: usize,
}

/// Mirrors `Parser` (and its `Recognizer` base class).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ParserModel {
    /// Recognizer name, for example `CSVParser`.
    pub name: String,
    pub grammar_name: String,
    pub grammar_file_name: String,
    pub tokens: Vec<TokenConstantModel>,
    pub rules: Vec<RuleRefModel>,
    pub rule_names: Vec<String>,
    pub literal_names: Vec<Option<String>>,
    pub symbolic_names: Vec<Option<String>>,
    pub funcs: Vec<RuleFunctionModel>,
    pub sempred_funcs: Vec<RuleActionFunctionModel>,
    pub atn: PackedAtnModel,
}

/// Mirrors `RuleFunction`. When `left_recursive` is set, the template
/// renders `LeftRecursiveRuleFunction` instead (the Java walker picks the
/// template by the `LeftRecursiveRuleFunction` subclass).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleFunctionModel {
    pub name: String,
    pub escaped_name: String,
    pub modifiers: Vec<String>,
    pub ctx_type: String,
    pub index: usize,
    /// Rule start state number.
    pub start_state: i32,
    pub has_lookahead_block: bool,
    /// Whether the rule was rewritten for left recursion.
    pub left_recursive: bool,
    /// Whether a shared-descent group shares this rule: its function starts
    /// with the `resume_take` hook.
    pub resume_target: bool,
    pub args: Vec<DeclModel>,
    pub locals: Vec<DeclModel>,
    pub code: Vec<SrcOpModel>,
    pub rule_ctx: StructDeclModel,
    pub alt_label_ctxs: Vec<StructDeclModel>,
    /// Rule-level named actions (`@init`, `@after`).
    pub named_actions: RuleNamedActionsModel,
    pub finally_action: Option<String>,
    pub postamble: Vec<SrcOpModel>,
    pub exceptions: Vec<String>,
}

/// One token of a lookahead set, as the `Choice.TokenInfo` pairs the
/// templates render (`<parser.grammarName>_<t.name>`).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenInfoModel {
    pub ttype: i32,
    pub name: String,
}

/// The `choice` attribute of the choice-block ops; fields of the Java
/// `Choice`/`LL1Choice`/`LL1Loop`/`Loop` hierarchy the templates read.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChoiceModel {
    /// The `ast.atnState.stateNumber` of the block or EBNF root.
    pub state_number: i32,
    pub decision: i32,
    /// `Loop.exitAlt`.
    pub exit_alt: i32,
    /// `LL1Loop.blockStartStateNumber` / `Loop.blockStartStateNumber`.
    pub block_start_state_number: i32,
    /// `LL1Loop.loopBackStateNumber` / `Loop.loopBackStateNumber`.
    pub loop_back_state_number: i32,
    /// Whether the EBNF root is greedy (`choice.ast.greedy`).
    pub greedy: bool,
    /// `LL1Choice.altLook`: one sorted token list per alternative. Empty
    /// for non-LL(1) choices.
    pub alt_look: Vec<Vec<TokenInfoModel>>,
    /// `Choice.tableCanDefer`: whether the static table prediction can return
    /// no alternative and has to fall back to `adaptive_predict`.
    pub table_can_defer: bool,
}

/// One shared-descent group of a `DescentAltBlock`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DescentGroupModel {
    /// The virtual alternative the table accepts with for the group.
    pub virtual_alt: i32,
    /// The call-site states of the members' calls of the shared rule.
    pub call_sites: Vec<i32>,
    /// The number of leading tokens before the shared rule.
    pub prefix_len: usize,
    /// The shared rule name, as `RULE_<name>` spells it.
    pub rule_name: String,
    /// The call of the shared rule: `<name>()`, or `<name>_rec(<p>)` for a
    /// left-recursive rule.
    pub invoke: String,
    /// The tail arms.
    pub tails: Vec<DescentTailModel>,
    /// The member alternative that every other token selects.
    pub default_alt: i32,
    /// The alternative a fallback predicts under `--static-dfa-only`; `None`
    /// falls back to `adaptive_predict`.
    pub static_fallback: Option<i32>,
}

/// One tail arm of a shared-descent group.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DescentTailModel {
    pub alt: i32,
    pub tokens: Vec<TokenInfoModel>,
}

/// One bitset window of `TestSetInline.Bitset`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitsetModel {
    pub shift: i32,
    pub tokens: Vec<TokenInfoModel>,
    pub calculated: i64,
}

/// The `ctx` attribute of action chunks and op labels: only the
/// `escapedName` of the owning `StructDecl` is read by the `Rust.stg`
/// templates (`actionChunk.ctx.escapedName`).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChunkContextModel {
    pub escaped_name: String,
}

impl ChunkContextModel {
    pub fn new(escaped_name: impl Into<String>) -> Self {
        Self {
            escaped_name: escaped_name.into(),
        }
    }
}

/// One label of a `LabeledOp` (`InvokeRule`/`MatchToken`/`MatchSet`/
/// `MatchNotSet`/`Wildcard`): the `Decl` fields the `LabelsAssign` template
/// reads (`l.escapedName`, `l.ctx.escapedName`).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OpLabelModel {
    pub name: String,
    pub escaped_name: String,
    /// The context struct the label decl was routed to (`Decl.ctx`).
    pub ctx: ChunkContextModel,
}

/// The chunks of a translated embedded action: the Java
/// `codegen.model.chunk` classes.
///
/// The `kind` tag drives the template's `Chunk` dispatcher, mirroring the
/// class-name dispatch. Variant fields serialize camelCase like the
/// `Rust.stg` attribute references.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all_fields = "camelCase")]
pub enum ActionChunkModel {
    ActionText {
        ctx: ChunkContextModel,
        text: String,
    },
    ArgRef {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
    },
    LocalRef {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
    },
    RetValueRef {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
    },
    QRetValueRef {
        ctx: ChunkContextModel,
        /// The rule label of the qualified reference (`a.dict`).
        dict: String,
        name: String,
        escaped_name: String,
    },
    TokenRef {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
    },
    LabelRef {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
    },
    ListLabelRef {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
    },
    #[serde(rename = "TokenPropertyRef_text")]
    TokenPropertyRefText {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "TokenPropertyRef_type")]
    TokenPropertyRefType {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "TokenPropertyRef_line")]
    TokenPropertyRefLine {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "TokenPropertyRef_pos")]
    TokenPropertyRefPos {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "TokenPropertyRef_channel")]
    TokenPropertyRefChannel {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "TokenPropertyRef_index")]
    TokenPropertyRefIndex {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "TokenPropertyRef_int")]
    TokenPropertyRefInt {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "RulePropertyRef_start")]
    RulePropertyRefStart {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "RulePropertyRef_stop")]
    RulePropertyRefStop {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "RulePropertyRef_text")]
    RulePropertyRefText {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "RulePropertyRef_ctx")]
    RulePropertyRefCtx {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "RulePropertyRef_parser")]
    RulePropertyRefParser {
        ctx: ChunkContextModel,
        label: String,
    },
    #[serde(rename = "ThisRulePropertyRef_start")]
    ThisRulePropertyRefStart { ctx: ChunkContextModel },
    #[serde(rename = "ThisRulePropertyRef_stop")]
    ThisRulePropertyRefStop { ctx: ChunkContextModel },
    #[serde(rename = "ThisRulePropertyRef_text")]
    ThisRulePropertyRefText { ctx: ChunkContextModel },
    #[serde(rename = "ThisRulePropertyRef_ctx")]
    ThisRulePropertyRefCtx { ctx: ChunkContextModel },
    #[serde(rename = "ThisRulePropertyRef_parser")]
    ThisRulePropertyRefParser { ctx: ChunkContextModel },
    SetAttr {
        ctx: ChunkContextModel,
        name: String,
        escaped_name: String,
        rhs_chunks: Vec<Self>,
    },
}

/// The ops of rule code blocks, alternatives, and choice preambles: the
/// Java `SrcOp` hierarchy.
///
/// The `kind` tag drives the template's `Op` dispatcher, which mirrors the
/// `OutputModelWalker` class-name dispatch. Variant fields serialize
/// camelCase like the `Rust.stg` attribute references (`op.stateNumber`,
/// `op.altLabel`, ...).
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all_fields = "camelCase")]
pub enum SrcOpModel {
    CodeBlockForOuterMostAlt {
        /// `CodeBlockForOuterMostAlt.alt.altNum`.
        alt_num: usize,
        /// `CodeBlockForOuterMostAlt.altLabel`.
        alt_label: Option<String>,
        locals: Vec<DeclModel>,
        preamble: Vec<Self>,
        ops: Vec<Self>,
    },
    CodeBlockForAlt {
        locals: Vec<DeclModel>,
        preamble: Vec<Self>,
        ops: Vec<Self>,
    },
    LL1AltBlock {
        choice: ChoiceModel,
        preamble: Vec<Self>,
        alts: Vec<Self>,
        error: Box<Self>,
    },
    LL1OptionalBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
        error: Box<Self>,
    },
    LL1OptionalBlockSingleAlt {
        choice: ChoiceModel,
        expr: Box<Self>,
        alts: Vec<Self>,
        preamble: Vec<Self>,
        error: Box<Self>,
        follow_expr: Box<Self>,
    },
    LL1StarBlockSingleAlt {
        choice: ChoiceModel,
        loop_expr: Box<Self>,
        alts: Vec<Self>,
        preamble: Vec<Self>,
        iteration: Vec<Self>,
    },
    LL1PlusBlockSingleAlt {
        choice: ChoiceModel,
        loop_expr: Box<Self>,
        alts: Vec<Self>,
        preamble: Vec<Self>,
        iteration: Vec<Self>,
    },
    AltBlock {
        choice: ChoiceModel,
        preamble: Vec<Self>,
        alts: Vec<Self>,
    },
    OptionalBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
    },
    StarBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
        iteration: Vec<Self>,
    },
    PlusBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
        error: Box<Self>,
    },
    /// A `(A | B | C)` block predicted from a static SLL DFA table.
    DFAAltBlock {
        choice: ChoiceModel,
        preamble: Vec<Self>,
        alts: Vec<Self>,
    },
    /// A `(A | B | C)` block predicted from a static SLL DFA table whose states
    /// can accept with the virtual alternative of a shared-descent group.
    DescentAltBlock {
        choice: ChoiceModel,
        preamble: Vec<Self>,
        alts: Vec<Self>,
        groups: Vec<DescentGroupModel>,
    },
    /// An optional `(...)?` block predicted from a static SLL DFA table.
    DFAOptionalBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
    },
    /// A `(...)*` loop predicted from a static SLL DFA table.
    DFAStarBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
        iteration: Vec<Self>,
    },
    /// A `(...)+` loop predicted from a static SLL DFA table.
    DFAPlusBlock {
        choice: ChoiceModel,
        alts: Vec<Self>,
        error: Box<Self>,
    },
    InvokeRule {
        name: String,
        escaped_name: String,
        state_number: i32,
        ctx_name: String,
        /// The `r.ast.options.p` precedence option: `Some` on references to
        /// left-recursive rules (`0` for external references), which renders
        /// the `_rec` suffix and the precedence argument.
        precedence: Option<u32>,
        labels: Vec<OpLabelModel>,
        /// `InvokeRule.argExprsChunks`: the translated call arguments.
        arg_exprs_chunks: Vec<ActionChunkModel>,
    },
    MatchToken {
        state_number: i32,
        name: String,
        escaped_name: String,
        labels: Vec<OpLabelModel>,
    },
    /// The `AddToLabelList` op following an invoke/match op with a `+=`
    /// list label: pushes the op's first label value onto the list.
    AddToLabelList {
        label: OpLabelModel,
        /// `Target.escapeIfNeeded(getListLabel(label))`.
        list_name: String,
    },
    MatchSet {
        state_number: i32,
        var_name: String,
        labels: Vec<OpLabelModel>,
        expr: Box<Self>,
        capture: Box<Self>,
    },
    MatchNotSet {
        state_number: i32,
        var_name: String,
        labels: Vec<OpLabelModel>,
        expr: Box<Self>,
        capture: Box<Self>,
    },
    Wildcard {
        state_number: i32,
        labels: Vec<OpLabelModel>,
    },
    /// `Action`: an embedded action element, translated to chunks by the
    /// action translator (an empty `chunks` list renders as nothing, like
    /// the empty action the left-recursion transform prepends).
    Action {
        chunks: Vec<ActionChunkModel>,
    },
    TestSetInline {
        var_name: String,
        bitsets: Vec<BitsetModel>,
    },
    ThrowNoViableAlt,
    SemPred {
        state_number: i32,
        /// The translated predicate expression (`chunks`).
        chunks: Vec<ActionChunkModel>,
        /// The predicate text as a target string literal (with quotes), used
        /// in the failure message.
        predicate: String,
        /// `SemPred.failChunks`: the translated `fail={...}` option.
        fail_chunks: Option<Vec<ActionChunkModel>>,
        /// `SemPred.msg`: the `fail='...'` option as a target string literal
        /// (with quotes).
        msg: Option<String>,
    },
    /// The `recRuleSetStopToken` action injected into left-recursive rule
    /// code (and into the postamble of rules with `@after`/`@finally`).
    RecRuleSetStopToken,
    /// The `recRuleSetPrevCtx` action injected as the iteration op of a
    /// left-recursive rule's operator star block.
    RecRuleSetPrevCtx,
    /// The `recRuleAltStartAction` action injected at the start of each
    /// left-recursive operator alternative without an alt label; `label`
    /// is the label the original alternative put on the deleted leading
    /// recursive reference (`e1` in `e1=e '+' e2=e`), when any.
    RecRuleAltStartAction {
        rule_name: String,
        /// Capitalized rule name (`Utils.capitalize`), without the `Context`
        /// suffix.
        ctx_name: String,
        label: Option<String>,
        is_list_label: bool,
    },
    /// The `recRuleLabeledAltStartAction` action injected at the start of
    /// each left-recursive operator alternative with an alt label; `label`
    /// is the label the original alternative put on the deleted leading
    /// recursive reference (`a` in `a=e op='*' b=e`), when any.
    RecRuleLabeledAltStartAction {
        rule_name: String,
        /// The alternative's alt label (`altInfo.altLabel`).
        current_alt_label: String,
        label: Option<String>,
        is_list_label: bool,
    },
    /// The `recRuleReplaceContext` action injected at the start of each
    /// labeled left-recursive primary alternative; `ctx_name` is the
    /// capitalized alt label without the `Context` suffix.
    RecRuleReplaceContext {
        ctx_name: String,
    },
    CaptureNextToken {
        var_name: String,
    },
    CaptureNextTokenType {
        var_name: String,
    },
}

/// Mirrors `decl.Decl` and its subclasses. `signature` marks the
/// trait-method (no body) variant of the context getters. Variant fields
/// serialize camelCase like the `Rust.stg` attribute references.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all_fields = "camelCase")]
pub enum DeclModel {
    TokenDecl {
        name: String,
        escaped_name: String,
    },
    TokenTypeDecl {
        name: String,
        escaped_name: String,
    },
    TokenListDecl {
        name: String,
        escaped_name: String,
    },
    RuleContextDecl {
        name: String,
        escaped_name: String,
        ctx_name: String,
    },
    RuleContextListDecl {
        name: String,
        escaped_name: String,
        ctx_name: String,
    },
    AttributeDecl {
        name: String,
        escaped_name: String,
        #[serde(rename = "type")]
        ty: String,
    },
    ContextTokenGetterDecl {
        name: String,
        signature: bool,
    },
    ContextTokenListGetterDecl {
        name: String,
        signature: bool,
    },
    ContextTokenListIndexedGetterDecl {
        name: String,
        signature: bool,
    },
    ContextRuleGetterDecl {
        name: String,
        escaped_name: String,
        ctx_name: String,
        signature: bool,
    },
    ContextRuleListGetterDecl {
        name: String,
        ctx_name: String,
        signature: bool,
    },
    ContextRuleListIndexedGetterDecl {
        name: String,
        escaped_name: String,
        ctx_name: String,
        signature: bool,
    },
}

/// Mirrors `decl.StructDecl`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StructDeclModel {
    pub name: String,
    pub escaped_name: String,
    /// Rule name the context struct derives from (`csvFile`).
    pub derived_from_name: String,
    /// Whether the rule has alt-specific contexts (`-> label`).
    pub provide_copy_from: bool,
    pub attrs: Vec<DeclModel>,
    pub getters: Vec<DeclModel>,
    pub signatures: Vec<DeclModel>,
    pub ctor_attrs: Vec<DeclModel>,
    pub token_decls: Vec<DeclModel>,
    pub token_type_decls: Vec<DeclModel>,
    pub token_list_decls: Vec<DeclModel>,
    pub rule_context_decls: Vec<DeclModel>,
    pub rule_context_list_decls: Vec<DeclModel>,
    pub attribute_decls: Vec<DeclModel>,
}

/// Mirrors `Lexer` (and its `Recognizer` base class).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LexerModel {
    /// Recognizer name, for example `CSVLexer`.
    pub name: String,
    pub grammar_name: String,
    pub grammar_file_name: String,
    /// Token constants with a positive token type, in declaration order.
    pub tokens: Vec<TokenConstantModel>,
    pub rule_names: Vec<String>,
    /// Fully translated Rust string literals (`"'\\r'"`), trailing `None`s
    /// trimmed like the Java tool does.
    pub literal_names: Vec<Option<String>>,
    pub symbolic_names: Vec<Option<String>>,
    /// User-declared channel names (excludes the two built-in channels).
    pub channel_names: Vec<String>,
    pub modes: Vec<String>,
    pub action_funcs: Vec<RuleActionFunctionModel>,
    pub sempred_funcs: Vec<RuleActionFunctionModel>,
    /// ATN statics; `None` when `static_tables` omit the ATN entirely, which is
    /// the case when every mode fully resolves.
    pub atn: Option<SerializedAtnModel>,
    /// Static lexer DFA tables (`--static-lexer-dfa`); `None` with the flag off.
    pub static_tables: Option<StaticLexerTablesModel>,
}