ANTLR 4 Runtime for TypeScript/JavaScript
antlr4ts is the official TypeScript/JavaScript runtime for ANTLR 4, a powerful parser generator. It enables developers to execute grammars written in ANTLR 4 within JavaScript or TypeScript applications, providing core parsing functionalities such as lexers, parsers, and tree walkers/visitors. Currently, the package is in an alpha state (v0.5.0-alpha.4), indicating ongoing development and potential API changes. Releases are made periodically to incorporate updates from the main ANTLR 4 Java target, fix bugs, and ensure compatibility with newer TypeScript versions. Its key differentiators include strong typing due to its TypeScript foundation, full support for ANTLR 4 features like listeners and visitors, and an integrated CLI for grammar compilation.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` syntax in an ES Module context (e.g., in a modern TypeScript project configured for ES Modules or in a browser environment without a bundler).fixChange `const MyClass = require('antlr4ts').MyClass;` to `import { MyClass } from 'antlr4ts';`. Ensure your `tsconfig.json` targets `ES2015` or later and has `"module": "ESNext"` or `"ES2020"` for Node.js environments, or `"UMD"`/`"AMD"` for browser environments if using a bundler. -
error TS2307: Cannot find module './MyGrammarLexer' or its corresponding type declarations.
cause The generated lexer/parser files (`.ts` or `.js` and `.d.ts`) were not created or are not in the expected path. This typically means the `antlr4ts-cli` command was not run or failed.fixRun your `antlr4ts` script (e.g., `npm run antlr4ts`) to generate the lexer and parser files from your `.g4` grammar. Verify the output directory and adjust your import paths accordingly. -
Error: Java Runtime Environment (JRE) 1.6+ is required.
cause The `antlr4ts-cli` command failed because a compatible Java Runtime Environment is not installed or not accessible in the system's PATH.fixInstall a JRE version 1.6 or higher (JRE 8 or newer is recommended). Ensure the `java` executable is available in your system's PATH environment variable.
Warnings
- gotcha The package is currently in an 'alpha' state. This means the API is subject to change without strict adherence to semantic versioning for breaking changes, and stability cannot be guaranteed. Use in production with caution.
- breaking Between alpha versions, method signatures and property access patterns can change. For example, some 'get'/'set' methods were converted to properties in `0.4.0-alpha.3`.
- gotcha Compiling ANTLR 4 grammars (`.g4` files) into TypeScript code requires a Java Runtime Environment (JRE 1.6+, 1.8+ recommended) installed on the development machine, as the ANTLR tool itself is Java-based.
- breaking Older versions of `antlr4ts` and its generated code had specific TypeScript version requirements. For instance, TypeScript 2.1 became mandatory in `0.4.0-alpha.2`, and `0.5.0-alpha.4` included fixes for TypeScript 4 compatibility.
Install
-
npm install antlr4ts -
yarn add antlr4ts -
pnpm add antlr4ts
Imports
- ANTLRInputStream
const ANTLRInputStream = require('antlr4ts').ANTLRInputStream;import { ANTLRInputStream } from 'antlr4ts'; - CommonTokenStream
import CommonTokenStream from 'antlr4ts/CommonTokenStream';
import { CommonTokenStream } from 'antlr4ts'; - ParseTreeWalker
import { ParseTreeWalker } from 'antlr4ts';import { ParseTreeWalker } from 'antlr4ts/tree/ParseTreeWalker'; - MyGrammarLexer
import { MyGrammarLexer } from 'antlr4ts';import { MyGrammarLexer } from './MyGrammarLexer';
Quickstart
import { ANTLRInputStream, CommonTokenStream } from 'antlr4ts';
import { MyGrammarLexer } from './MyGrammarLexer'; // Assuming generated lexer
import { MyGrammarParser, FunctionDeclarationContext } from './MyGrammarParser'; // Assuming generated parser and context
import { MyGrammarParserListener } from './MyGrammarParserListener'; // Assuming generated listener interface
import { ParseTreeWalker } from 'antlr4ts/tree/ParseTreeWalker';
// Step 1: Define your input text
const inputText = "function myFunction() { return 42; }";
// Step 2: Create an ANTLRInputStream from the input
let inputStream = new ANTLRInputStream(inputText);
// Step 3: Create a lexer (generated from your grammar) and tokenize the input
let lexer = new MyGrammarLexer(inputStream);
let tokenStream = new CommonTokenStream(lexer);
// Step 4: Create a parser (generated from your grammar) and parse the token stream
let parser = new MyGrammarParser(tokenStream);
// Step 5: Specify the entry point rule for parsing
let tree = parser.compilationUnit(); // Assuming 'compilationUnit' is your grammar's starting rule
// Step 6: (Optional) Implement a listener to traverse the parse tree
class MyFunctionListener implements MyGrammarParserListener {
enterFunctionDeclaration(context: FunctionDeclarationContext) {
console.log(`Found function: ${context.text} on line ${context._start.line}`);
// Additional logic to extract details from the function declaration
}
// Implement other enter/exit methods as needed for your grammar rules
}
// Step 7: Walk the parse tree with your listener
const listener = new MyFunctionListener();
ParseTreeWalker.DEFAULT.walk(listener, tree);
console.log("Parsing complete. Check console for listener output.");