Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/doc/lemon.html # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / doc / lemon.html` 1361 lines ยท 54293 bytes Raw Blame History 1 2 3 The Lemon Parser Generator 4 5 6 7

The Lemon Parser Generator

8 9

Lemon is an LALR(1) parser generator for C. 10 It does the same job as "bison" and "yacc". 11 But Lemon is not a bison or yacc clone. Lemon 12 uses a different grammar syntax which is designed to 13 reduce the number of coding errors. Lemon also uses a 14 parsing engine that is faster than yacc and 15 bison and which is both reentrant and threadsafe. 16 (Update: Since the previous sentence was written, bison 17 has also been updated so that it too can generate a 18 reentrant and threadsafe parser.) 19 Lemon also implements features that can be used 20 to eliminate resource leaks, making it suitable for use 21 in long-running programs such as graphical user interfaces 22 or embedded controllers.

23 24

This document is an introduction to the Lemon 25 parser generator.

26 27 28

1.0 Table of Contents

29 55 56 57

2.0 Security Note

58 59

The language parser code created by Lemon is very robust and 60 is well-suited for use in internet-facing applications that need to 61 safely process maliciously crafted inputs.

62 63

The "lemon.exe" command-line tool itself works great when given a valid 64 input grammar file and almost always gives helpful 65 error messages for malformed inputs. However, it is possible for 66 a malicious user to craft a grammar file that will cause 67 lemon.exe to crash. 68 We do not see this as a problem, as lemon.exe is not intended to be used 69 with hostile inputs. 70 To summarize:

71 72 76 77 78

3.0 Theory of Operation

79 80

Lemon is computer program that translates a context free grammar (CFG) 81 for a particular language into C code that implements a parser for 82 that language. 83 The Lemon program has two inputs:

84 88

Typically, only the grammar specification is supplied by the programmer. 89 Lemon comes with a default parser template 90 ("lempar.c") 91 that works fine for most applications. But the user is free to substitute 92 a different parser template if desired.

93 94

Depending on command-line options, Lemon will generate up to 95 three output files.

96 103

By default, all three of these output files are generated. 104 The header file is suppressed if the "-m" command-line option is 105 used and the report file is omitted when "-q" is selected.

106 107

The grammar specification file uses a ".y" suffix, by convention. 108 In the examples used in this document, we'll assume the name of the 109 grammar file is "gram.y". A typical use of Lemon would be the 110 following command:

111

112 lemon gram.y

113 
114

This command will generate three output files named "gram.c", 115 "gram.h" and "gram.out". 116 The first is C code to implement the parser. The second 117 is the header file that defines numerical values for all 118 terminal symbols, and the last is the report that explains 119 the states used by the parser automaton.

120 121 122

3.1 Command Line Options

123 124

The behavior of Lemon can be modified using command-line options. 125 You can obtain a list of the available command-line options together 126 with a brief explanation of what each does by typing

127

128 lemon "-?"

129 
130

As of this writing, the following command-line options are supported:

131 172 173 174

3.2 The Parser Interface

175 176

Lemon doesn't generate a complete, working program. It only generates 177 a few subroutines that implement a parser. This section describes 178 the interface to those subroutines. It is up to the programmer to 179 call these subroutines in an appropriate way in order to produce a 180 complete system.

181 182

Before a program begins using a Lemon-generated parser, the program 183 must first create the parser. 184 A new parser is created as follows:

185

186 void *pParser = ParseAlloc( malloc );

187 
188

The ParseAlloc() routine allocates and initializes a new parser and 189 returns a pointer to it. 190 The actual data structure used to represent a parser is opaque — 191 its internal structure is not visible or usable by the calling routine. 192 For this reason, the ParseAlloc() routine returns a pointer to void 193 rather than a pointer to some particular structure. 194 The sole argument to the ParseAlloc() routine is a pointer to the 195 subroutine used to allocate memory. Typically this means malloc().

196 197

After a program is finished using a parser, it can reclaim all 198 memory allocated by that parser by calling

199

200 ParseFree(pParser, free);

201 
202

The first argument is the same pointer returned by ParseAlloc(). The 203 second argument is a pointer to the function used to release bulk 204 memory back to the system.

205 206

After a parser has been allocated using ParseAlloc(), the programmer 207 must supply the parser with a sequence of tokens (terminal symbols) to 208 be parsed. This is accomplished by calling the following function 209 once for each token:

210


211 Parse(pParser, hTokenID, sTokenData, pArg);

212 
213

The first argument to the Parse() routine is the pointer returned by 214 ParseAlloc(). 215 The second argument is a small positive integer that tells the parser the 216 type of the next token in the data stream. 217 There is one token type for each terminal symbol in the grammar. 218 The gram.h file generated by Lemon contains #define statements that 219 map symbolic terminal symbol names into appropriate integer values. 220 A value of 0 for the second argument is a special flag to the 221 parser to indicate that the end of input has been reached. 222 The third argument is the value of the given token. By default, 223 the type of the third argument is "void*", but the grammar will 224 usually redefine this type to be some kind of structure. 225 Typically the second argument will be a broad category of tokens 226 such as "identifier" or "number" and the third argument will 227 be the name of the identifier or the value of the number.

228 229

The Parse() function may have either three or four arguments, 230 depending on the grammar. If the grammar specification file requests 231 it (via the %extra_argument directive), 232 the Parse() function will have a fourth parameter that can be 233 of any type chosen by the programmer. The parser doesn't do anything 234 with this argument except to pass it through to action routines. 235 This is a convenient mechanism for passing state information down 236 to the action routines without having to use global variables.

237 238

A typical use of a Lemon parser might look something like the 239 following:

240

241 1 ParseTree *ParseFile(const char *zFilename){

242 2 Tokenizer *pTokenizer;

243 3 void *pParser;

244 4 Token sToken;

245 5 int hTokenId;

246 6 ParserState sState;

247 7

248 8 pTokenizer = TokenizerCreate(zFilename);

249 9 pParser = ParseAlloc( malloc );

250 10 InitParserState(&sState);

251 11 while( GetNextToken(pTokenizer, &hTokenId, &sToken) ){

252 12 Parse(pParser, hTokenId, sToken, &sState);

253 13 }

254 14 Parse(pParser, 0, sToken, &sState);

255 15 ParseFree(pParser, free );

256 16 TokenizerFree(pTokenizer);

257 17 return sState.treeRoot;

258 18 }

259 
260

This example shows a user-written routine that parses a file of 261 text and returns a pointer to the parse tree. 262 (All error-handling code is omitted from this example to keep it 263 simple.) 264 We assume the existence of some kind of tokenizer which is created 265 using TokenizerCreate() on line 8 and deleted by TokenizerFree() 266 on line 16. The GetNextToken() function on line 11 retrieves the 267 next token from the input file and puts its type in the 268 integer variable hTokenId. The sToken variable is assumed to be 269 some kind of structure that contains details about each token, 270 such as its complete text, what line it occurs on, etc.

271 272

This example also assumes the existence of a structure of type 273 ParserState that holds state information about a particular parse. 274 An instance of such a structure is created on line 6 and initialized 275 on line 10. A pointer to this structure is passed into the Parse() 276 routine as the optional 4th argument. 277 The action routine specified by the grammar for the parser can use 278 the ParserState structure to hold whatever information is useful and 279 appropriate. In the example, we note that the treeRoot field of 280 the ParserState structure is left pointing to the root of the parse 281 tree.

282 283

The core of this example as it relates to Lemon is as follows:

284

285 ParseFile(){

286 pParser = ParseAlloc( malloc );

287 while( GetNextToken(pTokenizer,&hTokenId, &sToken) ){

288 Parse(pParser, hTokenId, sToken);

289 }

290 Parse(pParser, 0, sToken);

291 ParseFree(pParser, free );

292 }

293 
294

Basically, what a program has to do to use a Lemon-generated parser 295 is first create the parser, then send it lots of tokens obtained by 296 tokenizing an input source. When the end of input is reached, the 297 Parse() routine should be called one last time with a token type 298 of 0. This step is necessary to inform the parser that the end of 299 input has been reached. Finally, we reclaim memory used by the 300 parser by calling ParseFree().

301 302

There is one other interface routine that should be mentioned 303 before we move on. 304 The ParseTrace() function can be used to generate debugging output 305 from the parser. A prototype for this routine is as follows:

306

307 ParseTrace(FILE *stream, char *zPrefix);

308 
309

After this routine is called, a short (one-line) message is written 310 to the designated output stream every time the parser changes states 311 or calls an action routine. Each such message is prefaced using 312 the text given by zPrefix. This debugging output can be turned off 313 by calling ParseTrace() again with a first argument of NULL (0).

314 315 316

3.2.1 Allocating The Parse Object On Stack

317 318

If all calls to the Parse() interface are made from within 319 %code directives, then the parse 320 object can be allocated from the stack rather than from the heap. 321 These are the steps: 322 323

329 330

The following code illustrates how this is done: 331 332


333 ParseFile(){

334 yyParser x;

335 ParseInit( &x );

336 while( GetNextToken(pTokenizer,&hTokenId, &sToken) ){

337 Parse(&x, hTokenId, sToken);

338 }

339 Parse(&x, 0, sToken);

340 ParseFinalize( &x );

341 }

342 
343 344 345

3.2.2 Interface Summary

346 347

Here is a quick overview of the C-language interface to a 348 Lemon-generated parser:

349 350

351 void *ParseAlloc( (void*(*malloc)(size_t) );

352 void ParseFree(void *pParser, (void(*free)(void*) );

353 void Parse(void *pParser, int tokenCode, ParseTOKENTYPE token, ...);

354 void ParseTrace(FILE *stream, char *zPrefix);

355 
356 357

Notes:

358 367 368 369

3.3 Differences With YACC and BISON

370 371

Programmers who have previously used the yacc or bison parser 372 generator will notice several important differences between yacc and/or 373 bison and Lemon.

374 382

These differences may cause some initial confusion for programmers 383 with prior yacc and bison experience. 384 But after years of experience using Lemon, I firmly 385 believe that the Lemon way of doing things is better.

386 387

Updated as of 2016-02-16: 388 The text above was written in the 1990s. 389 We are told that Bison has lately been enhanced to support the 390 tokenizer-calls-parser paradigm used by Lemon, eliminating the 391 need for global variables.

392 393 394

3.4 Building The "lemon" or "lemon.exe" Executable

395 396

The "lemon" or "lemon.exe" program is built from a single file 397 of C-code named 398 "lemon.c". 399 The Lemon source code is generic C89 code that uses 400 no unusual or non-standard libraries. Any 401 reasonable C compiler should suffice to compile the lemon program. 402 A command-line like the following will usually work:

403 404

405 cc -o lemon lemon.c

406 
On Windows machines with Visual C++ installed, bring up a 409 "VS20NN x64 Native Tools Command Prompt" window and enter: 410 411

412 cl lemon.c

413 
414 415

Compiling Lemon really is that simple. 416 Additional compiler options such as 417 "-O2" or "-g" or "-Wall" can be added if desired, but they are not 418 necessary.

419 420 421 422

4.0 Input File Syntax

423 424

The main purpose of the grammar specification file for Lemon is 425 to define the grammar for the parser. But the input file also 426 specifies additional information Lemon requires to do its job. 427 Most of the work in using Lemon is in writing an appropriate 428 grammar file.

429 430

The grammar file for Lemon is, for the most part, a free format. 431 It does not have sections or divisions like yacc or bison. Any 432 declaration can occur at any point in the file. Lemon ignores 433 whitespace (except where it is needed to separate tokens), and it 434 honors the same commenting conventions as C and C++.

435 436 437

4.1 Terminals and Nonterminals

438 439

A terminal symbol (token) is any string of alphanumeric 440 and/or underscore characters 441 that begins with an uppercase letter. 442 A terminal can contain lowercase letters after the first character, 443 but the usual convention is to make terminals all uppercase. 444 A nonterminal, on the other hand, is any string of alphanumeric 445 and underscore characters than begins with a lowercase letter. 446 Again, the usual convention is to make nonterminals use all lowercase 447 letters.

448 449

In Lemon, terminal and nonterminal symbols do not need to 450 be declared or identified in a separate section of the grammar file. 451 Lemon is able to generate a list of all terminals and nonterminals 452 by examining the grammar rules, and it can always distinguish a 453 terminal from a nonterminal by checking the case of the first 454 character of the name.

455 456

Yacc and bison allow terminal symbols to have either alphanumeric 457 names or to be individual characters included in single quotes, like 458 this: ')' or '$'. Lemon does not allow this alternative form for 459 terminal symbols. With Lemon, all symbols, terminals and nonterminals, 460 must have alphanumeric names.

461 462 463

4.2 Grammar Rules

464 465

The main component of a Lemon grammar file is a sequence of grammar 466 rules. 467 Each grammar rule consists of a nonterminal symbol followed by 468 the special symbol "::=" and then a list of terminals and/or nonterminals. 469 The rule is terminated by a period. 470 The list of terminals and nonterminals on the right-hand side of the 471 rule can be empty. 472 Rules can occur in any order, except that the left-hand side of the 473 first rule is assumed to be the start symbol for the grammar (unless 474 specified otherwise using the %start_symbol 475 directive described below.) 476 A typical sequence of grammar rules might look something like this:

477

478 expr ::= expr PLUS expr.

479 expr ::= expr TIMES expr.

480 expr ::= LPAREN expr RPAREN.

481 expr ::= VALUE.

482 
483 484

There is one non-terminal in this example, "expr", and five 485 terminal symbols or tokens: "PLUS", "TIMES", "LPAREN", 486 "RPAREN" and "VALUE".

487 488

Like yacc and bison, Lemon allows the grammar to specify a block 489 of C code that will be executed whenever a grammar rule is reduced 490 by the parser. 491 In Lemon, this action is specified by putting the C code (contained 492 within curly braces {...}) immediately after the 493 period that closes the rule. 494 For example:

495

496 expr ::= expr PLUS expr. { printf("Doing an addition...\n"); }

497 
498 499

In order to be useful, grammar actions must normally be linked to 500 their associated grammar rules. 501 In yacc and bison, this is accomplished by embedding a "$$" in the 502 action to stand for the value of the left-hand side of the rule and 503 symbols "$1", "$2", and so forth to stand for the value of 504 the terminal or nonterminal at position 1, 2 and so forth on the 505 right-hand side of the rule. 506 This idea is very powerful, but it is also very error-prone. The 507 single most common source of errors in a yacc or bison grammar is 508 to miscount the number of symbols on the right-hand side of a grammar 509 rule and say "$7" when you really mean "$8".

510 511

Lemon avoids the need to count grammar symbols by assigning symbolic 512 names to each symbol in a grammar rule and then using those symbolic 513 names in the action. 514 In yacc or bison, one would write this:

515

516 expr -> expr PLUS expr { $$ = $1 + $3; };

517 
518

But in Lemon, the same rule becomes the following:

519

520 expr(A) ::= expr(B) PLUS expr(C). { A = B+C; }

521 
522

In the Lemon rule, any symbol in parentheses after a grammar rule 523 symbol becomes a place holder for that symbol in the grammar rule. 524 This place holder can then be used in the associated C action to 525 stand for the value of that symbol.

526 527

The Lemon notation for linking a grammar rule with its reduce 528 action is superior to yacc/bison on several counts. 529 First, as mentioned above, the Lemon method avoids the need to 530 count grammar symbols. 531 Secondly, if a terminal or nonterminal in a Lemon grammar rule 532 includes a linking symbol in parentheses but that linking symbol 533 is not actually used in the reduce action, then an error message 534 is generated. 535 For example, the rule

536

537 expr(A) ::= expr(B) PLUS expr(C). { A = B; }

538 
539

will generate an error because the linking symbol "C" is used 540 in the grammar rule but not in the reduce action.

541 542

The Lemon notation for linking grammar rules to reduce actions 543 also facilitates the use of destructors for reclaiming memory 544 allocated by the values of terminals and nonterminals on the 545 right-hand side of a rule.

546 547 548

4.3 Precedence Rules

549 550

Lemon resolves parsing ambiguities in exactly the same way as 551 yacc and bison. A shift-reduce conflict is resolved in favor 552 of the shift, and a reduce-reduce conflict is resolved by reducing 553 whichever rule comes first in the grammar file.

554 555

Just like in 556 yacc and bison, Lemon allows a measure of control 557 over the resolution of parsing conflicts using precedence rules. 558 A precedence value can be assigned to any terminal symbol 559 using the 560 %left, 561 %right or 562 %nonassoc directives. Terminal symbols 563 mentioned in earlier directives have a lower precedence than 564 terminal symbols mentioned in later directives. For example:

565 566

567 %left AND.

568 %left OR.

569 %nonassoc EQ NE GT GE LT LE.

570 %left PLUS MINUS.

571 %left TIMES DIVIDE MOD.

572 %right EXP NOT.

573 
574 575

In the preceding sequence of directives, the AND operator is 576 defined to have the lowest precedence. The OR operator is one 577 precedence level higher. And so forth. Hence, the grammar would 578 attempt to group the ambiguous expression

579

580 a AND b OR c

581 
582

like this

583

584 a AND (b OR c).

585 
586

The associativity (left, right or nonassoc) is used to determine 587 the grouping when the precedence is the same. AND is left-associative 588 in our example, so

589

590 a AND b AND c

591 
592

is parsed like this

593

594 (a AND b) AND c.

595 
596

The EXP operator is right-associative, though, so

597

598 a EXP b EXP c

599 
600

is parsed like this

601

602 a EXP (b EXP c).

603 
604

The nonassoc precedence is used for non-associative operators. 605 So

606

607 a EQ b EQ c

608 
609

is an error.

610 611

The precedence of non-terminals is transferred to rules as follows: 612 The precedence of a grammar rule is equal to the precedence of the 613 left-most terminal symbol in the rule for which a precedence is 614 defined. This is normally what you want, but in those cases where 615 you want the precedence of a grammar rule to be something different, 616 you can specify an alternative precedence symbol by putting the 617 symbol in square braces after the period at the end of the rule and 618 before any C-code. For example:

619 620

621 expr = MINUS expr. [NOT]

622 
623 624

This rule has a precedence equal to that of the NOT symbol, not the 625 MINUS symbol as would have been the case by default.

626 627

With the knowledge of how precedence is assigned to terminal 628 symbols and individual 629 grammar rules, we can now explain precisely how parsing conflicts 630 are resolved in Lemon. Shift-reduce conflicts are resolved 631 as follows:

632 651

Reduce-reduce conflicts are resolved this way:

652 663 664 665

4.4 Special Directives

666 667

The input grammar to Lemon consists of grammar rules and special 668 directives. We've described all the grammar rules, so now we'll 669 talk about the special directives.

670 671

Directives in Lemon can occur in any order. You can put them before 672 the grammar rules, or after the grammar rules, or in the midst of the 673 grammar rules. It doesn't matter. The relative order of 674 directives used to assign precedence to terminals is important, but 675 other than that, the order of directives in Lemon is arbitrary.

676 677

Lemon supports the following special directives:

678 712

Each of these directives will be described separately in the 713 following sections:

714 715 716

4.4.1 The %code directive

717 718

The %code directive is used to specify additional C code that 719 is added to the end of the main output file. This is similar to 720 the %include directive except that 721 %include is inserted at the beginning of the main output file.

722 723

%code is typically used to include some action routines or perhaps 724 a tokenizer or even the "main()" function 725 as part of the output file.

726 727

There can be multiple %code directives. The arguments of 728 all %code directives are concatenated.

729 730 731

4.4.2 The %default_destructor directive

732 733

The %default_destructor directive specifies a destructor to 734 use for non-terminals that do not have their own destructor 735 specified by a separate %destructor directive. See the documentation 736 on the %destructor directive below for 737 additional information.

738 739

In some grammars, many different non-terminal symbols have the 740 same data type and hence the same destructor. This directive is 741 a convenient way to specify the same destructor for all those 742 non-terminals using a single statement.

743 744 745

4.4.3 The %default_type directive

746 747

The %default_type directive specifies the data type of non-terminal 748 symbols that do not have their own data type defined using a separate 749 %type directive.

750 751 752

4.4.4 The %destructor directive

753 754

The %destructor directive is used to specify a destructor for 755 a non-terminal symbol. 756 (See also the %token_destructor 757 directive which is used to specify a destructor for terminal symbols.)

758 759

A non-terminal's destructor is called to dispose of the 760 non-terminal's value whenever the non-terminal is popped from 761 the stack. This includes all of the following circumstances:

762 768

The destructor can do whatever it wants with the value of 769 the non-terminal, but its design is to deallocate memory 770 or other resources held by that non-terminal.

771 772

Consider an example:

773

774 %type nt {void*}

775 %destructor nt { free($$); }

776 nt(A) ::= ID NUM. { A = malloc( 100 ); }

777 
778

This example is a bit contrived, but it serves to illustrate how 779 destructors work. The example shows a non-terminal named 780 "nt" that holds values of type "void*". When the rule for 781 an "nt" reduces, it sets the value of the non-terminal to 782 space obtained from malloc(). Later, when the nt non-terminal 783 is popped from the stack, the destructor will fire and call 784 free() on this malloced space, thus avoiding a memory leak. 785 (Note that the symbol "$$" in the destructor code is replaced 786 by the value of the non-terminal.)

787 788

It is important to note that the value of a non-terminal is passed 789 to the destructor whenever the non-terminal is removed from the 790 stack, unless the non-terminal is used in a C-code action. If 791 the non-terminal is used by C-code, then it is assumed that the 792 C-code will take care of destroying it. 793 More commonly, the value is used to build some 794 larger structure, and we don't want to destroy it, which is why 795 the destructor is not called in this circumstance.

796 797

Destructors help avoid memory leaks by automatically freeing 798 allocated objects when they go out of scope. 799 To do the same using yacc or bison is much more difficult.

800 801 802

4.4.5 The %extra_argument directive

803 804

The %extra_argument directive instructs Lemon to add a 4th parameter 805 to the parameter list of the Parse() function it generates. Lemon 806 doesn't do anything itself with this extra argument, but it does 807 make the argument available to C-code action routines, destructors, 808 and so forth. For example, if the grammar file contains:

809 810

811 %extra_argument { MyStruct *pAbc }

812 
813 814

Then the Parse() function generated will have an 4th parameter 815 of type "MyStruct*" and all action routines will have access to 816 a variable named "pAbc" that is the value of the 4th parameter 817 in the most recent call to Parse().

818 819

The %extra_context directive works the same except that it 820 is passed in on the ParseAlloc() or ParseInit() routines instead of 821 on Parse().

822 823 824

4.4.6 The %extra_context directive

825 826

The %extra_context directive instructs Lemon to add a 2nd parameter 827 to the parameter list of the ParseAlloc() and ParseInit() functions. Lemon 828 doesn't do anything itself with these extra argument, but it does 829 store the value make it available to C-code action routines, destructors, 830 and so forth. For example, if the grammar file contains:

831 832

833 %extra_context { MyStruct *pAbc }

834 
835 836

Then the ParseAlloc() and ParseInit() functions will have an 2nd parameter 837 of type "MyStruct*" and all action routines will have access to 838 a variable named "pAbc" that is the value of that 2nd parameter.

839 840

The %extra_argument directive works the same except that it 841 is passed in on the Parse() routine instead of on ParseAlloc()/ParseInit().

842 843 844

4.4.7 The %fallback directive

845 846

The %fallback directive specifies an alternative meaning for one 847 or more tokens. The alternative meaning is tried if the original token 848 would have generated a syntax error.

849 850

The %fallback directive was added to support robust parsing of SQL 851 syntax in SQLite. 852 The SQL language contains a large assortment of keywords, each of which 853 appears as a different token to the language parser. SQL contains so 854 many keywords that it can be difficult for programmers to keep up with 855 them all. Programmers will, therefore, sometimes mistakenly use an 856 obscure language keyword for an identifier. The %fallback directive 857 provides a mechanism to tell the parser: "If you are unable to parse 858 this keyword, try treating it as an identifier instead."

859 860

The syntax of %fallback is as follows:

861 862
863 %fallback ID TOKEN... . 864

865 866

In words, the %fallback directive is followed by a list of token 867 names terminated by a period. 868 The first token name is the fallback token — the 869 token to which all the other tokens fall back to. The second and subsequent 870 arguments are tokens which fall back to the token identified by the first 871 argument.

872 873

The %fallback mechanism should be thought of as an error-recovery 874 technique. The concept originated with SQLite and the need to maintain 875 backwards compatibility as new keywords were added to the SQL language dialect 876 understood by SQLite. For example, when SQLite was enhanced to support 877 window functions, it needed many new keywords including PARTITION, RANGE, and 878 UNBOUNDED. But what if there existed legacy database files that contained 879 tables or columns with those names? How would we continue to parse statements 880 like the following? 881 882


883 CREATE TABLE partition(range TEXT, unbounded BOOLEAN);

884 
885 886

This conundrum is resolved using a %fallback directive similar to: 887 888


889 %fallback ID PARTITION RANGE UNBOUNDED.

890 
891 892

According to the LALR grammar that defines the SQLite syntax, 893 the CREATE TABLE statement above is not syntactically correct 894 because of the use of those keywords. But the %fallback directive 895 instructs the parser to change the look-ahead token to ID if it encounters 896 a syntax error, and try using the ID token instead before giving up and 897 reporting an error. 898 899

As Sam Atman 900 observes on the SQLite Forum, it is possible to get goofy behavior 901 with %fallback. Used judiciously, %fallback can make 902 a parser simpler, faster and more robust. Misuse or overuse can lead 903 to ambiguities, however. 904 905 906

4.4.8 The %if directive and its friends

907 908

The %if, %ifdef, %ifndef, %else, 909 and %endif directives 910 are similar to #if, #ifdef, #ifndef, #else, and #endif in the C-preprocessor, 911 just not as general. 912 Each of these directives must begin at the left margin. No whitespace 913 is allowed between the "%" and the directive name.

914 915

Grammar text in between "%ifdef MACRO" and the next nested 916 "%endif" is 917 ignored unless the "-DMACRO" command-line option is used. Grammar text 918 between "%ifndef MACRO" and the next nested "%endif" is 919 included except when the "-DMACRO" command-line option is used.

920 921

The text in between "%if CONDITIONAL" and its 922 corresponding %endif is included only if CONDITIONAL 923 is true. The CONDITION is one or more macro names, optionally connected 924 using the "||" and "&&" binary operators, the "!" unary operator, 925 and grouped using balanced parentheses. Each term is true if the 926 corresponding macro exists, and false if it does not exist.

927 928

An optional "%else" directive can occur anywhere in between a 929 %ifdef, %ifndef, or %if directive and 930 its corresponding %endif.

931 932

Note that the argument to %ifdef and %ifndef is 933 intended to be a single preprocessor symbol name, not a general expression. 934 Use the "%if" directive for general expressions.

935 936 937

4.4.9 The %include directive

938 939

The %include directive specifies C code that is included at the 940 top of the generated parser. You can include any text you want — 941 the Lemon parser generator copies it blindly. If you have multiple 942 %include directives in your grammar file, their values are concatenated 943 so that all %include code ultimately appears near the top of the 944 generated parser, in the same order as it appeared in the grammar.

945 946

The %include directive is very handy for getting some extra #include 947 preprocessor statements at the beginning of the generated parser. 948 For example:

949 950

951 %include {#include <unistd.h>}

952 
953 954

This might be needed, for example, if some of the C actions in the 955 grammar call functions that are prototyped in unistd.h.

956 957

Use the %code directive to add code to 958 the end of the generated parser.

959 960 961

4.4.10 The %left directive

962 963 The %left directive is used (along with the 964 %right and 965 %nonassoc directives) to declare 966 precedences of terminal symbols. 967 Every terminal symbol whose name appears after 968 a %left directive but before the next period (".") is 969 given the same left-associative precedence value. Subsequent 970 %left directives have higher precedence. For example:

971 972

973 %left AND.

974 %left OR.

975 %nonassoc EQ NE GT GE LT LE.

976 %left PLUS MINUS.

977 %left TIMES DIVIDE MOD.

978 %right EXP NOT.

979 
980 981

Note the period that terminates each %left, 982 %right or %nonassoc 983 directive.

984 985

LALR(1) grammars can get into a situation where they require 986 a large amount of stack space if you make heavy use or right-associative 987 operators. For this reason, it is recommended that you use %left 988 rather than %right whenever possible.

989 990 991

4.4.11 The %name directive

992 993

By default, the functions generated by Lemon all begin with the 994 five-character string "Parse". You can change this string to something 995 different using the %name directive. For instance:

996 997

998 %name Abcde

999 
1000 1001

Putting this directive in the grammar file will cause Lemon to generate 1002 functions named

1003 1009

The %name directive allows you to generate two or more different 1010 parsers and link them all into the same executable.

1011 1012 1013

4.4.12 The %nonassoc directive

1014 1015

This directive is used to assign non-associative precedence to 1016 one or more terminal symbols. See the section on 1017 precedence rules 1018 or on the %left directive 1019 for additional information.

1020 1021 1022

4.4.13 The %parse_accept directive

1023 1024

The %parse_accept directive specifies a block of C code that is 1025 executed whenever the parser accepts its input string. To "accept" 1026 an input string means that the parser was able to process all tokens 1027 without error.

1028 1029

For example:

1030 1031

1032 %parse_accept {

1033 printf("parsing complete!\n");

1034 }

1035 
1036 1037 1038

4.4.14 The %parse_failure directive

1039 1040

The %parse_failure directive specifies a block of C code that 1041 is executed whenever the parser fails complete. This code is not 1042 executed until the parser has tried and failed to resolve an input 1043 error using is usual error recovery strategy. The routine is 1044 only invoked when parsing is unable to continue.

1045 1046

1047 %parse_failure {

1048 fprintf(stderr,"Giving up. Parser is hopelessly lost...\n");

1049 }

1050 
1051 1052 1053

4.4.15 The %right directive

1054 1055

This directive is used to assign right-associative precedence to 1056 one or more terminal symbols. See the section on 1057 precedence rules 1058 or on the %left directive for additional information.

1059 1060 1061

4.4.16 The %stack_overflow directive

1062 1063

The %stack_overflow directive specifies a block of C code that 1064 is executed if the parser's internal stack ever overflows. Typically 1065 this just prints an error message. After a stack overflow, the parser 1066 will be unable to continue and must be reset.

1067 1068

1069 %stack_overflow {

1070 fprintf(stderr,"Giving up. Parser stack overflow\n");

1071 }

1072 
1073 1074

You can help prevent parser stack overflows by avoiding the use 1075 of right recursion and right-precedence operators in your grammar. 1076 Use left recursion and and left-precedence operators instead to 1077 encourage rules to reduce sooner and keep the stack size down. 1078 For example, do rules like this:

1079

1080 list ::= list element. // left-recursion. Good!

1081 list ::= .

1082 
1083

Not like this:

1084

1085 list ::= element list. // right-recursion. Bad!

1086 list ::= .

1087 
1088 1089 1090

4.4.17 The %stack_size directive

1091 1092

If stack overflow is a problem and you can't resolve the trouble 1093 by using left-recursion, then you might want to increase the size 1094 of the parser's stack using this directive. Put an positive integer 1095 after the %stack_size directive and Lemon will generate a parse 1096 with a stack of the requested size. The default value is 100.

1097 1098

1099 %stack_size 2000

1100 
1101 1102 1103

4.4.18 The %start_symbol directive

1104 1105

By default, the start symbol for the grammar that Lemon generates 1106 is the first non-terminal that appears in the grammar file. But you 1107 can choose a different start symbol using the 1108 %start_symbol directive.

1109 1110

1111 %start_symbol prog

1112 
1113 1114 1115

4.4.19 The %syntax_error directive

1116 1117

See Error Processing.

1118 1119 1120

4.4.20 The %token directive

1121 1122

Tokens are normally created automatically, the first time they are used. 1123 Any identifier that begins with an upper-case letter is a token. 1124 1125

Sometimes it is useful to declare tokens in advance, however. The 1126 integer values assigned to each token determined by the order in which 1127 the tokens are seen. So by declaring tokens in advance, it is possible to 1128 cause some tokens to have low-numbered values, which might be desirable in 1129 some grammers, or to have sequential values assigned to a sequence of 1130 related tokens. For this reason, the %token directive is provided to 1131 declare tokens in advance. The syntax is as follows: 1132 1133

1134 %token TOKEN TOKEN... . 1135

1136 1137

The %token directive is followed by zero or more token symbols and 1138 terminated by a single ".". Each token named is created if it does not 1139 already exist. Tokens are created in order. 1140 1141 1142 1143

4.4.21 The %token_class directive

1144 1145

Undocumented. Appears to be related to the MULTITERMINAL concept. 1146 Implementation.

1147 1148 1149

4.4.22 The %token_destructor directive

1150 1151

The %destructor directive assigns a destructor to a non-terminal 1152 symbol. (See the description of the 1153 %destructor directive above.) 1154 The %token_destructor directive does the same thing 1155 for all terminal symbols.

1156 1157

Unlike non-terminal symbols, which may each have a different data type 1158 for their values, terminals all use the same data type (defined by 1159 the %token_type directive) 1160 and so they use a common destructor. 1161 Other than that, the token destructor works just like the non-terminal 1162 destructors.

1163 1164 1165

4.4.23 The %token_prefix directive

1166 1167

Lemon generates #defines that assign small integer constants 1168 to each terminal symbol in the grammar. If desired, Lemon will 1169 add a prefix specified by this directive 1170 to each of the #defines it generates.

1171 1172

So if the default output of Lemon looked like this:

1173

1174 #define AND 1

1175 #define MINUS 2

1176 #define OR 3

1177 #define PLUS 4

1178 
1179

You can insert a statement into the grammar like this:

1180

1181 %token_prefix TOKEN_

1182 
1183

to cause Lemon to produce these symbols instead:

1184

1185 #define TOKEN_AND 1

1186 #define TOKEN_MINUS 2

1187 #define TOKEN_OR 3

1188 #define TOKEN_PLUS 4

1189 
1190 1191 1192

4.4.24 The %token_type and %type directives

1193 1194

These directives are used to specify the data types for values 1195 on the parser's stack associated with terminal and non-terminal 1196 symbols. The values of all terminal symbols must be of the same 1197 type. This turns out to be the same data type as the 3rd parameter 1198 to the Parse() function generated by Lemon. Typically, you will 1199 make the value of a terminal symbol be a pointer to some kind of 1200 token structure. Like this:

1201 1202

1203 %token_type {Token*}

1204 
1205 1206

If the data type of terminals is not specified, the default value 1207 is "void*".

1208 1209

Non-terminal symbols can each have their own data types. Typically 1210 the data type of a non-terminal is a pointer to the root of a parse tree 1211 structure that contains all information about that non-terminal. 1212 For example:

1213 1214

1215 %type expr {Expr*}

1216 
1217 1218

Each entry on the parser's stack is actually a union containing 1219 instances of all data types for every non-terminal and terminal symbol. 1220 Lemon will automatically use the correct element of this union depending 1221 on what the corresponding non-terminal or terminal symbol is. But 1222 the grammar designer should keep in mind that the size of the union 1223 will be the size of its largest element. So if you have a single 1224 non-terminal whose data type requires 1K of storage, then your 100 1225 entry parser stack will require 100K of heap space. If you are willing 1226 and able to pay that price, fine. You just need to know.

1227 1228 1229

4.4.25 The %wildcard directive

1230 1231

The %wildcard directive is followed by a single token name and a 1232 period. This directive specifies that the identified token should 1233 match any input token.

1234 1235

When the generated parser has the choice of matching an input against 1236 the wildcard token and some other token, the other token is always used. 1237 The wildcard token is only matched if there are no alternatives.

1238 1239

Think of the wildcard as an error recovery mechanism. 1240 It is similar, but not identical to, the classic "error" non-terminal 1241 in Yacc/Bison. 1242 1243

1244 The %wildcard directive was added to support parsing 1245 of the CREATE VIRTUAL TABLE statement in the language dialect understood 1246 by SQLite. A CREATE VIRTUAL TABLE statement follows syntax like this: 1247 1248

1249 CREATE VIRTUAL TABLE name USING module(...) 1250
1251 1252

The ellipsis in the example means any (parenthesis-balanced) text can 1253 go here. The ellipsis can include keywords, operators, identifiers, and 1254 any other text, as long as parentheses are balanced. Maybe you could 1255 specify such a thing in pure LALR(1), but doing so would be tricky and 1256 fragile (likely to break as new keywords are added) and slow. By using 1257 %wildcard, the ellipsis gets parsed using the already existing 1258 error recovery logic. The grammar is simplified and the resulting parser 1259 is compact and efficient. 1260 1261

Indiscriminate use of %wildcard can lead to a parser with many 1262 conflicts and/or a parser that do not work as anticipated. However, used 1263 judiciously and in the right context, %wildcard provides a 1264 technique to identify a part of the language where any sequence of tokens 1265 can be inserted, and which is parsed robustly, efficiently, and with 1266 small parsing tables. Search for the "ANY" token in the 1267 SQLite grammar 1268 to see the case for which the %wildcard directive was originally 1269 designed and implemented. 1270 1271 1272

4.4.26 The %realloc, %free, and 1273 %stack_size_limit directives

1274 1275

The %realloc and %free directives defines function 1276 that allocate and free heap memory. The signatures and semantics of 1277 these functions are similar to the realloc() and free() functions from 1278 the standard C library, except that these functions take an extra 1279 parameter at the end that is determined by %extra_context. If 1280 %extra_context is not defined, then the extra argument is 0. The 1281 extra parameter provides the capability to do better error reporting 1282 in the event of a memory allocation error, and/or to use an alternative 1283 private application heap. 1284 1285

If both of these functions are defined then they are used to 1286 allocate and free memory for supplemental parser stack space, if 1287 the initial parse stack space is exceeded. The initial parser stack size 1288 is specified by either %stack_size or the 1289 -DYYSTACKDEPTH compile-time flag. 1290 1291

The %stack_size_limit directive defines a function that returns 1292 the maximum allowed parser stack size. If this diretive does not exist, 1293 no size limit is enforced. This function takes a single argument which 1294 is the %extra_context value or "0" if %extra_context is not defined. 1295 The function should return an integer that is the maximum 1296 number of parser stack entries. If more stack space 1297 than this is needed, the %stack_overflow code is invoked. 1298 1299 1300

5.0 Error Processing

1301 1302

After extensive experimentation over several years, it has been 1303 discovered that the error recovery strategy used by yacc is about 1304 as good as it gets. And so that is what Lemon uses.

1305 1306

When a Lemon-generated parser encounters a syntax error, it 1307 first invokes the code specified by the %syntax_error directive, if 1308 any. It then enters its error recovery strategy. The error recovery 1309 strategy is to begin popping the parsers stack until it enters a 1310 state where it is permitted to shift a special non-terminal symbol 1311 named "error". It then shifts this non-terminal and continues 1312 parsing. The %syntax_error routine will not be called again 1313 until at least three new tokens have been successfully shifted.

1314 1315

If the parser pops its stack until the stack is empty, and it still 1316 is unable to shift the error symbol, then the 1317 %parse_failure routine 1318 is invoked and the parser resets itself to its start state, ready 1319 to begin parsing a new file. This is what will happen at the very 1320 first syntax error, of course, if there are no instances of the 1321 "error" non-terminal in your grammar.

1322 1323 1324 1325

6.0 History of Lemon

1326 1327

Lemon was originally written by Richard Hipp sometime in the late 1328 1980s on a Sun4 Workstation using K&R C. 1329 There was a companion LL(1) parser generator program named "Lime". 1330 The Lime source code has been lost.

1331 1332

The lemon.c source file was originally many separate files that were 1333 compiled together to generate the "lemon" executable. Sometime in the 1334 1990s, the individual source code files were combined together into 1335 the current single large "lemon.c" source file. You can still see traces 1336 of original filenames in the code.

1337 1338

Since 2001, Lemon has been part of the 1339 SQLite project and the source code 1340 to Lemon has been managed as a part of the 1341 SQLite source tree in the following 1342 files:

1343 1344 1349 1350 1351

7.0 Copyright

1352 1353

All of the source code to Lemon, including the template parser file 1354 "lempar.c" and this documentation file ("lemon.html") are in the public 1355 domain. You can use the code for any purpose and without attribution.

1356 1357

The code comes with no warranty. If it breaks, you get to keep both 1358 pieces.

1359 1360 1361