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