antlr4-tool
Overview
The purpose and intent of this project was to create and generate Typescript declaration files for the Antlr4 JavaScript target. Allowing for generated Antlr Parsers and Lexers that have full ES5 browser support. This tool also allows for pure JavaScript implementations, if needed.
Requirements
- Java Runtime Environment 1.6+ (1.8+ recommended)
Getting Stated
- Install antlr4-tool, adding it to your package.json
npm install --save-dev antlr4-tool
- Install the Antlr4 library
npm install -S antlr4 # # (TypeScript Only) # npm install -S @types/antlr4
- Add a grammar to your project, e.g. path/to/Grammar.g4
"scripts":
- Run the NPM script command
npm run generate-parser
- Use your generated Parser
JavaScript
const antlr4 = const InputStream = antlr4InputStream;const CommonTokenStream = antlr4CommonTokenStream; const GrammarParser = GrammarParser;const GrammarLexer = GrammarLexer; const inputStream = 'int x = 10;';const lexer = inputStream;const tokenStream = lexer;const parser = tokenStream; // Parse the input, where `compilationUnit` is whatever entry point you definedconst tree = parser;console;
TypeScript
;;; ;;;; // Parse the input, where `compilationUnit` is whatever entry point you defined;console.logtree;
TypeScript Notes
Add to your tsconfig.json:
"typeRoots": ["types"],
For Command-Line Use
Installation For Command-Line Use
npm install -g antlr4-tool
Usage: antlr4-tool [options] <grammars...>
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
Finding the Version
antlr4-tool -V
Example Creating a C Parser for TypeScript
antlr4-tool -l ts -o c-parser samples/c/C.g4
Example Creating a C Parser for JavaScript
antlr4-tool -l js -o c-parser samples/c/C.g4
Using antlr4-tool as a Library
const tool = ; const opts = language: 'TypeScript' // Only support for JavaScript & TypeScript grammarFiles: 'samples/c/C.g4' outputDirectory: 'c-parser'; const compiledResults = tool; console;