{"id":10499,"library":"antlr4","title":"ANTLR 4 JavaScript Runtime","description":"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.","status":"active","version":"4.13.2","language":"javascript","source_language":"en","source_url":"https://github.com/antlr/antlr4","tags":["javascript","lexer","parser","antlr","antlr4","grammar","typescript"],"install":[{"cmd":"npm install antlr4","lang":"bash","label":"npm"},{"cmd":"yarn add antlr4","lang":"bash","label":"yarn"},{"cmd":"pnpm add antlr4","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"`CharStreams.fromString()` is the recommended way to create an input stream from a string since ANTLR 4.9. The older `ANTLRInputStream` is still available but deprecated.","wrong":"import { ANTLRInputStream } from 'antlr4'; // ANTLRInputStream is deprecated","symbol":"CharStreams","correct":"import { CharStreams } from 'antlr4';"},{"note":"The library supports both ES Modules and CommonJS. Use named imports for ESM. CJS users should access exports directly from the main `antlr4` module.","wrong":"const CommonTokenStream = require('antlr4').CommonTokenStream;","symbol":"CommonTokenStream","correct":"import { CommonTokenStream } from 'antlr4';"},{"note":"Base class for all generated parser rule contexts. Essential for working with parse trees.","symbol":"ParserRuleContext","correct":"import { ParserRuleContext } from 'antlr4';"},{"note":"Error handling components are nested under the `error` namespace.","symbol":"error.ErrorListener","correct":"import { error } from 'antlr4';\nconst { ErrorListener } = error;"}],"quickstart":{"code":"import { CharStreams, CommonTokenStream, error } from 'antlr4';\n// IMPORTANT: MyLexer and MyParser are GENERATED by the ANTLR tool from your grammar.\n// For example, if you have 'Hello.g4', run 'antlr4 -Dlanguage=JavaScript Hello.g4'\n// This will create 'HelloLexer.js', 'HelloParser.js', etc. in your output directory.\n// Replace './MyLexer' and './MyParser' with the correct paths to your generated files.\n\n// A minimal mock for demonstration. In a real app, these would be generated.\nclass MyLexer extends error.DefaultErrorListener {\n  constructor(input) { super(input); this.tokenFactory = null; this.charPositionInLine = 0; this.line = 1; }\n  nextToken() { return null; /* Real lexer logic */ }\n  getAllTokens() { return [{ type: 1, text: 'hello' }, { type: 2, text: 'world' }]; }\n}\nclass MyParser extends error.DefaultErrorListener {\n  constructor(tokens) { super(tokens); this.ruleNames = ['start']; this.errorHandler = null; this.tokenStream = tokens; }\n  start() { return { text: 'parsed hello world' }; /* Real parser logic */ }\n}\n\nclass CustomErrorListener extends error.ErrorListener {\n  syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) {\n    console.error(`Line ${line}, column ${charPositionInLine}: ${msg}`);\n  }\n}\n\n// 1. Create an input stream from your source code\nconst input = CharStreams.fromString('hello world');\n\n// 2. Create a lexer (tokenizer) from the input stream\n//    (Replace MyLexer with your generated lexer, e.g., 'HelloLexer')\nconst lexer = new MyLexer(input);\nlexer.removeErrorListeners(); // Remove default console error listener\nlexer.addErrorListener(new CustomErrorListener());\n\n// 3. Create a token stream from the lexer\nconst tokens = new CommonTokenStream(lexer);\n\n// 4. Create a parser from the token stream\n//    (Replace MyParser with your generated parser, e.g., 'HelloParser')\nconst parser = new MyParser(tokens);\nparser.removeErrorListeners(); // Remove default console error listener\nparser.addErrorListener(new CustomErrorListener());\n\n// 5. Invoke the parser's entry rule (e.g., 'start')\nconst tree = parser.start();\n\nconsole.log('Successfully attempted to parse:', input.getText());\n// In a real scenario, 'tree' would be a parse tree object\n// console.log('Parse tree:', tree.toStringTree(parser.ruleNames));\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Update your `package.json` to pin the exact version of `antlr4` you are using (e.g., `\"antlr4\": \"4.13.2\"`) to prevent unexpected breaking changes with `npm install`.","message":"ANTLR's versioning does not strictly follow npm semantic versioning, prioritizing consistency across its 10 target languages. This means minor version updates (e.g., 4.x.0 to 4.y.0) can introduce breaking changes. Developers are strongly advised to remove the `^` or `~` from `antlr4` entries in `package.json` to pin specific versions (e.g., `\"antlr4\": \"4.13.2\"`) and manually update.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"After updating the `antlr4` npm package, regenerate your lexer and parser JavaScript files using the ANTLR tool (e.g., `java -jar antlr-4.13.2-complete.jar -Dlanguage=JavaScript MyGrammar.g4`) matching the new runtime version.","message":"Starting with ANTLR 4.10.0, lexers and parsers generated by the ANTLR tool are often incompatible with code generated by previous versions of the tool. While the JavaScript runtime specifically noted 'except probably javascript' for 4.10.0, this general rule applies across targets. If you upgrade the `antlr4` runtime, you should also regenerate all your grammar-based lexer and parser code using the ANTLR tool (e.g., the `antlr4` JAR) of the *same major version* as the runtime to ensure compatibility.","severity":"breaking","affected_versions":">=4.10.0"},{"fix":"Ensure your Node.js environment is updated to version 16 or higher. You can use `nvm` or your system's package manager to upgrade Node.js.","message":"The `antlr4` package requires Node.js version 16 or newer. Using it with older Node.js versions will result in runtime errors or failures during installation.","severity":"breaking","affected_versions":"<4.0.0 (exact version depends on previous updates but >=16 is current)"},{"fix":"Replace `new ANTLRInputStream(inputString)` with `CharStreams.fromString(inputString)`.","message":"The `ANTLRInputStream` class, used for creating input streams, has been deprecated in favor of `CharStreams.fromString()` (or other `CharStreams` methods for files/buffers). While still functional, using `ANTLRInputStream` directly is discouraged.","severity":"deprecated","affected_versions":">=4.9.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Regenerate your lexer and parser JavaScript/TypeScript files using the ANTLR tool that matches the version of your `antlr4` npm package. For example, if you updated to `antlr4@4.13.2`, use `antlr-4.13.2-complete.jar` to generate your grammar files.","cause":"This error typically occurs in TypeScript projects when the generated lexer/parser files (e.g., `MyLexer.js` or `MyLexer.ts`) are out of sync with the `antlr4` runtime library's type definitions. This happens after upgrading the `antlr4` package without regenerating the grammar files.","error":"Error: The '`MyLexer`' class extends '`Lexer`' but is missing the following properties from type '`Lexer`': `tokenFactory`"},{"fix":"For CommonJS, use `const { CommonTokenStream } = require('antlr4');` or `const antlr4 = require('antlr4'); const CommonTokenStream = antlr4.CommonTokenStream;`. Ensure `antlr4` is installed.","cause":"This usually indicates an incorrect CommonJS `require` call where the named export is not directly accessible or a missing dependency.","error":"TypeError: Cannot read properties of undefined (reading 'CommonTokenStream')"},{"fix":"If your project is CommonJS-based, ensure you are using `const { NamedExport } = require('antlr4');`. If this specific error persists for deep imports, consider refactoring the affected part of your code to use dynamic `import()` or switch your project to ES Modules.","cause":"This error occurs in a CommonJS context when a module, explicitly marked as ESM-only, is attempted to be `require()`-d. While `antlr4` supports both, specific deep imports or usage in older build tools might trigger this.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported. Instead change the require of ... to a dynamic import()"}],"ecosystem":"npm"}