bison.info-3 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. This is Info file bison.info, produced by Makeinfo version 1.67 from
  2. the input file ./bison.texinfo.
  3. This file documents the Bison parser generator.
  4. Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  5. Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8. Permission is granted to copy and distribute modified versions of
  9. this manual under the conditions for verbatim copying, provided also
  10. that the sections entitled "GNU General Public License" and "Conditions
  11. for Using Bison" are included exactly as in the original, and provided
  12. that the entire resulting derived work is distributed under the terms
  13. of a permission notice identical to this one.
  14. Permission is granted to copy and distribute translations of this
  15. manual into another language, under the above conditions for modified
  16. versions, except that the sections entitled "GNU General Public
  17. License", "Conditions for Using Bison" and this permission notice may be
  18. included in translations approved by the Free Software Foundation
  19. instead of in the original English.
  20. 
  21. File: bison.info, Node: Type Decl, Next: Expect Decl, Prev: Union Decl, Up: Declarations
  22. Nonterminal Symbols
  23. -------------------
  24. When you use `%union' to specify multiple value types, you must declare
  25. the value type of each nonterminal symbol for which values are used.
  26. This is done with a `%type' declaration, like this:
  27. %type <TYPE> NONTERMINAL...
  28. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  29. name given in the `%union' to the alternative that you want (*note
  30. Union Decl::.). You can give any number of nonterminal symbols in the
  31. same `%type' declaration, if they have the same value type. Use spaces
  32. to separate the symbol names.
  33. 
  34. File: bison.info, Node: Expect Decl, Next: Start Decl, Prev: Type Decl, Up: Declarations
  35. Suppressing Conflict Warnings
  36. -----------------------------
  37. Bison normally warns if there are any conflicts in the grammar
  38. (*note Shift/Reduce::.), but most real grammars have harmless
  39. shift/reduce conflicts which are resolved in a predictable way and
  40. would be difficult to eliminate. It is desirable to suppress the
  41. warning about these conflicts unless the number of conflicts changes.
  42. You can do this with the `%expect' declaration.
  43. The declaration looks like this:
  44. %expect N
  45. Here N is a decimal integer. The declaration says there should be no
  46. warning if there are N shift/reduce conflicts and no reduce/reduce
  47. conflicts. The usual warning is given if there are either more or fewer
  48. conflicts, or if there are any reduce/reduce conflicts.
  49. In general, using `%expect' involves these steps:
  50. * Compile your grammar without `%expect'. Use the `-v' option to
  51. get a verbose list of where the conflicts occur. Bison will also
  52. print the number of conflicts.
  53. * Check each of the conflicts to make sure that Bison's default
  54. resolution is what you really want. If not, rewrite the grammar
  55. and go back to the beginning.
  56. * Add an `%expect' declaration, copying the number N from the number
  57. which Bison printed.
  58. Now Bison will stop annoying you about the conflicts you have
  59. checked, but it will warn you again if changes in the grammer result in
  60. additional conflicts.
  61. 
  62. File: bison.info, Node: Start Decl, Next: Pure Decl, Prev: Expect Decl, Up: Declarations
  63. The Start-Symbol
  64. ----------------
  65. Bison assumes by default that the start symbol for the grammar is
  66. the first nonterminal specified in the grammar specification section.
  67. The programmer may override this restriction with the `%start'
  68. declaration as follows:
  69. %start SYMBOL
  70. 
  71. File: bison.info, Node: Pure Decl, Next: Decl Summary, Prev: Start Decl, Up: Declarations
  72. A Pure (Reentrant) Parser
  73. -------------------------
  74. A "reentrant" program is one which does not alter in the course of
  75. execution; in other words, it consists entirely of "pure" (read-only)
  76. code. Reentrancy is important whenever asynchronous execution is
  77. possible; for example, a nonreentrant program may not be safe to call
  78. from a signal handler. In systems with multiple threads of control, a
  79. nonreentrant program must be called only within interlocks.
  80. The Bison parser is not normally a reentrant program, because it uses
  81. statically allocated variables for communication with `yylex'. These
  82. variables include `yylval' and `yylloc'.
  83. The Bison declaration `%pure_parser' says that you want the parser
  84. to be reentrant. It looks like this:
  85. %pure_parser
  86. The effect is that the two communication variables become local
  87. variables in `yyparse', and a different calling convention is used for
  88. the lexical analyzer function `yylex'. *Note Pure Calling::, for the
  89. details of this. The variable `yynerrs' also becomes local in
  90. `yyparse' (*note Error Reporting::.). The convention for calling
  91. `yyparse' itself is unchanged.
  92. 
  93. File: bison.info, Node: Decl Summary, Prev: Pure Decl, Up: Declarations
  94. Bison Declaration Summary
  95. -------------------------
  96. Here is a summary of all Bison declarations:
  97. `%union'
  98. Declare the collection of data types that semantic values may have
  99. (*note Union Decl::.).
  100. `%token'
  101. Declare a terminal symbol (token type name) with no precedence or
  102. associativity specified (*note Token Decl::.).
  103. `%right'
  104. Declare a terminal symbol (token type name) that is
  105. right-associative (*note Precedence Decl::.).
  106. `%left'
  107. Declare a terminal symbol (token type name) that is
  108. left-associative (*note Precedence Decl::.).
  109. `%nonassoc'
  110. Declare a terminal symbol (token type name) that is nonassociative
  111. (using it in a way that would be associative is a syntax error)
  112. (*note Precedence Decl::.).
  113. `%type'
  114. Declare the type of semantic values for a nonterminal symbol
  115. (*note Type Decl::.).
  116. `%start'
  117. Specify the grammar's start symbol (*note Start Decl::.).
  118. `%expect'
  119. Declare the expected number of shift-reduce conflicts (*note
  120. Expect Decl::.).
  121. `%pure_parser'
  122. Request a pure (reentrant) parser program (*note Pure Decl::.).
  123. 
  124. File: bison.info, Node: Multiple Parsers, Prev: Declarations, Up: Grammar File
  125. Multiple Parsers in the Same Program
  126. ====================================
  127. Most programs that use Bison parse only one language and therefore
  128. contain only one Bison parser. But what if you want to parse more than
  129. one language with the same program? Then you need to avoid a name
  130. conflict between different definitions of `yyparse', `yylval', and so
  131. on.
  132. The easy way to do this is to use the option `-p PREFIX' (*note
  133. Invocation::.). This renames the interface functions and variables of
  134. the Bison parser to start with PREFIX instead of `yy'. You can use
  135. this to give each parser distinct names that do not conflict.
  136. The precise list of symbols renamed is `yyparse', `yylex',
  137. `yyerror', `yylval', `yychar' and `yydebug'. For example, if you use
  138. `-p c', the names become `cparse', `clex', and so on.
  139. *All the other variables and macros associated with Bison are not
  140. renamed.* These others are not global; there is no conflict if the same
  141. name is used in different parsers. For example, `YYSTYPE' is not
  142. renamed, but defining this in different ways in different parsers causes
  143. no trouble (*note Value Type::.).
  144. The `-p' option works by adding macro definitions to the beginning
  145. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  146. on. This effectively substitutes one name for the other in the entire
  147. parser file.
  148. 
  149. File: bison.info, Node: Interface, Next: Algorithm, Prev: Grammar File, Up: Top
  150. Parser C-Language Interface
  151. ***************************
  152. The Bison parser is actually a C function named `yyparse'. Here we
  153. describe the interface conventions of `yyparse' and the other functions
  154. that it needs to use.
  155. Keep in mind that the parser uses many C identifiers starting with
  156. `yy' and `YY' for internal purposes. If you use such an identifier
  157. (aside from those in this manual) in an action or in additional C code
  158. in the grammar file, you are likely to run into trouble.
  159. * Menu:
  160. * Parser Function:: How to call `yyparse' and what it returns.
  161. * Lexical:: You must supply a function `yylex' which reads tokens.
  162. * Error Reporting:: You must supply a function `yyerror'.
  163. * Action Features:: Special features for use in actions.
  164. 
  165. File: bison.info, Node: Parser Function, Next: Lexical, Prev: Interface, Up: Interface
  166. The Parser Function `yyparse'
  167. =============================
  168. You call the function `yyparse' to cause parsing to occur. This
  169. function reads tokens, executes actions, and ultimately returns when it
  170. encounters end-of-input or an unrecoverable syntax error. You can also
  171. write an action which directs `yyparse' to return immediately without
  172. reading further.
  173. The value returned by `yyparse' is 0 if parsing was successful
  174. (return is due to end-of-input).
  175. The value is 1 if parsing failed (return is due to a syntax error).
  176. In an action, you can cause immediate return from `yyparse' by using
  177. these macros:
  178. `YYACCEPT'
  179. Return immediately with value 0 (to report success).
  180. `YYABORT'
  181. Return immediately with value 1 (to report failure).
  182. 
  183. File: bison.info, Node: Lexical, Next: Error Reporting, Prev: Parser Function, Up: Interface
  184. The Lexical Analyzer Function `yylex'
  185. =====================================
  186. The "lexical analyzer" function, `yylex', recognizes tokens from the
  187. input stream and returns them to the parser. Bison does not create
  188. this function automatically; you must write it so that `yyparse' can
  189. call it. The function is sometimes referred to as a lexical scanner.
  190. In simple programs, `yylex' is often defined at the end of the Bison
  191. grammar file. If `yylex' is defined in a separate source file, you
  192. need to arrange for the token-type macro definitions to be available
  193. there. To do this, use the `-d' option when you run Bison, so that it
  194. will write these macro definitions into a separate header file
  195. `NAME.tab.h' which you can include in the other source files that need
  196. it. *Note Invocation::.
  197. * Menu:
  198. * Calling Convention:: How `yyparse' calls `yylex'.
  199. * Token Values:: How `yylex' must return the semantic value
  200. of the token it has read.
  201. * Token Positions:: How `yylex' must return the text position
  202. (line number, etc.) of the token, if the
  203. actions want that.
  204. * Pure Calling:: How the calling convention differs
  205. in a pure parser (*note Pure Decl::.).
  206. 
  207. File: bison.info, Node: Calling Convention, Next: Token Values, Prev: Lexical, Up: Lexical
  208. Calling Convention for `yylex'
  209. ------------------------------
  210. The value that `yylex' returns must be the numeric code for the type
  211. of token it has just found, or 0 for end-of-input.
  212. When a token is referred to in the grammar rules by a name, that name
  213. in the parser file becomes a C macro whose definition is the proper
  214. numeric code for that token type. So `yylex' can use the name to
  215. indicate that type. *Note Symbols::.
  216. When a token is referred to in the grammar rules by a character
  217. literal, the numeric code for that character is also the code for the
  218. token type. So `yylex' can simply return that character code. The
  219. null character must not be used this way, because its code is zero and
  220. that is what signifies end-of-input.
  221. Here is an example showing these things:
  222. yylex ()
  223. {
  224. ...
  225. if (c == EOF) /* Detect end of file. */
  226. return 0;
  227. ...
  228. if (c == '+' || c == '-')
  229. return c; /* Assume token type for `+' is '+'. */
  230. ...
  231. return INT; /* Return the type of the token. */
  232. ...
  233. }
  234. This interface has been designed so that the output from the `lex'
  235. utility can be used without change as the definition of `yylex'.
  236. 
  237. File: bison.info, Node: Token Values, Next: Token Positions, Prev: Calling Convention, Up: Lexical
  238. Semantic Values of Tokens
  239. -------------------------
  240. In an ordinary (nonreentrant) parser, the semantic value of the
  241. token must be stored into the global variable `yylval'. When you are
  242. using just one data type for semantic values, `yylval' has that type.
  243. Thus, if the type is `int' (the default), you might write this in
  244. `yylex':
  245. ...
  246. yylval = value; /* Put value onto Bison stack. */
  247. return INT; /* Return the type of the token. */
  248. ...
  249. When you are using multiple data types, `yylval''s type is a union
  250. made from the `%union' declaration (*note Union Decl::.). So when you
  251. store a token's value, you must use the proper member of the union. If
  252. the `%union' declaration looks like this:
  253. %union {
  254. int intval;
  255. double val;
  256. symrec *tptr;
  257. }
  258. then the code in `yylex' might look like this:
  259. ...
  260. yylval.intval = value; /* Put value onto Bison stack. */
  261. return INT; /* Return the type of the token. */
  262. ...
  263. 
  264. File: bison.info, Node: Token Positions, Next: Pure Calling, Prev: Token Values, Up: Lexical
  265. Textual Positions of Tokens
  266. ---------------------------
  267. If you are using the `@N'-feature (*note Action Features::.) in
  268. actions to keep track of the textual locations of tokens and groupings,
  269. then you must provide this information in `yylex'. The function
  270. `yyparse' expects to find the textual location of a token just parsed
  271. in the global variable `yylloc'. So `yylex' must store the proper data
  272. in that variable. The value of `yylloc' is a structure and you need
  273. only initialize the members that are going to be used by the actions.
  274. The four members are called `first_line', `first_column', `last_line'
  275. and `last_column'. Note that the use of this feature makes the parser
  276. noticeably slower.
  277. The data type of `yylloc' has the name `YYLTYPE'.
  278. 
  279. File: bison.info, Node: Pure Calling, Prev: Token Positions, Up: Lexical
  280. Calling for Pure Parsers
  281. ------------------------
  282. When you use the Bison declaration `%pure_parser' to request a pure,
  283. reentrant parser, the global communication variables `yylval' and
  284. `yylloc' cannot be used. (*Note Pure Decl::.) In such parsers the two
  285. global variables are replaced by pointers passed as arguments to
  286. `yylex'. You must declare them as shown here, and pass the information
  287. back by storing it through those pointers.
  288. yylex (lvalp, llocp)
  289. YYSTYPE *lvalp;
  290. YYLTYPE *llocp;
  291. {
  292. ...
  293. *lvalp = value; /* Put value onto Bison stack. */
  294. return INT; /* Return the type of the token. */
  295. ...
  296. }
  297. If the grammar file does not use the `@' constructs to refer to
  298. textual positions, then the type `YYLTYPE' will not be defined. In
  299. this case, omit the second argument; `yylex' will be called with only
  300. one argument.
  301. 
  302. File: bison.info, Node: Error Reporting, Next: Action Features, Prev: Lexical, Up: Interface
  303. The Error Reporting Function `yyerror'
  304. ======================================
  305. The Bison parser detects a "parse error" or "syntax error" whenever
  306. it reads a token which cannot satisfy any syntax rule. A action in the
  307. grammar can also explicitly proclaim an error, using the macro
  308. `YYERROR' (*note Action Features::.).
  309. The Bison parser expects to report the error by calling an error
  310. reporting function named `yyerror', which you must supply. It is
  311. called by `yyparse' whenever a syntax error is found, and it receives
  312. one argument. For a parse error, the string is always `"parse error"'.
  313. The parser can detect one other kind of error: stack overflow. This
  314. happens when the input contains constructions that are very deeply
  315. nested. It isn't likely you will encounter this, since the Bison
  316. parser extends its stack automatically up to a very large limit. But
  317. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  318. except that the argument string is `"parser stack overflow"'.
  319. The following definition suffices in simple programs:
  320. yyerror (s)
  321. char *s;
  322. {
  323. fprintf (stderr, "%s\n", s);
  324. }
  325. After `yyerror' returns to `yyparse', the latter will attempt error
  326. recovery if you have written suitable error recovery grammar rules
  327. (*note Error Recovery::.). If recovery is impossible, `yyparse' will
  328. immediately return 1.
  329. The variable `yynerrs' contains the number of syntax errors
  330. encountered so far. Normally this variable is global; but if you
  331. request a pure parser (*note Pure Decl::.) then it is a local variable
  332. which only the actions can access.
  333. 
  334. File: bison.info, Node: Action Features, Prev: Error Reporting, Up: Interface
  335. Special Features for Use in Actions
  336. ===================================
  337. Here is a table of Bison constructs, variables and macros that are
  338. useful in actions.
  339. `$$'
  340. Acts like a variable that contains the semantic value for the
  341. grouping made by the current rule. *Note Actions::.
  342. `$N'
  343. Acts like a variable that contains the semantic value for the Nth
  344. component of the current rule. *Note Actions::.
  345. `$<TYPEALT>$'
  346. Like `$$' but specifies alternative TYPEALT in the union specified
  347. by the `%union' declaration. *Note Action Types::.
  348. `$<TYPEALT>N'
  349. Like `$N' but specifies alternative TYPEALT in the union specified
  350. by the `%union' declaration. *Note Action Types::.
  351. `YYABORT;'
  352. Return immediately from `yyparse', indicating failure. *Note
  353. Parser Function::.
  354. `YYACCEPT;'
  355. Return immediately from `yyparse', indicating success. *Note
  356. Parser Function::.
  357. `YYBACKUP (TOKEN, VALUE);'
  358. Unshift a token. This macro is allowed only for rules that reduce
  359. a single value, and only when there is no look-ahead token. It
  360. installs a look-ahead token with token type TOKEN and semantic
  361. value VALUE; then it discards the value that was going to be
  362. reduced by this rule.
  363. If the macro is used when it is not valid, such as when there is a
  364. look-ahead token already, then it reports a syntax error with a
  365. message `cannot back up' and performs ordinary error recovery.
  366. In either case, the rest of the action is not executed.
  367. `YYEMPTY'
  368. Value stored in `yychar' when there is no look-ahead token.
  369. `YYERROR;'
  370. Cause an immediate syntax error. This statement initiates error
  371. recovery just as if the parser itself had detected an error;
  372. however, it does not call `yyerror', and does not print any
  373. message. If you want to print an error message, call `yyerror'
  374. explicitly before the `YYERROR;' statement. *Note Error
  375. Recovery::.
  376. `YYRECOVERING'
  377. This macro stands for an expression that has the value 1 when the
  378. parser is recovering from a syntax error, and 0 the rest of the
  379. time. *Note Error Recovery::.
  380. `yychar'
  381. Variable containing the current look-ahead token. (In a pure
  382. parser, this is actually a local variable within `yyparse'.) When
  383. there is no look-ahead token, the value `YYEMPTY' is stored in the
  384. variable. *Note Look-Ahead::.
  385. `yyclearin;'
  386. Discard the current look-ahead token. This is useful primarily in
  387. error rules. *Note Error Recovery::.
  388. `yyerrok;'
  389. Resume generating error messages immediately for subsequent syntax
  390. errors. This is useful primarily in error rules. *Note Error
  391. Recovery::.
  392. `@N'
  393. Acts like a structure variable containing information on the line
  394. numbers and column numbers of the Nth component of the current
  395. rule. The structure has four members, like this:
  396. struct {
  397. int first_line, last_line;
  398. int first_column, last_column;
  399. };
  400. Thus, to get the starting line number of the third component, use
  401. `@3.first_line'.
  402. In order for the members of this structure to contain valid
  403. information, you must make `yylex' supply this information about
  404. each token. If you need only certain members, then `yylex' need
  405. only fill in those members.
  406. The use of this feature makes the parser noticeably slower.
  407. 
  408. File: bison.info, Node: Algorithm, Next: Error Recovery, Prev: Interface, Up: Top
  409. The Bison Parser Algorithm
  410. **************************
  411. As Bison reads tokens, it pushes them onto a stack along with their
  412. semantic values. The stack is called the "parser stack". Pushing a
  413. token is traditionally called "shifting".
  414. For example, suppose the infix calculator has read `1 + 5 *', with a
  415. `3' to come. The stack will have four elements, one for each token
  416. that was shifted.
  417. But the stack does not always have an element for each token read.
  418. When the last N tokens and groupings shifted match the components of a
  419. grammar rule, they can be combined according to that rule. This is
  420. called "reduction". Those tokens and groupings are replaced on the
  421. stack by a single grouping whose symbol is the result (left hand side)
  422. of that rule. Running the rule's action is part of the process of
  423. reduction, because this is what computes the semantic value of the
  424. resulting grouping.
  425. For example, if the infix calculator's parser stack contains this:
  426. 1 + 5 * 3
  427. and the next input token is a newline character, then the last three
  428. elements can be reduced to 15 via the rule:
  429. expr: expr '*' expr;
  430. Then the stack contains just these three elements:
  431. 1 + 15
  432. At this point, another reduction can be made, resulting in the single
  433. value 16. Then the newline token can be shifted.
  434. The parser tries, by shifts and reductions, to reduce the entire
  435. input down to a single grouping whose symbol is the grammar's
  436. start-symbol (*note Language and Grammar::.).
  437. This kind of parser is known in the literature as a bottom-up parser.
  438. * Menu:
  439. * Look-Ahead:: Parser looks one token ahead when deciding what to do.
  440. * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
  441. * Precedence:: Operator precedence works by resolving conflicts.
  442. * Contextual Precedence:: When an operator's precedence depends on context.
  443. * Parser States:: The parser is a finite-state-machine with stack.
  444. * Reduce/Reduce:: When two rules are applicable in the same situation.
  445. * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
  446. * Stack Overflow:: What happens when stack gets full. How to avoid it.
  447. 
  448. File: bison.info, Node: Look-Ahead, Next: Shift/Reduce, Prev: Algorithm, Up: Algorithm
  449. Look-Ahead Tokens
  450. =================
  451. The Bison parser does *not* always reduce immediately as soon as the
  452. last N tokens and groupings match a rule. This is because such a
  453. simple strategy is inadequate to handle most languages. Instead, when a
  454. reduction is possible, the parser sometimes "looks ahead" at the next
  455. token in order to decide what to do.
  456. When a token is read, it is not immediately shifted; first it
  457. becomes the "look-ahead token", which is not on the stack. Now the
  458. parser can perform one or more reductions of tokens and groupings on
  459. the stack, while the look-ahead token remains off to the side. When no
  460. more reductions should take place, the look-ahead token is shifted onto
  461. the stack. This does not mean that all possible reductions have been
  462. done; depending on the token type of the look-ahead token, some rules
  463. may choose to delay their application.
  464. Here is a simple case where look-ahead is needed. These three rules
  465. define expressions which contain binary addition operators and postfix
  466. unary factorial operators (`!'), and allow parentheses for grouping.
  467. expr: term '+' expr
  468. | term
  469. ;
  470. term: '(' expr ')'
  471. | term '!'
  472. | NUMBER
  473. ;
  474. Suppose that the tokens `1 + 2' have been read and shifted; what
  475. should be done? If the following token is `)', then the first three
  476. tokens must be reduced to form an `expr'. This is the only valid
  477. course, because shifting the `)' would produce a sequence of symbols
  478. `term ')'', and no rule allows this.
  479. If the following token is `!', then it must be shifted immediately so
  480. that `2 !' can be reduced to make a `term'. If instead the parser were
  481. to reduce before shifting, `1 + 2' would become an `expr'. It would
  482. then be impossible to shift the `!' because doing so would produce on
  483. the stack the sequence of symbols `expr '!''. No rule allows that
  484. sequence.
  485. The current look-ahead token is stored in the variable `yychar'.
  486. *Note Action Features::.
  487. 
  488. File: bison.info, Node: Shift/Reduce, Next: Precedence, Prev: Look-Ahead, Up: Algorithm
  489. Shift/Reduce Conflicts
  490. ======================
  491. Suppose we are parsing a language which has if-then and if-then-else
  492. statements, with a pair of rules like this:
  493. if_stmt:
  494. IF expr THEN stmt
  495. | IF expr THEN stmt ELSE stmt
  496. ;
  497. (Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  498. specific keyword tokens.)
  499. When the `ELSE' token is read and becomes the look-ahead token, the
  500. contents of the stack (assuming the input is valid) are just right for
  501. reduction by the first rule. But it is also legitimate to shift the
  502. `ELSE', because that would lead to eventual reduction by the second
  503. rule.
  504. This situation, where either a shift or a reduction would be valid,
  505. is called a "shift/reduce conflict". Bison is designed to resolve these
  506. conflicts by choosing to shift, unless otherwise directed by operator
  507. precedence declarations. To see the reason for this, let's contrast it
  508. with the other alternative.
  509. Since the parser prefers to shift the `ELSE', the result is to attach
  510. the else-clause to the innermost if-statement, making these two inputs
  511. equivalent:
  512. if x then if y then win (); else lose;
  513. if x then do; if y then win (); else lose; end;
  514. But if the parser chose to reduce when possible rather than shift,
  515. the result would be to attach the else-clause to the outermost
  516. if-statement, making these two inputs equivalent:
  517. if x then if y then win (); else lose;
  518. if x then do; if y then win (); end; else lose;
  519. The conflict exists because the grammar as written is ambiguous:
  520. either parsing of the simple nested if-statement is legitimate. The
  521. established convention is that these ambiguities are resolved by
  522. attaching the else-clause to the innermost if-statement; this is what
  523. Bison accomplishes by choosing to shift rather than reduce. (It would
  524. ideally be cleaner to write an unambiguous grammar, but that is very
  525. hard to do in this case.) This particular ambiguity was first
  526. encountered in the specifications of Algol 60 and is called the
  527. "dangling `else'" ambiguity.
  528. To avoid warnings from Bison about predictable, legitimate
  529. shift/reduce conflicts, use the `%expect N' declaration. There will be
  530. no warning as long as the number of shift/reduce conflicts is exactly N.
  531. *Note Expect Decl::.
  532. 
  533. File: bison.info, Node: Precedence, Next: Contextual Precedence, Prev: Shift/Reduce, Up: Algorithm
  534. Operator Precedence
  535. ===================
  536. Another situation where shift/reduce conflicts appear is in
  537. arithmetic expressions. Here shifting is not always the preferred
  538. resolution; the Bison declarations for operator precedence allow you to
  539. specify when to shift and when to reduce.
  540. * Menu:
  541. * Why Precedence:: An example showing why precedence is needed.
  542. * Using Precedence:: How to specify precedence in Bison grammars.
  543. * Precedence Examples:: How these features are used in the previous example.
  544. * How Precedence:: How they work.
  545. 
  546. File: bison.info, Node: Why Precedence, Next: Using Precedence, Prev: Precedence, Up: Precedence
  547. When Precedence is Needed
  548. -------------------------
  549. Consider the following ambiguous grammar fragment (ambiguous because
  550. the input `1 - 2 * 3' can be parsed in two different ways):
  551. expr: expr '-' expr
  552. | expr '*' expr
  553. | expr '<' expr
  554. | '(' expr ')'
  555. ...
  556. ;
  557. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  558. reduce them via the rule for the addition operator? It depends on the
  559. next token. Of course, if the next token is `)', we must reduce;
  560. shifting is invalid because no single rule can reduce the token
  561. sequence `- 2 )' or anything starting with that. But if the next token
  562. is `*' or `<', we have a choice: either shifting or reduction would
  563. allow the parse to complete, but with different results.
  564. To decide which one Bison should do, we must consider the results.
  565. If the next operator token OP is shifted, then it must be reduced first
  566. in order to permit another opportunity to reduce the sum. The result
  567. is (in effect) `1 - (2 OP 3)'. On the other hand, if the subtraction
  568. is reduced before shifting OP, the result is `(1 - 2) OP 3'. Clearly,
  569. then, the choice of shift or reduce should depend on the relative
  570. precedence of the operators `-' and OP: `*' should be shifted first,
  571. but not `<'.
  572. What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  573. or should it be `1 - (2 - 5)'? For most operators we prefer the
  574. former, which is called "left association". The latter alternative,
  575. "right association", is desirable for assignment operators. The choice
  576. of left or right association is a matter of whether the parser chooses
  577. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  578. token is `-': shifting makes right-associativity.
  579. 
  580. File: bison.info, Node: Using Precedence, Next: Precedence Examples, Prev: Why Precedence, Up: Precedence
  581. Specifying Operator Precedence
  582. ------------------------------
  583. Bison allows you to specify these choices with the operator
  584. precedence declarations `%left' and `%right'. Each such declaration
  585. contains a list of tokens, which are operators whose precedence and
  586. associativity is being declared. The `%left' declaration makes all
  587. those operators left-associative and the `%right' declaration makes
  588. them right-associative. A third alternative is `%nonassoc', which
  589. declares that it is a syntax error to find the same operator twice "in a
  590. row".
  591. The relative precedence of different operators is controlled by the
  592. order in which they are declared. The first `%left' or `%right'
  593. declaration in the file declares the operators whose precedence is
  594. lowest, the next such declaration declares the operators whose
  595. precedence is a little higher, and so on.
  596. 
  597. File: bison.info, Node: Precedence Examples, Next: How Precedence, Prev: Using Precedence, Up: Precedence
  598. Precedence Examples
  599. -------------------
  600. In our example, we would want the following declarations:
  601. %left '<'
  602. %left '-'
  603. %left '*'
  604. In a more complete example, which supports other operators as well,
  605. we would declare them in groups of equal precedence. For example,
  606. `'+'' is declared with `'-'':
  607. %left '<' '>' '=' NE LE GE
  608. %left '+' '-'
  609. %left '*' '/'
  610. (Here `NE' and so on stand for the operators for "not equal" and so on.
  611. We assume that these tokens are more than one character long and
  612. therefore are represented by names, not character literals.)
  613. 
  614. File: bison.info, Node: How Precedence, Prev: Precedence Examples, Up: Precedence
  615. How Precedence Works
  616. --------------------
  617. The first effect of the precedence declarations is to assign
  618. precedence levels to the terminal symbols declared. The second effect
  619. is to assign precedence levels to certain rules: each rule gets its
  620. precedence from the last terminal symbol mentioned in the components.
  621. (You can also specify explicitly the precedence of a rule. *Note
  622. Contextual Precedence::.)
  623. Finally, the resolution of conflicts works by comparing the
  624. precedence of the rule being considered with that of the look-ahead
  625. token. If the token's precedence is higher, the choice is to shift.
  626. If the rule's precedence is higher, the choice is to reduce. If they
  627. have equal precedence, the choice is made based on the associativity of
  628. that precedence level. The verbose output file made by `-v' (*note
  629. Invocation::.) says how each conflict was resolved.
  630. Not all rules and not all tokens have precedence. If either the
  631. rule or the look-ahead token has no precedence, then the default is to
  632. shift.
  633. 
  634. File: bison.info, Node: Contextual Precedence, Next: Parser States, Prev: Precedence, Up: Algorithm
  635. Context-Dependent Precedence
  636. ============================
  637. Often the precedence of an operator depends on the context. This
  638. sounds outlandish at first, but it is really very common. For example,
  639. a minus sign typically has a very high precedence as a unary operator,
  640. and a somewhat lower precedence (lower than multiplication) as a binary
  641. operator.
  642. The Bison precedence declarations, `%left', `%right' and
  643. `%nonassoc', can only be used once for a given token; so a token has
  644. only one precedence declared in this way. For context-dependent
  645. precedence, you need to use an additional mechanism: the `%prec'
  646. modifier for rules.
  647. The `%prec' modifier declares the precedence of a particular rule by
  648. specifying a terminal symbol whose precedence should be used for that
  649. rule. It's not necessary for that symbol to appear otherwise in the
  650. rule. The modifier's syntax is:
  651. %prec TERMINAL-SYMBOL
  652. and it is written after the components of the rule. Its effect is to
  653. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  654. precedence that would be deduced for it in the ordinary way. The
  655. altered rule precedence then affects how conflicts involving that rule
  656. are resolved (*note Precedence::.).
  657. Here is how `%prec' solves the problem of unary minus. First,
  658. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  659. There are no tokens of this type, but the symbol serves to stand for its
  660. precedence:
  661. ...
  662. %left '+' '-'
  663. %left '*'
  664. %left UMINUS
  665. Now the precedence of `UMINUS' can be used in specific rules:
  666. exp: ...
  667. | exp '-' exp
  668. ...
  669. | '-' exp %prec UMINUS
  670. 
  671. File: bison.info, Node: Parser States, Next: Reduce/Reduce, Prev: Contextual Precedence, Up: Algorithm
  672. Parser States
  673. =============
  674. The function `yyparse' is implemented using a finite-state machine.
  675. The values pushed on the parser stack are not simply token type codes;
  676. they represent the entire sequence of terminal and nonterminal symbols
  677. at or near the top of the stack. The current state collects all the
  678. information about previous input which is relevant to deciding what to
  679. do next.
  680. Each time a look-ahead token is read, the current parser state
  681. together with the type of look-ahead token are looked up in a table.
  682. This table entry can say, "Shift the look-ahead token." In this case,
  683. it also specifies the new parser state, which is pushed onto the top of
  684. the parser stack. Or it can say, "Reduce using rule number N." This
  685. means that a certain of tokens or groupings are taken off the top of
  686. the stack, and replaced by one grouping. In other words, that number
  687. of states are popped from the stack, and one new state is pushed.
  688. There is one other alternative: the table can say that the
  689. look-ahead token is erroneous in the current state. This causes error
  690. processing to begin (*note Error Recovery::.).
  691. 
  692. File: bison.info, Node: Reduce/Reduce, Next: Mystery Conflicts, Prev: Parser States, Up: Algorithm
  693. Reduce/Reduce Conflicts
  694. =======================
  695. A reduce/reduce conflict occurs if there are two or more rules that
  696. apply to the same sequence of input. This usually indicates a serious
  697. error in the grammar.
  698. For example, here is an erroneous attempt to define a sequence of
  699. zero or more `word' groupings.
  700. sequence: /* empty */
  701. { printf ("empty sequence\n"); }
  702. | word
  703. { printf ("single word %s\n", $1); }
  704. | sequence word
  705. { printf ("added word %s\n", $2); }
  706. ;
  707. The error is an ambiguity: there is more than one way to parse a single
  708. `word' into a `sequence'. It could be reduced directly via the second
  709. rule. Alternatively, nothing-at-all could be reduced into a `sequence'
  710. via the first rule, and this could be combined with the `word' using
  711. the third rule.
  712. You might think that this is a distinction without a difference,
  713. because it does not change whether any particular input is valid or
  714. not. But it does affect which actions are run. One parsing order runs
  715. the second rule's action; the other runs the first rule's action and
  716. the third rule's action. In this example, the output of the program
  717. changes.
  718. Bison resolves a reduce/reduce conflict by choosing to use the rule
  719. that appears first in the grammar, but it is very risky to rely on
  720. this. Every reduce/reduce conflict must be studied and usually
  721. eliminated. Here is the proper way to define `sequence':
  722. sequence: /* empty */
  723. { printf ("empty sequence\n"); }
  724. | sequence word
  725. { printf ("added word %s\n", $2); }
  726. ;
  727. Here is another common error that yields a reduce/reduce conflict:
  728. sequence: /* empty */
  729. | sequence words
  730. | sequence redirects
  731. ;
  732. words: /* empty */
  733. | words word
  734. ;
  735. redirects:/* empty */
  736. | redirects redirect
  737. ;
  738. The intention here is to define a sequence which can contain either
  739. `word' or `redirect' groupings. The individual definitions of
  740. `sequence', `words' and `redirects' are error-free, but the three
  741. together make a subtle ambiguity: even an empty input can be parsed in
  742. infinitely many ways!
  743. Consider: nothing-at-all could be a `words'. Or it could be two
  744. `words' in a row, or three, or any number. It could equally well be a
  745. `redirects', or two, or any number. Or it could be a `words' followed
  746. by three `redirects' and another `words'. And so on.
  747. Here are two ways to correct these rules. First, to make it a
  748. single level of sequence:
  749. sequence: /* empty */
  750. | sequence word
  751. | sequence redirect
  752. ;
  753. Second, to prevent either a `words' or a `redirects' from being
  754. empty:
  755. sequence: /* empty */
  756. | sequence words
  757. | sequence redirects
  758. ;
  759. words: word
  760. | words word
  761. ;
  762. redirects:redirect
  763. | redirects redirect
  764. ;
  765. 
  766. File: bison.info, Node: Mystery Conflicts, Next: Stack Overflow, Prev: Reduce/Reduce, Up: Algorithm
  767. Mysterious Reduce/Reduce Conflicts
  768. ==================================
  769. Sometimes reduce/reduce conflicts can occur that don't look
  770. warranted. Here is an example:
  771. %token ID
  772. %%
  773. def: param_spec return_spec ','
  774. ;
  775. param_spec:
  776. type
  777. | name_list ':' type
  778. ;
  779. return_spec:
  780. type
  781. | name ':' type
  782. ;
  783. type: ID
  784. ;
  785. name: ID
  786. ;
  787. name_list:
  788. name
  789. | name ',' name_list
  790. ;
  791. It would seem that this grammar can be parsed with only a single
  792. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  793. `name' if a comma or colon follows, or a `type' if another `ID'
  794. follows. In other words, this grammar is LR(1).
  795. However, Bison, like most parser generators, cannot actually handle
  796. all LR(1) grammars. In this grammar, two contexts, that after an `ID'
  797. at the beginning of a `param_spec' and likewise at the beginning of a
  798. `return_spec', are similar enough that Bison assumes they are the same.
  799. They appear similar because the same set of rules would be active--the
  800. rule for reducing to a `name' and that for reducing to a `type'. Bison
  801. is unable to determine at that stage of processing that the rules would
  802. require different look-ahead tokens in the two contexts, so it makes a
  803. single parser state for them both. Combining the two contexts causes a
  804. conflict later. In parser terminology, this occurrence means that the
  805. grammar is not LALR(1).
  806. In general, it is better to fix deficiencies than to document them.
  807. But this particular deficiency is intrinsically hard to fix; parser
  808. generators that can handle LR(1) grammars are hard to write and tend to
  809. produce parsers that are very large. In practice, Bison is more useful
  810. as it is now.
  811. When the problem arises, you can often fix it by identifying the two
  812. parser states that are being confused, and adding something to make them
  813. look distinct. In the above example, adding one rule to `return_spec'
  814. as follows makes the problem go away:
  815. %token BOGUS
  816. ...
  817. %%
  818. ...
  819. return_spec:
  820. type
  821. | name ':' type
  822. /* This rule is never used. */
  823. | ID BOGUS
  824. ;
  825. This corrects the problem because it introduces the possibility of an
  826. additional active rule in the context after the `ID' at the beginning of
  827. `return_spec'. This rule is not active in the corresponding context in
  828. a `param_spec', so the two contexts receive distinct parser states. As
  829. long as the token `BOGUS' is never generated by `yylex', the added rule
  830. cannot alter the way actual input is parsed.
  831. In this particular example, there is another way to solve the
  832. problem: rewrite the rule for `return_spec' to use `ID' directly
  833. instead of via `name'. This also causes the two confusing contexts to
  834. have different sets of active rules, because the one for `return_spec'
  835. activates the altered rule for `return_spec' rather than the one for
  836. `name'.
  837. param_spec:
  838. type
  839. | name_list ':' type
  840. ;
  841. return_spec:
  842. type
  843. | ID ':' type
  844. ;
  845. 
  846. File: bison.info, Node: Stack Overflow, Prev: Mystery Conflicts, Up: Algorithm
  847. Stack Overflow, and How to Avoid It
  848. ===================================
  849. The Bison parser stack can overflow if too many tokens are shifted
  850. and not reduced. When this happens, the parser function `yyparse'
  851. returns a nonzero value, pausing only to call `yyerror' to report the
  852. overflow.
  853. By defining the macro `YYMAXDEPTH', you can control how deep the
  854. parser stack can become before a stack overflow occurs. Define the
  855. macro with a value that is an integer. This value is the maximum number
  856. of tokens that can be shifted (and not reduced) before overflow. It
  857. must be a constant expression whose value is known at compile time.
  858. The stack space allowed is not necessarily allocated. If you
  859. specify a large value for `YYMAXDEPTH', the parser actually allocates a
  860. small stack at first, and then makes it bigger by stages as needed.
  861. This increasing allocation happens automatically and silently.
  862. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  863. to save space for ordinary inputs that do not need much stack.
  864. The default value of `YYMAXDEPTH', if you do not define it, is 10000.
  865. You can control how much stack is allocated initially by defining the
  866. macro `YYINITDEPTH'. This value too must be a compile-time constant
  867. integer. The default is 200.
  868. 
  869. File: bison.info, Node: Error Recovery, Next: Context Dependency, Prev: Algorithm, Up: Top
  870. Error Recovery
  871. **************
  872. It is not usually acceptable to have a program terminate on a parse
  873. error. For example, a compiler should recover sufficiently to parse the
  874. rest of the input file and check it for errors; a calculator should
  875. accept another expression.
  876. In a simple interactive command parser where each input is one line,
  877. it may be sufficient to allow `yyparse' to return 1 on error and have
  878. the caller ignore the rest of the input line when that happens (and
  879. then call `yyparse' again). But this is inadequate for a compiler,
  880. because it forgets all the syntactic context leading up to the error.
  881. A syntax error deep within a function in the compiler input should not
  882. cause the compiler to treat the following line like the beginning of a
  883. source file.
  884. You can define how to recover from a syntax error by writing rules to
  885. recognize the special token `error'. This is a terminal symbol that is
  886. always defined (you need not declare it) and reserved for error
  887. handling. The Bison parser generates an `error' token whenever a
  888. syntax error happens; if you have provided a rule to recognize this
  889. token in the current context, the parse can continue.
  890. For example:
  891. stmnts: /* empty string */
  892. | stmnts '\n'
  893. | stmnts exp '\n'
  894. | stmnts error '\n'
  895. The fourth rule in this example says that an error followed by a
  896. newline makes a valid addition to any `stmnts'.
  897. What happens if a syntax error occurs in the middle of an `exp'? The
  898. error recovery rule, interpreted strictly, applies to the precise
  899. sequence of a `stmnts', an `error' and a newline. If an error occurs in
  900. the middle of an `exp', there will probably be some additional tokens
  901. and subexpressions on the stack after the last `stmnts', and there will
  902. be tokens to read before the next newline. So the rule is not
  903. applicable in the ordinary way.
  904. But Bison can force the situation to fit the rule, by discarding
  905. part of the semantic context and part of the input. First it discards
  906. states and objects from the stack until it gets back to a state in
  907. which the `error' token is acceptable. (This means that the
  908. subexpressions already parsed are discarded, back to the last complete
  909. `stmnts'.) At this point the `error' token can be shifted. Then, if
  910. the old look-ahead token is not acceptable to be shifted next, the
  911. parser reads tokens and discards them until it finds a token which is
  912. acceptable. In this example, Bison reads and discards input until the
  913. next newline so that the fourth rule can apply.
  914. The choice of error rules in the grammar is a choice of strategies
  915. for error recovery. A simple and useful strategy is simply to skip the
  916. rest of the current input line or current statement if an error is
  917. detected:
  918. stmnt: error ';' /* on error, skip until ';' is read */
  919. It is also useful to recover to the matching close-delimiter of an
  920. opening-delimiter that has already been parsed. Otherwise the
  921. close-delimiter will probably appear to be unmatched, and generate
  922. another, spurious error message:
  923. primary: '(' expr ')'
  924. | '(' error ')'
  925. ...
  926. ;
  927. Error recovery strategies are necessarily guesses. When they guess
  928. wrong, one syntax error often leads to another. In the above example,
  929. the error recovery rule guesses that an error is due to bad input
  930. within one `stmnt'. Suppose that instead a spurious semicolon is
  931. inserted in the middle of a valid `stmnt'. After the error recovery
  932. rule recovers from the first error, another syntax error will be found
  933. straightaway, since the text following the spurious semicolon is also
  934. an invalid `stmnt'.
  935. To prevent an outpouring of error messages, the parser will output
  936. no error message for another syntax error that happens shortly after
  937. the first; only after three consecutive input tokens have been
  938. successfully shifted will error messages resume.
  939. Note that rules which accept the `error' token may have actions, just
  940. as any other rules can.
  941. You can make error messages resume immediately by using the macro
  942. `yyerrok' in an action. If you do this in the error rule's action, no
  943. error messages will be suppressed. This macro requires no arguments;
  944. `yyerrok;' is a valid C statement.
  945. The previous look-ahead token is reanalyzed immediately after an
  946. error. If this is unacceptable, then the macro `yyclearin' may be used
  947. to clear this token. Write the statement `yyclearin;' in the error
  948. rule's action.
  949. For example, suppose that on a parse error, an error handling
  950. routine is called that advances the input stream to some point where
  951. parsing should once again commence. The next symbol returned by the
  952. lexical scanner is probably correct. The previous look-ahead token
  953. ought to be discarded with `yyclearin;'.
  954. The macro `YYRECOVERING' stands for an expression that has the value
  955. 1 when the parser is recovering from a syntax error, and 0 the rest of
  956. the time. A value of 1 indicates that error messages are currently
  957. suppressed for new syntax errors.
  958. 
  959. File: bison.info, Node: Context Dependency, Next: Debugging, Prev: Error Recovery, Up: Top
  960. Handling Context Dependencies
  961. *****************************
  962. The Bison paradigm is to parse tokens first, then group them into
  963. larger syntactic units. In many languages, the meaning of a token is
  964. affected by its context. Although this violates the Bison paradigm,
  965. certain techniques (known as "kludges") may enable you to write Bison
  966. parsers for such languages.
  967. * Menu:
  968. * Semantic Tokens:: Token parsing can depend on the semantic context.
  969. * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
  970. * Tie-in Recovery:: Lexical tie-ins have implications for how
  971. error recovery rules must be written.
  972. (Actually, "kludge" means any technique that gets its job done but is
  973. neither clean nor robust.)