bison.info-3 50 KB

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