ANTLR4 TypeScript Runtime (antlr4ng)

3.0.16 · active · verified Sun Apr 19

antlr4ng is an alternative, TypeScript-first runtime for ANTLR4 grammars, specifically designed to be used with the `antlr-ng` parser generation tool. Currently stable at version `3.0.16`, it receives frequent point releases addressing bugs and introducing minor enhancements. Unlike the original ANTLR4 JavaScript runtime, `antlr4ng` operates identically across Node.js and browser environments and is built with strict TypeScript nullability checks. It requires an ES2022 (ES6) compatible runtime for features like static initialization blocks and private class fields. While implementing nearly all features of the Java ANTLR4 runtime, it notably omits the `UnbufferedCharStream` class. Developers migrating from other ANTLR4 JavaScript runtimes will need to adjust code for stricter null handling and renamed internal members.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a simple arithmetic expression using generated lexer and parser, highlighting basic setup with `CharStream` and `CommonTokenStream` from `antlr4ng`.

import { CharStream, CommonTokenStream } from "antlr4ng";
import { ExpressionLexer } from "./generated/ExpressionLexer.js";
import { ExpressionParser } from "./generated/ExpressionParser.js";

const input = "1 + 2 * 3";
const inputStream = CharStream.fromString(input);
const lexer = new ExpressionLexer(inputStream);
const tokenStream = new CommonTokenStream(lexer);
const parser = new ExpressionParser(tokenStream);

// Optionally configure error handling or listeners
// parser.removeErrorListeners();
// parser.addErrorListener(new MyErrorListener());

const tree = parser.start();

// To demonstrate visitor usage (assuming MyVisitor is defined):
// import { ExpressionVisitor } from "./generated/ExpressionVisitor.js";
// import { AddContext } from "./generated/ExpressionParser.js"; // Example context type
//
// class MyVisitor extends ExpressionVisitor<number> {
//   public visitAdd = (ctx: AddContext): number => {
//     // Assuming visit is implemented for other rule contexts
//     return this.visit(ctx.expression(0)) + this.visit(ctx.expression(1));
//   };
//   // ... implement other visit methods
//   protected defaultResult(): number { return 0; }
//   protected aggregateResult(aggregate: number, nextResult: number): number { return nextResult; }
// }
// const result = new MyVisitor().visit(tree);
// console.log(`Parse tree successfully created. Visitor result: ${result}`);
console.log("Parse tree successfully created.");

view raw JSON →