bison.info-1 49 KB

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