1
0

lemon.html 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. <html>
  2. <head>
  3. <title>The Lemon Parser Generator</title>
  4. </head>
  5. <body bgcolor=white>
  6. <h1 align=center>The Lemon Parser Generator</h1>
  7. <p>Lemon is an LALR(1) parser generator for C or C++.
  8. It does the same job as ``bison'' and ``yacc''.
  9. But lemon is not another bison or yacc clone. It
  10. uses a different grammar syntax which is designed to
  11. reduce the number of coding errors. Lemon also uses a more
  12. sophisticated parsing engine that is faster than yacc and
  13. bison and which is both reentrant and thread-safe.
  14. Furthermore, Lemon implements features that can be used
  15. to eliminate resource leaks, making is suitable for use
  16. in long-running programs such as graphical user interfaces
  17. or embedded controllers.</p>
  18. <p>This document is an introduction to the Lemon
  19. parser generator.</p>
  20. <h2>Theory of Operation</h2>
  21. <p>The main goal of Lemon is to translate a context free grammar (CFG)
  22. for a particular language into C code that implements a parser for
  23. that language.
  24. The program has two inputs:
  25. <ul>
  26. <li>The grammar specification.
  27. <li>A parser template file.
  28. </ul>
  29. Typically, only the grammar specification is supplied by the programmer.
  30. Lemon comes with a default parser template which works fine for most
  31. applications. But the user is free to substitute a different parser
  32. template if desired.</p>
  33. <p>Depending on command-line options, Lemon will generate between
  34. one and three files of outputs.
  35. <ul>
  36. <li>C code to implement the parser.
  37. <li>A header file defining an integer ID for each terminal symbol.
  38. <li>An information file that describes the states of the generated parser
  39. automaton.
  40. </ul>
  41. By default, all three of these output files are generated.
  42. The header file is suppressed if the ``-m'' command-line option is
  43. used and the report file is omitted when ``-q'' is selected.</p>
  44. <p>The grammar specification file uses a ``.y'' suffix, by convention.
  45. In the examples used in this document, we'll assume the name of the
  46. grammar file is ``gram.y''. A typical use of Lemon would be the
  47. following command:
  48. <pre>
  49. lemon gram.y
  50. </pre>
  51. This command will generate three output files named ``gram.c'',
  52. ``gram.h'' and ``gram.out''.
  53. The first is C code to implement the parser. The second
  54. is the header file that defines numerical values for all
  55. terminal symbols, and the last is the report that explains
  56. the states used by the parser automaton.</p>
  57. <h3>Command Line Options</h3>
  58. <p>The behavior of Lemon can be modified using command-line options.
  59. You can obtain a list of the available command-line options together
  60. with a brief explanation of what each does by typing
  61. <pre>
  62. lemon -?
  63. </pre>
  64. As of this writing, the following command-line options are supported:
  65. <ul>
  66. <li><tt>-b</tt>
  67. <li><tt>-c</tt>
  68. <li><tt>-g</tt>
  69. <li><tt>-m</tt>
  70. <li><tt>-q</tt>
  71. <li><tt>-s</tt>
  72. <li><tt>-x</tt>
  73. </ul>
  74. The ``-b'' option reduces the amount of text in the report file by
  75. printing only the basis of each parser state, rather than the full
  76. configuration.
  77. The ``-c'' option suppresses action table compression. Using -c
  78. will make the parser a little larger and slower but it will detect
  79. syntax errors sooner.
  80. The ``-g'' option causes no output files to be generated at all.
  81. Instead, the input grammar file is printed on standard output but
  82. with all comments, actions and other extraneous text deleted. This
  83. is a useful way to get a quick summary of a grammar.
  84. The ``-m'' option causes the output C source file to be compatible
  85. with the ``makeheaders'' program.
  86. Makeheaders is a program that automatically generates header files
  87. from C source code. When the ``-m'' option is used, the header
  88. file is not output since the makeheaders program will take care
  89. of generated all header files automatically.
  90. The ``-q'' option suppresses the report file.
  91. Using ``-s'' causes a brief summary of parser statistics to be
  92. printed. Like this:
  93. <pre>
  94. Parser statistics: 74 terminals, 70 nonterminals, 179 rules
  95. 340 states, 2026 parser table entries, 0 conflicts
  96. </pre>
  97. Finally, the ``-x'' option causes Lemon to print its version number
  98. and then stops without attempting to read the grammar or generate a parser.</p>
  99. <h3>The Parser Interface</h3>
  100. <p>Lemon doesn't generate a complete, working program. It only generates
  101. a few subroutines that implement a parser. This section describes
  102. the interface to those subroutines. It is up to the programmer to
  103. call these subroutines in an appropriate way in order to produce a
  104. complete system.</p>
  105. <p>Before a program begins using a Lemon-generated parser, the program
  106. must first create the parser.
  107. A new parser is created as follows:
  108. <pre>
  109. void *pParser = ParseAlloc( malloc );
  110. </pre>
  111. The ParseAlloc() routine allocates and initializes a new parser and
  112. returns a pointer to it.
  113. The actual data structure used to represent a parser is opaque --
  114. its internal structure is not visible or usable by the calling routine.
  115. For this reason, the ParseAlloc() routine returns a pointer to void
  116. rather than a pointer to some particular structure.
  117. The sole argument to the ParseAlloc() routine is a pointer to the
  118. subroutine used to allocate memory. Typically this means ``malloc()''.</p>
  119. <p>After a program is finished using a parser, it can reclaim all
  120. memory allocated by that parser by calling
  121. <pre>
  122. ParseFree(pParser, free);
  123. </pre>
  124. The first argument is the same pointer returned by ParseAlloc(). The
  125. second argument is a pointer to the function used to release bulk
  126. memory back to the system.</p>
  127. <p>After a parser has been allocated using ParseAlloc(), the programmer
  128. must supply the parser with a sequence of tokens (terminal symbols) to
  129. be parsed. This is accomplished by calling the following function
  130. once for each token:
  131. <pre>
  132. Parse(pParser, hTokenID, sTokenData, pArg);
  133. </pre>
  134. The first argument to the Parse() routine is the pointer returned by
  135. ParseAlloc().
  136. The second argument is a small positive integer that tells the parse the
  137. type of the next token in the data stream.
  138. There is one token type for each terminal symbol in the grammar.
  139. The gram.h file generated by Lemon contains #define statements that
  140. map symbolic terminal symbol names into appropriate integer values.
  141. (A value of 0 for the second argument is a special flag to the
  142. parser to indicate that the end of input has been reached.)
  143. The third argument is the value of the given token. By default,
  144. the type of the third argument is integer, but the grammar will
  145. usually redefine this type to be some kind of structure.
  146. Typically the second argument will be a broad category of tokens
  147. such as ``identifier'' or ``number'' and the third argument will
  148. be the name of the identifier or the value of the number.</p>
  149. <p>The Parse() function may have either three or four arguments,
  150. depending on the grammar. If the grammar specification file request
  151. it, the Parse() function will have a fourth parameter that can be
  152. of any type chosen by the programmer. The parser doesn't do anything
  153. with this argument except to pass it through to action routines.
  154. This is a convenient mechanism for passing state information down
  155. to the action routines without having to use global variables.</p>
  156. <p>A typical use of a Lemon parser might look something like the
  157. following:
  158. <pre>
  159. 01 ParseTree *ParseFile(const char *zFilename){
  160. 02 Tokenizer *pTokenizer;
  161. 03 void *pParser;
  162. 04 Token sToken;
  163. 05 int hTokenId;
  164. 06 ParserState sState;
  165. 07
  166. 08 pTokenizer = TokenizerCreate(zFilename);
  167. 09 pParser = ParseAlloc( malloc );
  168. 10 InitParserState(&sState);
  169. 11 while( GetNextToken(pTokenizer, &hTokenId, &sToken) ){
  170. 12 Parse(pParser, hTokenId, sToken, &sState);
  171. 13 }
  172. 14 Parse(pParser, 0, sToken, &sState);
  173. 15 ParseFree(pParser, free );
  174. 16 TokenizerFree(pTokenizer);
  175. 17 return sState.treeRoot;
  176. 18 }
  177. </pre>
  178. This example shows a user-written routine that parses a file of
  179. text and returns a pointer to the parse tree.
  180. (We've omitted all error-handling from this example to keep it
  181. simple.)
  182. We assume the existence of some kind of tokenizer which is created
  183. using TokenizerCreate() on line 8 and deleted by TokenizerFree()
  184. on line 16. The GetNextToken() function on line 11 retrieves the
  185. next token from the input file and puts its type in the
  186. integer variable hTokenId. The sToken variable is assumed to be
  187. some kind of structure that contains details about each token,
  188. such as its complete text, what line it occurs on, etc. </p>
  189. <p>This example also assumes the existence of structure of type
  190. ParserState that holds state information about a particular parse.
  191. An instance of such a structure is created on line 6 and initialized
  192. on line 10. A pointer to this structure is passed into the Parse()
  193. routine as the optional 4th argument.
  194. The action routine specified by the grammar for the parser can use
  195. the ParserState structure to hold whatever information is useful and
  196. appropriate. In the example, we note that the treeRoot field of
  197. the ParserState structure is left pointing to the root of the parse
  198. tree.</p>
  199. <p>The core of this example as it relates to Lemon is as follows:
  200. <pre>
  201. ParseFile(){
  202. pParser = ParseAlloc( malloc );
  203. while( GetNextToken(pTokenizer,&hTokenId, &sToken) ){
  204. Parse(pParser, hTokenId, sToken);
  205. }
  206. Parse(pParser, 0, sToken);
  207. ParseFree(pParser, free );
  208. }
  209. </pre>
  210. Basically, what a program has to do to use a Lemon-generated parser
  211. is first create the parser, then send it lots of tokens obtained by
  212. tokenizing an input source. When the end of input is reached, the
  213. Parse() routine should be called one last time with a token type
  214. of 0. This step is necessary to inform the parser that the end of
  215. input has been reached. Finally, we reclaim memory used by the
  216. parser by calling ParseFree().</p>
  217. <p>There is one other interface routine that should be mentioned
  218. before we move on.
  219. The ParseTrace() function can be used to generate debugging output
  220. from the parser. A prototype for this routine is as follows:
  221. <pre>
  222. ParseTrace(FILE *stream, char *zPrefix);
  223. </pre>
  224. After this routine is called, a short (one-line) message is written
  225. to the designated output stream every time the parser changes states
  226. or calls an action routine. Each such message is prefaced using
  227. the text given by zPrefix. This debugging output can be turned off
  228. by calling ParseTrace() again with a first argument of NULL (0).</p>
  229. <h3>Differences With YACC and BISON</h3>
  230. <p>Programmers who have previously used the yacc or bison parser
  231. generator will notice several important differences between yacc and/or
  232. bison and Lemon.
  233. <ul>
  234. <li>In yacc and bison, the parser calls the tokenizer. In Lemon,
  235. the tokenizer calls the parser.
  236. <li>Lemon uses no global variables. Yacc and bison use global variables
  237. to pass information between the tokenizer and parser.
  238. <li>Lemon allows multiple parsers to be running simultaneously. Yacc
  239. and bison do not.
  240. </ul>
  241. These differences may cause some initial confusion for programmers
  242. with prior yacc and bison experience.
  243. But after years of experience using Lemon, I firmly
  244. believe that the Lemon way of doing things is better.</p>
  245. <h2>Input File Syntax</h2>
  246. <p>The main purpose of the grammar specification file for Lemon is
  247. to define the grammar for the parser. But the input file also
  248. specifies additional information Lemon requires to do its job.
  249. Most of the work in using Lemon is in writing an appropriate
  250. grammar file.</p>
  251. <p>The grammar file for lemon is, for the most part, free format.
  252. It does not have sections or divisions like yacc or bison. Any
  253. declaration can occur at any point in the file.
  254. Lemon ignores whitespace (except where it is needed to separate
  255. tokens) and it honors the same commenting conventions as C and C++.</p>
  256. <h3>Terminals and Nonterminals</h3>
  257. <p>A terminal symbol (token) is any string of alphanumeric
  258. and underscore characters
  259. that begins with an upper case letter.
  260. A terminal can contain lowercase letters after the first character,
  261. but the usual convention is to make terminals all upper case.
  262. A nonterminal, on the other hand, is any string of alphanumeric
  263. and underscore characters than begins with a lower case letter.
  264. Again, the usual convention is to make nonterminals use all lower
  265. case letters.</p>
  266. <p>In Lemon, terminal and nonterminal symbols do not need to
  267. be declared or identified in a separate section of the grammar file.
  268. Lemon is able to generate a list of all terminals and nonterminals
  269. by examining the grammar rules, and it can always distinguish a
  270. terminal from a nonterminal by checking the case of the first
  271. character of the name.</p>
  272. <p>Yacc and bison allow terminal symbols to have either alphanumeric
  273. names or to be individual characters included in single quotes, like
  274. this: ')' or '$'. Lemon does not allow this alternative form for
  275. terminal symbols. With Lemon, all symbols, terminals and nonterminals,
  276. must have alphanumeric names.</p>
  277. <h3>Grammar Rules</h3>
  278. <p>The main component of a Lemon grammar file is a sequence of grammar
  279. rules.
  280. Each grammar rule consists of a nonterminal symbol followed by
  281. the special symbol ``::='' and then a list of terminals and/or nonterminals.
  282. The rule is terminated by a period.
  283. The list of terminals and nonterminals on the right-hand side of the
  284. rule can be empty.
  285. Rules can occur in any order, except that the left-hand side of the
  286. first rule is assumed to be the start symbol for the grammar (unless
  287. specified otherwise using the <tt>%start</tt> directive described below.)
  288. A typical sequence of grammar rules might look something like this:
  289. <pre>
  290. expr ::= expr PLUS expr.
  291. expr ::= expr TIMES expr.
  292. expr ::= LPAREN expr RPAREN.
  293. expr ::= VALUE.
  294. </pre>
  295. </p>
  296. <p>There is one non-terminal in this example, ``expr'', and five
  297. terminal symbols or tokens: ``PLUS'', ``TIMES'', ``LPAREN'',
  298. ``RPAREN'' and ``VALUE''.</p>
  299. <p>Like yacc and bison, Lemon allows the grammar to specify a block
  300. of C code that will be executed whenever a grammar rule is reduced
  301. by the parser.
  302. In Lemon, this action is specified by putting the C code (contained
  303. within curly braces <tt>{...}</tt>) immediately after the
  304. period that closes the rule.
  305. For example:
  306. <pre>
  307. expr ::= expr PLUS expr. { printf("Doing an addition...\n"); }
  308. </pre>
  309. </p>
  310. <p>In order to be useful, grammar actions must normally be linked to
  311. their associated grammar rules.
  312. In yacc and bison, this is accomplished by embedding a ``$$'' in the
  313. action to stand for the value of the left-hand side of the rule and
  314. symbols ``$1'', ``$2'', and so forth to stand for the value of
  315. the terminal or nonterminal at position 1, 2 and so forth on the
  316. right-hand side of the rule.
  317. This idea is very powerful, but it is also very error-prone. The
  318. single most common source of errors in a yacc or bison grammar is
  319. to miscount the number of symbols on the right-hand side of a grammar
  320. rule and say ``$7'' when you really mean ``$8''.</p>
  321. <p>Lemon avoids the need to count grammar symbols by assigning symbolic
  322. names to each symbol in a grammar rule and then using those symbolic
  323. names in the action.
  324. In yacc or bison, one would write this:
  325. <pre>
  326. expr -> expr PLUS expr { $$ = $1 + $3; };
  327. </pre>
  328. But in Lemon, the same rule becomes the following:
  329. <pre>
  330. expr(A) ::= expr(B) PLUS expr(C). { A = B+C; }
  331. </pre>
  332. In the Lemon rule, any symbol in parentheses after a grammar rule
  333. symbol becomes a place holder for that symbol in the grammar rule.
  334. This place holder can then be used in the associated C action to
  335. stand for the value of that symbol.<p>
  336. <p>The Lemon notation for linking a grammar rule with its reduce
  337. action is superior to yacc/bison on several counts.
  338. First, as mentioned above, the Lemon method avoids the need to
  339. count grammar symbols.
  340. Secondly, if a terminal or nonterminal in a Lemon grammar rule
  341. includes a linking symbol in parentheses but that linking symbol
  342. is not actually used in the reduce action, then an error message
  343. is generated.
  344. For example, the rule
  345. <pre>
  346. expr(A) ::= expr(B) PLUS expr(C). { A = B; }
  347. </pre>
  348. will generate an error because the linking symbol ``C'' is used
  349. in the grammar rule but not in the reduce action.</p>
  350. <p>The Lemon notation for linking grammar rules to reduce actions
  351. also facilitates the use of destructors for reclaiming memory
  352. allocated by the values of terminals and nonterminals on the
  353. right-hand side of a rule.</p>
  354. <h3>Precedence Rules</h3>
  355. <p>Lemon resolves parsing ambiguities in exactly the same way as
  356. yacc and bison. A shift-reduce conflict is resolved in favor
  357. of the shift, and a reduce-reduce conflict is resolved by reducing
  358. whichever rule comes first in the grammar file.</p>
  359. <p>Just like in
  360. yacc and bison, Lemon allows a measure of control
  361. over the resolution of paring conflicts using precedence rules.
  362. A precedence value can be assigned to any terminal symbol
  363. using the %left, %right or %nonassoc directives. Terminal symbols
  364. mentioned in earlier directives have a lower precedence that
  365. terminal symbols mentioned in later directives. For example:</p>
  366. <p><pre>
  367. %left AND.
  368. %left OR.
  369. %nonassoc EQ NE GT GE LT LE.
  370. %left PLUS MINUS.
  371. %left TIMES DIVIDE MOD.
  372. %right EXP NOT.
  373. </pre></p>
  374. <p>In the preceding sequence of directives, the AND operator is
  375. defined to have the lowest precedence. The OR operator is one
  376. precedence level higher. And so forth. Hence, the grammar would
  377. attempt to group the ambiguous expression
  378. <pre>
  379. a AND b OR c
  380. </pre>
  381. like this
  382. <pre>
  383. a AND (b OR c).
  384. </pre>
  385. The associativity (left, right or nonassoc) is used to determine
  386. the grouping when the precedence is the same. AND is left-associative
  387. in our example, so
  388. <pre>
  389. a AND b AND c
  390. </pre>
  391. is parsed like this
  392. <pre>
  393. (a AND b) AND c.
  394. </pre>
  395. The EXP operator is right-associative, though, so
  396. <pre>
  397. a EXP b EXP c
  398. </pre>
  399. is parsed like this
  400. <pre>
  401. a EXP (b EXP c).
  402. </pre>
  403. The nonassoc precedence is used for non-associative operators.
  404. So
  405. <pre>
  406. a EQ b EQ c
  407. </pre>
  408. is an error.</p>
  409. <p>The precedence of non-terminals is transferred to rules as follows:
  410. The precedence of a grammar rule is equal to the precedence of the
  411. left-most terminal symbol in the rule for which a precedence is
  412. defined. This is normally what you want, but in those cases where
  413. you want to precedence of a grammar rule to be something different,
  414. you can specify an alternative precedence symbol by putting the
  415. symbol in square braces after the period at the end of the rule and
  416. before any C-code. For example:</p>
  417. <p><pre>
  418. expr = MINUS expr. [NOT]
  419. </pre></p>
  420. <p>This rule has a precedence equal to that of the NOT symbol, not the
  421. MINUS symbol as would have been the case by default.</p>
  422. <p>With the knowledge of how precedence is assigned to terminal
  423. symbols and individual
  424. grammar rules, we can now explain precisely how parsing conflicts
  425. are resolved in Lemon. Shift-reduce conflicts are resolved
  426. as follows:
  427. <ul>
  428. <li> If either the token to be shifted or the rule to be reduced
  429. lacks precedence information, then resolve in favor of the
  430. shift, but report a parsing conflict.
  431. <li> If the precedence of the token to be shifted is greater than
  432. the precedence of the rule to reduce, then resolve in favor
  433. of the shift. No parsing conflict is reported.
  434. <li> If the precedence of the token it be shifted is less than the
  435. precedence of the rule to reduce, then resolve in favor of the
  436. reduce action. No parsing conflict is reported.
  437. <li> If the precedences are the same and the shift token is
  438. right-associative, then resolve in favor of the shift.
  439. No parsing conflict is reported.
  440. <li> If the precedences are the same the shift token is
  441. left-associative, then resolve in favor of the reduce.
  442. No parsing conflict is reported.
  443. <li> Otherwise, resolve the conflict by doing the shift and
  444. report the parsing conflict.
  445. </ul>
  446. Reduce-reduce conflicts are resolved this way:
  447. <ul>
  448. <li> If either reduce rule
  449. lacks precedence information, then resolve in favor of the
  450. rule that appears first in the grammar and report a parsing
  451. conflict.
  452. <li> If both rules have precedence and the precedence is different
  453. then resolve the dispute in favor of the rule with the highest
  454. precedence and do not report a conflict.
  455. <li> Otherwise, resolve the conflict by reducing by the rule that
  456. appears first in the grammar and report a parsing conflict.
  457. </ul>
  458. <h3>Special Directives</h3>
  459. <p>The input grammar to Lemon consists of grammar rules and special
  460. directives. We've described all the grammar rules, so now we'll
  461. talk about the special directives.</p>
  462. <p>Directives in lemon can occur in any order. You can put them before
  463. the grammar rules, or after the grammar rules, or in the mist of the
  464. grammar rules. It doesn't matter. The relative order of
  465. directives used to assign precedence to terminals is important, but
  466. other than that, the order of directives in Lemon is arbitrary.</p>
  467. <p>Lemon supports the following special directives:
  468. <ul>
  469. <li><tt>%code</tt>
  470. <li><tt>%default_destructor</tt>
  471. <li><tt>%default_type</tt>
  472. <li><tt>%destructor</tt>
  473. <li><tt>%extra_argument</tt>
  474. <li><tt>%include</tt>
  475. <li><tt>%left</tt>
  476. <li><tt>%name</tt>
  477. <li><tt>%nonassoc</tt>
  478. <li><tt>%parse_accept</tt>
  479. <li><tt>%parse_failure </tt>
  480. <li><tt>%right</tt>
  481. <li><tt>%stack_overflow</tt>
  482. <li><tt>%stack_size</tt>
  483. <li><tt>%start_symbol</tt>
  484. <li><tt>%syntax_error</tt>
  485. <li><tt>%token_destructor</tt>
  486. <li><tt>%token_prefix</tt>
  487. <li><tt>%token_type</tt>
  488. <li><tt>%type</tt>
  489. </ul>
  490. Each of these directives will be described separately in the
  491. following sections:</p>
  492. <h4>The <tt>%code</tt> directive</h4>
  493. <p>The %code directive is used to specify addition C/C++ code that
  494. is added to the end of the main output file. This is similar to
  495. the %include directive except that %include is inserted at the
  496. beginning of the main output file.</p>
  497. <p>%code is typically used to include some action routines or perhaps
  498. a tokenizer as part of the output file.</p>
  499. <h4>The <tt>%default_destructor</tt> directive</h4>
  500. <p>The %default_destructor directive specifies a destructor to
  501. use for non-terminals that do not have their own destructor
  502. specified by a separate %destructor directive. See the documentation
  503. on the %destructor directive below for additional information.</p>
  504. <p>In some grammers, many different non-terminal symbols have the
  505. same datatype and hence the same destructor. This directive is
  506. a convenience way to specify the same destructor for all those
  507. non-terminals using a single statement.</p>
  508. <h4>The <tt>%default_type</tt> directive</h4>
  509. <p>The %default_type directive specifies the datatype of non-terminal
  510. symbols that do no have their own datatype defined using a separate
  511. %type directive. See the documentation on %type below for addition
  512. information.</p>
  513. <h4>The <tt>%destructor</tt> directive</h4>
  514. <p>The %destructor directive is used to specify a destructor for
  515. a non-terminal symbol.
  516. (See also the %token_destructor directive which is used to
  517. specify a destructor for terminal symbols.)</p>
  518. <p>A non-terminal's destructor is called to dispose of the
  519. non-terminal's value whenever the non-terminal is popped from
  520. the stack. This includes all of the following circumstances:
  521. <ul>
  522. <li> When a rule reduces and the value of a non-terminal on
  523. the right-hand side is not linked to C code.
  524. <li> When the stack is popped during error processing.
  525. <li> When the ParseFree() function runs.
  526. </ul>
  527. The destructor can do whatever it wants with the value of
  528. the non-terminal, but its design is to deallocate memory
  529. or other resources held by that non-terminal.</p>
  530. <p>Consider an example:
  531. <pre>
  532. %type nt {void*}
  533. %destructor nt { free($$); }
  534. nt(A) ::= ID NUM. { A = malloc( 100 ); }
  535. </pre>
  536. This example is a bit contrived but it serves to illustrate how
  537. destructors work. The example shows a non-terminal named
  538. ``nt'' that holds values of type ``void*''. When the rule for
  539. an ``nt'' reduces, it sets the value of the non-terminal to
  540. space obtained from malloc(). Later, when the nt non-terminal
  541. is popped from the stack, the destructor will fire and call
  542. free() on this malloced space, thus avoiding a memory leak.
  543. (Note that the symbol ``$$'' in the destructor code is replaced
  544. by the value of the non-terminal.)</p>
  545. <p>It is important to note that the value of a non-terminal is passed
  546. to the destructor whenever the non-terminal is removed from the
  547. stack, unless the non-terminal is used in a C-code action. If
  548. the non-terminal is used by C-code, then it is assumed that the
  549. C-code will take care of destroying it if it should really
  550. be destroyed. More commonly, the value is used to build some
  551. larger structure and we don't want to destroy it, which is why
  552. the destructor is not called in this circumstance.</p>
  553. <p>By appropriate use of destructors, it is possible to
  554. build a parser using Lemon that can be used within a long-running
  555. program, such as a GUI, that will not leak memory or other resources.
  556. To do the same using yacc or bison is much more difficult.</p>
  557. <h4>The <tt>%extra_argument</tt> directive</h4>
  558. The %extra_argument directive instructs Lemon to add a 4th parameter
  559. to the parameter list of the Parse() function it generates. Lemon
  560. doesn't do anything itself with this extra argument, but it does
  561. make the argument available to C-code action routines, destructors,
  562. and so forth. For example, if the grammar file contains:</p>
  563. <p><pre>
  564. %extra_argument { MyStruct *pAbc }
  565. </pre></p>
  566. <p>Then the Parse() function generated will have an 4th parameter
  567. of type ``MyStruct*'' and all action routines will have access to
  568. a variable named ``pAbc'' that is the value of the 4th parameter
  569. in the most recent call to Parse().</p>
  570. <h4>The <tt>%include</tt> directive</h4>
  571. <p>The %include directive specifies C code that is included at the
  572. top of the generated parser. You can include any text you want --
  573. the Lemon parser generator copies it blindly. If you have multiple
  574. %include directives in your grammar file the value of the last
  575. %include directive overwrites all the others.</p.
  576. <p>The %include directive is very handy for getting some extra #include
  577. preprocessor statements at the beginning of the generated parser.
  578. For example:</p>
  579. <p><pre>
  580. %include {#include &lt;unistd.h&gt;}
  581. </pre></p>
  582. <p>This might be needed, for example, if some of the C actions in the
  583. grammar call functions that are prototyed in unistd.h.</p>
  584. <h4>The <tt>%left</tt> directive</h4>
  585. The %left directive is used (along with the %right and
  586. %nonassoc directives) to declare precedences of terminal
  587. symbols. Every terminal symbol whose name appears after
  588. a %left directive but before the next period (``.'') is
  589. given the same left-associative precedence value. Subsequent
  590. %left directives have higher precedence. For example:</p>
  591. <p><pre>
  592. %left AND.
  593. %left OR.
  594. %nonassoc EQ NE GT GE LT LE.
  595. %left PLUS MINUS.
  596. %left TIMES DIVIDE MOD.
  597. %right EXP NOT.
  598. </pre></p>
  599. <p>Note the period that terminates each %left, %right or %nonassoc
  600. directive.</p>
  601. <p>LALR(1) grammars can get into a situation where they require
  602. a large amount of stack space if you make heavy use or right-associative
  603. operators. For this reason, it is recommended that you use %left
  604. rather than %right whenever possible.</p>
  605. <h4>The <tt>%name</tt> directive</h4>
  606. <p>By default, the functions generated by Lemon all begin with the
  607. five-character string ``Parse''. You can change this string to something
  608. different using the %name directive. For instance:</p>
  609. <p><pre>
  610. %name Abcde
  611. </pre></p>
  612. <p>Putting this directive in the grammar file will cause Lemon to generate
  613. functions named
  614. <ul>
  615. <li> AbcdeAlloc(),
  616. <li> AbcdeFree(),
  617. <li> AbcdeTrace(), and
  618. <li> Abcde().
  619. </ul>
  620. The %name directive allows you to generator two or more different
  621. parsers and link them all into the same executable.
  622. </p>
  623. <h4>The <tt>%nonassoc</tt> directive</h4>
  624. <p>This directive is used to assign non-associative precedence to
  625. one or more terminal symbols. See the section on precedence rules
  626. or on the %left directive for additional information.</p>
  627. <h4>The <tt>%parse_accept</tt> directive</h4>
  628. <p>The %parse_accept directive specifies a block of C code that is
  629. executed whenever the parser accepts its input string. To ``accept''
  630. an input string means that the parser was able to process all tokens
  631. without error.</p>
  632. <p>For example:</p>
  633. <p><pre>
  634. %parse_accept {
  635. printf("parsing complete!\n");
  636. }
  637. </pre></p>
  638. <h4>The <tt>%parse_failure</tt> directive</h4>
  639. <p>The %parse_failure directive specifies a block of C code that
  640. is executed whenever the parser fails complete. This code is not
  641. executed until the parser has tried and failed to resolve an input
  642. error using is usual error recovery strategy. The routine is
  643. only invoked when parsing is unable to continue.</p>
  644. <p><pre>
  645. %parse_failure {
  646. fprintf(stderr,"Giving up. Parser is hopelessly lost...\n");
  647. }
  648. </pre></p>
  649. <h4>The <tt>%right</tt> directive</h4>
  650. <p>This directive is used to assign right-associative precedence to
  651. one or more terminal symbols. See the section on precedence rules
  652. or on the %left directive for additional information.</p>
  653. <h4>The <tt>%stack_overflow</tt> directive</h4>
  654. <p>The %stack_overflow directive specifies a block of C code that
  655. is executed if the parser's internal stack ever overflows. Typically
  656. this just prints an error message. After a stack overflow, the parser
  657. will be unable to continue and must be reset.</p>
  658. <p><pre>
  659. %stack_overflow {
  660. fprintf(stderr,"Giving up. Parser stack overflow\n");
  661. }
  662. </pre></p>
  663. <p>You can help prevent parser stack overflows by avoiding the use
  664. of right recursion and right-precedence operators in your grammar.
  665. Use left recursion and and left-precedence operators instead, to
  666. encourage rules to reduce sooner and keep the stack size down.
  667. For example, do rules like this:
  668. <pre>
  669. list ::= list element. // left-recursion. Good!
  670. list ::= .
  671. </pre>
  672. Not like this:
  673. <pre>
  674. list ::= element list. // right-recursion. Bad!
  675. list ::= .
  676. </pre>
  677. <h4>The <tt>%stack_size</tt> directive</h4>
  678. <p>If stack overflow is a problem and you can't resolve the trouble
  679. by using left-recursion, then you might want to increase the size
  680. of the parser's stack using this directive. Put an positive integer
  681. after the %stack_size directive and Lemon will generate a parse
  682. with a stack of the requested size. The default value is 100.</p>
  683. <p><pre>
  684. %stack_size 2000
  685. </pre></p>
  686. <h4>The <tt>%start_symbol</tt> directive</h4>
  687. <p>By default, the start-symbol for the grammar that Lemon generates
  688. is the first non-terminal that appears in the grammar file. But you
  689. can choose a different start-symbol using the %start_symbol directive.</p>
  690. <p><pre>
  691. %start_symbol prog
  692. </pre></p>
  693. <h4>The <tt>%token_destructor</tt> directive</h4>
  694. <p>The %destructor directive assigns a destructor to a non-terminal
  695. symbol. (See the description of the %destructor directive above.)
  696. This directive does the same thing for all terminal symbols.</p>
  697. <p>Unlike non-terminal symbols which may each have a different data type
  698. for their values, terminals all use the same data type (defined by
  699. the %token_type directive) and so they use a common destructor. Other
  700. than that, the token destructor works just like the non-terminal
  701. destructors.</p>
  702. <h4>The <tt>%token_prefix</tt> directive</h4>
  703. <p>Lemon generates #defines that assign small integer constants
  704. to each terminal symbol in the grammar. If desired, Lemon will
  705. add a prefix specified by this directive
  706. to each of the #defines it generates.
  707. So if the default output of Lemon looked like this:
  708. <pre>
  709. #define AND 1
  710. #define MINUS 2
  711. #define OR 3
  712. #define PLUS 4
  713. </pre>
  714. You can insert a statement into the grammar like this:
  715. <pre>
  716. %token_prefix TOKEN_
  717. </pre>
  718. to cause Lemon to produce these symbols instead:
  719. <pre>
  720. #define TOKEN_AND 1
  721. #define TOKEN_MINUS 2
  722. #define TOKEN_OR 3
  723. #define TOKEN_PLUS 4
  724. </pre>
  725. <h4>The <tt>%token_type</tt> and <tt>%type</tt> directives</h4>
  726. <p>These directives are used to specify the data types for values
  727. on the parser's stack associated with terminal and non-terminal
  728. symbols. The values of all terminal symbols must be of the same
  729. type. This turns out to be the same data type as the 3rd parameter
  730. to the Parse() function generated by Lemon. Typically, you will
  731. make the value of a terminal symbol by a pointer to some kind of
  732. token structure. Like this:</p>
  733. <p><pre>
  734. %token_type {Token*}
  735. </pre></p>
  736. <p>If the data type of terminals is not specified, the default value
  737. is ``int''.</p>
  738. <p>Non-terminal symbols can each have their own data types. Typically
  739. the data type of a non-terminal is a pointer to the root of a parse-tree
  740. structure that contains all information about that non-terminal.
  741. For example:</p>
  742. <p><pre>
  743. %type expr {Expr*}
  744. </pre></p>
  745. <p>Each entry on the parser's stack is actually a union containing
  746. instances of all data types for every non-terminal and terminal symbol.
  747. Lemon will automatically use the correct element of this union depending
  748. on what the corresponding non-terminal or terminal symbol is. But
  749. the grammar designer should keep in mind that the size of the union
  750. will be the size of its largest element. So if you have a single
  751. non-terminal whose data type requires 1K of storage, then your 100
  752. entry parser stack will require 100K of heap space. If you are willing
  753. and able to pay that price, fine. You just need to know.</p>
  754. <h3>Error Processing</h3>
  755. <p>After extensive experimentation over several years, it has been
  756. discovered that the error recovery strategy used by yacc is about
  757. as good as it gets. And so that is what Lemon uses.</p>
  758. <p>When a Lemon-generated parser encounters a syntax error, it
  759. first invokes the code specified by the %syntax_error directive, if
  760. any. It then enters its error recovery strategy. The error recovery
  761. strategy is to begin popping the parsers stack until it enters a
  762. state where it is permitted to shift a special non-terminal symbol
  763. named ``error''. It then shifts this non-terminal and continues
  764. parsing. But the %syntax_error routine will not be called again
  765. until at least three new tokens have been successfully shifted.</p>
  766. <p>If the parser pops its stack until the stack is empty, and it still
  767. is unable to shift the error symbol, then the %parse_failed routine
  768. is invoked and the parser resets itself to its start state, ready
  769. to begin parsing a new file. This is what will happen at the very
  770. first syntax error, of course, if there are no instances of the
  771. ``error'' non-terminal in your grammar.</p>
  772. </body>
  773. </html>