jison vs nearley vs pegjs
Parsing Libraries for JavaScript
jisonnearleypegjsSimilar Packages:

Parsing Libraries for JavaScript

Parsing libraries in JavaScript are tools that help developers analyze and process text or code by breaking it down into its component parts. These libraries are essential for tasks such as interpreting programming languages, processing structured data formats (like JSON or XML), or implementing domain-specific languages (DSLs). They typically use techniques like lexical analysis (tokenization) and syntactic analysis (parsing) to convert input text into a structured format, such as an abstract syntax tree (AST), which can then be manipulated or analyzed programmatically. Parsing libraries are widely used in compilers, interpreters, code editors, and any application that needs to understand and process text-based input. jison is a JavaScript library that generates parsers from a BNF-like grammar, making it easy to create custom parsers for various text formats. nearley is a fast, powerful, and easy-to-use parsing library that supports context-free grammars and allows for the creation of parsers using a simple, intuitive syntax. pegjs is a parser generator for JavaScript that uses Parsing Expression Grammars (PEGs) to create efficient parsers, offering a clear and expressive way to define grammars for complex languages and data formats.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
jison39,4164,387-1639 years agoMIT
nearley03,741-1985 years agoMIT
pegjs04,914-11710 years agoMIT

Feature Comparison: jison vs nearley vs pegjs

Grammar Definition

  • jison:

    jison uses a BNF-like syntax for grammar definition, allowing you to specify production rules, tokens, and actions directly in the grammar file. This approach provides a clear and structured way to define how input text should be parsed.

  • nearley:

    nearley supports context-free grammars and allows for more expressive grammar definitions, including the use of multiple rules for the same non-terminal. This flexibility enables you to define complex grammatical structures with ease.

  • pegjs:

    pegjs uses Parsing Expression Grammar (PEG) notation, which provides a clear and unambiguous way to define grammars. PEGs allow for more precise control over parsing behavior, making it easier to handle ambiguities and define complex parsing rules.

Parser Generation

  • jison:

    jison generates parsers as JavaScript code from the defined grammar, allowing for easy integration into web applications or Node.js projects. The generated parsers are efficient and can handle both lexical and syntactic analysis.

  • nearley:

    nearley generates parsers that are fast and memory-efficient, with a focus on performance for context-free grammars. The generated parsers can handle large inputs and complex grammatical structures with minimal overhead.

  • pegjs:

    pegjs generates parsers from PEG grammars, producing compact and efficient JavaScript code. The generated parsers are easy to use and integrate, with built-in support for error handling and debugging.

Error Handling

  • jison:

    jison provides customizable error handling, allowing you to define how parsing errors are reported and handled. You can specify error messages, recovery strategies, and actions to take when errors occur during parsing.

  • nearley:

    nearley includes built-in error handling for syntax errors, with support for customizable error messages and recovery. The library provides tools for debugging and visualizing parsing errors, making it easier to identify and fix issues in the grammar.

  • pegjs:

    pegjs offers robust error handling, including detailed error messages and support for custom error types. The generated parsers provide clear feedback on parsing failures, which helps developers diagnose and resolve issues quickly.

Performance

  • jison:

    jison generates parsers that are optimized for performance, but the speed depends on the complexity of the grammar and the efficiency of the parsing algorithms used. For most use cases, jison provides fast parsing with minimal overhead.

  • nearley:

    nearley is known for its high performance, especially with context-free grammars. It uses a packrat parsing algorithm that ensures linear time parsing for many grammars, making it one of the fastest parsing libraries available.

  • pegjs:

    pegjs generates efficient parsers that perform well for a wide range of grammars. However, the performance can vary depending on the complexity of the PEG grammar and the presence of backtracking.

Ease of Use: Code Examples

  • jison:

    jison Example

    // Define a simple grammar in Jison
    const grammar = `
    %lex
    %%
    
    %start start
    
    %%
    
    start
      : expression
      ;
    
    expression
      : expression '+' expression
      | expression '-' expression
      | expression '*' expression
      | expression '/' expression
      | NUMBER
      ;
    
    %%
    
    // Create a parser from the grammar
    const parser = new Parser(grammar);
    
    // Parse an expression
    const result = parser.parse('3 + 4 * 2');
    console.log(result);
    
  • nearley:

    nearley Example

    // Define a simple grammar in Nearley
    const grammar = `
    @{%
    const { Parser } = require('nearley');
    const grammar = require('./my-grammar.ne'); // Import your Nearley grammar
    %}
    
    // Create a parser instance
    const parser = new Parser(grammar);
    
    // Parse some input
    parser.feed('your input here');
    
    // Get the parse result
    const result = parser.results;
    console.log(result);
    
  • pegjs:

    pegjs Example

    // Define a simple PEG grammar
    const grammar = `
    start
      = expression
    
    expression
      = left:term op:('+' / '-') right:term {
          return { type: 'expression', operator: op, left, right };
        }
    
    term
      = left:factor op:('*' / '/') right:factor {
          return { type: 'term', operator: op, left, right };
        }
    
    factor
      = '(' expr:expression ')' {
          return expr;
        }
      / number:Number
    
    Number
      = digits:[0-9]+ {
          return parseInt(digits.join(''), 10);
        }
    `;
    
    // Create a parser from the PEG grammar
    const parser = peg.generate(grammar);
    
    // Parse an expression
    const result = parser.parse('3 + 4 * 2');
    console.log(result);
    

How to Choose: jison vs nearley vs pegjs

  • jison:

    Choose jison if you need a parser generator that creates parsers from BNF-like grammars and you want fine-grained control over the parsing process. It is suitable for projects where you need to implement custom parsing logic and handle ambiguities in the grammar.

  • nearley:

    Choose nearley if you want a fast and flexible parser that supports context-free grammars and allows for easy integration with existing projects. It is ideal for applications that require high-performance parsing and support for complex grammatical structures.

  • pegjs:

    Choose pegjs if you prefer a parser generator that uses PEGs for grammar definition and you need a simple, yet powerful tool for creating parsers. It is well-suited for projects that require clear and unambiguous grammar definitions, making it easier to understand and maintain the parsing logic.

README for jison

Jison

build status

An API for creating parsers in JavaScript

Jison generates bottom-up parsers in JavaScript. Its API is similar to Bison's, hence the name. It supports many of Bison's major features, plus some of its own. If you are new to parser generators such as Bison, and Context-free Grammars in general, a good introduction is found in the Bison manual. If you already know Bison, Jison should be easy to pickup.

Briefly, Jison takes a JSON encoded grammar or Bison style grammar and outputs a JavaScript file capable of parsing the language described by that grammar. You can then use the generated script to parse inputs and accept, reject, or perform actions based on the input.

Installation

Jison can be installed for Node using npm

Using npm:

npm install jison -g

Usage from the command line

Clone the github repository for examples:

git clone git://github.com/zaach/jison.git
cd jison/examples

Now you're ready to generate some parsers:

jison calculator.jison

This will generate calculator.js in your current working directory. This file can be used to parse an input file, like so:

echo "2^32 / 1024" > testcalc
node calculator.js testcalc

This will print out 4194304.

Full cli option list:

Usage: jison [file] [lexfile] [options]

file        file containing a grammar
lexfile     file containing a lexical grammar

Options:
   -j, --json                    force jison to expect a grammar in JSON format
   -o FILE, --outfile FILE       Filename and base module name of the generated parser
   -t, --debug                   Debug mode
   -m TYPE, --module-type TYPE   The type of module to generate (commonjs, amd, js)
   -p TYPE, --parser-type TYPE   The type of algorithm to use for the parser (lr0, slr, lalr, lr)
   -V, --version                 print version and exit

Usage from a CommonJS module

You can generate parsers programatically from JavaScript as well. Assuming Jison is in your commonjs environment's load path:

// mygenerator.js
var Parser = require("jison").Parser;

// a grammar in JSON
var grammar = {
    "lex": {
        "rules": [
           ["\\s+", "/* skip whitespace */"],
           ["[a-f0-9]+", "return 'HEX';"]
        ]
    },

    "bnf": {
        "hex_strings" :[ "hex_strings HEX",
                         "HEX" ]
    }
};

// `grammar` can also be a string that uses jison's grammar format
var parser = new Parser(grammar);

// generate source, ready to be written to disk
var parserSource = parser.generate();

// you can also use the parser directly from memory

// returns true
parser.parse("adfe34bc e82a");

// throws lexical error
parser.parse("adfe34bc zxg");

More Documentation

For more information on creating grammars and using the generated parsers, read the documentation.

How to contribute

See CONTRIBUTING.md for contribution guidelines, how to run the tests, etc.

Projects using Jison

View them on the wiki, or add your own.

Contributors

Githubbers

Special thanks to Jarred Ligatti, Manuel E. BermΓΊdez

License

Copyright (c) 2009-2014 Zachary Carter

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.