bison.info-1 49 KB

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