antlr-rust-codegen 0.33.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Konstantin Vyatkin
fn render_validated_tree_support(surface_name: &str) -> String {
    let validated_tree = format!("{surface_name}ValidatedTree");
    let validation_error = format!("{surface_name}ValidationError");
    format!(
        r#"/// Marker carried by generated contexts whose required-child
/// invariants were checked after a syntax-clean parse, and grammar brand of
/// this module's validated tree and rule-node types.
///
/// This marker stays module-local (unlike the runtime-owned support items)
/// so rustc can prove it never implements the runtime's
/// `__RecoveryContextState`, keeping the recovery-oriented and validated
/// accessor impls coherent — and so the runtime's branded validated types
/// stay nominally distinct per grammar.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ValidatedTreeContext {{
    __private: (),
}}

/// A completed, syntax-clean parse tree whose generated child cardinalities
/// have been structurally validated.
///
/// Alias of the runtime's grammar-agnostic `antlr4_runtime::ValidatedTree`
/// branded with this module's [`ValidatedTreeContext`] marker, so validated
/// trees of different grammars remain distinct types.
pub type {validated_tree} = antlr4_runtime::ValidatedTree<ValidatedTreeContext>;

/// A rule node borrowed from a [`{validated_tree}`].
///
/// Alias of the runtime's `antlr4_runtime::ValidatedRuleNode` branded with
/// this module's [`ValidatedTreeContext`] marker.
pub type ValidatedRuleNode<'a> = antlr4_runtime::ValidatedRuleNode<'a, ValidatedTreeContext>;

pub use antlr4_runtime::FromValidatedRuleNode;

/// Failure to recognize or validate a strict generated parse.
///
/// Alias of the grammar-agnostic `antlr4_runtime::ValidationError`; unlike
/// the branded tree types, the validation errors of every generated parser
/// are deliberately one shared type.
pub type {validation_error} = antlr4_runtime::ValidationError;

"#
    )
}

fn render_context_listener_surface(
    context_names: &ContextSurfaceNames,
    listener_trait: &str,
    tree_walker: &str,
    validated_listener_trait: &str,
    validated_tree_walker: &str,
) -> String {
    let mut out = String::new();
    let mut trait_methods = String::new();
    let mut enter_arms = String::new();
    let mut exit_arms = String::new();
    let mut validated_trait_methods = String::new();
    let mut validated_enter_arms = String::new();
    let mut validated_exit_arms = String::new();
    for (kind_id, view) in context_names.views.iter().enumerate() {
        let ContextSurfaceName {
            context_type,
            listener_method,
            ..
        } = &view.surface;
        let _ = writeln!(
            trait_methods,
            "    fn enter_{listener_method}(&mut self, _ctx: &{context_type}) -> Result<(), E> {{ Ok(()) }}\n    fn exit_{listener_method}(&mut self, _ctx: &{context_type}) -> Result<(), E> {{ Ok(()) }}"
        );
        let _ = writeln!(
            enter_arms,
            "            {kind_id} => listener.enter_{listener_method}(&{context_type}::__from_listener_node(context, invocation_states))?,"
        );
        let _ = writeln!(
            exit_arms,
            "            {kind_id} => listener.exit_{listener_method}(&{context_type}::__from_listener_node(context, invocation_states))?,"
        );
        let _ = writeln!(
            validated_trait_methods,
            "    fn enter_{listener_method}(&mut self, _ctx: &{context_type}<ValidatedTreeContext>) -> Result<(), E> {{ Ok(()) }}\n    fn exit_{listener_method}(&mut self, _ctx: &{context_type}<ValidatedTreeContext>) -> Result<(), E> {{ Ok(()) }}"
        );
        let _ = writeln!(
            validated_enter_arms,
            "            {kind_id} => listener.enter_{listener_method}(&{context_type}::<ValidatedTreeContext>::__from_validated_listener_node(context, invocation_states))?,"
        );
        let _ = writeln!(
            validated_exit_arms,
            "            {kind_id} => listener.exit_{listener_method}(&{context_type}::<ValidatedTreeContext>::__from_validated_listener_node(context, invocation_states))?,"
        );
    }
    let _ = writeln!(
        out,
        "#[allow(dead_code, unused_variables)]\npub trait {listener_trait}<E = std::convert::Infallible> {{\n    fn walk(&mut self, tree: antlr4_runtime::Node<'_>) -> Result<(), E>\n    where\n        Self: Sized,\n    {{\n        {tree_walker}::walk(self, tree)\n    }}\n\n    fn enter_every_rule(&mut self, _ctx: RuleNodeView<'_>) -> Result<(), E> {{ Ok(()) }}\n    fn exit_every_rule(&mut self, _ctx: RuleNodeView<'_>) -> Result<(), E> {{ Ok(()) }}\n\n{trait_methods}    fn visit_terminal(&mut self, _node: &TerminalNode) -> Result<(), E> {{ Ok(()) }}\n    fn visit_error_node(&mut self, _node: &ErrorNode) -> Result<(), E> {{ Ok(()) }}\n    fn output(&mut self) -> std::io::Stdout {{ std::io::stdout() }}\n}}\n"
    );

    let _ = writeln!(
        out,
        r#"antlr4_runtime::__antlr4_rust_generated_walk_callbacks! {{
    callbacks: __{tree_walker}Callbacks,
    listener: {listener_trait},
    enter: |listener, context, invocation_states| {{
        listener.enter_every_rule(context)?;
        match __context_kind(context) {{
{enter_arms}            _ => {{}}
        }}
        Ok(())
    }},
    exit: |listener, context, invocation_states| {{
        match __context_kind(context) {{
{exit_arms}            _ => {{}}
        }}
        listener.exit_every_rule(context)
    }},
    terminal: |listener, node| {{
        listener.visit_terminal(&TerminalNode::new(node))
    }},
    error: |listener, node| {{
        listener.visit_error_node(&ErrorNode::new(node))
    }},
}}

#[allow(dead_code)]
pub struct {tree_walker};

#[allow(dead_code)]
impl {tree_walker} {{
    pub fn walk<E, T: {listener_trait}<E>>(
        listener: &mut T,
        tree: antlr4_runtime::Node<'_>,
    ) -> Result<(), E> {{
        Self::__walk(listener, tree, None)
    }}

    pub fn walk_with_invocation_states<E, T: {listener_trait}<E>>(
        listener: &mut T,
        tree: antlr4_runtime::Node<'_>,
        parent_invocation_states: Vec<isize>,
    ) -> Result<(), E> {{
        Self::__walk(listener, tree, Some(parent_invocation_states))
    }}

    fn __walk<E, T: {listener_trait}<E>>(
        listener: &mut T,
        tree: antlr4_runtime::Node<'_>,
        invocation_states: Option<Vec<isize>>,
    ) -> Result<(), E> {{
        let mut callbacks = __{tree_walker}Callbacks(listener);
        antlr4_runtime::generated::walk_generated(tree, invocation_states, &mut callbacks)
    }}
}}

pub type ParseTreeWalker = {tree_walker};
"#
    );
    let _ = writeln!(
        out,
        r#"#[allow(dead_code, unused_variables)]
pub trait {validated_listener_trait}<E = std::convert::Infallible> {{
    fn walk(&mut self, tree: ValidatedRuleNode<'_>) -> Result<(), E>
    where
        Self: Sized,
    {{
        {validated_tree_walker}::walk(self, tree)
    }}

    fn enter_every_rule(&mut self, _ctx: ValidatedRuleNode<'_>) -> Result<(), E> {{ Ok(()) }}
    fn exit_every_rule(&mut self, _ctx: ValidatedRuleNode<'_>) -> Result<(), E> {{ Ok(()) }}

{validated_trait_methods}    fn visit_terminal(&mut self, _node: &TerminalNode) -> Result<(), E> {{ Ok(()) }}
    fn output(&mut self) -> std::io::Stdout {{ std::io::stdout() }}
}}

antlr4_runtime::__antlr4_rust_generated_walk_callbacks! {{
    callbacks: __{validated_tree_walker}Callbacks,
    listener: {validated_listener_trait},
    enter: |listener, context, invocation_states| {{
        listener.enter_every_rule(ValidatedRuleNode::__new(context))?;
        match __context_kind(context) {{
{validated_enter_arms}            _ => {{}}
        }}
        Ok(())
    }},
    exit: |listener, context, invocation_states| {{
        match __context_kind(context) {{
{validated_exit_arms}            _ => {{}}
        }}
        listener.exit_every_rule(ValidatedRuleNode::__new(context))
    }},
    terminal: |listener, node| {{
        listener.visit_terminal(&TerminalNode::new(node))
    }},
    error: |_listener, _node| {{
        unreachable!("validated parse tree contains an error node")
    }},
}}

#[allow(dead_code)]
pub struct {validated_tree_walker};

#[allow(dead_code)]
impl {validated_tree_walker} {{
    pub fn walk<E, T: {validated_listener_trait}<E>>(
        listener: &mut T,
        tree: ValidatedRuleNode<'_>,
    ) -> Result<(), E> {{
        Self::__walk(listener, tree.node(), None)
    }}

    pub fn walk_with_invocation_states<E, T: {validated_listener_trait}<E>>(
        listener: &mut T,
        tree: ValidatedRuleNode<'_>,
        parent_invocation_states: Vec<isize>,
    ) -> Result<(), E> {{
        Self::__walk(listener, tree.node(), Some(parent_invocation_states))
    }}

    fn __walk<E, T: {validated_listener_trait}<E>>(
        listener: &mut T,
        tree: antlr4_runtime::Node<'_>,
        invocation_states: Option<Vec<isize>>,
    ) -> Result<(), E> {{
        let mut callbacks = __{validated_tree_walker}Callbacks(listener);
        antlr4_runtime::generated::walk_generated(tree, invocation_states, &mut callbacks)
    }}
}}

pub type ValidatedParseTreeWalker = {validated_tree_walker};
"#
    );
    out
}

fn render_context_visitor_surface(
    context_names: &ContextSurfaceNames,
    visitor_trait: &str,
    visitable_trait: &str,
    validated_visitor_trait: &str,
    validated_visitable_trait: &str,
) -> String {
    let mut out = String::new();
    let mut visitor_methods = String::new();
    let mut visitor_arms = String::new();
    let mut validated_visitor_methods = String::new();
    let mut validated_visitor_arms = String::new();
    for (kind_id, view) in context_names.views.iter().enumerate() {
        let ContextSurfaceName {
            context_type,
            visitor_method,
            ..
        } = &view.surface;
        let _ = writeln!(
            visitor_methods,
            "    fn visit_{visitor_method}(&mut self, ctx: &{context_type}) -> Self::Result {{\n        self.visit_children(ctx)\n    }}"
        );
        let _ = writeln!(
            visitor_arms,
            "            {kind_id} => {visitor_trait}::visit_{visitor_method}(self.0, &{context_type}::__from_listener_node(context, None)),"
        );
        let _ = writeln!(
            validated_visitor_methods,
            "    fn visit_{visitor_method}(&mut self, ctx: &{context_type}<ValidatedTreeContext>) -> Self::Result {{\n        self.visit_children(ctx)\n    }}"
        );
        let _ = writeln!(
            validated_visitor_arms,
            "            {kind_id} => {validated_visitor_trait}::visit_{visitor_method}(self.0, &{context_type}::<ValidatedTreeContext>::__from_validated_listener_node(context, None)),"
        );
    }
    let _ = writeln!(
        out,
        r#"#[allow(dead_code, unused_variables)]
pub trait {visitor_trait}: Sized {{
    type Result;

    fn default_result(&mut self) -> Self::Result;

    fn visit<'tree, T>(&mut self, tree: T) -> Self::Result
    where
        T: {visitable_trait}<'tree>,
    {{
        let tree = {visitable_trait}::into_parse_tree_node(tree);
        let mut bridge = __VisitorBridge(self);
        antlr4_runtime::ParseTreeVisitor::visit(&mut bridge, tree)
    }}

    fn visit_children<'tree, T>(&mut self, context: T) -> Self::Result
    where
        T: {visitable_trait}<'tree>,
    {{
        let tree = {visitable_trait}::into_parse_tree_node(context);
        let context = tree.as_rule().expect("visit_children requires a rule context");
        let mut bridge = __VisitorBridge(self);
        antlr4_runtime::ParseTreeVisitor::visit_children(&mut bridge, context)
    }}

    fn aggregate_result(
        &mut self,
        _aggregate: Self::Result,
        next_result: Self::Result,
    ) -> Self::Result {{
        next_result
    }}

    fn should_visit_next_child(
        &mut self,
        _context: RuleNodeView<'_>,
        _current_result: &Self::Result,
    ) -> bool {{
        true
    }}

    fn visit_terminal(&mut self, _node: &TerminalNode) -> Self::Result {{
        self.default_result()
    }}

    fn visit_error_node(&mut self, _node: &ErrorNode) -> Self::Result {{
        self.default_result()
    }}

{visitor_methods}}}

#[allow(dead_code)]
struct __VisitorBridge<'a, T: {visitor_trait}>(&'a mut T);

impl<T: {visitor_trait}> antlr4_runtime::ParseTreeVisitor for __VisitorBridge<'_, T> {{
    type Result = T::Result;

    fn visit_rule(&mut self, context: RuleNodeView<'_>) -> Self::Result {{
        match __context_kind(context) {{
{visitor_arms}            _ => {visitor_trait}::default_result(self.0),
        }}
    }}

    fn visit_terminal(&mut self, node: RuntimeTerminalNode<'_>) -> Self::Result {{
        {visitor_trait}::visit_terminal(self.0, &TerminalNode::new(node))
    }}

    fn visit_error_node(&mut self, node: RuntimeErrorNode<'_>) -> Self::Result {{
        {visitor_trait}::visit_error_node(self.0, &ErrorNode::new(node))
    }}

    fn default_result(&mut self) -> Self::Result {{
        {visitor_trait}::default_result(self.0)
    }}

    fn aggregate_result(
        &mut self,
        aggregate: Self::Result,
        next_result: Self::Result,
    ) -> Self::Result {{
        {visitor_trait}::aggregate_result(self.0, aggregate, next_result)
    }}

    fn should_visit_next_child(
        &mut self,
        context: RuleNodeView<'_>,
        current_result: &Self::Result,
    ) -> bool {{
        {visitor_trait}::should_visit_next_child(self.0, context, current_result)
    }}
}}
"#
    );
    let _ = writeln!(
        out,
        r#"#[allow(dead_code, unused_variables)]
pub trait {validated_visitor_trait}: Sized {{
    type Result;

    fn default_result(&mut self) -> Self::Result;

    fn visit<'tree, T>(&mut self, tree: T) -> Self::Result
    where
        T: {validated_visitable_trait}<'tree>,
    {{
        let tree = {validated_visitable_trait}::into_validated_parse_tree_node(tree);
        let mut bridge = __ValidatedVisitorBridge(self);
        antlr4_runtime::ParseTreeVisitor::visit(&mut bridge, tree)
    }}

    fn visit_children<'tree, T>(&mut self, context: T) -> Self::Result
    where
        T: {validated_visitable_trait}<'tree>,
    {{
        let tree = {validated_visitable_trait}::into_validated_parse_tree_node(context);
        let context = tree.as_rule().expect("visit_children requires a rule context");
        let mut bridge = __ValidatedVisitorBridge(self);
        antlr4_runtime::ParseTreeVisitor::visit_children(&mut bridge, context)
    }}

    fn aggregate_result(
        &mut self,
        _aggregate: Self::Result,
        next_result: Self::Result,
    ) -> Self::Result {{
        next_result
    }}

    fn should_visit_next_child(
        &mut self,
        _context: ValidatedRuleNode<'_>,
        _current_result: &Self::Result,
    ) -> bool {{
        true
    }}

    fn visit_terminal(&mut self, _node: &TerminalNode) -> Self::Result {{
        self.default_result()
    }}

{validated_visitor_methods}}}

#[allow(dead_code)]
struct __ValidatedVisitorBridge<'a, T: {validated_visitor_trait}>(&'a mut T);

impl<T: {validated_visitor_trait}> antlr4_runtime::ParseTreeVisitor
    for __ValidatedVisitorBridge<'_, T>
{{
    type Result = T::Result;

    fn visit_rule(&mut self, context: RuleNodeView<'_>) -> Self::Result {{
        match __context_kind(context) {{
{validated_visitor_arms}            _ => {validated_visitor_trait}::default_result(self.0),
        }}
    }}

    fn visit_terminal(&mut self, node: RuntimeTerminalNode<'_>) -> Self::Result {{
        {validated_visitor_trait}::visit_terminal(self.0, &TerminalNode::new(node))
    }}

    fn visit_error_node(&mut self, _node: RuntimeErrorNode<'_>) -> Self::Result {{
        unreachable!("validated parse tree contains an error node")
    }}

    fn default_result(&mut self) -> Self::Result {{
        {validated_visitor_trait}::default_result(self.0)
    }}

    fn aggregate_result(
        &mut self,
        aggregate: Self::Result,
        next_result: Self::Result,
    ) -> Self::Result {{
        {validated_visitor_trait}::aggregate_result(self.0, aggregate, next_result)
    }}

    fn should_visit_next_child(
        &mut self,
        context: RuleNodeView<'_>,
        current_result: &Self::Result,
    ) -> bool {{
        {validated_visitor_trait}::should_visit_next_child(
            self.0,
            ValidatedRuleNode::__new(context),
            current_result,
        )
    }}
}}
"#
    );
    out
}