interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / doc / lemon.html

1361 lines · 54293 bytes Raw Blame History
1<html>
2<head>
3<title>The Lemon Parser Generator</title>
4</head>
5<body>
6<a id="main"></a>
7<h1 align='center'>The Lemon Parser Generator</h1>
8
9<p>Lemon is an LALR(1) parser generator for C.
10It does the same job as "bison" and "yacc".
11But Lemon is not a bison or yacc clone. Lemon
12uses a different grammar syntax which is designed to
13reduce the number of coding errors. Lemon also uses a
14parsing engine that is faster than yacc and
15bison and which is both reentrant and threadsafe.
16(Update: Since the previous sentence was written, bison
17has also been updated so that it too can generate a
18reentrant and threadsafe parser.)
19Lemon also implements features that can be used
20to eliminate resource leaks, making it suitable for use
21in long-running programs such as graphical user interfaces
22or embedded controllers.</p>
23
24<p>This document is an introduction to the Lemon
25parser generator.</p>
26
27<a id="toc"></a>
28<h2>1.0 Table of Contents</h2>
29<ul>
30<li><a href="#main">Introduction</a>
31<li><a href="#toc">1.0 Table of Contents</a>
32<li><a href="#secnot">2.0 Security Notes</a><br>
33<li><a href="#optheory">3.0 Theory of Operation</a>
34 <ul>
35 <li><a href="#options">3.1 Command Line Options</a>
36 <li><a href="#interface">3.2 The Parser Interface</a>
37 <ul>
38 <li><a href="#onstack">3.2.1 Allocating The Parse Object On Stack</a>
39 <li><a href="#ifsum">3.2.2 Interface Summary</a>
40 </ul>
41 <li><a href="#yaccdiff">3.3 Differences With YACC and BISON</a>
42 <li><a href="#build">3.4 Building The "lemon" Or "lemon.exe" Executable</a>
43 </ul>
44<li><a href="#syntax">4.0 Input File Syntax</a>
45 <ul>
46 <li><a href="#tnt">4.1 Terminals and Nonterminals</a>
47 <li><a href="#rules">4.2 Grammar Rules</a>
48 <li><a href="#precrules">4.3 Precedence Rules</a>
49 <li><a href="#special">4.4 Special Directives</a>
50 </ul>
51<li><a href="#errors">5.0 Error Processing</a>
52<li><a href="#history">6.0 History of Lemon</a>
53<li><a href="#copyright">7.0 Copyright</a>
54</ul>
55
56<a id="secnot"></a>
57<h2>2.0 Security Note</h2>
58
59<p>The language parser code created by Lemon is very robust and
60is well-suited for use in internet-facing applications that need to
61safely process maliciously crafted inputs.</p>
62
63<p>The "lemon.exe" command-line tool itself works great when given a valid
64input grammar file and almost always gives helpful
65error messages for malformed inputs. However, it is possible for
66a malicious user to craft a grammar file that will cause
67lemon.exe to crash.
68We do not see this as a problem, as lemon.exe is not intended to be used
69with hostile inputs.
70To summarize:</p>
71
72<ul>
73<li>Parser code generated by lemon &rarr; Robust and secure
74<li>The "lemon.exe" command line tool itself &rarr; Not so much
75</ul>
76
77<a id="optheory"></a>
78<h2>3.0 Theory of Operation</h2>
79
80<p>Lemon is computer program that translates a context free grammar (CFG)
81for a particular language into C code that implements a parser for
82that language.
83The Lemon program has two inputs:</p>
84<ul>
85<li>The grammar specification.
86<li>A parser template file.
87</ul>
88<p>Typically, only the grammar specification is supplied by the programmer.
89Lemon comes with a default parser template
90("<a href="https://sqlite.org/src/file/tool/lempar.c">lempar.c</a>")
91that works fine for most applications. But the user is free to substitute
92a different parser template if desired.</p>
93
94<p>Depending on command-line options, Lemon will generate up to
95three output files.</p>
96<ul>
97<li>C code to implement a parser for the input grammar.
98<li>A header file defining an integer ID for each terminal symbol
99 (or "token").
100<li>An information file that describes the states of the generated parser
101 automaton.
102</ul>
103<p>By default, all three of these output files are generated.
104The header file is suppressed if the "-m" command-line option is
105used and the report file is omitted when "-q" is selected.</p>
106
107<p>The grammar specification file uses a ".y" suffix, by convention.
108In the examples used in this document, we'll assume the name of the
109grammar file is "gram.y". A typical use of Lemon would be the
110following command:</p>
111<pre>
112 lemon gram.y
113</pre>
114<p>This command will generate three output files named "gram.c",
115"gram.h" and "gram.out".
116The first is C code to implement the parser. The second
117is the header file that defines numerical values for all
118terminal symbols, and the last is the report that explains
119the states used by the parser automaton.</p>
120
121<a id="options"></a>
122<h3>3.1 Command Line Options</h3>
123
124<p>The behavior of Lemon can be modified using command-line options.
125You can obtain a list of the available command-line options together
126with a brief explanation of what each does by typing</p>
127<pre>
128 lemon "-?"
129</pre>
130<p>As of this writing, the following command-line options are supported:</p>
131<ul>
132<li><b>-b</b>
133Show only the basis for each parser state in the report file.
134<li><b>-c</b>
135<s>Do not compress the generated action tables. The parser will be a
136little larger and slower, but it will detect syntax errors sooner.</s>
137As of 2026-08-31,
138this option is no longer supported. Lemon always compresses the action
139table.
140<li><b>-d</b><i>directory</i>
141Write all output files into <i>directory</i>. Normally, output files
142are written into the directory that contains the input grammar file.
143<li><b>-D<i>name</i></b>
144Define C preprocessor macro <i>name</i>. This macro is usable by
145"<tt><a href='#pifdef'>%ifdef</a></tt>",
146"<tt><a href='#pifdef'>%ifndef</a></tt>", and
147"<tt><a href="#pifdef">%if</a></tt> lines
148in the grammar file.
149<li><b>-E</b>
150Run the "%if" preprocessor step only and print the revised grammar
151file.
152<li><b>-g</b>
153Do not generate a parser. Instead write the input grammar to standard
154output with all comments, actions, and other extraneous text removed.
155<li><b>-l</b>
156Omit "#line" directives in the generated parser C code.
157<li><b>-m</b>
158Cause the output C source code to be compatible with the "makeheaders"
159program.
160<li><b>-p</b>
161Display all conflicts that are resolved by
162<a href='#precrules'>precedence rules</a>.
163<li><b>-q</b>
164Suppress generation of the report file.
165<li><b>-s</b>
166Show parser statistics before exiting.
167<li><b>-T<i>file</i></b>
168Use <i>file</i> as the template for the generated C-code parser implementation.
169<li><b>-x</b>
170Print the Lemon version number.
171</ul>
172
173<a id="interface"></a>
174<h3>3.2 The Parser Interface</h3>
175
176<p>Lemon doesn't generate a complete, working program. It only generates
177a few subroutines that implement a parser. This section describes
178the interface to those subroutines. It is up to the programmer to
179call these subroutines in an appropriate way in order to produce a
180complete system.</p>
181
182<p>Before a program begins using a Lemon-generated parser, the program
183must first create the parser.
184A new parser is created as follows:</p>
185<pre>
186 void *pParser = ParseAlloc( malloc );
187</pre>
188<p>The ParseAlloc() routine allocates and initializes a new parser and
189returns a pointer to it.
190The actual data structure used to represent a parser is opaque &mdash;
191its internal structure is not visible or usable by the calling routine.
192For this reason, the ParseAlloc() routine returns a pointer to void
193rather than a pointer to some particular structure.
194The sole argument to the ParseAlloc() routine is a pointer to the
195subroutine used to allocate memory. Typically this means malloc().</p>
196
197<p>After a program is finished using a parser, it can reclaim all
198memory allocated by that parser by calling</p>
199<pre>
200 ParseFree(pParser, free);
201</pre>
202<p>The first argument is the same pointer returned by ParseAlloc(). The
203second argument is a pointer to the function used to release bulk
204memory back to the system.</p>
205
206<p>After a parser has been allocated using ParseAlloc(), the programmer
207must supply the parser with a sequence of tokens (terminal symbols) to
208be parsed. This is accomplished by calling the following function
209once for each token:<p>
210<pre>
211 Parse(pParser, hTokenID, sTokenData, pArg);
212</pre>
213<p>The first argument to the Parse() routine is the pointer returned by
214ParseAlloc().
215The second argument is a small positive integer that tells the parser the
216type of the next token in the data stream.
217There is one token type for each terminal symbol in the grammar.
218The gram.h file generated by Lemon contains #define statements that
219map symbolic terminal symbol names into appropriate integer values.
220A value of 0 for the second argument is a special flag to the
221parser to indicate that the end of input has been reached.
222The third argument is the value of the given token. By default,
223the type of the third argument is "void*", but the grammar will
224usually redefine this type to be some kind of structure.
225Typically the second argument will be a broad category of tokens
226such as "identifier" or "number" and the third argument will
227be the name of the identifier or the value of the number.</p>
228
229<p>The Parse() function may have either three or four arguments,
230depending on the grammar. If the grammar specification file requests
231it (via the <tt><a href='#extraarg'>%extra_argument</a></tt> directive),
232the Parse() function will have a fourth parameter that can be
233of any type chosen by the programmer. The parser doesn't do anything
234with this argument except to pass it through to action routines.
235This is a convenient mechanism for passing state information down
236to the action routines without having to use global variables.</p>
237
238<p>A typical use of a Lemon parser might look something like the
239following:</p>
240<pre>
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(&amp;sState);
251 11 while( GetNextToken(pTokenizer, &amp;hTokenId, &amp;sToken) ){
252 12 Parse(pParser, hTokenId, sToken, &amp;sState);
253 13 }
254 14 Parse(pParser, 0, sToken, &amp;sState);
255 15 ParseFree(pParser, free );
256 16 TokenizerFree(pTokenizer);
257 17 return sState.treeRoot;
258 18 }
259</pre>
260<p>This example shows a user-written routine that parses a file of
261text and returns a pointer to the parse tree.
262(All error-handling code is omitted from this example to keep it
263simple.)
264We assume the existence of some kind of tokenizer which is created
265using TokenizerCreate() on line 8 and deleted by TokenizerFree()
266on line 16. The GetNextToken() function on line 11 retrieves the
267next token from the input file and puts its type in the
268integer variable hTokenId. The sToken variable is assumed to be
269some kind of structure that contains details about each token,
270such as its complete text, what line it occurs on, etc.</p>
271
272<p>This example also assumes the existence of a structure of type
273ParserState that holds state information about a particular parse.
274An instance of such a structure is created on line 6 and initialized
275on line 10. A pointer to this structure is passed into the Parse()
276routine as the optional 4th argument.
277The action routine specified by the grammar for the parser can use
278the ParserState structure to hold whatever information is useful and
279appropriate. In the example, we note that the treeRoot field of
280the ParserState structure is left pointing to the root of the parse
281tree.</p>
282
283<p>The core of this example as it relates to Lemon is as follows:</p>
284<pre>
285 ParseFile(){
286 pParser = ParseAlloc( malloc );
287 while( GetNextToken(pTokenizer,&amp;hTokenId, &amp;sToken) ){
288 Parse(pParser, hTokenId, sToken);
289 }
290 Parse(pParser, 0, sToken);
291 ParseFree(pParser, free );
292 }
293</pre>
294<p>Basically, what a program has to do to use a Lemon-generated parser
295is first create the parser, then send it lots of tokens obtained by
296tokenizing an input source. When the end of input is reached, the
297Parse() routine should be called one last time with a token type
298of 0. This step is necessary to inform the parser that the end of
299input has been reached. Finally, we reclaim memory used by the
300parser by calling ParseFree().</p>
301
302<p>There is one other interface routine that should be mentioned
303before we move on.
304The ParseTrace() function can be used to generate debugging output
305from the parser. A prototype for this routine is as follows:</p>
306<pre>
307 ParseTrace(FILE *stream, char *zPrefix);
308</pre>
309<p>After this routine is called, a short (one-line) message is written
310to the designated output stream every time the parser changes states
311or calls an action routine. Each such message is prefaced using
312the text given by zPrefix. This debugging output can be turned off
313by calling ParseTrace() again with a first argument of NULL (0).</p>
314
315<a id="onstack"></a>
316<h4>3.2.1 Allocating The Parse Object On Stack</h4>
317
318<p>If all calls to the Parse() interface are made from within
319<a href="#pcode"><tt>%code</tt> directives</a>, then the parse
320object can be allocated from the stack rather than from the heap.
321These are the steps:
322
323<ul>
324<li> Declare a local variable of type "yyParser"
325<li> Initialize the variable using ParseInit()
326<li> Pass a pointer to the variable in calls to Parse()
327<li> Deallocate substructure in the parse variable using ParseFinalize().
328</ul>
329
330<p>The following code illustrates how this is done:
331
332<pre>
333 ParseFile(){
334 yyParser x;
335 ParseInit( &x );
336 while( GetNextToken(pTokenizer,&amp;hTokenId, &amp;sToken) ){
337 Parse(&x, hTokenId, sToken);
338 }
339 Parse(&x, 0, sToken);
340 ParseFinalize( &x );
341 }
342</pre>
343
344<a id="ifsum"></a>
345<h4>3.2.2 Interface Summary</h4>
346
347<p>Here is a quick overview of the C-language interface to a
348Lemon-generated parser:</p>
349
350<blockquote><pre>
351void *ParseAlloc( (void*(*malloc)(size_t) );
352void ParseFree(void *pParser, (void(*free)(void*) );
353void Parse(void *pParser, int tokenCode, ParseTOKENTYPE token, ...);
354void ParseTrace(FILE *stream, char *zPrefix);
355</pre></blockquote>
356
357<p>Notes:</p>
358<ul>
359<li> Use the <a href="#pname"><tt>%name</tt> directive</a> to change
360the "Parse" prefix names of the procedures in the interface.
361<li> Use the <a href="#token_type"><tt>%token_type</tt> directive</a>
362to define the "ParseTOKENTYPE" type.
363<li> Use the <a href="#extraarg"><tt>%extra_argument</tt> directive</a>
364to specify the type and name of the 4th parameter to the
365Parse() function.
366</ul>
367
368<a id="yaccdiff"></a>
369<h3>3.3 Differences With YACC and BISON</h3>
370
371<p>Programmers who have previously used the yacc or bison parser
372generator will notice several important differences between yacc and/or
373bison and Lemon.</p>
374<ul>
375<li>In yacc and bison, the parser calls the tokenizer. In Lemon,
376 the tokenizer calls the parser.
377<li>Lemon uses no global variables. Yacc and bison use global variables
378 to pass information between the tokenizer and parser.
379<li>Lemon allows multiple parsers to be running simultaneously. Yacc
380 and bison do not.
381</ul>
382<p>These differences may cause some initial confusion for programmers
383with prior yacc and bison experience.
384But after years of experience using Lemon, I firmly
385believe that the Lemon way of doing things is better.</p>
386
387<p><i>Updated as of 2016-02-16:</i>
388The text above was written in the 1990s.
389We are told that Bison has lately been enhanced to support the
390tokenizer-calls-parser paradigm used by Lemon, eliminating the
391need for global variables.</p>
392
393<a id="build"><a>
394<h3>3.4 Building The "lemon" or "lemon.exe" Executable</h3>
395
396<p>The "lemon" or "lemon.exe" program is built from a single file
397of C-code named
398"<a href="https://sqlite.org/src/tool/lemon.c">lemon.c</a>".
399The Lemon source code is generic C89 code that uses
400no unusual or non-standard libraries. Any
401reasonable C compiler should suffice to compile the lemon program.
402A command-line like the following will usually work:</p>
403
404<blockquote><pre>
405cc -o lemon lemon.c
406</pre></blockquote
407
408<p>On Windows machines with Visual C++ installed, bring up a
409"VS20<i>NN</i> x64 Native Tools Command Prompt" window and enter:
410
411<blockquote><pre>
412cl lemon.c
413</pre></blockquote>
414
415<p>Compiling Lemon really is that simple.
416Additional compiler options such as
417"-O2" or "-g" or "-Wall" can be added if desired, but they are not
418necessary.</p>
419
420
421<a id="syntax"></a>
422<h2>4.0 Input File Syntax</h2>
423
424<p>The main purpose of the grammar specification file for Lemon is
425to define the grammar for the parser. But the input file also
426specifies additional information Lemon requires to do its job.
427Most of the work in using Lemon is in writing an appropriate
428grammar file.</p>
429
430<p>The grammar file for Lemon is, for the most part, a free format.
431It does not have sections or divisions like yacc or bison. Any
432declaration can occur at any point in the file. Lemon ignores
433whitespace (except where it is needed to separate tokens), and it
434honors the same commenting conventions as C and C++.</p>
435
436<a id="tnt"></a>
437<h3>4.1 Terminals and Nonterminals</h3>
438
439<p>A terminal symbol (token) is any string of alphanumeric
440and/or underscore characters
441that begins with an uppercase letter.
442A terminal can contain lowercase letters after the first character,
443but the usual convention is to make terminals all uppercase.
444A nonterminal, on the other hand, is any string of alphanumeric
445and underscore characters than begins with a lowercase letter.
446Again, the usual convention is to make nonterminals use all lowercase
447letters.</p>
448
449<p>In Lemon, terminal and nonterminal symbols do not need to
450be declared or identified in a separate section of the grammar file.
451Lemon is able to generate a list of all terminals and nonterminals
452by examining the grammar rules, and it can always distinguish a
453terminal from a nonterminal by checking the case of the first
454character of the name.</p>
455
456<p>Yacc and bison allow terminal symbols to have either alphanumeric
457names or to be individual characters included in single quotes, like
458this: ')' or '$'. Lemon does not allow this alternative form for
459terminal symbols. With Lemon, all symbols, terminals and nonterminals,
460must have alphanumeric names.</p>
461
462<a id="rules"></a>
463<h3>4.2 Grammar Rules</h3>
464
465<p>The main component of a Lemon grammar file is a sequence of grammar
466rules.
467Each grammar rule consists of a nonterminal symbol followed by
468the special symbol "::=" and then a list of terminals and/or nonterminals.
469The rule is terminated by a period.
470The list of terminals and nonterminals on the right-hand side of the
471rule can be empty.
472Rules can occur in any order, except that the left-hand side of the
473first rule is assumed to be the start symbol for the grammar (unless
474specified otherwise using the <tt><a href='#start_symbol'>%start_symbol</a></tt>
475directive described below.)
476A typical sequence of grammar rules might look something like this:</p>
477<pre>
478 expr ::= expr PLUS expr.
479 expr ::= expr TIMES expr.
480 expr ::= LPAREN expr RPAREN.
481 expr ::= VALUE.
482</pre>
483
484<p>There is one non-terminal in this example, "expr", and five
485terminal symbols or tokens: "PLUS", "TIMES", "LPAREN",
486"RPAREN" and "VALUE".</p>
487
488<p>Like yacc and bison, Lemon allows the grammar to specify a block
489of C code that will be executed whenever a grammar rule is reduced
490by the parser.
491In Lemon, this action is specified by putting the C code (contained
492within curly braces <tt>{...}</tt>) immediately after the
493period that closes the rule.
494For example:</p>
495<pre>
496 expr ::= expr PLUS expr. { printf("Doing an addition...\n"); }
497</pre>
498
499<p>In order to be useful, grammar actions must normally be linked to
500their associated grammar rules.
501In yacc and bison, this is accomplished by embedding a "$$" in the
502action to stand for the value of the left-hand side of the rule and
503symbols "$1", "$2", and so forth to stand for the value of
504the terminal or nonterminal at position 1, 2 and so forth on the
505right-hand side of the rule.
506This idea is very powerful, but it is also very error-prone. The
507single most common source of errors in a yacc or bison grammar is
508to miscount the number of symbols on the right-hand side of a grammar
509rule and say "$7" when you really mean "$8".</p>
510
511<p>Lemon avoids the need to count grammar symbols by assigning symbolic
512names to each symbol in a grammar rule and then using those symbolic
513names in the action.
514In yacc or bison, one would write this:</p>
515<pre>
516 expr -&gt; expr PLUS expr { $$ = $1 + $3; };
517</pre>
518<p>But in Lemon, the same rule becomes the following:</p>
519<pre>
520 expr(A) ::= expr(B) PLUS expr(C). { A = B+C; }
521</pre>
522<p>In the Lemon rule, any symbol in parentheses after a grammar rule
523symbol becomes a place holder for that symbol in the grammar rule.
524This place holder can then be used in the associated C action to
525stand for the value of that symbol.</p>
526
527<p>The Lemon notation for linking a grammar rule with its reduce
528action is superior to yacc/bison on several counts.
529First, as mentioned above, the Lemon method avoids the need to
530count grammar symbols.
531Secondly, if a terminal or nonterminal in a Lemon grammar rule
532includes a linking symbol in parentheses but that linking symbol
533is not actually used in the reduce action, then an error message
534is generated.
535For example, the rule</p>
536<pre>
537 expr(A) ::= expr(B) PLUS expr(C). { A = B; }
538</pre>
539<p>will generate an error because the linking symbol "C" is used
540in the grammar rule but not in the reduce action.</p>
541
542<p>The Lemon notation for linking grammar rules to reduce actions
543also facilitates the use of destructors for reclaiming memory
544allocated by the values of terminals and nonterminals on the
545right-hand side of a rule.</p>
546
547<a id='precrules'></a>
548<h3>4.3 Precedence Rules</h3>
549
550<p>Lemon resolves parsing ambiguities in exactly the same way as
551yacc and bison. A shift-reduce conflict is resolved in favor
552of the shift, and a reduce-reduce conflict is resolved by reducing
553whichever rule comes first in the grammar file.</p>
554
555<p>Just like in
556yacc and bison, Lemon allows a measure of control
557over the resolution of parsing conflicts using precedence rules.
558A precedence value can be assigned to any terminal symbol
559using the
560<tt><a href='#pleft'>%left</a></tt>,
561<tt><a href='#pright'>%right</a></tt> or
562<tt><a href='#pnonassoc'>%nonassoc</a></tt> directives. Terminal symbols
563mentioned in earlier directives have a lower precedence than
564terminal symbols mentioned in later directives. For example:</p>
565
566<pre>
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</pre>
574
575<p>In the preceding sequence of directives, the AND operator is
576defined to have the lowest precedence. The OR operator is one
577precedence level higher. And so forth. Hence, the grammar would
578attempt to group the ambiguous expression</p>
579<pre>
580 a AND b OR c
581</pre>
582<p>like this</p>
583<pre>
584 a AND (b OR c).
585</pre>
586<p>The associativity (left, right or nonassoc) is used to determine
587the grouping when the precedence is the same. AND is left-associative
588in our example, so</p>
589<pre>
590 a AND b AND c
591</pre>
592<p>is parsed like this</p>
593<pre>
594 (a AND b) AND c.
595</pre>
596<p>The EXP operator is right-associative, though, so</p>
597<pre>
598 a EXP b EXP c
599</pre>
600<p>is parsed like this</p>
601<pre>
602 a EXP (b EXP c).
603</pre>
604<p>The nonassoc precedence is used for non-associative operators.
605So</p>
606<pre>
607 a EQ b EQ c
608</pre>
609<p>is an error.</p>
610
611<p>The precedence of non-terminals is transferred to rules as follows:
612The precedence of a grammar rule is equal to the precedence of the
613left-most terminal symbol in the rule for which a precedence is
614defined. This is normally what you want, but in those cases where
615you want the precedence of a grammar rule to be something different,
616you can specify an alternative precedence symbol by putting the
617symbol in square braces after the period at the end of the rule and
618before any C-code. For example:</p>
619
620<pre>
621 expr = MINUS expr. [NOT]
622</pre>
623
624<p>This rule has a precedence equal to that of the NOT symbol, not the
625MINUS symbol as would have been the case by default.</p>
626
627<p>With the knowledge of how precedence is assigned to terminal
628symbols and individual
629grammar rules, we can now explain precisely how parsing conflicts
630are resolved in Lemon. Shift-reduce conflicts are resolved
631as follows:</p>
632<ul>
633<li> If either the token to be shifted or the rule to be reduced
634 lacks precedence information, then resolve in favor of the
635 shift, but report a parsing conflict.
636<li> If the precedence of the token to be shifted is greater than
637 the precedence of the rule to reduce, then resolve in favor
638 of the shift. No parsing conflict is reported.
639<li> If the precedence of the token to be shifted is less than the
640 precedence of the rule to reduce, then resolve in favor of the
641 reduce action. No parsing conflict is reported.
642<li> If the precedences are the same and the shift token is
643 right-associative, then resolve in favor of the shift.
644 No parsing conflict is reported.
645<li> If the precedences are the same and the shift token is
646 left-associative, then resolve in favor of the reduce.
647 No parsing conflict is reported.
648<li> Otherwise, resolve the conflict by doing the shift, and
649 report a parsing conflict.
650</ul>
651<p>Reduce-reduce conflicts are resolved this way:</p>
652<ul>
653<li> If either reduce rule
654 lacks precedence information, then resolve in favor of the
655 rule that appears first in the grammar, and report a parsing
656 conflict.
657<li> If both rules have precedence and the precedence is different,
658 then resolve the dispute in favor of the rule with the highest
659 precedence, and do not report a conflict.
660<li> Otherwise, resolve the conflict by reducing by the rule that
661 appears first in the grammar, and report a parsing conflict.
662</ul>
663
664<a id="special"></a>
665<h3>4.4 Special Directives</h3>
666
667<p>The input grammar to Lemon consists of grammar rules and special
668directives. We've described all the grammar rules, so now we'll
669talk about the special directives.</p>
670
671<p>Directives in Lemon can occur in any order. You can put them before
672the grammar rules, or after the grammar rules, or in the midst of the
673grammar rules. It doesn't matter. The relative order of
674directives used to assign precedence to terminals is important, but
675other than that, the order of directives in Lemon is arbitrary.</p>
676
677<p>Lemon supports the following special directives:</p>
678<ul>
679<li><tt><a href='#pcode'>%code</a></tt>
680<li><tt><a href='#default_destructor'>%default_destructor</a></tt>
681<li><tt><a href='#default_type'>%default_type</a></tt>
682<li><tt><a href='#destructor'>%destructor</a></tt>
683<li><tt><a href='#pifdef'>%else</a></tt>
684<li><tt><a href='#pifdef'>%endif</a></tt>
685<li><tt><a href='#extraarg'>%extra_argument</a></tt>
686<li><tt><a href='#pfallback'>%fallback</a></tt>
687<li><tt><a href='#reallc'>%free</a></tt>
688<li><tt><a href='#pifdef'>%if</a></tt>
689<li><tt><a href='#pifdef'>%ifdef</a></tt>
690<li><tt><a href='#pifdef'>%ifndef</a></tt>
691<li><tt><a href='#pinclude'>%include</a></tt>
692<li><tt><a href='#pleft'>%left</a></tt>
693<li><tt><a href='#pname'>%name</a></tt>
694<li><tt><a href='#pnonassoc'>%nonassoc</a></tt>
695<li><tt><a href='#parse_accept'>%parse_accept</a></tt>
696<li><tt><a href='#parse_failure'>%parse_failure</a></tt>
697<li><tt><a href='#pright'>%right</a></tt>
698<li><tt><a href='#reallc'>%realloc</a></tt>
699<li><tt><a href='#stack_overflow'>%stack_overflow</a></tt>
700<li><tt><a href='#reallc'>%stack_size_limit</a></tt>
701<li><tt><a href='#stack_size'>%stack_size</a></tt>
702<li><tt><a href='#start_symbol'>%start_symbol</a></tt>
703<li><tt><a href='#syntax_error'>%syntax_error</a></tt>
704<li><tt><a href='#token'>%token</a></tt>
705<li><tt><a href='#token_class'>%token_class</a></tt>
706<li><tt><a href='#token_destructor'>%token_destructor</a></tt>
707<li><tt><a href='#token_prefix'>%token_prefix</a></tt>
708<li><tt><a href='#token_type'>%token_type</a></tt>
709<li><tt><a href='#ptype'>%type</a></tt>
710<li><tt><a href='#pwildcard'>%wildcard</a></tt>
711</ul>
712<p>Each of these directives will be described separately in the
713following sections:</p>
714
715<a id='pcode'></a>
716<h4>4.4.1 The <tt>%code</tt> directive</h4>
717
718<p>The <tt>%code</tt> directive is used to specify additional C code that
719is added to the end of the main output file. This is similar to
720the <tt><a href='#pinclude'>%include</a></tt> directive except that
721<tt>%include</tt> is inserted at the beginning of the main output file.</p>
722
723<p><tt>%code</tt> is typically used to include some action routines or perhaps
724a tokenizer or even the "main()" function
725as part of the output file.</p>
726
727<p>There can be multiple <tt>%code</tt> directives. The arguments of
728all <tt>%code</tt> directives are concatenated.</p>
729
730<a id='default_destructor'></a>
731<h4>4.4.2 The <tt>%default_destructor</tt> directive</h4>
732
733<p>The <tt>%default_destructor</tt> directive specifies a destructor to
734use for non-terminals that do not have their own destructor
735specified by a separate <tt>%destructor</tt> directive. See the documentation
736on the <tt><a href='#destructor'>%destructor</a></tt> directive below for
737additional information.</p>
738
739<p>In some grammars, many different non-terminal symbols have the
740same data type and hence the same destructor. This directive is
741a convenient way to specify the same destructor for all those
742non-terminals using a single statement.</p>
743
744<a id='default_type'></a>
745<h4>4.4.3 The <tt>%default_type</tt> directive</h4>
746
747<p>The <tt>%default_type</tt> directive specifies the data type of non-terminal
748symbols that do not have their own data type defined using a separate
749<tt><a href='#ptype'>%type</a></tt> directive.</p>
750
751<a id='destructor'></a>
752<h4>4.4.4 The <tt>%destructor</tt> directive</h4>
753
754<p>The <tt>%destructor</tt> directive is used to specify a destructor for
755a non-terminal symbol.
756(See also the <tt><a href='#token_destructor'>%token_destructor</a></tt>
757directive which is used to specify a destructor for terminal symbols.)</p>
758
759<p>A non-terminal's destructor is called to dispose of the
760non-terminal's value whenever the non-terminal is popped from
761the stack. This includes all of the following circumstances:</p>
762<ul>
763<li> When a rule reduces and the value of a non-terminal on
764 the right-hand side is not linked to C code.
765<li> When the stack is popped during error processing.
766<li> When the ParseFree() function runs.
767</ul>
768<p>The destructor can do whatever it wants with the value of
769the non-terminal, but its design is to deallocate memory
770or other resources held by that non-terminal.</p>
771
772<p>Consider an example:</p>
773<pre>
774 %type nt {void*}
775 %destructor nt { free($$); }
776 nt(A) ::= ID NUM. { A = malloc( 100 ); }
777</pre>
778<p>This example is a bit contrived, but it serves to illustrate how
779destructors work. The example shows a non-terminal named
780"nt" that holds values of type "void*". When the rule for
781an "nt" reduces, it sets the value of the non-terminal to
782space obtained from malloc(). Later, when the nt non-terminal
783is popped from the stack, the destructor will fire and call
784free() on this malloced space, thus avoiding a memory leak.
785(Note that the symbol "$$" in the destructor code is replaced
786by the value of the non-terminal.)</p>
787
788<p>It is important to note that the value of a non-terminal is passed
789to the destructor whenever the non-terminal is removed from the
790stack, unless the non-terminal is used in a C-code action. If
791the non-terminal is used by C-code, then it is assumed that the
792C-code will take care of destroying it.
793More commonly, the value is used to build some
794larger structure, and we don't want to destroy it, which is why
795the destructor is not called in this circumstance.</p>
796
797<p>Destructors help avoid memory leaks by automatically freeing
798allocated objects when they go out of scope.
799To do the same using yacc or bison is much more difficult.</p>
800
801<a id='extraarg'></a>
802<h4>4.4.5 The <tt>%extra_argument</tt> directive</h4>
803
804<p>The <tt>%extra_argument</tt> directive instructs Lemon to add a 4th parameter
805to the parameter list of the Parse() function it generates. Lemon
806doesn't do anything itself with this extra argument, but it does
807make the argument available to C-code action routines, destructors,
808and so forth. For example, if the grammar file contains:</p>
809
810<pre>
811 %extra_argument { MyStruct *pAbc }
812</pre>
813
814<p>Then the Parse() function generated will have an 4th parameter
815of type "MyStruct*" and all action routines will have access to
816a variable named "pAbc" that is the value of the 4th parameter
817in the most recent call to Parse().</p>
818
819<p>The <tt>%extra_context</tt> directive works the same except that it
820is passed in on the ParseAlloc() or ParseInit() routines instead of
821on Parse().</p>
822
823<a id='extractx'></a>
824<h4>4.4.6 The <tt>%extra_context</tt> directive</h4>
825
826<p>The <tt>%extra_context</tt> directive instructs Lemon to add a 2nd parameter
827to the parameter list of the ParseAlloc() and ParseInit() functions. Lemon
828doesn't do anything itself with these extra argument, but it does
829store the value make it available to C-code action routines, destructors,
830and so forth. For example, if the grammar file contains:</p>
831
832<pre>
833 %extra_context { MyStruct *pAbc }
834</pre>
835
836<p>Then the ParseAlloc() and ParseInit() functions will have an 2nd parameter
837of type "MyStruct*" and all action routines will have access to
838a variable named "pAbc" that is the value of that 2nd parameter.</p>
839
840<p>The <tt>%extra_argument</tt> directive works the same except that it
841is passed in on the Parse() routine instead of on ParseAlloc()/ParseInit().</p>
842
843<a id='pfallback'></a>
844<h4>4.4.7 The <tt>%fallback</tt> directive</h4>
845
846<p>The <tt>%fallback</tt> directive specifies an alternative meaning for one
847or more tokens. The alternative meaning is tried if the original token
848would have generated a syntax error.</p>
849
850<p>The <tt>%fallback</tt> directive was added to support robust parsing of SQL
851syntax in <a href='https://sqlite.org/'>SQLite</a>.
852The SQL language contains a large assortment of keywords, each of which
853appears as a different token to the language parser. SQL contains so
854many keywords that it can be difficult for programmers to keep up with
855them all. Programmers will, therefore, sometimes mistakenly use an
856obscure language keyword for an identifier. The <tt>%fallback</tt> directive
857provides a mechanism to tell the parser: "If you are unable to parse
858this keyword, try treating it as an identifier instead."</p>
859
860<p>The syntax of <tt>%fallback</tt> is as follows:</p>
861
862<blockquote>
863<tt>%fallback</tt> <i>ID</i> <i>TOKEN...</i> <b>.</b>
864</blockquote></p>
865
866<p>In words, the <tt>%fallback</tt> directive is followed by a list of token
867names terminated by a period.
868The first token name is the fallback token &mdash; the
869token to which all the other tokens fall back to. The second and subsequent
870arguments are tokens which fall back to the token identified by the first
871argument.</p>
872
873<p>The <tt>%fallback</tt> mechanism should be thought of as an error-recovery
874technique. The concept originated with SQLite and the need to maintain
875backwards compatibility as new keywords were added to the SQL language dialect
876understood by SQLite. For example, when SQLite was enhanced to support
877window functions, it needed many new keywords including PARTITION, RANGE, and
878UNBOUNDED. But what if there existed legacy database files that contained
879tables or columns with those names? How would we continue to parse statements
880like the following?
881
882<blockquote><pre>
883CREATE TABLE partition(range TEXT, unbounded BOOLEAN);
884</pre></blockquote>
885
886<p>This conundrum is resolved using a <tt>%fallback</tt> directive similar to:
887
888<blockquote><pre>
889%fallback ID PARTITION RANGE UNBOUNDED.
890</pre></blockquote>
891
892<p>According to the LALR grammar that defines the SQLite syntax,
893the CREATE TABLE statement above is not syntactically correct
894because of the use of those keywords. But the <tt>%fallback</tt> directive
895instructs the parser to change the look-ahead token to ID if it encounters
896a syntax error, and try using the ID token instead before giving up and
897reporting an error.
898
899<p>As <a href="https://sqlite.org/forum/info/2026-08-21T19:04:53Z">Sam Atman
900observes on the SQLite Forum</a>, it is possible to get goofy behavior
901with <tt>%fallback</tt>. Used judiciously, <tt>%fallback</tt> can make
902a parser simpler, faster and more robust. Misuse or overuse can lead
903to ambiguities, however.
904
905<a id='pifdef'></a>
906<h4>4.4.8 The <tt>%if</tt> directive and its friends</h4>
907
908<p>The <tt>%if</tt>, <tt>%ifdef</tt>, <tt>%ifndef</tt>, <tt>%else</tt>,
909and <tt>%endif</tt> directives
910are similar to #if, #ifdef, #ifndef, #else, and #endif in the C-preprocessor,
911just not as general.
912Each of these directives must begin at the left margin. No whitespace
913is allowed between the "%" and the directive name.</p>
914
915<p>Grammar text in between "<tt>%ifdef MACRO</tt>" and the next nested
916"<tt>%endif</tt>" is
917ignored unless the "-DMACRO" command-line option is used. Grammar text
918between "<tt>%ifndef MACRO</tt>" and the next nested "<tt>%endif</tt>" is
919included except when the "-DMACRO" command-line option is used.<p>
920
921<p>The text in between "<tt>%if</tt> <i>CONDITIONAL</i>" and its
922corresponding <tt>%endif</tt> is included only if <i>CONDITIONAL</i>
923is true. The CONDITION is one or more macro names, optionally connected
924using the "||" and "&amp;&amp;" binary operators, the "!" unary operator,
925and grouped using balanced parentheses. Each term is true if the
926corresponding macro exists, and false if it does not exist.</p>
927
928<p>An optional "<tt>%else</tt>" directive can occur anywhere in between a
929<tt>%ifdef</tt>, <tt>%ifndef</tt>, or <tt>%if</tt> directive and
930its corresponding <tt>%endif</tt>.</p>
931
932<p>Note that the argument to <tt>%ifdef</tt> and <tt>%ifndef</tt> is
933intended to be a single preprocessor symbol name, not a general expression.
934Use the "<tt>%if</tt>" directive for general expressions.</p>
935
936<a id='pinclude'></a>
937<h4>4.4.9 The <tt>%include</tt> directive</h4>
938
939<p>The <tt>%include</tt> directive specifies C code that is included at the
940top of the generated parser. You can include any text you want &mdash;
941the Lemon parser generator copies it blindly. If you have multiple
942<tt>%include</tt> directives in your grammar file, their values are concatenated
943so that all <tt>%include</tt> code ultimately appears near the top of the
944generated parser, in the same order as it appeared in the grammar.</p>
945
946<p>The <tt>%include</tt> directive is very handy for getting some extra #include
947preprocessor statements at the beginning of the generated parser.
948For example:</p>
949
950<pre>
951 %include {#include &lt;unistd.h&gt;}
952</pre>
953
954<p>This might be needed, for example, if some of the C actions in the
955grammar call functions that are prototyped in unistd.h.</p>
956
957<p>Use the <tt><a href="#pcode">%code</a></tt> directive to add code to
958the end of the generated parser.</p>
959
960<a id='pleft'></a>
961<h4>4.4.10 The <tt>%left</tt> directive</h4>
962
963The <tt>%left</tt> directive is used (along with the
964<tt><a href='#pright'>%right</a></tt> and
965<tt><a href='#pnonassoc'>%nonassoc</a></tt> directives) to declare
966precedences of terminal symbols.
967Every terminal symbol whose name appears after
968a <tt>%left</tt> directive but before the next period (".") is
969given the same left-associative precedence value. Subsequent
970<tt>%left</tt> directives have higher precedence. For example:</p>
971
972<pre>
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</pre>
980
981<p>Note the period that terminates each <tt>%left</tt>,
982<tt>%right</tt> or <tt>%nonassoc</tt>
983directive.</p>
984
985<p>LALR(1) grammars can get into a situation where they require
986a large amount of stack space if you make heavy use or right-associative
987operators. For this reason, it is recommended that you use <tt>%left</tt>
988rather than <tt>%right</tt> whenever possible.</p>
989
990<a id='pname'></a>
991<h4>4.4.11 The <tt>%name</tt> directive</h4>
992
993<p>By default, the functions generated by Lemon all begin with the
994five-character string "Parse". You can change this string to something
995different using the <tt>%name</tt> directive. For instance:</p>
996
997<pre>
998 %name Abcde
999</pre>
1000
1001<p>Putting this directive in the grammar file will cause Lemon to generate
1002functions named</p>
1003<ul>
1004<li> AbcdeAlloc(),
1005<li> AbcdeFree(),
1006<li> AbcdeTrace(), and
1007<li> Abcde().
1008</ul>
1009</p>The <tt>%name</tt> directive allows you to generate two or more different
1010parsers and link them all into the same executable.</p>
1011
1012<a id='pnonassoc'></a>
1013<h4>4.4.12 The <tt>%nonassoc</tt> directive</h4>
1014
1015<p>This directive is used to assign non-associative precedence to
1016one or more terminal symbols. See the section on
1017<a href='#precrules'>precedence rules</a>
1018or on the <tt><a href='#pleft'>%left</a></tt> directive
1019for additional information.</p>
1020
1021<a id='parse_accept'></a>
1022<h4>4.4.13 The <tt>%parse_accept</tt> directive</h4>
1023
1024<p>The <tt>%parse_accept</tt> directive specifies a block of C code that is
1025executed whenever the parser accepts its input string. To "accept"
1026an input string means that the parser was able to process all tokens
1027without error.</p>
1028
1029<p>For example:</p>
1030
1031<pre>
1032 %parse_accept {
1033 printf("parsing complete!\n");
1034 }
1035</pre>
1036
1037<a id='parse_failure'></a>
1038<h4>4.4.14 The <tt>%parse_failure</tt> directive</h4>
1039
1040<p>The <tt>%parse_failure</tt> directive specifies a block of C code that
1041is executed whenever the parser fails complete. This code is not
1042executed until the parser has tried and failed to resolve an input
1043error using is usual error recovery strategy. The routine is
1044only invoked when parsing is unable to continue.</p>
1045
1046<pre>
1047 %parse_failure {
1048 fprintf(stderr,"Giving up. Parser is hopelessly lost...\n");
1049 }
1050</pre>
1051
1052<a id='pright'></a>
1053<h4>4.4.15 The <tt>%right</tt> directive</h4>
1054
1055<p>This directive is used to assign right-associative precedence to
1056one or more terminal symbols. See the section on
1057<a href='#precrules'>precedence rules</a>
1058or on the <a href='#pleft'>%left</a> directive for additional information.</p>
1059
1060<a id='stack_overflow'></a>
1061<h4>4.4.16 The <tt>%stack_overflow</tt> directive</h4>
1062
1063<p>The <tt>%stack_overflow</tt> directive specifies a block of C code that
1064is executed if the parser's internal stack ever overflows. Typically
1065this just prints an error message. After a stack overflow, the parser
1066will be unable to continue and must be reset.</p>
1067
1068<pre>
1069 %stack_overflow {
1070 fprintf(stderr,"Giving up. Parser stack overflow\n");
1071 }
1072</pre>
1073
1074<p>You can help prevent parser stack overflows by avoiding the use
1075of right recursion and right-precedence operators in your grammar.
1076Use left recursion and and left-precedence operators instead to
1077encourage rules to reduce sooner and keep the stack size down.
1078For example, do rules like this:</p>
1079<pre>
1080 list ::= list element. // left-recursion. Good!
1081 list ::= .
1082</pre>
1083<p>Not like this:</p>
1084<pre>
1085 list ::= element list. // right-recursion. Bad!
1086 list ::= .
1087</pre>
1088
1089<a id='stack_size'></a>
1090<h4>4.4.17 The <tt>%stack_size</tt> directive</h4>
1091
1092<p>If stack overflow is a problem and you can't resolve the trouble
1093by using left-recursion, then you might want to increase the size
1094of the parser's stack using this directive. Put an positive integer
1095after the <tt>%stack_size</tt> directive and Lemon will generate a parse
1096with a stack of the requested size. The default value is 100.</p>
1097
1098<pre>
1099 %stack_size 2000
1100</pre>
1101
1102<a id='start_symbol'></a>
1103<h4>4.4.18 The <tt>%start_symbol</tt> directive</h4>
1104
1105<p>By default, the start symbol for the grammar that Lemon generates
1106is the first non-terminal that appears in the grammar file. But you
1107can choose a different start symbol using the
1108<tt>%start_symbol</tt> directive.</p>
1109
1110<pre>
1111 %start_symbol prog
1112</pre>
1113
1114<a id='syntax_error'></a>
1115<h4>4.4.19 The <tt>%syntax_error</tt> directive</h4>
1116
1117<p>See <a href='#errors'>Error Processing</a>.</p>
1118
1119<a id='token'></a>
1120<h4>4.4.20 The <tt>%token</tt> directive</h4>
1121
1122<p>Tokens are normally created automatically, the first time they are used.
1123Any identifier that begins with an upper-case letter is a token.
1124
1125<p>Sometimes it is useful to declare tokens in advance, however. The
1126integer values assigned to each token determined by the order in which
1127the tokens are seen. So by declaring tokens in advance, it is possible to
1128cause some tokens to have low-numbered values, which might be desirable in
1129some grammers, or to have sequential values assigned to a sequence of
1130related tokens. For this reason, the %token directive is provided to
1131declare tokens in advance. The syntax is as follows:
1132
1133<blockquote>
1134<tt>%token</tt> <i>TOKEN</i> <i>TOKEN...</i> <b>.</b>
1135</blockquote></p>
1136
1137<p>The %token directive is followed by zero or more token symbols and
1138terminated by a single ".". Each token named is created if it does not
1139already exist. Tokens are created in order.
1140
1141
1142<a id='token_class'></a>
1143<h4>4.4.21 The <tt>%token_class</tt> directive</h4>
1144
1145<p>Undocumented. Appears to be related to the MULTITERMINAL concept.
1146<a href='http://sqlite.org/src/fdiff?v1=796930d5fc2036c7&v2=624b24c5dc048e09&sbs=0'>Implementation</a>.</p>
1147
1148<a id='token_destructor'></a>
1149<h4>4.4.22 The <tt>%token_destructor</tt> directive</h4>
1150
1151<p>The <tt>%destructor</tt> directive assigns a destructor to a non-terminal
1152symbol. (See the description of the
1153<tt><a href='#destructor'>%destructor</a></tt> directive above.)
1154The <tt>%token_destructor</tt> directive does the same thing
1155for all terminal symbols.</p>
1156
1157<p>Unlike non-terminal symbols, which may each have a different data type
1158for their values, terminals all use the same data type (defined by
1159the <tt><a href='#token_type'>%token_type</a></tt> directive)
1160and so they use a common destructor.
1161Other than that, the token destructor works just like the non-terminal
1162destructors.</p>
1163
1164<a id='token_prefix'></a>
1165<h4>4.4.23 The <tt>%token_prefix</tt> directive</h4>
1166
1167<p>Lemon generates #defines that assign small integer constants
1168to each terminal symbol in the grammar. If desired, Lemon will
1169add a prefix specified by this directive
1170to each of the #defines it generates.</p>
1171
1172<p>So if the default output of Lemon looked like this:</p>
1173<pre>
1174 #define AND 1
1175 #define MINUS 2
1176 #define OR 3
1177 #define PLUS 4
1178</pre>
1179<p>You can insert a statement into the grammar like this:</p>
1180<pre>
1181 %token_prefix TOKEN_
1182</pre>
1183<p>to cause Lemon to produce these symbols instead:</p>
1184<pre>
1185 #define TOKEN_AND 1
1186 #define TOKEN_MINUS 2
1187 #define TOKEN_OR 3
1188 #define TOKEN_PLUS 4
1189</pre>
1190
1191<a id='token_type'></a><a id='ptype'></a>
1192<h4>4.4.24 The <tt>%token_type</tt> and <tt>%type</tt> directives</h4>
1193
1194<p>These directives are used to specify the data types for values
1195on the parser's stack associated with terminal and non-terminal
1196symbols. The values of all terminal symbols must be of the same
1197type. This turns out to be the same data type as the 3rd parameter
1198to the Parse() function generated by Lemon. Typically, you will
1199make the value of a terminal symbol be a pointer to some kind of
1200token structure. Like this:</p>
1201
1202<pre>
1203 %token_type {Token*}
1204</pre>
1205
1206<p>If the data type of terminals is not specified, the default value
1207is "void*".</p>
1208
1209<p>Non-terminal symbols can each have their own data types. Typically
1210the data type of a non-terminal is a pointer to the root of a parse tree
1211structure that contains all information about that non-terminal.
1212For example:</p>
1213
1214<pre>
1215 %type expr {Expr*}
1216</pre>
1217
1218<p>Each entry on the parser's stack is actually a union containing
1219instances of all data types for every non-terminal and terminal symbol.
1220Lemon will automatically use the correct element of this union depending
1221on what the corresponding non-terminal or terminal symbol is. But
1222the grammar designer should keep in mind that the size of the union
1223will be the size of its largest element. So if you have a single
1224non-terminal whose data type requires 1K of storage, then your 100
1225entry parser stack will require 100K of heap space. If you are willing
1226and able to pay that price, fine. You just need to know.</p>
1227
1228<a id='pwildcard'></a>
1229<h4>4.4.25 The <tt>%wildcard</tt> directive</h4>
1230
1231<p>The <tt>%wildcard</tt> directive is followed by a single token name and a
1232period. This directive specifies that the identified token should
1233match any input token.</p>
1234
1235<p>When the generated parser has the choice of matching an input against
1236the wildcard token and some other token, the other token is always used.
1237The wildcard token is only matched if there are no alternatives.</p>
1238
1239<p>Think of the wildcard as an error recovery mechanism.
1240It is similar, but not identical to, the classic "error" non-terminal
1241in Yacc/Bison.
1242
1243<p>
1244The <tt>%wildcard</tt> directive was added to support parsing
1245of the CREATE VIRTUAL TABLE statement in the language dialect understood
1246by SQLite. A CREATE VIRTUAL TABLE statement follows syntax like this:
1247
1248<blockquote>
1249<tt>CREATE VIRTUAL TABLE</tt> <i>name</i> <tt>USING</tt> <i>module</i><tt>(</tt><i>...</i><tt>)</tt>
1250</blockquote>
1251
1252<p>The ellipsis in the example means any (parenthesis-balanced) text can
1253go here. The ellipsis can include keywords, operators, identifiers, and
1254any other text, as long as parentheses are balanced. Maybe you could
1255specify such a thing in pure LALR(1), but doing so would be tricky and
1256fragile (likely to break as new keywords are added) and slow. By using
1257<tt>%wildcard</tt>, the ellipsis gets parsed using the already existing
1258error recovery logic. The grammar is simplified and the resulting parser
1259is compact and efficient.
1260
1261<p>Indiscriminate use of <tt>%wildcard</tt> can lead to a parser with many
1262conflicts and/or a parser that do not work as anticipated. However, used
1263judiciously and in the right context, <tt>%wildcard</tt> provides a
1264technique to identify a part of the language where any sequence of tokens
1265can be inserted, and which is parsed robustly, efficiently, and with
1266small parsing tables. Search for the "ANY" token in the
1267<a href="https://sqlite.org/src/doc/trunk/src/parse.y?mimetype=text/plain">SQLite grammar</a>
1268to see the case for which the <tt>%wildcard</tt> directive was originally
1269designed and implemented.
1270
1271<a id='reallc'></a>
1272<h4>4.4.26 The <tt>%realloc</tt>, <tt>%free</tt>, and
1273<tt>%stack_size_limit</tt> directives</h4>
1274
1275<p>The <tt>%realloc</tt> and <tt>%free</tt> directives defines function
1276that allocate and free heap memory. The signatures and semantics of
1277these functions are similar to the realloc() and free() functions from
1278the standard C library, except that these functions take an extra
1279parameter at the end that is determined by %extra_context. If
1280%extra_context is not defined, then the extra argument is 0. The
1281extra parameter provides the capability to do better error reporting
1282in the event of a memory allocation error, and/or to use an alternative
1283private application heap.
1284
1285<p>If both of these functions are defined then they are used to
1286allocate and free memory for supplemental parser stack space, if
1287the initial parse stack space is exceeded. The initial parser stack size
1288is specified by either <tt>%stack_size</tt> or the
1289-DYYSTACKDEPTH compile-time flag.
1290
1291<p>The <tt>%stack_size_limit</tt> directive defines a function that returns
1292the maximum allowed parser stack size. If this diretive does not exist,
1293no size limit is enforced. This function takes a single argument which
1294is the %extra_context value or "0" if %extra_context is not defined.
1295The function should return an integer that is the maximum
1296number of parser stack entries. If more stack space
1297than this is needed, the %stack_overflow code is invoked.
1298
1299<a id='errors'></a>
1300<h2>5.0 Error Processing</h2>
1301
1302<p>After extensive experimentation over several years, it has been
1303discovered that the error recovery strategy used by yacc is about
1304as good as it gets. And so that is what Lemon uses.</p>
1305
1306<p>When a Lemon-generated parser encounters a syntax error, it
1307first invokes the code specified by the <tt>%syntax_error</tt> directive, if
1308any. It then enters its error recovery strategy. The error recovery
1309strategy is to begin popping the parsers stack until it enters a
1310state where it is permitted to shift a special non-terminal symbol
1311named "error". It then shifts this non-terminal and continues
1312parsing. The <tt>%syntax_error</tt> routine will not be called again
1313until at least three new tokens have been successfully shifted.</p>
1314
1315<p>If the parser pops its stack until the stack is empty, and it still
1316is unable to shift the error symbol, then the
1317<tt><a href='#parse_failure'>%parse_failure</a></tt> routine
1318is invoked and the parser resets itself to its start state, ready
1319to begin parsing a new file. This is what will happen at the very
1320first syntax error, of course, if there are no instances of the
1321"error" non-terminal in your grammar.</p>
1322
1323
1324<a id='history'></a>
1325<h2>6.0 History of Lemon</h2>
1326
1327<p>Lemon was originally written by Richard Hipp sometime in the late
13281980s on a Sun4 Workstation using K&amp;R C.
1329There was a companion LL(1) parser generator program named "Lime".
1330The Lime source code has been lost.</p>
1331
1332<p>The lemon.c source file was originally many separate files that were
1333compiled together to generate the "lemon" executable. Sometime in the
13341990s, the individual source code files were combined together into
1335the current single large "lemon.c" source file. You can still see traces
1336of original filenames in the code.</p>
1337
1338<p>Since 2001, Lemon has been part of the
1339<a href="https://sqlite.org/">SQLite project</a> and the source code
1340to Lemon has been managed as a part of the
1341<a href="https://sqlite.org/src">SQLite source tree</a> in the following
1342files:</p>
1343
1344<ul>
1345<li> <a href="https://sqlite.org/src/file/tool/lemon.c">tool/lemon.c</a>
1346<li> <a href="https://sqlite.org/src/file/tool/lempar.c">tool/lempar.c</a>
1347<li> <a href="https://sqlite.org/src/file/doc/lemon.html">doc/lemon.html</a>
1348</ul>
1349
1350<a id="copyright"></a>
1351<h2>7.0 Copyright</h2>
1352
1353<p>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
1355domain. You can use the code for any purpose and without attribution.</p>
1356
1357<p>The code comes with no warranty. If it breaks, you get to keep both
1358pieces.</p>
1359
1360</body>
1361</html>