An Antlr4 tool that generates both Typescript and JavaScript Antlr Parsers (Current Antlr version: 4.8)
npm install antlr4-toolInstall antlr4-tool*, adding it to your package.json
``bash`
npm install --save-dev antlr4-tool
* Install the Antlr4 library
`bash
npm install -S antlr4
#
* Add a grammar to your project, e.g. path/to/Grammar.g4
`json
"scripts": {
"generate-parser": "antlr4-tool -o parser path/to/Grammar.g4"
}
`* Run the NPM script command
`bash
npm run generate-parser
`* Use your generated Parser
JavaScript
`javascriptconst antlr4 = require('antlr4')
const InputStream = antlr4.InputStream;
const CommonTokenStream = antlr4.CommonTokenStream;
const GrammarParser = require('./parser/GrammarParser').GrammarParser;
const GrammarLexer = require('./parser/GrammarLexer').GrammarLexer;
const inputStream = new InputStream('int x = 10;');
const lexer = new GrammarLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new GrammarParser(tokenStream);
// Parse the input, where
compilationUnit is whatever entry point you defined
const tree = parser.compilationUnit();
console.log(tree);
`TypeScript
`typescript
import {InputStream, CommonTokenStream} from 'antlr4';
import {GrammarParser} from './parser/GrammarParser';
import {GrammarLexer} from './parser/GrammarLexer';const inputStream = new InputStream('enter you grammar here');
const lexer = new GrammarLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new GrammarParser(tokenStream);
// Parse the input, where
compilationUnit is whatever entry point you defined
const tree = parser.compilationUnit();
console.log(tree);
`$3
Add to your tsconfig.json:
`
"typeRoots": ["types"],
`
For Command-Line Use
$3
`bash
npm install -g antlr4-tool
``
Usage: antlr4-tool [options] Options:
-V, --version output the version number
-o --output-dir [output_dir] Output Directory (Default: Current Directory)
-l --language [language] Antlr Language Target: ts, typescript, js, javascript (Default: typescript)
--listener Generate parse tree listener (Default)
--no-listener Don't generate parse tree listener
--visitor Generate parse tree visitor (Default)
--no-visitor Don't generate parse tree visitor
-h, --help output usage information
`$3
`bash
antlr4-tool -V
`
$3
`bash
antlr4-tool -l ts -o c-parser samples/c/C.g4
`$3
`bash
antlr4-tool -l js -o c-parser samples/c/C.g4
`
Using antlr4-tool as a Library
`javascript
const tool = require('antlr4-tool');const opts = {
language: 'TypeScript', // Only support for JavaScript & TypeScript
grammarFiles: ['samples/c/C.g4'],
outputDirectory: 'c-parser'
};
const compiledResults = tool.compile(opts);
console.log(compiledResults);
``