bison.info-2 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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: Rpcalc Decls, Next: Rpcalc Rules, Up: RPN Calc
  31. Declarations for `rpcalc'
  32. -------------------------
  33. Here are the C and Bison declarations for the reverse polish notation
  34. calculator. As in C, comments are placed between `/*...*/'.
  35. /* Reverse polish notation calculator. */
  36. %{
  37. #define YYSTYPE double
  38. #include <math.h>
  39. %}
  40. %token NUM
  41. %% /* Grammar rules and actions follow */
  42. The C declarations section (*note The C Declarations Section: C
  43. Declarations.) contains two preprocessor directives.
  44. The `#define' directive defines the macro `YYSTYPE', thus specifying
  45. the C data type for semantic values of both tokens and groupings (*note
  46. Data Types of Semantic Values: Value Type.). The Bison parser will use
  47. whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
  48. the default. Because we specify `double', each token and each
  49. expression has an associated value, which is a floating point number.
  50. The `#include' directive is used to declare the exponentiation
  51. function `pow'.
  52. The second section, Bison declarations, provides information to
  53. Bison about the token types (*note The Bison Declarations Section:
  54. Bison Declarations.). Each terminal symbol that is not a
  55. single-character literal must be declared here. (Single-character
  56. literals normally don't need to be declared.) In this example, all the
  57. arithmetic operators are designated by single-character literals, so the
  58. only terminal symbol that needs to be declared is `NUM', the token type
  59. for numeric constants.
  60. 
  61. File: bison.info, Node: Rpcalc Rules, Next: Rpcalc Lexer, Prev: Rpcalc Decls, Up: RPN Calc
  62. Grammar Rules for `rpcalc'
  63. --------------------------
  64. Here are the grammar rules for the reverse polish notation
  65. calculator.
  66. input: /* empty */
  67. | input line
  68. ;
  69. line: '\n'
  70. | exp '\n' { printf ("\t%.10g\n", $1); }
  71. ;
  72. exp: NUM { $$ = $1; }
  73. | exp exp '+' { $$ = $1 + $2; }
  74. | exp exp '-' { $$ = $1 - $2; }
  75. | exp exp '*' { $$ = $1 * $2; }
  76. | exp exp '/' { $$ = $1 / $2; }
  77. /* Exponentiation */
  78. | exp exp '^' { $$ = pow ($1, $2); }
  79. /* Unary minus */
  80. | exp 'n' { $$ = -$1; }
  81. ;
  82. %%
  83. The groupings of the rpcalc "language" defined here are the
  84. expression (given the name `exp'), the line of input (`line'), and the
  85. complete input transcript (`input'). Each of these nonterminal symbols
  86. has several alternate rules, joined by the `|' punctuator which is read
  87. as "or". The following sections explain what these rules mean.
  88. The semantics of the language is determined by the actions taken
  89. when a grouping is recognized. The actions are the C code that appears
  90. inside braces. *Note Actions::.
  91. You must specify these actions in C, but Bison provides the means for
  92. passing semantic values between the rules. In each action, the
  93. pseudo-variable `$$' stands for the semantic value for the grouping
  94. that the rule is going to construct. Assigning a value to `$$' is the
  95. main job of most actions. The semantic values of the components of the
  96. rule are referred to as `$1', `$2', and so on.
  97. * Menu:
  98. * Rpcalc Input::
  99. * Rpcalc Line::
  100. * Rpcalc Expr::
  101. 
  102. File: bison.info, Node: Rpcalc Input, Next: Rpcalc Line, Up: Rpcalc Rules
  103. Explanation of `input'
  104. ......................
  105. Consider the definition of `input':
  106. input: /* empty */
  107. | input line
  108. ;
  109. This definition reads as follows: "A complete input is either an
  110. empty string, or a complete input followed by an input line". Notice
  111. that "complete input" is defined in terms of itself. This definition
  112. is said to be "left recursive" since `input' appears always as the
  113. leftmost symbol in the sequence. *Note Recursive Rules: Recursion.
  114. The first alternative is empty because there are no symbols between
  115. the colon and the first `|'; this means that `input' can match an empty
  116. string of input (no tokens). We write the rules this way because it is
  117. legitimate to type `Ctrl-d' right after you start the calculator. It's
  118. conventional to put an empty alternative first and write the comment
  119. `/* empty */' in it.
  120. The second alternate rule (`input line') handles all nontrivial
  121. input. It means, "After reading any number of lines, read one more
  122. line if possible." The left recursion makes this rule into a loop.
  123. Since the first alternative matches empty input, the loop can be
  124. executed zero or more times.
  125. The parser function `yyparse' continues to process input until a
  126. grammatical error is seen or the lexical analyzer says there are no more
  127. input tokens; we will arrange for the latter to happen at end of file.
  128. 
  129. File: bison.info, Node: Rpcalc Line, Next: Rpcalc Expr, Prev: Rpcalc Input, Up: Rpcalc Rules
  130. Explanation of `line'
  131. .....................
  132. Now consider the definition of `line':
  133. line: '\n'
  134. | exp '\n' { printf ("\t%.10g\n", $1); }
  135. ;
  136. The first alternative is a token which is a newline character; this
  137. means that rpcalc accepts a blank line (and ignores it, since there is
  138. no action). The second alternative is an expression followed by a
  139. newline. This is the alternative that makes rpcalc useful. The
  140. semantic value of the `exp' grouping is the value of `$1' because the
  141. `exp' in question is the first symbol in the alternative. The action
  142. prints this value, which is the result of the computation the user
  143. asked for.
  144. This action is unusual because it does not assign a value to `$$'.
  145. As a consequence, the semantic value associated with the `line' is
  146. uninitialized (its value will be unpredictable). This would be a bug if
  147. that value were ever used, but we don't use it: once rpcalc has printed
  148. the value of the user's input line, that value is no longer needed.
  149. 
  150. File: bison.info, Node: Rpcalc Expr, Prev: Rpcalc Line, Up: Rpcalc Rules
  151. Explanation of `expr'
  152. .....................
  153. The `exp' grouping has several rules, one for each kind of
  154. expression. The first rule handles the simplest expressions: those
  155. that are just numbers. The second handles an addition-expression,
  156. which looks like two expressions followed by a plus-sign. The third
  157. handles subtraction, and so on.
  158. exp: NUM
  159. | exp exp '+' { $$ = $1 + $2; }
  160. | exp exp '-' { $$ = $1 - $2; }
  161. ...
  162. ;
  163. We have used `|' to join all the rules for `exp', but we could
  164. equally well have written them separately:
  165. exp: NUM ;
  166. exp: exp exp '+' { $$ = $1 + $2; } ;
  167. exp: exp exp '-' { $$ = $1 - $2; } ;
  168. ...
  169. Most of the rules have actions that compute the value of the
  170. expression in terms of the value of its parts. For example, in the
  171. rule for addition, `$1' refers to the first component `exp' and `$2'
  172. refers to the second one. The third component, `'+'', has no meaningful
  173. associated semantic value, but if it had one you could refer to it as
  174. `$3'. When `yyparse' recognizes a sum expression using this rule, the
  175. sum of the two subexpressions' values is produced as the value of the
  176. entire expression. *Note Actions::.
  177. You don't have to give an action for every rule. When a rule has no
  178. action, Bison by default copies the value of `$1' into `$$'. This is
  179. what happens in the first rule (the one that uses `NUM').
  180. The formatting shown here is the recommended convention, but Bison
  181. does not require it. You can add or change whitespace as much as you
  182. wish. For example, this:
  183. exp : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  184. means the same thing as this:
  185. exp: NUM
  186. | exp exp '+' { $$ = $1 + $2; }
  187. | ...
  188. The latter, however, is much more readable.
  189. 
  190. File: bison.info, Node: Rpcalc Lexer, Next: Rpcalc Main, Prev: Rpcalc Rules, Up: RPN Calc
  191. The `rpcalc' Lexical Analyzer
  192. -----------------------------
  193. The lexical analyzer's job is low-level parsing: converting
  194. characters or sequences of characters into tokens. The Bison parser
  195. gets its tokens by calling the lexical analyzer. *Note The Lexical
  196. Analyzer Function `yylex': Lexical.
  197. Only a simple lexical analyzer is needed for the RPN calculator.
  198. This lexical analyzer skips blanks and tabs, then reads in numbers as
  199. `double' and returns them as `NUM' tokens. Any other character that
  200. isn't part of a number is a separate token. Note that the token-code
  201. for such a single-character token is the character itself.
  202. The return value of the lexical analyzer function is a numeric code
  203. which represents a token type. The same text used in Bison rules to
  204. stand for this token type is also a C expression for the numeric code
  205. for the type. This works in two ways. If the token type is a
  206. character literal, then its numeric code is the ASCII code for that
  207. character; you can use the same character literal in the lexical
  208. analyzer to express the number. If the token type is an identifier,
  209. that identifier is defined by Bison as a C macro whose definition is
  210. the appropriate number. In this example, therefore, `NUM' becomes a
  211. macro for `yylex' to use.
  212. The semantic value of the token (if it has one) is stored into the
  213. global variable `yylval', which is where the Bison parser will look for
  214. it. (The C data type of `yylval' is `YYSTYPE', which was defined at
  215. the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
  216. Decls..)
  217. A token type code of zero is returned if the end-of-file is
  218. encountered. (Bison recognizes any nonpositive value as indicating the
  219. end of the input.)
  220. Here is the code for the lexical analyzer:
  221. /* Lexical analyzer returns a double floating point
  222. number on the stack and the token NUM, or the ASCII
  223. character read if not a number. Skips all blanks
  224. and tabs, returns 0 for EOF. */
  225. #include <ctype.h>
  226. yylex ()
  227. {
  228. int c;
  229. /* skip white space */
  230. while ((c = getchar ()) == ' ' || c == '\t')
  231. ;
  232. /* process numbers */
  233. if (c == '.' || isdigit (c))
  234. {
  235. ungetc (c, stdin);
  236. scanf ("%lf", &yylval);
  237. return NUM;
  238. }
  239. /* return end-of-file */
  240. if (c == EOF)
  241. return 0;
  242. /* return single chars */
  243. return c;
  244. }
  245. 
  246. File: bison.info, Node: Rpcalc Main, Next: Rpcalc Error, Prev: Rpcalc Lexer, Up: RPN Calc
  247. The Controlling Function
  248. ------------------------
  249. In keeping with the spirit of this example, the controlling function
  250. is kept to the bare minimum. The only requirement is that it call
  251. `yyparse' to start the process of parsing.
  252. main ()
  253. {
  254. yyparse ();
  255. }
  256. 
  257. File: bison.info, Node: Rpcalc Error, Next: Rpcalc Gen, Prev: Rpcalc Main, Up: RPN Calc
  258. The Error Reporting Routine
  259. ---------------------------
  260. When `yyparse' detects a syntax error, it calls the error reporting
  261. function `yyerror' to print an error message (usually but not always
  262. `"parse error"'). It is up to the programmer to supply `yyerror'
  263. (*note Parser C-Language Interface: Interface.), so here is the
  264. definition we will use:
  265. #include <stdio.h>
  266. yyerror (s) /* Called by yyparse on error */
  267. char *s;
  268. {
  269. printf ("%s\n", s);
  270. }
  271. After `yyerror' returns, the Bison parser may recover from the error
  272. and continue parsing if the grammar contains a suitable error rule
  273. (*note Error Recovery::.). Otherwise, `yyparse' returns nonzero. We
  274. have not written any error rules in this example, so any invalid input
  275. will cause the calculator program to exit. This is not clean behavior
  276. for a real calculator, but it is adequate in the first example.
  277. 
  278. File: bison.info, Node: Rpcalc Gen, Next: Rpcalc Compile, Prev: Rpcalc Error, Up: RPN Calc
  279. Running Bison to Make the Parser
  280. --------------------------------
  281. Before running Bison to produce a parser, we need to decide how to
  282. arrange all the source code in one or more source files. For such a
  283. simple example, the easiest thing is to put everything in one file.
  284. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  285. "additional C code" section of the file (*note The Overall Layout of a
  286. Bison Grammar: Grammar Layout.).
  287. For a large project, you would probably have several source files,
  288. and use `make' to arrange to recompile them.
  289. With all the source in a single file, you use the following command
  290. to convert it into a parser file:
  291. bison FILE_NAME.y
  292. In this example the file was called `rpcalc.y' (for "Reverse Polish
  293. CALCulator"). Bison produces a file named `FILE_NAME.tab.c', removing
  294. the `.y' from the original file name. The file output by Bison contains
  295. the source code for `yyparse'. The additional functions in the input
  296. file (`yylex', `yyerror' and `main') are copied verbatim to the output.
  297. 
  298. File: bison.info, Node: Rpcalc Compile, Prev: Rpcalc Gen, Up: RPN Calc
  299. Compiling the Parser File
  300. -------------------------
  301. Here is how to compile and run the parser file:
  302. # List files in current directory.
  303. % ls
  304. rpcalc.tab.c rpcalc.y
  305. # Compile the Bison parser.
  306. # `-lm' tells compiler to search math library for `pow'.
  307. % cc rpcalc.tab.c -lm -o rpcalc
  308. # List files again.
  309. % ls
  310. rpcalc rpcalc.tab.c rpcalc.y
  311. The file `rpcalc' now contains the executable code. Here is an
  312. example session using `rpcalc'.
  313. % rpcalc
  314. 4 9 +
  315. 13
  316. 3 7 + 3 4 5 *+-
  317. -13
  318. 3 7 + 3 4 5 * + - n Note the unary minus, `n'
  319. 13
  320. 5 6 / 4 n +
  321. -3.166666667
  322. 3 4 ^ Exponentiation
  323. 81
  324. ^D End-of-file indicator
  325. %
  326. 
  327. File: bison.info, Node: Infix Calc, Next: Simple Error Recovery, Prev: RPN Calc, Up: Examples
  328. Infix Notation Calculator: `calc'
  329. =================================
  330. We now modify rpcalc to handle infix operators instead of postfix.
  331. Infix notation involves the concept of operator precedence and the need
  332. for parentheses nested to arbitrary depth. Here is the Bison code for
  333. `calc.y', an infix desk-top calculator.
  334. /* Infix notation calculator--calc */
  335. %{
  336. #define YYSTYPE double
  337. #include <math.h>
  338. %}
  339. /* BISON Declarations */
  340. %token NUM
  341. %left '-' '+'
  342. %left '*' '/'
  343. %left NEG /* negation--unary minus */
  344. %right '^' /* exponentiation */
  345. /* Grammar follows */
  346. %%
  347. input: /* empty string */
  348. | input line
  349. ;
  350. line: '\n'
  351. | exp '\n' { printf ("\t%.10g\n", $1); }
  352. ;
  353. exp: NUM { $$ = $1; }
  354. | exp '+' exp { $$ = $1 + $3; }
  355. | exp '-' exp { $$ = $1 - $3; }
  356. | exp '*' exp { $$ = $1 * $3; }
  357. | exp '/' exp { $$ = $1 / $3; }
  358. | '-' exp %prec NEG { $$ = -$2; }
  359. | exp '^' exp { $$ = pow ($1, $3); }
  360. | '(' exp ')' { $$ = $2; }
  361. ;
  362. %%
  363. The functions `yylex', `yyerror' and `main' can be the same as before.
  364. There are two important new features shown in this code.
  365. In the second section (Bison declarations), `%left' declares token
  366. types and says they are left-associative operators. The declarations
  367. `%left' and `%right' (right associativity) take the place of `%token'
  368. which is used to declare a token type name without associativity.
  369. (These tokens are single-character literals, which ordinarily don't
  370. need to be declared. We declare them here to specify the
  371. associativity.)
  372. Operator precedence is determined by the line ordering of the
  373. declarations; the higher the line number of the declaration (lower on
  374. the page or screen), the higher the precedence. Hence, exponentiation
  375. has the highest precedence, unary minus (`NEG') is next, followed by
  376. `*' and `/', and so on. *Note Operator Precedence: Precedence.
  377. The other important new feature is the `%prec' in the grammar section
  378. for the unary minus operator. The `%prec' simply instructs Bison that
  379. the rule `| '-' exp' has the same precedence as `NEG'--in this case the
  380. next-to-highest. *Note Context-Dependent Precedence: Contextual
  381. Precedence.
  382. Here is a sample run of `calc.y':
  383. % calc
  384. 4 + 4.5 - (34/(8*3+-3))
  385. 6.880952381
  386. -56 + 2
  387. -54
  388. 3 ^ 2
  389. 9
  390. 
  391. File: bison.info, Node: Simple Error Recovery, Next: Multi-function Calc, Prev: Infix Calc, Up: Examples
  392. Simple Error Recovery
  393. =====================
  394. Up to this point, this manual has not addressed the issue of "error
  395. recovery"--how to continue parsing after the parser detects a syntax
  396. error. All we have handled is error reporting with `yyerror'. Recall
  397. that by default `yyparse' returns after calling `yyerror'. This means
  398. that an erroneous input line causes the calculator program to exit.
  399. Now we show how to rectify this deficiency.
  400. The Bison language itself includes the reserved word `error', which
  401. may be included in the grammar rules. In the example below it has been
  402. added to one of the alternatives for `line':
  403. line: '\n'
  404. | exp '\n' { printf ("\t%.10g\n", $1); }
  405. | error '\n' { yyerrok; }
  406. ;
  407. This addition to the grammar allows for simple error recovery in the
  408. event of a parse error. If an expression that cannot be evaluated is
  409. read, the error will be recognized by the third rule for `line', and
  410. parsing will continue. (The `yyerror' function is still called upon to
  411. print its message as well.) The action executes the statement
  412. `yyerrok', a macro defined automatically by Bison; its meaning is that
  413. error recovery is complete (*note Error Recovery::.). Note the
  414. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  415. This form of error recovery deals with syntax errors. There are
  416. other kinds of errors; for example, division by zero, which raises an
  417. exception signal that is normally fatal. A real calculator program
  418. must handle this signal and use `longjmp' to return to `main' and
  419. resume parsing input lines; it would also have to discard the rest of
  420. the current line of input. We won't discuss this issue further because
  421. it is not specific to Bison programs.
  422. 
  423. File: bison.info, Node: Multi-function Calc, Next: Exercises, Prev: Simple Error Recovery, Up: Examples
  424. Multi-Function Calculator: `mfcalc'
  425. ===================================
  426. Now that the basics of Bison have been discussed, it is time to move
  427. on to a more advanced problem. The above calculators provided only five
  428. functions, `+', `-', `*', `/' and `^'. It would be nice to have a
  429. calculator that provides other mathematical functions such as `sin',
  430. `cos', etc.
  431. It is easy to add new operators to the infix calculator as long as
  432. they are only single-character literals. The lexical analyzer `yylex'
  433. passes back all non-number characters as tokens, so new grammar rules
  434. suffice for adding a new operator. But we want something more
  435. flexible: built-in functions whose syntax has this form:
  436. FUNCTION_NAME (ARGUMENT)
  437. At the same time, we will add memory to the calculator, by allowing you
  438. to create named variables, store values in them, and use them later.
  439. Here is a sample session with the multi-function calculator:
  440. % acalc
  441. pi = 3.141592653589
  442. 3.1415926536
  443. sin(pi)
  444. 0.0000000000
  445. alpha = beta1 = 2.3
  446. 2.3000000000
  447. alpha
  448. 2.3000000000
  449. ln(alpha)
  450. 0.8329091229
  451. exp(ln(beta1))
  452. 2.3000000000
  453. %
  454. Note that multiple assignment and nested function calls are
  455. permitted.
  456. * Menu:
  457. * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
  458. * Rules: Mfcalc Rules. Grammar rules for the calculator.
  459. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  460. 
  461. File: bison.info, Node: Mfcalc Decl, Next: Mfcalc Rules, Up: Multi-function Calc
  462. Declarations for `mfcalc'
  463. -------------------------
  464. Here are the C and Bison declarations for the multi-function
  465. calculator.
  466. %{
  467. #include <math.h> /* For math functions, cos(), sin(), etc. */
  468. #include "calc.h" /* Contains definition of `symrec' */
  469. %}
  470. %union {
  471. double val; /* For returning numbers. */
  472. symrec *tptr; /* For returning symbol-table pointers */
  473. }
  474. %token <val> NUM /* Simple double precision number */
  475. %token <tptr> VAR FNCT /* Variable and Function */
  476. %type <val> exp
  477. %right '='
  478. %left '-' '+'
  479. %left '*' '/'
  480. %left NEG /* Negation--unary minus */
  481. %right '^' /* Exponentiation */
  482. /* Grammar follows */
  483. %%
  484. The above grammar introduces only two new features of the Bison
  485. language. These features allow semantic values to have various data
  486. types (*note More Than One Value Type: Multiple Types.).
  487. The `%union' declaration specifies the entire list of possible types;
  488. this is instead of defining `YYSTYPE'. The allowable types are now
  489. double-floats (for `exp' and `NUM') and pointers to entries in the
  490. symbol table. *Note The Collection of Value Types: Union Decl.
  491. Since values can now have various types, it is necessary to
  492. associate a type with each grammar symbol whose semantic value is used.
  493. These symbols are `NUM', `VAR', `FNCT', and `exp'. Their declarations
  494. are augmented with information about their data type (placed between
  495. angle brackets).
  496. The Bison construct `%type' is used for declaring nonterminal
  497. symbols, just as `%token' is used for declaring token types. We have
  498. not used `%type' before because nonterminal symbols are normally
  499. declared implicitly by the rules that define them. But `exp' must be
  500. declared explicitly so we can specify its value type. *Note
  501. Nonterminal Symbols: Type Decl.
  502. 
  503. File: bison.info, Node: Mfcalc Rules, Next: Mfcalc Symtab, Prev: Mfcalc Decl, Up: Multi-function Calc
  504. Grammar Rules for `mfcalc'
  505. --------------------------
  506. Here are the grammar rules for the multi-function calculator. Most
  507. of them are copied directly from `calc'; three rules, those which
  508. mention `VAR' or `FNCT', are new.
  509. input: /* empty */
  510. | input line
  511. ;
  512. line:
  513. '\n'
  514. | exp '\n' { printf ("\t%.10g\n", $1); }
  515. | error '\n' { yyerrok; }
  516. ;
  517. exp: NUM { $$ = $1; }
  518. | VAR { $$ = $1->value.var; }
  519. | VAR '=' exp { $$ = $3; $1->value.var = $3; }
  520. | FNCT '(' exp ')' { $$ = (*($1->value.fnctptr))($3); }
  521. | exp '+' exp { $$ = $1 + $3; }
  522. | exp '-' exp { $$ = $1 - $3; }
  523. | exp '*' exp { $$ = $1 * $3; }
  524. | exp '/' exp { $$ = $1 / $3; }
  525. | '-' exp %prec NEG { $$ = -$2; }
  526. | exp '^' exp { $$ = pow ($1, $3); }
  527. | '(' exp ')' { $$ = $2; }
  528. ;
  529. /* End of grammar */
  530. %%
  531. 
  532. File: bison.info, Node: Mfcalc Symtab, Prev: Mfcalc Rules, Up: Multi-function Calc
  533. The `mfcalc' Symbol Table
  534. -------------------------
  535. The multi-function calculator requires a symbol table to keep track
  536. of the names and meanings of variables and functions. This doesn't
  537. affect the grammar rules (except for the actions) or the Bison
  538. declarations, but it requires some additional C functions for support.
  539. The symbol table itself consists of a linked list of records. Its
  540. definition, which is kept in the header `calc.h', is as follows. It
  541. provides for either functions or variables to be placed in the table.
  542. /* Data type for links in the chain of symbols. */
  543. struct symrec
  544. {
  545. char *name; /* name of symbol */
  546. int type; /* type of symbol: either VAR or FNCT */
  547. union {
  548. double var; /* value of a VAR */
  549. double (*fnctptr)(); /* value of a FNCT */
  550. } value;
  551. struct symrec *next; /* link field */
  552. };
  553. typedef struct symrec symrec;
  554. /* The symbol table: a chain of `struct symrec'. */
  555. extern symrec *sym_table;
  556. symrec *putsym ();
  557. symrec *getsym ();
  558. The new version of `main' includes a call to `init_table', a
  559. function that initializes the symbol table. Here it is, and
  560. `init_table' as well:
  561. #include <stdio.h>
  562. main ()
  563. {
  564. init_table ();
  565. yyparse ();
  566. }
  567. yyerror (s) /* Called by yyparse on error */
  568. char *s;
  569. {
  570. printf ("%s\n", s);
  571. }
  572. struct init
  573. {
  574. char *fname;
  575. double (*fnct)();
  576. };
  577. struct init arith_fncts[]
  578. = {
  579. "sin", sin,
  580. "cos", cos,
  581. "atan", atan,
  582. "ln", log,
  583. "exp", exp,
  584. "sqrt", sqrt,
  585. 0, 0
  586. };
  587. /* The symbol table: a chain of `struct symrec'. */
  588. symrec *sym_table = (symrec *)0;
  589. init_table () /* puts arithmetic functions in table. */
  590. {
  591. int i;
  592. symrec *ptr;
  593. for (i = 0; arith_fncts[i].fname != 0; i++)
  594. {
  595. ptr = putsym (arith_fncts[i].fname, FNCT);
  596. ptr->value.fnctptr = arith_fncts[i].fnct;
  597. }
  598. }
  599. By simply editing the initialization list and adding the necessary
  600. include files, you can add additional functions to the calculator.
  601. Two important functions allow look-up and installation of symbols in
  602. the symbol table. The function `putsym' is passed a name and the type
  603. (`VAR' or `FNCT') of the object to be installed. The object is linked
  604. to the front of the list, and a pointer to the object is returned. The
  605. function `getsym' is passed the name of the symbol to look up. If
  606. found, a pointer to that symbol is returned; otherwise zero is returned.
  607. symrec *
  608. putsym (sym_name,sym_type)
  609. char *sym_name;
  610. int sym_type;
  611. {
  612. symrec *ptr;
  613. ptr = (symrec *) malloc (sizeof (symrec));
  614. ptr->name = (char *) malloc (strlen (sym_name) + 1);
  615. strcpy (ptr->name,sym_name);
  616. ptr->type = sym_type;
  617. ptr->value.var = 0; /* set value to 0 even if fctn. */
  618. ptr->next = (struct symrec *)sym_table;
  619. sym_table = ptr;
  620. return ptr;
  621. }
  622. symrec *
  623. getsym (sym_name)
  624. char *sym_name;
  625. {
  626. symrec *ptr;
  627. for (ptr = sym_table; ptr != (symrec *) 0;
  628. ptr = (symrec *)ptr->next)
  629. if (strcmp (ptr->name,sym_name) == 0)
  630. return ptr;
  631. return 0;
  632. }
  633. The function `yylex' must now recognize variables, numeric values,
  634. and the single-character arithmetic operators. Strings of alphanumeric
  635. characters with a leading nondigit are recognized as either variables or
  636. functions depending on what the symbol table says about them.
  637. The string is passed to `getsym' for look up in the symbol table. If
  638. the name appears in the table, a pointer to its location and its type
  639. (`VAR' or `FNCT') is returned to `yyparse'. If it is not already in
  640. the table, then it is installed as a `VAR' using `putsym'. Again, a
  641. pointer and its type (which must be `VAR') is returned to `yyparse'.
  642. No change is needed in the handling of numeric values and arithmetic
  643. operators in `yylex'.
  644. #include <ctype.h>
  645. yylex ()
  646. {
  647. int c;
  648. /* Ignore whitespace, get first nonwhite character. */
  649. while ((c = getchar ()) == ' ' || c == '\t');
  650. if (c == EOF)
  651. return 0;
  652. /* Char starts a number => parse the number. */
  653. if (c == '.' || isdigit (c))
  654. {
  655. ungetc (c, stdin);
  656. scanf ("%lf", &yylval.val);
  657. return NUM;
  658. }
  659. /* Char starts an identifier => read the name. */
  660. if (isalpha (c))
  661. {
  662. symrec *s;
  663. static char *symbuf = 0;
  664. static int length = 0;
  665. int i;
  666. /* Initially make the buffer long enough
  667. for a 40-character symbol name. */
  668. if (length == 0)
  669. length = 40, symbuf = (char *)malloc (length + 1);
  670. i = 0;
  671. do
  672. {
  673. /* If buffer is full, make it bigger. */
  674. if (i == length)
  675. {
  676. length *= 2;
  677. symbuf = (char *)realloc (symbuf, length + 1);
  678. }
  679. /* Add this character to the buffer. */
  680. symbuf[i++] = c;
  681. /* Get another character. */
  682. c = getchar ();
  683. }
  684. while (c != EOF && isalnum (c));
  685. ungetc (c, stdin);
  686. symbuf[i] = '\0';
  687. s = getsym (symbuf);
  688. if (s == 0)
  689. s = putsym (symbuf, VAR);
  690. yylval.tptr = s;
  691. return s->type;
  692. }
  693. /* Any other character is a token by itself. */
  694. return c;
  695. }
  696. This program is both powerful and flexible. You may easily add new
  697. functions, and it is a simple job to modify this code to install
  698. predefined variables such as `pi' or `e' as well.
  699. 
  700. File: bison.info, Node: Exercises, Prev: Multi-function Calc, Up: Examples
  701. Exercises
  702. =========
  703. 1. Add some new functions from `math.h' to the initialization list.
  704. 2. Add another array that contains constants and their values. Then
  705. modify `init_table' to add these constants to the symbol table.
  706. It will be easiest to give the constants type `VAR'.
  707. 3. Make the program report an error if the user refers to an
  708. uninitialized variable in any way except to store a value in it.
  709. 
  710. File: bison.info, Node: Grammar File, Next: Interface, Prev: Examples, Up: Top
  711. Bison Grammar Files
  712. *******************
  713. Bison takes as input a context-free grammar specification and
  714. produces a C-language function that recognizes correct instances of the
  715. grammar.
  716. The Bison grammar input file conventionally has a name ending in
  717. `.y'.
  718. * Menu:
  719. * Grammar Outline:: Overall layout of the grammar file.
  720. * Symbols:: Terminal and nonterminal symbols.
  721. * Rules:: How to write grammar rules.
  722. * Recursion:: Writing recursive rules.
  723. * Semantics:: Semantic values and actions.
  724. * Declarations:: All kinds of Bison declarations are described here.
  725. * Multiple Parsers:: Putting more than one Bison parser in one program.
  726. 
  727. File: bison.info, Node: Grammar Outline, Next: Symbols, Up: Grammar File
  728. Outline of a Bison Grammar
  729. ==========================
  730. A Bison grammar file has four main sections, shown here with the
  731. appropriate delimiters:
  732. %{
  733. C DECLARATIONS
  734. %}
  735. BISON DECLARATIONS
  736. %%
  737. GRAMMAR RULES
  738. %%
  739. ADDITIONAL C CODE
  740. Comments enclosed in `/* ... */' may appear in any of the sections.
  741. * Menu:
  742. * C Declarations:: Syntax and usage of the C declarations section.
  743. * Bison Declarations:: Syntax and usage of the Bison declarations section.
  744. * Grammar Rules:: Syntax and usage of the grammar rules section.
  745. * C Code:: Syntax and usage of the additional C code section.
  746. 
  747. File: bison.info, Node: C Declarations, Next: Bison Declarations, Up: Grammar Outline
  748. The C Declarations Section
  749. --------------------------
  750. The C DECLARATIONS section contains macro definitions and
  751. declarations of functions and variables that are used in the actions in
  752. the grammar rules. These are copied to the beginning of the parser
  753. file so that they precede the definition of `yyparse'. You can use
  754. `#include' to get the declarations from a header file. If you don't
  755. need any C declarations, you may omit the `%{' and `%}' delimiters that
  756. bracket this section.
  757. 
  758. File: bison.info, Node: Bison Declarations, Next: Grammar Rules, Prev: C Declarations, Up: Grammar Outline
  759. The Bison Declarations Section
  760. ------------------------------
  761. The BISON DECLARATIONS section contains declarations that define
  762. terminal and nonterminal symbols, specify precedence, and so on. In
  763. some simple grammars you may not need any declarations. *Note Bison
  764. Declarations: Declarations.
  765. 
  766. File: bison.info, Node: Grammar Rules, Next: C Code, Prev: Bison Declarations, Up: Grammar Outline
  767. The Grammar Rules Section
  768. -------------------------
  769. The "grammar rules" section contains one or more Bison grammar
  770. rules, and nothing else. *Note Syntax of Grammar Rules: Rules.
  771. There must always be at least one grammar rule, and the first `%%'
  772. (which precedes the grammar rules) may never be omitted even if it is
  773. the first thing in the file.
  774. 
  775. File: bison.info, Node: C Code, Prev: Grammar Rules, Up: Grammar Outline
  776. The Additional C Code Section
  777. -----------------------------
  778. The ADDITIONAL C CODE section is copied verbatim to the end of the
  779. parser file, just as the C DECLARATIONS section is copied to the
  780. beginning. This is the most convenient place to put anything that you
  781. want to have in the parser file but which need not come before the
  782. definition of `yyparse'. For example, the definitions of `yylex' and
  783. `yyerror' often go here. *Note Parser C-Language Interface: Interface.
  784. If the last section is empty, you may omit the `%%' that separates it
  785. from the grammar rules.
  786. The Bison parser itself contains many static variables whose names
  787. start with `yy' and many macros whose names start with `YY'. It is a
  788. good idea to avoid using any such names (except those documented in this
  789. manual) in the additional C code section of the grammar file.
  790. 
  791. File: bison.info, Node: Symbols, Next: Rules, Prev: Grammar Outline, Up: Grammar File
  792. Symbols, Terminal and Nonterminal
  793. =================================
  794. "Symbols" in Bison grammars represent the grammatical classifications
  795. of the language.
  796. A "terminal symbol" (also known as a "token type") represents a
  797. class of syntactically equivalent tokens. You use the symbol in grammar
  798. rules to mean that a token in that class is allowed. The symbol is
  799. represented in the Bison parser by a numeric code, and the `yylex'
  800. function returns a token type code to indicate what kind of token has
  801. been read. You don't need to know what the code value is; you can use
  802. the symbol to stand for it.
  803. A "nonterminal symbol" stands for a class of syntactically equivalent
  804. groupings. The symbol name is used in writing grammar rules. By
  805. convention, it should be all lower case.
  806. Symbol names can contain letters, digits (not at the beginning),
  807. underscores and periods. Periods make sense only in nonterminals.
  808. There are three ways of writing terminal symbols in the grammar:
  809. * A "named token type" is written with an identifier, like an
  810. identifier in C. By convention, it should be all upper case. Each
  811. such name must be defined with a Bison declaration such as
  812. `%token'. *Note Token Type Names: Token Decl.
  813. * A "character token type" (or "literal token") is written in the
  814. grammar using the same syntax used in C for character constants;
  815. for example, `'+'' is a character token type. A character token
  816. type doesn't need to be declared unless you need to specify its
  817. semantic value data type (*note Data Types of Semantic Values:
  818. Value Type.), associativity, or precedence (*note Operator
  819. Precedence: Precedence.).
  820. By convention, a character token type is used only to represent a
  821. token that consists of that particular character. Thus, the token
  822. type `'+'' is used to represent the character `+' as a token.
  823. Nothing enforces this convention, but if you depart from it, your
  824. program will confuse other readers.
  825. All the usual escape sequences used in character literals in C can
  826. be used in Bison as well, but you must not use the null character
  827. as a character literal because its ASCII code, zero, is the code
  828. `yylex' returns for end-of-input (*note Calling Convention for
  829. `yylex': Calling Convention.).
  830. * WARNING: Use of string tokens such as `"<="' is incompatible with
  831. yacc.
  832. A "literal string token" is written in the grammar using the same
  833. syntax used in C for string constants; for example, `"<="' is a
  834. string literal. A string literal doesn't need to be declared
  835. unless you need to specify its semantic value data type (*note
  836. Value Type::.), associativity, precedence (*note Precedence::.).
  837. To associate a symbolic name with the string literal, use the
  838. `%thong' declaration (*note Thong Declarations: Thong Decl.);
  839. otherwise the lexical analyzer can retrieve the token number from
  840. the tables generated with the `-k' or `--token-table' switch.
  841. By convention, a string literal token is used only to represent a
  842. token that consists of that particular string. Thus, the token
  843. type `"<="' is used to represent the string `<=' as a token.
  844. Nothing enforces this convention, but if you depart from it, your
  845. program will confuse other readers.
  846. All the usual escape sequences used in string literals in C can be
  847. used in Bison as well. The contents of the string must be two or
  848. more characters; use a character token for a single character and
  849. `/*EMPTY*/' for the empty token.
  850. How you choose to write a terminal symbol has no effect on its
  851. grammatical meaning. That depends only on where it appears in rules and
  852. on when the parser function returns that symbol.
  853. The value returned by `yylex' is always one of the terminal symbols
  854. (or 0 for end-of-input). Whichever way you write the token type in the
  855. grammar rules, you write it the same way in the definition of `yylex'.
  856. The numeric code for a character token type is simply the ASCII code for
  857. the character, so `yylex' can use the identical character constant to
  858. generate the requisite code. Each named token type becomes a C macro in
  859. the parser file, so `yylex' can use the name to stand for the code.
  860. (This is why periods don't make sense in terminal symbols.) *Note
  861. Calling Convention for `yylex': Calling Convention.
  862. If `yylex' is defined in a separate file, you need to arrange for the
  863. token-type macro definitions to be available there. Use the `-d'
  864. option when you run Bison, so that it will write these macro definitions
  865. into a separate header file `NAME.tab.h' which you can include in the
  866. other source files that need it. *Note Invoking Bison: Invocation.
  867. The symbol `error' is a terminal symbol reserved for error recovery
  868. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  869. In particular, `yylex' should never return this value.
  870. 
  871. File: bison.info, Node: Rules, Next: Recursion, Prev: Symbols, Up: Grammar File
  872. Syntax of Grammar Rules
  873. =======================
  874. A Bison grammar rule has the following general form:
  875. RESULT: COMPONENTS...
  876. ;
  877. where RESULT is the nonterminal symbol that this rule describes and
  878. COMPONENTS are various terminal and nonterminal symbols that are put
  879. together by this rule (*note Symbols - Terminal and Nonterminal:
  880. Symbols.).
  881. For example,
  882. exp: exp '+' exp
  883. ;
  884. says that two groupings of type `exp', with a `+' token in between, can
  885. be combined into a larger grouping of type `exp'.
  886. Whitespace in rules is significant only to separate symbols. You
  887. can add extra whitespace as you wish.
  888. Scattered among the components can be ACTIONS that determine the
  889. semantics of the rule. An action looks like this:
  890. {C STATEMENTS}
  891. Usually there is only one action and it follows the components. *Note
  892. Actions::.
  893. Multiple rules for the same RESULT can be written separately or can
  894. be joined with the vertical-bar character `|' as follows:
  895. RESULT: RULE1-COMPONENTS...
  896. | RULE2-COMPONENTS...
  897. ...
  898. ;
  899. They are still considered distinct rules even when joined in this way.
  900. If COMPONENTS in a rule is empty, it means that RESULT can match the
  901. empty string. For example, here is how to define a comma-separated
  902. sequence of zero or more `exp' groupings:
  903. expseq: /* empty */
  904. | expseq1
  905. ;
  906. expseq1: exp
  907. | expseq1 ',' exp
  908. ;
  909. It is customary to write a comment `/* empty */' in each rule with no
  910. components.
  911. 
  912. File: bison.info, Node: Recursion, Next: Semantics, Prev: Rules, Up: Grammar File
  913. Recursive Rules
  914. ===============
  915. A rule is called "recursive" when its RESULT nonterminal appears
  916. also on its right hand side. Nearly all Bison grammars need to use
  917. recursion, because that is the only way to define a sequence of any
  918. number of somethings. Consider this recursive definition of a
  919. comma-separated sequence of one or more expressions:
  920. expseq1: exp
  921. | expseq1 ',' exp
  922. ;
  923. Since the recursive use of `expseq1' is the leftmost symbol in the
  924. right hand side, we call this "left recursion". By contrast, here the
  925. same construct is defined using "right recursion":
  926. expseq1: exp
  927. | exp ',' expseq1
  928. ;
  929. Any kind of sequence can be defined using either left recursion or
  930. right recursion, but you should always use left recursion, because it
  931. can parse a sequence of any number of elements with bounded stack
  932. space. Right recursion uses up space on the Bison stack in proportion
  933. to the number of elements in the sequence, because all the elements
  934. must be shifted onto the stack before the rule can be applied even
  935. once. *Note The Bison Parser Algorithm: Algorithm, for further
  936. explanation of this.
  937. "Indirect" or "mutual" recursion occurs when the result of the rule
  938. does not appear directly on its right hand side, but does appear in
  939. rules for other nonterminals which do appear on its right hand side.
  940. For example:
  941. expr: primary
  942. | primary '+' primary
  943. ;
  944. primary: constant
  945. | '(' expr ')'
  946. ;
  947. defines two mutually-recursive nonterminals, since each refers to the
  948. other.
  949. 
  950. File: bison.info, Node: Semantics, Next: Declarations, Prev: Recursion, Up: Grammar File
  951. Defining Language Semantics
  952. ===========================
  953. The grammar rules for a language determine only the syntax. The
  954. semantics are determined by the semantic values associated with various
  955. tokens and groupings, and by the actions taken when various groupings
  956. are recognized.
  957. For example, the calculator calculates properly because the value
  958. associated with each expression is the proper number; it adds properly
  959. because the action for the grouping `X + Y' is to add the numbers
  960. associated with X and Y.
  961. * Menu:
  962. * Value Type:: Specifying one data type for all semantic values.
  963. * Multiple Types:: Specifying several alternative data types.
  964. * Actions:: An action is the semantic definition of a grammar rule.
  965. * Action Types:: Specifying data types for actions to operate on.
  966. * Mid-Rule Actions:: Most actions go at the end of a rule.
  967. This says when, why and how to use the exceptional
  968. action in the middle of a rule.
  969. 
  970. File: bison.info, Node: Value Type, Next: Multiple Types, Up: Semantics
  971. Data Types of Semantic Values
  972. -----------------------------
  973. In a simple program it may be sufficient to use the same data type
  974. for the semantic values of all language constructs. This was true in
  975. the RPN and infix calculator examples (*note Reverse Polish Notation
  976. Calculator: RPN Calc.).
  977. Bison's default is to use type `int' for all semantic values. To
  978. specify some other type, define `YYSTYPE' as a macro, like this:
  979. #define YYSTYPE double
  980. This macro definition must go in the C declarations section of the
  981. grammar file (*note Outline of a Bison Grammar: Grammar Outline.).
  982. 
  983. File: bison.info, Node: Multiple Types, Next: Actions, Prev: Value Type, Up: Semantics
  984. More Than One Value Type
  985. ------------------------
  986. In most programs, you will need different data types for different
  987. kinds of tokens and groupings. For example, a numeric constant may
  988. need type `int' or `long', while a string constant needs type `char *',
  989. and an identifier might need a pointer to an entry in the symbol table.
  990. To use more than one data type for semantic values in one parser,
  991. Bison requires you to do two things:
  992. * Specify the entire collection of possible data types, with the
  993. `%union' Bison declaration (*note The Collection of Value Types:
  994. Union Decl.).
  995. * Choose one of those types for each symbol (terminal or nonterminal)
  996. for which semantic values are used. This is done for tokens with
  997. the `%token' Bison declaration (*note Token Type Names: Token
  998. Decl.) and for groupings with the `%type' Bison declaration (*note
  999. Nonterminal Symbols: Type Decl.).
  1000. 
  1001. File: bison.info, Node: Actions, Next: Action Types, Prev: Multiple Types, Up: Semantics
  1002. Actions
  1003. -------
  1004. An action accompanies a syntactic rule and contains C code to be
  1005. executed each time an instance of that rule is recognized. The task of
  1006. most actions is to compute a semantic value for the grouping built by
  1007. the rule from the semantic values associated with tokens or smaller
  1008. groupings.
  1009. An action consists of C statements surrounded by braces, much like a
  1010. compound statement in C. It can be placed at any position in the rule;
  1011. it is executed at that position. Most rules have just one action at
  1012. the end of the rule, following all the components. Actions in the
  1013. middle of a rule are tricky and used only for special purposes (*note
  1014. Actions in Mid-Rule: Mid-Rule Actions.).
  1015. The C code in an action can refer to the semantic values of the
  1016. components matched by the rule with the construct `$N', which stands for
  1017. the value of the Nth component. The semantic value for the grouping
  1018. being constructed is `$$'. (Bison translates both of these constructs
  1019. into array element references when it copies the actions into the parser
  1020. file.)
  1021. Here is a typical example:
  1022. exp: ...
  1023. | exp '+' exp
  1024. { $$ = $1 + $3; }
  1025. This rule constructs an `exp' from two smaller `exp' groupings
  1026. connected by a plus-sign token. In the action, `$1' and `$3' refer to
  1027. the semantic values of the two component `exp' groupings, which are the
  1028. first and third symbols on the right hand side of the rule. The sum is
  1029. stored into `$$' so that it becomes the semantic value of the
  1030. addition-expression just recognized by the rule. If there were a
  1031. useful semantic value associated with the `+' token, it could be
  1032. referred to as `$2'.
  1033. If you don't specify an action for a rule, Bison supplies a default:
  1034. `$$ = $1'. Thus, the value of the first symbol in the rule becomes the
  1035. value of the whole rule. Of course, the default rule is valid only if
  1036. the two data types match. There is no meaningful default action for an
  1037. empty rule; every empty rule must have an explicit action unless the
  1038. rule's value does not matter.
  1039. `$N' with N zero or negative is allowed for reference to tokens and
  1040. groupings on the stack *before* those that match the current rule.
  1041. This is a very risky practice, and to use it reliably you must be
  1042. certain of the context in which the rule is applied. Here is a case in
  1043. which you can use this reliably:
  1044. foo: expr bar '+' expr { ... }
  1045. | expr bar '-' expr { ... }
  1046. ;
  1047. bar: /* empty */
  1048. { previous_expr = $0; }
  1049. ;
  1050. As long as `bar' is used only in the fashion shown here, `$0' always
  1051. refers to the `expr' which precedes `bar' in the definition of `foo'.
  1052. 
  1053. File: bison.info, Node: Action Types, Next: Mid-Rule Actions, Prev: Actions, Up: Semantics
  1054. Data Types of Values in Actions
  1055. -------------------------------
  1056. If you have chosen a single data type for semantic values, the `$$'
  1057. and `$N' constructs always have that data type.
  1058. If you have used `%union' to specify a variety of data types, then
  1059. you must declare a choice among these types for each terminal or
  1060. nonterminal symbol that can have a semantic value. Then each time you
  1061. use `$$' or `$N', its data type is determined by which symbol it refers
  1062. to in the rule. In this example,
  1063. exp: ...
  1064. | exp '+' exp
  1065. { $$ = $1 + $3; }
  1066. `$1' and `$3' refer to instances of `exp', so they all have the data
  1067. type declared for the nonterminal symbol `exp'. If `$2' were used, it
  1068. would have the data type declared for the terminal symbol `'+'',
  1069. whatever that might be.
  1070. Alternatively, you can specify the data type when you refer to the
  1071. value, by inserting `<TYPE>' after the `$' at the beginning of the
  1072. reference. For example, if you have defined types as shown here:
  1073. %union {
  1074. int itype;
  1075. double dtype;
  1076. }
  1077. then you can write `$<itype>1' to refer to the first subunit of the
  1078. rule as an integer, or `$<dtype>1' to refer to it as a double.