ANTLR 4 JavaScript Runtime

4.13.2 · active · verified Sun Apr 19

The `antlr4` package provides the JavaScript runtime libraries for ANTLR 4, a powerful parser generator tool. It enables parsing various languages and data formats in Node.js (requiring Node.js >= 16) and major browsers like Safari, Firefox, and Chrome. The current stable version is 4.13.2, with minor updates released periodically. A key differentiator is its role as the official runtime for grammars defined using the ANTLR tool, supporting 10 target languages. Due to this multi-target consistency, ANTLR's versioning does not strictly follow npm semantic versioning, meaning minor version bumps can introduce breaking changes across targets; users are strongly advised to pin exact versions. The library ships with comprehensive TypeScript type definitions, making it suitable for modern TypeScript development.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core pipeline of using the ANTLR 4 JavaScript runtime to parse a simple input string. It shows how to initialize `CharStreams`, `CommonTokenStream`, and use placeholder lexer and parser classes (which would be generated by the ANTLR tool from your grammar), including custom error handling.

import { CharStreams, CommonTokenStream, error } from 'antlr4';
// IMPORTANT: MyLexer and MyParser are GENERATED by the ANTLR tool from your grammar.
// For example, if you have 'Hello.g4', run 'antlr4 -Dlanguage=JavaScript Hello.g4'
// This will create 'HelloLexer.js', 'HelloParser.js', etc. in your output directory.
// Replace './MyLexer' and './MyParser' with the correct paths to your generated files.

// A minimal mock for demonstration. In a real app, these would be generated.
class MyLexer extends error.DefaultErrorListener {
  constructor(input) { super(input); this.tokenFactory = null; this.charPositionInLine = 0; this.line = 1; }
  nextToken() { return null; /* Real lexer logic */ }
  getAllTokens() { return [{ type: 1, text: 'hello' }, { type: 2, text: 'world' }]; }
}
class MyParser extends error.DefaultErrorListener {
  constructor(tokens) { super(tokens); this.ruleNames = ['start']; this.errorHandler = null; this.tokenStream = tokens; }
  start() { return { text: 'parsed hello world' }; /* Real parser logic */ }
}

class CustomErrorListener extends error.ErrorListener {
  syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) {
    console.error(`Line ${line}, column ${charPositionInLine}: ${msg}`);
  }
}

// 1. Create an input stream from your source code
const input = CharStreams.fromString('hello world');

// 2. Create a lexer (tokenizer) from the input stream
//    (Replace MyLexer with your generated lexer, e.g., 'HelloLexer')
const lexer = new MyLexer(input);
lexer.removeErrorListeners(); // Remove default console error listener
lexer.addErrorListener(new CustomErrorListener());

// 3. Create a token stream from the lexer
const tokens = new CommonTokenStream(lexer);

// 4. Create a parser from the token stream
//    (Replace MyParser with your generated parser, e.g., 'HelloParser')
const parser = new MyParser(tokens);
parser.removeErrorListeners(); // Remove default console error listener
parser.addErrorListener(new CustomErrorListener());

// 5. Invoke the parser's entry rule (e.g., 'start')
const tree = parser.start();

console.log('Successfully attempted to parse:', input.getText());
// In a real scenario, 'tree' would be a parse tree object
// console.log('Parse tree:', tree.toStringTree(parser.ruleNames));

view raw JSON →