bison.info-2 50 KB

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