| 1 | [](https://travis-ci.org/pegjs/pegjs) |
| 2 | [](https://www.npmjs.com/package/pegjs) |
| 3 | [](https://github.com/pegjs/bower) |
| 4 | [](https://opensource.org/licenses/MIT) |
| 5 | |
| 6 | PEG.js |
| 7 | ====== |
| 8 | |
| 9 | PEG.js is a simple parser generator for JavaScript that produces fast parsers |
| 10 | with excellent error reporting. You can use it to process complex data or |
| 11 | computer languages and build transformers, interpreters, compilers and other |
| 12 | tools easily. |
| 13 | |
| 14 | Features |
| 15 | -------- |
| 16 | |
| 17 | * Simple and expressive grammar syntax |
| 18 | * Integrates both lexical and syntactical analysis |
| 19 | * Parsers have excellent error reporting out of the box |
| 20 | * Based on [parsing expression |
| 21 | grammar](http://en.wikipedia.org/wiki/Parsing_expression_grammar) formalism |
| 22 | — more powerful than traditional LL(*k*) and LR(*k*) parsers |
| 23 | * Usable [from your browser](http://pegjs.org/online), from the command line, |
| 24 | or via JavaScript API |
| 25 | |
| 26 | Getting Started |
| 27 | --------------- |
| 28 | |
| 29 | [Online version](http://pegjs.org/online) is the easiest way to generate a |
| 30 | parser. Just enter your grammar, try parsing few inputs, and download generated |
| 31 | parser code. |
| 32 | |
| 33 | Installation |
| 34 | ------------ |
| 35 | |
| 36 | ### Node.js |
| 37 | |
| 38 | To use the `pegjs` command, install PEG.js globally: |
| 39 | |
| 40 | ```console |
| 41 | $ npm install -g pegjs |
| 42 | ``` |
| 43 | |
| 44 | To use the JavaScript API, install PEG.js locally: |
| 45 | |
| 46 | ```console |
| 47 | $ npm install pegjs |
| 48 | ``` |
| 49 | |
| 50 | If you need both the `pegjs` command and the JavaScript API, install PEG.js both |
| 51 | ways. |
| 52 | |
| 53 | ### Browser |
| 54 | |
| 55 | [Download](http://pegjs.org/#download) the PEG.js library (regular or minified |
| 56 | version) or install it using Bower: |
| 57 | |
| 58 | ```console |
| 59 | $ bower install pegjs |
| 60 | ``` |
| 61 | |
| 62 | Generating a Parser |
| 63 | ------------------- |
| 64 | |
| 65 | PEG.js generates parser from a grammar that describes expected input and can |
| 66 | specify what the parser returns (using semantic actions on matched parts of the |
| 67 | input). Generated parser itself is a JavaScript object with a simple API. |
| 68 | |
| 69 | ### Command Line |
| 70 | |
| 71 | To generate a parser from your grammar, use the `pegjs` command: |
| 72 | |
| 73 | ```console |
| 74 | $ pegjs arithmetics.pegjs |
| 75 | ``` |
| 76 | |
| 77 | This writes parser source code into a file with the same name as the grammar |
| 78 | file but with “.js” extension. You can also specify the output file explicitly: |
| 79 | |
| 80 | ```console |
| 81 | $ pegjs -o arithmetics-parser.js arithmetics.pegjs |
| 82 | ``` |
| 83 | |
| 84 | If you omit both input and output file, standard input and output are used. |
| 85 | |
| 86 | By default, the generated parser is in the Node.js module format. You can |
| 87 | override this using the `--format` option. |
| 88 | |
| 89 | You can tweak the generated parser with several options: |
| 90 | |
| 91 | * `--allowed-start-rules` — comma-separated list of rules the parser will be |
| 92 | allowed to start parsing from (default: the first rule in the grammar) |
| 93 | * `--cache` — makes the parser cache results, avoiding exponential parsing |
| 94 | time in pathological cases but making the parser slower |
| 95 | * `--dependency` — makes the parser require a specified dependency (can be |
| 96 | specified multiple times) |
| 97 | * `--export-var` — name of a global variable into which the parser object is |
| 98 | assigned to when no module loader is detected |
| 99 | * `--extra-options` — additional options (in JSON format) to pass to |
| 100 | `peg.generate` |
| 101 | * `--extra-options-file` — file with additional options (in JSON format) to |
| 102 | pass to `peg.generate` |
| 103 | * `--format` — format of the generated parser: `amd`, `commonjs`, `globals`, |
| 104 | `umd` (default: `commonjs`) |
| 105 | * `--optimize` — selects between optimizing the generated parser for parsing |
| 106 | speed (`speed`) or code size (`size`) (default: `speed`) |
| 107 | * `--plugin` — makes PEG.js use a specified plugin (can be specified multiple |
| 108 | times) |
| 109 | * `--trace` — makes the parser trace its progress |
| 110 | |
| 111 | ### JavaScript API |
| 112 | |
| 113 | In Node.js, require the PEG.js parser generator module: |
| 114 | |
| 115 | ```javascript |
| 116 | var peg = require("pegjs"); |
| 117 | ``` |
| 118 | |
| 119 | In browser, include the PEG.js library in your web page or application using the |
| 120 | `<script>` tag. If PEG.js detects an AMD loader, it will define itself as a |
| 121 | module, otherwise the API will be available in the `peg` global object. |
| 122 | |
| 123 | To generate a parser, call the `peg.generate` method and pass your grammar as a |
| 124 | parameter: |
| 125 | |
| 126 | ```javascript |
| 127 | var parser = peg.generate("start = ('a' / 'b')+"); |
| 128 | ``` |
| 129 | |
| 130 | The method will return generated parser object or its source code as a string |
| 131 | (depending on the value of the `output` option — see below). It will throw an |
| 132 | exception if the grammar is invalid. The exception will contain `message` |
| 133 | property with more details about the error. |
| 134 | |
| 135 | You can tweak the generated parser by passing a second parameter with an options |
| 136 | object to `peg.generate`. The following options are supported: |
| 137 | |
| 138 | * `allowedStartRules` — rules the parser will be allowed to start parsing from |
| 139 | (default: the first rule in the grammar) |
| 140 | * `cache` — if `true`, makes the parser cache results, avoiding exponential |
| 141 | parsing time in pathological cases but making the parser slower (default: |
| 142 | `false`) |
| 143 | * `dependencies` — parser dependencies, the value is an object which maps |
| 144 | variables used to access the dependencies in the parser to module IDs used |
| 145 | to load them; valid only when `format` is set to `"amd"`, `"commonjs"`, or |
| 146 | `"umd"` (default: `{}`) |
| 147 | * `exportVar` — name of a global variable into which the parser object is |
| 148 | assigned to when no module loader is detected; valid only when `format` is |
| 149 | set to `"globals"` or `"umd"` (default: `null`) |
| 150 | * `format` — format of the genreated parser (`"amd"`, `"bare"`, `"commonjs"`, |
| 151 | `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` |
| 152 | (default: `"bare"`) |
| 153 | * `optimize`— selects between optimizing the generated parser for parsing |
| 154 | speed (`"speed"`) or code size (`"size"`) (default: `"speed"`) |
| 155 | * `output` — if set to `"parser"`, the method will return generated parser |
| 156 | object; if set to `"source"`, it will return parser source code as a string |
| 157 | (default: `"parser"`) |
| 158 | * `plugins` — plugins to use |
| 159 | * `trace` — makes the parser trace its progress (default: `false`) |
| 160 | |
| 161 | Using the Parser |
| 162 | ---------------- |
| 163 | |
| 164 | Using the generated parser is simple — just call its `parse` method and pass an |
| 165 | input string as a parameter. The method will return a parse result (the exact |
| 166 | value depends on the grammar used to generate the parser) or throw an exception |
| 167 | if the input is invalid. The exception will contain `location`, `expected`, |
| 168 | `found`, and `message` properties with more details about the error. |
| 169 | |
| 170 | ```javascript |
| 171 | parser.parse("abba"); // returns ["a", "b", "b", "a"] |
| 172 | |
| 173 | parser.parse("abcd"); // throws an exception |
| 174 | ``` |
| 175 | |
| 176 | You can tweak parser behavior by passing a second parameter with an options |
| 177 | object to the `parse` method. The following options are supported: |
| 178 | |
| 179 | * `startRule` — name of the rule to start parsing from |
| 180 | * `tracer` — tracer to use |
| 181 | |
| 182 | Parsers can also support their own custom options. |
| 183 | |
| 184 | Grammar Syntax and Semantics |
| 185 | ---------------------------- |
| 186 | |
| 187 | The grammar syntax is similar to JavaScript in that it is not line-oriented and |
| 188 | ignores whitespace between tokens. You can also use JavaScript-style comments |
| 189 | (`// ...` and `/* ... */`). |
| 190 | |
| 191 | Let's look at example grammar that recognizes simple arithmetic expressions like |
| 192 | `2*(3+4)`. A parser generated from this grammar computes their values. |
| 193 | |
| 194 | ```pegjs |
| 195 | start |
| 196 | = additive |
| 197 | |
| 198 | additive |
| 199 | = left:multiplicative "+" right:additive { return left + right; } |
| 200 | / multiplicative |
| 201 | |
| 202 | multiplicative |
| 203 | = left:primary "*" right:multiplicative { return left * right; } |
| 204 | / primary |
| 205 | |
| 206 | primary |
| 207 | = integer |
| 208 | / "(" additive:additive ")" { return additive; } |
| 209 | |
| 210 | integer "integer" |
| 211 | = digits:[0-9]+ { return parseInt(digits.join(""), 10); } |
| 212 | ``` |
| 213 | |
| 214 | On the top level, the grammar consists of *rules* (in our example, there are |
| 215 | five of them). Each rule has a *name* (e.g. `integer`) that identifies the rule, |
| 216 | and a *parsing expression* (e.g. `digits:[0-9]+ { return |
| 217 | parseInt(digits.join(""), 10); }`) that defines a pattern to match against the |
| 218 | input text and possibly contains some JavaScript code that determines what |
| 219 | happens when the pattern matches successfully. A rule can also contain |
| 220 | *human-readable name* that is used in error messages (in our example, only the |
| 221 | `integer` rule has a human-readable name). The parsing starts at the first rule, |
| 222 | which is also called the *start rule*. |
| 223 | |
| 224 | A rule name must be a JavaScript identifier. It is followed by an equality sign |
| 225 | (“=”) and a parsing expression. If the rule has a human-readable name, it is |
| 226 | written as a JavaScript string between the name and separating equality sign. |
| 227 | Rules need to be separated only by whitespace (their beginning is easily |
| 228 | recognizable), but a semicolon (“;”) after the parsing expression is allowed. |
| 229 | |
| 230 | The first rule can be preceded by an *initializer* — a piece of JavaScript code |
| 231 | in curly braces (“{” and “}”). This code is executed before the generated parser |
| 232 | starts parsing. All variables and functions defined in the initializer are |
| 233 | accessible in rule actions and semantic predicates. The code inside the |
| 234 | initializer can access options passed to the parser using the `options` |
| 235 | variable. Curly braces in the initializer code must be balanced. Let's look at |
| 236 | the example grammar from above using a simple initializer. |
| 237 | |
| 238 | ```pegjs |
| 239 | { |
| 240 | function makeInteger(o) { |
| 241 | return parseInt(o.join(""), 10); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | start |
| 246 | = additive |
| 247 | |
| 248 | additive |
| 249 | = left:multiplicative "+" right:additive { return left + right; } |
| 250 | / multiplicative |
| 251 | |
| 252 | multiplicative |
| 253 | = left:primary "*" right:multiplicative { return left * right; } |
| 254 | / primary |
| 255 | |
| 256 | primary |
| 257 | = integer |
| 258 | / "(" additive:additive ")" { return additive; } |
| 259 | |
| 260 | integer "integer" |
| 261 | = digits:[0-9]+ { return makeInteger(digits); } |
| 262 | ``` |
| 263 | |
| 264 | The parsing expressions of the rules are used to match the input text to the |
| 265 | grammar. There are various types of expressions — matching characters or |
| 266 | character classes, indicating optional parts and repetition, etc. Expressions |
| 267 | can also contain references to other rules. See detailed description below. |
| 268 | |
| 269 | If an expression successfully matches a part of the text when running the |
| 270 | generated parser, it produces a *match result*, which is a JavaScript value. For |
| 271 | example: |
| 272 | |
| 273 | * An expression matching a literal string produces a JavaScript string |
| 274 | containing matched text. |
| 275 | * An expression matching repeated occurrence of some subexpression produces a |
| 276 | JavaScript array with all the matches. |
| 277 | |
| 278 | The match results propagate through the rules when the rule names are used in |
| 279 | expressions, up to the start rule. The generated parser returns start rule's |
| 280 | match result when parsing is successful. |
| 281 | |
| 282 | One special case of parser expression is a *parser action* — a piece of |
| 283 | JavaScript code inside curly braces (“{” and “}”) that takes match results of |
| 284 | some of the the preceding expressions and returns a JavaScript value. This value |
| 285 | is considered match result of the preceding expression (in other words, the |
| 286 | parser action is a match result transformer). |
| 287 | |
| 288 | In our arithmetics example, there are many parser actions. Consider the action |
| 289 | in expression `digits:[0-9]+ { return parseInt(digits.join(""), 10); }`. It |
| 290 | takes the match result of the expression [0-9]+, which is an array of strings |
| 291 | containing digits, as its parameter. It joins the digits together to form a |
| 292 | number and converts it to a JavaScript `number` object. |
| 293 | |
| 294 | ### Parsing Expression Types |
| 295 | |
| 296 | There are several types of parsing expressions, some of them containing |
| 297 | subexpressions and thus forming a recursive structure: |
| 298 | |
| 299 | #### "*literal*"<br>'*literal*' |
| 300 | |
| 301 | Match exact literal string and return it. The string syntax is the same as in |
| 302 | JavaScript. Appending `i` right after the literal makes the match |
| 303 | case-insensitive. |
| 304 | |
| 305 | #### . |
| 306 | |
| 307 | Match exactly one character and return it as a string. |
| 308 | |
| 309 | #### [*characters*] |
| 310 | |
| 311 | Match one character from a set and return it as a string. The characters in the |
| 312 | list can be escaped in exactly the same way as in JavaScript string. The list of |
| 313 | characters can also contain ranges (e.g. `[a-z]` means “all lowercase letters”). |
| 314 | Preceding the characters with `^` inverts the matched set (e.g. `[^a-z]` means |
| 315 | “all character but lowercase letters”). Appending `i` right after the right |
| 316 | bracket makes the match case-insensitive. |
| 317 | |
| 318 | #### *rule* |
| 319 | |
| 320 | Match a parsing expression of a rule recursively and return its match result. |
| 321 | |
| 322 | #### ( *expression* ) |
| 323 | |
| 324 | Match a subexpression and return its match result. |
| 325 | |
| 326 | #### *expression* \* |
| 327 | |
| 328 | Match zero or more repetitions of the expression and return their match results |
| 329 | in an array. The matching is greedy, i.e. the parser tries to match the |
| 330 | expression as many times as possible. Unlike in regular expressions, there is no |
| 331 | backtracking. |
| 332 | |
| 333 | #### *expression* + |
| 334 | |
| 335 | Match one or more repetitions of the expression and return their match results |
| 336 | in an array. The matching is greedy, i.e. the parser tries to match the |
| 337 | expression as many times as possible. Unlike in regular expressions, there is no |
| 338 | backtracking. |
| 339 | |
| 340 | #### *expression* ? |
| 341 | |
| 342 | Try to match the expression. If the match succeeds, return its match result, |
| 343 | otherwise return `null`. Unlike in regular expressions, there is no |
| 344 | backtracking. |
| 345 | |
| 346 | #### & *expression* |
| 347 | |
| 348 | Try to match the expression. If the match succeeds, just return `undefined` and |
| 349 | do not consume any input, otherwise consider the match failed. |
| 350 | |
| 351 | #### ! *expression* |
| 352 | |
| 353 | Try to match the expression. If the match does not succeed, just return |
| 354 | `undefined` and do not consume any input, otherwise consider the match failed. |
| 355 | |
| 356 | #### & { *predicate* } |
| 357 | |
| 358 | The predicate is a piece of JavaScript code that is executed as if it was inside |
| 359 | a function. It gets the match results of labeled expressions in preceding |
| 360 | expression as its arguments. It should return some JavaScript value using the |
| 361 | `return` statement. If the returned value evaluates to `true` in boolean |
| 362 | context, just return `undefined` and do not consume any input; otherwise |
| 363 | consider the match failed. |
| 364 | |
| 365 | The code inside the predicate can access all variables and functions defined in |
| 366 | the initializer at the beginning of the grammar. |
| 367 | |
| 368 | The code inside the predicate can also access location information using the |
| 369 | `location` function. It returns an object like this: |
| 370 | |
| 371 | ```javascript |
| 372 | { |
| 373 | start: { offset: 23, line: 5, column: 6 }, |
| 374 | end: { offset: 23, line: 5, column: 6 } |
| 375 | } |
| 376 | ``` |
| 377 | |
| 378 | The `start` and `end` properties both refer to the current parse position. The |
| 379 | `offset` property contains an offset as a zero-based index and `line` and |
| 380 | `column` properties contain a line and a column as one-based indices. |
| 381 | |
| 382 | The code inside the predicate can also access options passed to the parser using |
| 383 | the `options` variable. |
| 384 | |
| 385 | Note that curly braces in the predicate code must be balanced. |
| 386 | |
| 387 | #### ! { *predicate* } |
| 388 | |
| 389 | The predicate is a piece of JavaScript code that is executed as if it was inside |
| 390 | a function. It gets the match results of labeled expressions in preceding |
| 391 | expression as its arguments. It should return some JavaScript value using the |
| 392 | `return` statement. If the returned value evaluates to `false` in boolean |
| 393 | context, just return `undefined` and do not consume any input; otherwise |
| 394 | consider the match failed. |
| 395 | |
| 396 | The code inside the predicate can access all variables and functions defined in |
| 397 | the initializer at the beginning of the grammar. |
| 398 | |
| 399 | The code inside the predicate can also access location information using the |
| 400 | `location` function. It returns an object like this: |
| 401 | |
| 402 | ```javascript |
| 403 | { |
| 404 | start: { offset: 23, line: 5, column: 6 }, |
| 405 | end: { offset: 23, line: 5, column: 6 } |
| 406 | } |
| 407 | ``` |
| 408 | |
| 409 | The `start` and `end` properties both refer to the current parse position. The |
| 410 | `offset` property contains an offset as a zero-based index and `line` and |
| 411 | `column` properties contain a line and a column as one-based indices. |
| 412 | |
| 413 | The code inside the predicate can also access options passed to the parser using |
| 414 | the `options` variable. |
| 415 | |
| 416 | Note that curly braces in the predicate code must be balanced. |
| 417 | |
| 418 | #### $ *expression* |
| 419 | |
| 420 | Try to match the expression. If the match succeeds, return the matched text |
| 421 | instead of the match result. |
| 422 | |
| 423 | #### *label* : *expression* |
| 424 | |
| 425 | Match the expression and remember its match result under given label. The label |
| 426 | must be a JavaScript identifier. |
| 427 | |
| 428 | Labeled expressions are useful together with actions, where saved match results |
| 429 | can be accessed by action's JavaScript code. |
| 430 | |
| 431 | #### *expression<sub>1</sub>* *expression<sub>2</sub>* ... *expression<sub>n</sub>* |
| 432 | |
| 433 | Match a sequence of expressions and return their match results in an array. |
| 434 | |
| 435 | #### *expression* { *action* } |
| 436 | |
| 437 | Match the expression. If the match is successful, run the action, otherwise |
| 438 | consider the match failed. |
| 439 | |
| 440 | The action is a piece of JavaScript code that is executed as if it was inside a |
| 441 | function. It gets the match results of labeled expressions in preceding |
| 442 | expression as its arguments. The action should return some JavaScript value |
| 443 | using the `return` statement. This value is considered match result of the |
| 444 | preceding expression. |
| 445 | |
| 446 | To indicate an error, the code inside the action can invoke the `expected` |
| 447 | function, which makes the parser throw an exception. The function takes two |
| 448 | parameters — a description of what was expected at the current position and |
| 449 | optional location information (the default is what `location` would return — see |
| 450 | below). The description will be used as part of a message of the thrown |
| 451 | exception. |
| 452 | |
| 453 | The code inside an action can also invoke the `error` function, which also makes |
| 454 | the parser throw an exception. The function takes two parameters — an error |
| 455 | message and optional location information (the default is what `location` would |
| 456 | return — see below). The message will be used by the thrown exception. |
| 457 | |
| 458 | The code inside the action can access all variables and functions defined in the |
| 459 | initializer at the beginning of the grammar. Curly braces in the action code |
| 460 | must be balanced. |
| 461 | |
| 462 | The code inside the action can also access the text matched by the expression |
| 463 | using the `text` function. |
| 464 | |
| 465 | |
| 466 | The code inside the action can also access location information using the |
| 467 | `location` function. It returns an object like this: |
| 468 | |
| 469 | ```javascript |
| 470 | { |
| 471 | start: { offset: 23, line: 5, column: 6 }, |
| 472 | end: { offset: 25, line: 5, column: 8 } |
| 473 | } |
| 474 | ``` |
| 475 | |
| 476 | The `start` property refers to the position at the beginning of the expression, |
| 477 | the `end` property refers to position after the end of the expression. The |
| 478 | `offset` property contains an offset as a zero-based index and `line` and |
| 479 | `column` properties contain a line and a column as one-based indices. |
| 480 | |
| 481 | The code inside the action can also access options passed to the parser using |
| 482 | the `options` variable. |
| 483 | |
| 484 | Note that curly braces in the action code must be balanced. |
| 485 | |
| 486 | #### *expression<sub>1</sub>* / *expression<sub>2</sub>* / ... / *expression<sub>n</sub>* |
| 487 | |
| 488 | Try to match the first expression, if it does not succeed, try the second one, |
| 489 | etc. Return the match result of the first successfully matched expression. If no |
| 490 | expression matches, consider the match failed. |
| 491 | |
| 492 | Compatibility |
| 493 | ------------- |
| 494 | |
| 495 | Both the parser generator and generated parsers should run well in the following |
| 496 | environments: |
| 497 | |
| 498 | * Node.js 0.10.0+ |
| 499 | * Internet Explorer 8+ |
| 500 | * Edge |
| 501 | * Firefox |
| 502 | * Chrome |
| 503 | * Safari |
| 504 | * Opera |
| 505 | |
| 506 | Development |
| 507 | ----------- |
| 508 | |
| 509 | * [Project website](http://pegjs.org/) |
| 510 | * [Wiki](https://github.com/pegjs/pegjs/wiki) |
| 511 | * [Source code](https://github.com/pegjs/pegjs) |
| 512 | * [Issue tracker](https://github.com/pegjs/pegjs/issues) |
| 513 | * [Google Group](http://groups.google.com/group/pegjs) |
| 514 | * [Twitter](http://twitter.com/peg_js) |
| 515 | |
| 516 | PEG.js is developed by [David Majda](http://majda.cz/) |
| 517 | ([@dmajda](http://twitter.com/dmajda)). The [Bower |
| 518 | package](https://github.com/pegjs/bower) is maintained by [Michel |
| 519 | Krämer](http://www.michel-kraemer.com/) |
| 520 | ([@michelkraemer](https://twitter.com/michelkraemer)). |
| 521 | |
| 522 | You are welcome to contribute code. Unless your contribution is really trivial |
| 523 | you should get in touch with me first — this can prevent wasted effort on both |
| 524 | sides. You can send code both as a patch or a GitHub pull request. |
| 525 | |
| 526 | Note that PEG.js is still very much work in progress. There are no compatibility |
| 527 | guarantees until version 1.0. |