Quick start on ANTLR4 in Rust - part1
This is my note in adopting and learning ANTLR4Rust
Series
- Quick Start on ANTLR4 in Rust — Part1 (This article)
- Quick Start on ANTLR4 in Rust — Part2
- Quick Start on ANTLR4 in Rust — Part3
Install nightly version of Rust (and make it default if you want for convenience).
1 | $ rustup toolchain install nightly |
Get ANTLR4 runtime for Rust from here:
Prepare a grammar. I will use an example grammar: https://raw.githubusercontent.com/antlr/grammars-v4/master/csv/CSV.g4
Generate a parser:
1 | $ java -jar <ANTLR4 runtime path> -Dlanguage=Rust CSV.g4 |
You will get csvlexer.rs
, csvlistener.rs
, csvparser.rs
. Place them into your project src
directory.
Add dependencies in Cargo.toml
:
1 | [dependencies] |
Add a feature and import lazy_static
macros to the root module:
1 |
|
Import common and essential things:
1 | use antlr_rust::common_token_stream::CommonTokenStream; |
Import grammar-specific things:
1 | mod csvlexer; |
Implement ParseTreeListener
, a supertraint of CSVListener
:
1 | struct Listener;impl ParseTreeListener for Listener { |
Implement CSVListener
:
1 | impl CSVListener for Listener { |
Read and parse an input. Note that csvFile
in the last line is a rule name in CSV.g4
:
1 | fn main() { |
The minimal working example can be found here.