bison.info-1 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. This is Info file bison.info, produced by Makeinfo-1.55 from the input
  2. file ./bison.texinfo.
  3. This file documents the Bison parser generator.
  4. Copyright (C) 1988, 89, 90, 91, 92, 93, 1995 Free Software
  5. Foundation, 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: Top, Next: Introduction, Prev: (dir), Up: (dir)
  23. This manual documents version 1.24 of Bison.
  24. * Menu:
  25. * Introduction::
  26. * Conditions::
  27. * Copying:: The GNU General Public License says
  28. how you can copy and share Bison
  29. Tutorial sections:
  30. * Concepts:: Basic concepts for understanding Bison.
  31. * Examples:: Three simple explained examples of using Bison.
  32. Reference sections:
  33. * Grammar File:: Writing Bison declarations and rules.
  34. * Interface:: C-language interface to the parser function `yyparse'.
  35. * Algorithm:: How the Bison parser works at run-time.
  36. * Error Recovery:: Writing rules for error recovery.
  37. * Context Dependency:: What to do if your language syntax is too
  38. messy for Bison to handle straightforwardly.
  39. * Debugging:: Debugging Bison parsers that parse wrong.
  40. * Invocation:: How to run Bison (to produce the parser source file).
  41. * Table of Symbols:: All the keywords of the Bison language are explained.
  42. * Glossary:: Basic concepts are explained.
  43. * Index:: Cross-references to the text.
  44. -- The Detailed Node Listing --
  45. The Concepts of Bison
  46. * Language and Grammar:: Languages and context-free grammars,
  47. as mathematical ideas.
  48. * Grammar in Bison:: How we represent grammars for Bison's sake.
  49. * Semantic Values:: Each token or syntactic grouping can have
  50. a semantic value (the value of an integer,
  51. the name of an identifier, etc.).
  52. * Semantic Actions:: Each rule can have an action containing C code.
  53. * Bison Parser:: What are Bison's input and output,
  54. how is the output used?
  55. * Stages:: Stages in writing and running Bison grammars.
  56. * Grammar Layout:: Overall structure of a Bison grammar file.
  57. Examples
  58. * RPN Calc:: Reverse polish notation calculator;
  59. a first example with no operator precedence.
  60. * Infix Calc:: Infix (algebraic) notation calculator.
  61. Operator precedence is introduced.
  62. * Simple Error Recovery:: Continuing after syntax errors.
  63. * Multi-function Calc:: Calculator with memory and trig functions.
  64. It uses multiple data-types for semantic values.
  65. * Exercises:: Ideas for improving the multi-function calculator.
  66. Reverse Polish Notation Calculator
  67. * Decls: Rpcalc Decls. Bison and C declarations for rpcalc.
  68. * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
  69. * Lexer: Rpcalc Lexer. The lexical analyzer.
  70. * Main: Rpcalc Main. The controlling function.
  71. * Error: Rpcalc Error. The error reporting function.
  72. * Gen: Rpcalc Gen. Running Bison on the grammar file.
  73. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  74. Grammar Rules for `rpcalc'
  75. * Rpcalc Input::
  76. * Rpcalc Line::
  77. * Rpcalc Expr::
  78. Multi-Function Calculator: `mfcalc'
  79. * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
  80. * Rules: Mfcalc Rules. Grammar rules for the calculator.
  81. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  82. Bison Grammar Files
  83. * Grammar Outline:: Overall layout of the grammar file.
  84. * Symbols:: Terminal and nonterminal symbols.
  85. * Rules:: How to write grammar rules.
  86. * Recursion:: Writing recursive rules.
  87. * Semantics:: Semantic values and actions.
  88. * Declarations:: All kinds of Bison declarations are described here.
  89. * Multiple Parsers:: Putting more than one Bison parser in one program.
  90. Outline of a Bison Grammar
  91. * C Declarations:: Syntax and usage of the C declarations section.
  92. * Bison Declarations:: Syntax and usage of the Bison declarations section.
  93. * Grammar Rules:: Syntax and usage of the grammar rules section.
  94. * C Code:: Syntax and usage of the additional C code section.
  95. Defining Language Semantics
  96. * Value Type:: Specifying one data type for all semantic values.
  97. * Multiple Types:: Specifying several alternative data types.
  98. * Actions:: An action is the semantic definition of a grammar rule.
  99. * Action Types:: Specifying data types for actions to operate on.
  100. * Mid-Rule Actions:: Most actions go at the end of a rule.
  101. This says when, why and how to use the exceptional
  102. action in the middle of a rule.
  103. Bison Declarations
  104. * Token Decl:: Declaring terminal symbols.
  105. * Precedence Decl:: Declaring terminals with precedence and associativity.
  106. * Union Decl:: Declaring the set of all semantic value types.
  107. * Type Decl:: Declaring the choice of type for a nonterminal symbol.
  108. * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
  109. * Start Decl:: Specifying the start symbol.
  110. * Pure Decl:: Requesting a reentrant parser.
  111. * Decl Summary:: Table of all Bison declarations.
  112. Parser C-Language Interface
  113. * Parser Function:: How to call `yyparse' and what it returns.
  114. * Lexical:: You must supply a function `yylex'
  115. which reads tokens.
  116. * Error Reporting:: You must supply a function `yyerror'.
  117. * Action Features:: Special features for use in actions.
  118. The Lexical Analyzer Function `yylex'
  119. * Calling Convention:: How `yyparse' calls `yylex'.
  120. * Token Values:: How `yylex' must return the semantic value
  121. of the token it has read.
  122. * Token Positions:: How `yylex' must return the text position
  123. (line number, etc.) of the token, if the
  124. actions want that.
  125. * Pure Calling:: How the calling convention differs
  126. in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  127. The Bison Parser Algorithm
  128. * Look-Ahead:: Parser looks one token ahead when deciding what to do.
  129. * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
  130. * Precedence:: Operator precedence works by resolving conflicts.
  131. * Contextual Precedence:: When an operator's precedence depends on context.
  132. * Parser States:: The parser is a finite-state-machine with stack.
  133. * Reduce/Reduce:: When two rules are applicable in the same situation.
  134. * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
  135. * Stack Overflow:: What happens when stack gets full. How to avoid it.
  136. Operator Precedence
  137. * Why Precedence:: An example showing why precedence is needed.
  138. * Using Precedence:: How to specify precedence in Bison grammars.
  139. * Precedence Examples:: How these features are used in the previous example.
  140. * How Precedence:: How they work.
  141. Handling Context Dependencies
  142. * Semantic Tokens:: Token parsing can depend on the semantic context.
  143. * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
  144. * Tie-in Recovery:: Lexical tie-ins have implications for how
  145. error recovery rules must be written.
  146. Invoking Bison
  147. * Bison Options:: All the options described in detail,
  148. in alphabetical order by short options.
  149. * Option Cross Key:: Alphabetical list of long options.
  150. * VMS Invocation:: Bison command syntax on VMS.
  151. 
  152. File: bison.info, Node: Introduction, Next: Conditions, Prev: Top, Up: Top
  153. Introduction
  154. ************
  155. "Bison" is a general-purpose parser generator that converts a
  156. grammar description for an LALR(1) context-free grammar into a C
  157. program to parse that grammar. Once you are proficient with Bison, you
  158. may use it to develop a wide range of language parsers, from those used
  159. in simple desk calculators to complex programming languages.
  160. Bison is upward compatible with Yacc: all properly-written Yacc
  161. grammars ought to work with Bison with no change. Anyone familiar with
  162. Yacc should be able to use Bison with little trouble. You need to be
  163. fluent in C programming in order to use Bison or to understand this
  164. manual.
  165. We begin with tutorial chapters that explain the basic concepts of
  166. using Bison and show three explained examples, each building on the
  167. last. If you don't know Bison or Yacc, start by reading these
  168. chapters. Reference chapters follow which describe specific aspects of
  169. Bison in detail.
  170. Bison was written primarily by Robert Corbett; Richard Stallman made
  171. it Yacc-compatible. This edition corresponds to version 1.24 of Bison.
  172. 
  173. File: bison.info, Node: Conditions, Next: Copying, Prev: Introduction, Up: Top
  174. Conditions for Using Bison
  175. **************************
  176. As of Bison version 1.24, we have changed the distribution terms for
  177. `yyparse' to permit using Bison's output in non-free programs.
  178. Formerly, Bison parsers could be used only in programs that were free
  179. software.
  180. The other GNU programming tools, such as the GNU C compiler, have
  181. never had such a requirement. They could always be used for non-free
  182. software. The reason Bison was different was not due to a special
  183. policy decision; it resulted from applying the usual General Public
  184. License to all of the Bison source code.
  185. The output of the Bison utility--the Bison parser file--contains a
  186. verbatim copy of a sizable piece of Bison, which is the code for the
  187. `yyparse' function. (The actions from your grammar are inserted into
  188. this function at one point, but the rest of the function is not
  189. changed.) When we applied the GPL terms to the code for `yyparse', the
  190. effect was to restrict the use of Bison output to free software.
  191. We didn't change the terms because of sympathy for people who want to
  192. make software proprietary. *Software should be free.* But we
  193. concluded that limiting Bison's use to free software was doing little to
  194. encourage people to make other software free. So we decided to make the
  195. practical conditions for using Bison match the practical conditions for
  196. using the other GNU tools.
  197. 
  198. File: bison.info, Node: Copying, Next: Concepts, Prev: Conditions, Up: Top
  199. GNU GENERAL PUBLIC LICENSE
  200. **************************
  201. Version 2, June 1991
  202. Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  203. 675 Mass Ave, Cambridge, MA 02139, USA
  204. Everyone is permitted to copy and distribute verbatim copies
  205. of this license document, but changing it is not allowed.
  206. Preamble
  207. ========
  208. The licenses for most software are designed to take away your
  209. freedom to share and change it. By contrast, the GNU General Public
  210. License is intended to guarantee your freedom to share and change free
  211. software--to make sure the software is free for all its users. This
  212. General Public License applies to most of the Free Software
  213. Foundation's software and to any other program whose authors commit to
  214. using it. (Some other Free Software Foundation software is covered by
  215. the GNU Library General Public License instead.) You can apply it to
  216. your programs, too.
  217. When we speak of free software, we are referring to freedom, not
  218. price. Our General Public Licenses are designed to make sure that you
  219. have the freedom to distribute copies of free software (and charge for
  220. this service if you wish), that you receive source code or can get it
  221. if you want it, that you can change the software or use pieces of it in
  222. new free programs; and that you know you can do these things.
  223. To protect your rights, we need to make restrictions that forbid
  224. anyone to deny you these rights or to ask you to surrender the rights.
  225. These restrictions translate to certain responsibilities for you if you
  226. distribute copies of the software, or if you modify it.
  227. For example, if you distribute copies of such a program, whether
  228. gratis or for a fee, you must give the recipients all the rights that
  229. you have. You must make sure that they, too, receive or can get the
  230. source code. And you must show them these terms so they know their
  231. rights.
  232. We protect your rights with two steps: (1) copyright the software,
  233. and (2) offer you this license which gives you legal permission to copy,
  234. distribute and/or modify the software.
  235. Also, for each author's protection and ours, we want to make certain
  236. that everyone understands that there is no warranty for this free
  237. software. If the software is modified by someone else and passed on, we
  238. want its recipients to know that what they have is not the original, so
  239. that any problems introduced by others will not reflect on the original
  240. authors' reputations.
  241. Finally, any free program is threatened constantly by software
  242. patents. We wish to avoid the danger that redistributors of a free
  243. program will individually obtain patent licenses, in effect making the
  244. program proprietary. To prevent this, we have made it clear that any
  245. patent must be licensed for everyone's free use or not licensed at all.
  246. The precise terms and conditions for copying, distribution and
  247. modification follow.
  248. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  249. 0. This License applies to any program or other work which contains a
  250. notice placed by the copyright holder saying it may be distributed
  251. under the terms of this General Public License. The "Program",
  252. below, refers to any such program or work, and a "work based on
  253. the Program" means either the Program or any derivative work under
  254. copyright law: that is to say, a work containing the Program or a
  255. portion of it, either verbatim or with modifications and/or
  256. translated into another language. (Hereinafter, translation is
  257. included without limitation in the term "modification".) Each
  258. licensee is addressed as "you".
  259. Activities other than copying, distribution and modification are
  260. not covered by this License; they are outside its scope. The act
  261. of running the Program is not restricted, and the output from the
  262. Program is covered only if its contents constitute a work based on
  263. the Program (independent of having been made by running the
  264. Program). Whether that is true depends on what the Program does.
  265. 1. You may copy and distribute verbatim copies of the Program's
  266. source code as you receive it, in any medium, provided that you
  267. conspicuously and appropriately publish on each copy an appropriate
  268. copyright notice and disclaimer of warranty; keep intact all the
  269. notices that refer to this License and to the absence of any
  270. warranty; and give any other recipients of the Program a copy of
  271. this License along with the Program.
  272. You may charge a fee for the physical act of transferring a copy,
  273. and you may at your option offer warranty protection in exchange
  274. for a fee.
  275. 2. You may modify your copy or copies of the Program or any portion
  276. of it, thus forming a work based on the Program, and copy and
  277. distribute such modifications or work under the terms of Section 1
  278. above, provided that you also meet all of these conditions:
  279. a. You must cause the modified files to carry prominent notices
  280. stating that you changed the files and the date of any change.
  281. b. You must cause any work that you distribute or publish, that
  282. in whole or in part contains or is derived from the Program
  283. or any part thereof, to be licensed as a whole at no charge
  284. to all third parties under the terms of this License.
  285. c. If the modified program normally reads commands interactively
  286. when run, you must cause it, when started running for such
  287. interactive use in the most ordinary way, to print or display
  288. an announcement including an appropriate copyright notice and
  289. a notice that there is no warranty (or else, saying that you
  290. provide a warranty) and that users may redistribute the
  291. program under these conditions, and telling the user how to
  292. view a copy of this License. (Exception: if the Program
  293. itself is interactive but does not normally print such an
  294. announcement, your work based on the Program is not required
  295. to print an announcement.)
  296. These requirements apply to the modified work as a whole. If
  297. identifiable sections of that work are not derived from the
  298. Program, and can be reasonably considered independent and separate
  299. works in themselves, then this License, and its terms, do not
  300. apply to those sections when you distribute them as separate
  301. works. But when you distribute the same sections as part of a
  302. whole which is a work based on the Program, the distribution of
  303. the whole must be on the terms of this License, whose permissions
  304. for other licensees extend to the entire whole, and thus to each
  305. and every part regardless of who wrote it.
  306. Thus, it is not the intent of this section to claim rights or
  307. contest your rights to work written entirely by you; rather, the
  308. intent is to exercise the right to control the distribution of
  309. derivative or collective works based on the Program.
  310. In addition, mere aggregation of another work not based on the
  311. Program with the Program (or with a work based on the Program) on
  312. a volume of a storage or distribution medium does not bring the
  313. other work under the scope of this License.
  314. 3. You may copy and distribute the Program (or a work based on it,
  315. under Section 2) in object code or executable form under the terms
  316. of Sections 1 and 2 above provided that you also do one of the
  317. following:
  318. a. Accompany it with the complete corresponding machine-readable
  319. source code, which must be distributed under the terms of
  320. Sections 1 and 2 above on a medium customarily used for
  321. software interchange; or,
  322. b. Accompany it with a written offer, valid for at least three
  323. years, to give any third party, for a charge no more than your
  324. cost of physically performing source distribution, a complete
  325. machine-readable copy of the corresponding source code, to be
  326. distributed under the terms of Sections 1 and 2 above on a
  327. medium customarily used for software interchange; or,
  328. c. Accompany it with the information you received as to the offer
  329. to distribute corresponding source code. (This alternative is
  330. allowed only for noncommercial distribution and only if you
  331. received the program in object code or executable form with
  332. such an offer, in accord with Subsection b above.)
  333. The source code for a work means the preferred form of the work for
  334. making modifications to it. For an executable work, complete
  335. source code means all the source code for all modules it contains,
  336. plus any associated interface definition files, plus the scripts
  337. used to control compilation and installation of the executable.
  338. However, as a special exception, the source code distributed need
  339. not include anything that is normally distributed (in either
  340. source or binary form) with the major components (compiler,
  341. kernel, and so on) of the operating system on which the executable
  342. runs, unless that component itself accompanies the executable.
  343. If distribution of executable or object code is made by offering
  344. access to copy from a designated place, then offering equivalent
  345. access to copy the source code from the same place counts as
  346. distribution of the source code, even though third parties are not
  347. compelled to copy the source along with the object code.
  348. 4. You may not copy, modify, sublicense, or distribute the Program
  349. except as expressly provided under this License. Any attempt
  350. otherwise to copy, modify, sublicense or distribute the Program is
  351. void, and will automatically terminate your rights under this
  352. License. However, parties who have received copies, or rights,
  353. from you under this License will not have their licenses
  354. terminated so long as such parties remain in full compliance.
  355. 5. You are not required to accept this License, since you have not
  356. signed it. However, nothing else grants you permission to modify
  357. or distribute the Program or its derivative works. These actions
  358. are prohibited by law if you do not accept this License.
  359. Therefore, by modifying or distributing the Program (or any work
  360. based on the Program), you indicate your acceptance of this
  361. License to do so, and all its terms and conditions for copying,
  362. distributing or modifying the Program or works based on it.
  363. 6. Each time you redistribute the Program (or any work based on the
  364. Program), the recipient automatically receives a license from the
  365. original licensor to copy, distribute or modify the Program
  366. subject to these terms and conditions. You may not impose any
  367. further restrictions on the recipients' exercise of the rights
  368. granted herein. You are not responsible for enforcing compliance
  369. by third parties to this License.
  370. 7. If, as a consequence of a court judgment or allegation of patent
  371. infringement or for any other reason (not limited to patent
  372. issues), conditions are imposed on you (whether by court order,
  373. agreement or otherwise) that contradict the conditions of this
  374. License, they do not excuse you from the conditions of this
  375. License. If you cannot distribute so as to satisfy simultaneously
  376. your obligations under this License and any other pertinent
  377. obligations, then as a consequence you may not distribute the
  378. Program at all. For example, if a patent license would not permit
  379. royalty-free redistribution of the Program by all those who
  380. receive copies directly or indirectly through you, then the only
  381. way you could satisfy both it and this License would be to refrain
  382. entirely from distribution of the Program.
  383. If any portion of this section is held invalid or unenforceable
  384. under any particular circumstance, the balance of the section is
  385. intended to apply and the section as a whole is intended to apply
  386. in other circumstances.
  387. It is not the purpose of this section to induce you to infringe any
  388. patents or other property right claims or to contest validity of
  389. any such claims; this section has the sole purpose of protecting
  390. the integrity of the free software distribution system, which is
  391. implemented by public license practices. Many people have made
  392. generous contributions to the wide range of software distributed
  393. through that system in reliance on consistent application of that
  394. system; it is up to the author/donor to decide if he or she is
  395. willing to distribute software through any other system and a
  396. licensee cannot impose that choice.
  397. This section is intended to make thoroughly clear what is believed
  398. to be a consequence of the rest of this License.
  399. 8. If the distribution and/or use of the Program is restricted in
  400. certain countries either by patents or by copyrighted interfaces,
  401. the original copyright holder who places the Program under this
  402. License may add an explicit geographical distribution limitation
  403. excluding those countries, so that distribution is permitted only
  404. in or among countries not thus excluded. In such case, this
  405. License incorporates the limitation as if written in the body of
  406. this License.
  407. 9. The Free Software Foundation may publish revised and/or new
  408. versions of the General Public License from time to time. Such
  409. new versions will be similar in spirit to the present version, but
  410. may differ in detail to address new problems or concerns.
  411. Each version is given a distinguishing version number. If the
  412. Program specifies a version number of this License which applies
  413. to it and "any later version", you have the option of following
  414. the terms and conditions either of that version or of any later
  415. version published by the Free Software Foundation. If the Program
  416. does not specify a version number of this License, you may choose
  417. any version ever published by the Free Software Foundation.
  418. 10. If you wish to incorporate parts of the Program into other free
  419. programs whose distribution conditions are different, write to the
  420. author to ask for permission. For software which is copyrighted
  421. by the Free Software Foundation, write to the Free Software
  422. Foundation; we sometimes make exceptions for this. Our decision
  423. will be guided by the two goals of preserving the free status of
  424. all derivatives of our free software and of promoting the sharing
  425. and reuse of software generally.
  426. NO WARRANTY
  427. 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  428. WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  429. LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  430. HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  431. WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  432. NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  433. FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
  434. QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
  435. PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  436. SERVICING, REPAIR OR CORRECTION.
  437. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  438. WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  439. MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  440. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  441. INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  442. INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  443. DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  444. OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  445. OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  446. ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  447. END OF TERMS AND CONDITIONS
  448. How to Apply These Terms to Your New Programs
  449. =============================================
  450. If you develop a new program, and you want it to be of the greatest
  451. possible use to the public, the best way to achieve this is to make it
  452. free software which everyone can redistribute and change under these
  453. terms.
  454. To do so, attach the following notices to the program. It is safest
  455. to attach them to the start of each source file to most effectively
  456. convey the exclusion of warranty; and each file should have at least
  457. the "copyright" line and a pointer to where the full notice is found.
  458. ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  459. Copyright (C) 19YY NAME OF AUTHOR
  460. This program is free software; you can redistribute it and/or modify
  461. it under the terms of the GNU General Public License as published by
  462. the Free Software Foundation; either version 2 of the License, or
  463. (at your option) any later version.
  464. This program is distributed in the hope that it will be useful,
  465. but WITHOUT ANY WARRANTY; without even the implied warranty of
  466. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  467. GNU General Public License for more details.
  468. You should have received a copy of the GNU General Public License
  469. along with this program; if not, write to the Free Software
  470. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  471. Also add information on how to contact you by electronic and paper
  472. mail.
  473. If the program is interactive, make it output a short notice like
  474. this when it starts in an interactive mode:
  475. Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  476. Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  477. type `show w'.
  478. This is free software, and you are welcome to redistribute it
  479. under certain conditions; type `show c' for details.
  480. The hypothetical commands `show w' and `show c' should show the
  481. appropriate parts of the General Public License. Of course, the
  482. commands you use may be called something other than `show w' and `show
  483. c'; they could even be mouse-clicks or menu items--whatever suits your
  484. program.
  485. You should also get your employer (if you work as a programmer) or
  486. your school, if any, to sign a "copyright disclaimer" for the program,
  487. if necessary. Here is a sample; alter the names:
  488. Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  489. `Gnomovision' (which makes passes at compilers) written by James Hacker.
  490. SIGNATURE OF TY COON, 1 April 1989
  491. Ty Coon, President of Vice
  492. This General Public License does not permit incorporating your
  493. program into proprietary programs. If your program is a subroutine
  494. library, you may consider it more useful to permit linking proprietary
  495. applications with the library. If this is what you want to do, use the
  496. GNU Library General Public License instead of this License.
  497. 
  498. File: bison.info, Node: Concepts, Next: Examples, Prev: Copying, Up: Top
  499. The Concepts of Bison
  500. *********************
  501. This chapter introduces many of the basic concepts without which the
  502. details of Bison will not make sense. If you do not already know how to
  503. use Bison or Yacc, we suggest you start by reading this chapter
  504. carefully.
  505. * Menu:
  506. * Language and Grammar:: Languages and context-free grammars,
  507. as mathematical ideas.
  508. * Grammar in Bison:: How we represent grammars for Bison's sake.
  509. * Semantic Values:: Each token or syntactic grouping can have
  510. a semantic value (the value of an integer,
  511. the name of an identifier, etc.).
  512. * Semantic Actions:: Each rule can have an action containing C code.
  513. * Bison Parser:: What are Bison's input and output,
  514. how is the output used?
  515. * Stages:: Stages in writing and running Bison grammars.
  516. * Grammar Layout:: Overall structure of a Bison grammar file.
  517. 
  518. File: bison.info, Node: Language and Grammar, Next: Grammar in Bison, Up: Concepts
  519. Languages and Context-Free Grammars
  520. ===================================
  521. In order for Bison to parse a language, it must be described by a
  522. "context-free grammar". This means that you specify one or more
  523. "syntactic groupings" and give rules for constructing them from their
  524. parts. For example, in the C language, one kind of grouping is called
  525. an `expression'. One rule for making an expression might be, "An
  526. expression can be made of a minus sign and another expression".
  527. Another would be, "An expression can be an integer". As you can see,
  528. rules are often recursive, but there must be at least one rule which
  529. leads out of the recursion.
  530. The most common formal system for presenting such rules for humans
  531. to read is "Backus-Naur Form" or "BNF", which was developed in order to
  532. specify the language Algol 60. Any grammar expressed in BNF is a
  533. context-free grammar. The input to Bison is essentially
  534. machine-readable BNF.
  535. Not all context-free languages can be handled by Bison, only those
  536. that are LALR(1). In brief, this means that it must be possible to
  537. tell how to parse any portion of an input string with just a single
  538. token of look-ahead. Strictly speaking, that is a description of an
  539. LR(1) grammar, and LALR(1) involves additional restrictions that are
  540. hard to explain simply; but it is rare in actual practice to find an
  541. LR(1) grammar that fails to be LALR(1). *Note Mysterious Reduce/Reduce
  542. Conflicts: Mystery Conflicts, for more information on this.
  543. In the formal grammatical rules for a language, each kind of
  544. syntactic unit or grouping is named by a "symbol". Those which are
  545. built by grouping smaller constructs according to grammatical rules are
  546. called "nonterminal symbols"; those which can't be subdivided are called
  547. "terminal symbols" or "token types". We call a piece of input
  548. corresponding to a single terminal symbol a "token", and a piece
  549. corresponding to a single nonterminal symbol a "grouping".
  550. We can use the C language as an example of what symbols, terminal and
  551. nonterminal, mean. The tokens of C are identifiers, constants (numeric
  552. and string), and the various keywords, arithmetic operators and
  553. punctuation marks. So the terminal symbols of a grammar for C include
  554. `identifier', `number', `string', plus one symbol for each keyword,
  555. operator or punctuation mark: `if', `return', `const', `static', `int',
  556. `char', `plus-sign', `open-brace', `close-brace', `comma' and many
  557. more. (These tokens can be subdivided into characters, but that is a
  558. matter of lexicography, not grammar.)
  559. Here is a simple C function subdivided into tokens:
  560. int /* keyword `int' */
  561. square (x) /* identifier, open-paren, */
  562. /* identifier, close-paren */
  563. int x; /* keyword `int', identifier, semicolon */
  564. { /* open-brace */
  565. return x * x; /* keyword `return', identifier, */
  566. /* asterisk, identifier, semicolon */
  567. } /* close-brace */
  568. The syntactic groupings of C include the expression, the statement,
  569. the declaration, and the function definition. These are represented in
  570. the grammar of C by nonterminal symbols `expression', `statement',
  571. `declaration' and `function definition'. The full grammar uses dozens
  572. of additional language constructs, each with its own nonterminal
  573. symbol, in order to express the meanings of these four. The example
  574. above is a function definition; it contains one declaration, and one
  575. statement. In the statement, each `x' is an expression and so is `x *
  576. x'.
  577. Each nonterminal symbol must have grammatical rules showing how it
  578. is made out of simpler constructs. For example, one kind of C
  579. statement is the `return' statement; this would be described with a
  580. grammar rule which reads informally as follows:
  581. A `statement' can be made of a `return' keyword, an `expression'
  582. and a `semicolon'.
  583. There would be many other rules for `statement', one for each kind of
  584. statement in C.
  585. One nonterminal symbol must be distinguished as the special one which
  586. defines a complete utterance in the language. It is called the "start
  587. symbol". In a compiler, this means a complete input program. In the C
  588. language, the nonterminal symbol `sequence of definitions and
  589. declarations' plays this role.
  590. For example, `1 + 2' is a valid C expression--a valid part of a C
  591. program--but it is not valid as an *entire* C program. In the
  592. context-free grammar of C, this follows from the fact that `expression'
  593. is not the start symbol.
  594. The Bison parser reads a sequence of tokens as its input, and groups
  595. the tokens using the grammar rules. If the input is valid, the end
  596. result is that the entire token sequence reduces to a single grouping
  597. whose symbol is the grammar's start symbol. If we use a grammar for C,
  598. the entire input must be a `sequence of definitions and declarations'.
  599. If not, the parser reports a syntax error.
  600. 
  601. File: bison.info, Node: Grammar in Bison, Next: Semantic Values, Prev: Language and Grammar, Up: Concepts
  602. From Formal Rules to Bison Input
  603. ================================
  604. A formal grammar is a mathematical construct. To define the language
  605. for Bison, you must write a file expressing the grammar in Bison syntax:
  606. a "Bison grammar" file. *Note Bison Grammar Files: Grammar File.
  607. A nonterminal symbol in the formal grammar is represented in Bison
  608. input as an identifier, like an identifier in C. By convention, it
  609. should be in lower case, such as `expr', `stmt' or `declaration'.
  610. The Bison representation for a terminal symbol is also called a
  611. "token type". Token types as well can be represented as C-like
  612. identifiers. By convention, these identifiers should be upper case to
  613. distinguish them from nonterminals: for example, `INTEGER',
  614. `IDENTIFIER', `IF' or `RETURN'. A terminal symbol that stands for a
  615. particular keyword in the language should be named after that keyword
  616. converted to upper case. The terminal symbol `error' is reserved for
  617. error recovery. *Note Symbols::.
  618. A terminal symbol can also be represented as a character literal,
  619. just like a C character constant. You should do this whenever a token
  620. is just a single character (parenthesis, plus-sign, etc.): use that
  621. same character in a literal as the terminal symbol for that token.
  622. The grammar rules also have an expression in Bison syntax. For
  623. example, here is the Bison rule for a C `return' statement. The
  624. semicolon in quotes is a literal character token, representing part of
  625. the C syntax for the statement; the naked semicolon, and the colon, are
  626. Bison punctuation used in every rule.
  627. stmt: RETURN expr ';'
  628. ;
  629. *Note Syntax of Grammar Rules: Rules.
  630. 
  631. File: bison.info, Node: Semantic Values, Next: Semantic Actions, Prev: Grammar in Bison, Up: Concepts
  632. Semantic Values
  633. ===============
  634. A formal grammar selects tokens only by their classifications: for
  635. example, if a rule mentions the terminal symbol `integer constant', it
  636. means that *any* integer constant is grammatically valid in that
  637. position. The precise value of the constant is irrelevant to how to
  638. parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
  639. equally grammatical.
  640. But the precise value is very important for what the input means
  641. once it is parsed. A compiler is useless if it fails to distinguish
  642. between 4, 1 and 3989 as constants in the program! Therefore, each
  643. token in a Bison grammar has both a token type and a "semantic value".
  644. *Note Defining Language Semantics: Semantics, for details.
  645. The token type is a terminal symbol defined in the grammar, such as
  646. `INTEGER', `IDENTIFIER' or `',''. It tells everything you need to know
  647. to decide where the token may validly appear and how to group it with
  648. other tokens. The grammar rules know nothing about tokens except their
  649. types.
  650. The semantic value has all the rest of the information about the
  651. meaning of the token, such as the value of an integer, or the name of an
  652. identifier. (A token such as `','' which is just punctuation doesn't
  653. need to have any semantic value.)
  654. For example, an input token might be classified as token type
  655. `INTEGER' and have the semantic value 4. Another input token might
  656. have the same token type `INTEGER' but value 3989. When a grammar rule
  657. says that `INTEGER' is allowed, either of these tokens is acceptable
  658. because each is an `INTEGER'. When the parser accepts the token, it
  659. keeps track of the token's semantic value.
  660. Each grouping can also have a semantic value as well as its
  661. nonterminal symbol. For example, in a calculator, an expression
  662. typically has a semantic value that is a number. In a compiler for a
  663. programming language, an expression typically has a semantic value that
  664. is a tree structure describing the meaning of the expression.
  665. 
  666. File: bison.info, Node: Semantic Actions, Next: Bison Parser, Prev: Semantic Values, Up: Concepts
  667. Semantic Actions
  668. ================
  669. In order to be useful, a program must do more than parse input; it
  670. must also produce some output based on the input. In a Bison grammar,
  671. a grammar rule can have an "action" made up of C statements. Each time
  672. the parser recognizes a match for that rule, the action is executed.
  673. *Note Actions::.
  674. Most of the time, the purpose of an action is to compute the
  675. semantic value of the whole construct from the semantic values of its
  676. parts. For example, suppose we have a rule which says an expression
  677. can be the sum of two expressions. When the parser recognizes such a
  678. sum, each of the subexpressions has a semantic value which describes
  679. how it was built up. The action for this rule should create a similar
  680. sort of value for the newly recognized larger expression.
  681. For example, here is a rule that says an expression can be the sum of
  682. two subexpressions:
  683. expr: expr '+' expr { $$ = $1 + $3; }
  684. ;
  685. The action says how to produce the semantic value of the sum expression
  686. from the values of the two subexpressions.
  687. 
  688. File: bison.info, Node: Bison Parser, Next: Stages, Prev: Semantic Actions, Up: Concepts
  689. Bison Output: the Parser File
  690. =============================
  691. When you run Bison, you give it a Bison grammar file as input. The
  692. output is a C source file that parses the language described by the
  693. grammar. This file is called a "Bison parser". Keep in mind that the
  694. Bison utility and the Bison parser are two distinct programs: the Bison
  695. utility is a program whose output is the Bison parser that becomes part
  696. of your program.
  697. The job of the Bison parser is to group tokens into groupings
  698. according to the grammar rules--for example, to build identifiers and
  699. operators into expressions. As it does this, it runs the actions for
  700. the grammar rules it uses.
  701. The tokens come from a function called the "lexical analyzer" that
  702. you must supply in some fashion (such as by writing it in C). The
  703. Bison parser calls the lexical analyzer each time it wants a new token.
  704. It doesn't know what is "inside" the tokens (though their semantic
  705. values may reflect this). Typically the lexical analyzer makes the
  706. tokens by parsing characters of text, but Bison does not depend on
  707. this. *Note The Lexical Analyzer Function `yylex': Lexical.
  708. The Bison parser file is C code which defines a function named
  709. `yyparse' which implements that grammar. This function does not make a
  710. complete C program: you must supply some additional functions. One is
  711. the lexical analyzer. Another is an error-reporting function which the
  712. parser calls to report an error. In addition, a complete C program must
  713. start with a function called `main'; you have to provide this, and
  714. arrange for it to call `yyparse' or the parser will never run. *Note
  715. Parser C-Language Interface: Interface.
  716. Aside from the token type names and the symbols in the actions you
  717. write, all variable and function names used in the Bison parser file
  718. begin with `yy' or `YY'. This includes interface functions such as the
  719. lexical analyzer function `yylex', the error reporting function
  720. `yyerror' and the parser function `yyparse' itself. This also includes
  721. numerous identifiers used for internal purposes. Therefore, you should
  722. avoid using C identifiers starting with `yy' or `YY' in the Bison
  723. grammar file except for the ones defined in this manual.
  724. 
  725. File: bison.info, Node: Stages, Next: Grammar Layout, Prev: Bison Parser, Up: Concepts
  726. Stages in Using Bison
  727. =====================
  728. The actual language-design process using Bison, from grammar
  729. specification to a working compiler or interpreter, has these parts:
  730. 1. Formally specify the grammar in a form recognized by Bison (*note
  731. Bison Grammar Files: Grammar File.). For each grammatical rule in
  732. the language, describe the action that is to be taken when an
  733. instance of that rule is recognized. The action is described by a
  734. sequence of C statements.
  735. 2. Write a lexical analyzer to process input and pass tokens to the
  736. parser. The lexical analyzer may be written by hand in C (*note
  737. The Lexical Analyzer Function `yylex': Lexical.). It could also
  738. be produced using Lex, but the use of Lex is not discussed in this
  739. manual.
  740. 3. Write a controlling function that calls the Bison-produced parser.
  741. 4. Write error-reporting routines.
  742. To turn this source code as written into a runnable program, you
  743. must follow these steps:
  744. 1. Run Bison on the grammar to produce the parser.
  745. 2. Compile the code output by Bison, as well as any other source
  746. files.
  747. 3. Link the object files to produce the finished product.
  748. 
  749. File: bison.info, Node: Grammar Layout, Prev: Stages, Up: Concepts
  750. The Overall Layout of a Bison Grammar
  751. =====================================
  752. The input file for the Bison utility is a "Bison grammar file". The
  753. general form of a Bison grammar file is as follows:
  754. %{
  755. C DECLARATIONS
  756. %}
  757. BISON DECLARATIONS
  758. %%
  759. GRAMMAR RULES
  760. %%
  761. ADDITIONAL C CODE
  762. The `%%', `%{' and `%}' are punctuation that appears in every Bison
  763. grammar file to separate the sections.
  764. The C declarations may define types and variables used in the
  765. actions. You can also use preprocessor commands to define macros used
  766. there, and use `#include' to include header files that do any of these
  767. things.
  768. The Bison declarations declare the names of the terminal and
  769. nonterminal symbols, and may also describe operator precedence and the
  770. data types of semantic values of various symbols.
  771. The grammar rules define how to construct each nonterminal symbol
  772. from its parts.
  773. The additional C code can contain any C code you want to use. Often
  774. the definition of the lexical analyzer `yylex' goes here, plus
  775. subroutines called by the actions in the grammar rules. In a simple
  776. program, all the rest of the program can go here.
  777. 
  778. File: bison.info, Node: Examples, Next: Grammar File, Prev: Concepts, Up: Top
  779. Examples
  780. ********
  781. Now we show and explain three sample programs written using Bison: a
  782. reverse polish notation calculator, an algebraic (infix) notation
  783. calculator, and a multi-function calculator. All three have been tested
  784. under BSD Unix 4.3; each produces a usable, though limited, interactive
  785. desk-top calculator.
  786. These examples are simple, but Bison grammars for real programming
  787. languages are written the same way. You can copy these examples out of
  788. the Info file and into a source file to try them.
  789. * Menu:
  790. * RPN Calc:: Reverse polish notation calculator;
  791. a first example with no operator precedence.
  792. * Infix Calc:: Infix (algebraic) notation calculator.
  793. Operator precedence is introduced.
  794. * Simple Error Recovery:: Continuing after syntax errors.
  795. * Multi-function Calc:: Calculator with memory and trig functions.
  796. It uses multiple data-types for semantic values.
  797. * Exercises:: Ideas for improving the multi-function calculator.
  798. 
  799. File: bison.info, Node: RPN Calc, Next: Infix Calc, Up: Examples
  800. Reverse Polish Notation Calculator
  801. ==================================
  802. The first example is that of a simple double-precision "reverse
  803. polish notation" calculator (a calculator using postfix operators).
  804. This example provides a good starting point, since operator precedence
  805. is not an issue. The second example will illustrate how operator
  806. precedence is handled.
  807. The source code for this calculator is named `rpcalc.y'. The `.y'
  808. extension is a convention used for Bison input files.
  809. * Menu:
  810. * Decls: Rpcalc Decls. Bison and C declarations for rpcalc.
  811. * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
  812. * Lexer: Rpcalc Lexer. The lexical analyzer.
  813. * Main: Rpcalc Main. The controlling function.
  814. * Error: Rpcalc Error. The error reporting function.
  815. * Gen: Rpcalc Gen. Running Bison on the grammar file.
  816. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  817. 
  818. File: bison.info, Node: Rpcalc Decls, Next: Rpcalc Rules, Up: RPN Calc
  819. Declarations for `rpcalc'
  820. -------------------------
  821. Here are the C and Bison declarations for the reverse polish notation
  822. calculator. As in C, comments are placed between `/*...*/'.
  823. /* Reverse polish notation calculator. */
  824. %{
  825. #define YYSTYPE double
  826. #include <math.h>
  827. %}
  828. %token NUM
  829. %% /* Grammar rules and actions follow */
  830. The C declarations section (*note The C Declarations Section: C
  831. Declarations.) contains two preprocessor directives.
  832. The `#define' directive defines the macro `YYSTYPE', thus specifying
  833. the C data type for semantic values of both tokens and groupings (*note
  834. Data Types of Semantic Values: Value Type.). The Bison parser will use
  835. whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
  836. the default. Because we specify `double', each token and each
  837. expression has an associated value, which is a floating point number.
  838. The `#include' directive is used to declare the exponentiation
  839. function `pow'.
  840. The second section, Bison declarations, provides information to
  841. Bison about the token types (*note The Bison Declarations Section:
  842. Bison Declarations.). Each terminal symbol that is not a
  843. single-character literal must be declared here. (Single-character
  844. literals normally don't need to be declared.) In this example, all the
  845. arithmetic operators are designated by single-character literals, so the
  846. only terminal symbol that needs to be declared is `NUM', the token type
  847. for numeric constants.