Quick start on ANTLR4 in Rust - part3

This is my note in adopting and learning ANTLR4Rust

Series


In the previous article, we implemented a parser with internal state variables. However, if a grammar is huge, it is practically impossible to manage a huge number of state variables. Alternatively, a visitor-like approach can be used.

In an exit method of the root rule in the Listener, we can grab the current context and its children and call custom parser methods:

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
impl Listener {
fn hdr(&self, ctx: &HdrContextAll) -> Row {
let row_ctx = ctx.row().unwrap();
self.row(&row_ctx)
} fn row(&self, ctx: &RowContextAll) -> Row {
let mut row = Row::new();
let field_ctx_list = ctx.field_all();
for (_i, field_ctx) in field_ctx_list.iter().enumerate() {
let field = self.field(&field_ctx);
row.push(field);
}
row
} fn field(&self, ctx: &FieldContextAll) -> String {
ctx.get_text()
}
}
impl CSVListener for Listener {
fn exit_csvFile(&mut self, ctx: &CsvFileContext) {
let hdr_ctx = ctx.hdr().unwrap();
let header = self.hdr(&hdr_ctx);
self.csv.header = header;
let row_ctx_list = ctx.row_all();
for (_i, row_ctx) in row_ctx_list.iter().enumerate() {
let row = self.row(&row_ctx);
self.csv.rows.push(row);
}
}
}

The minimal working example can be found here.