ANTLR 4 Runtime for TypeScript/JavaScript

0.5.0-alpha.4 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates the basic workflow of parsing an input string using a generated ANTLR 4 lexer and parser in TypeScript, including traversing the parse tree with a listener.

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.");

view raw JSON →