Top Related Projects
A library and language for building parsers, interpreters, compilers, etc.
PEG.js: Parser generator for JavaScript
A monadic LL(infinity) parser combinator library for javascript
📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
Parser Building Toolkit for JavaScript
Quick Overview
Jison is a parser generator for JavaScript, inspired by Bison and Yacc. It allows developers to define grammars using a syntax similar to Bison/Yacc and generates JavaScript code that can parse the defined language. Jison is particularly useful for creating domain-specific languages, interpreters, and compilers in JavaScript.
Pros
- Easy to use for developers familiar with Bison/Yacc syntax
- Generates pure JavaScript code, making it suitable for both browser and Node.js environments
- Supports both LALR(1) and LR(1) parsing algorithms
- Includes a lexical analyzer generator, eliminating the need for separate lexer tools
Cons
- Documentation can be sparse and outdated in some areas
- Performance may not be optimal for very large or complex grammars
- Limited community support compared to more mainstream parsing tools
- Debugging complex grammars can be challenging
Code Examples
- Defining a simple arithmetic grammar:
%lex
%%
\s+ /* skip whitespace */
[0-9]+ return 'NUMBER'
"+" return '+'
"-" return '-'
"*" return '*'
"/" return '/'
"(" return '('
")" return ')'
/lex
%left '+' '-'
%left '*' '/'
%%
expressions
: e EOF
{ return $1; }
;
e
: e '+' e
{ $$ = $1 + $3; }
| e '-' e
{ $$ = $1 - $3; }
| e '*' e
{ $$ = $1 * $3; }
| e '/' e
{ $$ = $1 / $3; }
| '(' e ')'
{ $$ = $2; }
| NUMBER
{ $$ = Number(yytext); }
;
- Generating and using the parser:
const Parser = require('jison').Parser;
const grammar = fs.readFileSync('arithmetic.jison', 'utf8');
const parser = new Parser(grammar);
const result = parser.parse('3 + 4 * (2 - 1)');
console.log(result); // Output: 7
- Adding custom error handling:
%{
const CustomError = function(message, hash) {
this.name = 'CustomError';
this.message = message;
this.hash = hash;
};
%}
%%
/* Grammar rules */
%%
parser.yy.parseError = function(str, hash) {
throw new CustomError(str, hash);
};
Getting Started
-
Install Jison:
npm install jison
-
Create a grammar file (e.g.,
my_grammar.jison
) and define your language. -
Generate the parser:
const Parser = require('jison').Parser; const fs = require('fs'); const grammar = fs.readFileSync('my_grammar.jison', 'utf8'); const parser = new Parser(grammar); // Optional: Generate standalone parser file fs.writeFileSync('parser.js', parser.generate());
-
Use the parser in your code:
const result = parser.parse('your input string here'); console.log(result);
Competitor Comparisons
A library and language for building parsers, interpreters, compilers, etc.
Pros of Ohm
- More flexible and expressive grammar syntax, allowing for easier handling of complex language structures
- Better error reporting and debugging capabilities, making it easier to identify and fix issues in grammars
- Supports incremental parsing, which can improve performance for large inputs or frequent updates
Cons of Ohm
- Steeper learning curve due to its unique approach to grammar definition
- Less widespread adoption compared to Jison, potentially resulting in a smaller community and fewer resources
Code Comparison
Jison grammar example:
expression
: NUMBER
| expression '+' expression
| expression '-' expression
;
Ohm grammar example:
Expression {
Exp = number | Exp "+" Exp | Exp "-" Exp
number = digit+
}
Both Jison and Ohm are popular parser generators for JavaScript, but they differ in their approach to grammar definition and parsing. Jison follows a more traditional LALR(1) parsing approach, while Ohm uses a unique PEG-like syntax with additional features.
Ohm's flexibility and powerful error reporting make it attractive for complex language processing tasks, but its unique approach may require more time to master. Jison, on the other hand, offers a more familiar syntax for those experienced with tools like Yacc or Bison, and has a larger user base.
Ultimately, the choice between Jison and Ohm depends on the specific requirements of your project and your familiarity with different parsing techniques.
PEG.js: Parser generator for JavaScript
Pros of PEG.js
- Simpler syntax and easier to learn for beginners
- Generates faster parsers for certain grammar types
- Better documentation and more extensive examples
Cons of PEG.js
- Less flexible than Jison for complex grammars
- Limited support for left-recursive rules
- Smaller community and fewer third-party tools
Code Comparison
PEG.js grammar example:
start
= additive
additive
= left:multiplicative "+" right:additive { return left + right; }
/ multiplicative
multiplicative
= left:primary "*" right:multiplicative { return left * right; }
/ primary
primary
= integer
/ "(" additive:additive ")" { return additive; }
integer "integer"
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }
Jison grammar example:
%lex
%%
\s+ /* skip whitespace */
[0-9]+ return 'NUMBER'
"*" return '*'
"+" return '+'
"(" return '('
")" return ')'
/lex
%%
expressions
: e
;
e
: e '+' e
{$$ = $1 + $3;}
| e '*' e
{$$ = $1 * $3;}
| '(' e ')'
{$$ = $2;}
| NUMBER
{$$ = Number(yytext);}
;
Both PEG.js and Jison are powerful parser generators for JavaScript, but they have different strengths and use cases. PEG.js is often preferred for simpler grammars and quick prototyping, while Jison offers more flexibility for complex language parsing tasks.
A monadic LL(infinity) parser combinator library for javascript
Pros of Parsimmon
- More flexible and expressive, allowing for easier creation of complex parsers
- Better performance for certain types of grammars
- Easier to debug and maintain due to its functional programming approach
Cons of Parsimmon
- Steeper learning curve, especially for those unfamiliar with functional programming
- Less suitable for generating parsers from formal grammar specifications
- May require more code for simple parsing tasks compared to Jison
Code Comparison
Jison example:
expression
: NUMBER
| expression '+' expression
| expression '-' expression
;
Parsimmon example:
const expr = P.lazy(() => P.alt(
P.regexp(/[0-9]+/).map(Number),
P.seq(expr, P.string('+'), expr).map(([left, _, right]) => left + right),
P.seq(expr, P.string('-'), expr).map(([left, _, right]) => left - right)
));
Both Jison and Parsimmon are popular parser generators for JavaScript, but they take different approaches. Jison follows a more traditional LALR(1) parsing method, while Parsimmon uses parser combinators. Jison is better suited for generating parsers from formal grammars, while Parsimmon offers more flexibility and expressiveness for complex parsing tasks. The choice between the two depends on the specific requirements of your project and your familiarity with different parsing paradigms.
📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
Pros of Nearley
- More modern and actively maintained
- Supports streaming input for parsing large files
- Offers better error reporting and debugging tools
Cons of Nearley
- Steeper learning curve due to its unique grammar syntax
- Potentially slower parsing speed for complex grammars
- Less extensive documentation compared to Jison
Code Comparison
Jison grammar example:
expression
: NUMBER
| expression '+' expression
| expression '-' expression
;
Nearley grammar example:
expression -> number
| expression "+" expression
| expression "-" expression
number -> [0-9]:+
Both Jison and Nearley are parser generators for JavaScript, but they differ in their approach and features. Jison follows a more traditional LALR(1) parsing method, while Nearley uses the Earley parsing algorithm, which allows for more flexible grammars.
Nearley's modern approach and active development make it attractive for new projects, especially those requiring streaming input or advanced error handling. However, Jison's simpler syntax and extensive documentation may be preferable for developers familiar with traditional parser generators or working on less complex parsing tasks.
When choosing between the two, consider your project's specific requirements, your team's expertise, and the complexity of the grammars you need to parse.
Parser Building Toolkit for JavaScript
Pros of Chevrotain
- Better performance due to its parsing algorithm and optimizations
- More flexible and customizable, allowing for complex grammar definitions
- Extensive documentation and examples for easier adoption
Cons of Chevrotain
- Steeper learning curve, especially for developers new to parsing
- Requires more boilerplate code for basic parser setup
Code Comparison
Jison:
expression
: NUMBER
| expression '+' expression
| expression '-' expression
;
Chevrotain:
const $ = this;
$.RULE("expression", () => {
$.OR([
{ ALT: () => $.CONSUME(NumberToken) },
{ ALT: () => {
$.SUBRULE($.expression);
$.CONSUME(PlusToken);
$.SUBRULE2($.expression);
}},
{ ALT: () => {
$.SUBRULE($.expression);
$.CONSUME(MinusToken);
$.SUBRULE2($.expression);
}}
]);
});
Chevrotain offers more granular control over parsing rules but requires more verbose syntax. Jison's syntax is more concise and closer to traditional BNF notation, making it easier for quick grammar definitions. However, Chevrotain's approach allows for more complex parsing scenarios and better integration with JavaScript ecosystems.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Jison
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
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.
Top Related Projects
A library and language for building parsers, interpreters, compilers, etc.
PEG.js: Parser generator for JavaScript
A monadic LL(infinity) parser combinator library for javascript
📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
Parser Building Toolkit for JavaScript
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot