-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathdocumentation.html
1647 lines (1352 loc) · 65 KB
/
documentation.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: 'Documentation'
permalink: '/documentation.html'
layout: main-layout
stylesheets: ["css/documentation.css"]
---
<script src="js/examples.js?2022-06-03T00:53:11Z"></script>
<h1>Documentation</h1>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>
<a href="#installation">Installation</a>
<ul>
<li><a href="#installation-node-js">Node.js</a></li>
<li><a href="#installation-browser">Browser</a></li>
</ul>
</li>
<li>
<a href="#generating-a-parser">Generating a Parser</a>
<ul>
<li><a href="#generating-a-parser-command-line">Command Line</a></li>
<li>
<a href="#generating-a-parser-javascript-api">JavaScript API</a>
<ul>
<li><a href="#error-reporting">Error Reporting</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#using-the-parser">Using the Parser</a></li>
<li>
<a href="#grammar-syntax-and-semantics">Grammar Syntax and Semantics</a>
<ul>
<li><a href="#grammar-syntax-and-semantics-parsing-expression-types">Parsing Expression Types</a></li>
<li><a href="#action-execution-environment">Action Execution Environment</a></li>
<li><a href="#parsing-lists">Parsing Lists</a></li>
</ul>
</li>
<li><a href="#identifiers">Peggy Identifiers</a></li>
<li><a href="#error-messages">Error Messages</a></li>
<li><a href="#locations">Locations</a></li>
<li>
<a href="#plugins-api">Plugins API</a>
<ul>
<li><a href="#session-api">Session API</a></li>
</ul>
</li>
<li><a href="#compatibility">Compatibility</a></li>
</ul>
<h2 id="installation">Installation</h2>
<h3 id="installation-node-js">Node.js</h3>
<p>To use the <code>peggy</code> command, install Peggy globally:</p>
<pre><code class="language-console">$ npm install -g peggy</code></pre>
<p>To use the JavaScript API, install Peggy locally:</p>
<pre><code class="language-console">$ npm install peggy</code></pre>
<p>If you need both the <code>peggy</code> command and the JavaScript API,
install Peggy both ways.</p>
<h3 id="installation-browser">Browser</h3>
<p>The easiest way to use Peggy from the browser is to pull the latest version
from a CDN. Either of these should work:</p>
<pre><code class="language-html"><script src="https://unpkg.com/peggy"></script></code></pre>
<pre><code class="language-html"><script src="https://cdn.jsdelivr.net/npm/peggy"></script></code></pre>
<p>Both of those CDNs support pinning a version number rather than always
taking the latest. Not only is that good practice, it will save several
redirects, improving performance. See their documentation for more
information:</p>
<ul>
<li><a href="https://unpkg.com/">unpkg</a></li>
<li><a href="https://www.jsdelivr.com/">jsDelivr</a></li>
</ul>
<p>When your document is done loading, there will be a global <code>peggy</code> object.</p>
<h2 id="generating-a-parser">Generating a Parser</h2>
<p>Peggy generates parser from a grammar that describes expected input and can
specify what the parser returns (using semantic actions on matched parts of the
input). Generated parser itself is a JavaScript object with a simple API.</p>
<h3 id="generating-a-parser-command-line">Command Line</h3>
<p>To generate a parser from your grammar, use the <code>peggy</code>
command:</p>
<pre><code class="language-console">$ peggy arithmetics.pegjs</code></pre>
<p>This writes parser source code into a file with the same name as the grammar
file but with “.js” extension. You can also specify the output file
explicitly:</p>
<pre><code class="language-console">$ peggy -o arithmetics-parser.js arithmetics.pegjs</code></pre>
<p>If you omit both input and output file, standard input and standard output
are used.</p>
<p>By default, the generated parser is in the Node.js module format. You can
override this using the <code>--format</code> option.</p>
<p>You can tweak the generated parser with several options:</p>
<dl>
<dt><code>--allowed-start-rules <rules></code></dt>
<dd>Comma-separated list of rules the parser will be allowed to start parsing
from. Use '*' if you want any rule to be allowed as a start rule.
(default: only the first rule in the grammar).</dd>
<dt><code>--ast</code></dt>
<dd>Outputting an internal AST representation of the grammar after
all optimizations instead of the parser source code. Useful for plugin authors
to see how their plugin changes the AST. This option cannot be mixed with the
<code>-t/--test</code>, <code>-T/--test-file</code> and <code>-m/--source-map</code>
options.
</dd>
<dt><code>--cache</code></dt>
<dd>Makes the parser cache results, avoiding exponential parsing time in
pathological cases but making the parser slower.</dd>
<dt><code>-d</code>, <code>--dependency <[name:]module></code></dt>
<dd>Makes the parser require a specified dependency (can be specified
multiple times). A variable name for the import/require/etc. may be given,
followed by a colon. If no name is given, the module name will also be used
for the variable name.</dd>
<dt><code>-D</code>, <code>--dependencies <json></code></dt>
<dd>Dependencies, in JSON object format with variable:module pairs. (Can be
specified multiple times).</dd>
<dt><code>-e</code>, <code>--export-var <variable></code></dt>
<dd>Name of a global variable into which the parser object is assigned to when
no module loader is detected.</dd>
<dt><code>--extra-options <options></code></dt>
<dd>Additional options (in JSON format, as an object) to pass to
<code>peg.generate</code>.
</dd>
<dt><code>-c</code>, <code>--extra-options-file <file></code></dt>
<dd>File with additional options (in JSON format, as an object) to pass to
<code>peg.generate</code>.
</dd>
<dt><code>--format <format></code></dt>
<dd>Format of the generated parser: <code>amd</code>, <code>commonjs</code>,
<code>globals</code>, <code>umd</code>, <code>es</code> (default: <code>commonjs</code>).
</dd>
<dt><code>-o</code>, <code>--output <file></code></dt>
<dd>File to send output to. Defaults to input file name with
extension changed to <code>.js</code>, or stdout if no input file is given.</dd>
<dt><code>--plugin</code></dt>
<dd>Makes Peggy use a specified plugin (can be specified multiple
times).</dd>
<dt><code>-m</code>, <code>--source-map <file></code></dt>
<dd>Generate a source map. If name is not specified, the source map will be
named "<input_file>.map" if input is a file and "source.map" if input
is a standard input. If the special filename <code>inline</code> is given,
the sourcemap will be embedded in the output file as a data URI. If the
filename is prefixed with <code>hidden:</code>, no mapping URL will be
included so that the mapping can be specified with an HTTP SourceMap:
header. This option conflicts with the <code>-t/--test</code> and
<code>-T/--test-file</code> options unless <code>-o/--output</code> is also
specified
</dd>
<dt><code>-S</code>, <code>--start-rule <rule></code></dt>
<dd>When testing, use this rule as the start rule. Automatically added to
the allowedStartRules.</dd>
<dt><code>-t</code>, <code>--test <text></code></dt>
<dd>Test the parser with the given text, outputting the result of running
the parser against this input.
If the input to be tested is not parsed, the CLI will exit with code 2.</dd>
<dt><code>-T</code>, <code>--test-file <text></code></dt>
<dd>Test the parser with the contents of the given file, outputting the
result of running the parser against this input.
If the input to be tested is not parsed, the CLI will exit with code 2.</dd>
<dt><code>--trace</code></dt>
<dd>Makes the parser trace its progress.</dd>
<dt><code>-v</code>, <code>--version</code></dt>
<dd>Output the version number.</dd>
<dt><code>-h</code>, <code>--help</code></dt>
<dd>Display help for the command.</dd>
</dl>
<p>If you specify options using <code>-c <file></code> or
<code>--extra-options-file <file></code>, you will need to ensure you
are using the correct types. In particular, you may specify "plugin" as a
string, or "plugins" as an array of objects that have a <code>use</code>
method. Always use the long (two-dash) form of the option, without the
dashes, as the key. Options that contain internal dashes should be specified
in camel case. You may also specify an "input" field instead of using the
command line. For example:</p>
<pre><code class="language-javascript">// config.js or config.cjs
module.exports = {
allowedStartRules = ["foo", "bar"],
format: "umd",
exportVar: "foo",
input: "fooGrammar.peggy",
plugins: [require("./plugin.js")],
testFile: "myTestInput.foo",
trace: true,
};
</code></pre>
<p>You can test generated parser immediately if you specify the
<code>-t/--test</code> or <code>-T/--test-file</code>
option. This option conflicts with the
<code>--ast</code> option, and also conflicts with the
<code>-m/--source-map</code> option unless <code>-o/--output</code> is also
specified.</p>
<p>The CLI will exit with the code:</p>
<ul>
<li><code>0</code>: if successful</li>
<li><code>1</code>: if you supply incorrect or conflicting parameters</li>
<li><code>2</code>: if you specified the
<code>-t/--test</code> or <code>-T/--test-file</code> option and the specified
input fails parsing with the specified grammar
</li>
</ul>
<p>Examples:</p>
<pre><code class="language-console"># - write test results to stdout (42)
# - exit with the code 0
echo "foo = '1' { return 42 }" | peggy --test 1
# - write a parser error to stdout (Expected "1" but "2" found)
# - exit with the code 2
echo "foo = '1' { return 42 }" | peggy --test 2
# - write an error to stdout (Generation of the source map is useless if you don't
# store a generated parser code, perhaps you forgot to add an `-o/--output` option?)
# - exit with the code 1
echo "foo = '1' { return 42 }" | peggy --source-map --test 1
# - write an error to stdout (Generation of the source map is useless if you don't
# store a generated parser code, perhaps you forgot to add an `-o/--output` option?)
# - exit with the code 1
echo "foo = '1' { return 42 }" | peggy --source-map --test 2
# - write an output to `parser.js`,
# - write a source map to `parser.js.map`
# - write test results to stdout (42)
# - exit with the code 0
echo "foo = '1' { return 42 }" | peggy --output parser.js --source-map --test 1
# - write an output to `parser.js`,
# - write a source map to `parser.js.map`
# - write a parser error to stdout (Expected "1" but "2" found)
# - exit with the code 2
echo "foo = '1' { return 42 }" | peggy --output parser.js --source-map --test 2
</code></pre>
<h3 id="generating-a-parser-javascript-api">JavaScript API</h3>
<p>In Node.js, require the Peggy parser generator module:</p>
<pre><code class="language-javascript">const peggy = require("peggy");</code></pre>
<p>or:</p>
<pre><code class="language-javascript">import * as peggy from "peggy";</code></pre>
<p>For use in browsers, include the Peggy library in your web page or
application using the <code><script></code> tag. If Peggy detects an
<a href="https://requirejs.org/docs/whyamd.html">AMD</a> loader, it will define
itself as a module, otherwise the API will be available in the
<code>peg</code> global object.</p>
<p>To generate a parser, call the <code>peggy.generate</code> method and pass your
grammar as a parameter:</p>
<pre><code class="language-javascript">const parser = peggy.generate("start = ('a' / 'b')+");</code></pre>
<p>The method will return generated parser object or its source code as a string
(depending on the value of the <code>output</code> option — see below). It will
throw an exception if the grammar is invalid. The exception will contain a
<code>message</code> property with more details about the error.</p>
<p>You can tweak the generated parser by passing a second parameter with an
options object to <code>peg.generate</code>. The following options are
supported:</p>
<dl>
<dt><code>allowedStartRules</code></dt>
<dd>Rules the parser will be allowed to start parsing from (default: the
first rule in the grammar). If any of the rules specified is "*", any of
the rules in the grammar can be used as start rules.</dd>
<dt><code>cache</code></dt>
<dd>If <code>true</code>, makes the parser cache results, avoiding exponential
parsing time in pathological cases but making the parser slower (default:
<code>false</code>).
</dd>
<dt><code>dependencies</code></dt>
<dd>Parser dependencies. The value is an object which maps variables used to
access the dependencies in the parser to module IDs used to load them; valid
only when <code>format</code> is set to <code>"amd"</code>,
<code>"commonjs"</code>, <code>"es"</code>, or <code>"umd"</code>.
Dependencies variables will be available in both the <em>global
initializer</em> and the <em>per-parse initializer</em>. Unless the parser
is to be generated in different formats, it is recommended to rather
import dependencies from within the <em>global initializer</em> (default:
<code>{}</code>).
</dd>
<dt><code>error</code></dt>
<dd>Callback for errors. See <a href="#error-reporting">Error Reporting</a></dd>
<dt><code>exportVar</code></dt>
<dd>Name of a global variable into which the parser object is assigned to when
no module loader is detected; valid only when <code>format</code> is set to
<code>"globals"</code> or <code>"umd"</code> (default:
<code>null</code>).
</dd>
<dt><code>format</code></dt>
<dd>
Format of the generated parser (<code>"amd"</code>, <code>"bare"</code>,
<code>"commonjs"</code>, <code>"es"</code>, <code>"globals"</code>, or
<code>"umd"</code>); valid only when <code>output</code> is set to
<code>"source"</code>, <code>"source-and-map"</code>, or
<code>"source-with-inline-map"</code>. (default: <code>"bare"</code>).
</dd>
<dt id="grammar-source"><code>grammarSource</code></dt>
<dd>
A string or object representing the "origin" of the input string being
parsed. The <code>location()</code> API returns the supplied
<code>grammarSource</code> in the <code>source</code> key. As an example, if
you pass in <code>grammarSource</code> as "main.js", then errors with
locations include <code>{ source: 'main.js', ... }</code>.
<br><br>
If you pass an object, the location API returns the entire object in the
<code>source</code> key. If you format an error containing a location with
<a href="#error-messages"><code>format()</code></a>, the formatter
stringifies the object. If you pass an object, we recommend you add
a <code>toString()</code> method to the object to improve error messages.
</dd>
<dt><code>info</code></dt>
<dd>Callback for informational messages. See <a href="#error-reporting">Error Reporting</a></dd>
<dt><code>output</code></dt>
<dd>
<p>A string, one of:</p>
<ul>
<li><code>"parser"</code> - return generated parser object.</li>
<li><code>"source"</code> - return parser source code as a string.</li>
<li><code>"source-and-map"</code> - return a
<a href="https://github.com/mozilla/source-map#sourcenode"><code>SourceNode</code></a>
object; you can get source code by calling <code>toString()</code>
method or source code and mapping by calling
<code>toStringWithSourceMap()</code> method, see the
<a href="https://github.com/mozilla/source-map#sourcenode"><code>SourceNode</code></a>
documentation.
</li>
<li><code>"source-with-inline-map"</code> - return the parser source along
with an embedded source map as a <code>data:</code> URI. This option
leads to a larger output string, but is the easiest to integrate with
developer tooling.</li>
<li><code>"ast"</code> - return the internal AST of the grammar as a JSON
string. Useful for plugin authors to explore internals of Peggy and
for automation.</li>
</ul>
<p>(default: <code>"parser"</code>)</p>
<blockquote>
<p><strong>Note</strong>: You should also set <code>grammarSource</code>
to a not-empty string if you set this value to
<code>"source-and-map"</code> or
<code>"source-with-inline-map"</code>. The path should be relative to
the location where the generated parser code will be stored. For
example, if you are generating <code>lib/parser.js</code> from
<code>src/parser.peggy</code>, then your options should be:
<code>{ grammarSource: "../src/parser.peggy" }</code>
</p>
</blockquote>
</dd>
<dt><code>plugins</code></dt>
<dd>Plugins to use. See the <a href="#plugins-api">Plugins API</a> section.</dd>
<dt><code>trace</code></dt>
<dd>Makes the parser trace its progress (default: <code>false</code>).</dd>
<dt><code>warning</code></dt>
<dd>Callback for warnings. See <a href="#error-reporting">Error Reporting</a></dd>
</dl>
<h4 id="error-reporting">Error Reporting</h4>
<p>While generating the parser, the compiler may throw a <code>GrammarError</code> which collects
all of the issues that were seen.</p>
<p>There is also another way to collect problems as fast as they are reported —
register one or more of these callbacks:</p>
<ul>
<li><code>error(stage: Stage, message: string, location?: LocationRange, notes?: DiagnosticNote[]): void</code></li>
<li><code>warning(stage: Stage, message: string, location?: LocationRange, notes?: DiagnosticNote[]): void</code></li>
<li><code>info(stage: Stage, message: string, location?: LocationRange, notes?: DiagnosticNote[]): void</code></li>
</ul>
<p>All parameters are the same as the parameters of the <a href="#session-api">reporting API</a> except the first.
The <code>stage</code> represent one of possible stages during which execution a diagnostic was generated.
This is a string enumeration, that currently has one of three values:</p>
<ul>
<li><code>check</code></li>
<li><code>transform</code></li>
<li><code>generate</code></li>
</ul>
<h2 id="using-the-parser">Using the Parser</h2>
<p>To use the generated parser, call its <code>parse</code>
method and pass an input string as a parameter. The method will return a parse
result (the exact value depends on the grammar used to generate the parser) or
throw an exception if the input is invalid. The exception will contain
<code>location</code>, <code>expected</code>, <code>found</code>,
<code>message</code>, and <code>diagnostic</code> properties with more details about the error. The error
will have a <code>format(SourceText[])</code> function, to which you pass an array
of objects that look like <code>{ source: grammarSource, text: string }</code>; this
will return a nicely-formatted error suitable for human consumption.</p>
<pre><code class="language-javascript">parser.parse("abba"); // returns ["a", "b", "b", "a"]
parser.parse("abcd"); // throws an exception</code></pre>
<p>You can tweak parser behavior by passing a second parameter with an options
object to the <code>parse</code> method. The following options are
supported:</p>
<dl>
<dt><code>startRule</code></dt>
<dd>Name of the rule to start parsing from.</dd>
<dt><code>tracer</code></dt>
<dd>
Tracer to use. A tracer is an object containing a <code>trace()</code> function.
<code>trace()</code> takes a single parameter which is an object containing
"type" ("rule.enter", "rule.fail", "rule.match"), "rule" (the rule name as a
string), "<a href="<a href=" #locations">location</a>", and, if the type is
"rule.match", "result" (what the rule returned).
</dd>
<dt><code>...</code> (any others)</dt>
<dd>Made available in the <code>options</code> variable</dd>
</dl>
<p>As you can see above, parsers can also support their own custom options. For example:</p>
<pre><code class="language-javascript">const parser = peggy.generate(`
{
// options are available in the per-parse initializer
console.log(options.validWords); // outputs "[ 'boo', 'baz', 'boop' ]"
}
validWord = @word:$[a-z]+ &{ return options.validWords.includes(word) }
`);
const result = parser.parse("boo", {
validWords: [ "boo", "baz", "boop" ]
});
console.log(result); // outputs "boo"
</code></pre>
<h2 id="grammar-syntax-and-semantics">Grammar Syntax and Semantics</h2>
<p>The grammar syntax is similar to JavaScript in that it is not line-oriented
and ignores whitespace between tokens. You can also use JavaScript-style
comments (<code>// ...</code> and <code>/* ... */</code>).</p>
<p>Let's look at example grammar that recognizes simple arithmetic expressions
like <code>2*(3+4)</code>. A parser generated from this grammar computes their
values.</p>
<pre><code class="language-peggy">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 "simple number"
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }</code></pre>
<p>On the top level, the grammar consists of <em>rules</em> (in our example,
there are five of them). Each rule has a <em>name</em> (e.g.
<code>integer</code>) that identifies the rule, and a <em>parsing
expression</em> (e.g. <code>digits:[0-9]+ { return parseInt(digits.join(""), 10); }</code>)
that defines a pattern to match against the input text and
possibly contains some JavaScript code that determines what happens when the
pattern matches successfully. A rule can also contain <em>human-readable
name</em> that is used in error messages (in our example, only the
<code>integer</code> rule has a human-readable name). The parsing starts at the
first rule, which is also called the <em>start rule</em>.</p>
<p>A rule name must be a Peggy <a href="#identifiers">identifier</a>. It is
followed by an equality sign (“=”) and a parsing expression. If the rule has a
human-readable name, it is written as a JavaScript string between the rule
name and the equality sign. Rules need to be separated only by whitespace
(their beginning is easily recognizable), but a semicolon (“;”) after the
parsing expression is allowed.</p>
<p>The first rule can be preceded by a <em>global initializer</em> and/or a
<em>per-parse initializer</em>, in that order. Both are pieces of JavaScript
code in double curly braces (“{{'{{'}}” and “}}”) and single curly braces (“{” and
“}”) respectively. All variables and functions defined in both
<em>initializers</em> are accessible in rule actions and semantic predicates.
Curly braces in both <em>initializers</em> code must be balanced.</p>
<p>The <em>global initializer</em> is executed once and only once, when the
generated parser is loaded (through a <code>require</code> or an
<code>import</code> statement for instance). It is the ideal location to
require, to import, to declare constants, or to declare utility functions to be used in rule actions
and semantic predicates.</p>
<p>The <em>per-parse initializer</em> is called before the generated parser
starts parsing. The code inside the <em>per-parse initializer</em> can access
the input string and the options passed to the parser using the
<code>input</code> variable and the <code>options</code> variable respectively.
It is the ideal location to create data structures that are unique to each
parse or to modify the input before the parse.</p>
<p>Let's look at the example grammar from above using a <em>global
initializer</em> and a <em>per-parse initializer</em>:</p>
<pre><code class="language-peggy">{{'{{'}}
function makeInteger(o) {
return parseInt(o.join(""), 10);
}
}}
{
if (options.multiplier) {
input = `(${input})*(${options.multiplier})`;
}
}
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 "simple number"
= digits:[0-9]+ { return makeInteger(digits); }</code></pre>
<p>The parsing expressions of the rules are used to match the input text to the
grammar. There are various types of expressions — matching characters or
character classes, indicating optional parts and repetition, etc. Expressions
can also contain references to other rules. See
<a href="#grammar-syntax-and-semantics-parsing-expression-types">detailed
description below</a>.</p>
<p>If an expression successfully matches a part of the text when running the
generated parser, it produces a <em>match result</em>, which is a JavaScript
value. For example:</p>
<ul>
<li>An expression matching a literal string produces a JavaScript string
containing matched text.</li>
<li>An expression matching repeated occurrence of some subexpression produces
a JavaScript array with all the matches.</li>
</ul>
<p>The match results propagate through the rules when the rule names are used in
expressions, up to the start rule. The generated parser returns start rule's
match result when parsing is successful.</p>
<p>One special case of parser expression is a <em>parser action</em> — a
piece of JavaScript code inside curly braces (“{” and “}”) that takes match
results of the preceding expression and returns a JavaScript value.
This value is then considered match result of the preceding expression (in other
words, the parser action is a match result transformer).</p>
<p>In our arithmetics example, there are many parser actions. Consider the
action in expression <code>digits:[0-9]+ { return parseInt(digits.join(""), 10); }</code>.
It takes the match result of the expression [0-9]+, which is an array
of strings containing digits, as its parameter. It joins the digits together to
form a number and converts it to a JavaScript <code>number</code> object.</p>
<h3 id="grammar-syntax-and-semantics-parsing-expression-types">Parsing Expression Types</h3>
<p>There are several types of parsing expressions, some of them containing
subexpressions and thus forming a recursive structure. Each example below is
a part of a <a href="js/examples.peggy">full grammar</a>, which produces an
object that contains <code>match</code> and <code>rest</code>.
<code>match</code> is the part of the input that matched the example,
<code>rest</code> is any remaining input after the match.</p>
<dl>
<dt><code>"<em>literal</em>"<br>'<em>literal</em>'</code></dt>
<dd>
<p>Match exact literal string and return it. The string syntax is the same
as in JavaScript. Appending <code>i</code> right after the literal makes the
match case-insensitive.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>literal = "foo"</code></div>
<div><em>Matches:</em> <code>"foo"</code></div>
<div><em>Does not match:</em> <code>"Foo"</code>, <code>"fOo"</code>, <code>"bar"</code>, <code>"fo"</code>
</div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="foo" class="exampleInput" name="literal">
<div class="result"></div>
</div>
</div>
<div class="example">
<div>
<div><em>Example:</em> <code>literal_i = "foo"i</code></div>
<div><em>Matches:</em> <code>"foo"</code>, <code>"Foo"</code>, <code>"fOo"</code></div>
<div><em>Does not match:</em> <code>"bar"</code>, <code>"fo"</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="FOO" class="exampleInput" name="literal_i">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code>.</code> (U+002E: FULL STOP, or "period")</dt>
<dd>
<p>Match exactly one character and return it as a string.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>any = .</code></div>
<div><em>Matches:</em> <code>"f"</code>, <code>"."</code>, <code>" "</code></div>
<div><em>Does not match:</em> <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="f" class="exampleInput" name="any">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code>[<em>characters</em>]</code></dt>
<dd>
<p>Match one character from a set and return it as a string. The characters
in the list can be escaped in exactly the same way as in JavaScript string.
The list of characters can also contain ranges (e.g. <code>[a-z]</code>
means “all lowercase letters”). Preceding the characters with <code>^</code>
inverts the matched set (e.g. <code>[^a-z]</code> means “all character but
lowercase letters”). Appending <code>i</code> right after the literal makes
the match case-insensitive.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>class = [a-z]</code></div>
<div><em>Matches:</em> <code>"f"</code></div>
<div><em>Does not match:</em> <code>"A"</code>, <code>"-"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="f" class="exampleInput" name="class">
<div class="result"></div>
</div>
</div>
<div class="example">
<div>
<div><em>Example:</em> <code>class_i = [^a-z]i</code></div>
<div><em>Matches:</em> <code>"="</code>, <code>" "</code></div>
<div><em>Does not match:</em> <code>"F"</code>, <code>"f"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="=" class="exampleInput" name="class_i">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code><em>rule</em></code></dt>
<dd>
<p>Match a parsing expression of a rule (perhaps recursively) and return its match
result.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>rule = child; child = "foo"</code></div>
<div><em>Matches:</em> <code>"foo"</code></div>
<div><em>Does not match:</em> <code>"Foo"</code>, <code>"fOo"</code>, <code>"bar"</code>, <code>"fo"</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="foo" class="exampleInput" name="rule">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code>( <em>expression</em> )</code></dt>
<dd>
<p>Match a subexpression and return its match result.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>paren = ("1" { return 2; })+</code></div>
<div><em>Matches:</em> <code>"11"</code></div>
<div><em>Does not match:</em> <code>"2"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="11" class="exampleInput" name="paren">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code><em>expression</em> *</code></dt>
<dd>
<p>Match zero or more repetitions of the expression and return their match
results in an array. The matching is greedy, i.e. the parser tries to match
the expression as many times as possible. Unlike in regular expressions,
there is no backtracking.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>star = "a"*</code></div>
<div><em>Matches:</em> <code>"a"</code>, <code>"aaa"</code></div>
<div><em>Does not match:</em> (always matches)</div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="aa" class="exampleInput" name="star">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code><em>expression</em> +</code></dt>
<dd>
<p>Match one or more repetitions of the expression and return their match
results in an array. The matching is greedy, i.e. the parser tries to match
the expression as many times as possible. Unlike in regular expressions,
there is no backtracking.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>plus = "a"+</code></div>
<div><em>Matches:</em> <code>"a"</code>, <code>"aaa"</code></div>
<div><em>Does not match:</em> <code>"b"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="aa" class="exampleInput" name="plus">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code><em>expression</em> |count|
<br><em>expression</em> |min..max|
<br><em>expression</em> |count, delimiter|
<br><em>expression</em> |min..max, delimiter|</code></dt>
<dd>
<p>Match exact <code>count</code> repetitions of <code>expression</code>.
If the match succeeds, return their match results in an array.</p>
<p><em>-or-</em></p>
<p>Match expression at least <code>min</code> but not more then <code>max</code> times.
If the match succeeds, return their match results in an array. Both <code>min</code>
and <code>max</code> may be omitted. If <code>min</code> is omitted, then it is assumed
to be <code>0</code>. If <code>max</code> is omitted, then it is assumed to be infinity.
Hence</p>
<ul>
<li><code>expression |..|</code> is equivalent to <code>expression |0..|</code>
and <code>expression *</code></li>
<li><code>expression |1..|</code> is equivalent to <code>expression +</code></li>
</ul>
<p>Optionally, <code>delimiter</code> expression can be specified. The
delimiter is a separate parser expression, its match results are ignored,
and it must appear between matched expressions exactly once.</p>
<p><code>count</code>, <code>min</code> and <code>max</code> can be
represented as:</p>
<ul>
<li>positive integer:
<pre><code class="language-peggy">start = "a"|2|;</code></pre>
</li>
<li>name of the preceding label:
<pre><code class="language-peggy">start = count:n1 "a"|count|;
n1 = n:$[0-9] { return parseInt(n); };</code></pre>
</li>
<li>code block:
<pre><code class="language-peggy">start = "a"|{ return options.count; }|;</code></pre>
</li>
Any non-number values, returned by the code block, will be interpreted as <code>0</code>.
</ul>
<div class="example">
<div>
<div><em>Example:</em> <code>repetition = "a"|2..3, ","|</code></div>
<div><em>Matches:</em> <code>"a,a"</code>, <code>"a,a,a"</code></div>
<div><em>Does not match:</em> <code>"a"</code>, <code>"b,b"</code>,
<code>"a,a,a,"</code>, <code>"a,a,a,a"</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="a,a" class="exampleInput" name="repetition">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code><em>expression</em> ?</code></dt>
<dd>
<p>Try to match the expression. If the match succeeds, return its match
result, otherwise return <code>null</code>. Unlike in regular expressions,
there is no backtracking.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>maybe = "a"?</code></div>
<div><em>Matches:</em> <code>"a"</code>, <code>""</code></div>
<div><em>Does not match:</em> (always matches)</div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="aa" class="exampleInput" name="maybe">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code>& <em>expression</em></code></dt>
<dd>
<p>This is a positive assertion. No input is consumed.</p>
<p>Try to match the expression. If the match succeeds, just return
<code>undefined</code> and do not consume any input, otherwise consider the
match failed.
</p>
<div class="example">
<div>
<div><em>Example:</em> <code>posAssertion = "a" &"b"</code></div>
<div><em>Matches:</em> <code>"ab"</code></div>
<div><em>Does not match:</em> <code>"ac"</code>, <code>"a"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="ab" class="exampleInput" name="posAssertion">
<div class="result"></div>
</div>
</div>
</dd>
<dt><code>! <em>expression</em></code></dt>
<dd>
<p>This is a negative assertion. No input is consumed.</p>
<p>Try to match the expression. If the match does
not succeed, just return <code>undefined</code> and do not consume any
input, otherwise consider the match failed.</p>
<div class="example">
<div>
<div><em>Example:</em> <code>negAssertion = "a" !"b"</code></div>
<div><em>Matches:</em> <code>"a"</code>, <code>"ac"</code></div>
<div><em>Does not match:</em> <code>"ab"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="ac" class="exampleInput" name="negAssertion">
<div class="result"></div>
</div>
</div>
</dd>
<dt id="-predicate-"><code>& { <em>predicate</em> }</code></dt>
<dd>
<p>This is a positive assertion. No input is consumed.</p>
<p>The predicate should be JavaScript code, and it's executed as a
function. Curly braces in the predicate must be balanced.</p>
<p>The predicate should <code>return</code> a boolean value. If the result
is truthy, it's match result is <code>undefined</code>, otherwise the
match is considered failed. Failure to include the <code>return</code>
keyword is a common mistake.</p>
<p>The predicate has access to all variables and functions in the
<a href="#action-execution-environment">Action Execution Environment</a>.
</p>
<div class="example">
<div>
<div><em>Example:</em> <br><code>posPredicate = [0-9]+ &{return parseInt(match, 10) < 100}</code></div>
<div><em>Matches:</em> <code>"0"</code>, <code>"99"</code></div>
<div><em>Does not match:</em> <code>"100"</code>, <code>"-1"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="56" class="exampleInput" name="posPredicate">
<div class="result"></div>
</div>
</div>
</dd>
<dt id="--predicate-"><code>! { <em>predicate</em> }</code></dt>
<dd>
<p>This is a negative assertion. No input is consumed.</p>
<p>The predicate should be JavaScript code, and it's executed as a
function. Curly braces in the predicate must be balanced.</p>
<p>The predicate should <code>return</code> a boolean value. If the result is
falsy, it's match result is <code>undefined</code>, otherwise the match is
considered failed.</p>
<p>The predicate has access to all variables and functions in the
<a href="#action-execution-environment">Action Execution Environment</a>.
</p>
<div class="example">
<div>
<div><em>Example:</em> <br><code>negPredicate = $[0-9]+ !{ return parseInt(match, 10) < 100 }</code></div>
<div><em>Matches:</em> <code>"100"</code>, <code>"156"</code></div>
<div><em>Does not match:</em> <code>"56"</code>, <code>"-1"</code>, <code>""</code></div>
</div>
<div class="try">
<em>Try it:</em>
<input type="text" value="156" class="exampleInput" name="negPredicate">
<div class="result"></div>
</div>