Generate ADT Typescript types for ANTLR4 grammars using antlr4ts.
$ yarn add -D antlr4ts
$ yarn add antlr4ts-adt
Now create a MyGrammar.g4
file and generate the corresponding ADT types:
$ npx antlr4ts MyGrammar.g4 -visitor
$ npx antlr4ts-adt MyGrammarParser.ts
This creates a file MyGrammarAdt.ts
with the types generated from the grammar and a getAst
function.
A simple calculator:
- ANTL4 Grammar: Calculator.g4
- Autogenerated ADT Typescript types: CalculatorAdt.ts
- AST eval example: calculator.ts
$ git clone https://github.com/tokland/antlr4ts-adt
$ cd example
$ yarn install
$ npx antlr4ts Calculator.g4 -o antlr4 -visitor
$ npx antlr4ts-adt antlr4/CalculatorParser.ts
$ npx ts-node calculator.ts "1 + product(5 - 2, 2) + sum(1, 2, 2 + 1)"
# 13