lemon.html 49 KB

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