Debian Codegraph @

src/xtc/parser/package.html

raw symbols SCIP
1 <html><body>
2
3 <i>Rats&#033;</i>, a parser generator supporting extensible syntax.
4
5 <p />Grammars for <i>Rats!</i> build on the Parsing Expression Grammar
6 (PEG) formalism described in Brian
7 Ford's <a href="http://www.brynosaurus.com/pub/lang/peg.pdf">Parsing
8 Expression Grammars</a> paper. However, since <i>Rats!</i> produces
9 working parsers, the syntax of <i>Rats!</i> grammars is somewhat
10 different from and more expressive than the PEG syntax described in
11 the paper. Additionally, to make grammars more easily reusable and
12 extensible, <i>Rats</i> organizes grammar fragments into modules. A
13 good starting point for learning how to use <i>Rats!</i>, in addition
14 to this introduction, are <i>Rats!</i>' own grammar in
15 package <code>xtc.parser</code> and the C and Java grammars in
16 package <code>xtc.lang</code>.
17
18 <p />The rest of this document covers the following topics:<ul>
19 <li><a href="#syntax">Syntax</a></li>
20 <li><a href="#overview">Overview of Expressions and Operators</a></li>
21 <li><a href="#modules">Grammar Modules</a></li>
22 <li><a href="#values">Productions and Semantic Values</a></li>
23 <li><a href="#pass-through">Passing the Semantic Value Through</a></li>
24 <li><a href="#options-etc">Options, Repetitions, and Nested Choices</a></li>
25 <li><a href="#void">Void and Text-Only Productions</a></li>
26 <li><a href="#generic">Generic Productions</a></li>
27 <li><a href="#list-valued">List-Valued Productions</a></li>
28 <li><a href="#left-recursion">Left-Recursive Productions</a></li>
29 <li><a href="#node-markers">Node Markers in Generic Productions</a></li>
30 <li><a href="#parameters">Modules, Name Spaces, and Parameters</a></li>
31 <li><a href="#modifications">Module Modifications</a></li>
32 <li><a href="#transient">Memoization and Transient Productions</a></li>
33 <li><a href="#attributes">Grammar and Production Attributes</a></li>
34 <li><a href="#parser-actions">Parser Actions</a></li>
35 </ul>
36
37
38 <!-- -------------------------------------------------------------------- -->
39
40 <a name="syntax"></a><h4>Syntax</h4>
41
42 Here is the syntax of <i>Rats!</i>' grammar modules, expressed in PEG
43 syntax:
44 <pre>
45 Module &lt;- Spacing Intro Production* EOF
46
47 Intro &lt;- ModuleDecl Dependency* Header? Body? Footer? Option?
48 ModuleDecl &lt;- "module" FSpacing ModuleRef SEMICOLON
49 Dependency &lt;- Modification / Instantiation / Import
50 Modification &lt;- "modify" FSpacing ModuleRef ModuleTarget? SEMICOLON
51 Instantiation &lt;- "instantiate" FSpacing ModuleRef ModuleTarget? SEMICOLON
52 Import &lt;- "import" FSpacing ModuleRef ModuleTarget? SEMICOLON
53 ModuleRef &lt;- QName ModuleParams?
54 ModuleParams &lt;- OPEN ( QName (COMMA QName)* )? CLOSE
55 ModuleTarget &lt;- "as" FSpacing QName
56 Header &lt;- "header" Spacing Action
57 Body &lt;- "body" Spacing Action
58 Footer &lt;- "footer" Spacing Action
59 Option &lt;- "option" FSpacing Attribute (COMMA Attribute)* SEMICOLON
60
61 Production &lt;- Full / Addition / Removal / Override
62 Full &lt;- PAttributes QName Identifier EQUAL Choice SEMICOLON
63 Addition &lt;- QName Identifier PLUSEQUAL
64 ( SName ELLIPSIS SLASH Choice SEMICOLON
65 / Choice SLASH SName ELLIPSIS SEMICOLON )
66 Removal &lt;- QName Identifier MINUSEQUAL
67 SName ( COMMA SName )* SEMICOLON
68 Override &lt;- QName Identifier COLONEQUAL Choice SEMICOLON
69 / QName Identifier COLONEQUAL ELLIPSIS SLASH Choice SEMICOLON
70 / QName Identifier COLONEQUAL Choice SLASH ELLIPSIS SEMICOLON
71 / PAttributes QName Identifier COLONEQUAL ELLIPSIS SEMICOLON
72 PAttributes &lt;- &(QName Identifier EQUAL) / Attribute PAttributes
73 Choice &lt;- Sequence (SLASH Sequence)*
74 Sequence &lt;- !(SName ELLIPSIS / ELLIPSIS) SName? Voided*
75 Voided &lt;- ("void" Spacing COLON)? Prefix
76 Prefix &lt;- (AND / NOT / CARET / Identifier COLON
77 / StringLit Spacing COLON)? Suffix
78 Suffix &lt;- Primary (QUESTION / STAR / PLUS)?
79 Primary &lt;- NullLit / QName / Literal / NodeMarker / Action
80 / OPEN Choice CLOSE
81
82 NullLit &lt;- "null" Spacing
83
84 NodeMarker &lt;- '&#x40;' Id Spacing
85
86 Action &lt;- '{' ActionBody* '}' Spacing
87 ActionBody &lt;- Action / CharLit / StringLit / MLComment / SLComment / !'}' .
88
89 Attribute &lt;- Identifier (OPEN AttValue CLOSE)?
90 AttValue &lt;- Integer / QName / StringLit Spacing
91
92 QName &lt;- Id ('.' Id)* Spacing
93 SName &lt;- LESS Id GREATER
94 Identifier &lt;- Id Spacing
95 Id &lt;- [a-zA-Z] [a-zA-Z0-9]*
96
97 Literal &lt;- ('_' / CharLit / StringLit / Class) Spacing
98 CharLit &lt;- ['] (Escape / !['\\] .) [']
99 StringLit &lt;- ["] (Escape / !["\\] .)* ["]
100 Class &lt;- '[' (Char '-' Char / Char)* ']'
101 Char &lt;- Escape / ![-\]\\] .
102 Escape &lt;- '\\' [btnfr"'\[\\\]-] / '\\' 'u' HexQuad / OctalEscape
103 OctalEscape &lt;- '\\' ([0-3] OctDigit OctDigit / OctDigit OctDigit / OctDigit)
104
105 Integer &lt;- (HexNumber / OctNumber / Number) Spacing
106 HexNumber &lt;- '0' [xX] HexDigit+
107 HexQuad &lt;- HexDigit HexDigit HexDigit HexDigit
108 HexDigit &lt;- [0-9a-fA-F]
109 Number &lt;- '0' / NZDigit Digit*
110 NZDigit &lt;- [1-9]
111 Digit &lt;- [0-9]
112 OctNumber &lt;- '0' OctDigit+
113 OctDigit &lt;- [0-7]
114
115 ELLIPSIS &lt;- "..." Spacing
116 PLUSEQUAL &lt;- "+=" Spacing
117 MINUSEQUAL &lt;- "-=" Spacing
118 COLONEQUAL &lt;- ":=" Spacing
119 COMMA &lt;- ',' Spacing
120 EQUAL &lt;- '=' Spacing
121 SLASH &lt;- '/' ![/*] Spacing
122 AND &lt;- '&' Spacing
123 NOT &lt;- '!' Spacing
124 CARET &lt;- '^' Spacing
125 COLON &lt;- ':' Spacing
126 QUESTION &lt;- '?' Spacing
127 STAR &lt;- '*' Spacing
128 PLUS &lt;- '+' Spacing
129 OPEN &lt;- '(' Spacing
130 CLOSE &lt;- ')' Spacing
131 SEMICOLON &lt;- ';' Spacing
132 LESS &lt;- '<'
133 GREATER &gt;- '>' Spacing
134
135 Spacing &lt;- (Space / SLComment / MLComment)*
136 FSpacing &lt;- (Space / SLComment / MLComment)+
137 Space &lt;- ' ' / '\t' / '\f' / EOL
138 SLComment &lt;- "//" (![\n\r] .)* EOL
139 MLComment &lt;- "/*" ('*' !'/' / !'*' .)* "*/"
140 EOL &lt;- '\r' '\n' / '\r' / '\n'
141 EOF &lt;- !.
142 </pre>
143
144 Note that <code>QName</code> stands for "qualified
145 name," <code>SName</code> stands for "sequence
146 name," <code>PAttributes</code> for "production
147 attributes," <code>AttValue</code> for "attribute
148 value," <code>NZDigit</code> for "non-zero
149 digit," <code>FSpacing</code> for "forced
150 spacing," <code>SLComment</code> for "single-line comment,"
151 and <code>MLComment</code> for "multi-line comment."
152
153 <!-- -------------------------------------------------------------------- -->
154
155 <a name="overview"></a><h4>Overview of Expressions and Operators</h4>
156
157 The biggest difference between parsing expression grammars and the
158 more familiar context-free grammars (CFGs) is the use
159 of <i>ordered</i> choices instead of symmetric choices. Hence, the
160 different options in a PEG choice (and also a <i>Rats!</i> choice) are
161 separated by a slash <code>/</code> instead of a vertical
162 bar <code>|</code>. Furthermore, to emphasize that PEGs define how
163 to <i>parse</i> a language instead of how to generate a language, PEGs
164 use a left arrow <code>&lt;-</code> instead of the right
165 arrow <code>-&gt;</code> used in CFGs. Note that <i>Rats!</i> uses an
166 equal sign instead.
167
168 <p />Otherwise, PEGs have many of the same expressions and operators
169 as other syntax and grammar formalisms. For example, the any
170 character constant <code>.</code> (<code>_</code> for <i>Rats!</i>)
171 matches any character in the input, and a character class, as defined
172 by the <code>[]</code> operator, matches any of the characters in the
173 class. The option operator <code>?</code> makes an expression
174 optional, and the star <code>*</code> and plus <code>+</code>
175 operators indicate zero-or-more and one-or-more repetitions,
176 respectively. Somewhat less common are the and <code>&</code> and
177 not <code>!</code> operators, which denote syntactic predicates.
178 Expressions in a syntactic predicate must match (for the
179 and <code>&</code> operator) or not match (for the not <code>!</code>
180 operator) the input, though the corresponding text in the input is
181 <i>not</i> consumed.
182
183 <p /><i>Rats!</i> grammars differ from PEGs in that they have
184 additional expressions and operators necessary for generating actual
185 parsers. Most importantly, <i>Rats!</i> grammars include
186 <i>actions</i> that generate semantic values. Actions are surrounded
187 by curly brackets <code>{}</code>, just like blocks of code in C, C++,
188 or Java. To access such semantic values, <i>Rats!</i> grammars can
189 also include <i>bindings</i>. Bindings first specify the variable
190 name, followed by a colon <code>:</code>, and then the expression to
191 be bound. Additionally, <i>Rats!</i> grammars support <i>semantic
192 predicates</i>, which are denoted by the and
193 <code>&</code> operator directly followed by an action (which must be
194 an expression evaluating to a boolean value). Furthermore,
195 <i>Rats!</i> grammars support <i>text matching expressions</i>,
196 which first specify the text to be matched as a string literal,
197 followed by a colon <code>:</code>, and then the expression to be
198 matched. A text matching expression
199
200 <p />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>"</code><i>text</i><code>":</code><i>expr</i><br />
201
202 <p />is equivalent to the expression
203
204 <p />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>fresh-variable</i><code>:</code><i>expr</i><code>&nbsp;&amp;{&nbsp;"</code><i>text</i><code>".equals(</code><i>fresh-variable</i><code>)&nbsp;}</code><br />
205
206 <p />but implemented more efficiently.
207
208 <i>Rats!</i> grammars also support a <i>voiding operator</i>, which is
209 specified as "<code>void:</code>" followed by an expression, <i>node
210 markers</i>, which are specified as an at sign '<code>&#x40;</code>'
211 immediately followed by an identifier, and <i>parser actions</i>,
212 which are actions prefixed by a caret '<code>^</code>'. Voided
213 expressions and node markers help with the automatic generation of
214 abstract syntax trees and are explained <a href="#generic">here</a>.
215 Parser actions provide a low-level interface for extending parsers
216 generated by <i>Rats!</i> and are
217 explained <a href="#parser-actions">here</a>.
218
219 <p />Other differences between PEGs and <i>Rats!</i> grammars include
220 that, as already mentioned <i>Rats!</i> uses an underscore
221 '<code>_</code>' as the any character constant, while PEGs use a dot
222 '<code>.</code>'. Furthermore, <i>Rats!</i>, just like C/C++/Java,
223 requires that single-quoted literals specify exactly one character,
224 while double-quoted literals may specify an arbitrary number of
225 characters. Escape sequences include basic C/C++/Java escapes such as
226 '<code>\n</code>' and '<code>\\</code>', Java Unicode escapes such as
227 '<code>\u00ff</code>', and '<code>\[</code>', '<code>\-</code>', and
228 '<code>\]</code>' for character class specifications. <i>Rats!</i>
229 grammars also use standard C/C++/Java comments. Note that, while
230 <i>Rats!</i> supports Unicode, it only supports 16 bit characters in
231 the basic multilingual plane (i.e., with code points between U+0000
232 and U+FFFF). Expressions recognizing supplementary characters (i.e.,
233 with code points between U+10000 and U+10FFFF) need to
234 use <a
235 href="http://java.sun.com/developer/technicalArticles/Intl/Supplementary/">Java's
236 encoding</a> as a pair of <code>char</code> values in the surrogates
237 range.
238
239 <!-- -------------------------------------------------------------------- -->
240
241 <a name="modules"></a><h4>Grammar Modules</h4>
242
243 A <i>Rats!</i> grammar consists of one top-level module, which is the
244 module specified on the command line when invoking <i>Rats!</i>, and
245 zero or more dependent modules. Each module starts with several
246 declarations, whose syntax follows from <code>Intro</code> in
247 the <i>Rats!</i> syntax specification <a href="#syntax">above</a>:<ul>
248
249 <li>The <code>module</code> declaration specifies the fully qualified
250 name of a grammar module. Optionally, the module may have one or more
251 parameters, which are treated as module names and are replaced with
252 the actual arguments throughout the module, notably in module
253 dependency declarations and in qualified nonterminals (a qualified
254 nonterminal consists of the module name, followed by a dot
255 '<code>.</code>', followed by the unqualified nonterminal). Module
256 parameters are discussed in more
257 detail <a href="#parameters">here</a>.<p /></li>
258
259 <li>Zero or more module dependency declarations specify how the
260 current module depends on other modules. <i>Rats!</i> supports three
261 types of such dependency declarations. First, import dependencies
262 make another module's nonterminals referenceable from within the
263 current module. Second, modification dependencies make another
264 module's productions available for modification in the current module.
265 Each module can have at most one modification dependency. Finally,
266 instantiation dependencies instantiate other modules (typically,
267 modules that require arguments) and make their names available for use
268 in other dependencies. The effects of import and instantiation
269 declarations are discussed in more
270 detail <a href="#parameters">here</a>; module modifications are
271 discussed in detail <a href="#modifications">here</a>.<p /></li>
272
273 <li>The action code following an optional <code>header</code>
274 declaration is copied into the parser just before the parser class
275 declaration. If a grammar spans several modules, all unique header
276 actions are copied into the parser class.<p /></li>
277
278 <li>The action code following an optional <code>body</code>
279 declaration is copied into the body of the parser class. Again, if a
280 grammar spans several modules, all unique body actions are copied into
281 the parser class.<p /></li>
282
283 <li>The action code following an optional <code>footer</code>
284 declaration is copied just after the parser class declaration. As for
285 header and body declarations, if a grammar spans several modules, all
286 unique footer actions are copied into the parser class.<p /></li>
287
288 <li>An optional <code>option</code> declaration specifies parser
289 options. Each option is expressed as an attribute, which is an
290 identifier specifying the attribute's name followed by an optional
291 integer literal, qualified name, or string within
292 parentheses <code>()</code> specifying the attribute's value. The
293 currently recognized options are
294 discussed <a href="#attributes">here</a>.<p /></li>
295
296 </ul>
297
298 <p />A grammar's top-level module (i.e., the module specified on the
299 command line when invoking <i>Rats!</i>) is treated somewhat
300 differently from its dependent modules:<ul>
301
302 <li>By default, the Java package and class names of the generated
303 parser are automatically deduced from the fully qualified name of the
304 top-level module. For example, the default package and class names
305 for module <code>xtc.parser.PGrammar</code> would be
306 <code>xtc.parser</code> and <code>PGrammar</code>, respectively.
307 However, this default can be overriden through
308 the <a href="#parser-attribute"><code>parser</code></a> option (and
309 is, in fact, overriden by that module).<p /></li>
310
311 <li>Option declarations are outside the module system, and only the
312 top-level module's options are observed by the parser generator. The
313 exceptions are the following options. First,
314 the <a href="#stateful-attribute"><code>stateful</code></a> option
315 specifies a global state object and must have the same value across
316 all of a grammar's modules (if it appears at all). Second,
317 the <a href="#set"><code>setOfString</code></a> option specifies a
318 global set of strings and has the corresponding field's name as its
319 value; each unique value results in its own global field. Finally
320 the <a href="#flag"><code>flag</code></a> option specifies a global
321 boolean field and has the corresponding field's name as its value;
322 each unique value results in its own global field.<p /></li>
323
324 <li>The top-level module must have at least one production that is
325 marked as <a href="#public-attribute"><code>public</code></a>, which
326 indicates that that production is a top-level production and thus
327 visible outside the parser class. Other modules' public productions
328 are not treated as top-level production for the grammar.<p /></li>
329
330 <li>Finally, because the top-level module is directly instantiated, it
331 cannot have any parameters. Only dependent modules may have
332 parameters; the corresponding arguments are specified when importing,
333 instantiating, or modifying the module.<p /></li>
334
335 </ul>
336
337 <p />Similar to the Java compiler automatically loading dependent Java
338 classes, <i>Rats!</i> automatically loads dependent modules from the
339 file system. For example, when looking for the dependent
340 module <code>xtc.util.Spacing</code>, <i>Rats!</i> searches for the
341 file <code>xtc/util/Spacing.rats</code> on Unix-like systems. One or
342 more root directories for this search can be specified through
343 the <code>-in</code> command line option.
344
345 <p />A grammar's modules can be visualized by
346 using <i>Rats!</i>' <code>-html</code> command line option combined
347 with either the <code>-instantiated</code>, <code>-applied</code>,
348 or <code>-processed</code> command line option to specify the stage
349 of <i>Rats!</i>' processing. In all three cases,
350 <i>Rats!</i> creates a hyperlinked version of the grammar at that
351 processing stage. Make sure that
352 the <a
353 href="http://cs.nyu.edu/rgrimm/xtc/grammar.css"><code>grammar.css</code></a>
354 stylesheet is in the same directory as the generated HTML file(s).
355 The output directory can be controlled with the <code>-out</code>
356 command line option.
357
358 <!-- -------------------------------------------------------------------- -->
359
360 <a name="values"></a><h4>Productions and Semantic Values</h4>
361
362 After the module declarations follow the productions, with each
363 production defining how to parse a nonterminal. Regular modules may
364 only contain full productions, whose syntax follows from
365 <code>Full</code> in the <i>Rats!</i> syntax
366 specification <a href="#syntax">above</a>. Module modifications may
367 also contain alternative additions, alternative removals, and
368 production overrides, which are
369 discussed <a href="#modifications">below</a>.
370
371 <p />Each full production first lists zero or more attributes, then
372 declares the type of the semantic value it returns, and then specifies
373 the name of the nonterminal it defines (which must be unqualified).
374 The definition follows after the equals sign <code>=</code> and is
375 terminated by a semicolon <code>;</code>. Each full production can
376 either be public, protected, or private, as indicated by the
377 corresponding attribute of the same name. A public production is a
378 top-level production for the grammar if it appears in the top-level
379 module. Otherwise, it is treated as a protected production, which is
380 the default, can be omitted, and makes the production referenceable
381 from other modules. Finally, a private production can only be
382 referenced from within the same module. Note that the use of
383 the <code>transient</code> attribute is
384 explained <a href="#transient">here</a>. All per-production
385 attributes supported by <i>Rats!</i> are discussed
386 <a href="#attributes">here</a>. Further note that types cannot be
387 primitive types, such as <code>int</code>; though, as
388 discussed <a href="#void">here</a>, <code>void</code> is allowed.
389
390 <p />A production's semantic value is usually defined in an action by
391 setting the <code>yyValue</code> variable (so named in deference to
392 the <a href="http://dinosaur.compilertools.net/">Yacc</a> parser
393 generator) to the desired value. The action code can use characters
394 or strings matched by a literal as well as semantic values returned by
395 nested nonterminals through <i>bindings</i>. As specified <a
396 href="#syntax">above</a>, each binding first declares the variable,
397 followed by a colon, and then the bound expression.
398
399 <p /><a name="production-example"></a>For example, this is the
400 production for the <code>FullProduction</code> nonterminal
401 from <i>Rats!</i>' own grammar:
402 <pre>
403 FullProduction FullProduction =
404 atts:ProductionAttributes
405 type:Name nt:UnqualifiedNonTerminal "=":Symbol choice:Choice ";":Symbol
406 { yyValue = new FullProduction(atts.list(), type, nt, choice); }
407 ;
408 </pre>
409
410 <p />The production first declares the type of the semantic value it
411 returns to be <code>FullProduction</code> (which only coincidentally
412 has the same name as the production). In the definition, the semantic
413 value of recognizing the production's attributes is bound to the
414 variable <code>atts</code>, the semantic value returned by
415 the <code>Name</code> production is bound to the variable
416 <code>type</code>, the semantic value returned by the
417 <code>UnqualifiedNonTerminal</code> production is bound to the
418 variable <code>nt</code>, and the semantic value returned by the
419 <code>Choice</code> production is bound to the variable
420 <code>choice</code>. The action code then uses these variables to
421 create a new <code>FullProduction</code> object and assigns that
422 object to <code>yyValue</code>, thus making the newly created object
423 the production's semantic value.
424
425 <p />In the generated parser, <i>Rats!</i> declares the types of
426 variables as following:
427 <ul>
428
429 <li>Variables bound to the any character constant <code>_</code>, to a
430 character literal, or a character class are declared
431 as <code>char</code>.<p /></li>
432
433 <li>Variables bound to a string literal are declared
434 as <code>String</code>.<p /></li>
435
436 <li>Variables bound to a nonterminal are declared to be of the type of
437 the corresponding production. For example, the declared type of
438 the <code>Name</code> production from the above example
439 is <code>String</code> and, consequently, <code>type</code> is
440 declared to be a <code>String</code> as well.<p /></li>
441
442 <li>Similarly, <code>yyValue</code> is declared to be of the type of
443 the corresponding production.<p /></li>
444
445 </ul>
446
447 <!-- -------------------------------------------------------------------- -->
448
449 <a name="pass-through"></a><h4>Passing the Semantic Value Through</h4>
450
451 Sometimes, the semantic value of a production is the same as the
452 semantic value of one of the expressions appearing in that production.
453 To avoid first binding that expression to some variable and then
454 assigning that variable to <code>yyValue</code> , it is possible to
455 directly bind <code>yyValue</code>.
456
457 <p />For example, the production for the <code>Header</code> nonterminal
458 from <i>Rats!</i>' own grammar makes use of this feature:
459 <pre>
460 Action Header = "header":Word yyValue:Action ;
461 </pre>
462 An equivalent, but more verbose definition might look like this:
463 <pre>
464 Action Header = "header":Word a:Action { yyValue = a; } ;
465 </pre>
466
467 <!-- -------------------------------------------------------------------- -->
468
469 <a name="options-etc"></a><h4>Options, Repetitions, and Nested Choices</h4>
470
471 In general, <i>Rats!</i> lifts options, repetitions, and nested
472 choices into their own, newly generated productions. It also desugars
473 options and repetitions into equivalent productions without the option
474 or repetition operators. Note that nested choices are <i>not</i>
475 lifted if they are the last element in a sequence. Further note that
476 repetitions are <i>not</i> desugared if they appear in
477 a <a href="#transient">transient</a> production. Finally, options are
478 <i>not</i> desugared if they are not bound or if <i>Rats</i> can
479 automatically deduce the value of the bound optional expression.
480
481 <p />This lifting and desugaring raises several questions:
482 <ul>
483
484 <li>What is the semantic value of an expression before applying the
485 option or repetition operator? Similarly, what is the semantic value
486 of a nested choice?<p /></li>
487
488 <li>For options and repetitions, what is the semantic value after
489 applying the option or repetition operator?<p /></li>
490
491 <li>Finally, for each of these expressions, what is the type of the
492 newly generated production?<p /></li>
493
494 </ul>
495 We now answer these questions in turn.
496
497 <p />To determine the semantic value of an expression before applying
498 the option or repetition operator and that of a nested
499 choice, <i>Rats!</i> generally requires that each expression has
500 its own, embedded action that defines the corresponding value. As a
501 result, the definition of a production may contain several actions
502 that all assign values to <code>yyValue</code>, even in nested
503 expressions.
504
505 <p />However, for some expressions, <i>Rats!</i> is able to
506 automatically deduce their semantic values. Notably, if a nonterminal
507 is optional or repeated, the semantic value of the expression before
508 applying the option or repetition operator simply is the semantic
509 value of the nonterminal's production. Similarly, if a nonterminal is
510 the only expression appearing in an option, the semantic value for
511 that option simply is the semantic value of the nonterminal's
512 production. In these cases, no embedded actions are necessary.
513
514 <p />For options, the semantic value after applying the option
515 operator is the semantic value of the expression, if that expression
516 can be matched in the input. Otherwise, the overall semantic value is
517 simply <code>null</code>. For repetitions, the semantic value after
518 applying the repetition operator is a {@link xtc.util.Pair}. Pairs
519 are used to implement singly-linked lists and contain the semantic
520 values of the repeated expressions. In the case of zero matches, the
521 pair is the special {@link xtc.util.Pair#EMPTY empty pair}, which is
522 also accessible through the type-safe {@link xtc.util.Pair#empty()}
523 method. <i>Rats!</i> uses pairs as they allow for efficient addition
524 of an element to the front of a sequence of pairs. Note that pairs
525 can easily be converted into a Java Collections Framework list by
526 calling {@link xtc.util.Pair#list()} (as illustrated in the production
527 for <i>Rats!</i> productions
528 shown <a href="#production-example">above</a>).
529
530 <p />The type of a newly generated production representing a desugared
531 option generally is <code>Object</code>. However,
532 if <i>Rats!</i> can automatically determine the semantic value of
533 an optional expression, it uses the more specific type (which, in the
534 case of desugared optional nonterminals, is the type of the
535 corresponding production). The type of a newly generated production
536 representing a desugared repetition always
537 is <code>xtc.util.Pair</code>. Finally, the type of a newly generated
538 production representing a lifted choice always is <code>Object</code>.
539
540 <p />To illustrate the general case of repetitions and nested choices,
541 consider the following snippet from <i>Rats!</i>' own grammar,
542 which is taken from the <code>Terminal</code> production and parses
543 character class specifications:
544 <pre>
545 / '['
546 l:( c1:ClassChar '-' c2:ClassChar
547 {
548 yyValue = new CharRange(Utilities.unescape(c1).charAt(0),
549 Utilities.unescape(c2).charAt(0));
550 }
551 / c1:ClassChar
552 {
553 yyValue = new CharRange(Utilities.unescape(c1).charAt(0));
554 }
555 )*
556 ']' Spacing
557 { yyValue = new CharClass(l.list()); }
558 </pre>
559 The nested choice has its own actions, which create character ranges
560 as their semantic values. The parser collects these character ranges
561 into a sequence of pairs, which is then bound to the <code>l</code>
562 variable. The outer action uses this sequence of pairs to create a
563 new character class as the overall semantic value (converting the
564 sequence of pairs into a Java Collections Framework list along the
565 way).
566
567 <p /><a name="sequence-example"></a>To illustrate the automatic
568 deduction of a semantic value, consider the production for sequences
569 from <i>Rats!</i>' own grammar:
570 <pre>
571 Sequence Sequence =
572 !Ellipsis n:SequenceName? l:Voided*
573 { yyValue = new Sequence(n, l.list()); }
574 ;
575 </pre>
576 A sequence essentially consists of zero or more repetitions of the
577 <code>Voided</code> nonterminal; no embedded action is necessary for
578 the repetition. <i>Rats!</i> automatically collects the individual
579 semantic values into a sequence of pairs. The optional sequence name
580 preceding the repeated <code>Voided</code> nonterminal simply is an
581 identifier between less-than <code>&lt;</code> and
582 greater-than <code>&gt;</code> signs and is used
583 when <a href="#modifications">modifying productions</a>. It can also
584 be used for documentation, as <i>Rats!</i> tries to preserve it
585 throughout its internal processing, so that it will be included in the
586 generated parser (within a comment). The corresponding optional
587 expression does not need an embedded action either. The syntactic
588 predicate <code>!Ellipsis</code> excludes sequence names followed by
589 an ellipsis <code>...</code> or an ellipsis by itself from sequences,
590 as they are used to <a href="#modifications">modify productions</a>.
591
592 <!-- -------------------------------------------------------------------- -->
593
594 <a name="void"></a><h4>Void and Text-Only Productions</h4>
595
596 Adding actions to create a production's semantic value can seem
597 tedious and may make grammars unnecessarily verbose. To reduce the
598 need for explicit actions, <i>Rats!</i> supports special types of
599 productions, which need <i>no</i> semantic actions at all. We now
600 discuss void and text-only productions, which are especially useful
601 for recognizing lexical syntax (such as identifiers, punctuation,
602 numbers, and so on).
603
604 <p />A <i>void production</i> is a production that declares the type
605 of its semantic value to be <code>void</code>. Such a production does
606 not require any actions, but it may not be bound to an identifier
607 either. A void production is typically used for ignored spacing or
608 punctuation elements. Void productions also improve the accuracy of
609 <i>Rats!</i>' deduction of a compound expression's semantic
610 value. If the compound expression only contains a single non-void
611 nonterminal, that nonterminal's semantic value is used as the semantic
612 value of the entire expression.
613
614 <p />Here is an example void production from <i>Rats!</i>' own
615 grammar:
616 <pre>
617 transient void Spacing =
618 (Space / LineTerminator / TraditionalComment/ EndOfLineComment)*
619 ;
620 </pre>
621 This production matches space characters, line terminators, and
622 comments. Note that the <code>transient</code> keyword is explained
623 <a href="#transient">here</a>.
624
625 <p />The fact the <code>Spacing</code> is declared
626 as <code>void</code> is then used in the production
627 for <code>Symbol</code>:
628 <pre>
629 String Symbol = SymbolCharacters Spacing ;
630 </pre>
631 No action is necessary because only the <code>SymbolCharacters</code>
632 nonterminal produces a semantic value. <i>Rats!</i> automatically
633 detects this case and passes the value
634 of <code>SymbolCharacters</code> through.
635
636 <p />In general, <i>Rats!</i> tries to deduce a compound expression's
637 value, even if it is nested within another expression, ignoring
638 nonterminals referencing a void production or explicitly voided
639 expressions. Furthermore, for repetitions, options, and nested
640 choices that do not appear as the last expression in a sequence, it
641 treats the <em>entire</em> repetition, option, or nested choice as
642 void, if all component expressions are nonterminals referencing void
643 productions, explicitly voided expressions, or predicates. For
644 example, if <code>nt</code> references a void production, then the
645 expression "<code>nt*</code>" is equivalent to
646 "<code>void:(nt*)</code>" (note that the parentheses are not strictly
647 necessary).
648
649 <p />A <i>text-only production</i> is a production that declares the
650 type of its semantic value to be a <code>String</code>, does not
651 contain any bindings to <code>yyValue</code> nor actions that
652 reference <code>yyValue</code> and references only other text-only
653 productions (if any). The semantic value of a text-only production is
654 the text matched in the input, represented as a <code>String</code>.
655 Note that the above <code>Symbol</code> production is not text-only
656 because it references a void production. Also note that bindings
657 (besides to <code>yyValue</code>) and semantic predicates may appear
658 in text-only productions.
659
660 <p /><a name="transient-example"></a>To illustrate text-only
661 productions, consider the following productions from <i>Rats!</i>' own
662 grammar:
663 <pre>
664 String StringLiteral = ["] ( EscapeSequence / !["\\] _ )* ["] ;
665
666 transient String EscapeSequence =
667 '\\' ( [btnfr\"\'\-\[\\\]] / 'u' HexNumber ) ;
668 transient String HexNumber = HexDigit HexDigit HexDigit HexDigit ;
669 transient String HexDigit = [0-9a-fA-F] ;
670 </pre>
671 The <code>StringLiteral</code> production only references terminals
672 and other productions that are also text-only. As a result, its
673 semantic value is the text matched in the input, exactly what we
674 expect from a production that matches string literals. Note that the
675 <code>transient</code> keyword is explained <a
676 href="#transient">here</a>.
677
678 <p />A note on bindings <i>within</i> text-only productions: When
679 binding to a character terminal (the any character constant, a
680 character class, or a character literal), the bound variable is a
681 <code>char</code> (just as for all other productions). However, for
682 <i>all</i> other expressions (including options, repetitions, and
683 nested choices), the value of the bound variable always is a string
684 representing the text matched by that expression in the input. For
685 options that cannot be matched in the input, the value is the empty
686 string (and not <code>null</code>).
687
688 <!-- -------------------------------------------------------------------- -->
689
690 <a name="generic"></a><h4>Generic Productions</h4>
691
692 Void and text-only productions typically help with recognizing lexical
693 syntax; though, they are of limited use for productions that recognize
694 hierarchical syntax, such as the productions for
695 <code>FullProduction</code>, <code>Header</code>,
696 or <code>Sequence</code> shown above. Generic productions help
697 simplify productions for hierarchical syntax. Just as for void and
698 text-only productions, no explicit semantic actions are required.
699
700 <p />A <i>generic production</i> is a production that declares
701 <code>generic</code> as its type and returns a semantic value that is
702 a {@link xtc.tree.GNode generic node}. <i>Rats!</i>
703 automatically creates the production's semantic value: its name is the
704 name of the production, and its children are the semantic values of
705 the component expressions in the recognized sequence, with the
706 exception of any voided expressions (using the <code>void:</code>
707 operator), void nonterminals, and character terminals, which are
708 ignored.
709
710 <p />For example, we could rewrite the production
711 for <a href="#production-example"><code>FullProduction</code></a> as a
712 generic production:
713 <pre>
714 generic FullProduction =
715 ProductionAttributes
716 Name UnqualifiedNonTerminal void:"=":Symbol Choice void:";":Symbol ;
717 ;
718 </pre>
719 The rewritten production has a generic node as its semantic value; the
720 grammar author thus does not need to define
721 a <code>FullProduction</code> class to represent the semantic value.
722 Furthermore, the rewritten production is equivalent to the following
723 production with an explicit semantic action:
724 <pre>
725 Node FullProduction =
726 v1:ProductionAttributes
727 v2:Name v3:UnqualifiedNonTerminal "=":Symbol v4:Choice ";":Symbol
728 { yyValue = GNode.create("Production", v1, v2, v3, v4); }
729 ;
730 </pre>
731 The two symbol references are not bound because they are explicitly
732 voided.
733
734 <p />Options, repetitions, and nested choices in generic productions
735 are treated just like the corresponding expressions in regular
736 productions. In other words, they may be desugared and lifted into
737 their own productions. As a result, they require explicit actions to
738 create their semantic values, unless, of course, <i>Rats!</i> can
739 automatically determine the corresponding values.
740
741 <p />The creation of generic syntax tree nodes can be customized
742 through the <a href="#attributes">factory attribute</a>, which
743 specifies a class different from <code>GNode</code>. For example,
744 <code>factory(MyTreeFactory)</code> causes <em>Rats!</em> to emit
745 invocations to <code>MyTreeFactory.create</code> methods instead
746 of <code>GNode.create</code>.
747
748 <!-- -------------------------------------------------------------------- -->
749
750 <a name="list-valued"></a><h4>List-Valued Productions</h4>
751
752 <p />If a grammar has the <code>flatten</code> attribute, pairs
753 resulting from a repeated expression are treated somewhat differently
754 in generic productions: the values on the list are added to the
755 production's generic node as <i>individual</i> children. For example,
756 consider this production for recognizing parameter lists in C:
757 <pre>
758 generic ParameterList =
759 ParameterDeclaration (void:",":Symbol ParameterDeclaration)* ;
760 </pre>
761 Because the semantic values of the embedded repetition are added as
762 invidividual children to the production's generic node, that node's
763 children are all parameter declarations, which is exactly the desired
764 behavior.
765
766 <p />Alternatively, <i>Rats!</i> can automatically deduce the semantic
767 value of productions with a <code>Pair</code> type. The production's
768 value is a list of all of a sequence's component expressions. For
769 example, consider this rewritten production for recognizing parameter
770 lists:
771 <pre>
772 Pair&lt;Node&gt; ParameterList =
773 ParameterDeclaration (void:",":Symbol ParameterDeclaration)* ;
774 </pre>
775 Beacuse the declared type
776 is <code>Pair&lt;Node&gt;</code>, <i>Rats!</i> automatically deduces
777 the semantic value of the production. It is a list containing the
778 value of the first parameter declaration followed by the value of the
779 repetition. The production is equivalent to the following production
780 using an explicit semantic action:
781 <pre>
782 Pair&lt;Node&gt; ParameterList =
783 head:ParamterDeclaration tail:(void:",":Symbol ParameterDeclaration)*
784 { yyValue = new Pair&lt;Node&gt;(head, tail); } ;
785 </pre>
786 As illustrated by this version, <i>Rats!</i> recognizes when the last
787 component expression in a list-valued production already has a list
788 value and turns that value into the overall list's tail. If the last
789 component expression does not have a list value, the overall list's
790 tail is the empty list.
791
792 <p />Whether to (1) use the <code>flatten</code> attribute so that
793 list elements are added as individual children to generic nodes or (2)
794 use list-valued productions to create lists and preserve them as
795 generic nodes' children is a trade-off. With the <code>flatten</code>
796 attribute, ASTs are more uniform, typically consisting of only generic
797 nodes and strings. In contrast, without the <code>flatten</code>
798 attribute, generic nodes may also contain lists of, say, nodes or
799 strings. However, flattening lists may result in the loss of
800 information. For example, consider this production for Java
801 compilation units:
802 <pre>
803 public generic CompilationUnit =
804 Spacing
805 PackageDeclaration? ImportDeclaration* Declaration*
806 EndOfFile ;
807 </pre>
808 When lists are flattened, there is no way to distinguish import
809 declarations from regular declarations <em>without</em> looking at the
810 actual children. In contrast, when lists are not flattened, the
811 generic node for compilation units has exactly three children,
812 corresponding to package, import, and regular declarations
813 respectively. Additionally, the preservation of lists in generic
814 nodes enables more exact typing of ASTs
815 through <i>Rats!</i>' <code>-ast</code> option. Consequently, the
816 recommended practice is <em>not</em> to use the <code>flatten</code>
817 attribute.
818
819 <!-- -------------------------------------------------------------------- -->
820
821 <a name="left-recursion"></a><h4>Left-Recursive Productions</h4>
822
823 <p />To simplify the specification of productions that recognize
824 expressions at different precedence levels, void, text-only, and
825 generic productions may contain <i>direct</i> left-recursions; though
826 arbitrary left-recursions are illegal in <i>Rats!</i> grammars just
827 as for PEGs. Directly left-recursive productions are automatically
828 transformed into equivalent right-iterative productions, while
829 preserving the left-recursive structure of the original production's
830 semantic value. As an example, consider the following generic
831 production for recognizing logical and expressions in C:
832 <pre>
833 generic LogicalAndExpression =
834 LogicalAndExpression void:"&&":Symbol BitwiseOrExpression
835 / BitwiseOrExpression
836 ;
837 </pre>
838 This directly left-recursive production is equivalent to the following
839 two productions, which leverage so-called actions (i.e., promises) to
840 create the semantic values:
841 <pre>
842 Node LogicalAndExpression =
843 seed:BitwiseOrExpression actions:LogicalAndExpressionTail*
844 { yyValue = apply(actions, seed); }
845 ;
846
847 constant Action&lt;Node&gt; LogicalAndExpressionTail =
848 "&&":Symbol right:BitwiseOrExpression
849 {
850 yyValue = new Action&lt;Node&gt;() {
851 public Node run(Node left) {
852 Node result = GNode.create("LogicalAndExpression", left, right);
853 result.setLocation(location(yyStart));
854 return result;
855 }};
856 }
857 ;
858 </pre>
859 The <code>LogicalAndExpressionTail*</code> expression creates a list
860 of {@link xtc.util.Action actions}, with each action on the list
861 creating a generic node that is annotated with the source location
862 corresponding to the start of the production.
863 (The <code>constant</code> attribute ensures that the Java binding for
864 <code>right</code> is declared <code>final</code>; this is necessary
865 because <code>right</code> is referenced in an anonymous inner class.)
866 The <code>LogicalAndExpression</code> production uses {@link
867 xtc.parser.ParserBase#apply(Pair,Object)} to apply each action in the
868 list onto the result of the previous action, starting with
869 the <code>seed</code> value for the first action. If the list is
870 empty, the seed value is simply passed through, which is the desired
871 behavior. By using actions and thus delaying the creation of generic
872 nodes, the rewritten productions ensure that the resulting abstract
873 syntax tree preserves left-associativity. Note that actions can also
874 be used outside of generic productions to create left-associative
875 abstract syntax trees.
876
877 <p />In the previous example, the use of a list of actions results in
878 the correct treatment of the base case: no new generic node is
879 created, rather the semantic value of the bitwise or expression is
880 simply passed through. When specifying productions that do not use
881 actions, grammar writers can achieve similar results by explicitly
882 binding <code>yyValue</code>. For alternatives in a generic
883 production that assign <code>yyValue</code> either through a binding
884 or a semantic action, <i>Rats!</i> does not create a new generic node
885 but rather uses the explicitly specified semantic value.
886
887 <!-- -------------------------------------------------------------------- -->
888
889 <a name="node-markers"></a><h4>Node Markers in Generic Productions</h4>
890
891 <p />Also in the previous example, there is only one recursive
892 alternative; consequently, the production's name, i.e.,
893 "<code>LogicalAndExpression</code>", provides a meaningful name for
894 the newly created generic node. However, languages such as C contain
895 more than one left-recursive operator at the same precedence level.
896 Using the features described so far, grammar developers can either
897 write one directly left-recursive generic production for all
898 operators, thus using the same name for all operators' generic nodes,
899 or they can write several right-iterative productions that create the
900 generic nodes through explicit semantic actions. Neither option is
901 particularly attractive and node markers provide a more elegant
902 solution. They are written as an at sign '<code>&#x40;</code>'
903 immediately followed by an identifier and specify a generic node's
904 name for nodes generated by the sequence they appear in.
905
906 <p />As an example, consider the following generic production for
907 recognizing postfix expressions in C:
908 <pre>
909 generic PostfixExpression =
910 &lt;Subscript&gt; PostfixExpression void:"[":Symbol Expression
911 void:"]":Symbol
912 &#x40;SubscriptExpression
913 / &lt;DirectSelection&gt; PostfixExpression void:".":Symbol Identifier
914 &#x40;DirectComponentSelection
915 / &lt;IndirectSelection&gt; PostfixExpression void:"-&gt;":Symbol Identifier
916 &#x40;IndirectComponentSelection
917 / &lt;FunctionCall&gt; PostfixExpression void:"(":Symbol ExpressionList?
918 void:")":Symbol
919 &#x40;FunctionCall
920 / &lt;Increment&gt; PostfixExpression void:"++":Symbol
921 &#x40;PostincrementExpression
922 / &lt;Decrement&gt; PostfixExpression void:"--":Symbol
923 &#x40;PostdecrementExpression
924 / &lt;Compound&gt; CompoundLiteral
925 / &lt;Primary&gt; PrimaryExpression
926 ;
927 </pre>
928 In a single directly left-recursive production, the example specifies
929 all of C's postfix expressions. Yet, each recursive alternative
930 contains a distinct node marker, thus resulting in a differently named
931 generic node. Internally (and as described above), <i>Rats!</i>
932 converts the directly left-recursive production into the corresponding
933 right-iterative version, which uses actions to create left-recursive
934 AST nodes. Note that the last two alternatives do not require node
935 markers (nor bindings to <code>yyValue</code>) because they provide
936 the base cases for the recursion.
937
938 <!-- -------------------------------------------------------------------- -->
939
940 <a name="parameters"></a><h4>Modules, Name Spaces, and Parameters</h4>
941
942 The intent behind <i>Rats!</i>' module system is to facilitate the
943 re-use and extensibility of grammar specifications. Even without
944 parameters and modifications, basic modules help, as they allow a
945 grammar writer to break up a grammar into several units. All modules
946 exist in the same global name space. Without parameters and
947 modifications, this name space consists simply of the module names as
948 specified by the corresponding <code>module</code> declarations. With
949 parameters and modifications, this name space consists of the module
950 names of all <em>instantiated</em> modules (with instantiation being
951 the process of providing arguments to parameterized modules).
952
953 <p />In contrast to module names, nonterminals are only meaningful in
954 relation to a specific module. Without any <code>import</code>
955 or <code>modify</code> declarations, a module can only reference the
956 nonterminals defined in that module. In the presence
957 of <code>import</code> or <code>modify</code> declarations, a module
958 can also reference the public and protected nonterminals defined by
959 imported modules and all nonterminals defined by modified modules.
960
961 <p />Nonterminals may be ambiguous, e.g., the same nonterminal may be
962 defined within a module and an imported module or in several imported
963 modules. <i>Rats!</i> gives precedence to nonterminals defined in the
964 same module as the nonterminal reference. For example, if
965 module <code>Foo</code> defines nonterminal <code>Name</code> and
966 imports module <code>Bar</code>, which also defines nonterminal
967 <code>Name</code>, then a reference to <code>Name</code> appearing in
968 one of <code>Foo</code>'s productions is interpreted to
969 mean <code>Foo</code>'s <code>Name</code>. <code>Bar</code>'s
970 <code>Name</code> can still be referenced by using the qualified
971 notation <code>Bar.Name</code>. Furthermore, if
972 module <code>Foo</code> does not define <code>Name</code> but
973 imports <code>Bar</code> and <code>Baz</code>, which both
974 define <code>Name</code>, any reference to <code>Name</code>
975 in <code>Foo</code> must be qualified, writing <code>Bar.Name</code> and
976 <code>Baz.Name</code> respectively. Note that, while qualified
977 nonterminals are globally unique and thus always unambiguous, a
978 nonterminal, whether qualified or not, can only be used if the
979 corresponding production's module is the same module, imported by the
980 referencing module, or modified by the referencing module.
981
982 <p />Parameterized modules improve re-use when compared to basic
983 modules, as the same parameterized module can be used with different
984 actual dependencies. For example, module <code>xtc.util.Symbol</code>
985 takes one parameter for a module defining spacing:
986 <pre>
987 module xtc.util.Symbol(Spacing);
988
989 import Spacing;
990
991 String Symbol = SymbolCharacters Spacing ;
992
993 transient String SymbolCharacters = <i>..elided..</i> ;
994 </pre>
995 As a result, this module can be instantiated with different forms of
996 spacing, without changing <code>xtc.util.Symbol</code>. At the same
997 time, an instantiation must provide a module that specifies a void
998 nonterminal <code>Spacing</code> for the resulting module to be
999 meaningful.
1000
1001 <p />A parameterized module is instantiated by specifying the
1002 corresponding arguments in the corresponding <code>import</code>
1003 declaration:
1004 <pre>
1005 import xtc.util.Symbol(xtc.util.Spacing);
1006 </pre>
1007 This <code>import</code> declaration without a target name is
1008 equivalent to the following declaration with a target name:
1009 <pre>
1010 import xtc.util.Symbol(xtc.util.Spacing) as xtc.util.Symbol;
1011 </pre>
1012 In either case, all occurrences of the parameter module name
1013 <code>Spacing</code> are replaced by the specified argument module
1014 name <code>xtc.util.Spacing</code>. Furthermore, all occurrences of
1015 the module name itself are replaced by the specified target name
1016 (which, in this example, is the same as the module name). Finally,
1017 the instantiated module becomes the sole module of that name in the
1018 global module name space. No other instantiation with the same target
1019 name is possible, unless it instantiates exactly the same module with
1020 the same arguments.
1021
1022 <p />Note that the nonterminal <code>Spacing</code> in the production
1023 for <code>Symbol</code> is not renamed during instantiation, as it
1024 denotes a nonterminal and not a module. However, if the nonterminal
1025 was written as <code>Spacing.Spacing</code>, it would be renamed
1026 to <code>xtc.util.Spacing.Spacing</code>. Further note
1027 that <code>xtc.util.Symbol</code> could be instantiated with a
1028 different argument within the same grammar, as long as that
1029 instantiation's target name is different. Finally, note that once
1030 instantiated, other modules can reference the instantiated module
1031 through its target name. For example, after
1032 module <code>xtc.util.Symbol</code> has been instantiated through
1033 either of the above <code>import</code> declarations, it can also be
1034 imported as following:
1035 <pre>
1036 import xtc.util.Symbol;
1037 </pre>
1038 This import declaration, when appearing in a dependent module,
1039 references the same instantiated module.
1040
1041 <p />While module parameters and arguments can only be module names
1042 and never more complex expressions, sometimes more complex arguments
1043 are desirable. For example, a grammar writer may want to
1044 instantiate <code>xtc.util.Symbol</code> with a more complex
1045 module <code>my.Spacing</code>, which requires its own
1046 argument <code>my.Argument</code>. In this case, the grammar writer
1047 can use an <code>instantiate</code> declaration, which instantiates a
1048 module but does not make its nonterminals accessible from within the
1049 instantiating module. In the example, the grammar writer would use
1050 the following declarations:
1051 <pre>
1052 instantiate my.Spacing(my.Argument) as Spacing;
1053 import xtc.util.Symbol(Spacing);
1054 </pre>
1055
1056 <p />Module dependencies are resolved through a breadth-first search
1057 starting with the top-level module. In other words, a dependent
1058 module's dependencies are only processed <em>after</em> all the
1059 dependencies of the depending module have been resolved. As a result,
1060 the order of <code>import</code>, <code>instantiate</code>, and
1061 <code>modify</code> declarations in a module does not matter and
1062 mutually dependent modules can be instantiated within the same module.
1063 For example, <code>xtc.lang.CSpacing</code> has a parameter for a
1064 constant module and <code>xtc.lang.CConstant</code> has a parameter
1065 for a spacing module, with each module importing the parameterized
1066 module. To instantiate these two mutually dependent modules,
1067 module <code>xtc.lang.C</code> simply declares (with some intermediate
1068 declarations omitted and ignoring the
1069 additional <code>xtc.lang.CState</code> argument):
1070 <pre>
1071 instantiate xtc.lang.CConstant(xtc.lang.CSpacing);
1072 instantiate xtc.lang.CSpacing(xtc.lang.CState, xtc.lang.CConstant);
1073 </pre>
1074 Because it uses breadth-first search, <i>Rats!</i> processes these
1075 two <code>instantiate</code> declarations before processing the
1076 corresponding
1077 <code>import</code> declarations in <code>xtc.lang.CConstant</code>
1078 and <code>xtc.lang.CSpacing</code>. By the time <i>Rats</i> reaches
1079 the <code>import</code> declarations in the dependent modules, the
1080 modules have been instantiated and no arguments are necessary.
1081
1082 <!-- -------------------------------------------------------------------- -->
1083
1084 <a name="modifications"></a><h4>Module Modifications</h4>
1085
1086 To further facilitate re-use and extensibility, <i>Rats!</i> supports
1087 module modifications, which concisely express extensions to a grammar
1088 and, in addition to full productions, can also contain <em>alternative
1089 additions</em>, which add new alternatives to a production's top-level
1090 choice, <em>alternative removals</em>, which remove alternatives from
1091 a production's top-level choice, and <em>production overrides</em>,
1092 which can override an entire production, specific alternatives, or a
1093 production's attributes. All three types of partial production, whose
1094 syntax is specified <a href="#syntax">above</a> and illustrated below,
1095 depend on the different alternatives in a production's top-level
1096 choice having sequence names. Consequently, it is good practice to
1097 always name your sequences!
1098
1099 <p />A module modification must contain a single <code>modify</code>
1100 declaration, which specifies the module to be modified. For example,
1101 the following declaration specifies that
1102 module <code>xtc.lang.JavaSymbol</code> modifies
1103 module <code>Symbol</code>:
1104 <pre>
1105 module xtc.lang.JavaSymbol(Symbol);
1106
1107 modify Symbol;
1108 </pre>
1109 The example uses a module parameter to ensure that
1110 module <code>xtc.lang.JavaSymbol</code> can be applied to different
1111 versions of <code>Symbol</code>. The resulting module contains all
1112 full productions appearing in both the modifying and modified modules
1113 (in the example, <code>xtc.lang.JavaSymbol</code>
1114 and <code>Symbol</code>, respectively). Furthermore, all productions
1115 in the resulting module are modified as specified by the alternative
1116 additions, alternative removals, and production overrides in the
1117 modifying module. Modifications are applied in the same order as they
1118 appear in the modifying module (in the
1119 example, <code>xtc.lang.JavaSymbol</code>). The resulting productions
1120 are the only versions; i.e., all nonterminals, whether they originally
1121 appear in the modifying module or the modified module reference the
1122 modified productions.
1123
1124 <p />The resulting module's options are the options of the modifying
1125 module, with exception of
1126 any <a
1127 href="#stateful"><code>stateful</code></a>, <a
1128 href="#set"><code>setOfString</code></a>,
1129 and <a href="#flag"><code>flag</code></a> options, which are preserved
1130 if they appear in the modified module's options. Furthermore, the
1131 modifying module's header, body, and footer actions are combined with
1132 the modified module's actions (if they exist).
1133
1134 <p />An alternative addition adds an expression before or after an
1135 existing sequence. For example, the following addition adds
1136 sequence <code><i>s</i></code> after sequence <code>&lt;Bar&gt;</code>
1137 in production <code>Foo</code>:
1138 <pre>
1139 Type Foo += &lt;Bar&gt; ... / &lt;NewSequence&gt; <i>s</i> ;
1140 </pre>
1141 Similarly, the following addition adds the new sequence before
1142 sequence <code>&lt;Bar&gt;</code>:
1143 <pre>
1144 Type Foo += &lt;NewSequence&gt; <i>s</i> / &lt;Bar&gt; ... ;
1145 </pre>
1146 Note that the new expression may actually consist of several sequences
1147 and not only one as suggested by the examples. Further note that the
1148 type and nonterminal must both be specified and match an existing full
1149 production.
1150
1151 <p />An alternative removal removes one or more sequences from a
1152 production. For example, the following removal eliminates sequences
1153 <code>&lt;Bar&gt;</code> and <code>&lt;Baz&gt;</code> from production
1154 <code>Foo</code>:
1155 <pre>
1156 Type Foo -= &lt;Bar&gt;, &lt;Baz&gt; ;
1157 </pre>
1158 As before, the type and nonterminal must both be specified and match
1159 an existing full production.
1160
1161 <p />A production override can replace all alternatives, only specific
1162 alternatives, or a production's attributes. For example, the
1163 following override replaces all alternatives of
1164 production <code>Foo</code> with expression <code><i>e</i></code>:
1165 <pre>
1166 Type Foo := <i>e</i> ;
1167 </pre>
1168 In contrast, this override only replaces
1169 alternatives <code>&lt;Bar&gt;</code> and <code>&lt;Baz&lt;</code>:
1170 <pre>
1171 Type Foo := ... / &lt;Bar&gt; <i>s1</i> / &lt;Baz&gt; <i>s2</i> ;
1172 </pre>
1173 Finally, this override replaces <code>Foo</code>'s attributes with
1174 the <code>public</code> attribute:
1175 <pre>
1176 public Type Foo := ... ;
1177 </pre>
1178 Note that the list of attributes may be empty, thus removing all
1179 attributes from the full production.
1180
1181 <!-- -------------------------------------------------------------------- -->
1182
1183 <a name="transient"></a><h4>Memoization and Transient Productions</h4>
1184
1185 Packrat parsers process their input in time linear to the size of the
1186 input, even if they need to backtrack. The reason they can do this is
1187 that they store, or <i>memoize</i>, the result of trying each
1188 nonterminal at every input position &#150; hence the name "packrat"
1189 parser.
1190
1191 <p />The benefits of memoization are best illustrated with a production
1192 from <i>Rats!</i>' own grammar:
1193 <pre>
1194 Element Suffix =
1195 ( p:Primary "?":Symbol { yyValue = new Option(p); }
1196 / p:Primary "*":Symbol { yyValue = new Repetition(false, p); }
1197 / p:Primary "+":Symbol { yyValue = new Repetition(true, p); }
1198 / Primary
1199 )
1200 ;
1201 </pre>
1202 The <code>Suffix</code> production matches possible suffix expressions
1203 in the input, with each of the four alternatives in the choice first
1204 trying to parse a primary expression. Assume that the current input
1205 contains a primary expression <i>without</i> a suffix (i.e., the
1206 fourth alternative is the alternative that will succeed). If the
1207 parser did <i>not</i> memoize its results, the primary expression
1208 would be parsed <i>four</i> times, once for each alternative,
1209 resulting in suboptimal performance. However, because parsers
1210 generated by <i>Rats!</i> memoize their results, the primary
1211 expression is parsed exactly once. Each subsequent alternative simply
1212 looks up the result of the first parse.
1213
1214 <p />Note that it is possible to rewrite the production
1215 for <code>Suffix</code> to not require backtracking. An alternative
1216 expression, without semantic actions, might look like this:
1217 <pre>
1218 Primary ( Question / Star / Plus / /* Empty */ )
1219 </pre>
1220 Further note that other top-down parsers, such as JavaCC and ANTLR,
1221 may not require backtracking, even with a comparable production to the
1222 one used in <i>Rats!</i>' own grammar as they support (limited)
1223 lookahead. However, the original form clearly and concisely expresses
1224 the intent behind this production and, because parsers generated
1225 by <i>Rats!</i> memoize their results, does not require any
1226 fiddling with lookahead (as would be necessary for other top-down
1227 parsers).
1228
1229 <p />In theory, packrat parsers create a two-dimensional array, with
1230 characters in the input stream along the x-axis and nonterminals along
1231 the y-axis. In practice, not all values in this array are calculated
1232 (many of them represent mismatched nonterminals anyway) and the array
1233 is sparse. To avoid allocating memory for the entire array, parsers
1234 generated by <i>Rats!</i> break each column into several chunks.
1235 Memory for the different chunks is allocated independently and on
1236 demand (i.e., if a parsing result needs to be stored). Furthermore,
1237 for productions that are only referenced once in the entire grammar
1238 the corresponding row is never allocated.
1239
1240 <p />Grammar writers have further control over memory allocation by
1241 declaring productions to be <code>transient</code>: if a production is
1242 transient, the corresponding row is not allocated either. The
1243 transient keyword can thus reduce a parser's memory footprint and also
1244 improve its performance. However, it is also <i>dangerous</i>
1245 because, if overused, the resulting parser may need to reparse the
1246 same input for the same nonterminal several times and thus perform in
1247 time superlinear to the size of the input.
1248
1249 <p />So, which productions should be declared transient? In other
1250 parsers, the parser processes <i>tokens</i> generated by a separate
1251 lexer instead of accessing the character stream directly. Packrat
1252 parser grammars thus need to include productions that build up tokens.
1253 Examples include the <code>Escape</code>, <code>HexNumber</code>, and
1254 <code>HexDigit</code> productions in <i>Rats!</i>' own grammar
1255 (shown <a href="#transient-example">above</a>). Such productions can
1256 be declared transient, as the parser typically does not backtrack at
1257 the level of individual characters. Furthermore, productions that
1258 cover ignored input characters, notably all productions that cover
1259 white space and comments, can be declared transient as well. However,
1260 when in doubt, it is best to <i>not</i> declare a production as
1261 transient, or to perform performance studies on several inputs to see
1262 how such declarations impact the parser's memory footprint and
1263 performance.
1264
1265 <!-- -------------------------------------------------------------------- -->
1266
1267 <a name="attributes"></a><h4>Grammar and Production Attributes</h4></a>
1268
1269 <i>Rats!</i> supports a number of options, which are either specified
1270 as a grammar-wide option in the top-level module's introduction or as
1271 per-production attributes:<ul>
1272
1273 <li><a
1274 name="public-attribute"></a><code>public</code>, <code>protected</code>,
1275 and <code>private</code> instruct <i>Rats!</i> to make a production a
1276 top-level production, referenceable from other modules, and
1277 referenceable only from the same module, respectively. These
1278 attributes do not have values. Furthermore, these attributes can only
1279 be specified as per-production attributes. The default
1280 is <code>protected</code> and can be omitted from productions.</li>
1281
1282 <li><code>transient</code> instructs <i>Rats!</i> not to memoize the
1283 corresponding production. The attribute does not have a value and can
1284 only be specified as a per-production attribute.</li>
1285
1286 <li><code>memoized</code> instructs <i>Rats!</i> to always memoize the
1287 corresponding production. The attribute does not have a value and can
1288 only be specified as a per-production attribute.</li>
1289
1290 <li><code>inline</code> instructs <i>Rats!</i> not to memoize the
1291 corresponding production. For productions that are neither void nor
1292 text-only, it also instructs <i>Rats!</i> to inline the production if
1293 the corresponding nonterminal appears as the only element in an
1294 ordered choice's alternative. The attribute does not have a value and
1295 can only be specified as a per-production attribute.</li>
1296
1297 <li><code>noinline</code> instructs <i>Rats!</i> not to inline the
1298 production, even if it is (recognized as) transient. The attribute
1299 does not have a value and can only be specified as a per-production
1300 attribute.</li>
1301
1302 <li><code>constant</code> instructs <i>Rats!</i> to make all bindings
1303 constant and thus unmodifiable. The attribute does not have a value.
1304 This attribute can be specified either as a grammar-wide attribute or
1305 as a per-production attribute.</li>
1306
1307 <li><code>withLocation</code> instructs <i>Rats!</i> to annotate all
1308 semantic values that are instances of {@link xtc.tree.Node} with their
1309 locations in the source file. The attribute does not have a value.
1310 This attribute can be specified either as a grammar-wide attribute or
1311 as a per-production attribute.</li>
1312
1313 <li><a name="stateful-attribute"></a><code>stateful</code>
1314 instructs <i>Rats!</i> to include code for managing global parsing
1315 state through a {@link xtc.util.State state object}. This attribute
1316 is used both as a grammar-wide attribute and a per-production
1317 attribute. The grammar-wide attribute value specifies the class
1318 managing the global state (which must have a no-argument
1319 constructor). <i>Rats!</i> includes a static final
1320 field <code>yyState</code>, which references an instance of that
1321 class, in the generated parser. For a production with this attribute,
1322 the attribute does not have a value and <i>Rats!</i> includes the
1323 appropriate calls to {@link xtc.util.State#start()}, {@link
1324 xtc.util.State#commit()}, and {@link xtc.util.State#abort()}. Note
1325 that the state object must be reset explicitly with the
1326 per-production <code>resetting</code> attribute. Further note that,
1327 if a grammar spans several modules, all the module's stateful options
1328 must specify the same class name.</li>
1329
1330 <li><code>resetting</code> instructs <i>Rats!</i> to include code to
1331 {@link xtc.util.State#reset(String) reset} the global state object.
1332 The attribut does not have a value. This attribute can only be
1333 specified as a per-production attribute and requires a grammar-wide
1334 <code>stateful</code> attribute.</li>
1335
1336 <li><code>ignoringCase</code> instructs <i>Rats!</i> to perform
1337 comparisons for string matches in a case-insensitive manner. The
1338 attribute does not have a value. This attribute can be specified
1339 either as a grammar-wide attribute or as a per-production
1340 attribute.</li>
1341
1342 <li><code>flatten</code> instructs <i>Rats!</i> to add the elements of
1343 list values (i.e., instances of {@link xtc.util.Pair}) to generic
1344 nodes instead of adding the list values themselves. This attribute
1345 does not have a value and can only be specified as a grammar-wide
1346 attribute.</li>
1347
1348 <li><code>variant</code> instructs <i>Rats!</i> that all generic nodes
1349 returned by the production as a semantic value are variants of the
1350 same type. This attribute does not have a value and can only be
1351 specified as a per-production attribute.</li>
1352
1353 <li><code>withParseTree</code> instructs <i>Rats!</i> to generate a
1354 parse tree instead of an abstract syntax tree. This attribute is
1355 specified as a grammar-wide attribute and does not have a value. For
1356 a grammar with this attribute, <i>Rats!</i> rewrites all generic,
1357 text-only, and void productions as well as productions that pass the
1358 semantic value through to preserve the input in the form of {@link
1359 xtc.tree.Formatting} annotations. The embedded AST generally has the
1360 same structure as for the grammr without the attribute. The exception
1361 are strings, which are represented as instances of {@link
1362 xtc.tree.Token}. Furthermore, generic nodes include additional
1363 children consisting of <code>Formatting</code>
1364 annotating <code>null</code> values if voided expressions or void
1365 nonterminals appear between two non-void repetitions.</li>
1366
1367 <li><code>verbose</code> instructs <i>Rats!</i> to print debugging
1368 information to the console for each parser method invocation. The
1369 attribute does not have a value. This attribute can be specified
1370 either as a grammar-wide attribute or as a per-production
1371 attribute.</li>
1372
1373 <li><code>nowarn</code> instructs <i>Rats!</i> to suppress warnings
1374 during parser generation. The attribute does not have a value; it can
1375 be specified either as a grammar-wide attribute or as a per-production
1376 attribute.</li>
1377
1378 <li><a name="parser-attribute"></a><code>parser</code>
1379 instructs <i>Rats!</i> to use the fully qualified class name specified
1380 by the attribute's value as the Java class name for the generated
1381 parser, instead of deducing that name from the module's name. This
1382 attribute can only be specified as a grammar-wide attribute.</li>
1383
1384 <li><code>factory</code> instructs <i>Rats!</i> to use the (optionally
1385 qualified) class name specified by the attribute's value as the
1386 factory for creating generic nodes instead of
1387 using <code>xtc.tree.GNode</code>. This attribute can only be
1388 specified as a grammar-wide attribute.</li>
1389
1390 <li><code>visibility</code> instructs <i>Rats!</i> to make the
1391 generated parser class either public or package private, depending on
1392 the attribute's value (<code>public</code>
1393 or <code>packagePrivate</code>). This attribute can only be specified
1394 as a grammar-wide attribute. The default for modules without this
1395 attribute is public.</li>
1396
1397 <li><code>rawTypes</code> instructs <i>Rats!</i> to use raw types
1398 instead of generic types. Besides a
1399 "<code>&#x40;SuppressWarnings("unchecked")</code>" annotation for the
1400 parser class, the generated code is compatible with Java 1.4. The
1401 attribute does not have a value and can only be specified as a
1402 grammar-wide attribute.</li>
1403
1404 <li><code>main</code> instructs <i>Rats!</i> to include a static main
1405 method that parses one or more input files and prints the
1406 corresponding results. The value of this attribute must be the name
1407 of the top-level nonterminal to parse. This attribute can only be
1408 specified as a grammar-wide attribute.</li>
1409
1410 <li><code>printer</code> instructs <i>Rats!</i> to use the visitor
1411 specified by the attribute's value for printing the semantic value
1412 returned by a successful parse. This attribute can only be specified
1413 as a grammar-wide attribute and requires that the grammar also has the
1414 <code>main</code> attribute.</li>
1415
1416 <li><a name="set"></a><code>setOfString</code> instructs <i>Rats!</i>
1417 to include a static final set of strings with the attribute's value as
1418 its name. <i>Rats!</i> also includes a convience method for filling
1419 sets <code>add(Set<T>,T[])</code>. This attribute can only be
1420 specified as a grammar-wide attribute.</li>
1421
1422 <li><a name="flag"></a><code>flag</code> instructs <i>Rats!</i> to
1423 include a public static final boolean field with the attribute's value
1424 as its name. The field's value is <code>true</code>. This attribute
1425 can only be specified as a grammar-wide attribute.</li>
1426
1427 <li><code>genericAsVoid</code> instructs <i>Rats!</i> to treat generic
1428 productions as void productions. The attribute does not have a value
1429 and can only be specified as a grammar-wide attribute.</li>
1430
1431 <li><code>dump</code> instructs <i>Rats!</i> to include a method for
1432 dumping a plain-text representation of the parser's memoization table
1433 to a printer: <code>dump({@link xtc.tree.Printer})</code>. The
1434 attribute does not have a value and can only be specified as a
1435 grammar-wide attribute.</li>
1436
1437 <li><code>explicit</code> instructs <i>Rats!</i> to always generate an
1438 explicit error for the production instead of reusing parse errors
1439 where possible. The attribute does not have a value and can only be
1440 specified as a per-production attribute.</li>
1441
1442 </ul>
1443
1444 <p />A note on licensing: Parsers generated with the
1445 <code>main</code>, <code>printer</code>, and <code>dump</code>
1446 attributes link with code licensed under the GNU GPL version 2. As a
1447 result, parsers generated with these attributes may <em>not</em> be
1448 used in software that is not compatible with the GPL version 2. To
1449 generate parsers that are not restricted by the GPL, use
1450 the <code>-lgpl</code> option when running <em>Rats!</em>.
1451
1452 <!-- -------------------------------------------------------------------- -->
1453
1454 <a name="parser-actions"></a><h4>Parser Actions</h4>
1455
1456 Some languages cannot be expressed by PEGs or <i>Rats!</i> grammars.
1457 For example, the on-the-wire format
1458 for <a href="http://world.std.com/~cme/html/spki.html">SPKI/SDSI</a>
1459 represents byte strings as one or more digits, followed by a colon,
1460 followed by the number of characters specified by the sequence of
1461 digits (when interpreted as a decimal integer); but parsing a specific
1462 number of characters cannot be expressed by PEGs. Parser actions
1463 allow grammar writers to still use <i>Rats!</i> for such languages by
1464 providing a low-level extensibility mechanism.
1465
1466 <p />Parser actions work as follows. Before executing the code in a
1467 parser action, the variable <code>yyBase</code> is assigned the index
1468 of the current parser position. The parser action can then use this
1469 index together with the parser's methods to further consume the input,
1470 parsing the expression not expressible by PEGs. When finished, it
1471 assigns the corresponding result to <code>yyResult</code>, which must
1472 either be a {@link xtc.parser.SemanticValue} object indicating a
1473 successful parse or a {@link xtc.parser.ParseError} object indicating
1474 a parse error. In the case of a semantic value object, that object's
1475 semantic value becomes the semantic value of the production, unless
1476 another action after the parser action changes it.
1477
1478 <p />The following grammar illustrates the use of a parser action for
1479 parsing byte strings as used by SPKI/SDSI. Note that
1480 the <code>yyStart</code> reference in the parser action is the parser
1481 position at the beginning of the production and is used for indicating
1482 the position of an error.
1483 <pre>
1484 module ByteString;
1485
1486 body {
1487 Result parseChars(String number, int start, int base) throws IOException {
1488 int n;
1489
1490 try {
1491 n = Integer.parseInt(number);
1492 } catch (NumberFormatException x) {
1493 return new ParseError("Malformed length", start);
1494 }
1495
1496 StringBuilder buf = new StringBuilder(n);
1497 for (int i=0; i&lt;n; i++) {
1498 int c = character(base + i);
1499
1500 if (c != -1) {
1501 buf.append((char)c);
1502 } else {
1503 return new ParseError("Unexpected end of bytestring", base + i);
1504 }
1505 }
1506
1507 return new SemanticValue(buf.toString(), base + n);
1508 }
1509 }
1510
1511 option main(ByteString);
1512
1513 public String ByteString =
1514 n:Integer ':' ^{ yyResult = parseChars(n, yyStart, yyBase); } ;
1515
1516 String Integer = [0-9]+ ;
1517 </pre>
1518
1519 </body></html>