1<html> 2<head> 3<title>The Lemon Parser Generator</title> 4</head> 5<body bgcolor='white'> 6<h1 align='center'>The Lemon Parser Generator</h1> 7 8<p>Lemon is an LALR(1) parser generator for C. 9It does the same job as "bison" and "yacc". 10But Lemon is not a bison or yacc clone. Lemon 11uses a different grammar syntax which is designed to 12reduce the number of coding errors. Lemon also uses a 13parsing engine that is faster than yacc and 14bison and which is both reentrant and threadsafe. 15(Update: Since the previous sentence was written, bison 16has also been updated so that it too can generate a 17reentrant and threadsafe parser.) 18Lemon also implements features that can be used 19to eliminate resource leaks, making it suitable for use 20in long-running programs such as graphical user interfaces 21or embedded controllers.</p> 22 23<p>This document is an introduction to the Lemon 24parser generator.</p> 25 26<h2>Security Note</h2> 27 28<p>The language parser code created by Lemon is very robust and 29is well-suited for use in internet-facing applications that need to 30safely process maliciously crafted inputs.</p> 31 32<p>The "lemon.exe" command-line tool itself works great when given a valid 33input grammar file and almost always gives helpful 34error messages for malformed inputs. However, it is possible for 35a malicious user to craft a grammar file that will cause 36lemon.exe to crash. 37We do not see this as a problem, as lemon.exe is not intended to be used 38with hostile inputs. 39To summarize:</p> 40 41<ul> 42<li>Parser code generated by lemon → Robust and secure 43<li>The "lemon.exe" command line tool itself → Not so much 44</ul> 45 46<h2>Theory of Operation</h2> 47 48<p>The main goal of Lemon is to translate a context free grammar (CFG) 49for a particular language into C code that implements a parser for 50that language. 51The program has two inputs:</p> 52<ul> 53<li>The grammar specification. 54<li>A parser template file. 55</ul> 56<p>Typically, only the grammar specification is supplied by the programmer. 57Lemon comes with a default parser template which works fine for most 58applications. But the user is free to substitute a different parser 59template if desired.</p> 60 61<p>Depending on command-line options, Lemon will generate up to 62three output files.</p> 63<ul> 64<li>C code to implement the parser. 65<li>A header file defining an integer ID for each terminal symbol. 66<li>An information file that describes the states of the generated parser 67 automaton. 68</ul> 69<p>By default, all three of these output files are generated. 70The header file is suppressed if the "-m" command-line option is 71used and the report file is omitted when "-q" is selected.</p> 72 73<p>The grammar specification file uses a ".y" suffix, by convention. 74In the examples used in this document, we'll assume the name of the 75grammar file is "gram.y". A typical use of Lemon would be the 76following command:</p> 77<pre> 78 lemon gram.y 79</pre> 80<p>This command will generate three output files named "gram.c", 81"gram.h" and "gram.out". 82The first is C code to implement the parser. The second 83is the header file that defines numerical values for all 84terminal symbols, and the last is the report that explains 85the states used by the parser automaton.</p> 86 87<h3>Command Line Options</h3> 88 89<p>The behavior of Lemon can be modified using command-line options. 90You can obtain a list of the available command-line options together 91with a brief explanation of what each does by typing</p> 92<pre> 93 lemon "-?" 94</pre> 95<p>As of this writing, the following command-line options are supported:</p> 96<ul> 97<li><b>-b</b> 98Show only the basis for each parser state in the report file. 99<li><b>-c</b> 100Do not compress the generated action tables. The parser will be a 101little larger and slower, but it will detect syntax errors sooner. 102<li><b>-d</b><i>directory</i> 103Write all output files into <i>directory</i>. Normally, output files 104are written into the directory that contains the input grammar file. 105<li><b>-D<i>name</i></b> 106Define C preprocessor macro <i>name</i>. This macro is usable by 107"<tt><a href='#pifdef'>%ifdef</a></tt>", 108"<tt><a href='#pifdef'>%ifndef</a></tt>", and 109"<tt><a href="#pifdef">%if</a></tt> lines 110in the grammar file. 111<li><b>-E</b> 112Run the "%if" preprocessor step only and print the revised grammar 113file. 114<li><b>-g</b> 115Do not generate a parser. Instead write the input grammar to standard 116output with all comments, actions, and other extraneous text removed. 117<li><b>-l</b> 118Omit "#line" directives in the generated parser C code. 119<li><b>-m</b> 120Cause the output C source code to be compatible with the "makeheaders" 121program. 122<li><b>-p</b> 123Display all conflicts that are resolved by 124<a href='#precrules'>precedence rules</a>. 125<li><b>-q</b> 126Suppress generation of the report file. 127<li><b>-r</b> 128Do not sort or renumber the parser states as part of optimization. 129<li><b>-s</b> 130Show parser statistics before exiting. 131<li><b>-T<i>file</i></b> 132Use <i>file</i> as the template for the generated C-code parser implementation. 133<li><b>-x</b> 134Print the Lemon version number. 135</ul> 136 137<h3>The Parser Interface</h3> 138 139<p>Lemon doesn't generate a complete, working program. It only generates 140a few subroutines that implement a parser. This section describes 141the interface to those subroutines. It is up to the programmer to 142call these subroutines in an appropriate way in order to produce a 143complete system.</p> 144 145<p>Before a program begins using a Lemon-generated parser, the program 146must first create the parser. 147A new parser is created as follows:</p> 148<pre> 149 void *pParser = ParseAlloc( malloc ); 150</pre> 151<p>The ParseAlloc() routine allocates and initializes a new parser and 152returns a pointer to it. 153The actual data structure used to represent a parser is opaque — 154its internal structure is not visible or usable by the calling routine. 155For this reason, the ParseAlloc() routine returns a pointer to void 156rather than a pointer to some particular structure. 157The sole argument to the ParseAlloc() routine is a pointer to the 158subroutine used to allocate memory. Typically this means malloc().</p> 159 160<p>After a program is finished using a parser, it can reclaim all 161memory allocated by that parser by calling</p> 162<pre> 163 ParseFree(pParser, free); 164</pre> 165<p>The first argument is the same pointer returned by ParseAlloc(). The 166second argument is a pointer to the function used to release bulk 167memory back to the system.</p> 168 169<p>After a parser has been allocated using ParseAlloc(), the programmer 170must supply the parser with a sequence of tokens (terminal symbols) to 171be parsed. This is accomplished by calling the following function 172once for each token:<p> 173<pre> 174 Parse(pParser, hTokenID, sTokenData, pArg); 175</pre> 176<p>The first argument to the Parse() routine is the pointer returned by 177ParseAlloc(). 178The second argument is a small positive integer that tells the parser the 179type of the next token in the data stream. 180There is one token type for each terminal symbol in the grammar. 181The gram.h file generated by Lemon contains #define statements that 182map symbolic terminal symbol names into appropriate integer values. 183A value of 0 for the second argument is a special flag to the 184parser to indicate that the end of input has been reached. 185The third argument is the value of the given token. By default, 186the type of the third argument is "void*", but the grammar will 187usually redefine this type to be some kind of structure. 188Typically the second argument will be a broad category of tokens 189such as "identifier" or "number" and the third argument will 190be the name of the identifier or the value of the number.</p> 191 192<p>The Parse() function may have either three or four arguments, 193depending on the grammar. If the grammar specification file requests 194it (via the <tt><a href='#extraarg'>%extra_argument</a></tt> directive), 195the Parse() function will have a fourth parameter that can be 196of any type chosen by the programmer. The parser doesn't do anything 197with this argument except to pass it through to action routines. 198This is a convenient mechanism for passing state information down 199to the action routines without having to use global variables.</p> 200 201<p>A typical use of a Lemon parser might look something like the 202following:</p> 203<pre> 204 1 ParseTree *ParseFile(const char *zFilename){ 205 2 Tokenizer *pTokenizer; 206 3 void *pParser; 207 4 Token sToken; 208 5 int hTokenId; 209 6 ParserState sState; 210 7 211 8 pTokenizer = TokenizerCreate(zFilename); 212 9 pParser = ParseAlloc( malloc ); 213 10 InitParserState(&sState); 214 11 while( GetNextToken(pTokenizer, &hTokenId, &sToken) ){ 215 12 Parse(pParser, hTokenId, sToken, &sState); 216 13 } 217 14 Parse(pParser, 0, sToken, &sState); 218 15 ParseFree(pParser, free ); 219 16 TokenizerFree(pTokenizer); 220 17 return sState.treeRoot; 221 18 } 222</pre> 223<p>This example shows a user-written routine that parses a file of 224text and returns a pointer to the parse tree. 225(All error-handling code is omitted from this example to keep it 226simple.) 227We assume the existence of some kind of tokenizer which is created 228using TokenizerCreate() on line 8 and deleted by TokenizerFree() 229on line 16. The GetNextToken() function on line 11 retrieves the 230next token from the input file and puts its type in the 231integer variable hTokenId. The sToken variable is assumed to be 232some kind of structure that contains details about each token, 233such as its complete text, what line it occurs on, etc.</p> 234 235<p>This example also assumes the existence of a structure of type 236ParserState that holds state information about a particular parse. 237An instance of such a structure is created on line 6 and initialized 238on line 10. A pointer to this structure is passed into the Parse() 239routine as the optional 4th argument. 240The action routine specified by the grammar for the parser can use 241the ParserState structure to hold whatever information is useful and 242appropriate. In the example, we note that the treeRoot field of 243the ParserState structure is left pointing to the root of the parse 244tree.</p> 245 246<p>The core of this example as it relates to Lemon is as follows:</p> 247<pre> 248 ParseFile(){ 249 pParser = ParseAlloc( malloc ); 250 while( GetNextToken(pTokenizer,&hTokenId, &sToken) ){ 251 Parse(pParser, hTokenId, sToken); 252 } 253 Parse(pParser, 0, sToken); 254 ParseFree(pParser, free ); 255 } 256</pre> 257<p>Basically, what a program has to do to use a Lemon-generated parser 258is first create the parser, then send it lots of tokens obtained by 259tokenizing an input source. When the end of input is reached, the 260Parse() routine should be called one last time with a token type 261of 0. This step is necessary to inform the parser that the end of 262input has been reached. Finally, we reclaim memory used by the 263parser by calling ParseFree().</p> 264 265<p>There is one other interface routine that should be mentioned 266before we move on. 267The ParseTrace() function can be used to generate debugging output 268from the parser. A prototype for this routine is as follows:</p> 269<pre> 270 ParseTrace(FILE *stream, char *zPrefix); 271</pre> 272<p>After this routine is called, a short (one-line) message is written 273to the designated output stream every time the parser changes states 274or calls an action routine. Each such message is prefaced using 275the text given by zPrefix. This debugging output can be turned off 276by calling ParseTrace() again with a first argument of NULL (0).</p> 277 278<h3>Differences With YACC and BISON</h3> 279 280<p>Programmers who have previously used the yacc or bison parser 281generator will notice several important differences between yacc and/or 282bison and Lemon.</p> 283<ul> 284<li>In yacc and bison, the parser calls the tokenizer. In Lemon, 285 the tokenizer calls the parser. 286<li>Lemon uses no global variables. Yacc and bison use global variables 287 to pass information between the tokenizer and parser. 288<li>Lemon allows multiple parsers to be running simultaneously. Yacc 289 and bison do not. 290</ul> 291<p>These differences may cause some initial confusion for programmers 292with prior yacc and bison experience. 293But after years of experience using Lemon, I firmly 294believe that the Lemon way of doing things is better.</p> 295 296<p><i>Updated as of 2016-02-16:</i> 297The text above was written in the 1990s. 298We are told that Bison has lately been enhanced to support the 299tokenizer-calls-parser paradigm used by Lemon, and to obviate the 300need for global variables.</p> 301 302<h2>Input File Syntax</h2> 303 304<p>The main purpose of the grammar specification file for Lemon is 305to define the grammar for the parser. But the input file also 306specifies additional information Lemon requires to do its job. 307Most of the work in using Lemon is in writing an appropriate 308grammar file.</p> 309 310<p>The grammar file for Lemon is, for the most part, a free format. 311It does not have sections or divisions like yacc or bison. Any 312declaration can occur at any point in the file. Lemon ignores 313whitespace (except where it is needed to separate tokens), and it 314honors the same commenting conventions as C and C++.</p> 315 316<h3>Terminals and Nonterminals</h3> 317 318<p>A terminal symbol (token) is any string of alphanumeric 319and/or underscore characters 320that begins with an uppercase letter. 321A terminal can contain lowercase letters after the first character, 322but the usual convention is to make terminals all uppercase. 323A nonterminal, on the other hand, is any string of alphanumeric 324and underscore characters than begins with a lowercase letter. 325Again, the usual convention is to make nonterminals use all lowercase 326letters.</p> 327 328<p>In Lemon, terminal and nonterminal symbols do not need to 329be declared or identified in a separate section of the grammar file. 330Lemon is able to generate a list of all terminals and nonterminals 331by examining the grammar rules, and it can always distinguish a 332terminal from a nonterminal by checking the case of the first 333character of the name.</p> 334 335<p>Yacc and bison allow terminal symbols to have either alphanumeric 336names or to be individual characters included in single quotes, like 337this: ')' or '$'. Lemon does not allow this alternative form for 338terminal symbols. With Lemon, all symbols, terminals and nonterminals, 339must have alphanumeric names.</p> 340 341<h3>Grammar Rules</h3> 342 343<p>The main component of a Lemon grammar file is a sequence of grammar 344rules. 345Each grammar rule consists of a nonterminal symbol followed by 346the special symbol "::=" and then a list of terminals and/or nonterminals. 347The rule is terminated by a period. 348The list of terminals and nonterminals on the right-hand side of the 349rule can be empty. 350Rules can occur in any order, except that the left-hand side of the 351first rule is assumed to be the start symbol for the grammar (unless 352specified otherwise using the <tt><a href='#start_symbol'>%start_symbol</a></tt> 353directive described below.) 354A typical sequence of grammar rules might look something like this:</p> 355<pre> 356 expr ::= expr PLUS expr. 357 expr ::= expr TIMES expr. 358 expr ::= LPAREN expr RPAREN. 359 expr ::= VALUE. 360</pre> 361 362<p>There is one non-terminal in this example, "expr", and five 363terminal symbols or tokens: "PLUS", "TIMES", "LPAREN", 364"RPAREN" and "VALUE".</p> 365 366<p>Like yacc and bison, Lemon allows the grammar to specify a block 367of C code that will be executed whenever a grammar rule is reduced 368by the parser. 369In Lemon, this action is specified by putting the C code (contained 370within curly braces <tt>{...}</tt>) immediately after the 371period that closes the rule. 372For example:</p> 373<pre> 374 expr ::= expr PLUS expr. { printf("Doing an addition...\n"); } 375</pre> 376 377<p>In order to be useful, grammar actions must normally be linked to 378their associated grammar rules. 379In yacc and bison, this is accomplished by embedding a "$$" in the 380action to stand for the value of the left-hand side of the rule and 381symbols "$1", "$2", and so forth to stand for the value of 382the terminal or nonterminal at position 1, 2 and so forth on the 383right-hand side of the rule. 384This idea is very powerful, but it is also very error-prone. The 385single most common source of errors in a yacc or bison grammar is 386to miscount the number of symbols on the right-hand side of a grammar 387rule and say "$7" when you really mean "$8".</p> 388 389<p>Lemon avoids the need to count grammar symbols by assigning symbolic 390names to each symbol in a grammar rule and then using those symbolic 391names in the action. 392In yacc or bison, one would write this:</p> 393<pre> 394 expr -> expr PLUS expr { $$ = $1 + $3; }; 395</pre> 396<p>But in Lemon, the same rule becomes the following:</p> 397<pre> 398 expr(A) ::= expr(B) PLUS expr(C). { A = B+C; } 399</pre> 400<p>In the Lemon rule, any symbol in parentheses after a grammar rule 401symbol becomes a place holder for that symbol in the grammar rule. 402This place holder can then be used in the associated C action to 403stand for the value of that symbol.</p> 404 405<p>The Lemon notation for linking a grammar rule with its reduce 406action is superior to yacc/bison on several counts. 407First, as mentioned above, the Lemon method avoids the need to 408count grammar symbols. 409Secondly, if a terminal or nonterminal in a Lemon grammar rule 410includes a linking symbol in parentheses but that linking symbol 411is not actually used in the reduce action, then an error message 412is generated. 413For example, the rule</p> 414<pre> 415 expr(A) ::= expr(B) PLUS expr(C). { A = B; } 416</pre> 417<p>will generate an error because the linking symbol "C" is used 418in the grammar rule but not in the reduce action.</p> 419 420<p>The Lemon notation for linking grammar rules to reduce actions 421also facilitates the use of destructors for reclaiming memory 422allocated by the values of terminals and nonterminals on the 423right-hand side of a rule.</p> 424 425<a id='precrules'></a> 426<h3>Precedence Rules</h3> 427 428<p>Lemon resolves parsing ambiguities in exactly the same way as 429yacc and bison. A shift-reduce conflict is resolved in favor 430of the shift, and a reduce-reduce conflict is resolved by reducing 431whichever rule comes first in the grammar file.</p> 432 433<p>Just like in 434yacc and bison, Lemon allows a measure of control 435over the resolution of parsing conflicts using precedence rules. 436A precedence value can be assigned to any terminal symbol 437using the 438<tt><a href='#pleft'>%left</a></tt>, 439<tt><a href='#pright'>%right</a></tt> or 440<tt><a href='#pnonassoc'>%nonassoc</a></tt> directives. Terminal symbols 441mentioned in earlier directives have a lower precedence than 442terminal symbols mentioned in later directives. For example:</p> 443 444<pre> 445 %left AND. 446 %left OR. 447 %nonassoc EQ NE GT GE LT LE. 448 %left PLUS MINUS. 449 %left TIMES DIVIDE MOD. 450 %right EXP NOT. 451</pre> 452 453<p>In the preceding sequence of directives, the AND operator is 454defined to have the lowest precedence. The OR operator is one 455precedence level higher. And so forth. Hence, the grammar would 456attempt to group the ambiguous expression</p> 457<pre> 458 a AND b OR c 459</pre> 460<p>like this</p> 461<pre> 462 a AND (b OR c). 463</pre> 464<p>The associativity (left, right or nonassoc) is used to determine 465the grouping when the precedence is the same. AND is left-associative 466in our example, so</p> 467<pre> 468 a AND b AND c 469</pre> 470<p>is parsed like this</p> 471<pre> 472 (a AND b) AND c. 473</pre> 474<p>The EXP operator is right-associative, though, so</p> 475<pre> 476 a EXP b EXP c 477</pre> 478<p>is parsed like this</p> 479<pre> 480 a EXP (b EXP c). 481</pre> 482<p>The nonassoc precedence is used for non-associative operators. 483So</p> 484<pre> 485 a EQ b EQ c 486</pre> 487<p>is an error.</p> 488 489<p>The precedence of non-terminals is transferred to rules as follows: 490The precedence of a grammar rule is equal to the precedence of the 491left-most terminal symbol in the rule for which a precedence is 492defined. This is normally what you want, but in those cases where 493you want the precedence of a grammar rule to be something different, 494you can specify an alternative precedence symbol by putting the 495symbol in square braces after the period at the end of the rule and 496before any C-code. For example:</p> 497 498<pre> 499 expr = MINUS expr. [NOT] 500</pre> 501 502<p>This rule has a precedence equal to that of the NOT symbol, not the 503MINUS symbol as would have been the case by default.</p> 504 505<p>With the knowledge of how precedence is assigned to terminal 506symbols and individual 507grammar rules, we can now explain precisely how parsing conflicts 508are resolved in Lemon. Shift-reduce conflicts are resolved 509as follows:</p> 510<ul> 511<li> If either the token to be shifted or the rule to be reduced 512 lacks precedence information, then resolve in favor of the 513 shift, but report a parsing conflict. 514<li> If the precedence of the token to be shifted is greater than 515 the precedence of the rule to reduce, then resolve in favor 516 of the shift. No parsing conflict is reported. 517<li> If the precedence of the token to be shifted is less than the 518 precedence of the rule to reduce, then resolve in favor of the 519 reduce action. No parsing conflict is reported. 520<li> If the precedences are the same and the shift token is 521 right-associative, then resolve in favor of the shift. 522 No parsing conflict is reported. 523<li> If the precedences are the same and the shift token is 524 left-associative, then resolve in favor of the reduce. 525 No parsing conflict is reported. 526<li> Otherwise, resolve the conflict by doing the shift, and 527 report a parsing conflict. 528</ul> 529<p>Reduce-reduce conflicts are resolved this way:</p> 530<ul> 531<li> If either reduce rule 532 lacks precedence information, then resolve in favor of the 533 rule that appears first in the grammar, and report a parsing 534 conflict. 535<li> If both rules have precedence and the precedence is different, 536 then resolve the dispute in favor of the rule with the highest 537 precedence, and do not report a conflict. 538<li> Otherwise, resolve the conflict by reducing by the rule that 539 appears first in the grammar, and report a parsing conflict. 540</ul> 541 542<h3>Special Directives</h3> 543 544<p>The input grammar to Lemon consists of grammar rules and special 545directives. We've described all the grammar rules, so now we'll 546talk about the special directives.</p> 547 548<p>Directives in Lemon can occur in any order. You can put them before 549the grammar rules, or after the grammar rules, or in the midst of the 550grammar rules. It doesn't matter. The relative order of 551directives used to assign precedence to terminals is important, but 552other than that, the order of directives in Lemon is arbitrary.</p> 553 554<p>Lemon supports the following special directives:</p> 555<ul> 556<li><tt><a href='#pcode'>%code</a></tt> 557<li><tt><a href='#default_destructor'>%default_destructor</a></tt> 558<li><tt><a href='#default_type'>%default_type</a></tt> 559<li><tt><a href='#destructor'>%destructor</a></tt> 560<li><tt><a href='#pifdef'>%else</a></tt> 561<li><tt><a href='#pifdef'>%endif</a></tt> 562<li><tt><a href='#extraarg'>%extra_argument</a></tt> 563<li><tt><a href='#pfallback'>%fallback</a></tt> 564<li><tt><a href='#pifdef'>%if</a></tt> 565<li><tt><a href='#pifdef'>%ifdef</a></tt> 566<li><tt><a href='#pifdef'>%ifndef</a></tt> 567<li><tt><a href='#pinclude'>%include</a></tt> 568<li><tt><a href='#pleft'>%left</a></tt> 569<li><tt><a href='#pname'>%name</a></tt> 570<li><tt><a href='#pnonassoc'>%nonassoc</a></tt> 571<li><tt><a href='#parse_accept'>%parse_accept</a></tt> 572<li><tt><a href='#parse_failure'>%parse_failure</a></tt> 573<li><tt><a href='#pright'>%right</a></tt> 574<li><tt><a href='#stack_overflow'>%stack_overflow</a></tt> 575<li><tt><a href='#stack_size'>%stack_size</a></tt> 576<li><tt><a href='#start_symbol'>%start_symbol</a></tt> 577<li><tt><a href='#syntax_error'>%syntax_error</a></tt> 578<li><tt><a href='#token_class'>%token_class</a></tt> 579<li><tt><a href='#token_destructor'>%token_destructor</a></tt> 580<li><tt><a href='#token_prefix'>%token_prefix</a></tt> 581<li><tt><a href='#token_type'>%token_type</a></tt> 582<li><tt><a href='#ptype'>%type</a></tt> 583<li><tt><a href='#pwildcard'>%wildcard</a></tt> 584</ul> 585<p>Each of these directives will be described separately in the 586following sections:</p> 587 588<a id='pcode'></a> 589<h4>The <tt>%code</tt> directive</h4> 590 591<p>The <tt>%code</tt> directive is used to specify additional C code that 592is added to the end of the main output file. This is similar to 593the <tt><a href='#pinclude'>%include</a></tt> directive except that 594<tt>%include</tt> is inserted at the beginning of the main output file.</p> 595 596<p><tt>%code</tt> is typically used to include some action routines or perhaps 597a tokenizer or even the "main()" function 598as part of the output file.</p> 599 600<a id='default_destructor'></a> 601<h4>The <tt>%default_destructor</tt> directive</h4> 602 603<p>The <tt>%default_destructor</tt> directive specifies a destructor to 604use for non-terminals that do not have their own destructor 605specified by a separate <tt>%destructor</tt> directive. See the documentation 606on the <tt><a href='#destructor'>%destructor</a></tt> directive below for 607additional information.</p> 608 609<p>In some grammars, many different non-terminal symbols have the 610same data type and hence the same destructor. This directive is 611a convenient way to specify the same destructor for all those 612non-terminals using a single statement.</p> 613 614<a id='default_type'></a> 615<h4>The <tt>%default_type</tt> directive</h4> 616 617<p>The <tt>%default_type</tt> directive specifies the data type of non-terminal 618symbols that do not have their own data type defined using a separate 619<tt><a href='#ptype'>%type</a></tt> directive.</p> 620 621<a id='destructor'></a> 622<h4>The <tt>%destructor</tt> directive</h4> 623 624<p>The <tt>%destructor</tt> directive is used to specify a destructor for 625a non-terminal symbol. 626(See also the <tt><a href='#token_destructor'>%token_destructor</a></tt> 627directive which is used to specify a destructor for terminal symbols.)</p> 628 629<p>A non-terminal's destructor is called to dispose of the 630non-terminal's value whenever the non-terminal is popped from 631the stack. This includes all of the following circumstances:</p> 632<ul> 633<li> When a rule reduces and the value of a non-terminal on 634 the right-hand side is not linked to C code. 635<li> When the stack is popped during error processing. 636<li> When the ParseFree() function runs. 637</ul> 638<p>The destructor can do whatever it wants with the value of 639the non-terminal, but its design is to deallocate memory 640or other resources held by that non-terminal.</p> 641 642<p>Consider an example:</p> 643<pre> 644 %type nt {void*} 645 %destructor nt { free($$); } 646 nt(A) ::= ID NUM. { A = malloc( 100 ); } 647</pre> 648<p>This example is a bit contrived, but it serves to illustrate how 649destructors work. The example shows a non-terminal named 650"nt" that holds values of type "void*". When the rule for 651an "nt" reduces, it sets the value of the non-terminal to 652space obtained from malloc(). Later, when the nt non-terminal 653is popped from the stack, the destructor will fire and call 654free() on this malloced space, thus avoiding a memory leak. 655(Note that the symbol "$$" in the destructor code is replaced 656by the value of the non-terminal.)</p> 657 658<p>It is important to note that the value of a non-terminal is passed 659to the destructor whenever the non-terminal is removed from the 660stack, unless the non-terminal is used in a C-code action. If 661the non-terminal is used by C-code, then it is assumed that the 662C-code will take care of destroying it. 663More commonly, the value is used to build some 664larger structure, and we don't want to destroy it, which is why 665the destructor is not called in this circumstance.</p> 666 667<p>Destructors help avoid memory leaks by automatically freeing 668allocated objects when they go out of scope. 669To do the same using yacc or bison is much more difficult.</p> 670 671<a id='extraarg'></a> 672<h4>The <tt>%extra_argument</tt> directive</h4> 673 674<p>The <tt>%extra_argument</tt> directive instructs Lemon to add a 4th parameter 675to the parameter list of the Parse() function it generates. Lemon 676doesn't do anything itself with this extra argument, but it does 677make the argument available to C-code action routines, destructors, 678and so forth. For example, if the grammar file contains:</p> 679 680<pre> 681 %extra_argument { MyStruct *pAbc } 682</pre> 683 684<p>Then the Parse() function generated will have an 4th parameter 685of type "MyStruct*" and all action routines will have access to 686a variable named "pAbc" that is the value of the 4th parameter 687in the most recent call to Parse().</p> 688 689<p>The <tt>%extra_context</tt> directive works the same except that it 690is passed in on the ParseAlloc() or ParseInit() routines instead of 691on Parse().</p> 692 693<a id='extractx'></a> 694<h4>The <tt>%extra_context</tt> directive</h4> 695 696<p>The <tt>%extra_context</tt> directive instructs Lemon to add a 2nd parameter 697to the parameter list of the ParseAlloc() and ParseInit() functions. Lemon 698doesn't do anything itself with these extra argument, but it does 699store the value make it available to C-code action routines, destructors, 700and so forth. For example, if the grammar file contains:</p> 701 702<pre> 703 %extra_context { MyStruct *pAbc } 704</pre> 705 706<p>Then the ParseAlloc() and ParseInit() functions will have an 2nd parameter 707of type "MyStruct*" and all action routines will have access to 708a variable named "pAbc" that is the value of that 2nd parameter.</p> 709 710<p>The <tt>%extra_argument</tt> directive works the same except that it 711is passed in on the Parse() routine instead of on ParseAlloc()/ParseInit().</p> 712 713<a id='pfallback'></a> 714<h4>The <tt>%fallback</tt> directive</h4> 715 716<p>The <tt>%fallback</tt> directive specifies an alternative meaning for one 717or more tokens. The alternative meaning is tried if the original token 718would have generated a syntax error.</p> 719 720<p>The <tt>%fallback</tt> directive was added to support robust parsing of SQL 721syntax in <a href='https://www.sqlite.org/'>SQLite</a>. 722The SQL language contains a large assortment of keywords, each of which 723appears as a different token to the language parser. SQL contains so 724many keywords that it can be difficult for programmers to keep up with 725them all. Programmers will, therefore, sometimes mistakenly use an 726obscure language keyword for an identifier. The <tt>%fallback</tt> directive 727provides a mechanism to tell the parser: "If you are unable to parse 728this keyword, try treating it as an identifier instead."</p> 729 730<p>The syntax of <tt>%fallback</tt> is as follows:</p> 731 732<blockquote> 733<tt>%fallback</tt> <i>ID</i> <i>TOKEN...</i> <b>.</b> 734</blockquote></p> 735 736<p>In words, the <tt>%fallback</tt> directive is followed by a list of token 737names terminated by a period. 738The first token name is the fallback token — the 739token to which all the other tokens fall back to. The second and subsequent 740arguments are tokens which fall back to the token identified by the first 741argument.</p> 742 743<a id='pifdef'></a> 744<h4>The <tt>%if</tt> directive and its friends</h4> 745 746<p>The <tt>%if</tt>, <tt>%ifdef</tt>, <tt>%ifndef</tt>, <tt>%else</tt>, 747and <tt>%endif</tt> directives 748are similar to #if, #ifdef, #ifndef, #else, and #endif in the C-preprocessor, 749just not as general. 750Each of these directives must begin at the left margin. No whitespace 751is allowed between the "%" and the directive name.</p> 752 753<p>Grammar text in between "<tt>%ifdef MACRO</tt>" and the next nested 754"<tt>%endif</tt>" is 755ignored unless the "-DMACRO" command-line option is used. Grammar text 756betwen "<tt>%ifndef MACRO</tt>" and the next nested "<tt>%endif</tt>" is 757included except when the "-DMACRO" command-line option is used.<p> 758 759<p>The text in between "<tt>%if</tt> <i>CONDITIONAL</i>" and its 760corresponding <tt>%endif</tt> is included only if <i>CONDITIONAL</i> 761is true. The CONDITION is one or more macro names, optionally connected 762using the "||" and "&&" binary operators, the "!" unary operator, 763and grouped using balanced parentheses. Each term is true if the 764corresponding macro exists, and false if it does not exist.</p> 765 766<p>An optional "<tt>%else</tt>" directive can occur anywhere in between a 767<tt>%ifdef</tt>, <tt>%ifndef</tt>, or <tt>%if</tt> directive and 768its corresponding <tt>%endif</tt>.</p> 769 770<p>Note that the argument to <tt>%ifdef</tt> and <tt>%ifndef</tt> is 771intended to be a single preprocessor symbol name, not a general expression. 772Use the "<tt>%if</tt>" directive for general expressions.</p> 773 774<a id='pinclude'></a> 775<h4>The <tt>%include</tt> directive</h4> 776 777<p>The <tt>%include</tt> directive specifies C code that is included at the 778top of the generated parser. You can include any text you want — 779the Lemon parser generator copies it blindly. If you have multiple 780<tt>%include</tt> directives in your grammar file, their values are concatenated 781so that all <tt>%include</tt> code ultimately appears near the top of the 782generated parser, in the same order as it appeared in the grammar.</p> 783 784<p>The <tt>%include</tt> directive is very handy for getting some extra #include 785preprocessor statements at the beginning of the generated parser. 786For example:</p> 787 788<pre> 789 %include {#include <unistd.h>} 790</pre> 791 792<p>This might be needed, for example, if some of the C actions in the 793grammar call functions that are prototyped in unistd.h.</p> 794 795<p>Use the <tt><a href="#pcode">%code</a></tt> directive to add code to 796the end of the generated parser.</p> 797 798<a id='pleft'></a> 799<h4>The <tt>%left</tt> directive</h4> 800 801The <tt>%left</tt> directive is used (along with the 802<tt><a href='#pright'>%right</a></tt> and 803<tt><a href='#pnonassoc'>%nonassoc</a></tt> directives) to declare 804precedences of terminal symbols. 805Every terminal symbol whose name appears after 806a <tt>%left</tt> directive but before the next period (".") is 807given the same left-associative precedence value. Subsequent 808<tt>%left</tt> directives have higher precedence. For example:</p> 809 810<pre> 811 %left AND. 812 %left OR. 813 %nonassoc EQ NE GT GE LT LE. 814 %left PLUS MINUS. 815 %left TIMES DIVIDE MOD. 816 %right EXP NOT. 817</pre> 818 819<p>Note the period that terminates each <tt>%left</tt>, 820<tt>%right</tt> or <tt>%nonassoc</tt> 821directive.</p> 822 823<p>LALR(1) grammars can get into a situation where they require 824a large amount of stack space if you make heavy use or right-associative 825operators. For this reason, it is recommended that you use <tt>%left</tt> 826rather than <tt>%right</tt> whenever possible.</p> 827 828<a id='pname'></a> 829<h4>The <tt>%name</tt> directive</h4> 830 831<p>By default, the functions generated by Lemon all begin with the 832five-character string "Parse". You can change this string to something 833different using the <tt>%name</tt> directive. For instance:</p> 834 835<pre> 836 %name Abcde 837</pre> 838 839<p>Putting this directive in the grammar file will cause Lemon to generate 840functions named</p> 841<ul> 842<li> AbcdeAlloc(), 843<li> AbcdeFree(), 844<li> AbcdeTrace(), and 845<li> Abcde(). 846</ul> 847</p>The <tt>%name</tt> directive allows you to generate two or more different 848parsers and link them all into the same executable.</p> 849 850<a id='pnonassoc'></a> 851<h4>The <tt>%nonassoc</tt> directive</h4> 852 853<p>This directive is used to assign non-associative precedence to 854one or more terminal symbols. See the section on 855<a href='#precrules'>precedence rules</a> 856or on the <tt><a href='#pleft'>%left</a></tt> directive 857for additional information.</p> 858 859<a id='parse_accept'></a> 860<h4>The <tt>%parse_accept</tt> directive</h4> 861 862<p>The <tt>%parse_accept</tt> directive specifies a block of C code that is 863executed whenever the parser accepts its input string. To "accept" 864an input string means that the parser was able to process all tokens 865without error.</p> 866 867<p>For example:</p> 868 869<pre> 870 %parse_accept { 871 printf("parsing complete!\n"); 872 } 873</pre> 874 875<a id='parse_failure'></a> 876<h4>The <tt>%parse_failure</tt> directive</h4> 877 878<p>The <tt>%parse_failure</tt> directive specifies a block of C code that 879is executed whenever the parser fails complete. This code is not 880executed until the parser has tried and failed to resolve an input 881error using is usual error recovery strategy. The routine is 882only invoked when parsing is unable to continue.</p> 883 884<pre> 885 %parse_failure { 886 fprintf(stderr,"Giving up. Parser is hopelessly lost...\n"); 887 } 888</pre> 889 890<a id='pright'></a> 891<h4>The <tt>%right</tt> directive</h4> 892 893<p>This directive is used to assign right-associative precedence to 894one or more terminal symbols. See the section on 895<a href='#precrules'>precedence rules</a> 896or on the <a href='#pleft'>%left</a> directive for additional information.</p> 897 898<a id='stack_overflow'></a> 899<h4>The <tt>%stack_overflow</tt> directive</h4> 900 901<p>The <tt>%stack_overflow</tt> directive specifies a block of C code that 902is executed if the parser's internal stack ever overflows. Typically 903this just prints an error message. After a stack overflow, the parser 904will be unable to continue and must be reset.</p> 905 906<pre> 907 %stack_overflow { 908 fprintf(stderr,"Giving up. Parser stack overflow\n"); 909 } 910</pre> 911 912<p>You can help prevent parser stack overflows by avoiding the use 913of right recursion and right-precedence operators in your grammar. 914Use left recursion and and left-precedence operators instead to 915encourage rules to reduce sooner and keep the stack size down. 916For example, do rules like this:</p> 917<pre> 918 list ::= list element. // left-recursion. Good! 919 list ::= . 920</pre> 921<p>Not like this:</p> 922<pre> 923 list ::= element list. // right-recursion. Bad! 924 list ::= . 925</pre> 926 927<a id='stack_size'></a> 928<h4>The <tt>%stack_size</tt> directive</h4> 929 930<p>If stack overflow is a problem and you can't resolve the trouble 931by using left-recursion, then you might want to increase the size 932of the parser's stack using this directive. Put an positive integer 933after the <tt>%stack_size</tt> directive and Lemon will generate a parse 934with a stack of the requested size. The default value is 100.</p> 935 936<pre> 937 %stack_size 2000 938</pre> 939 940<a id='start_symbol'></a> 941<h4>The <tt>%start_symbol</tt> directive</h4> 942 943<p>By default, the start symbol for the grammar that Lemon generates 944is the first non-terminal that appears in the grammar file. But you 945can choose a different start symbol using the 946<tt>%start_symbol</tt> directive.</p> 947 948<pre> 949 %start_symbol prog 950</pre> 951 952<a id='syntax_error'></a> 953<h4>The <tt>%syntax_error</tt> directive</h4> 954 955<p>See <a href='#error_processing'>Error Processing</a>.</p> 956 957<a id='token_class'></a> 958<h4>The <tt>%token_class</tt> directive</h4> 959 960<p>Undocumented. Appears to be related to the MULTITERMINAL concept. 961<a href='http://sqlite.org/src/fdiff?v1=796930d5fc2036c7&v2=624b24c5dc048e09&sbs=0'>Implementation</a>.</p> 962 963<a id='token_destructor'></a> 964<h4>The <tt>%token_destructor</tt> directive</h4> 965 966<p>The <tt>%destructor</tt> directive assigns a destructor to a non-terminal 967symbol. (See the description of the 968<tt><a href='%destructor'>%destructor</a></tt> directive above.) 969The <tt>%token_destructor</tt> directive does the same thing 970for all terminal symbols.</p> 971 972<p>Unlike non-terminal symbols, which may each have a different data type 973for their values, terminals all use the same data type (defined by 974the <tt><a href='#token_type'>%token_type</a></tt> directive) 975and so they use a common destructor. 976Other than that, the token destructor works just like the non-terminal 977destructors.</p> 978 979<a id='token_prefix'></a> 980<h4>The <tt>%token_prefix</tt> directive</h4> 981 982<p>Lemon generates #defines that assign small integer constants 983to each terminal symbol in the grammar. If desired, Lemon will 984add a prefix specified by this directive 985to each of the #defines it generates.</p> 986 987<p>So if the default output of Lemon looked like this:</p> 988<pre> 989 #define AND 1 990 #define MINUS 2 991 #define OR 3 992 #define PLUS 4 993</pre> 994<p>You can insert a statement into the grammar like this:</p> 995<pre> 996 %token_prefix TOKEN_ 997</pre> 998<p>to cause Lemon to produce these symbols instead:</p> 999<pre> 1000 #define TOKEN_AND 1 1001 #define TOKEN_MINUS 2 1002 #define TOKEN_OR 3 1003 #define TOKEN_PLUS 4 1004</pre> 1005 1006<a id='token_type'></a><a id='ptype'></a> 1007<h4>The <tt>%token_type</tt> and <tt>%type</tt> directives</h4> 1008 1009<p>These directives are used to specify the data types for values 1010on the parser's stack associated with terminal and non-terminal 1011symbols. The values of all terminal symbols must be of the same 1012type. This turns out to be the same data type as the 3rd parameter 1013to the Parse() function generated by Lemon. Typically, you will 1014make the value of a terminal symbol be a pointer to some kind of 1015token structure. Like this:</p> 1016 1017<pre> 1018 %token_type {Token*} 1019</pre> 1020 1021<p>If the data type of terminals is not specified, the default value 1022is "void*".</p> 1023 1024<p>Non-terminal symbols can each have their own data types. Typically 1025the data type of a non-terminal is a pointer to the root of a parse tree 1026structure that contains all information about that non-terminal. 1027For example:</p> 1028 1029<pre> 1030 %type expr {Expr*} 1031</pre> 1032 1033<p>Each entry on the parser's stack is actually a union containing 1034instances of all data types for every non-terminal and terminal symbol. 1035Lemon will automatically use the correct element of this union depending 1036on what the corresponding non-terminal or terminal symbol is. But 1037the grammar designer should keep in mind that the size of the union 1038will be the size of its largest element. So if you have a single 1039non-terminal whose data type requires 1K of storage, then your 100 1040entry parser stack will require 100K of heap space. If you are willing 1041and able to pay that price, fine. You just need to know.</p> 1042 1043<a id='pwildcard'></a> 1044<h4>The <tt>%wildcard</tt> directive</h4> 1045 1046<p>The <tt>%wildcard</tt> directive is followed by a single token name and a 1047period. This directive specifies that the identified token should 1048match any input token.</p> 1049 1050<p>When the generated parser has the choice of matching an input against 1051the wildcard token and some other token, the other token is always used. 1052The wildcard token is only matched if there are no alternatives.</p> 1053 1054<a id='error_processing'></a> 1055<h3>Error Processing</h3> 1056 1057<p>After extensive experimentation over several years, it has been 1058discovered that the error recovery strategy used by yacc is about 1059as good as it gets. And so that is what Lemon uses.</p> 1060 1061<p>When a Lemon-generated parser encounters a syntax error, it 1062first invokes the code specified by the <tt>%syntax_error</tt> directive, if 1063any. It then enters its error recovery strategy. The error recovery 1064strategy is to begin popping the parsers stack until it enters a 1065state where it is permitted to shift a special non-terminal symbol 1066named "error". It then shifts this non-terminal and continues 1067parsing. The <tt>%syntax_error</tt> routine will not be called again 1068until at least three new tokens have been successfully shifted.</p> 1069 1070<p>If the parser pops its stack until the stack is empty, and it still 1071is unable to shift the error symbol, then the 1072<tt><a href='#parse_failure'>%parse_failure</a></tt> routine 1073is invoked and the parser resets itself to its start state, ready 1074to begin parsing a new file. This is what will happen at the very 1075first syntax error, of course, if there are no instances of the 1076"error" non-terminal in your grammar.</p> 1077 1078</body> 1079</html> 1080