These four packages are parser generators that allow developers to define formal grammars and automatically create parsers for custom languages, domain-specific languages (DSLs), or complex data formats. antlr4 provides an industry-standard LL(*) parsing runtime suitable for complex, multi-language projects. jison brings the classic Yacc/Bison LALR(1) approach to JavaScript. nearley offers a modern, unlimited-lookahead grammar system optimized for readability and debugging. pegjs implements Parsing Expression Grammars (PEG), focusing on simplicity and top-down parsing logic directly within JavaScript.
When frontend applications grow complex, you often need to parse more than just JSON or URL parameters. Whether you are building a query builder, a custom configuration language, or a formula engine, you need a parser generator. The tools antlr4, jison, nearley, and pegjs all solve this problem, but they use different mathematical models and offer vastly different developer experiences. Let's compare how they handle grammar definition, execution, and error management.
The way you write your grammar rules dictates how the parser behaves and how easy it is to maintain.
antlr4 uses a separate .g4 grammar file that must be compiled to JavaScript before use. It supports LL(*) parsing, which handles a wide range of grammars but requires a build step.
// antlr4: Grammar defined in separate .g4 file
// Then compiled to JS classes like MyParser.js
grammar Calc;
expression: term (('+' | '-') term)*;
term: factor (('*' | '/') factor)*;
factor: INT | '(' expression ')';
INT: [0-9]+;
jison uses a JSON structure or a Yacc-style string to define LALR(1) grammars. It looks very similar to C-based parser generators.
// jison: Grammar defined in JSON or Yacc format
var grammar = {
"bnf": {
"expression": ["term", "expression '+' term"],
"term": ["factor", "term '*' factor"],
"factor": ["INT", "'(' expression ')'"]
}
};
nearley uses a custom grammar syntax that is concise and supports unlimited lookahead. It compiles to a JavaScript module.
// nearley: Grammar defined in .ne file
expression -> term (("+" | "-") term)*
term -> factor (("*" | "/") factor)*
factor -> INT | "(" expression ")"
INT -> [0-9]+:
pegjs uses Parsing Expression Grammar (PEG) syntax, which is intuitive and looks like a mix of regex and code. It is defined as a string passed to the generator.
// pegjs: Grammar defined as a string
var grammar = `
expression = term (('+' / '-') term)*
term = factor (('*' / '/') factor)*
factor = INT / '(' expression ')'
INT = [0-9]+
`;
Once you have a grammar, the runtime API determines how you integrate parsing into your application logic.
antlr4 requires setting up a stream, a lexer, and a token stream before creating the parser instance. It is verbose but gives fine-grained control.
// antlr4: Verbose setup chain
const chars = new antlr4.InputStream(input);
const lexer = new CalcLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new CalcParser(tokens);
const tree = parser.expression();
jison provides a straightforward constructor that takes the grammar object and returns a parser with a parse method.
// jison: Direct constructor
const Parser = require('jison').Parser;
const parser = new Parser(grammar);
const result = parser.parse(input);
nearley requires compiling the grammar first, then feeding input into the parser instance. It returns an array of possible results.
// nearley: Feed-based execution
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
parser.feed(input);
console.log(parser.results);
pegjs generates a parser object directly from the grammar string. The resulting object has a simple parse method.
// pegjs: Generate and parse
const parser = peg.generate(grammar);
const result = parser.parse(input);
How the tool fails is just as important as how it succeeds, especially for user-facing languages.
antlr4 has a robust error listener system. You can override the default listener to collect errors and continue parsing, allowing for partial results.
// antlr4: Custom error listener
class CustomListener extends antlr4.error.ErrorListener {
syntaxError(recognizer, offendingSymbol, line, col, msg, e) {
console.log(`Error at ${line}:${col}: ${msg}`);
}
}
parser.removeErrorListeners();
parser.addErrorListener(new CustomListener());
jison throws an exception when it encounters a syntax error. You must wrap the parse call in a try-catch block to handle failures gracefully.
// jison: Try-catch required
try {
parser.parse(input);
} catch (e) {
console.log('Parse failed:', e.message);
}
nearley throws an error if the input does not match the grammar. It provides line and column information in the exception object.
// nearley: Exception with location
try {
parser.feed(input);
} catch (e) {
console.log(`Failed at line ${e.line}, col ${e.column}`);
}
pegjs throws a SyntaxError with detailed location data. It also allows you to pass a start rule if you want to parse a specific subset of the grammar.
// pegjs: Detailed SyntaxError
try {
parser.parse(input, { startRule: "expression" });
} catch (e) {
console.log(`Expected ${e.expected} at ${e.location.start}`);
}
For long-term projects, the activity level of the maintainers matters as much as the features.
antlr4 is part of a massive ecosystem supporting Java, C#, Python, and more. It is actively maintained and widely used in enterprise tooling. You get long-term stability.
// antlr4: Enterprise support
// Regular updates, cross-language grammar sharing
// Suitable for mission-critical compilers
jison is an older project with less frequent updates. It is stable but does not see new features often. It is best for maintaining legacy systems rather than starting new ones.
// jison: Legacy stability
// Good for porting old Yacc grammars
// Less active community compared to newer tools
nearley is actively maintained with a focus on developer experience. It has a strong community presence in the JavaScript DSL space and regular improvements.
// nearley: Modern DX
// Active NPM package
// Good documentation and examples
pegjs is the original PEG library for JS, but development has slowed. The community fork peggy is now the recommended path for active development, though pegjs remains functional.
// pegjs: Community fork available
// Core features are stable
// Consider 'peggy' for new projects needing active maintenance
| Feature | antlr4 | jison | nearley | pegjs |
|---|---|---|---|---|
| Formalism | LL(*) | LALR(1) | Unlimited Lookahead | PEG |
| Setup | External CLI + Runtime | JSON or Yacc String | .ne File + Compiler | Grammar String |
| Error Recovery | Advanced Listeners | Basic Exception | Exception | Exception with Location |
| Best For | Complex Languages | Legacy Ports | Modern DSLs | Simple Configs |
antlr4 is the heavy-duty choice 🏗️. Use it when you are building a compiler or a language that needs to scale across multiple platforms. The setup cost is high, but the power is unmatched.
jison is the legacy bridge 🌉. Use it if you are migrating old C tools to the web. For new work, there are better options.
nearley is the modern standard 🎯. It balances power and ease of use perfectly for JavaScript teams. It is the safest bet for new DSLs.
pegjs is the simple tool 🔧. It works well for small tasks, but keep an eye on the peggy fork for future-proofing.
Final Thought: All four tools can parse text into data. The decision comes down to how complex your language is and how much time you want to spend managing the parser itself versus building your product.
Choose nearley if you want a modern, JavaScript-native experience with excellent debugging tools and unlimited lookahead capabilities. It is ideal for creating DSLs where grammar readability and ease of maintenance are priorities. The compilation step is fast, and the runtime is lightweight compared to ANTLR.
Choose antlr4 if you are building a complex language that requires robust error recovery, multiple target languages, or integration with existing ANTLR grammars. It is the best fit for enterprise-grade tooling where performance and strict formalism outweigh bundle size concerns. Be prepared for a steeper learning curve and a heavier runtime dependency.
Choose pegjs if you need a simple, top-down parser for configuration files or small DSLs where PEG formalism fits your mental model. It requires no separate compilation step if you generate the parser at build time. Note that the community has largely shifted to the peggy fork for active maintenance, so evaluate long-term support needs carefully.
Choose jison if you have existing Yacc or Bison grammars you need to port to JavaScript without rewriting the logic. It is suitable for legacy projects or teams already familiar with LALR(1) parser theory. However, for new greenfield projects, consider more modern alternatives due to its age and slower evolution.
nearley is a simple, fast and powerful parsing toolkit. It consists of:
nearley is a streaming parser with support for catching errors gracefully and providing all parsings for ambiguous grammars. It is compatible with a variety of lexers (we recommend moo). It comes with tools for creating tests, railroad diagrams and fuzzers from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser.
Unlike most other parser generators, nearley can handle any grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. left recursive ones), nearley handles them easily and efficiently by using the Earley parsing algorithm.
nearley is used by a wide variety of projects:
nearley is an npm staff pick.
Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired.
Please read this document before working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github).
nearley is MIT licensed.
A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables.
If you are citing nearley in academic work, please use the following BibTeX entry.
@misc{nearley,
author = "Kartik Chandra and Tim Radvan",
title = "{nearley}: a parsing toolkit for {JavaScript}",
year = {2014},
doi = {10.5281/zenodo.3897993},
url = {https://github.com/kach/nearley}
}