chevrotain vs jison vs nearley vs pegjs
Building Custom Languages and Parsers in JavaScript
chevrotainjisonnearleypegjsSimilar Packages:

Building Custom Languages and Parsers in JavaScript

chevrotain, jison, nearley, and pegjs are JavaScript libraries designed to help developers build parsersβ€”tools that read structured text (like code, config files, or data formats) and turn it into a usable format. While they all solve the same core problem, they use different underlying theories and offer distinct developer experiences. jison is a classic tool based on LALR(1) grammar, similar to Yacc. pegjs uses Parsing Expression Grammars (PEG), focusing on top-down parsing with infinite lookahead. nearley also uses PEG but adds support for probabilistic parsing and near-linear performance. chevrotain takes a unique approach by letting you write parsers in pure JavaScript code rather than a separate grammar syntax, offering high performance and excellent debugging tools.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
chevrotain02,8031.24 MB292 months agoApache-2.0
jison04,379-1629 years agoMIT
nearley03,742-1996 years agoMIT
pegjs04,902-11710 years agoMIT

Building Custom Languages: Chevrotain vs Jison vs Nearley vs PEG.js

When you need to read structured textβ€”like a custom config file, a query language, or even a new programming languageβ€”you need a parser. The JavaScript ecosystem offers four major tools for this: chevrotain, jison, nearley, and pegjs. While they all turn text into data, they work in very different ways. Choosing the right one depends on your need for speed, error handling, grammar complexity, and how much you want to learn a new syntax.

πŸ› οΈ How You Define Grammar: Code vs. Special Syntax

The biggest difference is how you tell the library what your language looks like.

chevrotain lets you write your parser using standard JavaScript classes and methods. You don't learn a new grammar language; you just write code. This makes it easy to debug because you can set breakpoints in your editor.

// chevrotain: Parser defined in pure JS
class MyParser extends Parser {
  constructor(input) {
    super(input, [MyLexer]);
    this.RULE("expression", () => {
      this.SUBRULE(this.term);
      this.OPTION(() => {
        this.CONSUME(Plus);
        this.SUBRULE2(this.term);
      });
    });
    this.performSelfAnalysis();
  }
}

jison uses a special grammar syntax based on Yacc/Bison. You write rules in a separate string or file, mixing code blocks inside the grammar definitions.

// jison: Grammar definition string
const parser = new Parser(`
  %start expression
  %%
  expression : expression '+' term { $$ = $1 + $3; }
             | term { $$ = $1; }
  ;
  term : number { $$ = $1; }
  ;
`);

pegjs uses a Parsing Expression Grammar (PEG) syntax. It looks clean and focuses on matching patterns from top to bottom.

// pegjs: PEG grammar string
const parser = peggy.generate(`
  expression = head:term tail:("+" @term)* {
    return tail.reduce((a, b) => a + b, head);
  }
  term = [0-9]+ { return parseInt(text()); }
`);

nearley also uses a PEG-style syntax but is more concise and supports advanced features like probabilistic parsing directly in the grammar definition.

// nearley: Grammar file (.ne)
expression -> term (("+" | "-") term):+ {% (data) => data[0].reduce((a, b) => a + b) %}
term -> [0-9]+ {% (data) => parseInt(data[0]) %}

⚑ Performance and Parsing Strategy

How the parser reads your text affects speed and what kinds of languages it can handle.

chevrotain builds a highly optimized parser that runs extremely fast. Because it's pure JavaScript, it avoids the overhead of interpreting a grammar string at runtime. It is often the fastest option for large inputs.

// chevrotain: High performance via static analysis
const parser = new MyParser(tokenStream);
const result = parser.expression(); // Direct method call, very fast

jison generates a table-driven parser. It is generally fast for valid input but can struggle with complex error recovery. Its LALR(1) strategy means it looks ahead only one token, which limits the kinds of grammars it can parse without conflicts.

// jison: Table-driven execution
const result = parser.parse("1 + 2"); // Uses generated lookup tables

pegjs uses a top-down approach with infinite lookahead. It tries to match rules recursively. This makes it easy to write but can be slower on large inputs or deeply nested structures because it might re-scan the same text multiple times.

// pegjs: Recursive descent
const result = parser.parse("1 + 2"); // May backtrack if rules fail

nearley improves on standard PEG by using a chart parsing algorithm. This gives it near-linear performance even for ambiguous grammars where pegjs would fail or loop forever.

// nearley: Chart parsing for efficiency
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
parser.feed("1 + 2");
const result = parser.results[0]; // Handles ambiguity gracefully

πŸš‘ Error Handling and Recovery

When a user makes a typo, how does your parser react? This is critical for tools like IDEs or linters.

chevrotain shines here. It has built-in error recovery strategies. If it finds a mistake, it can skip the bad token and keep going, allowing you to show multiple errors at once instead of stopping at the first one.

// chevrotain: Automatic error recovery
parser.expression();
if (parser.errors.length > 0) {
  // Parser found errors but kept going
  console.log("Found errors:", parser.errors);
}

jison stops immediately when it hits an error. You can define a custom error handler, but it doesn't naturally support recovering and continuing to parse the rest of the file.

// jison: Stops on first error
try {
  parser.parse("1 +"); // Throws exception immediately
} catch (e) {
  console.log("Parse failed:", e.message);
}

pegjs also throws an exception when a match fails. It tells you exactly where it got stuck, but it doesn't try to fix the input or continue parsing.

// pegjs: Throws detailed exception
try {
  parser.parse("1 +");
} catch (e) {
  console.log("Expected number at line", e.location.start.line);
}

nearley behaves similarly to pegjs by default. If the input doesn't match the grammar, it throws an error. However, because it handles ambiguity well, it can sometimes parse inputs that other PEG parsers reject, reducing false errors.

// nearley: Throws if no valid parse tree found
try {
  parser.feed("1 +");
  if (parser.results.length === 0) throw new Error("No valid parse");
} catch (e) {
  console.log("Invalid input");
}

🌐 Real-World Scenarios

Scenario 1: Building an IDE Plugin or Linter

You need to parse code even when it's incomplete or has syntax errors, so you can highlight problems as the user types.

  • βœ… Best choice: chevrotain
  • Why? Its error recovery lets you parse broken code and provide helpful feedback without crashing.
// chevrotain: Parse incomplete code safely
const parser = new MyLexerAndParser(incompleteCode);
parser.parse();
// Even with errors, you get a partial AST to highlight

Scenario 2: Parsing a Simple Config File

You have a small, well-defined format (like a custom CSS-like config) and want a quick solution.

  • βœ… Best choice: pegjs
  • Why? The grammar is simple, unambiguous, and pegjs is easy to set up.
// pegjs: Quick setup for simple formats
const config = parser.parse(`theme: dark; width: 100px;`);

Scenario 3: Experimental Language with Ambiguous Rules

You are designing a new language where some sentences could be interpreted in multiple ways, and you want to explore all possibilities.

  • βœ… Best choice: nearley
  • Why? It handles ambiguity natively and returns all possible parse trees.
// nearley: Handle ambiguous input
parser.feed("ambiguous sentence");
const allInterpretations = parser.results; // Array of all valid trees

Scenario 4: Maintaining Legacy Build Tools

You are working on an old project that uses a .jison file for its build process.

  • ⚠️ Choice: jison (only for maintenance)
  • Why? Migrating might break subtle behaviors. Stick with it until you can refactor.
// jison: Legacy compatibility
const oldParser = require('./legacy-grammar.jison');

πŸ“Œ Summary Table

Featurechevrotainjisonpegjsnearley
Definition StylePure JavaScript CodeYacc/Bison SyntaxPEG SyntaxConcise PEG Syntax
Parsing StrategyOptimized Recursive DescentLALR(1) Table-DrivenRecursive Descent (PEG)Chart Parsing (PEG)
Error Recoveryβœ… Excellent (Continues parsing)❌ Poor (Stops immediately)❌ Poor (Stops immediately)❌ Poor (Stops immediately)
Ambiguity Support❌ No❌ No❌ Noβœ… Yes (Returns all trees)
PerformanceπŸš€ Very High⚑ High🐒 Moderate⚑ High (for ambiguous)
Maintenance Statusβœ… Active⚠️ Unmaintainedβœ… Activeβœ… Active

πŸ’‘ Final Recommendation

Think about your project's needs:

  • Need robust error handling for an editor or linter? β†’ Go with chevrotain. Its ability to recover from errors is unmatched.
  • Parsing a simple, standard format? β†’ pegjs is easy to learn and sufficient for most tasks.
  • Dealing with ambiguous grammar or research? β†’ nearley is the only choice that handles multiple interpretations well.
  • Stuck on an old project? β†’ You might be using jison, but plan to migrate away since it is no longer maintained.

For most modern frontend architectures requiring custom language support, chevrotain or pegjs will be your go-to tools. Choose chevrotain for power and control, and pegjs for simplicity and speed of development.

How to Choose: chevrotain vs jison vs nearley vs pegjs

  • chevrotain:

    Choose chevrotain if you need maximum performance, strong error recovery, and the ability to debug your parser step-by-step. It is ideal for building complex IDE features, linters, or language servers where you need fine-grained control over the parsing process without learning a new grammar syntax.

  • jison:

    Avoid jison for new projects as it is largely unmaintained. Only consider it if you are maintaining a legacy codebase that already depends on its specific LALR(1) behavior and migrating to a modern alternative is too costly.

  • nearley:

    Choose nearley if you need to parse ambiguous grammars (where a sentence could have multiple valid structures) or if you want a concise grammar syntax with powerful features like built-in support for comments and whitespace handling. It is great for experimental languages or data formats with complex rules.

  • pegjs:

    Choose pegjs if you want a simple, well-established PEG parser for standard tasks like parsing configuration files, simple query languages, or data formats where ambiguity is not a concern. It offers a good balance of ease-of-use and performance for most common parsing needs.

README for chevrotain

Chevrotain

For details see:

Install

Using npm:

npm install chevrotain

or using yarn:

yarn add chevrotain