bison.info-1 49 KB

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