4b51e6a6d3 | 15 years ago | |
---|---|---|
benchmark | 15 years ago | |
bin | 15 years ago | |
examples | 15 years ago | |
lib | 15 years ago | |
test | 15 years ago | |
vendor | 15 years ago | |
.gitignore | 15 years ago | |
LICENSE | 15 years ago | |
README.md | 15 years ago | |
Rakefile | 15 years ago | |
VERSION | 15 years ago |
README.md
PEG.js: Parser Generator for JavaScript
PEG.js is a parser generator for JavaScript based on the parsing expression grammar formalism. It is designed to be used either from your browser or from the command line (using Rhino JavaScript interpreter).
Requirements
Both the parser generator and generated parsers should run well in IE8 and recent versions of Firefox, Chrome, Safari and Opera, as well as Rhino JavaScript engine. IE6 and IE7 are not supported.
Note: IE7 might be supported sometime in the future, IE6 probably not.
Usage
To use PEG.js, you need to generate a parser from your grammar and then use the generated parser in your project.
Generating a Parser
A parser can be generated either online in your browser or using the command line. Let's look at the second option. You need to follow these steps:
-
Install Java. This is necessary to run Rhino (which is bundled with PEG.js).
-
Generate the parser using
bin/pegjs
script on Unix orbin/pegjs.bat
batch file on Windows.
For example, to generate a parser from an example grammar in the examples/arithmetics.pegjs
file on Unix, run:
$ bin/pegjs arithmeticsParser examples/arithmetics.pegjs
This command will create the parser in the examples/arithmetics.js
file and will make it available in the arithmeticsParser
global variable.
The bin/pegjs
command has several options that influence the generator—to learn more about them, use the --help
option.
Note: In the future, I will probably use Narwhal for the command-line version.
Using the Generated Parser
Let's assume that you want to use the parser in a web page. To do this, you need to:
-
Include the generated parser into your page:
<!-- Replace "example/arithmetics.js" with your parser file --> <script src="example/arithmetics.js"></script>
This creates a variable with the parser object in the global scope (you can choose name of the variable when generating the parser).
-
Use the parser, i.e. call the
parse
method on the parser variable:<script> // Replace "arithmeticsParser" with your parser variable document.write(arithmeticsParser.parse("2*(3+4)")); </script>
The
parse
method of the generated parser will return either the result of the parsing (dependent on the actions you specified in the grammar) or throwPEG.Parser.SyntaxError
exception if the input contains a syntax error. The exception has propertiesmessage
,line
andcolumn
, which contain details about the error.
Grammar
For detailed description of the grammar see the online documentation.