bison.info-2 50 KB

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