]>
Commit | Line | Data |
---|---|---|
bfa74976 RS |
1 | \input texinfo @c -*-texinfo-*- |
2 | @comment %**start of header | |
3 | @setfilename bison.info | |
df1af54c JT |
4 | @include version.texi |
5 | @settitle Bison @value{VERSION} | |
bfa74976 RS |
6 | @setchapternewpage odd |
7 | ||
5378c3e7 DM |
8 | @iftex |
9 | @finalout | |
10 | @end iftex | |
11 | ||
13863333 | 12 | @c SMALL BOOK version |
bfa74976 | 13 | @c This edition has been formatted so that you can format and print it in |
13863333 | 14 | @c the smallbook format. |
bfa74976 RS |
15 | @c @smallbook |
16 | ||
bfa74976 RS |
17 | @c Set following if you have the new `shorttitlepage' command |
18 | @c @clear shorttitlepage-enabled | |
19 | @c @set shorttitlepage-enabled | |
20 | ||
21 | @c ISPELL CHECK: done, 14 Jan 1993 --bob | |
22 | ||
23 | @c Check COPYRIGHT dates. should be updated in the titlepage, ifinfo | |
24 | @c titlepage; should NOT be changed in the GPL. --mew | |
25 | ||
26 | @iftex | |
27 | @syncodeindex fn cp | |
28 | @syncodeindex vr cp | |
29 | @syncodeindex tp cp | |
30 | @end iftex | |
31 | @ifinfo | |
32 | @synindex fn cp | |
33 | @synindex vr cp | |
34 | @synindex tp cp | |
35 | @end ifinfo | |
36 | @comment %**end of header | |
37 | ||
bd773d73 JT |
38 | @ifinfo |
39 | @format | |
40 | START-INFO-DIR-ENTRY | |
41 | * bison: (bison). GNU Project parser generator (yacc replacement). | |
42 | END-INFO-DIR-ENTRY | |
43 | @end format | |
44 | @end ifinfo | |
45 | ||
bfa74976 RS |
46 | @ifinfo |
47 | This file documents the Bison parser generator. | |
48 | ||
13863333 AD |
49 | Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 1999, 2000 |
50 | Free Software Foundation, Inc. | |
bfa74976 RS |
51 | |
52 | Permission is granted to make and distribute verbatim copies of | |
53 | this manual provided the copyright notice and this permission notice | |
54 | are preserved on all copies. | |
55 | ||
56 | @ignore | |
57 | Permission is granted to process this file through Tex and print the | |
58 | results, provided the printed document carries copying permission | |
59 | notice identical to this one except for the removal of this paragraph | |
60 | (this paragraph not being relevant to the printed manual). | |
61 | ||
62 | @end ignore | |
63 | Permission is granted to copy and distribute modified versions of this | |
64 | manual under the conditions for verbatim copying, provided also that the | |
65 | sections entitled ``GNU General Public License'' and ``Conditions for | |
66 | Using Bison'' are included exactly as in the original, and provided that | |
67 | the entire resulting derived work is distributed under the terms of a | |
68 | permission notice identical to this one. | |
69 | ||
70 | Permission is granted to copy and distribute translations of this manual | |
71 | into another language, under the above conditions for modified versions, | |
72 | except that the sections entitled ``GNU General Public License'', | |
73 | ``Conditions for Using Bison'' and this permission notice may be | |
74 | included in translations approved by the Free Software Foundation | |
75 | instead of in the original English. | |
76 | @end ifinfo | |
77 | ||
78 | @ifset shorttitlepage-enabled | |
79 | @shorttitlepage Bison | |
80 | @end ifset | |
81 | @titlepage | |
82 | @title Bison | |
83 | @subtitle The YACC-compatible Parser Generator | |
df1af54c | 84 | @subtitle @value{UPDATED}, Bison Version @value{VERSION} |
bfa74976 RS |
85 | |
86 | @author by Charles Donnelly and Richard Stallman | |
87 | ||
88 | @page | |
89 | @vskip 0pt plus 1filll | |
13863333 AD |
90 | Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, |
91 | 1999, 2000 | |
92 | Free Software Foundation, Inc. | |
bfa74976 RS |
93 | |
94 | @sp 2 | |
95 | Published by the Free Software Foundation @* | |
931c7513 RS |
96 | 59 Temple Place, Suite 330 @* |
97 | Boston, MA 02111-1307 USA @* | |
9ecbd125 JT |
98 | Printed copies are available from the Free Software Foundation.@* |
99 | ISBN 1-882114-44-2 | |
bfa74976 RS |
100 | |
101 | Permission is granted to make and distribute verbatim copies of | |
102 | this manual provided the copyright notice and this permission notice | |
103 | are preserved on all copies. | |
104 | ||
105 | @ignore | |
106 | Permission is granted to process this file through TeX and print the | |
107 | results, provided the printed document carries copying permission | |
108 | notice identical to this one except for the removal of this paragraph | |
109 | (this paragraph not being relevant to the printed manual). | |
110 | ||
111 | @end ignore | |
112 | Permission is granted to copy and distribute modified versions of this | |
113 | manual under the conditions for verbatim copying, provided also that the | |
114 | sections entitled ``GNU General Public License'' and ``Conditions for | |
115 | Using Bison'' are included exactly as in the original, and provided that | |
116 | the entire resulting derived work is distributed under the terms of a | |
117 | permission notice identical to this one. | |
118 | ||
119 | Permission is granted to copy and distribute translations of this manual | |
120 | into another language, under the above conditions for modified versions, | |
121 | except that the sections entitled ``GNU General Public License'', | |
122 | ``Conditions for Using Bison'' and this permission notice may be | |
123 | included in translations approved by the Free Software Foundation | |
124 | instead of in the original English. | |
125 | @sp 2 | |
126 | Cover art by Etienne Suvasa. | |
127 | @end titlepage | |
d5796688 JT |
128 | |
129 | @contents | |
bfa74976 RS |
130 | |
131 | @node Top, Introduction, (dir), (dir) | |
132 | ||
133 | @ifinfo | |
df1af54c | 134 | This manual documents version @value{VERSION} of Bison. |
bfa74976 RS |
135 | @end ifinfo |
136 | ||
137 | @menu | |
13863333 AD |
138 | * Introduction:: |
139 | * Conditions:: | |
bfa74976 RS |
140 | * Copying:: The GNU General Public License says |
141 | how you can copy and share Bison | |
142 | ||
143 | Tutorial sections: | |
144 | * Concepts:: Basic concepts for understanding Bison. | |
145 | * Examples:: Three simple explained examples of using Bison. | |
146 | ||
147 | Reference sections: | |
148 | * Grammar File:: Writing Bison declarations and rules. | |
149 | * Interface:: C-language interface to the parser function @code{yyparse}. | |
150 | * Algorithm:: How the Bison parser works at run-time. | |
151 | * Error Recovery:: Writing rules for error recovery. | |
152 | * Context Dependency:: What to do if your language syntax is too | |
153 | messy for Bison to handle straightforwardly. | |
154 | * Debugging:: Debugging Bison parsers that parse wrong. | |
155 | * Invocation:: How to run Bison (to produce the parser source file). | |
156 | * Table of Symbols:: All the keywords of the Bison language are explained. | |
157 | * Glossary:: Basic concepts are explained. | |
158 | * Index:: Cross-references to the text. | |
159 | ||
160 | --- The Detailed Node Listing --- | |
161 | ||
162 | The Concepts of Bison | |
163 | ||
164 | * Language and Grammar:: Languages and context-free grammars, | |
165 | as mathematical ideas. | |
166 | * Grammar in Bison:: How we represent grammars for Bison's sake. | |
167 | * Semantic Values:: Each token or syntactic grouping can have | |
168 | a semantic value (the value of an integer, | |
169 | the name of an identifier, etc.). | |
170 | * Semantic Actions:: Each rule can have an action containing C code. | |
171 | * Bison Parser:: What are Bison's input and output, | |
172 | how is the output used? | |
173 | * Stages:: Stages in writing and running Bison grammars. | |
174 | * Grammar Layout:: Overall structure of a Bison grammar file. | |
175 | ||
176 | Examples | |
177 | ||
178 | * RPN Calc:: Reverse polish notation calculator; | |
179 | a first example with no operator precedence. | |
180 | * Infix Calc:: Infix (algebraic) notation calculator. | |
181 | Operator precedence is introduced. | |
182 | * Simple Error Recovery:: Continuing after syntax errors. | |
183 | * Multi-function Calc:: Calculator with memory and trig functions. | |
184 | It uses multiple data-types for semantic values. | |
185 | * Exercises:: Ideas for improving the multi-function calculator. | |
186 | ||
187 | Reverse Polish Notation Calculator | |
188 | ||
189 | * Decls: Rpcalc Decls. Bison and C declarations for rpcalc. | |
190 | * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation. | |
191 | * Lexer: Rpcalc Lexer. The lexical analyzer. | |
192 | * Main: Rpcalc Main. The controlling function. | |
193 | * Error: Rpcalc Error. The error reporting function. | |
194 | * Gen: Rpcalc Gen. Running Bison on the grammar file. | |
195 | * Comp: Rpcalc Compile. Run the C compiler on the output code. | |
196 | ||
197 | Grammar Rules for @code{rpcalc} | |
198 | ||
13863333 AD |
199 | * Rpcalc Input:: |
200 | * Rpcalc Line:: | |
201 | * Rpcalc Expr:: | |
bfa74976 RS |
202 | |
203 | Multi-Function Calculator: @code{mfcalc} | |
204 | ||
205 | * Decl: Mfcalc Decl. Bison declarations for multi-function calculator. | |
206 | * Rules: Mfcalc Rules. Grammar rules for the calculator. | |
207 | * Symtab: Mfcalc Symtab. Symbol table management subroutines. | |
208 | ||
209 | Bison Grammar Files | |
210 | ||
211 | * Grammar Outline:: Overall layout of the grammar file. | |
212 | * Symbols:: Terminal and nonterminal symbols. | |
213 | * Rules:: How to write grammar rules. | |
214 | * Recursion:: Writing recursive rules. | |
215 | * Semantics:: Semantic values and actions. | |
216 | * Declarations:: All kinds of Bison declarations are described here. | |
217 | * Multiple Parsers:: Putting more than one Bison parser in one program. | |
218 | ||
219 | Outline of a Bison Grammar | |
220 | ||
221 | * C Declarations:: Syntax and usage of the C declarations section. | |
222 | * Bison Declarations:: Syntax and usage of the Bison declarations section. | |
223 | * Grammar Rules:: Syntax and usage of the grammar rules section. | |
224 | * C Code:: Syntax and usage of the additional C code section. | |
225 | ||
226 | Defining Language Semantics | |
227 | ||
228 | * Value Type:: Specifying one data type for all semantic values. | |
229 | * Multiple Types:: Specifying several alternative data types. | |
230 | * Actions:: An action is the semantic definition of a grammar rule. | |
231 | * Action Types:: Specifying data types for actions to operate on. | |
232 | * Mid-Rule Actions:: Most actions go at the end of a rule. | |
233 | This says when, why and how to use the exceptional | |
234 | action in the middle of a rule. | |
235 | ||
236 | Bison Declarations | |
237 | ||
238 | * Token Decl:: Declaring terminal symbols. | |
239 | * Precedence Decl:: Declaring terminals with precedence and associativity. | |
240 | * Union Decl:: Declaring the set of all semantic value types. | |
241 | * Type Decl:: Declaring the choice of type for a nonterminal symbol. | |
242 | * Expect Decl:: Suppressing warnings about shift/reduce conflicts. | |
243 | * Start Decl:: Specifying the start symbol. | |
244 | * Pure Decl:: Requesting a reentrant parser. | |
245 | * Decl Summary:: Table of all Bison declarations. | |
246 | ||
247 | Parser C-Language Interface | |
248 | ||
249 | * Parser Function:: How to call @code{yyparse} and what it returns. | |
13863333 | 250 | * Lexical:: You must supply a function @code{yylex} |
bfa74976 RS |
251 | which reads tokens. |
252 | * Error Reporting:: You must supply a function @code{yyerror}. | |
253 | * Action Features:: Special features for use in actions. | |
254 | ||
255 | The Lexical Analyzer Function @code{yylex} | |
256 | ||
257 | * Calling Convention:: How @code{yyparse} calls @code{yylex}. | |
258 | * Token Values:: How @code{yylex} must return the semantic value | |
259 | of the token it has read. | |
260 | * Token Positions:: How @code{yylex} must return the text position | |
261 | (line number, etc.) of the token, if the | |
262 | actions want that. | |
263 | * Pure Calling:: How the calling convention differs | |
264 | in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}). | |
265 | ||
13863333 | 266 | The Bison Parser Algorithm |
bfa74976 RS |
267 | |
268 | * Look-Ahead:: Parser looks one token ahead when deciding what to do. | |
269 | * Shift/Reduce:: Conflicts: when either shifting or reduction is valid. | |
270 | * Precedence:: Operator precedence works by resolving conflicts. | |
271 | * Contextual Precedence:: When an operator's precedence depends on context. | |
272 | * Parser States:: The parser is a finite-state-machine with stack. | |
273 | * Reduce/Reduce:: When two rules are applicable in the same situation. | |
274 | * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified. | |
275 | * Stack Overflow:: What happens when stack gets full. How to avoid it. | |
276 | ||
277 | Operator Precedence | |
278 | ||
279 | * Why Precedence:: An example showing why precedence is needed. | |
280 | * Using Precedence:: How to specify precedence in Bison grammars. | |
281 | * Precedence Examples:: How these features are used in the previous example. | |
282 | * How Precedence:: How they work. | |
283 | ||
284 | Handling Context Dependencies | |
285 | ||
286 | * Semantic Tokens:: Token parsing can depend on the semantic context. | |
287 | * Lexical Tie-ins:: Token parsing can depend on the syntactic context. | |
288 | * Tie-in Recovery:: Lexical tie-ins have implications for how | |
289 | error recovery rules must be written. | |
290 | ||
291 | Invoking Bison | |
292 | ||
13863333 | 293 | * Bison Options:: All the options described in detail, |
bfa74976 RS |
294 | in alphabetical order by short options. |
295 | * Option Cross Key:: Alphabetical list of long options. | |
296 | * VMS Invocation:: Bison command syntax on VMS. | |
297 | @end menu | |
298 | ||
299 | @node Introduction, Conditions, Top, Top | |
300 | @unnumbered Introduction | |
301 | @cindex introduction | |
302 | ||
303 | @dfn{Bison} is a general-purpose parser generator that converts a | |
304 | grammar description for an LALR(1) context-free grammar into a C | |
305 | program to parse that grammar. Once you are proficient with Bison, | |
306 | you may use it to develop a wide range of language parsers, from those | |
307 | used in simple desk calculators to complex programming languages. | |
308 | ||
309 | Bison is upward compatible with Yacc: all properly-written Yacc grammars | |
310 | ought to work with Bison with no change. Anyone familiar with Yacc | |
311 | should be able to use Bison with little trouble. You need to be fluent in | |
312 | C programming in order to use Bison or to understand this manual. | |
313 | ||
314 | We begin with tutorial chapters that explain the basic concepts of using | |
315 | Bison and show three explained examples, each building on the last. If you | |
316 | don't know Bison or Yacc, start by reading these chapters. Reference | |
317 | chapters follow which describe specific aspects of Bison in detail. | |
318 | ||
931c7513 RS |
319 | Bison was written primarily by Robert Corbett; Richard Stallman made it |
320 | Yacc-compatible. Wilfred Hansen of Carnegie Mellon University added | |
14ded682 | 321 | multi-character string literals and other features. |
931c7513 | 322 | |
df1af54c | 323 | This edition corresponds to version @value{VERSION} of Bison. |
bfa74976 RS |
324 | |
325 | @node Conditions, Copying, Introduction, Top | |
326 | @unnumbered Conditions for Using Bison | |
327 | ||
a31239f1 | 328 | As of Bison version 1.24, we have changed the distribution terms for |
9ecbd125 | 329 | @code{yyparse} to permit using Bison's output in nonfree programs. |
a31239f1 RS |
330 | Formerly, Bison parsers could be used only in programs that were free |
331 | software. | |
332 | ||
333 | The other GNU programming tools, such as the GNU C compiler, have never | |
9ecbd125 | 334 | had such a requirement. They could always be used for nonfree |
a31239f1 RS |
335 | software. The reason Bison was different was not due to a special |
336 | policy decision; it resulted from applying the usual General Public | |
337 | License to all of the Bison source code. | |
338 | ||
339 | The output of the Bison utility---the Bison parser file---contains a | |
340 | verbatim copy of a sizable piece of Bison, which is the code for the | |
341 | @code{yyparse} function. (The actions from your grammar are inserted | |
342 | into this function at one point, but the rest of the function is not | |
343 | changed.) When we applied the GPL terms to the code for @code{yyparse}, | |
344 | the effect was to restrict the use of Bison output to free software. | |
345 | ||
346 | We didn't change the terms because of sympathy for people who want to | |
347 | make software proprietary. @strong{Software should be free.} But we | |
348 | concluded that limiting Bison's use to free software was doing little to | |
349 | encourage people to make other software free. So we decided to make the | |
350 | practical conditions for using Bison match the practical conditions for | |
351 | using the other GNU tools. | |
bfa74976 | 352 | |
c67a198d | 353 | @include gpl.texi |
bfa74976 RS |
354 | |
355 | @node Concepts, Examples, Copying, Top | |
356 | @chapter The Concepts of Bison | |
357 | ||
358 | This chapter introduces many of the basic concepts without which the | |
359 | details of Bison will not make sense. If you do not already know how to | |
360 | use Bison or Yacc, we suggest you start by reading this chapter carefully. | |
361 | ||
362 | @menu | |
363 | * Language and Grammar:: Languages and context-free grammars, | |
364 | as mathematical ideas. | |
365 | * Grammar in Bison:: How we represent grammars for Bison's sake. | |
366 | * Semantic Values:: Each token or syntactic grouping can have | |
367 | a semantic value (the value of an integer, | |
368 | the name of an identifier, etc.). | |
369 | * Semantic Actions:: Each rule can have an action containing C code. | |
847bf1f5 | 370 | * Locations Overview:: Tracking Locations. |
bfa74976 RS |
371 | * Bison Parser:: What are Bison's input and output, |
372 | how is the output used? | |
373 | * Stages:: Stages in writing and running Bison grammars. | |
374 | * Grammar Layout:: Overall structure of a Bison grammar file. | |
375 | @end menu | |
376 | ||
377 | @node Language and Grammar, Grammar in Bison, , Concepts | |
378 | @section Languages and Context-Free Grammars | |
379 | ||
bfa74976 RS |
380 | @cindex context-free grammar |
381 | @cindex grammar, context-free | |
382 | In order for Bison to parse a language, it must be described by a | |
383 | @dfn{context-free grammar}. This means that you specify one or more | |
384 | @dfn{syntactic groupings} and give rules for constructing them from their | |
385 | parts. For example, in the C language, one kind of grouping is called an | |
386 | `expression'. One rule for making an expression might be, ``An expression | |
387 | can be made of a minus sign and another expression''. Another would be, | |
388 | ``An expression can be an integer''. As you can see, rules are often | |
389 | recursive, but there must be at least one rule which leads out of the | |
390 | recursion. | |
391 | ||
392 | @cindex BNF | |
393 | @cindex Backus-Naur form | |
394 | The most common formal system for presenting such rules for humans to read | |
395 | is @dfn{Backus-Naur Form} or ``BNF'', which was developed in order to | |
396 | specify the language Algol 60. Any grammar expressed in BNF is a | |
397 | context-free grammar. The input to Bison is essentially machine-readable | |
398 | BNF. | |
399 | ||
400 | Not all context-free languages can be handled by Bison, only those | |
401 | that are LALR(1). In brief, this means that it must be possible to | |
402 | tell how to parse any portion of an input string with just a single | |
403 | token of look-ahead. Strictly speaking, that is a description of an | |
404 | LR(1) grammar, and LALR(1) involves additional restrictions that are | |
405 | hard to explain simply; but it is rare in actual practice to find an | |
406 | LR(1) grammar that fails to be LALR(1). @xref{Mystery Conflicts, , | |
407 | Mysterious Reduce/Reduce Conflicts}, for more information on this. | |
408 | ||
409 | @cindex symbols (abstract) | |
410 | @cindex token | |
411 | @cindex syntactic grouping | |
412 | @cindex grouping, syntactic | |
413 | In the formal grammatical rules for a language, each kind of syntactic unit | |
414 | or grouping is named by a @dfn{symbol}. Those which are built by grouping | |
415 | smaller constructs according to grammatical rules are called | |
416 | @dfn{nonterminal symbols}; those which can't be subdivided are called | |
417 | @dfn{terminal symbols} or @dfn{token types}. We call a piece of input | |
418 | corresponding to a single terminal symbol a @dfn{token}, and a piece | |
419 | corresponding to a single nonterminal symbol a @dfn{grouping}.@refill | |
420 | ||
421 | We can use the C language as an example of what symbols, terminal and | |
422 | nonterminal, mean. The tokens of C are identifiers, constants (numeric and | |
423 | string), and the various keywords, arithmetic operators and punctuation | |
424 | marks. So the terminal symbols of a grammar for C include `identifier', | |
425 | `number', `string', plus one symbol for each keyword, operator or | |
426 | punctuation mark: `if', `return', `const', `static', `int', `char', | |
427 | `plus-sign', `open-brace', `close-brace', `comma' and many more. (These | |
428 | tokens can be subdivided into characters, but that is a matter of | |
429 | lexicography, not grammar.) | |
430 | ||
431 | Here is a simple C function subdivided into tokens: | |
432 | ||
433 | @example | |
434 | int /* @r{keyword `int'} */ | |
435 | square (x) /* @r{identifier, open-paren,} */ | |
436 | /* @r{identifier, close-paren} */ | |
437 | int x; /* @r{keyword `int', identifier, semicolon} */ | |
438 | @{ /* @r{open-brace} */ | |
439 | return x * x; /* @r{keyword `return', identifier,} */ | |
440 | /* @r{asterisk, identifier, semicolon} */ | |
441 | @} /* @r{close-brace} */ | |
442 | @end example | |
443 | ||
444 | The syntactic groupings of C include the expression, the statement, the | |
445 | declaration, and the function definition. These are represented in the | |
446 | grammar of C by nonterminal symbols `expression', `statement', | |
447 | `declaration' and `function definition'. The full grammar uses dozens of | |
448 | additional language constructs, each with its own nonterminal symbol, in | |
449 | order to express the meanings of these four. The example above is a | |
450 | function definition; it contains one declaration, and one statement. In | |
451 | the statement, each @samp{x} is an expression and so is @samp{x * x}. | |
452 | ||
453 | Each nonterminal symbol must have grammatical rules showing how it is made | |
454 | out of simpler constructs. For example, one kind of C statement is the | |
455 | @code{return} statement; this would be described with a grammar rule which | |
456 | reads informally as follows: | |
457 | ||
458 | @quotation | |
459 | A `statement' can be made of a `return' keyword, an `expression' and a | |
460 | `semicolon'. | |
461 | @end quotation | |
462 | ||
463 | @noindent | |
464 | There would be many other rules for `statement', one for each kind of | |
465 | statement in C. | |
466 | ||
467 | @cindex start symbol | |
468 | One nonterminal symbol must be distinguished as the special one which | |
469 | defines a complete utterance in the language. It is called the @dfn{start | |
470 | symbol}. In a compiler, this means a complete input program. In the C | |
471 | language, the nonterminal symbol `sequence of definitions and declarations' | |
472 | plays this role. | |
473 | ||
474 | For example, @samp{1 + 2} is a valid C expression---a valid part of a C | |
475 | program---but it is not valid as an @emph{entire} C program. In the | |
476 | context-free grammar of C, this follows from the fact that `expression' is | |
477 | not the start symbol. | |
478 | ||
479 | The Bison parser reads a sequence of tokens as its input, and groups the | |
480 | tokens using the grammar rules. If the input is valid, the end result is | |
481 | that the entire token sequence reduces to a single grouping whose symbol is | |
482 | the grammar's start symbol. If we use a grammar for C, the entire input | |
483 | must be a `sequence of definitions and declarations'. If not, the parser | |
484 | reports a syntax error. | |
485 | ||
486 | @node Grammar in Bison, Semantic Values, Language and Grammar, Concepts | |
487 | @section From Formal Rules to Bison Input | |
488 | @cindex Bison grammar | |
489 | @cindex grammar, Bison | |
490 | @cindex formal grammar | |
491 | ||
492 | A formal grammar is a mathematical construct. To define the language | |
493 | for Bison, you must write a file expressing the grammar in Bison syntax: | |
494 | a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}. | |
495 | ||
496 | A nonterminal symbol in the formal grammar is represented in Bison input | |
497 | as an identifier, like an identifier in C. By convention, it should be | |
498 | in lower case, such as @code{expr}, @code{stmt} or @code{declaration}. | |
499 | ||
500 | The Bison representation for a terminal symbol is also called a @dfn{token | |
501 | type}. Token types as well can be represented as C-like identifiers. By | |
502 | convention, these identifiers should be upper case to distinguish them from | |
503 | nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or | |
504 | @code{RETURN}. A terminal symbol that stands for a particular keyword in | |
505 | the language should be named after that keyword converted to upper case. | |
506 | The terminal symbol @code{error} is reserved for error recovery. | |
931c7513 | 507 | @xref{Symbols}. |
bfa74976 RS |
508 | |
509 | A terminal symbol can also be represented as a character literal, just like | |
510 | a C character constant. You should do this whenever a token is just a | |
511 | single character (parenthesis, plus-sign, etc.): use that same character in | |
512 | a literal as the terminal symbol for that token. | |
513 | ||
931c7513 RS |
514 | A third way to represent a terminal symbol is with a C string constant |
515 | containing several characters. @xref{Symbols}, for more information. | |
516 | ||
bfa74976 RS |
517 | The grammar rules also have an expression in Bison syntax. For example, |
518 | here is the Bison rule for a C @code{return} statement. The semicolon in | |
519 | quotes is a literal character token, representing part of the C syntax for | |
520 | the statement; the naked semicolon, and the colon, are Bison punctuation | |
521 | used in every rule. | |
522 | ||
523 | @example | |
524 | stmt: RETURN expr ';' | |
525 | ; | |
526 | @end example | |
527 | ||
528 | @noindent | |
529 | @xref{Rules, ,Syntax of Grammar Rules}. | |
530 | ||
531 | @node Semantic Values, Semantic Actions, Grammar in Bison, Concepts | |
532 | @section Semantic Values | |
533 | @cindex semantic value | |
534 | @cindex value, semantic | |
535 | ||
536 | A formal grammar selects tokens only by their classifications: for example, | |
537 | if a rule mentions the terminal symbol `integer constant', it means that | |
538 | @emph{any} integer constant is grammatically valid in that position. The | |
539 | precise value of the constant is irrelevant to how to parse the input: if | |
540 | @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally | |
541 | grammatical.@refill | |
542 | ||
543 | But the precise value is very important for what the input means once it is | |
544 | parsed. A compiler is useless if it fails to distinguish between 4, 1 and | |
545 | 3989 as constants in the program! Therefore, each token in a Bison grammar | |
546 | has both a token type and a @dfn{semantic value}. @xref{Semantics, ,Defining Language Semantics}, | |
547 | for details. | |
548 | ||
549 | The token type is a terminal symbol defined in the grammar, such as | |
550 | @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything | |
551 | you need to know to decide where the token may validly appear and how to | |
552 | group it with other tokens. The grammar rules know nothing about tokens | |
553 | except their types.@refill | |
554 | ||
555 | The semantic value has all the rest of the information about the | |
556 | meaning of the token, such as the value of an integer, or the name of an | |
557 | identifier. (A token such as @code{','} which is just punctuation doesn't | |
558 | need to have any semantic value.) | |
559 | ||
560 | For example, an input token might be classified as token type | |
561 | @code{INTEGER} and have the semantic value 4. Another input token might | |
562 | have the same token type @code{INTEGER} but value 3989. When a grammar | |
563 | rule says that @code{INTEGER} is allowed, either of these tokens is | |
564 | acceptable because each is an @code{INTEGER}. When the parser accepts the | |
565 | token, it keeps track of the token's semantic value. | |
566 | ||
567 | Each grouping can also have a semantic value as well as its nonterminal | |
568 | symbol. For example, in a calculator, an expression typically has a | |
569 | semantic value that is a number. In a compiler for a programming | |
570 | language, an expression typically has a semantic value that is a tree | |
571 | structure describing the meaning of the expression. | |
572 | ||
847bf1f5 | 573 | @node Semantic Actions, Locations Overview, Semantic Values, Concepts |
bfa74976 RS |
574 | @section Semantic Actions |
575 | @cindex semantic actions | |
576 | @cindex actions, semantic | |
577 | ||
578 | In order to be useful, a program must do more than parse input; it must | |
579 | also produce some output based on the input. In a Bison grammar, a grammar | |
580 | rule can have an @dfn{action} made up of C statements. Each time the | |
581 | parser recognizes a match for that rule, the action is executed. | |
582 | @xref{Actions}. | |
13863333 | 583 | |
bfa74976 RS |
584 | Most of the time, the purpose of an action is to compute the semantic value |
585 | of the whole construct from the semantic values of its parts. For example, | |
586 | suppose we have a rule which says an expression can be the sum of two | |
587 | expressions. When the parser recognizes such a sum, each of the | |
588 | subexpressions has a semantic value which describes how it was built up. | |
589 | The action for this rule should create a similar sort of value for the | |
590 | newly recognized larger expression. | |
591 | ||
592 | For example, here is a rule that says an expression can be the sum of | |
593 | two subexpressions: | |
594 | ||
595 | @example | |
596 | expr: expr '+' expr @{ $$ = $1 + $3; @} | |
597 | ; | |
598 | @end example | |
599 | ||
600 | @noindent | |
601 | The action says how to produce the semantic value of the sum expression | |
602 | from the values of the two subexpressions. | |
603 | ||
847bf1f5 AD |
604 | @node Locations Overview, Bison Parser, Semantic Actions, Concepts |
605 | @section Locations | |
606 | @cindex location | |
607 | @cindex textual position | |
608 | @cindex position, textual | |
609 | ||
610 | Many applications, like interpreters or compilers, have to produce verbose | |
611 | and useful error messages. To achieve this, one must be able to keep track of | |
612 | the @dfn{textual position}, or @dfn{location}, of each syntactic construct. | |
613 | Bison provides a mechanism for handling these locations. | |
614 | ||
615 | Each token has a semantic value. In a similar fashion, each token has an | |
616 | associated location, but the type of locations is the same for all tokens and | |
617 | groupings. Moreover, the output parser is equipped with a default data | |
618 | structure for storing locations (@pxref{Locations}, for more details). | |
619 | ||
620 | Like semantic values, locations can be reached in actions using a dedicated | |
621 | set of constructs. In the example above, the location of the whole grouping | |
622 | is @code{@@$}, while the locations of the subexpressions are @code{@@1} and | |
623 | @code{@@3}. | |
624 | ||
625 | When a rule is matched, a default action is used to compute the semantic value | |
626 | of its left hand side (@pxref{Actions}). In the same way, another default | |
627 | action is used for locations. However, the action for locations is general | |
628 | enough for most cases, meaning there is usually no need to describe for each | |
629 | rule how @code{@@$} should be formed. When building a new location for a given | |
630 | grouping, the default behavior of the output parser is to take the beginning | |
631 | of the first symbol, and the end of the last symbol. | |
632 | ||
633 | @node Bison Parser, Stages, Locations Overview, Concepts | |
bfa74976 RS |
634 | @section Bison Output: the Parser File |
635 | @cindex Bison parser | |
636 | @cindex Bison utility | |
637 | @cindex lexical analyzer, purpose | |
638 | @cindex parser | |
639 | ||
640 | When you run Bison, you give it a Bison grammar file as input. The output | |
641 | is a C source file that parses the language described by the grammar. | |
642 | This file is called a @dfn{Bison parser}. Keep in mind that the Bison | |
643 | utility and the Bison parser are two distinct programs: the Bison utility | |
644 | is a program whose output is the Bison parser that becomes part of your | |
645 | program. | |
646 | ||
647 | The job of the Bison parser is to group tokens into groupings according to | |
648 | the grammar rules---for example, to build identifiers and operators into | |
649 | expressions. As it does this, it runs the actions for the grammar rules it | |
650 | uses. | |
651 | ||
652 | The tokens come from a function called the @dfn{lexical analyzer} that you | |
653 | must supply in some fashion (such as by writing it in C). The Bison parser | |
654 | calls the lexical analyzer each time it wants a new token. It doesn't know | |
655 | what is ``inside'' the tokens (though their semantic values may reflect | |
656 | this). Typically the lexical analyzer makes the tokens by parsing | |
657 | characters of text, but Bison does not depend on this. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}. | |
658 | ||
659 | The Bison parser file is C code which defines a function named | |
660 | @code{yyparse} which implements that grammar. This function does not make | |
661 | a complete C program: you must supply some additional functions. One is | |
662 | the lexical analyzer. Another is an error-reporting function which the | |
663 | parser calls to report an error. In addition, a complete C program must | |
664 | start with a function called @code{main}; you have to provide this, and | |
665 | arrange for it to call @code{yyparse} or the parser will never run. | |
666 | @xref{Interface, ,Parser C-Language Interface}. | |
667 | ||
668 | Aside from the token type names and the symbols in the actions you | |
669 | write, all variable and function names used in the Bison parser file | |
670 | begin with @samp{yy} or @samp{YY}. This includes interface functions | |
671 | such as the lexical analyzer function @code{yylex}, the error reporting | |
672 | function @code{yyerror} and the parser function @code{yyparse} itself. | |
673 | This also includes numerous identifiers used for internal purposes. | |
674 | Therefore, you should avoid using C identifiers starting with @samp{yy} | |
675 | or @samp{YY} in the Bison grammar file except for the ones defined in | |
676 | this manual. | |
677 | ||
678 | @node Stages, Grammar Layout, Bison Parser, Concepts | |
679 | @section Stages in Using Bison | |
680 | @cindex stages in using Bison | |
681 | @cindex using Bison | |
682 | ||
683 | The actual language-design process using Bison, from grammar specification | |
684 | to a working compiler or interpreter, has these parts: | |
685 | ||
686 | @enumerate | |
687 | @item | |
688 | Formally specify the grammar in a form recognized by Bison | |
689 | (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule in the language, | |
690 | describe the action that is to be taken when an instance of that rule | |
691 | is recognized. The action is described by a sequence of C statements. | |
692 | ||
693 | @item | |
694 | Write a lexical analyzer to process input and pass tokens to the | |
695 | parser. The lexical analyzer may be written by hand in C | |
696 | (@pxref{Lexical, ,The Lexical Analyzer Function @code{yylex}}). It could also be produced using Lex, but the use | |
697 | of Lex is not discussed in this manual. | |
698 | ||
699 | @item | |
700 | Write a controlling function that calls the Bison-produced parser. | |
701 | ||
702 | @item | |
703 | Write error-reporting routines. | |
704 | @end enumerate | |
705 | ||
706 | To turn this source code as written into a runnable program, you | |
707 | must follow these steps: | |
708 | ||
709 | @enumerate | |
710 | @item | |
711 | Run Bison on the grammar to produce the parser. | |
712 | ||
713 | @item | |
714 | Compile the code output by Bison, as well as any other source files. | |
715 | ||
716 | @item | |
717 | Link the object files to produce the finished product. | |
718 | @end enumerate | |
719 | ||
720 | @node Grammar Layout, , Stages, Concepts | |
721 | @section The Overall Layout of a Bison Grammar | |
722 | @cindex grammar file | |
723 | @cindex file format | |
724 | @cindex format of grammar file | |
725 | @cindex layout of Bison grammar | |
726 | ||
727 | The input file for the Bison utility is a @dfn{Bison grammar file}. The | |
728 | general form of a Bison grammar file is as follows: | |
729 | ||
730 | @example | |
731 | %@{ | |
732 | @var{C declarations} | |
733 | %@} | |
734 | ||
735 | @var{Bison declarations} | |
736 | ||
737 | %% | |
738 | @var{Grammar rules} | |
739 | %% | |
740 | @var{Additional C code} | |
741 | @end example | |
742 | ||
743 | @noindent | |
744 | The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears | |
745 | in every Bison grammar file to separate the sections. | |
746 | ||
747 | The C declarations may define types and variables used in the actions. | |
748 | You can also use preprocessor commands to define macros used there, and use | |
749 | @code{#include} to include header files that do any of these things. | |
750 | ||
751 | The Bison declarations declare the names of the terminal and nonterminal | |
752 | symbols, and may also describe operator precedence and the data types of | |
753 | semantic values of various symbols. | |
754 | ||
755 | The grammar rules define how to construct each nonterminal symbol from its | |
756 | parts. | |
757 | ||
758 | The additional C code can contain any C code you want to use. Often the | |
759 | definition of the lexical analyzer @code{yylex} goes here, plus subroutines | |
760 | called by the actions in the grammar rules. In a simple program, all the | |
761 | rest of the program can go here. | |
762 | ||
763 | @node Examples, Grammar File, Concepts, Top | |
764 | @chapter Examples | |
765 | @cindex simple examples | |
766 | @cindex examples, simple | |
767 | ||
768 | Now we show and explain three sample programs written using Bison: a | |
769 | reverse polish notation calculator, an algebraic (infix) notation | |
770 | calculator, and a multi-function calculator. All three have been tested | |
771 | under BSD Unix 4.3; each produces a usable, though limited, interactive | |
772 | desk-top calculator. | |
773 | ||
774 | These examples are simple, but Bison grammars for real programming | |
775 | languages are written the same way. | |
776 | @ifinfo | |
777 | You can copy these examples out of the Info file and into a source file | |
778 | to try them. | |
779 | @end ifinfo | |
780 | ||
781 | @menu | |
782 | * RPN Calc:: Reverse polish notation calculator; | |
783 | a first example with no operator precedence. | |
784 | * Infix Calc:: Infix (algebraic) notation calculator. | |
785 | Operator precedence is introduced. | |
786 | * Simple Error Recovery:: Continuing after syntax errors. | |
787 | * Multi-function Calc:: Calculator with memory and trig functions. | |
788 | It uses multiple data-types for semantic values. | |
789 | * Exercises:: Ideas for improving the multi-function calculator. | |
790 | @end menu | |
791 | ||
792 | @node RPN Calc, Infix Calc, , Examples | |
793 | @section Reverse Polish Notation Calculator | |
794 | @cindex reverse polish notation | |
795 | @cindex polish notation calculator | |
796 | @cindex @code{rpcalc} | |
797 | @cindex calculator, simple | |
798 | ||
799 | The first example is that of a simple double-precision @dfn{reverse polish | |
800 | notation} calculator (a calculator using postfix operators). This example | |
801 | provides a good starting point, since operator precedence is not an issue. | |
802 | The second example will illustrate how operator precedence is handled. | |
803 | ||
804 | The source code for this calculator is named @file{rpcalc.y}. The | |
805 | @samp{.y} extension is a convention used for Bison input files. | |
806 | ||
807 | @menu | |
808 | * Decls: Rpcalc Decls. Bison and C declarations for rpcalc. | |
809 | * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation. | |
810 | * Lexer: Rpcalc Lexer. The lexical analyzer. | |
811 | * Main: Rpcalc Main. The controlling function. | |
812 | * Error: Rpcalc Error. The error reporting function. | |
813 | * Gen: Rpcalc Gen. Running Bison on the grammar file. | |
814 | * Comp: Rpcalc Compile. Run the C compiler on the output code. | |
815 | @end menu | |
816 | ||
817 | @node Rpcalc Decls, Rpcalc Rules, , RPN Calc | |
818 | @subsection Declarations for @code{rpcalc} | |
819 | ||
820 | Here are the C and Bison declarations for the reverse polish notation | |
821 | calculator. As in C, comments are placed between @samp{/*@dots{}*/}. | |
822 | ||
823 | @example | |
824 | /* Reverse polish notation calculator. */ | |
825 | ||
826 | %@{ | |
827 | #define YYSTYPE double | |
828 | #include <math.h> | |
829 | %@} | |
830 | ||
831 | %token NUM | |
832 | ||
833 | %% /* Grammar rules and actions follow */ | |
834 | @end example | |
835 | ||
836 | The C declarations section (@pxref{C Declarations, ,The C Declarations Section}) contains two | |
837 | preprocessor directives. | |
838 | ||
839 | The @code{#define} directive defines the macro @code{YYSTYPE}, thus | |
840 | specifying the C data type for semantic values of both tokens and groupings | |
841 | (@pxref{Value Type, ,Data Types of Semantic Values}). The Bison parser will use whatever type | |
842 | @code{YYSTYPE} is defined as; if you don't define it, @code{int} is the | |
843 | default. Because we specify @code{double}, each token and each expression | |
844 | has an associated value, which is a floating point number. | |
845 | ||
846 | The @code{#include} directive is used to declare the exponentiation | |
847 | function @code{pow}. | |
848 | ||
849 | The second section, Bison declarations, provides information to Bison about | |
850 | the token types (@pxref{Bison Declarations, ,The Bison Declarations Section}). Each terminal symbol that is | |
851 | not a single-character literal must be declared here. (Single-character | |
852 | literals normally don't need to be declared.) In this example, all the | |
853 | arithmetic operators are designated by single-character literals, so the | |
854 | only terminal symbol that needs to be declared is @code{NUM}, the token | |
855 | type for numeric constants. | |
856 | ||
857 | @node Rpcalc Rules, Rpcalc Lexer, Rpcalc Decls, RPN Calc | |
858 | @subsection Grammar Rules for @code{rpcalc} | |
859 | ||
860 | Here are the grammar rules for the reverse polish notation calculator. | |
861 | ||
862 | @example | |
863 | input: /* empty */ | |
864 | | input line | |
865 | ; | |
866 | ||
867 | line: '\n' | |
868 | | exp '\n' @{ printf ("\t%.10g\n", $1); @} | |
869 | ; | |
870 | ||
871 | exp: NUM @{ $$ = $1; @} | |
872 | | exp exp '+' @{ $$ = $1 + $2; @} | |
873 | | exp exp '-' @{ $$ = $1 - $2; @} | |
874 | | exp exp '*' @{ $$ = $1 * $2; @} | |
875 | | exp exp '/' @{ $$ = $1 / $2; @} | |
876 | /* Exponentiation */ | |
877 | | exp exp '^' @{ $$ = pow ($1, $2); @} | |
878 | /* Unary minus */ | |
879 | | exp 'n' @{ $$ = -$1; @} | |
880 | ; | |
881 | %% | |
882 | @end example | |
883 | ||
884 | The groupings of the rpcalc ``language'' defined here are the expression | |
885 | (given the name @code{exp}), the line of input (@code{line}), and the | |
886 | complete input transcript (@code{input}). Each of these nonterminal | |
887 | symbols has several alternate rules, joined by the @samp{|} punctuator | |
888 | which is read as ``or''. The following sections explain what these rules | |
889 | mean. | |
890 | ||
891 | The semantics of the language is determined by the actions taken when a | |
892 | grouping is recognized. The actions are the C code that appears inside | |
893 | braces. @xref{Actions}. | |
894 | ||
895 | You must specify these actions in C, but Bison provides the means for | |
896 | passing semantic values between the rules. In each action, the | |
897 | pseudo-variable @code{$$} stands for the semantic value for the grouping | |
898 | that the rule is going to construct. Assigning a value to @code{$$} is the | |
899 | main job of most actions. The semantic values of the components of the | |
900 | rule are referred to as @code{$1}, @code{$2}, and so on. | |
901 | ||
902 | @menu | |
13863333 AD |
903 | * Rpcalc Input:: |
904 | * Rpcalc Line:: | |
905 | * Rpcalc Expr:: | |
bfa74976 RS |
906 | @end menu |
907 | ||
908 | @node Rpcalc Input, Rpcalc Line, , Rpcalc Rules | |
909 | @subsubsection Explanation of @code{input} | |
910 | ||
911 | Consider the definition of @code{input}: | |
912 | ||
913 | @example | |
914 | input: /* empty */ | |
915 | | input line | |
916 | ; | |
917 | @end example | |
918 | ||
919 | This definition reads as follows: ``A complete input is either an empty | |
920 | string, or a complete input followed by an input line''. Notice that | |
921 | ``complete input'' is defined in terms of itself. This definition is said | |
922 | to be @dfn{left recursive} since @code{input} appears always as the | |
923 | leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}. | |
924 | ||
925 | The first alternative is empty because there are no symbols between the | |
926 | colon and the first @samp{|}; this means that @code{input} can match an | |
927 | empty string of input (no tokens). We write the rules this way because it | |
928 | is legitimate to type @kbd{Ctrl-d} right after you start the calculator. | |
929 | It's conventional to put an empty alternative first and write the comment | |
930 | @samp{/* empty */} in it. | |
931 | ||
932 | The second alternate rule (@code{input line}) handles all nontrivial input. | |
933 | It means, ``After reading any number of lines, read one more line if | |
934 | possible.'' The left recursion makes this rule into a loop. Since the | |
935 | first alternative matches empty input, the loop can be executed zero or | |
936 | more times. | |
937 | ||
938 | The parser function @code{yyparse} continues to process input until a | |
939 | grammatical error is seen or the lexical analyzer says there are no more | |
940 | input tokens; we will arrange for the latter to happen at end of file. | |
941 | ||
942 | @node Rpcalc Line, Rpcalc Expr, Rpcalc Input, Rpcalc Rules | |
943 | @subsubsection Explanation of @code{line} | |
944 | ||
945 | Now consider the definition of @code{line}: | |
946 | ||
947 | @example | |
948 | line: '\n' | |
949 | | exp '\n' @{ printf ("\t%.10g\n", $1); @} | |
950 | ; | |
951 | @end example | |
952 | ||
953 | The first alternative is a token which is a newline character; this means | |
954 | that rpcalc accepts a blank line (and ignores it, since there is no | |
955 | action). The second alternative is an expression followed by a newline. | |
956 | This is the alternative that makes rpcalc useful. The semantic value of | |
957 | the @code{exp} grouping is the value of @code{$1} because the @code{exp} in | |
958 | question is the first symbol in the alternative. The action prints this | |
959 | value, which is the result of the computation the user asked for. | |
960 | ||
961 | This action is unusual because it does not assign a value to @code{$$}. As | |
962 | a consequence, the semantic value associated with the @code{line} is | |
963 | uninitialized (its value will be unpredictable). This would be a bug if | |
964 | that value were ever used, but we don't use it: once rpcalc has printed the | |
965 | value of the user's input line, that value is no longer needed. | |
966 | ||
967 | @node Rpcalc Expr, , Rpcalc Line, Rpcalc Rules | |
968 | @subsubsection Explanation of @code{expr} | |
969 | ||
970 | The @code{exp} grouping has several rules, one for each kind of expression. | |
971 | The first rule handles the simplest expressions: those that are just numbers. | |
972 | The second handles an addition-expression, which looks like two expressions | |
973 | followed by a plus-sign. The third handles subtraction, and so on. | |
974 | ||
975 | @example | |
976 | exp: NUM | |
977 | | exp exp '+' @{ $$ = $1 + $2; @} | |
978 | | exp exp '-' @{ $$ = $1 - $2; @} | |
979 | @dots{} | |
980 | ; | |
981 | @end example | |
982 | ||
983 | We have used @samp{|} to join all the rules for @code{exp}, but we could | |
984 | equally well have written them separately: | |
985 | ||
986 | @example | |
987 | exp: NUM ; | |
988 | exp: exp exp '+' @{ $$ = $1 + $2; @} ; | |
989 | exp: exp exp '-' @{ $$ = $1 - $2; @} ; | |
990 | @dots{} | |
991 | @end example | |
992 | ||
993 | Most of the rules have actions that compute the value of the expression in | |
994 | terms of the value of its parts. For example, in the rule for addition, | |
995 | @code{$1} refers to the first component @code{exp} and @code{$2} refers to | |
996 | the second one. The third component, @code{'+'}, has no meaningful | |
997 | associated semantic value, but if it had one you could refer to it as | |
998 | @code{$3}. When @code{yyparse} recognizes a sum expression using this | |
999 | rule, the sum of the two subexpressions' values is produced as the value of | |
1000 | the entire expression. @xref{Actions}. | |
1001 | ||
1002 | You don't have to give an action for every rule. When a rule has no | |
1003 | action, Bison by default copies the value of @code{$1} into @code{$$}. | |
1004 | This is what happens in the first rule (the one that uses @code{NUM}). | |
1005 | ||
1006 | The formatting shown here is the recommended convention, but Bison does | |
1007 | not require it. You can add or change whitespace as much as you wish. | |
1008 | For example, this: | |
1009 | ||
1010 | @example | |
1011 | exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{} | |
1012 | @end example | |
1013 | ||
1014 | @noindent | |
1015 | means the same thing as this: | |
1016 | ||
1017 | @example | |
1018 | exp: NUM | |
1019 | | exp exp '+' @{ $$ = $1 + $2; @} | |
1020 | | @dots{} | |
1021 | @end example | |
1022 | ||
1023 | @noindent | |
1024 | The latter, however, is much more readable. | |
1025 | ||
1026 | @node Rpcalc Lexer, Rpcalc Main, Rpcalc Rules, RPN Calc | |
1027 | @subsection The @code{rpcalc} Lexical Analyzer | |
1028 | @cindex writing a lexical analyzer | |
1029 | @cindex lexical analyzer, writing | |
1030 | ||
1031 | The lexical analyzer's job is low-level parsing: converting characters or | |
1032 | sequences of characters into tokens. The Bison parser gets its tokens by | |
1033 | calling the lexical analyzer. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}. | |
1034 | ||
1035 | Only a simple lexical analyzer is needed for the RPN calculator. This | |
1036 | lexical analyzer skips blanks and tabs, then reads in numbers as | |
1037 | @code{double} and returns them as @code{NUM} tokens. Any other character | |
1038 | that isn't part of a number is a separate token. Note that the token-code | |
1039 | for such a single-character token is the character itself. | |
1040 | ||
1041 | The return value of the lexical analyzer function is a numeric code which | |
1042 | represents a token type. The same text used in Bison rules to stand for | |
1043 | this token type is also a C expression for the numeric code for the type. | |
1044 | This works in two ways. If the token type is a character literal, then its | |
1045 | numeric code is the ASCII code for that character; you can use the same | |
1046 | character literal in the lexical analyzer to express the number. If the | |
1047 | token type is an identifier, that identifier is defined by Bison as a C | |
1048 | macro whose definition is the appropriate number. In this example, | |
1049 | therefore, @code{NUM} becomes a macro for @code{yylex} to use. | |
1050 | ||
1051 | The semantic value of the token (if it has one) is stored into the global | |
1052 | variable @code{yylval}, which is where the Bison parser will look for it. | |
1053 | (The C data type of @code{yylval} is @code{YYSTYPE}, which was defined | |
1054 | at the beginning of the grammar; @pxref{Rpcalc Decls, ,Declarations for @code{rpcalc}}.) | |
1055 | ||
1056 | A token type code of zero is returned if the end-of-file is encountered. | |
1057 | (Bison recognizes any nonpositive value as indicating the end of the | |
1058 | input.) | |
1059 | ||
1060 | Here is the code for the lexical analyzer: | |
1061 | ||
1062 | @example | |
1063 | @group | |
13863333 | 1064 | /* Lexical analyzer returns a double floating point |
bfa74976 RS |
1065 | number on the stack and the token NUM, or the ASCII |
1066 | character read if not a number. Skips all blanks | |
1067 | and tabs, returns 0 for EOF. */ | |
1068 | ||
1069 | #include <ctype.h> | |
1070 | @end group | |
1071 | ||
1072 | @group | |
13863333 AD |
1073 | int |
1074 | yylex (void) | |
bfa74976 RS |
1075 | @{ |
1076 | int c; | |
1077 | ||
1078 | /* skip white space */ | |
13863333 | 1079 | while ((c = getchar ()) == ' ' || c == '\t') |
bfa74976 RS |
1080 | ; |
1081 | @end group | |
1082 | @group | |
1083 | /* process numbers */ | |
13863333 | 1084 | if (c == '.' || isdigit (c)) |
bfa74976 RS |
1085 | @{ |
1086 | ungetc (c, stdin); | |
1087 | scanf ("%lf", &yylval); | |
1088 | return NUM; | |
1089 | @} | |
1090 | @end group | |
1091 | @group | |
1092 | /* return end-of-file */ | |
13863333 | 1093 | if (c == EOF) |
bfa74976 RS |
1094 | return 0; |
1095 | /* return single chars */ | |
13863333 | 1096 | return c; |
bfa74976 RS |
1097 | @} |
1098 | @end group | |
1099 | @end example | |
1100 | ||
1101 | @node Rpcalc Main, Rpcalc Error, Rpcalc Lexer, RPN Calc | |
1102 | @subsection The Controlling Function | |
1103 | @cindex controlling function | |
1104 | @cindex main function in simple example | |
1105 | ||
1106 | In keeping with the spirit of this example, the controlling function is | |
1107 | kept to the bare minimum. The only requirement is that it call | |
1108 | @code{yyparse} to start the process of parsing. | |
1109 | ||
1110 | @example | |
1111 | @group | |
13863333 AD |
1112 | int |
1113 | main (void) | |
bfa74976 | 1114 | @{ |
13863333 | 1115 | return yyparse (); |
bfa74976 RS |
1116 | @} |
1117 | @end group | |
1118 | @end example | |
1119 | ||
1120 | @node Rpcalc Error, Rpcalc Gen, Rpcalc Main, RPN Calc | |
1121 | @subsection The Error Reporting Routine | |
1122 | @cindex error reporting routine | |
1123 | ||
1124 | When @code{yyparse} detects a syntax error, it calls the error reporting | |
13863333 AD |
1125 | function @code{yyerror} to print an error message (usually but not |
1126 | always @code{"parse error"}). It is up to the programmer to supply | |
1127 | @code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so | |
1128 | here is the definition we will use: | |
bfa74976 RS |
1129 | |
1130 | @example | |
1131 | @group | |
1132 | #include <stdio.h> | |
1133 | ||
13863333 AD |
1134 | void |
1135 | yyerror (const char *s) /* Called by yyparse on error */ | |
bfa74976 RS |
1136 | @{ |
1137 | printf ("%s\n", s); | |
1138 | @} | |
1139 | @end group | |
1140 | @end example | |
1141 | ||
1142 | After @code{yyerror} returns, the Bison parser may recover from the error | |
1143 | and continue parsing if the grammar contains a suitable error rule | |
1144 | (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We | |
1145 | have not written any error rules in this example, so any invalid input will | |
1146 | cause the calculator program to exit. This is not clean behavior for a | |
9ecbd125 | 1147 | real calculator, but it is adequate for the first example. |
bfa74976 RS |
1148 | |
1149 | @node Rpcalc Gen, Rpcalc Compile, Rpcalc Error, RPN Calc | |
1150 | @subsection Running Bison to Make the Parser | |
1151 | @cindex running Bison (introduction) | |
1152 | ||
ceed8467 AD |
1153 | Before running Bison to produce a parser, we need to decide how to |
1154 | arrange all the source code in one or more source files. For such a | |
1155 | simple example, the easiest thing is to put everything in one file. The | |
1156 | definitions of @code{yylex}, @code{yyerror} and @code{main} go at the | |
1157 | end, in the ``additional C code'' section of the file (@pxref{Grammar | |
1158 | Layout, ,The Overall Layout of a Bison Grammar}). | |
bfa74976 RS |
1159 | |
1160 | For a large project, you would probably have several source files, and use | |
1161 | @code{make} to arrange to recompile them. | |
1162 | ||
1163 | With all the source in a single file, you use the following command to | |
1164 | convert it into a parser file: | |
1165 | ||
1166 | @example | |
1167 | bison @var{file_name}.y | |
1168 | @end example | |
1169 | ||
1170 | @noindent | |
1171 | In this example the file was called @file{rpcalc.y} (for ``Reverse Polish | |
1172 | CALCulator''). Bison produces a file named @file{@var{file_name}.tab.c}, | |
1173 | removing the @samp{.y} from the original file name. The file output by | |
1174 | Bison contains the source code for @code{yyparse}. The additional | |
1175 | functions in the input file (@code{yylex}, @code{yyerror} and @code{main}) | |
1176 | are copied verbatim to the output. | |
1177 | ||
1178 | @node Rpcalc Compile, , Rpcalc Gen, RPN Calc | |
1179 | @subsection Compiling the Parser File | |
1180 | @cindex compiling the parser | |
1181 | ||
1182 | Here is how to compile and run the parser file: | |
1183 | ||
1184 | @example | |
1185 | @group | |
1186 | # @r{List files in current directory.} | |
1187 | % ls | |
1188 | rpcalc.tab.c rpcalc.y | |
1189 | @end group | |
1190 | ||
1191 | @group | |
1192 | # @r{Compile the Bison parser.} | |
1193 | # @r{@samp{-lm} tells compiler to search math library for @code{pow}.} | |
1194 | % cc rpcalc.tab.c -lm -o rpcalc | |
1195 | @end group | |
1196 | ||
1197 | @group | |
1198 | # @r{List files again.} | |
1199 | % ls | |
1200 | rpcalc rpcalc.tab.c rpcalc.y | |
1201 | @end group | |
1202 | @end example | |
1203 | ||
1204 | The file @file{rpcalc} now contains the executable code. Here is an | |
1205 | example session using @code{rpcalc}. | |
1206 | ||
1207 | @example | |
1208 | % rpcalc | |
1209 | 4 9 + | |
1210 | 13 | |
1211 | 3 7 + 3 4 5 *+- | |
1212 | -13 | |
1213 | 3 7 + 3 4 5 * + - n @r{Note the unary minus, @samp{n}} | |
1214 | 13 | |
1215 | 5 6 / 4 n + | |
1216 | -3.166666667 | |
1217 | 3 4 ^ @r{Exponentiation} | |
1218 | 81 | |
1219 | ^D @r{End-of-file indicator} | |
1220 | % | |
1221 | @end example | |
1222 | ||
1223 | @node Infix Calc, Simple Error Recovery, RPN Calc, Examples | |
1224 | @section Infix Notation Calculator: @code{calc} | |
1225 | @cindex infix notation calculator | |
1226 | @cindex @code{calc} | |
1227 | @cindex calculator, infix notation | |
1228 | ||
1229 | We now modify rpcalc to handle infix operators instead of postfix. Infix | |
1230 | notation involves the concept of operator precedence and the need for | |
1231 | parentheses nested to arbitrary depth. Here is the Bison code for | |
1232 | @file{calc.y}, an infix desk-top calculator. | |
1233 | ||
1234 | @example | |
1235 | /* Infix notation calculator--calc */ | |
1236 | ||
1237 | %@{ | |
1238 | #define YYSTYPE double | |
1239 | #include <math.h> | |
1240 | %@} | |
1241 | ||
1242 | /* BISON Declarations */ | |
1243 | %token NUM | |
1244 | %left '-' '+' | |
1245 | %left '*' '/' | |
1246 | %left NEG /* negation--unary minus */ | |
1247 | %right '^' /* exponentiation */ | |
1248 | ||
1249 | /* Grammar follows */ | |
1250 | %% | |
1251 | input: /* empty string */ | |
1252 | | input line | |
1253 | ; | |
1254 | ||
1255 | line: '\n' | |
1256 | | exp '\n' @{ printf ("\t%.10g\n", $1); @} | |
1257 | ; | |
1258 | ||
1259 | exp: NUM @{ $$ = $1; @} | |
1260 | | exp '+' exp @{ $$ = $1 + $3; @} | |
1261 | | exp '-' exp @{ $$ = $1 - $3; @} | |
1262 | | exp '*' exp @{ $$ = $1 * $3; @} | |
1263 | | exp '/' exp @{ $$ = $1 / $3; @} | |
1264 | | '-' exp %prec NEG @{ $$ = -$2; @} | |
1265 | | exp '^' exp @{ $$ = pow ($1, $3); @} | |
1266 | | '(' exp ')' @{ $$ = $2; @} | |
1267 | ; | |
1268 | %% | |
1269 | @end example | |
1270 | ||
1271 | @noindent | |
ceed8467 AD |
1272 | The functions @code{yylex}, @code{yyerror} and @code{main} can be the |
1273 | same as before. | |
bfa74976 RS |
1274 | |
1275 | There are two important new features shown in this code. | |
1276 | ||
1277 | In the second section (Bison declarations), @code{%left} declares token | |
1278 | types and says they are left-associative operators. The declarations | |
1279 | @code{%left} and @code{%right} (right associativity) take the place of | |
1280 | @code{%token} which is used to declare a token type name without | |
1281 | associativity. (These tokens are single-character literals, which | |
1282 | ordinarily don't need to be declared. We declare them here to specify | |
1283 | the associativity.) | |
1284 | ||
1285 | Operator precedence is determined by the line ordering of the | |
1286 | declarations; the higher the line number of the declaration (lower on | |
1287 | the page or screen), the higher the precedence. Hence, exponentiation | |
1288 | has the highest precedence, unary minus (@code{NEG}) is next, followed | |
1289 | by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator Precedence}. | |
1290 | ||
1291 | The other important new feature is the @code{%prec} in the grammar section | |
1292 | for the unary minus operator. The @code{%prec} simply instructs Bison that | |
1293 | the rule @samp{| '-' exp} has the same precedence as @code{NEG}---in this | |
1294 | case the next-to-highest. @xref{Contextual Precedence, ,Context-Dependent Precedence}. | |
1295 | ||
1296 | Here is a sample run of @file{calc.y}: | |
1297 | ||
1298 | @need 500 | |
1299 | @example | |
1300 | % calc | |
1301 | 4 + 4.5 - (34/(8*3+-3)) | |
1302 | 6.880952381 | |
1303 | -56 + 2 | |
1304 | -54 | |
1305 | 3 ^ 2 | |
1306 | 9 | |
1307 | @end example | |
1308 | ||
1309 | @node Simple Error Recovery, Multi-function Calc, Infix Calc, Examples | |
1310 | @section Simple Error Recovery | |
1311 | @cindex error recovery, simple | |
1312 | ||
1313 | Up to this point, this manual has not addressed the issue of @dfn{error | |
1314 | recovery}---how to continue parsing after the parser detects a syntax | |
ceed8467 AD |
1315 | error. All we have handled is error reporting with @code{yyerror}. |
1316 | Recall that by default @code{yyparse} returns after calling | |
1317 | @code{yyerror}. This means that an erroneous input line causes the | |
1318 | calculator program to exit. Now we show how to rectify this deficiency. | |
bfa74976 RS |
1319 | |
1320 | The Bison language itself includes the reserved word @code{error}, which | |
1321 | may be included in the grammar rules. In the example below it has | |
1322 | been added to one of the alternatives for @code{line}: | |
1323 | ||
1324 | @example | |
1325 | @group | |
1326 | line: '\n' | |
1327 | | exp '\n' @{ printf ("\t%.10g\n", $1); @} | |
1328 | | error '\n' @{ yyerrok; @} | |
1329 | ; | |
1330 | @end group | |
1331 | @end example | |
1332 | ||
ceed8467 AD |
1333 | This addition to the grammar allows for simple error recovery in the |
1334 | event of a parse error. If an expression that cannot be evaluated is | |
1335 | read, the error will be recognized by the third rule for @code{line}, | |
1336 | and parsing will continue. (The @code{yyerror} function is still called | |
1337 | upon to print its message as well.) The action executes the statement | |
1338 | @code{yyerrok}, a macro defined automatically by Bison; its meaning is | |
1339 | that error recovery is complete (@pxref{Error Recovery}). Note the | |
1340 | difference between @code{yyerrok} and @code{yyerror}; neither one is a | |
1341 | misprint.@refill | |
bfa74976 RS |
1342 | |
1343 | This form of error recovery deals with syntax errors. There are other | |
1344 | kinds of errors; for example, division by zero, which raises an exception | |
1345 | signal that is normally fatal. A real calculator program must handle this | |
1346 | signal and use @code{longjmp} to return to @code{main} and resume parsing | |
1347 | input lines; it would also have to discard the rest of the current line of | |
1348 | input. We won't discuss this issue further because it is not specific to | |
1349 | Bison programs. | |
1350 | ||
1351 | @node Multi-function Calc, Exercises, Simple Error Recovery, Examples | |
1352 | @section Multi-Function Calculator: @code{mfcalc} | |
1353 | @cindex multi-function calculator | |
1354 | @cindex @code{mfcalc} | |
1355 | @cindex calculator, multi-function | |
1356 | ||
1357 | Now that the basics of Bison have been discussed, it is time to move on to | |
1358 | a more advanced problem. The above calculators provided only five | |
1359 | functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would | |
1360 | be nice to have a calculator that provides other mathematical functions such | |
1361 | as @code{sin}, @code{cos}, etc. | |
1362 | ||
1363 | It is easy to add new operators to the infix calculator as long as they are | |
1364 | only single-character literals. The lexical analyzer @code{yylex} passes | |
9ecbd125 | 1365 | back all nonnumber characters as tokens, so new grammar rules suffice for |
bfa74976 RS |
1366 | adding a new operator. But we want something more flexible: built-in |
1367 | functions whose syntax has this form: | |
1368 | ||
1369 | @example | |
1370 | @var{function_name} (@var{argument}) | |
1371 | @end example | |
1372 | ||
1373 | @noindent | |
1374 | At the same time, we will add memory to the calculator, by allowing you | |
1375 | to create named variables, store values in them, and use them later. | |
1376 | Here is a sample session with the multi-function calculator: | |
1377 | ||
1378 | @example | |
2a2e87db | 1379 | % mfcalc |
bfa74976 RS |
1380 | pi = 3.141592653589 |
1381 | 3.1415926536 | |
1382 | sin(pi) | |
1383 | 0.0000000000 | |
1384 | alpha = beta1 = 2.3 | |
1385 | 2.3000000000 | |
1386 | alpha | |
1387 | 2.3000000000 | |
1388 | ln(alpha) | |
1389 | 0.8329091229 | |
1390 | exp(ln(beta1)) | |
1391 | 2.3000000000 | |
1392 | % | |
1393 | @end example | |
1394 | ||
1395 | Note that multiple assignment and nested function calls are permitted. | |
1396 | ||
1397 | @menu | |
1398 | * Decl: Mfcalc Decl. Bison declarations for multi-function calculator. | |
1399 | * Rules: Mfcalc Rules. Grammar rules for the calculator. | |
1400 | * Symtab: Mfcalc Symtab. Symbol table management subroutines. | |
1401 | @end menu | |
1402 | ||
1403 | @node Mfcalc Decl, Mfcalc Rules, , Multi-function Calc | |
1404 | @subsection Declarations for @code{mfcalc} | |
1405 | ||
1406 | Here are the C and Bison declarations for the multi-function calculator. | |
1407 | ||
1408 | @smallexample | |
1409 | %@{ | |
1410 | #include <math.h> /* For math functions, cos(), sin(), etc. */ | |
1411 | #include "calc.h" /* Contains definition of `symrec' */ | |
1412 | %@} | |
1413 | %union @{ | |
1414 | double val; /* For returning numbers. */ | |
1415 | symrec *tptr; /* For returning symbol-table pointers */ | |
1416 | @} | |
1417 | ||
1418 | %token <val> NUM /* Simple double precision number */ | |
1419 | %token <tptr> VAR FNCT /* Variable and Function */ | |
1420 | %type <val> exp | |
1421 | ||
1422 | %right '=' | |
1423 | %left '-' '+' | |
1424 | %left '*' '/' | |
1425 | %left NEG /* Negation--unary minus */ | |
1426 | %right '^' /* Exponentiation */ | |
1427 | ||
1428 | /* Grammar follows */ | |
1429 | ||
1430 | %% | |
1431 | @end smallexample | |
1432 | ||
1433 | The above grammar introduces only two new features of the Bison language. | |
1434 | These features allow semantic values to have various data types | |
1435 | (@pxref{Multiple Types, ,More Than One Value Type}). | |
1436 | ||
1437 | The @code{%union} declaration specifies the entire list of possible types; | |
1438 | this is instead of defining @code{YYSTYPE}. The allowable types are now | |
1439 | double-floats (for @code{exp} and @code{NUM}) and pointers to entries in | |
1440 | the symbol table. @xref{Union Decl, ,The Collection of Value Types}. | |
1441 | ||
1442 | Since values can now have various types, it is necessary to associate a | |
1443 | type with each grammar symbol whose semantic value is used. These symbols | |
1444 | are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their | |
1445 | declarations are augmented with information about their data type (placed | |
1446 | between angle brackets). | |
1447 | ||
1448 | The Bison construct @code{%type} is used for declaring nonterminal symbols, | |
1449 | just as @code{%token} is used for declaring token types. We have not used | |
1450 | @code{%type} before because nonterminal symbols are normally declared | |
1451 | implicitly by the rules that define them. But @code{exp} must be declared | |
1452 | explicitly so we can specify its value type. @xref{Type Decl, ,Nonterminal Symbols}. | |
1453 | ||
1454 | @node Mfcalc Rules, Mfcalc Symtab, Mfcalc Decl, Multi-function Calc | |
1455 | @subsection Grammar Rules for @code{mfcalc} | |
1456 | ||
1457 | Here are the grammar rules for the multi-function calculator. | |
1458 | Most of them are copied directly from @code{calc}; three rules, | |
1459 | those which mention @code{VAR} or @code{FNCT}, are new. | |
1460 | ||
1461 | @smallexample | |
1462 | input: /* empty */ | |
1463 | | input line | |
1464 | ; | |
1465 | ||
1466 | line: | |
1467 | '\n' | |
1468 | | exp '\n' @{ printf ("\t%.10g\n", $1); @} | |
1469 | | error '\n' @{ yyerrok; @} | |
1470 | ; | |
1471 | ||
1472 | exp: NUM @{ $$ = $1; @} | |
1473 | | VAR @{ $$ = $1->value.var; @} | |
1474 | | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @} | |
1475 | | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @} | |
1476 | | exp '+' exp @{ $$ = $1 + $3; @} | |
1477 | | exp '-' exp @{ $$ = $1 - $3; @} | |
1478 | | exp '*' exp @{ $$ = $1 * $3; @} | |
1479 | | exp '/' exp @{ $$ = $1 / $3; @} | |
1480 | | '-' exp %prec NEG @{ $$ = -$2; @} | |
1481 | | exp '^' exp @{ $$ = pow ($1, $3); @} | |
1482 | | '(' exp ')' @{ $$ = $2; @} | |
1483 | ; | |
1484 | /* End of grammar */ | |
1485 | %% | |
1486 | @end smallexample | |
1487 | ||
1488 | @node Mfcalc Symtab, , Mfcalc Rules, Multi-function Calc | |
1489 | @subsection The @code{mfcalc} Symbol Table | |
1490 | @cindex symbol table example | |
1491 | ||
1492 | The multi-function calculator requires a symbol table to keep track of the | |
1493 | names and meanings of variables and functions. This doesn't affect the | |
1494 | grammar rules (except for the actions) or the Bison declarations, but it | |
1495 | requires some additional C functions for support. | |
1496 | ||
1497 | The symbol table itself consists of a linked list of records. Its | |
1498 | definition, which is kept in the header @file{calc.h}, is as follows. It | |
1499 | provides for either functions or variables to be placed in the table. | |
1500 | ||
1501 | @smallexample | |
1502 | @group | |
32dfccf8 AD |
1503 | /* Fonctions type. */ |
1504 | typedef double (*func_t) (double); | |
1505 | ||
bfa74976 RS |
1506 | /* Data type for links in the chain of symbols. */ |
1507 | struct symrec | |
1508 | @{ | |
1509 | char *name; /* name of symbol */ | |
1510 | int type; /* type of symbol: either VAR or FNCT */ | |
32dfccf8 AD |
1511 | union |
1512 | @{ | |
1513 | double var; /* value of a VAR */ | |
1514 | func_t fnctptr; /* value of a FNCT */ | |
bfa74976 RS |
1515 | @} value; |
1516 | struct symrec *next; /* link field */ | |
1517 | @}; | |
1518 | @end group | |
1519 | ||
1520 | @group | |
1521 | typedef struct symrec symrec; | |
1522 | ||
1523 | /* The symbol table: a chain of `struct symrec'. */ | |
1524 | extern symrec *sym_table; | |
1525 | ||
32dfccf8 AD |
1526 | symrec *putsym (const char *, func_t); |
1527 | symrec *getsym (const char *); | |
bfa74976 RS |
1528 | @end group |
1529 | @end smallexample | |
1530 | ||
1531 | The new version of @code{main} includes a call to @code{init_table}, a | |
1532 | function that initializes the symbol table. Here it is, and | |
1533 | @code{init_table} as well: | |
1534 | ||
1535 | @smallexample | |
1536 | @group | |
1537 | #include <stdio.h> | |
1538 | ||
13863333 AD |
1539 | int |
1540 | main (void) | |
bfa74976 RS |
1541 | @{ |
1542 | init_table (); | |
13863333 | 1543 | return yyparse (); |
bfa74976 RS |
1544 | @} |
1545 | @end group | |
1546 | ||
1547 | @group | |
13863333 AD |
1548 | void |
1549 | yyerror (const char *s) /* Called by yyparse on error */ | |
bfa74976 RS |
1550 | @{ |
1551 | printf ("%s\n", s); | |
1552 | @} | |
1553 | ||
1554 | struct init | |
1555 | @{ | |
1556 | char *fname; | |
32dfccf8 | 1557 | double (*fnct)(double); |
bfa74976 RS |
1558 | @}; |
1559 | @end group | |
1560 | ||
1561 | @group | |
13863333 AD |
1562 | struct init arith_fncts[] = |
1563 | @{ | |
32dfccf8 AD |
1564 | "sin", sin, |
1565 | "cos", cos, | |
13863333 | 1566 | "atan", atan, |
32dfccf8 AD |
1567 | "ln", log, |
1568 | "exp", exp, | |
13863333 AD |
1569 | "sqrt", sqrt, |
1570 | 0, 0 | |
1571 | @}; | |
bfa74976 RS |
1572 | |
1573 | /* The symbol table: a chain of `struct symrec'. */ | |
32dfccf8 | 1574 | symrec *sym_table = (symrec *) 0; |
bfa74976 RS |
1575 | @end group |
1576 | ||
1577 | @group | |
13863333 AD |
1578 | /* Put arithmetic functions in table. */ |
1579 | void | |
1580 | init_table (void) | |
bfa74976 RS |
1581 | @{ |
1582 | int i; | |
1583 | symrec *ptr; | |
1584 | for (i = 0; arith_fncts[i].fname != 0; i++) | |
1585 | @{ | |
1586 | ptr = putsym (arith_fncts[i].fname, FNCT); | |
1587 | ptr->value.fnctptr = arith_fncts[i].fnct; | |
1588 | @} | |
1589 | @} | |
1590 | @end group | |
1591 | @end smallexample | |
1592 | ||
1593 | By simply editing the initialization list and adding the necessary include | |
1594 | files, you can add additional functions to the calculator. | |
1595 | ||
1596 | Two important functions allow look-up and installation of symbols in the | |
1597 | symbol table. The function @code{putsym} is passed a name and the type | |
1598 | (@code{VAR} or @code{FNCT}) of the object to be installed. The object is | |
1599 | linked to the front of the list, and a pointer to the object is returned. | |
1600 | The function @code{getsym} is passed the name of the symbol to look up. If | |
1601 | found, a pointer to that symbol is returned; otherwise zero is returned. | |
1602 | ||
1603 | @smallexample | |
1604 | symrec * | |
13863333 | 1605 | putsym (char *sym_name, int sym_type) |
bfa74976 RS |
1606 | @{ |
1607 | symrec *ptr; | |
1608 | ptr = (symrec *) malloc (sizeof (symrec)); | |
1609 | ptr->name = (char *) malloc (strlen (sym_name) + 1); | |
1610 | strcpy (ptr->name,sym_name); | |
1611 | ptr->type = sym_type; | |
1612 | ptr->value.var = 0; /* set value to 0 even if fctn. */ | |
1613 | ptr->next = (struct symrec *)sym_table; | |
1614 | sym_table = ptr; | |
1615 | return ptr; | |
1616 | @} | |
1617 | ||
1618 | symrec * | |
13863333 | 1619 | getsym (const char *sym_name) |
bfa74976 RS |
1620 | @{ |
1621 | symrec *ptr; | |
1622 | for (ptr = sym_table; ptr != (symrec *) 0; | |
1623 | ptr = (symrec *)ptr->next) | |
1624 | if (strcmp (ptr->name,sym_name) == 0) | |
1625 | return ptr; | |
1626 | return 0; | |
1627 | @} | |
1628 | @end smallexample | |
1629 | ||
1630 | The function @code{yylex} must now recognize variables, numeric values, and | |
1631 | the single-character arithmetic operators. Strings of alphanumeric | |
14ded682 | 1632 | characters with a leading non-digit are recognized as either variables or |
bfa74976 RS |
1633 | functions depending on what the symbol table says about them. |
1634 | ||
1635 | The string is passed to @code{getsym} for look up in the symbol table. If | |
1636 | the name appears in the table, a pointer to its location and its type | |
1637 | (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not | |
1638 | already in the table, then it is installed as a @code{VAR} using | |
1639 | @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is | |
1640 | returned to @code{yyparse}.@refill | |
1641 | ||
1642 | No change is needed in the handling of numeric values and arithmetic | |
1643 | operators in @code{yylex}. | |
1644 | ||
1645 | @smallexample | |
1646 | @group | |
1647 | #include <ctype.h> | |
13863333 AD |
1648 | |
1649 | int | |
1650 | yylex (void) | |
bfa74976 RS |
1651 | @{ |
1652 | int c; | |
1653 | ||
1654 | /* Ignore whitespace, get first nonwhite character. */ | |
1655 | while ((c = getchar ()) == ' ' || c == '\t'); | |
1656 | ||
1657 | if (c == EOF) | |
1658 | return 0; | |
1659 | @end group | |
1660 | ||
1661 | @group | |
1662 | /* Char starts a number => parse the number. */ | |
1663 | if (c == '.' || isdigit (c)) | |
1664 | @{ | |
1665 | ungetc (c, stdin); | |
1666 | scanf ("%lf", &yylval.val); | |
1667 | return NUM; | |
1668 | @} | |
1669 | @end group | |
1670 | ||
1671 | @group | |
1672 | /* Char starts an identifier => read the name. */ | |
1673 | if (isalpha (c)) | |
1674 | @{ | |
1675 | symrec *s; | |
1676 | static char *symbuf = 0; | |
1677 | static int length = 0; | |
1678 | int i; | |
1679 | @end group | |
1680 | ||
1681 | @group | |
1682 | /* Initially make the buffer long enough | |
1683 | for a 40-character symbol name. */ | |
1684 | if (length == 0) | |
1685 | length = 40, symbuf = (char *)malloc (length + 1); | |
1686 | ||
1687 | i = 0; | |
1688 | do | |
1689 | @end group | |
1690 | @group | |
1691 | @{ | |
1692 | /* If buffer is full, make it bigger. */ | |
1693 | if (i == length) | |
1694 | @{ | |
1695 | length *= 2; | |
1696 | symbuf = (char *)realloc (symbuf, length + 1); | |
1697 | @} | |
1698 | /* Add this character to the buffer. */ | |
1699 | symbuf[i++] = c; | |
1700 | /* Get another character. */ | |
1701 | c = getchar (); | |
1702 | @} | |
1703 | @end group | |
1704 | @group | |
1705 | while (c != EOF && isalnum (c)); | |
1706 | ||
1707 | ungetc (c, stdin); | |
1708 | symbuf[i] = '\0'; | |
1709 | @end group | |
1710 | ||
1711 | @group | |
1712 | s = getsym (symbuf); | |
1713 | if (s == 0) | |
1714 | s = putsym (symbuf, VAR); | |
1715 | yylval.tptr = s; | |
1716 | return s->type; | |
1717 | @} | |
1718 | ||
1719 | /* Any other character is a token by itself. */ | |
1720 | return c; | |
1721 | @} | |
1722 | @end group | |
1723 | @end smallexample | |
1724 | ||
1725 | This program is both powerful and flexible. You may easily add new | |
1726 | functions, and it is a simple job to modify this code to install predefined | |
1727 | variables such as @code{pi} or @code{e} as well. | |
1728 | ||
1729 | @node Exercises, , Multi-function Calc, Examples | |
1730 | @section Exercises | |
1731 | @cindex exercises | |
1732 | ||
1733 | @enumerate | |
1734 | @item | |
1735 | Add some new functions from @file{math.h} to the initialization list. | |
1736 | ||
1737 | @item | |
1738 | Add another array that contains constants and their values. Then | |
1739 | modify @code{init_table} to add these constants to the symbol table. | |
1740 | It will be easiest to give the constants type @code{VAR}. | |
1741 | ||
1742 | @item | |
1743 | Make the program report an error if the user refers to an | |
1744 | uninitialized variable in any way except to store a value in it. | |
1745 | @end enumerate | |
1746 | ||
1747 | @node Grammar File, Interface, Examples, Top | |
1748 | @chapter Bison Grammar Files | |
1749 | ||
1750 | Bison takes as input a context-free grammar specification and produces a | |
1751 | C-language function that recognizes correct instances of the grammar. | |
1752 | ||
1753 | The Bison grammar input file conventionally has a name ending in @samp{.y}. | |
234a3be3 | 1754 | @xref{Invocation, ,Invoking Bison}. |
bfa74976 RS |
1755 | |
1756 | @menu | |
1757 | * Grammar Outline:: Overall layout of the grammar file. | |
1758 | * Symbols:: Terminal and nonterminal symbols. | |
1759 | * Rules:: How to write grammar rules. | |
1760 | * Recursion:: Writing recursive rules. | |
1761 | * Semantics:: Semantic values and actions. | |
847bf1f5 | 1762 | * Locations:: Locations and actions. |
bfa74976 RS |
1763 | * Declarations:: All kinds of Bison declarations are described here. |
1764 | * Multiple Parsers:: Putting more than one Bison parser in one program. | |
1765 | @end menu | |
1766 | ||
1767 | @node Grammar Outline, Symbols, , Grammar File | |
1768 | @section Outline of a Bison Grammar | |
1769 | ||
1770 | A Bison grammar file has four main sections, shown here with the | |
1771 | appropriate delimiters: | |
1772 | ||
1773 | @example | |
1774 | %@{ | |
1775 | @var{C declarations} | |
1776 | %@} | |
1777 | ||
1778 | @var{Bison declarations} | |
1779 | ||
1780 | %% | |
1781 | @var{Grammar rules} | |
1782 | %% | |
1783 | ||
1784 | @var{Additional C code} | |
1785 | @end example | |
1786 | ||
1787 | Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections. | |
1788 | ||
1789 | @menu | |
1790 | * C Declarations:: Syntax and usage of the C declarations section. | |
1791 | * Bison Declarations:: Syntax and usage of the Bison declarations section. | |
1792 | * Grammar Rules:: Syntax and usage of the grammar rules section. | |
1793 | * C Code:: Syntax and usage of the additional C code section. | |
1794 | @end menu | |
1795 | ||
1796 | @node C Declarations, Bison Declarations, , Grammar Outline | |
1797 | @subsection The C Declarations Section | |
1798 | @cindex C declarations section | |
1799 | @cindex declarations, C | |
1800 | ||
1801 | The @var{C declarations} section contains macro definitions and | |
1802 | declarations of functions and variables that are used in the actions in the | |
1803 | grammar rules. These are copied to the beginning of the parser file so | |
1804 | that they precede the definition of @code{yyparse}. You can use | |
1805 | @samp{#include} to get the declarations from a header file. If you don't | |
1806 | need any C declarations, you may omit the @samp{%@{} and @samp{%@}} | |
1807 | delimiters that bracket this section. | |
1808 | ||
1809 | @node Bison Declarations, Grammar Rules, C Declarations, Grammar Outline | |
1810 | @subsection The Bison Declarations Section | |
1811 | @cindex Bison declarations (introduction) | |
1812 | @cindex declarations, Bison (introduction) | |
1813 | ||
1814 | The @var{Bison declarations} section contains declarations that define | |
1815 | terminal and nonterminal symbols, specify precedence, and so on. | |
1816 | In some simple grammars you may not need any declarations. | |
1817 | @xref{Declarations, ,Bison Declarations}. | |
1818 | ||
1819 | @node Grammar Rules, C Code, Bison Declarations, Grammar Outline | |
1820 | @subsection The Grammar Rules Section | |
1821 | @cindex grammar rules section | |
1822 | @cindex rules section for grammar | |
1823 | ||
1824 | The @dfn{grammar rules} section contains one or more Bison grammar | |
1825 | rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}. | |
1826 | ||
1827 | There must always be at least one grammar rule, and the first | |
1828 | @samp{%%} (which precedes the grammar rules) may never be omitted even | |
1829 | if it is the first thing in the file. | |
1830 | ||
1831 | @node C Code, , Grammar Rules, Grammar Outline | |
1832 | @subsection The Additional C Code Section | |
1833 | @cindex additional C code section | |
1834 | @cindex C code, section for additional | |
1835 | ||
ceed8467 AD |
1836 | The @var{additional C code} section is copied verbatim to the end of the |
1837 | parser file, just as the @var{C declarations} section is copied to the | |
1838 | beginning. This is the most convenient place to put anything that you | |
1839 | want to have in the parser file but which need not come before the | |
1840 | definition of @code{yyparse}. For example, the definitions of | |
1841 | @code{yylex} and @code{yyerror} often go here. @xref{Interface, ,Parser | |
1842 | C-Language Interface}. | |
bfa74976 RS |
1843 | |
1844 | If the last section is empty, you may omit the @samp{%%} that separates it | |
1845 | from the grammar rules. | |
1846 | ||
1847 | The Bison parser itself contains many static variables whose names start | |
1848 | with @samp{yy} and many macros whose names start with @samp{YY}. It is a | |
1849 | good idea to avoid using any such names (except those documented in this | |
1850 | manual) in the additional C code section of the grammar file. | |
1851 | ||
1852 | @node Symbols, Rules, Grammar Outline, Grammar File | |
1853 | @section Symbols, Terminal and Nonterminal | |
1854 | @cindex nonterminal symbol | |
1855 | @cindex terminal symbol | |
1856 | @cindex token type | |
1857 | @cindex symbol | |
1858 | ||
1859 | @dfn{Symbols} in Bison grammars represent the grammatical classifications | |
1860 | of the language. | |
1861 | ||
1862 | A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a | |
1863 | class of syntactically equivalent tokens. You use the symbol in grammar | |
1864 | rules to mean that a token in that class is allowed. The symbol is | |
1865 | represented in the Bison parser by a numeric code, and the @code{yylex} | |
1866 | function returns a token type code to indicate what kind of token has been | |
1867 | read. You don't need to know what the code value is; you can use the | |
1868 | symbol to stand for it. | |
1869 | ||
1870 | A @dfn{nonterminal symbol} stands for a class of syntactically equivalent | |
1871 | groupings. The symbol name is used in writing grammar rules. By convention, | |
1872 | it should be all lower case. | |
1873 | ||
1874 | Symbol names can contain letters, digits (not at the beginning), | |
1875 | underscores and periods. Periods make sense only in nonterminals. | |
1876 | ||
931c7513 | 1877 | There are three ways of writing terminal symbols in the grammar: |
bfa74976 RS |
1878 | |
1879 | @itemize @bullet | |
1880 | @item | |
1881 | A @dfn{named token type} is written with an identifier, like an | |
1882 | identifier in C. By convention, it should be all upper case. Each | |
1883 | such name must be defined with a Bison declaration such as | |
1884 | @code{%token}. @xref{Token Decl, ,Token Type Names}. | |
1885 | ||
1886 | @item | |
1887 | @cindex character token | |
1888 | @cindex literal token | |
1889 | @cindex single-character literal | |
931c7513 RS |
1890 | A @dfn{character token type} (or @dfn{literal character token}) is |
1891 | written in the grammar using the same syntax used in C for character | |
1892 | constants; for example, @code{'+'} is a character token type. A | |
1893 | character token type doesn't need to be declared unless you need to | |
1894 | specify its semantic value data type (@pxref{Value Type, ,Data Types of | |
1895 | Semantic Values}), associativity, or precedence (@pxref{Precedence, | |
1896 | ,Operator Precedence}). | |
bfa74976 RS |
1897 | |
1898 | By convention, a character token type is used only to represent a | |
1899 | token that consists of that particular character. Thus, the token | |
1900 | type @code{'+'} is used to represent the character @samp{+} as a | |
1901 | token. Nothing enforces this convention, but if you depart from it, | |
1902 | your program will confuse other readers. | |
1903 | ||
1904 | All the usual escape sequences used in character literals in C can be | |
1905 | used in Bison as well, but you must not use the null character as a | |
931c7513 RS |
1906 | character literal because its ASCII code, zero, is the code @code{yylex} |
1907 | returns for end-of-input (@pxref{Calling Convention, ,Calling Convention | |
1908 | for @code{yylex}}). | |
1909 | ||
1910 | @item | |
1911 | @cindex string token | |
1912 | @cindex literal string token | |
9ecbd125 | 1913 | @cindex multicharacter literal |
931c7513 RS |
1914 | A @dfn{literal string token} is written like a C string constant; for |
1915 | example, @code{"<="} is a literal string token. A literal string token | |
1916 | doesn't need to be declared unless you need to specify its semantic | |
14ded682 | 1917 | value data type (@pxref{Value Type}), associativity, or precedence |
931c7513 RS |
1918 | (@pxref{Precedence}). |
1919 | ||
1920 | You can associate the literal string token with a symbolic name as an | |
1921 | alias, using the @code{%token} declaration (@pxref{Token Decl, ,Token | |
1922 | Declarations}). If you don't do that, the lexical analyzer has to | |
1923 | retrieve the token number for the literal string token from the | |
1924 | @code{yytname} table (@pxref{Calling Convention}). | |
1925 | ||
1926 | @strong{WARNING}: literal string tokens do not work in Yacc. | |
1927 | ||
1928 | By convention, a literal string token is used only to represent a token | |
1929 | that consists of that particular string. Thus, you should use the token | |
1930 | type @code{"<="} to represent the string @samp{<=} as a token. Bison | |
9ecbd125 | 1931 | does not enforce this convention, but if you depart from it, people who |
931c7513 RS |
1932 | read your program will be confused. |
1933 | ||
1934 | All the escape sequences used in string literals in C can be used in | |
1935 | Bison as well. A literal string token must contain two or more | |
1936 | characters; for a token containing just one character, use a character | |
1937 | token (see above). | |
bfa74976 RS |
1938 | @end itemize |
1939 | ||
1940 | How you choose to write a terminal symbol has no effect on its | |
1941 | grammatical meaning. That depends only on where it appears in rules and | |
1942 | on when the parser function returns that symbol. | |
1943 | ||
1944 | The value returned by @code{yylex} is always one of the terminal symbols | |
1945 | (or 0 for end-of-input). Whichever way you write the token type in the | |
1946 | grammar rules, you write it the same way in the definition of @code{yylex}. | |
1947 | The numeric code for a character token type is simply the ASCII code for | |
1948 | the character, so @code{yylex} can use the identical character constant to | |
1949 | generate the requisite code. Each named token type becomes a C macro in | |
1950 | the parser file, so @code{yylex} can use the name to stand for the code. | |
13863333 | 1951 | (This is why periods don't make sense in terminal symbols.) |
bfa74976 RS |
1952 | @xref{Calling Convention, ,Calling Convention for @code{yylex}}. |
1953 | ||
1954 | If @code{yylex} is defined in a separate file, you need to arrange for the | |
1955 | token-type macro definitions to be available there. Use the @samp{-d} | |
1956 | option when you run Bison, so that it will write these macro definitions | |
1957 | into a separate header file @file{@var{name}.tab.h} which you can include | |
1958 | in the other source files that need it. @xref{Invocation, ,Invoking Bison}. | |
1959 | ||
1960 | The symbol @code{error} is a terminal symbol reserved for error recovery | |
1961 | (@pxref{Error Recovery}); you shouldn't use it for any other purpose. | |
1962 | In particular, @code{yylex} should never return this value. | |
1963 | ||
1964 | @node Rules, Recursion, Symbols, Grammar File | |
1965 | @section Syntax of Grammar Rules | |
1966 | @cindex rule syntax | |
1967 | @cindex grammar rule syntax | |
1968 | @cindex syntax of grammar rules | |
1969 | ||
1970 | A Bison grammar rule has the following general form: | |
1971 | ||
1972 | @example | |
e425e872 | 1973 | @group |
bfa74976 RS |
1974 | @var{result}: @var{components}@dots{} |
1975 | ; | |
e425e872 | 1976 | @end group |
bfa74976 RS |
1977 | @end example |
1978 | ||
1979 | @noindent | |
9ecbd125 | 1980 | where @var{result} is the nonterminal symbol that this rule describes, |
bfa74976 | 1981 | and @var{components} are various terminal and nonterminal symbols that |
13863333 | 1982 | are put together by this rule (@pxref{Symbols}). |
bfa74976 RS |
1983 | |
1984 | For example, | |
1985 | ||
1986 | @example | |
1987 | @group | |
1988 | exp: exp '+' exp | |
1989 | ; | |
1990 | @end group | |
1991 | @end example | |
1992 | ||
1993 | @noindent | |
1994 | says that two groupings of type @code{exp}, with a @samp{+} token in between, | |
1995 | can be combined into a larger grouping of type @code{exp}. | |
1996 | ||
1997 | Whitespace in rules is significant only to separate symbols. You can add | |
1998 | extra whitespace as you wish. | |
1999 | ||
2000 | Scattered among the components can be @var{actions} that determine | |
2001 | the semantics of the rule. An action looks like this: | |
2002 | ||
2003 | @example | |
2004 | @{@var{C statements}@} | |
2005 | @end example | |
2006 | ||
2007 | @noindent | |
2008 | Usually there is only one action and it follows the components. | |
2009 | @xref{Actions}. | |
2010 | ||
2011 | @findex | | |
2012 | Multiple rules for the same @var{result} can be written separately or can | |
2013 | be joined with the vertical-bar character @samp{|} as follows: | |
2014 | ||
2015 | @ifinfo | |
2016 | @example | |
2017 | @var{result}: @var{rule1-components}@dots{} | |
2018 | | @var{rule2-components}@dots{} | |
2019 | @dots{} | |
2020 | ; | |
2021 | @end example | |
2022 | @end ifinfo | |
2023 | @iftex | |
2024 | @example | |
2025 | @group | |
2026 | @var{result}: @var{rule1-components}@dots{} | |
2027 | | @var{rule2-components}@dots{} | |
2028 | @dots{} | |
2029 | ; | |
2030 | @end group | |
2031 | @end example | |
2032 | @end iftex | |
2033 | ||
2034 | @noindent | |
2035 | They are still considered distinct rules even when joined in this way. | |
2036 | ||
2037 | If @var{components} in a rule is empty, it means that @var{result} can | |
2038 | match the empty string. For example, here is how to define a | |
2039 | comma-separated sequence of zero or more @code{exp} groupings: | |
2040 | ||
2041 | @example | |
2042 | @group | |
2043 | expseq: /* empty */ | |
2044 | | expseq1 | |
2045 | ; | |
2046 | @end group | |
2047 | ||
2048 | @group | |
2049 | expseq1: exp | |
2050 | | expseq1 ',' exp | |
2051 | ; | |
2052 | @end group | |
2053 | @end example | |
2054 | ||
2055 | @noindent | |
2056 | It is customary to write a comment @samp{/* empty */} in each rule | |
2057 | with no components. | |
2058 | ||
2059 | @node Recursion, Semantics, Rules, Grammar File | |
2060 | @section Recursive Rules | |
2061 | @cindex recursive rule | |
2062 | ||
2063 | A rule is called @dfn{recursive} when its @var{result} nonterminal appears | |
2064 | also on its right hand side. Nearly all Bison grammars need to use | |
2065 | recursion, because that is the only way to define a sequence of any number | |
9ecbd125 JT |
2066 | of a particular thing. Consider this recursive definition of a |
2067 | comma-separated sequence of one or more expressions: | |
bfa74976 RS |
2068 | |
2069 | @example | |
2070 | @group | |
2071 | expseq1: exp | |
2072 | | expseq1 ',' exp | |
2073 | ; | |
2074 | @end group | |
2075 | @end example | |
2076 | ||
2077 | @cindex left recursion | |
2078 | @cindex right recursion | |
2079 | @noindent | |
2080 | Since the recursive use of @code{expseq1} is the leftmost symbol in the | |
2081 | right hand side, we call this @dfn{left recursion}. By contrast, here | |
2082 | the same construct is defined using @dfn{right recursion}: | |
2083 | ||
2084 | @example | |
2085 | @group | |
2086 | expseq1: exp | |
2087 | | exp ',' expseq1 | |
2088 | ; | |
2089 | @end group | |
2090 | @end example | |
2091 | ||
2092 | @noindent | |
2093 | Any kind of sequence can be defined using either left recursion or | |
2094 | right recursion, but you should always use left recursion, because it | |
2095 | can parse a sequence of any number of elements with bounded stack | |
2096 | space. Right recursion uses up space on the Bison stack in proportion | |
2097 | to the number of elements in the sequence, because all the elements | |
2098 | must be shifted onto the stack before the rule can be applied even | |
2099 | once. @xref{Algorithm, ,The Bison Parser Algorithm }, for | |
2100 | further explanation of this. | |
2101 | ||
2102 | @cindex mutual recursion | |
2103 | @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the | |
2104 | rule does not appear directly on its right hand side, but does appear | |
2105 | in rules for other nonterminals which do appear on its right hand | |
13863333 | 2106 | side. |
bfa74976 RS |
2107 | |
2108 | For example: | |
2109 | ||
2110 | @example | |
2111 | @group | |
2112 | expr: primary | |
2113 | | primary '+' primary | |
2114 | ; | |
2115 | @end group | |
2116 | ||
2117 | @group | |
2118 | primary: constant | |
2119 | | '(' expr ')' | |
2120 | ; | |
2121 | @end group | |
2122 | @end example | |
2123 | ||
2124 | @noindent | |
2125 | defines two mutually-recursive nonterminals, since each refers to the | |
2126 | other. | |
2127 | ||
847bf1f5 | 2128 | @node Semantics, Locations, Recursion, Grammar File |
bfa74976 RS |
2129 | @section Defining Language Semantics |
2130 | @cindex defining language semantics | |
13863333 | 2131 | @cindex language semantics, defining |
bfa74976 RS |
2132 | |
2133 | The grammar rules for a language determine only the syntax. The semantics | |
2134 | are determined by the semantic values associated with various tokens and | |
2135 | groupings, and by the actions taken when various groupings are recognized. | |
2136 | ||
2137 | For example, the calculator calculates properly because the value | |
2138 | associated with each expression is the proper number; it adds properly | |
2139 | because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add | |
2140 | the numbers associated with @var{x} and @var{y}. | |
2141 | ||
2142 | @menu | |
2143 | * Value Type:: Specifying one data type for all semantic values. | |
2144 | * Multiple Types:: Specifying several alternative data types. | |
2145 | * Actions:: An action is the semantic definition of a grammar rule. | |
2146 | * Action Types:: Specifying data types for actions to operate on. | |
2147 | * Mid-Rule Actions:: Most actions go at the end of a rule. | |
2148 | This says when, why and how to use the exceptional | |
2149 | action in the middle of a rule. | |
2150 | @end menu | |
2151 | ||
2152 | @node Value Type, Multiple Types, , Semantics | |
2153 | @subsection Data Types of Semantic Values | |
2154 | @cindex semantic value type | |
2155 | @cindex value type, semantic | |
2156 | @cindex data types of semantic values | |
2157 | @cindex default data type | |
2158 | ||
2159 | In a simple program it may be sufficient to use the same data type for | |
2160 | the semantic values of all language constructs. This was true in the | |
2161 | RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish Notation Calculator}). | |
2162 | ||
2163 | Bison's default is to use type @code{int} for all semantic values. To | |
2164 | specify some other type, define @code{YYSTYPE} as a macro, like this: | |
2165 | ||
2166 | @example | |
2167 | #define YYSTYPE double | |
2168 | @end example | |
2169 | ||
2170 | @noindent | |
2171 | This macro definition must go in the C declarations section of the grammar | |
2172 | file (@pxref{Grammar Outline, ,Outline of a Bison Grammar}). | |
2173 | ||
2174 | @node Multiple Types, Actions, Value Type, Semantics | |
2175 | @subsection More Than One Value Type | |
2176 | ||
2177 | In most programs, you will need different data types for different kinds | |
2178 | of tokens and groupings. For example, a numeric constant may need type | |
2179 | @code{int} or @code{long}, while a string constant needs type @code{char *}, | |
2180 | and an identifier might need a pointer to an entry in the symbol table. | |
2181 | ||
2182 | To use more than one data type for semantic values in one parser, Bison | |
2183 | requires you to do two things: | |
2184 | ||
2185 | @itemize @bullet | |
2186 | @item | |
2187 | Specify the entire collection of possible data types, with the | |
2188 | @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of Value Types}). | |
2189 | ||
2190 | @item | |
14ded682 AD |
2191 | Choose one of those types for each symbol (terminal or nonterminal) for |
2192 | which semantic values are used. This is done for tokens with the | |
2193 | @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names}) | |
2194 | and for groupings with the @code{%type} Bison declaration (@pxref{Type | |
2195 | Decl, ,Nonterminal Symbols}). | |
bfa74976 RS |
2196 | @end itemize |
2197 | ||
2198 | @node Actions, Action Types, Multiple Types, Semantics | |
2199 | @subsection Actions | |
2200 | @cindex action | |
2201 | @vindex $$ | |
2202 | @vindex $@var{n} | |
2203 | ||
2204 | An action accompanies a syntactic rule and contains C code to be executed | |
2205 | each time an instance of that rule is recognized. The task of most actions | |
2206 | is to compute a semantic value for the grouping built by the rule from the | |
2207 | semantic values associated with tokens or smaller groupings. | |
2208 | ||
2209 | An action consists of C statements surrounded by braces, much like a | |
2210 | compound statement in C. It can be placed at any position in the rule; it | |
2211 | is executed at that position. Most rules have just one action at the end | |
2212 | of the rule, following all the components. Actions in the middle of a rule | |
2213 | are tricky and used only for special purposes (@pxref{Mid-Rule Actions, ,Actions in Mid-Rule}). | |
2214 | ||
2215 | The C code in an action can refer to the semantic values of the components | |
2216 | matched by the rule with the construct @code{$@var{n}}, which stands for | |
2217 | the value of the @var{n}th component. The semantic value for the grouping | |
2218 | being constructed is @code{$$}. (Bison translates both of these constructs | |
2219 | into array element references when it copies the actions into the parser | |
2220 | file.) | |
2221 | ||
2222 | Here is a typical example: | |
2223 | ||
2224 | @example | |
2225 | @group | |
2226 | exp: @dots{} | |
2227 | | exp '+' exp | |
2228 | @{ $$ = $1 + $3; @} | |
2229 | @end group | |
2230 | @end example | |
2231 | ||
2232 | @noindent | |
2233 | This rule constructs an @code{exp} from two smaller @code{exp} groupings | |
2234 | connected by a plus-sign token. In the action, @code{$1} and @code{$3} | |
2235 | refer to the semantic values of the two component @code{exp} groupings, | |
2236 | which are the first and third symbols on the right hand side of the rule. | |
2237 | The sum is stored into @code{$$} so that it becomes the semantic value of | |
2238 | the addition-expression just recognized by the rule. If there were a | |
2239 | useful semantic value associated with the @samp{+} token, it could be | |
2240 | referred to as @code{$2}.@refill | |
2241 | ||
2242 | @cindex default action | |
2243 | If you don't specify an action for a rule, Bison supplies a default: | |
2244 | @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule becomes | |
2245 | the value of the whole rule. Of course, the default rule is valid only | |
2246 | if the two data types match. There is no meaningful default action for | |
2247 | an empty rule; every empty rule must have an explicit action unless the | |
2248 | rule's value does not matter. | |
2249 | ||
2250 | @code{$@var{n}} with @var{n} zero or negative is allowed for reference | |
2251 | to tokens and groupings on the stack @emph{before} those that match the | |
2252 | current rule. This is a very risky practice, and to use it reliably | |
2253 | you must be certain of the context in which the rule is applied. Here | |
2254 | is a case in which you can use this reliably: | |
2255 | ||
2256 | @example | |
2257 | @group | |
2258 | foo: expr bar '+' expr @{ @dots{} @} | |
2259 | | expr bar '-' expr @{ @dots{} @} | |
2260 | ; | |
2261 | @end group | |
2262 | ||
2263 | @group | |
2264 | bar: /* empty */ | |
2265 | @{ previous_expr = $0; @} | |
2266 | ; | |
2267 | @end group | |
2268 | @end example | |
2269 | ||
2270 | As long as @code{bar} is used only in the fashion shown here, @code{$0} | |
2271 | always refers to the @code{expr} which precedes @code{bar} in the | |
2272 | definition of @code{foo}. | |
2273 | ||
2274 | @node Action Types, Mid-Rule Actions, Actions, Semantics | |
2275 | @subsection Data Types of Values in Actions | |
2276 | @cindex action data types | |
2277 | @cindex data types in actions | |
2278 | ||
2279 | If you have chosen a single data type for semantic values, the @code{$$} | |
2280 | and @code{$@var{n}} constructs always have that data type. | |
2281 | ||
2282 | If you have used @code{%union} to specify a variety of data types, then you | |
2283 | must declare a choice among these types for each terminal or nonterminal | |
2284 | symbol that can have a semantic value. Then each time you use @code{$$} or | |
2285 | @code{$@var{n}}, its data type is determined by which symbol it refers to | |
2286 | in the rule. In this example,@refill | |
2287 | ||
2288 | @example | |
2289 | @group | |
2290 | exp: @dots{} | |
2291 | | exp '+' exp | |
2292 | @{ $$ = $1 + $3; @} | |
2293 | @end group | |
2294 | @end example | |
2295 | ||
2296 | @noindent | |
2297 | @code{$1} and @code{$3} refer to instances of @code{exp}, so they all | |
2298 | have the data type declared for the nonterminal symbol @code{exp}. If | |
2299 | @code{$2} were used, it would have the data type declared for the | |
2300 | terminal symbol @code{'+'}, whatever that might be.@refill | |
2301 | ||
2302 | Alternatively, you can specify the data type when you refer to the value, | |
2303 | by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the | |
2304 | reference. For example, if you have defined types as shown here: | |
2305 | ||
2306 | @example | |
2307 | @group | |
2308 | %union @{ | |
2309 | int itype; | |
2310 | double dtype; | |
2311 | @} | |
2312 | @end group | |
2313 | @end example | |
2314 | ||
2315 | @noindent | |
2316 | then you can write @code{$<itype>1} to refer to the first subunit of the | |
2317 | rule as an integer, or @code{$<dtype>1} to refer to it as a double. | |
2318 | ||
2319 | @node Mid-Rule Actions, , Action Types, Semantics | |
2320 | @subsection Actions in Mid-Rule | |
2321 | @cindex actions in mid-rule | |
2322 | @cindex mid-rule actions | |
2323 | ||
2324 | Occasionally it is useful to put an action in the middle of a rule. | |
2325 | These actions are written just like usual end-of-rule actions, but they | |
2326 | are executed before the parser even recognizes the following components. | |
2327 | ||
2328 | A mid-rule action may refer to the components preceding it using | |
2329 | @code{$@var{n}}, but it may not refer to subsequent components because | |
2330 | it is run before they are parsed. | |
2331 | ||
2332 | The mid-rule action itself counts as one of the components of the rule. | |
2333 | This makes a difference when there is another action later in the same rule | |
2334 | (and usually there is another at the end): you have to count the actions | |
2335 | along with the symbols when working out which number @var{n} to use in | |
2336 | @code{$@var{n}}. | |
2337 | ||
2338 | The mid-rule action can also have a semantic value. The action can set | |
2339 | its value with an assignment to @code{$$}, and actions later in the rule | |
2340 | can refer to the value using @code{$@var{n}}. Since there is no symbol | |
2341 | to name the action, there is no way to declare a data type for the value | |
fdc6758b MA |
2342 | in advance, so you must use the @samp{$<@dots{}>@var{n}} construct to |
2343 | specify a data type each time you refer to this value. | |
bfa74976 RS |
2344 | |
2345 | There is no way to set the value of the entire rule with a mid-rule | |
2346 | action, because assignments to @code{$$} do not have that effect. The | |
2347 | only way to set the value for the entire rule is with an ordinary action | |
2348 | at the end of the rule. | |
2349 | ||
2350 | Here is an example from a hypothetical compiler, handling a @code{let} | |
2351 | statement that looks like @samp{let (@var{variable}) @var{statement}} and | |
2352 | serves to create a variable named @var{variable} temporarily for the | |
2353 | duration of @var{statement}. To parse this construct, we must put | |
2354 | @var{variable} into the symbol table while @var{statement} is parsed, then | |
2355 | remove it afterward. Here is how it is done: | |
2356 | ||
2357 | @example | |
2358 | @group | |
2359 | stmt: LET '(' var ')' | |
2360 | @{ $<context>$ = push_context (); | |
2361 | declare_variable ($3); @} | |
2362 | stmt @{ $$ = $6; | |
2363 | pop_context ($<context>5); @} | |
2364 | @end group | |
2365 | @end example | |
2366 | ||
2367 | @noindent | |
2368 | As soon as @samp{let (@var{variable})} has been recognized, the first | |
2369 | action is run. It saves a copy of the current semantic context (the | |
2370 | list of accessible variables) as its semantic value, using alternative | |
2371 | @code{context} in the data-type union. Then it calls | |
2372 | @code{declare_variable} to add the new variable to that list. Once the | |
2373 | first action is finished, the embedded statement @code{stmt} can be | |
2374 | parsed. Note that the mid-rule action is component number 5, so the | |
2375 | @samp{stmt} is component number 6. | |
2376 | ||
2377 | After the embedded statement is parsed, its semantic value becomes the | |
2378 | value of the entire @code{let}-statement. Then the semantic value from the | |
2379 | earlier action is used to restore the prior list of variables. This | |
2380 | removes the temporary @code{let}-variable from the list so that it won't | |
2381 | appear to exist while the rest of the program is parsed. | |
2382 | ||
2383 | Taking action before a rule is completely recognized often leads to | |
2384 | conflicts since the parser must commit to a parse in order to execute the | |
2385 | action. For example, the following two rules, without mid-rule actions, | |
2386 | can coexist in a working parser because the parser can shift the open-brace | |
2387 | token and look at what follows before deciding whether there is a | |
2388 | declaration or not: | |
2389 | ||
2390 | @example | |
2391 | @group | |
2392 | compound: '@{' declarations statements '@}' | |
2393 | | '@{' statements '@}' | |
2394 | ; | |
2395 | @end group | |
2396 | @end example | |
2397 | ||
2398 | @noindent | |
2399 | But when we add a mid-rule action as follows, the rules become nonfunctional: | |
2400 | ||
2401 | @example | |
2402 | @group | |
2403 | compound: @{ prepare_for_local_variables (); @} | |
2404 | '@{' declarations statements '@}' | |
2405 | @end group | |
2406 | @group | |
2407 | | '@{' statements '@}' | |
2408 | ; | |
2409 | @end group | |
2410 | @end example | |
2411 | ||
2412 | @noindent | |
2413 | Now the parser is forced to decide whether to run the mid-rule action | |
2414 | when it has read no farther than the open-brace. In other words, it | |
2415 | must commit to using one rule or the other, without sufficient | |
2416 | information to do it correctly. (The open-brace token is what is called | |
2417 | the @dfn{look-ahead} token at this time, since the parser is still | |
2418 | deciding what to do about it. @xref{Look-Ahead, ,Look-Ahead Tokens}.) | |
2419 | ||
2420 | You might think that you could correct the problem by putting identical | |
2421 | actions into the two rules, like this: | |
2422 | ||
2423 | @example | |
2424 | @group | |
2425 | compound: @{ prepare_for_local_variables (); @} | |
2426 | '@{' declarations statements '@}' | |
2427 | | @{ prepare_for_local_variables (); @} | |
2428 | '@{' statements '@}' | |
2429 | ; | |
2430 | @end group | |
2431 | @end example | |
2432 | ||
2433 | @noindent | |
2434 | But this does not help, because Bison does not realize that the two actions | |
2435 | are identical. (Bison never tries to understand the C code in an action.) | |
2436 | ||
2437 | If the grammar is such that a declaration can be distinguished from a | |
2438 | statement by the first token (which is true in C), then one solution which | |
2439 | does work is to put the action after the open-brace, like this: | |
2440 | ||
2441 | @example | |
2442 | @group | |
2443 | compound: '@{' @{ prepare_for_local_variables (); @} | |
2444 | declarations statements '@}' | |
2445 | | '@{' statements '@}' | |
2446 | ; | |
2447 | @end group | |
2448 | @end example | |
2449 | ||
2450 | @noindent | |
2451 | Now the first token of the following declaration or statement, | |
2452 | which would in any case tell Bison which rule to use, can still do so. | |
2453 | ||
2454 | Another solution is to bury the action inside a nonterminal symbol which | |
2455 | serves as a subroutine: | |
2456 | ||
2457 | @example | |
2458 | @group | |
2459 | subroutine: /* empty */ | |
2460 | @{ prepare_for_local_variables (); @} | |
2461 | ; | |
2462 | ||
2463 | @end group | |
2464 | ||
2465 | @group | |
2466 | compound: subroutine | |
2467 | '@{' declarations statements '@}' | |
2468 | | subroutine | |
2469 | '@{' statements '@}' | |
2470 | ; | |
2471 | @end group | |
2472 | @end example | |
2473 | ||
2474 | @noindent | |
2475 | Now Bison can execute the action in the rule for @code{subroutine} without | |
2476 | deciding which rule for @code{compound} it will eventually use. Note that | |
2477 | the action is now at the end of its rule. Any mid-rule action can be | |
2478 | converted to an end-of-rule action in this way, and this is what Bison | |
2479 | actually does to implement mid-rule actions. | |
2480 | ||
847bf1f5 AD |
2481 | @node Locations, Declarations, Semantics, Grammar File |
2482 | @section Tracking Locations | |
2483 | @cindex location | |
2484 | @cindex textual position | |
2485 | @cindex position, textual | |
2486 | ||
2487 | Though grammar rules and semantic actions are enough to write a fully | |
2488 | functional parser, it can be useful to process some additionnal informations, | |
3e259915 MA |
2489 | especially symbol locations. |
2490 | ||
2491 | @c (terminal or not) ? | |
847bf1f5 AD |
2492 | |
2493 | The way locations are handled is defined by providing a data type, and actions | |
2494 | to take when rules are matched. | |
2495 | ||
2496 | @menu | |
2497 | * Location Type:: Specifying a data type for locations. | |
2498 | * Actions and Locations:: Using locations in actions. | |
2499 | * Location Default Action:: Defining a general way to compute locations. | |
2500 | @end menu | |
2501 | ||
2502 | @node Location Type, Actions and Locations, , Locations | |
2503 | @subsection Data Type of Locations | |
2504 | @cindex data type of locations | |
2505 | @cindex default location type | |
2506 | ||
2507 | Defining a data type for locations is much simpler than for semantic values, | |
2508 | since all tokens and groupings always use the same type. | |
2509 | ||
2510 | The type of locations is specified by defining a macro called @code{YYLTYPE}. | |
2511 | When @code{YYLTYPE} is not defined, Bison uses a default structure type with | |
2512 | four members: | |
2513 | ||
2514 | @example | |
2515 | struct | |
2516 | @{ | |
2517 | int first_line; | |
2518 | int first_column; | |
2519 | int last_line; | |
2520 | int last_column; | |
2521 | @} | |
2522 | @end example | |
2523 | ||
2524 | @node Actions and Locations, Location Default Action, Location Type, Locations | |
2525 | @subsection Actions and Locations | |
2526 | @cindex location actions | |
2527 | @cindex actions, location | |
2528 | @vindex @@$ | |
2529 | @vindex @@@var{n} | |
2530 | ||
2531 | Actions are not only useful for defining language semantics, but also for | |
2532 | describing the behavior of the output parser with locations. | |
2533 | ||
2534 | The most obvious way for building locations of syntactic groupings is very | |
2535 | similar to the way semantic values are computed. In a given rule, several | |
2536 | constructs can be used to access the locations of the elements being matched. | |
2537 | The location of the @var{n}th component of the right hand side is | |
2538 | @code{@@@var{n}}, while the location of the left hand side grouping is | |
2539 | @code{@@$}. | |
2540 | ||
3e259915 | 2541 | Here is a basic example using the default data type for locations: |
847bf1f5 AD |
2542 | |
2543 | @example | |
2544 | @group | |
2545 | exp: @dots{} | |
3e259915 | 2546 | | exp '/' exp |
847bf1f5 | 2547 | @{ |
3e259915 MA |
2548 | @@$.first_column = @@1.first_column; |
2549 | @@$.first_line = @@1.first_line; | |
847bf1f5 AD |
2550 | @@$.last_column = @@3.last_column; |
2551 | @@$.last_line = @@3.last_line; | |
3e259915 MA |
2552 | if ($3) |
2553 | $$ = $1 / $3; | |
2554 | else | |
2555 | @{ | |
2556 | $$ = 1; | |
2557 | printf("Division by zero, l%d,c%d-l%d,c%d", | |
2558 | @@3.first_line, @@3.first_column, | |
2559 | @@3.last_line, @@3.last_column); | |
2560 | @} | |
847bf1f5 AD |
2561 | @} |
2562 | @end group | |
2563 | @end example | |
2564 | ||
3e259915 MA |
2565 | As for semantic values, there is a default action for locations that is |
2566 | run each time a rule is matched. It sets the beginning of @code{@@$} to the | |
2567 | beginning of the first symbol, and the end of @code{@@$} to the end of the | |
2568 | last symbol. | |
2569 | ||
2570 | With this default action, the location tracking can be fully automatic. The | |
2571 | example above simply rewrites this way: | |
2572 | ||
2573 | @example | |
2574 | @group | |
2575 | exp: @dots{} | |
2576 | | exp '/' exp | |
2577 | @{ | |
2578 | if ($3) | |
2579 | $$ = $1 / $3; | |
2580 | else | |
2581 | @{ | |
2582 | $$ = 1; | |
2583 | printf("Division by zero, l%d,c%d-l%d,c%d", | |
2584 | @@3.first_line, @@3.first_column, | |
2585 | @@3.last_line, @@3.last_column); | |
2586 | @} | |
2587 | @} | |
2588 | @end group | |
2589 | @end example | |
847bf1f5 AD |
2590 | |
2591 | @node Location Default Action, , Actions and Locations, Locations | |
2592 | @subsection Default Action for Locations | |
2593 | @vindex YYLLOC_DEFAULT | |
2594 | ||
2595 | Actually, actions are not the best place to compute locations. Since locations | |
2596 | are much more general than semantic values, there is room in the output parser | |
3e259915 MA |
2597 | to redefine the default action to take for each rule. The |
2598 | @code{YYLLOC_DEFAULT} macro is called each time a rule is matched, before the | |
2599 | associated action is run. | |
847bf1f5 | 2600 | |
3e259915 MA |
2601 | Most of the time, this macro is general enough to suppress location |
2602 | dedicated code from semantic actions. | |
847bf1f5 | 2603 | |
3e259915 MA |
2604 | The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is |
2605 | the location of the grouping (the result of the computation). The second one | |
2606 | is an array holding locations of all right hand side elements of the rule | |
2607 | being matched. The last one is the size of the right hand side rule. | |
847bf1f5 | 2608 | |
3e259915 | 2609 | By default, it is defined this way: |
847bf1f5 AD |
2610 | |
2611 | @example | |
2612 | @group | |
3e259915 MA |
2613 | #define YYLLOC_DEFAULT(Current, Rhs, N) \ |
2614 | Current.last_line = Rhs[N].last_line; \ | |
2615 | Current.last_column = Rhs[N].last_column; | |
847bf1f5 AD |
2616 | @end group |
2617 | @end example | |
2618 | ||
3e259915 | 2619 | When defining @code{YYLLOC_DEFAULT}, you should consider that: |
847bf1f5 | 2620 | |
3e259915 MA |
2621 | @itemize @bullet |
2622 | @item | |
2623 | All arguments are free of side-effects. However, only the first one (the | |
2624 | result) should be modified by @code{YYLLOC_DEFAULT}. | |
847bf1f5 | 2625 | |
3e259915 MA |
2626 | @item |
2627 | Before @code{YYLLOC_DEFAULT} is executed, the output parser sets @code{@@$} | |
2628 | to @code{@@1}. | |
2629 | ||
2630 | @item | |
2631 | For consistency with semantic actions, valid indexes for the location array | |
2632 | range from 1 to @var{n}. | |
2633 | @end itemize | |
847bf1f5 AD |
2634 | |
2635 | @node Declarations, Multiple Parsers, Locations, Grammar File | |
bfa74976 RS |
2636 | @section Bison Declarations |
2637 | @cindex declarations, Bison | |
2638 | @cindex Bison declarations | |
2639 | ||
2640 | The @dfn{Bison declarations} section of a Bison grammar defines the symbols | |
2641 | used in formulating the grammar and the data types of semantic values. | |
2642 | @xref{Symbols}. | |
2643 | ||
2644 | All token type names (but not single-character literal tokens such as | |
2645 | @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be | |
2646 | declared if you need to specify which data type to use for the semantic | |
2647 | value (@pxref{Multiple Types, ,More Than One Value Type}). | |
2648 | ||
2649 | The first rule in the file also specifies the start symbol, by default. | |
2650 | If you want some other symbol to be the start symbol, you must declare | |
2651 | it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}). | |
2652 | ||
2653 | @menu | |
2654 | * Token Decl:: Declaring terminal symbols. | |
2655 | * Precedence Decl:: Declaring terminals with precedence and associativity. | |
2656 | * Union Decl:: Declaring the set of all semantic value types. | |
2657 | * Type Decl:: Declaring the choice of type for a nonterminal symbol. | |
2658 | * Expect Decl:: Suppressing warnings about shift/reduce conflicts. | |
2659 | * Start Decl:: Specifying the start symbol. | |
2660 | * Pure Decl:: Requesting a reentrant parser. | |
2661 | * Decl Summary:: Table of all Bison declarations. | |
2662 | @end menu | |
2663 | ||
2664 | @node Token Decl, Precedence Decl, , Declarations | |
2665 | @subsection Token Type Names | |
2666 | @cindex declaring token type names | |
2667 | @cindex token type names, declaring | |
931c7513 | 2668 | @cindex declaring literal string tokens |
bfa74976 RS |
2669 | @findex %token |
2670 | ||
2671 | The basic way to declare a token type name (terminal symbol) is as follows: | |
2672 | ||
2673 | @example | |
2674 | %token @var{name} | |
2675 | @end example | |
2676 | ||
2677 | Bison will convert this into a @code{#define} directive in | |
2678 | the parser, so that the function @code{yylex} (if it is in this file) | |
2679 | can use the name @var{name} to stand for this token type's code. | |
2680 | ||
14ded682 AD |
2681 | Alternatively, you can use @code{%left}, @code{%right}, or |
2682 | @code{%nonassoc} instead of @code{%token}, if you wish to specify | |
2683 | associativity and precedence. @xref{Precedence Decl, ,Operator | |
2684 | Precedence}. | |
bfa74976 RS |
2685 | |
2686 | You can explicitly specify the numeric code for a token type by appending | |
2687 | an integer value in the field immediately following the token name: | |
2688 | ||
2689 | @example | |
2690 | %token NUM 300 | |
2691 | @end example | |
2692 | ||
2693 | @noindent | |
2694 | It is generally best, however, to let Bison choose the numeric codes for | |
2695 | all token types. Bison will automatically select codes that don't conflict | |
2696 | with each other or with ASCII characters. | |
2697 | ||
2698 | In the event that the stack type is a union, you must augment the | |
2699 | @code{%token} or other token declaration to include the data type | |
13863333 | 2700 | alternative delimited by angle-brackets (@pxref{Multiple Types, ,More Than One Value Type}). |
bfa74976 RS |
2701 | |
2702 | For example: | |
2703 | ||
2704 | @example | |
2705 | @group | |
2706 | %union @{ /* define stack type */ | |
2707 | double val; | |
2708 | symrec *tptr; | |
2709 | @} | |
2710 | %token <val> NUM /* define token NUM and its type */ | |
2711 | @end group | |
2712 | @end example | |
2713 | ||
931c7513 RS |
2714 | You can associate a literal string token with a token type name by |
2715 | writing the literal string at the end of a @code{%token} | |
2716 | declaration which declares the name. For example: | |
2717 | ||
2718 | @example | |
2719 | %token arrow "=>" | |
2720 | @end example | |
2721 | ||
2722 | @noindent | |
2723 | For example, a grammar for the C language might specify these names with | |
2724 | equivalent literal string tokens: | |
2725 | ||
2726 | @example | |
2727 | %token <operator> OR "||" | |
2728 | %token <operator> LE 134 "<=" | |
2729 | %left OR "<=" | |
2730 | @end example | |
2731 | ||
2732 | @noindent | |
2733 | Once you equate the literal string and the token name, you can use them | |
2734 | interchangeably in further declarations or the grammar rules. The | |
2735 | @code{yylex} function can use the token name or the literal string to | |
2736 | obtain the token type code number (@pxref{Calling Convention}). | |
2737 | ||
bfa74976 RS |
2738 | @node Precedence Decl, Union Decl, Token Decl, Declarations |
2739 | @subsection Operator Precedence | |
2740 | @cindex precedence declarations | |
2741 | @cindex declaring operator precedence | |
2742 | @cindex operator precedence, declaring | |
2743 | ||
2744 | Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to | |
2745 | declare a token and specify its precedence and associativity, all at | |
2746 | once. These are called @dfn{precedence declarations}. | |
2747 | @xref{Precedence, ,Operator Precedence}, for general information on operator precedence. | |
2748 | ||
2749 | The syntax of a precedence declaration is the same as that of | |
2750 | @code{%token}: either | |
2751 | ||
2752 | @example | |
2753 | %left @var{symbols}@dots{} | |
2754 | @end example | |
2755 | ||
2756 | @noindent | |
2757 | or | |
2758 | ||
2759 | @example | |
2760 | %left <@var{type}> @var{symbols}@dots{} | |
2761 | @end example | |
2762 | ||
2763 | And indeed any of these declarations serves the purposes of @code{%token}. | |
2764 | But in addition, they specify the associativity and relative precedence for | |
2765 | all the @var{symbols}: | |
2766 | ||
2767 | @itemize @bullet | |
2768 | @item | |
2769 | The associativity of an operator @var{op} determines how repeated uses | |
2770 | of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op} | |
2771 | @var{z}} is parsed by grouping @var{x} with @var{y} first or by | |
2772 | grouping @var{y} with @var{z} first. @code{%left} specifies | |
2773 | left-associativity (grouping @var{x} with @var{y} first) and | |
2774 | @code{%right} specifies right-associativity (grouping @var{y} with | |
2775 | @var{z} first). @code{%nonassoc} specifies no associativity, which | |
2776 | means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is | |
2777 | considered a syntax error. | |
2778 | ||
2779 | @item | |
2780 | The precedence of an operator determines how it nests with other operators. | |
2781 | All the tokens declared in a single precedence declaration have equal | |
2782 | precedence and nest together according to their associativity. | |
2783 | When two tokens declared in different precedence declarations associate, | |
2784 | the one declared later has the higher precedence and is grouped first. | |
2785 | @end itemize | |
2786 | ||
2787 | @node Union Decl, Type Decl, Precedence Decl, Declarations | |
2788 | @subsection The Collection of Value Types | |
2789 | @cindex declaring value types | |
2790 | @cindex value types, declaring | |
2791 | @findex %union | |
2792 | ||
2793 | The @code{%union} declaration specifies the entire collection of possible | |
2794 | data types for semantic values. The keyword @code{%union} is followed by a | |
2795 | pair of braces containing the same thing that goes inside a @code{union} in | |
13863333 | 2796 | C. |
bfa74976 RS |
2797 | |
2798 | For example: | |
2799 | ||
2800 | @example | |
2801 | @group | |
2802 | %union @{ | |
2803 | double val; | |
2804 | symrec *tptr; | |
2805 | @} | |
2806 | @end group | |
2807 | @end example | |
2808 | ||
2809 | @noindent | |
2810 | This says that the two alternative types are @code{double} and @code{symrec | |
2811 | *}. They are given names @code{val} and @code{tptr}; these names are used | |
2812 | in the @code{%token} and @code{%type} declarations to pick one of the types | |
2813 | for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}). | |
2814 | ||
2815 | Note that, unlike making a @code{union} declaration in C, you do not write | |
2816 | a semicolon after the closing brace. | |
2817 | ||
2818 | @node Type Decl, Expect Decl, Union Decl, Declarations | |
2819 | @subsection Nonterminal Symbols | |
2820 | @cindex declaring value types, nonterminals | |
2821 | @cindex value types, nonterminals, declaring | |
2822 | @findex %type | |
2823 | ||
2824 | @noindent | |
2825 | When you use @code{%union} to specify multiple value types, you must | |
2826 | declare the value type of each nonterminal symbol for which values are | |
2827 | used. This is done with a @code{%type} declaration, like this: | |
2828 | ||
2829 | @example | |
2830 | %type <@var{type}> @var{nonterminal}@dots{} | |
2831 | @end example | |
2832 | ||
2833 | @noindent | |
2834 | Here @var{nonterminal} is the name of a nonterminal symbol, and @var{type} | |
2835 | is the name given in the @code{%union} to the alternative that you want | |
2836 | (@pxref{Union Decl, ,The Collection of Value Types}). You can give any number of nonterminal symbols in | |
2837 | the same @code{%type} declaration, if they have the same value type. Use | |
2838 | spaces to separate the symbol names. | |
2839 | ||
931c7513 RS |
2840 | You can also declare the value type of a terminal symbol. To do this, |
2841 | use the same @code{<@var{type}>} construction in a declaration for the | |
2842 | terminal symbol. All kinds of token declarations allow | |
2843 | @code{<@var{type}>}. | |
2844 | ||
bfa74976 RS |
2845 | @node Expect Decl, Start Decl, Type Decl, Declarations |
2846 | @subsection Suppressing Conflict Warnings | |
2847 | @cindex suppressing conflict warnings | |
2848 | @cindex preventing warnings about conflicts | |
2849 | @cindex warnings, preventing | |
2850 | @cindex conflicts, suppressing warnings of | |
2851 | @findex %expect | |
2852 | ||
2853 | Bison normally warns if there are any conflicts in the grammar | |
2854 | (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars have harmless shift/reduce | |
2855 | conflicts which are resolved in a predictable way and would be difficult to | |
2856 | eliminate. It is desirable to suppress the warning about these conflicts | |
2857 | unless the number of conflicts changes. You can do this with the | |
2858 | @code{%expect} declaration. | |
2859 | ||
2860 | The declaration looks like this: | |
2861 | ||
2862 | @example | |
2863 | %expect @var{n} | |
2864 | @end example | |
2865 | ||
2866 | Here @var{n} is a decimal integer. The declaration says there should be no | |
2867 | warning if there are @var{n} shift/reduce conflicts and no reduce/reduce | |
2868 | conflicts. The usual warning is given if there are either more or fewer | |
2869 | conflicts, or if there are any reduce/reduce conflicts. | |
2870 | ||
2871 | In general, using @code{%expect} involves these steps: | |
2872 | ||
2873 | @itemize @bullet | |
2874 | @item | |
2875 | Compile your grammar without @code{%expect}. Use the @samp{-v} option | |
2876 | to get a verbose list of where the conflicts occur. Bison will also | |
2877 | print the number of conflicts. | |
2878 | ||
2879 | @item | |
2880 | Check each of the conflicts to make sure that Bison's default | |
2881 | resolution is what you really want. If not, rewrite the grammar and | |
2882 | go back to the beginning. | |
2883 | ||
2884 | @item | |
2885 | Add an @code{%expect} declaration, copying the number @var{n} from the | |
2886 | number which Bison printed. | |
2887 | @end itemize | |
2888 | ||
2889 | Now Bison will stop annoying you about the conflicts you have checked, but | |
2890 | it will warn you again if changes in the grammar result in additional | |
2891 | conflicts. | |
2892 | ||
2893 | @node Start Decl, Pure Decl, Expect Decl, Declarations | |
2894 | @subsection The Start-Symbol | |
2895 | @cindex declaring the start symbol | |
2896 | @cindex start symbol, declaring | |
2897 | @cindex default start symbol | |
2898 | @findex %start | |
2899 | ||
2900 | Bison assumes by default that the start symbol for the grammar is the first | |
2901 | nonterminal specified in the grammar specification section. The programmer | |
2902 | may override this restriction with the @code{%start} declaration as follows: | |
2903 | ||
2904 | @example | |
2905 | %start @var{symbol} | |
2906 | @end example | |
2907 | ||
2908 | @node Pure Decl, Decl Summary, Start Decl, Declarations | |
2909 | @subsection A Pure (Reentrant) Parser | |
2910 | @cindex reentrant parser | |
2911 | @cindex pure parser | |
2912 | @findex %pure_parser | |
2913 | ||
2914 | A @dfn{reentrant} program is one which does not alter in the course of | |
2915 | execution; in other words, it consists entirely of @dfn{pure} (read-only) | |
2916 | code. Reentrancy is important whenever asynchronous execution is possible; | |
14ded682 AD |
2917 | for example, a non-reentrant program may not be safe to call from a signal |
2918 | handler. In systems with multiple threads of control, a non-reentrant | |
bfa74976 RS |
2919 | program must be called only within interlocks. |
2920 | ||
70811b85 RS |
2921 | Normally, Bison generates a parser which is not reentrant. This is |
2922 | suitable for most uses, and it permits compatibility with YACC. (The | |
2923 | standard YACC interfaces are inherently nonreentrant, because they use | |
2924 | statically allocated variables for communication with @code{yylex}, | |
2925 | including @code{yylval} and @code{yylloc}.) | |
bfa74976 | 2926 | |
70811b85 RS |
2927 | Alternatively, you can generate a pure, reentrant parser. The Bison |
2928 | declaration @code{%pure_parser} says that you want the parser to be | |
2929 | reentrant. It looks like this: | |
bfa74976 RS |
2930 | |
2931 | @example | |
2932 | %pure_parser | |
2933 | @end example | |
2934 | ||
70811b85 RS |
2935 | The result is that the communication variables @code{yylval} and |
2936 | @code{yylloc} become local variables in @code{yyparse}, and a different | |
2937 | calling convention is used for the lexical analyzer function | |
2938 | @code{yylex}. @xref{Pure Calling, ,Calling Conventions for Pure | |
2939 | Parsers}, for the details of this. The variable @code{yynerrs} also | |
2940 | becomes local in @code{yyparse} (@pxref{Error Reporting, ,The Error | |
2941 | Reporting Function @code{yyerror}}). The convention for calling | |
2942 | @code{yyparse} itself is unchanged. | |
2943 | ||
2944 | Whether the parser is pure has nothing to do with the grammar rules. | |
2945 | You can generate either a pure parser or a nonreentrant parser from any | |
2946 | valid grammar. | |
bfa74976 RS |
2947 | |
2948 | @node Decl Summary, , Pure Decl, Declarations | |
2949 | @subsection Bison Declaration Summary | |
2950 | @cindex Bison declaration summary | |
2951 | @cindex declaration summary | |
2952 | @cindex summary, Bison declaration | |
2953 | ||
2954 | Here is a summary of all Bison declarations: | |
2955 | ||
2956 | @table @code | |
2957 | @item %union | |
2958 | Declare the collection of data types that semantic values may have | |
2959 | (@pxref{Union Decl, ,The Collection of Value Types}). | |
2960 | ||
2961 | @item %token | |
2962 | Declare a terminal symbol (token type name) with no precedence | |
2963 | or associativity specified (@pxref{Token Decl, ,Token Type Names}). | |
2964 | ||
2965 | @item %right | |
2966 | Declare a terminal symbol (token type name) that is right-associative | |
2967 | (@pxref{Precedence Decl, ,Operator Precedence}). | |
2968 | ||
2969 | @item %left | |
2970 | Declare a terminal symbol (token type name) that is left-associative | |
2971 | (@pxref{Precedence Decl, ,Operator Precedence}). | |
2972 | ||
2973 | @item %nonassoc | |
2974 | Declare a terminal symbol (token type name) that is nonassociative | |
2975 | (using it in a way that would be associative is a syntax error) | |
2976 | (@pxref{Precedence Decl, ,Operator Precedence}). | |
2977 | ||
2978 | @item %type | |
2979 | Declare the type of semantic values for a nonterminal symbol | |
2980 | (@pxref{Type Decl, ,Nonterminal Symbols}). | |
2981 | ||
2982 | @item %start | |
89cab50d AD |
2983 | Specify the grammar's start symbol (@pxref{Start Decl, ,The |
2984 | Start-Symbol}). | |
bfa74976 RS |
2985 | |
2986 | @item %expect | |
2987 | Declare the expected number of shift-reduce conflicts | |
2988 | (@pxref{Expect Decl, ,Suppressing Conflict Warnings}). | |
2989 | ||
6deb4447 AD |
2990 | @item %yacc |
2991 | @itemx %fixed_output_files | |
2992 | Pretend the option @option{--yacc} was given, i.e., imitate Yacc, | |
2993 | including its naming conventions. @xref{Bison Options}, for more. | |
2994 | ||
89cab50d AD |
2995 | @item %locations |
2996 | Generate the code processing the locations (@pxref{Action Features, | |
2997 | ,Special Features for Use in Actions}). This mode is enabled as soon as | |
2998 | the grammar uses the special @samp{@@@var{n}} tokens, but if your | |
2999 | grammar does not use it, using @samp{%locations} allows for more | |
3000 | accurate parse error messages. | |
3001 | ||
bfa74976 | 3002 | @item %pure_parser |
89cab50d AD |
3003 | Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure |
3004 | (Reentrant) Parser}). | |
931c7513 | 3005 | |
6deb4447 AD |
3006 | @item %no_parser |
3007 | Do not include any C code in the parser file; generate tables only. The | |
3008 | parser file contains just @code{#define} directives and static variable | |
3009 | declarations. | |
3010 | ||
3011 | This option also tells Bison to write the C code for the grammar actions | |
3012 | into a file named @file{@var{filename}.act}, in the form of a | |
3013 | brace-surrounded body fit for a @code{switch} statement. | |
3014 | ||
931c7513 RS |
3015 | @item %no_lines |
3016 | Don't generate any @code{#line} preprocessor commands in the parser | |
3017 | file. Ordinarily Bison writes these commands in the parser file so that | |
3018 | the C compiler and debuggers will associate errors and object code with | |
3019 | your source file (the grammar file). This directive causes them to | |
3020 | associate errors with the parser file, treating it an independent source | |
3021 | file in its own right. | |
3022 | ||
6deb4447 AD |
3023 | @item %debug |
3024 | Output a definition of the macro @code{YYDEBUG} into the parser file, so | |
3025 | that the debugging facilities are compiled. @xref{Debugging, ,Debugging | |
3026 | Your Parser}. | |
3027 | ||
3028 | @item %defines | |
3029 | Write an extra output file containing macro definitions for the token | |
3030 | type names defined in the grammar and the semantic value type | |
3031 | @code{YYSTYPE}, as well as a few @code{extern} variable declarations. | |
3032 | ||
3033 | If the parser output file is named @file{@var{name}.c} then this file | |
3034 | is named @file{@var{name}.h}.@refill | |
3035 | ||
3036 | This output file is essential if you wish to put the definition of | |
3037 | @code{yylex} in a separate source file, because @code{yylex} needs to | |
3038 | be able to refer to token type codes and the variable | |
3039 | @code{yylval}. @xref{Token Values, ,Semantic Values of Tokens}.@refill | |
3040 | ||
3041 | @item %verbose | |
3042 | Write an extra output file containing verbose descriptions of the | |
3043 | parser states and what is done for each type of look-ahead token in | |
3044 | that state. | |
3045 | ||
3046 | This file also describes all the conflicts, both those resolved by | |
3047 | operator precedence and the unresolved ones. | |
3048 | ||
3049 | The file's name is made by removing @samp{.tab.c} or @samp{.c} from | |
3050 | the parser output file name, and adding @samp{.output} instead.@refill | |
3051 | ||
3052 | Therefore, if the input file is @file{foo.y}, then the parser file is | |
3053 | called @file{foo.tab.c} by default. As a consequence, the verbose | |
3054 | output file is called @file{foo.output}.@refill | |
3055 | ||
931c7513 RS |
3056 | @item %token_table |
3057 | Generate an array of token names in the parser file. The name of the | |
3058 | array is @code{yytname}; @code{yytname[@var{i}]} is the name of the | |
3059 | token whose internal Bison token code number is @var{i}. The first three | |
3060 | elements of @code{yytname} are always @code{"$"}, @code{"error"}, and | |
3061 | @code{"$illegal"}; after these come the symbols defined in the grammar | |
3062 | file. | |
3063 | ||
3064 | For single-character literal tokens and literal string tokens, the name | |
3065 | in the table includes the single-quote or double-quote characters: for | |
3066 | example, @code{"'+'"} is a single-character literal and @code{"\"<=\""} | |
3067 | is a literal string token. All the characters of the literal string | |
3068 | token appear verbatim in the string found in the table; even | |
3069 | double-quote characters are not escaped. For example, if the token | |
3070 | consists of three characters @samp{*"*}, its string in @code{yytname} | |
3071 | contains @samp{"*"*"}. (In C, that would be written as | |
3072 | @code{"\"*\"*\""}). | |
3073 | ||
3074 | When you specify @code{%token_table}, Bison also generates macro | |
3075 | definitions for macros @code{YYNTOKENS}, @code{YYNNTS}, and | |
3076 | @code{YYNRULES}, and @code{YYNSTATES}: | |
3077 | ||
3078 | @table @code | |
3079 | @item YYNTOKENS | |
3080 | The highest token number, plus one. | |
3081 | @item YYNNTS | |
9ecbd125 | 3082 | The number of nonterminal symbols. |
931c7513 RS |
3083 | @item YYNRULES |
3084 | The number of grammar rules, | |
3085 | @item YYNSTATES | |
3086 | The number of parser states (@pxref{Parser States}). | |
3087 | @end table | |
bfa74976 RS |
3088 | @end table |
3089 | ||
931c7513 | 3090 | @node Multiple Parsers,, Declarations, Grammar File |
bfa74976 RS |
3091 | @section Multiple Parsers in the Same Program |
3092 | ||
3093 | Most programs that use Bison parse only one language and therefore contain | |
3094 | only one Bison parser. But what if you want to parse more than one | |
3095 | language with the same program? Then you need to avoid a name conflict | |
3096 | between different definitions of @code{yyparse}, @code{yylval}, and so on. | |
3097 | ||
3098 | The easy way to do this is to use the option @samp{-p @var{prefix}} | |
3099 | (@pxref{Invocation, ,Invoking Bison}). This renames the interface functions and | |
3100 | variables of the Bison parser to start with @var{prefix} instead of | |
3101 | @samp{yy}. You can use this to give each parser distinct names that do | |
3102 | not conflict. | |
3103 | ||
3104 | The precise list of symbols renamed is @code{yyparse}, @code{yylex}, | |
c656404a RS |
3105 | @code{yyerror}, @code{yynerrs}, @code{yylval}, @code{yychar} and |
3106 | @code{yydebug}. For example, if you use @samp{-p c}, the names become | |
3107 | @code{cparse}, @code{clex}, and so on. | |
bfa74976 RS |
3108 | |
3109 | @strong{All the other variables and macros associated with Bison are not | |
3110 | renamed.} These others are not global; there is no conflict if the same | |
3111 | name is used in different parsers. For example, @code{YYSTYPE} is not | |
3112 | renamed, but defining this in different ways in different parsers causes | |
3113 | no trouble (@pxref{Value Type, ,Data Types of Semantic Values}). | |
3114 | ||
3115 | The @samp{-p} option works by adding macro definitions to the beginning | |
3116 | of the parser source file, defining @code{yyparse} as | |
3117 | @code{@var{prefix}parse}, and so on. This effectively substitutes one | |
3118 | name for the other in the entire parser file. | |
3119 | ||
3120 | @node Interface, Algorithm, Grammar File, Top | |
3121 | @chapter Parser C-Language Interface | |
3122 | @cindex C-language interface | |
3123 | @cindex interface | |
3124 | ||
3125 | The Bison parser is actually a C function named @code{yyparse}. Here we | |
3126 | describe the interface conventions of @code{yyparse} and the other | |
3127 | functions that it needs to use. | |
3128 | ||
3129 | Keep in mind that the parser uses many C identifiers starting with | |
3130 | @samp{yy} and @samp{YY} for internal purposes. If you use such an | |
3131 | identifier (aside from those in this manual) in an action or in additional | |
3132 | C code in the grammar file, you are likely to run into trouble. | |
3133 | ||
3134 | @menu | |
3135 | * Parser Function:: How to call @code{yyparse} and what it returns. | |
13863333 | 3136 | * Lexical:: You must supply a function @code{yylex} |
bfa74976 RS |
3137 | which reads tokens. |
3138 | * Error Reporting:: You must supply a function @code{yyerror}. | |
3139 | * Action Features:: Special features for use in actions. | |
3140 | @end menu | |
3141 | ||
3142 | @node Parser Function, Lexical, , Interface | |
3143 | @section The Parser Function @code{yyparse} | |
3144 | @findex yyparse | |
3145 | ||
3146 | You call the function @code{yyparse} to cause parsing to occur. This | |
3147 | function reads tokens, executes actions, and ultimately returns when it | |
3148 | encounters end-of-input or an unrecoverable syntax error. You can also | |
14ded682 AD |
3149 | write an action which directs @code{yyparse} to return immediately |
3150 | without reading further. | |
bfa74976 RS |
3151 | |
3152 | The value returned by @code{yyparse} is 0 if parsing was successful (return | |
3153 | is due to end-of-input). | |
3154 | ||
3155 | The value is 1 if parsing failed (return is due to a syntax error). | |
3156 | ||
3157 | In an action, you can cause immediate return from @code{yyparse} by using | |
3158 | these macros: | |
3159 | ||
3160 | @table @code | |
3161 | @item YYACCEPT | |
3162 | @findex YYACCEPT | |
3163 | Return immediately with value 0 (to report success). | |
3164 | ||
3165 | @item YYABORT | |
3166 | @findex YYABORT | |
3167 | Return immediately with value 1 (to report failure). | |
3168 | @end table | |
3169 | ||
3170 | @node Lexical, Error Reporting, Parser Function, Interface | |
3171 | @section The Lexical Analyzer Function @code{yylex} | |
3172 | @findex yylex | |
3173 | @cindex lexical analyzer | |
3174 | ||
3175 | The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from | |
3176 | the input stream and returns them to the parser. Bison does not create | |
3177 | this function automatically; you must write it so that @code{yyparse} can | |
3178 | call it. The function is sometimes referred to as a lexical scanner. | |
3179 | ||
3180 | In simple programs, @code{yylex} is often defined at the end of the Bison | |
3181 | grammar file. If @code{yylex} is defined in a separate source file, you | |
3182 | need to arrange for the token-type macro definitions to be available there. | |
3183 | To do this, use the @samp{-d} option when you run Bison, so that it will | |
3184 | write these macro definitions into a separate header file | |
3185 | @file{@var{name}.tab.h} which you can include in the other source files | |
3186 | that need it. @xref{Invocation, ,Invoking Bison}.@refill | |
3187 | ||
3188 | @menu | |
3189 | * Calling Convention:: How @code{yyparse} calls @code{yylex}. | |
3190 | * Token Values:: How @code{yylex} must return the semantic value | |
3191 | of the token it has read. | |
3192 | * Token Positions:: How @code{yylex} must return the text position | |
3193 | (line number, etc.) of the token, if the | |
3194 | actions want that. | |
3195 | * Pure Calling:: How the calling convention differs | |
3196 | in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}). | |
3197 | @end menu | |
3198 | ||
3199 | @node Calling Convention, Token Values, , Lexical | |
3200 | @subsection Calling Convention for @code{yylex} | |
3201 | ||
3202 | The value that @code{yylex} returns must be the numeric code for the type | |
3203 | of token it has just found, or 0 for end-of-input. | |
3204 | ||
3205 | When a token is referred to in the grammar rules by a name, that name | |
3206 | in the parser file becomes a C macro whose definition is the proper | |
3207 | numeric code for that token type. So @code{yylex} can use the name | |
3208 | to indicate that type. @xref{Symbols}. | |
3209 | ||
3210 | When a token is referred to in the grammar rules by a character literal, | |
3211 | the numeric code for that character is also the code for the token type. | |
3212 | So @code{yylex} can simply return that character code. The null character | |
3213 | must not be used this way, because its code is zero and that is what | |
3214 | signifies end-of-input. | |
3215 | ||
3216 | Here is an example showing these things: | |
3217 | ||
3218 | @example | |
13863333 AD |
3219 | int |
3220 | yylex (void) | |
bfa74976 RS |
3221 | @{ |
3222 | @dots{} | |
3223 | if (c == EOF) /* Detect end of file. */ | |
3224 | return 0; | |
3225 | @dots{} | |
3226 | if (c == '+' || c == '-') | |
3227 | return c; /* Assume token type for `+' is '+'. */ | |
3228 | @dots{} | |
3229 | return INT; /* Return the type of the token. */ | |
3230 | @dots{} | |
3231 | @} | |
3232 | @end example | |
3233 | ||
3234 | @noindent | |
3235 | This interface has been designed so that the output from the @code{lex} | |
3236 | utility can be used without change as the definition of @code{yylex}. | |
3237 | ||
931c7513 RS |
3238 | If the grammar uses literal string tokens, there are two ways that |
3239 | @code{yylex} can determine the token type codes for them: | |
3240 | ||
3241 | @itemize @bullet | |
3242 | @item | |
3243 | If the grammar defines symbolic token names as aliases for the | |
3244 | literal string tokens, @code{yylex} can use these symbolic names like | |
3245 | all others. In this case, the use of the literal string tokens in | |
3246 | the grammar file has no effect on @code{yylex}. | |
3247 | ||
3248 | @item | |
9ecbd125 | 3249 | @code{yylex} can find the multicharacter token in the @code{yytname} |
931c7513 | 3250 | table. The index of the token in the table is the token type's code. |
9ecbd125 | 3251 | The name of a multicharacter token is recorded in @code{yytname} with a |
931c7513 RS |
3252 | double-quote, the token's characters, and another double-quote. The |
3253 | token's characters are not escaped in any way; they appear verbatim in | |
3254 | the contents of the string in the table. | |
3255 | ||
3256 | Here's code for looking up a token in @code{yytname}, assuming that the | |
3257 | characters of the token are stored in @code{token_buffer}. | |
3258 | ||
3259 | @smallexample | |
3260 | for (i = 0; i < YYNTOKENS; i++) | |
3261 | @{ | |
3262 | if (yytname[i] != 0 | |
3263 | && yytname[i][0] == '"' | |
6f515a27 JT |
3264 | && strncmp (yytname[i] + 1, token_buffer, |
3265 | strlen (token_buffer)) | |
931c7513 RS |
3266 | && yytname[i][strlen (token_buffer) + 1] == '"' |
3267 | && yytname[i][strlen (token_buffer) + 2] == 0) | |
3268 | break; | |
3269 | @} | |
3270 | @end smallexample | |
3271 | ||
3272 | The @code{yytname} table is generated only if you use the | |
3273 | @code{%token_table} declaration. @xref{Decl Summary}. | |
3274 | @end itemize | |
3275 | ||
bfa74976 RS |
3276 | @node Token Values, Token Positions, Calling Convention, Lexical |
3277 | @subsection Semantic Values of Tokens | |
3278 | ||
3279 | @vindex yylval | |
14ded682 | 3280 | In an ordinary (non-reentrant) parser, the semantic value of the token must |
bfa74976 RS |
3281 | be stored into the global variable @code{yylval}. When you are using |
3282 | just one data type for semantic values, @code{yylval} has that type. | |
3283 | Thus, if the type is @code{int} (the default), you might write this in | |
3284 | @code{yylex}: | |
3285 | ||
3286 | @example | |
3287 | @group | |
3288 | @dots{} | |
3289 | yylval = value; /* Put value onto Bison stack. */ | |
3290 | return INT; /* Return the type of the token. */ | |
3291 | @dots{} | |
3292 | @end group | |
3293 | @end example | |
3294 | ||
3295 | When you are using multiple data types, @code{yylval}'s type is a union | |
3296 | made from the @code{%union} declaration (@pxref{Union Decl, ,The Collection of Value Types}). So when | |
3297 | you store a token's value, you must use the proper member of the union. | |
3298 | If the @code{%union} declaration looks like this: | |
3299 | ||
3300 | @example | |
3301 | @group | |
3302 | %union @{ | |
3303 | int intval; | |
3304 | double val; | |
3305 | symrec *tptr; | |
3306 | @} | |
3307 | @end group | |
3308 | @end example | |
3309 | ||
3310 | @noindent | |
3311 | then the code in @code{yylex} might look like this: | |
3312 | ||
3313 | @example | |
3314 | @group | |
3315 | @dots{} | |
3316 | yylval.intval = value; /* Put value onto Bison stack. */ | |
3317 | return INT; /* Return the type of the token. */ | |
3318 | @dots{} | |
3319 | @end group | |
3320 | @end example | |
3321 | ||
3322 | @node Token Positions, Pure Calling, Token Values, Lexical | |
3323 | @subsection Textual Positions of Tokens | |
3324 | ||
3325 | @vindex yylloc | |
847bf1f5 AD |
3326 | If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, , |
3327 | Tracking Locations}) in actions to keep track of the | |
89cab50d AD |
3328 | textual locations of tokens and groupings, then you must provide this |
3329 | information in @code{yylex}. The function @code{yyparse} expects to | |
3330 | find the textual location of a token just parsed in the global variable | |
3331 | @code{yylloc}. So @code{yylex} must store the proper data in that | |
847bf1f5 AD |
3332 | variable. |
3333 | ||
3334 | By default, the value of @code{yylloc} is a structure and you need only | |
89cab50d AD |
3335 | initialize the members that are going to be used by the actions. The |
3336 | four members are called @code{first_line}, @code{first_column}, | |
3337 | @code{last_line} and @code{last_column}. Note that the use of this | |
3338 | feature makes the parser noticeably slower. | |
bfa74976 RS |
3339 | |
3340 | @tindex YYLTYPE | |
3341 | The data type of @code{yylloc} has the name @code{YYLTYPE}. | |
3342 | ||
3343 | @node Pure Calling, , Token Positions, Lexical | |
c656404a | 3344 | @subsection Calling Conventions for Pure Parsers |
bfa74976 | 3345 | |
e425e872 RS |
3346 | When you use the Bison declaration @code{%pure_parser} to request a |
3347 | pure, reentrant parser, the global communication variables @code{yylval} | |
3348 | and @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant) | |
3349 | Parser}.) In such parsers the two global variables are replaced by | |
3350 | pointers passed as arguments to @code{yylex}. You must declare them as | |
3351 | shown here, and pass the information back by storing it through those | |
3352 | pointers. | |
bfa74976 RS |
3353 | |
3354 | @example | |
13863333 AD |
3355 | int |
3356 | yylex (YYSTYPE *lvalp, YYLTYPE *llocp) | |
bfa74976 RS |
3357 | @{ |
3358 | @dots{} | |
3359 | *lvalp = value; /* Put value onto Bison stack. */ | |
3360 | return INT; /* Return the type of the token. */ | |
3361 | @dots{} | |
3362 | @} | |
3363 | @end example | |
3364 | ||
3365 | If the grammar file does not use the @samp{@@} constructs to refer to | |
3366 | textual positions, then the type @code{YYLTYPE} will not be defined. In | |
3367 | this case, omit the second argument; @code{yylex} will be called with | |
3368 | only one argument. | |
3369 | ||
c656404a | 3370 | @vindex YYPARSE_PARAM |
931c7513 RS |
3371 | If you use a reentrant parser, you can optionally pass additional |
3372 | parameter information to it in a reentrant way. To do so, define the | |
3373 | macro @code{YYPARSE_PARAM} as a variable name. This modifies the | |
3374 | @code{yyparse} function to accept one argument, of type @code{void *}, | |
3375 | with that name. | |
e425e872 RS |
3376 | |
3377 | When you call @code{yyparse}, pass the address of an object, casting the | |
3378 | address to @code{void *}. The grammar actions can refer to the contents | |
3379 | of the object by casting the pointer value back to its proper type and | |
3380 | then dereferencing it. Here's an example. Write this in the parser: | |
3381 | ||
3382 | @example | |
3383 | %@{ | |
3384 | struct parser_control | |
3385 | @{ | |
3386 | int nastiness; | |
3387 | int randomness; | |
3388 | @}; | |
3389 | ||
3390 | #define YYPARSE_PARAM parm | |
3391 | %@} | |
3392 | @end example | |
3393 | ||
3394 | @noindent | |
3395 | Then call the parser like this: | |
3396 | ||
3397 | @example | |
3398 | struct parser_control | |
3399 | @{ | |
3400 | int nastiness; | |
3401 | int randomness; | |
3402 | @}; | |
3403 | ||
3404 | @dots{} | |
3405 | ||
3406 | @{ | |
3407 | struct parser_control foo; | |
3408 | @dots{} /* @r{Store proper data in @code{foo}.} */ | |
3409 | value = yyparse ((void *) &foo); | |
3410 | @dots{} | |
3411 | @} | |
3412 | @end example | |
3413 | ||
3414 | @noindent | |
3415 | In the grammar actions, use expressions like this to refer to the data: | |
3416 | ||
3417 | @example | |
3418 | ((struct parser_control *) parm)->randomness | |
3419 | @end example | |
3420 | ||
c656404a RS |
3421 | @vindex YYLEX_PARAM |
3422 | If you wish to pass the additional parameter data to @code{yylex}, | |
3423 | define the macro @code{YYLEX_PARAM} just like @code{YYPARSE_PARAM}, as | |
3424 | shown here: | |
3425 | ||
3426 | @example | |
3427 | %@{ | |
3428 | struct parser_control | |
3429 | @{ | |
3430 | int nastiness; | |
3431 | int randomness; | |
3432 | @}; | |
3433 | ||
3434 | #define YYPARSE_PARAM parm | |
3435 | #define YYLEX_PARAM parm | |
3436 | %@} | |
3437 | @end example | |
3438 | ||
3439 | You should then define @code{yylex} to accept one additional | |
3440 | argument---the value of @code{parm}. (This makes either two or three | |
3441 | arguments in total, depending on whether an argument of type | |
3442 | @code{YYLTYPE} is passed.) You can declare the argument as a pointer to | |
3443 | the proper object type, or you can declare it as @code{void *} and | |
3444 | access the contents as shown above. | |
3445 | ||
931c7513 RS |
3446 | You can use @samp{%pure_parser} to request a reentrant parser without |
3447 | also using @code{YYPARSE_PARAM}. Then you should call @code{yyparse} | |
3448 | with no arguments, as usual. | |
3449 | ||
bfa74976 RS |
3450 | @node Error Reporting, Action Features, Lexical, Interface |
3451 | @section The Error Reporting Function @code{yyerror} | |
3452 | @cindex error reporting function | |
3453 | @findex yyerror | |
3454 | @cindex parse error | |
3455 | @cindex syntax error | |
3456 | ||
3457 | The Bison parser detects a @dfn{parse error} or @dfn{syntax error} | |
9ecbd125 | 3458 | whenever it reads a token which cannot satisfy any syntax rule. An |
bfa74976 | 3459 | action in the grammar can also explicitly proclaim an error, using the |
ceed8467 AD |
3460 | macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use |
3461 | in Actions}). | |
bfa74976 RS |
3462 | |
3463 | The Bison parser expects to report the error by calling an error | |
3464 | reporting function named @code{yyerror}, which you must supply. It is | |
3465 | called by @code{yyparse} whenever a syntax error is found, and it | |
3466 | receives one argument. For a parse error, the string is normally | |
3467 | @w{@code{"parse error"}}. | |
3468 | ||
3469 | @findex YYERROR_VERBOSE | |
3470 | If you define the macro @code{YYERROR_VERBOSE} in the Bison declarations | |
ceed8467 AD |
3471 | section (@pxref{Bison Declarations, ,The Bison Declarations Section}), |
3472 | then Bison provides a more verbose and specific error message string | |
3473 | instead of just plain @w{@code{"parse error"}}. It doesn't matter what | |
3474 | definition you use for @code{YYERROR_VERBOSE}, just whether you define | |
3475 | it. | |
bfa74976 RS |
3476 | |
3477 | The parser can detect one other kind of error: stack overflow. This | |
3478 | happens when the input contains constructions that are very deeply | |
3479 | nested. It isn't likely you will encounter this, since the Bison | |
3480 | parser extends its stack automatically up to a very large limit. But | |
3481 | if overflow happens, @code{yyparse} calls @code{yyerror} in the usual | |
3482 | fashion, except that the argument string is @w{@code{"parser stack | |
3483 | overflow"}}. | |
3484 | ||
3485 | The following definition suffices in simple programs: | |
3486 | ||
3487 | @example | |
3488 | @group | |
13863333 AD |
3489 | void |
3490 | yyerror (char *s) | |
bfa74976 RS |
3491 | @{ |
3492 | @end group | |
3493 | @group | |
3494 | fprintf (stderr, "%s\n", s); | |
3495 | @} | |
3496 | @end group | |
3497 | @end example | |
3498 | ||
3499 | After @code{yyerror} returns to @code{yyparse}, the latter will attempt | |
3500 | error recovery if you have written suitable error recovery grammar rules | |
3501 | (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will | |
3502 | immediately return 1. | |
3503 | ||
3504 | @vindex yynerrs | |
3505 | The variable @code{yynerrs} contains the number of syntax errors | |
3506 | encountered so far. Normally this variable is global; but if you | |
3507 | request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}) then it is a local variable | |
3508 | which only the actions can access. | |
3509 | ||
3510 | @node Action Features, , Error Reporting, Interface | |
3511 | @section Special Features for Use in Actions | |
3512 | @cindex summary, action features | |
3513 | @cindex action features summary | |
3514 | ||
3515 | Here is a table of Bison constructs, variables and macros that | |
3516 | are useful in actions. | |
3517 | ||
3518 | @table @samp | |
3519 | @item $$ | |
3520 | Acts like a variable that contains the semantic value for the | |
3521 | grouping made by the current rule. @xref{Actions}. | |
3522 | ||
3523 | @item $@var{n} | |
3524 | Acts like a variable that contains the semantic value for the | |
3525 | @var{n}th component of the current rule. @xref{Actions}. | |
3526 | ||
3527 | @item $<@var{typealt}>$ | |
3528 | Like @code{$$} but specifies alternative @var{typealt} in the union | |
3529 | specified by the @code{%union} declaration. @xref{Action Types, ,Data Types of Values in Actions}. | |
3530 | ||
3531 | @item $<@var{typealt}>@var{n} | |
3532 | Like @code{$@var{n}} but specifies alternative @var{typealt} in the | |
13863333 | 3533 | union specified by the @code{%union} declaration. |
bfa74976 RS |
3534 | @xref{Action Types, ,Data Types of Values in Actions}.@refill |
3535 | ||
3536 | @item YYABORT; | |
3537 | Return immediately from @code{yyparse}, indicating failure. | |
3538 | @xref{Parser Function, ,The Parser Function @code{yyparse}}. | |
3539 | ||
3540 | @item YYACCEPT; | |
3541 | Return immediately from @code{yyparse}, indicating success. | |
3542 | @xref{Parser Function, ,The Parser Function @code{yyparse}}. | |
3543 | ||
3544 | @item YYBACKUP (@var{token}, @var{value}); | |
3545 | @findex YYBACKUP | |
3546 | Unshift a token. This macro is allowed only for rules that reduce | |
3547 | a single value, and only when there is no look-ahead token. | |
3548 | It installs a look-ahead token with token type @var{token} and | |
3549 | semantic value @var{value}; then it discards the value that was | |
3550 | going to be reduced by this rule. | |
3551 | ||
3552 | If the macro is used when it is not valid, such as when there is | |
3553 | a look-ahead token already, then it reports a syntax error with | |
3554 | a message @samp{cannot back up} and performs ordinary error | |
3555 | recovery. | |
3556 | ||
3557 | In either case, the rest of the action is not executed. | |
3558 | ||
3559 | @item YYEMPTY | |
3560 | @vindex YYEMPTY | |
3561 | Value stored in @code{yychar} when there is no look-ahead token. | |
3562 | ||
3563 | @item YYERROR; | |
3564 | @findex YYERROR | |
3565 | Cause an immediate syntax error. This statement initiates error | |
3566 | recovery just as if the parser itself had detected an error; however, it | |
3567 | does not call @code{yyerror}, and does not print any message. If you | |
3568 | want to print an error message, call @code{yyerror} explicitly before | |
3569 | the @samp{YYERROR;} statement. @xref{Error Recovery}. | |
3570 | ||
3571 | @item YYRECOVERING | |
3572 | This macro stands for an expression that has the value 1 when the parser | |
3573 | is recovering from a syntax error, and 0 the rest of the time. | |
3574 | @xref{Error Recovery}. | |
3575 | ||
3576 | @item yychar | |
3577 | Variable containing the current look-ahead token. (In a pure parser, | |
3578 | this is actually a local variable within @code{yyparse}.) When there is | |
3579 | no look-ahead token, the value @code{YYEMPTY} is stored in the variable. | |
3580 | @xref{Look-Ahead, ,Look-Ahead Tokens}. | |
3581 | ||
3582 | @item yyclearin; | |
3583 | Discard the current look-ahead token. This is useful primarily in | |
3584 | error rules. @xref{Error Recovery}. | |
3585 | ||
3586 | @item yyerrok; | |
3587 | Resume generating error messages immediately for subsequent syntax | |
13863333 | 3588 | errors. This is useful primarily in error rules. |
bfa74976 RS |
3589 | @xref{Error Recovery}. |
3590 | ||
847bf1f5 AD |
3591 | @item @@$ |
3592 | @findex @@$ | |
3593 | Acts like a structure variable containing information on the textual position | |
3594 | of the grouping made by the current rule. @xref{Locations, , | |
3595 | Tracking Locations}. | |
bfa74976 | 3596 | |
847bf1f5 AD |
3597 | @c Check if those paragraphs are still useful or not. |
3598 | ||
3599 | @c @example | |
3600 | @c struct @{ | |
3601 | @c int first_line, last_line; | |
3602 | @c int first_column, last_column; | |
3603 | @c @}; | |
3604 | @c @end example | |
3605 | ||
3606 | @c Thus, to get the starting line number of the third component, you would | |
3607 | @c use @samp{@@3.first_line}. | |
bfa74976 | 3608 | |
847bf1f5 AD |
3609 | @c In order for the members of this structure to contain valid information, |
3610 | @c you must make @code{yylex} supply this information about each token. | |
3611 | @c If you need only certain members, then @code{yylex} need only fill in | |
3612 | @c those members. | |
bfa74976 | 3613 | |
847bf1f5 AD |
3614 | @c The use of this feature makes the parser noticeably slower. |
3615 | ||
3616 | @item @@@var{n} | |
3617 | @findex @@@var{n} | |
3618 | Acts like a structure variable containing information on the textual position | |
3619 | of the @var{n}th component of the current rule. @xref{Locations, , | |
3620 | Tracking Locations}. | |
bfa74976 | 3621 | |
bfa74976 RS |
3622 | @end table |
3623 | ||
3624 | @node Algorithm, Error Recovery, Interface, Top | |
13863333 AD |
3625 | @chapter The Bison Parser Algorithm |
3626 | @cindex Bison parser algorithm | |
bfa74976 RS |
3627 | @cindex algorithm of parser |
3628 | @cindex shifting | |
3629 | @cindex reduction | |
3630 | @cindex parser stack | |
3631 | @cindex stack, parser | |
3632 | ||
3633 | As Bison reads tokens, it pushes them onto a stack along with their | |
3634 | semantic values. The stack is called the @dfn{parser stack}. Pushing a | |
3635 | token is traditionally called @dfn{shifting}. | |
3636 | ||
3637 | For example, suppose the infix calculator has read @samp{1 + 5 *}, with a | |
3638 | @samp{3} to come. The stack will have four elements, one for each token | |
3639 | that was shifted. | |
3640 | ||
3641 | But the stack does not always have an element for each token read. When | |
3642 | the last @var{n} tokens and groupings shifted match the components of a | |
3643 | grammar rule, they can be combined according to that rule. This is called | |
3644 | @dfn{reduction}. Those tokens and groupings are replaced on the stack by a | |
3645 | single grouping whose symbol is the result (left hand side) of that rule. | |
3646 | Running the rule's action is part of the process of reduction, because this | |
3647 | is what computes the semantic value of the resulting grouping. | |
3648 | ||
3649 | For example, if the infix calculator's parser stack contains this: | |
3650 | ||
3651 | @example | |
3652 | 1 + 5 * 3 | |
3653 | @end example | |
3654 | ||
3655 | @noindent | |
3656 | and the next input token is a newline character, then the last three | |
3657 | elements can be reduced to 15 via the rule: | |
3658 | ||
3659 | @example | |
3660 | expr: expr '*' expr; | |
3661 | @end example | |
3662 | ||
3663 | @noindent | |
3664 | Then the stack contains just these three elements: | |
3665 | ||
3666 | @example | |
3667 | 1 + 15 | |
3668 | @end example | |
3669 | ||
3670 | @noindent | |
3671 | At this point, another reduction can be made, resulting in the single value | |
3672 | 16. Then the newline token can be shifted. | |
3673 | ||
3674 | The parser tries, by shifts and reductions, to reduce the entire input down | |
3675 | to a single grouping whose symbol is the grammar's start-symbol | |
3676 | (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}). | |
3677 | ||
3678 | This kind of parser is known in the literature as a bottom-up parser. | |
3679 | ||
3680 | @menu | |
3681 | * Look-Ahead:: Parser looks one token ahead when deciding what to do. | |
3682 | * Shift/Reduce:: Conflicts: when either shifting or reduction is valid. | |
3683 | * Precedence:: Operator precedence works by resolving conflicts. | |
3684 | * Contextual Precedence:: When an operator's precedence depends on context. | |
3685 | * Parser States:: The parser is a finite-state-machine with stack. | |
3686 | * Reduce/Reduce:: When two rules are applicable in the same situation. | |
3687 | * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified. | |
3688 | * Stack Overflow:: What happens when stack gets full. How to avoid it. | |
3689 | @end menu | |
3690 | ||
3691 | @node Look-Ahead, Shift/Reduce, , Algorithm | |
3692 | @section Look-Ahead Tokens | |
3693 | @cindex look-ahead token | |
3694 | ||
3695 | The Bison parser does @emph{not} always reduce immediately as soon as the | |
3696 | last @var{n} tokens and groupings match a rule. This is because such a | |
3697 | simple strategy is inadequate to handle most languages. Instead, when a | |
3698 | reduction is possible, the parser sometimes ``looks ahead'' at the next | |
3699 | token in order to decide what to do. | |
3700 | ||
3701 | When a token is read, it is not immediately shifted; first it becomes the | |
3702 | @dfn{look-ahead token}, which is not on the stack. Now the parser can | |
3703 | perform one or more reductions of tokens and groupings on the stack, while | |
3704 | the look-ahead token remains off to the side. When no more reductions | |
3705 | should take place, the look-ahead token is shifted onto the stack. This | |
3706 | does not mean that all possible reductions have been done; depending on the | |
3707 | token type of the look-ahead token, some rules may choose to delay their | |
3708 | application. | |
3709 | ||
3710 | Here is a simple case where look-ahead is needed. These three rules define | |
3711 | expressions which contain binary addition operators and postfix unary | |
3712 | factorial operators (@samp{!}), and allow parentheses for grouping. | |
3713 | ||
3714 | @example | |
3715 | @group | |
3716 | expr: term '+' expr | |
3717 | | term | |
3718 | ; | |
3719 | @end group | |
3720 | ||
3721 | @group | |
3722 | term: '(' expr ')' | |
3723 | | term '!' | |
3724 | | NUMBER | |
3725 | ; | |
3726 | @end group | |
3727 | @end example | |
3728 | ||
3729 | Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what | |
3730 | should be done? If the following token is @samp{)}, then the first three | |
3731 | tokens must be reduced to form an @code{expr}. This is the only valid | |
3732 | course, because shifting the @samp{)} would produce a sequence of symbols | |
3733 | @w{@code{term ')'}}, and no rule allows this. | |
3734 | ||
3735 | If the following token is @samp{!}, then it must be shifted immediately so | |
3736 | that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the | |
3737 | parser were to reduce before shifting, @w{@samp{1 + 2}} would become an | |
3738 | @code{expr}. It would then be impossible to shift the @samp{!} because | |
3739 | doing so would produce on the stack the sequence of symbols @code{expr | |
3740 | '!'}. No rule allows that sequence. | |
3741 | ||
3742 | @vindex yychar | |
3743 | The current look-ahead token is stored in the variable @code{yychar}. | |
3744 | @xref{Action Features, ,Special Features for Use in Actions}. | |
3745 | ||
3746 | @node Shift/Reduce, Precedence, Look-Ahead, Algorithm | |
3747 | @section Shift/Reduce Conflicts | |
3748 | @cindex conflicts | |
3749 | @cindex shift/reduce conflicts | |
3750 | @cindex dangling @code{else} | |
3751 | @cindex @code{else}, dangling | |
3752 | ||
3753 | Suppose we are parsing a language which has if-then and if-then-else | |
3754 | statements, with a pair of rules like this: | |
3755 | ||
3756 | @example | |
3757 | @group | |
3758 | if_stmt: | |
3759 | IF expr THEN stmt | |
3760 | | IF expr THEN stmt ELSE stmt | |
3761 | ; | |
3762 | @end group | |
3763 | @end example | |
3764 | ||
3765 | @noindent | |
3766 | Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are | |
3767 | terminal symbols for specific keyword tokens. | |
3768 | ||
3769 | When the @code{ELSE} token is read and becomes the look-ahead token, the | |
3770 | contents of the stack (assuming the input is valid) are just right for | |
3771 | reduction by the first rule. But it is also legitimate to shift the | |
3772 | @code{ELSE}, because that would lead to eventual reduction by the second | |
3773 | rule. | |
3774 | ||
3775 | This situation, where either a shift or a reduction would be valid, is | |
3776 | called a @dfn{shift/reduce conflict}. Bison is designed to resolve | |
3777 | these conflicts by choosing to shift, unless otherwise directed by | |
3778 | operator precedence declarations. To see the reason for this, let's | |
3779 | contrast it with the other alternative. | |
3780 | ||
3781 | Since the parser prefers to shift the @code{ELSE}, the result is to attach | |
3782 | the else-clause to the innermost if-statement, making these two inputs | |
3783 | equivalent: | |
3784 | ||
3785 | @example | |
3786 | if x then if y then win (); else lose; | |
3787 | ||
3788 | if x then do; if y then win (); else lose; end; | |
3789 | @end example | |
3790 | ||
3791 | But if the parser chose to reduce when possible rather than shift, the | |
3792 | result would be to attach the else-clause to the outermost if-statement, | |
3793 | making these two inputs equivalent: | |
3794 | ||
3795 | @example | |
3796 | if x then if y then win (); else lose; | |
3797 | ||
3798 | if x then do; if y then win (); end; else lose; | |
3799 | @end example | |
3800 | ||
3801 | The conflict exists because the grammar as written is ambiguous: either | |
3802 | parsing of the simple nested if-statement is legitimate. The established | |
3803 | convention is that these ambiguities are resolved by attaching the | |
3804 | else-clause to the innermost if-statement; this is what Bison accomplishes | |
3805 | by choosing to shift rather than reduce. (It would ideally be cleaner to | |
3806 | write an unambiguous grammar, but that is very hard to do in this case.) | |
3807 | This particular ambiguity was first encountered in the specifications of | |
3808 | Algol 60 and is called the ``dangling @code{else}'' ambiguity. | |
3809 | ||
3810 | To avoid warnings from Bison about predictable, legitimate shift/reduce | |
3811 | conflicts, use the @code{%expect @var{n}} declaration. There will be no | |
3812 | warning as long as the number of shift/reduce conflicts is exactly @var{n}. | |
3813 | @xref{Expect Decl, ,Suppressing Conflict Warnings}. | |
3814 | ||
3815 | The definition of @code{if_stmt} above is solely to blame for the | |
3816 | conflict, but the conflict does not actually appear without additional | |
3817 | rules. Here is a complete Bison input file that actually manifests the | |
3818 | conflict: | |
3819 | ||
3820 | @example | |
3821 | @group | |
3822 | %token IF THEN ELSE variable | |
3823 | %% | |
3824 | @end group | |
3825 | @group | |
3826 | stmt: expr | |
3827 | | if_stmt | |
3828 | ; | |
3829 | @end group | |
3830 | ||
3831 | @group | |
3832 | if_stmt: | |
3833 | IF expr THEN stmt | |
3834 | | IF expr THEN stmt ELSE stmt | |
3835 | ; | |
3836 | @end group | |
3837 | ||
3838 | expr: variable | |
3839 | ; | |
3840 | @end example | |
3841 | ||
3842 | @node Precedence, Contextual Precedence, Shift/Reduce, Algorithm | |
3843 | @section Operator Precedence | |
3844 | @cindex operator precedence | |
3845 | @cindex precedence of operators | |
3846 | ||
3847 | Another situation where shift/reduce conflicts appear is in arithmetic | |
3848 | expressions. Here shifting is not always the preferred resolution; the | |
3849 | Bison declarations for operator precedence allow you to specify when to | |
3850 | shift and when to reduce. | |
3851 | ||
3852 | @menu | |
3853 | * Why Precedence:: An example showing why precedence is needed. | |
3854 | * Using Precedence:: How to specify precedence in Bison grammars. | |
3855 | * Precedence Examples:: How these features are used in the previous example. | |
3856 | * How Precedence:: How they work. | |
3857 | @end menu | |
3858 | ||
3859 | @node Why Precedence, Using Precedence, , Precedence | |
3860 | @subsection When Precedence is Needed | |
3861 | ||
3862 | Consider the following ambiguous grammar fragment (ambiguous because the | |
3863 | input @w{@samp{1 - 2 * 3}} can be parsed in two different ways): | |
3864 | ||
3865 | @example | |
3866 | @group | |
3867 | expr: expr '-' expr | |
3868 | | expr '*' expr | |
3869 | | expr '<' expr | |
3870 | | '(' expr ')' | |
3871 | @dots{} | |
3872 | ; | |
3873 | @end group | |
3874 | @end example | |
3875 | ||
3876 | @noindent | |
3877 | Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2}; | |
14ded682 AD |
3878 | should it reduce them via the rule for the subtraction operator? It |
3879 | depends on the next token. Of course, if the next token is @samp{)}, we | |
3880 | must reduce; shifting is invalid because no single rule can reduce the | |
3881 | token sequence @w{@samp{- 2 )}} or anything starting with that. But if | |
3882 | the next token is @samp{*} or @samp{<}, we have a choice: either | |
3883 | shifting or reduction would allow the parse to complete, but with | |
3884 | different results. | |
3885 | ||
3886 | To decide which one Bison should do, we must consider the results. If | |
3887 | the next operator token @var{op} is shifted, then it must be reduced | |
3888 | first in order to permit another opportunity to reduce the difference. | |
3889 | The result is (in effect) @w{@samp{1 - (2 @var{op} 3)}}. On the other | |
3890 | hand, if the subtraction is reduced before shifting @var{op}, the result | |
3891 | is @w{@samp{(1 - 2) @var{op} 3}}. Clearly, then, the choice of shift or | |
3892 | reduce should depend on the relative precedence of the operators | |
3893 | @samp{-} and @var{op}: @samp{*} should be shifted first, but not | |
3894 | @samp{<}. | |
bfa74976 RS |
3895 | |
3896 | @cindex associativity | |
3897 | What about input such as @w{@samp{1 - 2 - 5}}; should this be | |
14ded682 AD |
3898 | @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For most |
3899 | operators we prefer the former, which is called @dfn{left association}. | |
3900 | The latter alternative, @dfn{right association}, is desirable for | |
3901 | assignment operators. The choice of left or right association is a | |
3902 | matter of whether the parser chooses to shift or reduce when the stack | |
3903 | contains @w{@samp{1 - 2}} and the look-ahead token is @samp{-}: shifting | |
3904 | makes right-associativity. | |
bfa74976 RS |
3905 | |
3906 | @node Using Precedence, Precedence Examples, Why Precedence, Precedence | |
3907 | @subsection Specifying Operator Precedence | |
3908 | @findex %left | |
3909 | @findex %right | |
3910 | @findex %nonassoc | |
3911 | ||
3912 | Bison allows you to specify these choices with the operator precedence | |
3913 | declarations @code{%left} and @code{%right}. Each such declaration | |
3914 | contains a list of tokens, which are operators whose precedence and | |
3915 | associativity is being declared. The @code{%left} declaration makes all | |
3916 | those operators left-associative and the @code{%right} declaration makes | |
3917 | them right-associative. A third alternative is @code{%nonassoc}, which | |
3918 | declares that it is a syntax error to find the same operator twice ``in a | |
3919 | row''. | |
3920 | ||
3921 | The relative precedence of different operators is controlled by the | |
3922 | order in which they are declared. The first @code{%left} or | |
3923 | @code{%right} declaration in the file declares the operators whose | |
3924 | precedence is lowest, the next such declaration declares the operators | |
3925 | whose precedence is a little higher, and so on. | |
3926 | ||
3927 | @node Precedence Examples, How Precedence, Using Precedence, Precedence | |
3928 | @subsection Precedence Examples | |
3929 | ||
3930 | In our example, we would want the following declarations: | |
3931 | ||
3932 | @example | |
3933 | %left '<' | |
3934 | %left '-' | |
3935 | %left '*' | |
3936 | @end example | |
3937 | ||
3938 | In a more complete example, which supports other operators as well, we | |
3939 | would declare them in groups of equal precedence. For example, @code{'+'} is | |
3940 | declared with @code{'-'}: | |
3941 | ||
3942 | @example | |
3943 | %left '<' '>' '=' NE LE GE | |
3944 | %left '+' '-' | |
3945 | %left '*' '/' | |
3946 | @end example | |
3947 | ||
3948 | @noindent | |
3949 | (Here @code{NE} and so on stand for the operators for ``not equal'' | |
3950 | and so on. We assume that these tokens are more than one character long | |
3951 | and therefore are represented by names, not character literals.) | |
3952 | ||
3953 | @node How Precedence, , Precedence Examples, Precedence | |
3954 | @subsection How Precedence Works | |
3955 | ||
3956 | The first effect of the precedence declarations is to assign precedence | |
3957 | levels to the terminal symbols declared. The second effect is to assign | |
3958 | precedence levels to certain rules: each rule gets its precedence from the | |
3959 | last terminal symbol mentioned in the components. (You can also specify | |
3960 | explicitly the precedence of a rule. @xref{Contextual Precedence, ,Context-Dependent Precedence}.) | |
3961 | ||
3962 | Finally, the resolution of conflicts works by comparing the | |
3963 | precedence of the rule being considered with that of the | |
3964 | look-ahead token. If the token's precedence is higher, the | |
3965 | choice is to shift. If the rule's precedence is higher, the | |
3966 | choice is to reduce. If they have equal precedence, the choice | |
3967 | is made based on the associativity of that precedence level. The | |
3968 | verbose output file made by @samp{-v} (@pxref{Invocation, ,Invoking Bison}) says | |
3969 | how each conflict was resolved. | |
3970 | ||
3971 | Not all rules and not all tokens have precedence. If either the rule or | |
3972 | the look-ahead token has no precedence, then the default is to shift. | |
3973 | ||
3974 | @node Contextual Precedence, Parser States, Precedence, Algorithm | |
3975 | @section Context-Dependent Precedence | |
3976 | @cindex context-dependent precedence | |
3977 | @cindex unary operator precedence | |
3978 | @cindex precedence, context-dependent | |
3979 | @cindex precedence, unary operator | |
3980 | @findex %prec | |
3981 | ||
3982 | Often the precedence of an operator depends on the context. This sounds | |
3983 | outlandish at first, but it is really very common. For example, a minus | |
3984 | sign typically has a very high precedence as a unary operator, and a | |
3985 | somewhat lower precedence (lower than multiplication) as a binary operator. | |
3986 | ||
3987 | The Bison precedence declarations, @code{%left}, @code{%right} and | |
3988 | @code{%nonassoc}, can only be used once for a given token; so a token has | |
3989 | only one precedence declared in this way. For context-dependent | |
3990 | precedence, you need to use an additional mechanism: the @code{%prec} | |
3991 | modifier for rules.@refill | |
3992 | ||
3993 | The @code{%prec} modifier declares the precedence of a particular rule by | |
3994 | specifying a terminal symbol whose precedence should be used for that rule. | |
3995 | It's not necessary for that symbol to appear otherwise in the rule. The | |
3996 | modifier's syntax is: | |
3997 | ||
3998 | @example | |
3999 | %prec @var{terminal-symbol} | |
4000 | @end example | |
4001 | ||
4002 | @noindent | |
4003 | and it is written after the components of the rule. Its effect is to | |
4004 | assign the rule the precedence of @var{terminal-symbol}, overriding | |
4005 | the precedence that would be deduced for it in the ordinary way. The | |
4006 | altered rule precedence then affects how conflicts involving that rule | |
4007 | are resolved (@pxref{Precedence, ,Operator Precedence}). | |
4008 | ||
4009 | Here is how @code{%prec} solves the problem of unary minus. First, declare | |
4010 | a precedence for a fictitious terminal symbol named @code{UMINUS}. There | |
4011 | are no tokens of this type, but the symbol serves to stand for its | |
4012 | precedence: | |
4013 | ||
4014 | @example | |
4015 | @dots{} | |
4016 | %left '+' '-' | |
4017 | %left '*' | |
4018 | %left UMINUS | |
4019 | @end example | |
4020 | ||
4021 | Now the precedence of @code{UMINUS} can be used in specific rules: | |
4022 | ||
4023 | @example | |
4024 | @group | |
4025 | exp: @dots{} | |
4026 | | exp '-' exp | |
4027 | @dots{} | |
4028 | | '-' exp %prec UMINUS | |
4029 | @end group | |
4030 | @end example | |
4031 | ||
4032 | @node Parser States, Reduce/Reduce, Contextual Precedence, Algorithm | |
4033 | @section Parser States | |
4034 | @cindex finite-state machine | |
4035 | @cindex parser state | |
4036 | @cindex state (of parser) | |
4037 | ||
4038 | The function @code{yyparse} is implemented using a finite-state machine. | |
4039 | The values pushed on the parser stack are not simply token type codes; they | |
4040 | represent the entire sequence of terminal and nonterminal symbols at or | |
4041 | near the top of the stack. The current state collects all the information | |
4042 | about previous input which is relevant to deciding what to do next. | |
4043 | ||
4044 | Each time a look-ahead token is read, the current parser state together | |
4045 | with the type of look-ahead token are looked up in a table. This table | |
4046 | entry can say, ``Shift the look-ahead token.'' In this case, it also | |
4047 | specifies the new parser state, which is pushed onto the top of the | |
4048 | parser stack. Or it can say, ``Reduce using rule number @var{n}.'' | |
4049 | This means that a certain number of tokens or groupings are taken off | |
4050 | the top of the stack, and replaced by one grouping. In other words, | |
4051 | that number of states are popped from the stack, and one new state is | |
4052 | pushed. | |
4053 | ||
4054 | There is one other alternative: the table can say that the look-ahead token | |
4055 | is erroneous in the current state. This causes error processing to begin | |
4056 | (@pxref{Error Recovery}). | |
4057 | ||
4058 | @node Reduce/Reduce, Mystery Conflicts, Parser States, Algorithm | |
4059 | @section Reduce/Reduce Conflicts | |
4060 | @cindex reduce/reduce conflict | |
4061 | @cindex conflicts, reduce/reduce | |
4062 | ||
4063 | A reduce/reduce conflict occurs if there are two or more rules that apply | |
4064 | to the same sequence of input. This usually indicates a serious error | |
4065 | in the grammar. | |
4066 | ||
4067 | For example, here is an erroneous attempt to define a sequence | |
4068 | of zero or more @code{word} groupings. | |
4069 | ||
4070 | @example | |
4071 | sequence: /* empty */ | |
4072 | @{ printf ("empty sequence\n"); @} | |
4073 | | maybeword | |
4074 | | sequence word | |
4075 | @{ printf ("added word %s\n", $2); @} | |
4076 | ; | |
4077 | ||
4078 | maybeword: /* empty */ | |
4079 | @{ printf ("empty maybeword\n"); @} | |
4080 | | word | |
4081 | @{ printf ("single word %s\n", $1); @} | |
4082 | ; | |
4083 | @end example | |
4084 | ||
4085 | @noindent | |
4086 | The error is an ambiguity: there is more than one way to parse a single | |
4087 | @code{word} into a @code{sequence}. It could be reduced to a | |
4088 | @code{maybeword} and then into a @code{sequence} via the second rule. | |
4089 | Alternatively, nothing-at-all could be reduced into a @code{sequence} | |
4090 | via the first rule, and this could be combined with the @code{word} | |
4091 | using the third rule for @code{sequence}. | |
4092 | ||
4093 | There is also more than one way to reduce nothing-at-all into a | |
4094 | @code{sequence}. This can be done directly via the first rule, | |
4095 | or indirectly via @code{maybeword} and then the second rule. | |
4096 | ||
4097 | You might think that this is a distinction without a difference, because it | |
4098 | does not change whether any particular input is valid or not. But it does | |
4099 | affect which actions are run. One parsing order runs the second rule's | |
4100 | action; the other runs the first rule's action and the third rule's action. | |
4101 | In this example, the output of the program changes. | |
4102 | ||
4103 | Bison resolves a reduce/reduce conflict by choosing to use the rule that | |
4104 | appears first in the grammar, but it is very risky to rely on this. Every | |
4105 | reduce/reduce conflict must be studied and usually eliminated. Here is the | |
4106 | proper way to define @code{sequence}: | |
4107 | ||
4108 | @example | |
4109 | sequence: /* empty */ | |
4110 | @{ printf ("empty sequence\n"); @} | |
4111 | | sequence word | |
4112 | @{ printf ("added word %s\n", $2); @} | |
4113 | ; | |
4114 | @end example | |
4115 | ||
4116 | Here is another common error that yields a reduce/reduce conflict: | |
4117 | ||
4118 | @example | |
4119 | sequence: /* empty */ | |
4120 | | sequence words | |
4121 | | sequence redirects | |
4122 | ; | |
4123 | ||
4124 | words: /* empty */ | |
4125 | | words word | |
4126 | ; | |
4127 | ||
4128 | redirects:/* empty */ | |
4129 | | redirects redirect | |
4130 | ; | |
4131 | @end example | |
4132 | ||
4133 | @noindent | |
4134 | The intention here is to define a sequence which can contain either | |
4135 | @code{word} or @code{redirect} groupings. The individual definitions of | |
4136 | @code{sequence}, @code{words} and @code{redirects} are error-free, but the | |
4137 | three together make a subtle ambiguity: even an empty input can be parsed | |
4138 | in infinitely many ways! | |
4139 | ||
4140 | Consider: nothing-at-all could be a @code{words}. Or it could be two | |
4141 | @code{words} in a row, or three, or any number. It could equally well be a | |
4142 | @code{redirects}, or two, or any number. Or it could be a @code{words} | |
4143 | followed by three @code{redirects} and another @code{words}. And so on. | |
4144 | ||
4145 | Here are two ways to correct these rules. First, to make it a single level | |
4146 | of sequence: | |
4147 | ||
4148 | @example | |
4149 | sequence: /* empty */ | |
4150 | | sequence word | |
4151 | | sequence redirect | |
4152 | ; | |
4153 | @end example | |
4154 | ||
4155 | Second, to prevent either a @code{words} or a @code{redirects} | |
4156 | from being empty: | |
4157 | ||
4158 | @example | |
4159 | sequence: /* empty */ | |
4160 | | sequence words | |
4161 | | sequence redirects | |
4162 | ; | |
4163 | ||
4164 | words: word | |
4165 | | words word | |
4166 | ; | |
4167 | ||
4168 | redirects:redirect | |
4169 | | redirects redirect | |
4170 | ; | |
4171 | @end example | |
4172 | ||
4173 | @node Mystery Conflicts, Stack Overflow, Reduce/Reduce, Algorithm | |
4174 | @section Mysterious Reduce/Reduce Conflicts | |
4175 | ||
4176 | Sometimes reduce/reduce conflicts can occur that don't look warranted. | |
4177 | Here is an example: | |
4178 | ||
4179 | @example | |
4180 | @group | |
4181 | %token ID | |
4182 | ||
4183 | %% | |
4184 | def: param_spec return_spec ',' | |
4185 | ; | |
4186 | param_spec: | |
4187 | type | |
4188 | | name_list ':' type | |
4189 | ; | |
4190 | @end group | |
4191 | @group | |
4192 | return_spec: | |
4193 | type | |
4194 | | name ':' type | |
4195 | ; | |
4196 | @end group | |
4197 | @group | |
4198 | type: ID | |
4199 | ; | |
4200 | @end group | |
4201 | @group | |
4202 | name: ID | |
4203 | ; | |
4204 | name_list: | |
4205 | name | |
4206 | | name ',' name_list | |
4207 | ; | |
4208 | @end group | |
4209 | @end example | |
4210 | ||
4211 | It would seem that this grammar can be parsed with only a single token | |
13863333 | 4212 | of look-ahead: when a @code{param_spec} is being read, an @code{ID} is |
bfa74976 RS |
4213 | a @code{name} if a comma or colon follows, or a @code{type} if another |
4214 | @code{ID} follows. In other words, this grammar is LR(1). | |
4215 | ||
4216 | @cindex LR(1) | |
4217 | @cindex LALR(1) | |
4218 | However, Bison, like most parser generators, cannot actually handle all | |
4219 | LR(1) grammars. In this grammar, two contexts, that after an @code{ID} | |
4220 | at the beginning of a @code{param_spec} and likewise at the beginning of | |
4221 | a @code{return_spec}, are similar enough that Bison assumes they are the | |
4222 | same. They appear similar because the same set of rules would be | |
4223 | active---the rule for reducing to a @code{name} and that for reducing to | |
4224 | a @code{type}. Bison is unable to determine at that stage of processing | |
4225 | that the rules would require different look-ahead tokens in the two | |
4226 | contexts, so it makes a single parser state for them both. Combining | |
4227 | the two contexts causes a conflict later. In parser terminology, this | |
4228 | occurrence means that the grammar is not LALR(1). | |
4229 | ||
4230 | In general, it is better to fix deficiencies than to document them. But | |
4231 | this particular deficiency is intrinsically hard to fix; parser | |
4232 | generators that can handle LR(1) grammars are hard to write and tend to | |
4233 | produce parsers that are very large. In practice, Bison is more useful | |
4234 | as it is now. | |
4235 | ||
4236 | When the problem arises, you can often fix it by identifying the two | |
4237 | parser states that are being confused, and adding something to make them | |
4238 | look distinct. In the above example, adding one rule to | |
4239 | @code{return_spec} as follows makes the problem go away: | |
4240 | ||
4241 | @example | |
4242 | @group | |
4243 | %token BOGUS | |
4244 | @dots{} | |
4245 | %% | |
4246 | @dots{} | |
4247 | return_spec: | |
4248 | type | |
4249 | | name ':' type | |
4250 | /* This rule is never used. */ | |
4251 | | ID BOGUS | |
4252 | ; | |
4253 | @end group | |
4254 | @end example | |
4255 | ||
4256 | This corrects the problem because it introduces the possibility of an | |
4257 | additional active rule in the context after the @code{ID} at the beginning of | |
4258 | @code{return_spec}. This rule is not active in the corresponding context | |
4259 | in a @code{param_spec}, so the two contexts receive distinct parser states. | |
4260 | As long as the token @code{BOGUS} is never generated by @code{yylex}, | |
4261 | the added rule cannot alter the way actual input is parsed. | |
4262 | ||
4263 | In this particular example, there is another way to solve the problem: | |
4264 | rewrite the rule for @code{return_spec} to use @code{ID} directly | |
4265 | instead of via @code{name}. This also causes the two confusing | |
4266 | contexts to have different sets of active rules, because the one for | |
4267 | @code{return_spec} activates the altered rule for @code{return_spec} | |
4268 | rather than the one for @code{name}. | |
4269 | ||
4270 | @example | |
4271 | param_spec: | |
4272 | type | |
4273 | | name_list ':' type | |
4274 | ; | |
4275 | return_spec: | |
4276 | type | |
4277 | | ID ':' type | |
4278 | ; | |
4279 | @end example | |
4280 | ||
4281 | @node Stack Overflow, , Mystery Conflicts, Algorithm | |
4282 | @section Stack Overflow, and How to Avoid It | |
4283 | @cindex stack overflow | |
4284 | @cindex parser stack overflow | |
4285 | @cindex overflow of parser stack | |
4286 | ||
4287 | The Bison parser stack can overflow if too many tokens are shifted and | |
4288 | not reduced. When this happens, the parser function @code{yyparse} | |
4289 | returns a nonzero value, pausing only to call @code{yyerror} to report | |
4290 | the overflow. | |
4291 | ||
4292 | @vindex YYMAXDEPTH | |
4293 | By defining the macro @code{YYMAXDEPTH}, you can control how deep the | |
4294 | parser stack can become before a stack overflow occurs. Define the | |
4295 | macro with a value that is an integer. This value is the maximum number | |
4296 | of tokens that can be shifted (and not reduced) before overflow. | |
4297 | It must be a constant expression whose value is known at compile time. | |
4298 | ||
4299 | The stack space allowed is not necessarily allocated. If you specify a | |
4300 | large value for @code{YYMAXDEPTH}, the parser actually allocates a small | |
4301 | stack at first, and then makes it bigger by stages as needed. This | |
4302 | increasing allocation happens automatically and silently. Therefore, | |
4303 | you do not need to make @code{YYMAXDEPTH} painfully small merely to save | |
4304 | space for ordinary inputs that do not need much stack. | |
4305 | ||
4306 | @cindex default stack limit | |
4307 | The default value of @code{YYMAXDEPTH}, if you do not define it, is | |
4308 | 10000. | |
4309 | ||
4310 | @vindex YYINITDEPTH | |
4311 | You can control how much stack is allocated initially by defining the | |
4312 | macro @code{YYINITDEPTH}. This value too must be a compile-time | |
4313 | constant integer. The default is 200. | |
4314 | ||
4315 | @node Error Recovery, Context Dependency, Algorithm, Top | |
4316 | @chapter Error Recovery | |
4317 | @cindex error recovery | |
4318 | @cindex recovery from errors | |
4319 | ||
4320 | It is not usually acceptable to have a program terminate on a parse | |
4321 | error. For example, a compiler should recover sufficiently to parse the | |
4322 | rest of the input file and check it for errors; a calculator should accept | |
4323 | another expression. | |
4324 | ||
4325 | In a simple interactive command parser where each input is one line, it may | |
4326 | be sufficient to allow @code{yyparse} to return 1 on error and have the | |
4327 | caller ignore the rest of the input line when that happens (and then call | |
4328 | @code{yyparse} again). But this is inadequate for a compiler, because it | |
4329 | forgets all the syntactic context leading up to the error. A syntax error | |
4330 | deep within a function in the compiler input should not cause the compiler | |
4331 | to treat the following line like the beginning of a source file. | |
4332 | ||
4333 | @findex error | |
4334 | You can define how to recover from a syntax error by writing rules to | |
4335 | recognize the special token @code{error}. This is a terminal symbol that | |
4336 | is always defined (you need not declare it) and reserved for error | |
4337 | handling. The Bison parser generates an @code{error} token whenever a | |
4338 | syntax error happens; if you have provided a rule to recognize this token | |
13863333 | 4339 | in the current context, the parse can continue. |
bfa74976 RS |
4340 | |
4341 | For example: | |
4342 | ||
4343 | @example | |
4344 | stmnts: /* empty string */ | |
4345 | | stmnts '\n' | |
4346 | | stmnts exp '\n' | |
4347 | | stmnts error '\n' | |
4348 | @end example | |
4349 | ||
4350 | The fourth rule in this example says that an error followed by a newline | |
4351 | makes a valid addition to any @code{stmnts}. | |
4352 | ||
4353 | What happens if a syntax error occurs in the middle of an @code{exp}? The | |
4354 | error recovery rule, interpreted strictly, applies to the precise sequence | |
4355 | of a @code{stmnts}, an @code{error} and a newline. If an error occurs in | |
4356 | the middle of an @code{exp}, there will probably be some additional tokens | |
4357 | and subexpressions on the stack after the last @code{stmnts}, and there | |
4358 | will be tokens to read before the next newline. So the rule is not | |
4359 | applicable in the ordinary way. | |
4360 | ||
4361 | But Bison can force the situation to fit the rule, by discarding part of | |
4362 | the semantic context and part of the input. First it discards states and | |
4363 | objects from the stack until it gets back to a state in which the | |
4364 | @code{error} token is acceptable. (This means that the subexpressions | |
4365 | already parsed are discarded, back to the last complete @code{stmnts}.) At | |
4366 | this point the @code{error} token can be shifted. Then, if the old | |
4367 | look-ahead token is not acceptable to be shifted next, the parser reads | |
4368 | tokens and discards them until it finds a token which is acceptable. In | |
4369 | this example, Bison reads and discards input until the next newline | |
4370 | so that the fourth rule can apply. | |
4371 | ||
4372 | The choice of error rules in the grammar is a choice of strategies for | |
4373 | error recovery. A simple and useful strategy is simply to skip the rest of | |
4374 | the current input line or current statement if an error is detected: | |
4375 | ||
4376 | @example | |
4377 | stmnt: error ';' /* on error, skip until ';' is read */ | |
4378 | @end example | |
4379 | ||
4380 | It is also useful to recover to the matching close-delimiter of an | |
4381 | opening-delimiter that has already been parsed. Otherwise the | |
4382 | close-delimiter will probably appear to be unmatched, and generate another, | |
4383 | spurious error message: | |
4384 | ||
4385 | @example | |
4386 | primary: '(' expr ')' | |
4387 | | '(' error ')' | |
4388 | @dots{} | |
4389 | ; | |
4390 | @end example | |
4391 | ||
4392 | Error recovery strategies are necessarily guesses. When they guess wrong, | |
4393 | one syntax error often leads to another. In the above example, the error | |
4394 | recovery rule guesses that an error is due to bad input within one | |
4395 | @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the | |
4396 | middle of a valid @code{stmnt}. After the error recovery rule recovers | |
4397 | from the first error, another syntax error will be found straightaway, | |
4398 | since the text following the spurious semicolon is also an invalid | |
4399 | @code{stmnt}. | |
4400 | ||
4401 | To prevent an outpouring of error messages, the parser will output no error | |
4402 | message for another syntax error that happens shortly after the first; only | |
4403 | after three consecutive input tokens have been successfully shifted will | |
4404 | error messages resume. | |
4405 | ||
4406 | Note that rules which accept the @code{error} token may have actions, just | |
4407 | as any other rules can. | |
4408 | ||
4409 | @findex yyerrok | |
4410 | You can make error messages resume immediately by using the macro | |
4411 | @code{yyerrok} in an action. If you do this in the error rule's action, no | |
4412 | error messages will be suppressed. This macro requires no arguments; | |
4413 | @samp{yyerrok;} is a valid C statement. | |
4414 | ||
4415 | @findex yyclearin | |
4416 | The previous look-ahead token is reanalyzed immediately after an error. If | |
4417 | this is unacceptable, then the macro @code{yyclearin} may be used to clear | |
4418 | this token. Write the statement @samp{yyclearin;} in the error rule's | |
4419 | action. | |
4420 | ||
4421 | For example, suppose that on a parse error, an error handling routine is | |
4422 | called that advances the input stream to some point where parsing should | |
4423 | once again commence. The next symbol returned by the lexical scanner is | |
4424 | probably correct. The previous look-ahead token ought to be discarded | |
4425 | with @samp{yyclearin;}. | |
4426 | ||
4427 | @vindex YYRECOVERING | |
4428 | The macro @code{YYRECOVERING} stands for an expression that has the | |
4429 | value 1 when the parser is recovering from a syntax error, and 0 the | |
4430 | rest of the time. A value of 1 indicates that error messages are | |
4431 | currently suppressed for new syntax errors. | |
4432 | ||
4433 | @node Context Dependency, Debugging, Error Recovery, Top | |
4434 | @chapter Handling Context Dependencies | |
4435 | ||
4436 | The Bison paradigm is to parse tokens first, then group them into larger | |
4437 | syntactic units. In many languages, the meaning of a token is affected by | |
4438 | its context. Although this violates the Bison paradigm, certain techniques | |
4439 | (known as @dfn{kludges}) may enable you to write Bison parsers for such | |
4440 | languages. | |
4441 | ||
4442 | @menu | |
4443 | * Semantic Tokens:: Token parsing can depend on the semantic context. | |
4444 | * Lexical Tie-ins:: Token parsing can depend on the syntactic context. | |
4445 | * Tie-in Recovery:: Lexical tie-ins have implications for how | |
4446 | error recovery rules must be written. | |
4447 | @end menu | |
4448 | ||
4449 | (Actually, ``kludge'' means any technique that gets its job done but is | |
4450 | neither clean nor robust.) | |
4451 | ||
4452 | @node Semantic Tokens, Lexical Tie-ins, , Context Dependency | |
4453 | @section Semantic Info in Token Types | |
4454 | ||
4455 | The C language has a context dependency: the way an identifier is used | |
4456 | depends on what its current meaning is. For example, consider this: | |
4457 | ||
4458 | @example | |
4459 | foo (x); | |
4460 | @end example | |
4461 | ||
4462 | This looks like a function call statement, but if @code{foo} is a typedef | |
4463 | name, then this is actually a declaration of @code{x}. How can a Bison | |
4464 | parser for C decide how to parse this input? | |
4465 | ||
4466 | The method used in GNU C is to have two different token types, | |
4467 | @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an | |
4468 | identifier, it looks up the current declaration of the identifier in order | |
4469 | to decide which token type to return: @code{TYPENAME} if the identifier is | |
4470 | declared as a typedef, @code{IDENTIFIER} otherwise. | |
4471 | ||
4472 | The grammar rules can then express the context dependency by the choice of | |
4473 | token type to recognize. @code{IDENTIFIER} is accepted as an expression, | |
4474 | but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but | |
4475 | @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier | |
4476 | is @emph{not} significant, such as in declarations that can shadow a | |
4477 | typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is | |
4478 | accepted---there is one rule for each of the two token types. | |
4479 | ||
4480 | This technique is simple to use if the decision of which kinds of | |
4481 | identifiers to allow is made at a place close to where the identifier is | |
4482 | parsed. But in C this is not always so: C allows a declaration to | |
4483 | redeclare a typedef name provided an explicit type has been specified | |
4484 | earlier: | |
4485 | ||
4486 | @example | |
4487 | typedef int foo, bar, lose; | |
4488 | static foo (bar); /* @r{redeclare @code{bar} as static variable} */ | |
4489 | static int foo (lose); /* @r{redeclare @code{foo} as function} */ | |
4490 | @end example | |
4491 | ||
4492 | Unfortunately, the name being declared is separated from the declaration | |
4493 | construct itself by a complicated syntactic structure---the ``declarator''. | |
4494 | ||
9ecbd125 | 4495 | As a result, part of the Bison parser for C needs to be duplicated, with |
14ded682 AD |
4496 | all the nonterminal names changed: once for parsing a declaration in |
4497 | which a typedef name can be redefined, and once for parsing a | |
4498 | declaration in which that can't be done. Here is a part of the | |
4499 | duplication, with actions omitted for brevity: | |
bfa74976 RS |
4500 | |
4501 | @example | |
4502 | initdcl: | |
4503 | declarator maybeasm '=' | |
4504 | init | |
4505 | | declarator maybeasm | |
4506 | ; | |
4507 | ||
4508 | notype_initdcl: | |
4509 | notype_declarator maybeasm '=' | |
4510 | init | |
4511 | | notype_declarator maybeasm | |
4512 | ; | |
4513 | @end example | |
4514 | ||
4515 | @noindent | |
4516 | Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl} | |
4517 | cannot. The distinction between @code{declarator} and | |
4518 | @code{notype_declarator} is the same sort of thing. | |
4519 | ||
4520 | There is some similarity between this technique and a lexical tie-in | |
4521 | (described next), in that information which alters the lexical analysis is | |
4522 | changed during parsing by other parts of the program. The difference is | |
4523 | here the information is global, and is used for other purposes in the | |
4524 | program. A true lexical tie-in has a special-purpose flag controlled by | |
4525 | the syntactic context. | |
4526 | ||
4527 | @node Lexical Tie-ins, Tie-in Recovery, Semantic Tokens, Context Dependency | |
4528 | @section Lexical Tie-ins | |
4529 | @cindex lexical tie-in | |
4530 | ||
4531 | One way to handle context-dependency is the @dfn{lexical tie-in}: a flag | |
4532 | which is set by Bison actions, whose purpose is to alter the way tokens are | |
4533 | parsed. | |
4534 | ||
4535 | For example, suppose we have a language vaguely like C, but with a special | |
4536 | construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes | |
4537 | an expression in parentheses in which all integers are hexadecimal. In | |
4538 | particular, the token @samp{a1b} must be treated as an integer rather than | |
4539 | as an identifier if it appears in that context. Here is how you can do it: | |
4540 | ||
4541 | @example | |
4542 | @group | |
4543 | %@{ | |
4544 | int hexflag; | |
4545 | %@} | |
4546 | %% | |
4547 | @dots{} | |
4548 | @end group | |
4549 | @group | |
4550 | expr: IDENTIFIER | |
4551 | | constant | |
4552 | | HEX '(' | |
4553 | @{ hexflag = 1; @} | |
4554 | expr ')' | |
4555 | @{ hexflag = 0; | |
4556 | $$ = $4; @} | |
4557 | | expr '+' expr | |
4558 | @{ $$ = make_sum ($1, $3); @} | |
4559 | @dots{} | |
4560 | ; | |
4561 | @end group | |
4562 | ||
4563 | @group | |
4564 | constant: | |
4565 | INTEGER | |
4566 | | STRING | |
4567 | ; | |
4568 | @end group | |
4569 | @end example | |
4570 | ||
4571 | @noindent | |
4572 | Here we assume that @code{yylex} looks at the value of @code{hexflag}; when | |
4573 | it is nonzero, all integers are parsed in hexadecimal, and tokens starting | |
4574 | with letters are parsed as integers if possible. | |
4575 | ||
4576 | The declaration of @code{hexflag} shown in the C declarations section of | |
13863333 | 4577 | the parser file is needed to make it accessible to the actions |
bfa74976 RS |
4578 | (@pxref{C Declarations, ,The C Declarations Section}). You must also write the code in @code{yylex} |
4579 | to obey the flag. | |
4580 | ||
4581 | @node Tie-in Recovery, , Lexical Tie-ins, Context Dependency | |
4582 | @section Lexical Tie-ins and Error Recovery | |
4583 | ||
4584 | Lexical tie-ins make strict demands on any error recovery rules you have. | |
4585 | @xref{Error Recovery}. | |
4586 | ||
4587 | The reason for this is that the purpose of an error recovery rule is to | |
4588 | abort the parsing of one construct and resume in some larger construct. | |
4589 | For example, in C-like languages, a typical error recovery rule is to skip | |
4590 | tokens until the next semicolon, and then start a new statement, like this: | |
4591 | ||
4592 | @example | |
4593 | stmt: expr ';' | |
4594 | | IF '(' expr ')' stmt @{ @dots{} @} | |
4595 | @dots{} | |
4596 | error ';' | |
4597 | @{ hexflag = 0; @} | |
4598 | ; | |
4599 | @end example | |
4600 | ||
4601 | If there is a syntax error in the middle of a @samp{hex (@var{expr})} | |
4602 | construct, this error rule will apply, and then the action for the | |
4603 | completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would | |
4604 | remain set for the entire rest of the input, or until the next @code{hex} | |
4605 | keyword, causing identifiers to be misinterpreted as integers. | |
4606 | ||
4607 | To avoid this problem the error recovery rule itself clears @code{hexflag}. | |
4608 | ||
4609 | There may also be an error recovery rule that works within expressions. | |
4610 | For example, there could be a rule which applies within parentheses | |
4611 | and skips to the close-parenthesis: | |
4612 | ||
4613 | @example | |
4614 | @group | |
4615 | expr: @dots{} | |
4616 | | '(' expr ')' | |
4617 | @{ $$ = $2; @} | |
4618 | | '(' error ')' | |
4619 | @dots{} | |
4620 | @end group | |
4621 | @end example | |
4622 | ||
4623 | If this rule acts within the @code{hex} construct, it is not going to abort | |
4624 | that construct (since it applies to an inner level of parentheses within | |
4625 | the construct). Therefore, it should not clear the flag: the rest of | |
4626 | the @code{hex} construct should be parsed with the flag still in effect. | |
4627 | ||
4628 | What if there is an error recovery rule which might abort out of the | |
4629 | @code{hex} construct or might not, depending on circumstances? There is no | |
4630 | way you can write the action to determine whether a @code{hex} construct is | |
4631 | being aborted or not. So if you are using a lexical tie-in, you had better | |
4632 | make sure your error recovery rules are not of this kind. Each rule must | |
4633 | be such that you can be sure that it always will, or always won't, have to | |
4634 | clear the flag. | |
4635 | ||
4636 | @node Debugging, Invocation, Context Dependency, Top | |
4637 | @chapter Debugging Your Parser | |
4638 | @findex YYDEBUG | |
4639 | @findex yydebug | |
4640 | @cindex debugging | |
4641 | @cindex tracing the parser | |
4642 | ||
4643 | If a Bison grammar compiles properly but doesn't do what you want when it | |
4644 | runs, the @code{yydebug} parser-trace feature can help you figure out why. | |
4645 | ||
4646 | To enable compilation of trace facilities, you must define the macro | |
4647 | @code{YYDEBUG} when you compile the parser. You could use | |
4648 | @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define | |
13863333 | 4649 | YYDEBUG 1} in the C declarations section of the grammar file |
bfa74976 RS |
4650 | (@pxref{C Declarations, ,The C Declarations Section}). Alternatively, use the @samp{-t} option when |
4651 | you run Bison (@pxref{Invocation, ,Invoking Bison}). We always define @code{YYDEBUG} so that | |
4652 | debugging is always possible. | |
4653 | ||
4654 | The trace facility uses @code{stderr}, so you must add @w{@code{#include | |
4655 | <stdio.h>}} to the C declarations section unless it is already there. | |
4656 | ||
4657 | Once you have compiled the program with trace facilities, the way to | |
4658 | request a trace is to store a nonzero value in the variable @code{yydebug}. | |
4659 | You can do this by making the C code do it (in @code{main}, perhaps), or | |
4660 | you can alter the value with a C debugger. | |
4661 | ||
4662 | Each step taken by the parser when @code{yydebug} is nonzero produces a | |
4663 | line or two of trace information, written on @code{stderr}. The trace | |
4664 | messages tell you these things: | |
4665 | ||
4666 | @itemize @bullet | |
4667 | @item | |
4668 | Each time the parser calls @code{yylex}, what kind of token was read. | |
4669 | ||
4670 | @item | |
4671 | Each time a token is shifted, the depth and complete contents of the | |
4672 | state stack (@pxref{Parser States}). | |
4673 | ||
4674 | @item | |
4675 | Each time a rule is reduced, which rule it is, and the complete contents | |
4676 | of the state stack afterward. | |
4677 | @end itemize | |
4678 | ||
4679 | To make sense of this information, it helps to refer to the listing file | |
4680 | produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking Bison}). This file | |
4681 | shows the meaning of each state in terms of positions in various rules, and | |
4682 | also what each state will do with each possible input token. As you read | |
4683 | the successive trace messages, you can see that the parser is functioning | |
4684 | according to its specification in the listing file. Eventually you will | |
4685 | arrive at the place where something undesirable happens, and you will see | |
4686 | which parts of the grammar are to blame. | |
4687 | ||
4688 | The parser file is a C program and you can use C debuggers on it, but it's | |
4689 | not easy to interpret what it is doing. The parser function is a | |
4690 | finite-state machine interpreter, and aside from the actions it executes | |
4691 | the same code over and over. Only the values of variables show where in | |
4692 | the grammar it is working. | |
4693 | ||
4694 | @findex YYPRINT | |
4695 | The debugging information normally gives the token type of each token | |
4696 | read, but not its semantic value. You can optionally define a macro | |
4697 | named @code{YYPRINT} to provide a way to print the value. If you define | |
4698 | @code{YYPRINT}, it should take three arguments. The parser will pass a | |
4699 | standard I/O stream, the numeric code for the token type, and the token | |
4700 | value (from @code{yylval}). | |
4701 | ||
4702 | Here is an example of @code{YYPRINT} suitable for the multi-function | |
4703 | calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}): | |
4704 | ||
4705 | @smallexample | |
4706 | #define YYPRINT(file, type, value) yyprint (file, type, value) | |
4707 | ||
4708 | static void | |
13863333 | 4709 | yyprint (FILE *file, int type, YYSTYPE value) |
bfa74976 RS |
4710 | @{ |
4711 | if (type == VAR) | |
4712 | fprintf (file, " %s", value.tptr->name); | |
4713 | else if (type == NUM) | |
4714 | fprintf (file, " %d", value.val); | |
4715 | @} | |
4716 | @end smallexample | |
4717 | ||
4718 | @node Invocation, Table of Symbols, Debugging, Top | |
4719 | @chapter Invoking Bison | |
4720 | @cindex invoking Bison | |
4721 | @cindex Bison invocation | |
4722 | @cindex options for invoking Bison | |
4723 | ||
4724 | The usual way to invoke Bison is as follows: | |
4725 | ||
4726 | @example | |
4727 | bison @var{infile} | |
4728 | @end example | |
4729 | ||
4730 | Here @var{infile} is the grammar file name, which usually ends in | |
4731 | @samp{.y}. The parser file's name is made by replacing the @samp{.y} | |
4732 | with @samp{.tab.c}. Thus, the @samp{bison foo.y} filename yields | |
4733 | @file{foo.tab.c}, and the @samp{bison hack/foo.y} filename yields | |
234a3be3 AD |
4734 | @file{hack/foo.tab.c}. It's is also possible, in case you are writting |
4735 | C++ code instead of C in your grammar file, to name it @file{foo.ypp} | |
4736 | or @file{foo.y++}. Then, the output files will take an extention like | |
4737 | the given one as input (repectively @file{foo.tab.cpp} and @file{foo.tab.c++}). | |
4738 | This feature takes effect with all options that manipulate filenames like | |
4739 | @samp{-o} or @samp{-d}. | |
4740 | ||
4741 | For example : | |
4742 | ||
4743 | @example | |
4744 | bison -d @var{infile.yxx} | |
4745 | @end example | |
84163231 | 4746 | @noindent |
234a3be3 AD |
4747 | will produce @file{infile.tab.cxx} and @file{infile.tab.hxx}. and |
4748 | ||
4749 | @example | |
4750 | bison -d @var{infile.y} -o @var{output.c++} | |
4751 | @end example | |
84163231 | 4752 | @noindent |
234a3be3 AD |
4753 | will produce @file{output.c++} and @file{outfile.h++}. |
4754 | ||
bfa74976 RS |
4755 | |
4756 | @menu | |
13863333 | 4757 | * Bison Options:: All the options described in detail, |
bfa74976 | 4758 | in alphabetical order by short options. |
9ecbd125 | 4759 | * Environment Variables:: Variables which affect Bison execution. |
bfa74976 RS |
4760 | * Option Cross Key:: Alphabetical list of long options. |
4761 | * VMS Invocation:: Bison command syntax on VMS. | |
4762 | @end menu | |
4763 | ||
9ecbd125 | 4764 | @node Bison Options, Environment Variables, , Invocation |
bfa74976 RS |
4765 | @section Bison Options |
4766 | ||
4767 | Bison supports both traditional single-letter options and mnemonic long | |
4768 | option names. Long option names are indicated with @samp{--} instead of | |
4769 | @samp{-}. Abbreviations for option names are allowed as long as they | |
4770 | are unique. When a long option takes an argument, like | |
4771 | @samp{--file-prefix}, connect the option name and the argument with | |
4772 | @samp{=}. | |
4773 | ||
4774 | Here is a list of options that can be used with Bison, alphabetized by | |
4775 | short option. It is followed by a cross key alphabetized by long | |
4776 | option. | |
4777 | ||
89cab50d AD |
4778 | @c Please, keep this ordered as in `bison --help'. |
4779 | @noindent | |
4780 | Operations modes: | |
4781 | @table @option | |
4782 | @item -h | |
4783 | @itemx --help | |
4784 | Print a summary of the command-line options to Bison and exit. | |
bfa74976 | 4785 | |
89cab50d AD |
4786 | @item -V |
4787 | @itemx --version | |
4788 | Print the version number of Bison and exit. | |
bfa74976 | 4789 | |
89cab50d AD |
4790 | @need 1750 |
4791 | @item -y | |
4792 | @itemx --yacc | |
4793 | @itemx --fixed-output-files | |
4794 | Equivalent to @samp{-o y.tab.c}; the parser output file is called | |
4795 | @file{y.tab.c}, and the other outputs are called @file{y.output} and | |
4796 | @file{y.tab.h}. The purpose of this option is to imitate Yacc's output | |
4797 | file name conventions. Thus, the following shell script can substitute | |
4798 | for Yacc:@refill | |
bfa74976 | 4799 | |
89cab50d AD |
4800 | @example |
4801 | bison -y $* | |
4802 | @end example | |
4803 | @end table | |
4804 | ||
4805 | @noindent | |
4806 | Tuning the parser: | |
4807 | ||
4808 | @table @option | |
cd5bd6ac AD |
4809 | @item -S @var{file} |
4810 | @itemx --skeleton=@var{file} | |
4811 | Specify the skeleton to use. You probably don't need this option unless | |
4812 | you are developing Bison. | |
4813 | ||
89cab50d AD |
4814 | @item -t |
4815 | @itemx --debug | |
6deb4447 AD |
4816 | Output a definition of the macro @code{YYDEBUG} into the parser file, so |
4817 | that the debugging facilities are compiled. @xref{Debugging, ,Debugging | |
4818 | Your Parser}. | |
89cab50d AD |
4819 | |
4820 | @item --locations | |
4821 | Pretend that @code{%locactions} was specified. @xref{Decl Summary}. | |
4822 | ||
4823 | @item -p @var{prefix} | |
4824 | @itemx --name-prefix=@var{prefix} | |
4825 | Rename the external symbols used in the parser so that they start with | |
4826 | @var{prefix} instead of @samp{yy}. The precise list of symbols renamed | |
4827 | is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yynerrs}, | |
4828 | @code{yylval}, @code{yychar} and @code{yydebug}. | |
4829 | ||
4830 | For example, if you use @samp{-p c}, the names become @code{cparse}, | |
4831 | @code{clex}, and so on. | |
4832 | ||
4833 | @xref{Multiple Parsers, ,Multiple Parsers in the Same Program}. | |
bfa74976 RS |
4834 | |
4835 | @item -l | |
4836 | @itemx --no-lines | |
4837 | Don't put any @code{#line} preprocessor commands in the parser file. | |
4838 | Ordinarily Bison puts them in the parser file so that the C compiler | |
4839 | and debuggers will associate errors with your source file, the | |
4840 | grammar file. This option causes them to associate errors with the | |
95e742f7 | 4841 | parser file, treating it as an independent source file in its own right. |
bfa74976 | 4842 | |
931c7513 RS |
4843 | @item -n |
4844 | @itemx --no-parser | |
6deb4447 | 4845 | Pretend that @code{%no_parser} was specified. @xref{Decl Summary}. |
931c7513 | 4846 | |
89cab50d AD |
4847 | @item -k |
4848 | @itemx --token-table | |
4849 | Pretend that @code{%token_table} was specified. @xref{Decl Summary}. | |
4850 | @end table | |
bfa74976 | 4851 | |
89cab50d AD |
4852 | @noindent |
4853 | Adjust the output: | |
bfa74976 | 4854 | |
89cab50d AD |
4855 | @table @option |
4856 | @item -d | |
4857 | @itemx --defines | |
6deb4447 AD |
4858 | Pretend that @code{%verbose} was specified, i.e., write an extra output |
4859 | file containing macro definitions for the token type names defined in | |
4860 | the grammar and the semantic value type @code{YYSTYPE}, as well as a few | |
4861 | @code{extern} variable declarations. @xref{Decl Summary}. | |
931c7513 | 4862 | |
89cab50d AD |
4863 | @item -b @var{file-prefix} |
4864 | @itemx --file-prefix=@var{prefix} | |
4865 | Specify a prefix to use for all Bison output file names. The names are | |
4866 | chosen as if the input file were named @file{@var{prefix}.c}. | |
bfa74976 RS |
4867 | |
4868 | @item -v | |
4869 | @itemx --verbose | |
6deb4447 AD |
4870 | Pretend that @code{%verbose} was specified, i.e, write an extra output |
4871 | file containing verbose descriptions of the grammar and | |
4872 | parser. @xref{Decl Summary}, for more. | |
bfa74976 | 4873 | |
89cab50d AD |
4874 | @item -o @var{outfile} |
4875 | @itemx --output-file=@var{outfile} | |
4876 | Specify the name @var{outfile} for the parser file. | |
bfa74976 | 4877 | |
89cab50d AD |
4878 | The other output files' names are constructed from @var{outfile} |
4879 | as described under the @samp{-v} and @samp{-d} options. | |
bfa74976 RS |
4880 | @end table |
4881 | ||
9ecbd125 JT |
4882 | @node Environment Variables, Option Cross Key, Bison Options, Invocation |
4883 | @section Environment Variables | |
4884 | @cindex environment variables | |
4885 | @cindex BISON_HAIRY | |
4886 | @cindex BISON_SIMPLE | |
4887 | ||
4888 | Here is a list of environment variables which affect the way Bison | |
4889 | runs. | |
4890 | ||
4891 | @table @samp | |
4892 | @item BISON_SIMPLE | |
4893 | @itemx BISON_HAIRY | |
4894 | Much of the parser generated by Bison is copied verbatim from a file | |
4895 | called @file{bison.simple}. If Bison cannot find that file, or if you | |
4896 | would like to direct Bison to use a different copy, setting the | |
4897 | environment variable @code{BISON_SIMPLE} to the path of the file will | |
4898 | cause Bison to use that copy instead. | |
4899 | ||
13863333 | 4900 | When the @samp{%semantic_parser} declaration is used, Bison copies from |
9ecbd125 JT |
4901 | a file called @file{bison.hairy} instead. The location of this file can |
4902 | also be specified or overridden in a similar fashion, with the | |
4903 | @code{BISON_HAIRY} environment variable. | |
4904 | ||
4905 | @end table | |
4906 | ||
4907 | @node Option Cross Key, VMS Invocation, Environment Variables, Invocation | |
bfa74976 RS |
4908 | @section Option Cross Key |
4909 | ||
4910 | Here is a list of options, alphabetized by long option, to help you find | |
4911 | the corresponding short option. | |
4912 | ||
4913 | @tex | |
4914 | \def\leaderfill{\leaders\hbox to 1em{\hss.\hss}\hfill} | |
4915 | ||
4916 | {\tt | |
4917 | \line{ --debug \leaderfill -t} | |
4918 | \line{ --defines \leaderfill -d} | |
4919 | \line{ --file-prefix \leaderfill -b} | |
4920 | \line{ --fixed-output-files \leaderfill -y} | |
ff51d159 | 4921 | \line{ --help \leaderfill -h} |
bfa74976 RS |
4922 | \line{ --name-prefix \leaderfill -p} |
4923 | \line{ --no-lines \leaderfill -l} | |
931c7513 | 4924 | \line{ --no-parser \leaderfill -n} |
bfa74976 | 4925 | \line{ --output-file \leaderfill -o} |
931c7513 | 4926 | \line{ --token-table \leaderfill -k} |
bfa74976 RS |
4927 | \line{ --verbose \leaderfill -v} |
4928 | \line{ --version \leaderfill -V} | |
4929 | \line{ --yacc \leaderfill -y} | |
4930 | } | |
4931 | @end tex | |
4932 | ||
4933 | @ifinfo | |
4934 | @example | |
4935 | --debug -t | |
4936 | --defines -d | |
4937 | --file-prefix=@var{prefix} -b @var{file-prefix} | |
4938 | --fixed-output-files --yacc -y | |
ff51d159 | 4939 | --help -h |
931c7513 | 4940 | --name-prefix=@var{prefix} -p @var{name-prefix} |
bfa74976 | 4941 | --no-lines -l |
931c7513 | 4942 | --no-parser -n |
bfa74976 | 4943 | --output-file=@var{outfile} -o @var{outfile} |
931c7513 | 4944 | --token-table -k |
bfa74976 RS |
4945 | --verbose -v |
4946 | --version -V | |
4947 | @end example | |
4948 | @end ifinfo | |
4949 | ||
4950 | @node VMS Invocation, , Option Cross Key, Invocation | |
4951 | @section Invoking Bison under VMS | |
4952 | @cindex invoking Bison under VMS | |
4953 | @cindex VMS | |
4954 | ||
4955 | The command line syntax for Bison on VMS is a variant of the usual | |
4956 | Bison command syntax---adapted to fit VMS conventions. | |
4957 | ||
4958 | To find the VMS equivalent for any Bison option, start with the long | |
4959 | option, and substitute a @samp{/} for the leading @samp{--}, and | |
4960 | substitute a @samp{_} for each @samp{-} in the name of the long option. | |
4961 | For example, the following invocation under VMS: | |
4962 | ||
4963 | @example | |
4964 | bison /debug/name_prefix=bar foo.y | |
4965 | @end example | |
4966 | ||
4967 | @noindent | |
4968 | is equivalent to the following command under POSIX. | |
4969 | ||
4970 | @example | |
4971 | bison --debug --name-prefix=bar foo.y | |
4972 | @end example | |
4973 | ||
4974 | The VMS file system does not permit filenames such as | |
4975 | @file{foo.tab.c}. In the above example, the output file | |
4976 | would instead be named @file{foo_tab.c}. | |
4977 | ||
4978 | @node Table of Symbols, Glossary, Invocation, Top | |
4979 | @appendix Bison Symbols | |
4980 | @cindex Bison symbols, table of | |
4981 | @cindex symbols in Bison, table of | |
4982 | ||
4983 | @table @code | |
4984 | @item error | |
4985 | A token name reserved for error recovery. This token may be used in | |
4986 | grammar rules so as to allow the Bison parser to recognize an error in | |
4987 | the grammar without halting the process. In effect, a sentence | |
4988 | containing an error may be recognized as valid. On a parse error, the | |
4989 | token @code{error} becomes the current look-ahead token. Actions | |
4990 | corresponding to @code{error} are then executed, and the look-ahead | |
4991 | token is reset to the token that originally caused the violation. | |
4992 | @xref{Error Recovery}. | |
4993 | ||
4994 | @item YYABORT | |
4995 | Macro to pretend that an unrecoverable syntax error has occurred, by | |
4996 | making @code{yyparse} return 1 immediately. The error reporting | |
ceed8467 AD |
4997 | function @code{yyerror} is not called. @xref{Parser Function, ,The |
4998 | Parser Function @code{yyparse}}. | |
bfa74976 RS |
4999 | |
5000 | @item YYACCEPT | |
5001 | Macro to pretend that a complete utterance of the language has been | |
13863333 | 5002 | read, by making @code{yyparse} return 0 immediately. |
bfa74976 RS |
5003 | @xref{Parser Function, ,The Parser Function @code{yyparse}}. |
5004 | ||
5005 | @item YYBACKUP | |
5006 | Macro to discard a value from the parser stack and fake a look-ahead | |
5007 | token. @xref{Action Features, ,Special Features for Use in Actions}. | |
5008 | ||
5009 | @item YYERROR | |
5010 | Macro to pretend that a syntax error has just been detected: call | |
5011 | @code{yyerror} and then perform normal error recovery if possible | |
5012 | (@pxref{Error Recovery}), or (if recovery is impossible) make | |
5013 | @code{yyparse} return 1. @xref{Error Recovery}. | |
5014 | ||
5015 | @item YYERROR_VERBOSE | |
5016 | Macro that you define with @code{#define} in the Bison declarations | |
5017 | section to request verbose, specific error message strings when | |
5018 | @code{yyerror} is called. | |
5019 | ||
5020 | @item YYINITDEPTH | |
5021 | Macro for specifying the initial size of the parser stack. | |
5022 | @xref{Stack Overflow}. | |
5023 | ||
c656404a RS |
5024 | @item YYLEX_PARAM |
5025 | Macro for specifying an extra argument (or list of extra arguments) for | |
5026 | @code{yyparse} to pass to @code{yylex}. @xref{Pure Calling,, Calling | |
5027 | Conventions for Pure Parsers}. | |
5028 | ||
bfa74976 RS |
5029 | @item YYLTYPE |
5030 | Macro for the data type of @code{yylloc}; a structure with four | |
847bf1f5 | 5031 | members. @xref{Location Type, , Data Types of Locations}. |
bfa74976 | 5032 | |
931c7513 RS |
5033 | @item yyltype |
5034 | Default value for YYLTYPE. | |
5035 | ||
bfa74976 RS |
5036 | @item YYMAXDEPTH |
5037 | Macro for specifying the maximum size of the parser stack. | |
5038 | @xref{Stack Overflow}. | |
5039 | ||
c656404a RS |
5040 | @item YYPARSE_PARAM |
5041 | Macro for specifying the name of a parameter that @code{yyparse} should | |
5042 | accept. @xref{Pure Calling,, Calling Conventions for Pure Parsers}. | |
5043 | ||
bfa74976 RS |
5044 | @item YYRECOVERING |
5045 | Macro whose value indicates whether the parser is recovering from a | |
5046 | syntax error. @xref{Action Features, ,Special Features for Use in Actions}. | |
5047 | ||
5048 | @item YYSTYPE | |
5049 | Macro for the data type of semantic values; @code{int} by default. | |
5050 | @xref{Value Type, ,Data Types of Semantic Values}. | |
5051 | ||
5052 | @item yychar | |
13863333 AD |
5053 | External integer variable that contains the integer value of the current |
5054 | look-ahead token. (In a pure parser, it is a local variable within | |
5055 | @code{yyparse}.) Error-recovery rule actions may examine this variable. | |
5056 | @xref{Action Features, ,Special Features for Use in Actions}. | |
bfa74976 RS |
5057 | |
5058 | @item yyclearin | |
5059 | Macro used in error-recovery rule actions. It clears the previous | |
5060 | look-ahead token. @xref{Error Recovery}. | |
5061 | ||
5062 | @item yydebug | |
5063 | External integer variable set to zero by default. If @code{yydebug} | |
5064 | is given a nonzero value, the parser will output information on input | |
5065 | symbols and parser action. @xref{Debugging, ,Debugging Your Parser}. | |
5066 | ||
5067 | @item yyerrok | |
5068 | Macro to cause parser to recover immediately to its normal mode | |
5069 | after a parse error. @xref{Error Recovery}. | |
5070 | ||
5071 | @item yyerror | |
5072 | User-supplied function to be called by @code{yyparse} on error. The | |
5073 | function receives one argument, a pointer to a character string | |
13863333 AD |
5074 | containing an error message. @xref{Error Reporting, ,The Error |
5075 | Reporting Function @code{yyerror}}. | |
bfa74976 RS |
5076 | |
5077 | @item yylex | |
5078 | User-supplied lexical analyzer function, called with no arguments | |
5079 | to get the next token. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}. | |
5080 | ||
5081 | @item yylval | |
5082 | External variable in which @code{yylex} should place the semantic | |
5083 | value associated with a token. (In a pure parser, it is a local | |
5084 | variable within @code{yyparse}, and its address is passed to | |
5085 | @code{yylex}.) @xref{Token Values, ,Semantic Values of Tokens}. | |
5086 | ||
5087 | @item yylloc | |
13863333 AD |
5088 | External variable in which @code{yylex} should place the line and column |
5089 | numbers associated with a token. (In a pure parser, it is a local | |
5090 | variable within @code{yyparse}, and its address is passed to | |
bfa74976 | 5091 | @code{yylex}.) You can ignore this variable if you don't use the |
13863333 AD |
5092 | @samp{@@} feature in the grammar actions. @xref{Token Positions, |
5093 | ,Textual Positions of Tokens}. | |
bfa74976 RS |
5094 | |
5095 | @item yynerrs | |
13863333 AD |
5096 | Global variable which Bison increments each time there is a parse error. |
5097 | (In a pure parser, it is a local variable within @code{yyparse}.) | |
5098 | @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}. | |
bfa74976 RS |
5099 | |
5100 | @item yyparse | |
5101 | The parser function produced by Bison; call this function to start | |
5102 | parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}. | |
5103 | ||
6deb4447 AD |
5104 | @item %debug |
5105 | Equip the parser for debugging. @xref{Decl Summary}. | |
5106 | ||
5107 | @item %defines | |
5108 | Bison declaration to create a header file meant for the scanner. | |
5109 | @xref{Decl Summary}. | |
5110 | ||
bfa74976 RS |
5111 | @item %left |
5112 | Bison declaration to assign left associativity to token(s). | |
5113 | @xref{Precedence Decl, ,Operator Precedence}. | |
5114 | ||
931c7513 RS |
5115 | @item %no_lines |
5116 | Bison declaration to avoid generating @code{#line} directives in the | |
5117 | parser file. @xref{Decl Summary}. | |
5118 | ||
bfa74976 | 5119 | @item %nonassoc |
14ded682 | 5120 | Bison declaration to assign non-associativity to token(s). |
bfa74976 RS |
5121 | @xref{Precedence Decl, ,Operator Precedence}. |
5122 | ||
5123 | @item %prec | |
5124 | Bison declaration to assign a precedence to a specific rule. | |
5125 | @xref{Contextual Precedence, ,Context-Dependent Precedence}. | |
5126 | ||
5127 | @item %pure_parser | |
5128 | Bison declaration to request a pure (reentrant) parser. | |
5129 | @xref{Pure Decl, ,A Pure (Reentrant) Parser}. | |
5130 | ||
5131 | @item %right | |
5132 | Bison declaration to assign right associativity to token(s). | |
5133 | @xref{Precedence Decl, ,Operator Precedence}. | |
5134 | ||
5135 | @item %start | |
5136 | Bison declaration to specify the start symbol. @xref{Start Decl, ,The Start-Symbol}. | |
5137 | ||
5138 | @item %token | |
5139 | Bison declaration to declare token(s) without specifying precedence. | |
5140 | @xref{Token Decl, ,Token Type Names}. | |
5141 | ||
931c7513 RS |
5142 | @item %token_table |
5143 | Bison declaration to include a token name table in the parser file. | |
5144 | @xref{Decl Summary}. | |
5145 | ||
bfa74976 RS |
5146 | @item %type |
5147 | Bison declaration to declare nonterminals. @xref{Type Decl, ,Nonterminal Symbols}. | |
5148 | ||
5149 | @item %union | |
5150 | Bison declaration to specify several possible data types for semantic | |
5151 | values. @xref{Union Decl, ,The Collection of Value Types}. | |
5152 | @end table | |
5153 | ||
5154 | These are the punctuation and delimiters used in Bison input: | |
5155 | ||
5156 | @table @samp | |
5157 | @item %% | |
5158 | Delimiter used to separate the grammar rule section from the | |
5159 | Bison declarations section or the additional C code section. | |
5160 | @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}. | |
5161 | ||
5162 | @item %@{ %@} | |
89cab50d AD |
5163 | All code listed between @samp{%@{} and @samp{%@}} is copied directly to |
5164 | the output file uninterpreted. Such code forms the ``C declarations'' | |
5165 | section of the input file. @xref{Grammar Outline, ,Outline of a Bison | |
5166 | Grammar}. | |
bfa74976 RS |
5167 | |
5168 | @item /*@dots{}*/ | |
5169 | Comment delimiters, as in C. | |
5170 | ||
5171 | @item : | |
89cab50d AD |
5172 | Separates a rule's result from its components. @xref{Rules, ,Syntax of |
5173 | Grammar Rules}. | |
bfa74976 RS |
5174 | |
5175 | @item ; | |
5176 | Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}. | |
5177 | ||
5178 | @item | | |
5179 | Separates alternate rules for the same result nonterminal. | |
5180 | @xref{Rules, ,Syntax of Grammar Rules}. | |
5181 | @end table | |
5182 | ||
5183 | @node Glossary, Index, Table of Symbols, Top | |
5184 | @appendix Glossary | |
5185 | @cindex glossary | |
5186 | ||
5187 | @table @asis | |
5188 | @item Backus-Naur Form (BNF) | |
5189 | Formal method of specifying context-free grammars. BNF was first used | |
89cab50d AD |
5190 | in the @cite{ALGOL-60} report, 1963. @xref{Language and Grammar, |
5191 | ,Languages and Context-Free Grammars}. | |
bfa74976 RS |
5192 | |
5193 | @item Context-free grammars | |
5194 | Grammars specified as rules that can be applied regardless of context. | |
5195 | Thus, if there is a rule which says that an integer can be used as an | |
5196 | expression, integers are allowed @emph{anywhere} an expression is | |
89cab50d AD |
5197 | permitted. @xref{Language and Grammar, ,Languages and Context-Free |
5198 | Grammars}. | |
bfa74976 RS |
5199 | |
5200 | @item Dynamic allocation | |
5201 | Allocation of memory that occurs during execution, rather than at | |
5202 | compile time or on entry to a function. | |
5203 | ||
5204 | @item Empty string | |
5205 | Analogous to the empty set in set theory, the empty string is a | |
5206 | character string of length zero. | |
5207 | ||
5208 | @item Finite-state stack machine | |
5209 | A ``machine'' that has discrete states in which it is said to exist at | |
5210 | each instant in time. As input to the machine is processed, the | |
5211 | machine moves from state to state as specified by the logic of the | |
5212 | machine. In the case of the parser, the input is the language being | |
5213 | parsed, and the states correspond to various stages in the grammar | |
5214 | rules. @xref{Algorithm, ,The Bison Parser Algorithm }. | |
5215 | ||
5216 | @item Grouping | |
5217 | A language construct that is (in general) grammatically divisible; | |
13863333 | 5218 | for example, `expression' or `declaration' in C. |
bfa74976 RS |
5219 | @xref{Language and Grammar, ,Languages and Context-Free Grammars}. |
5220 | ||
5221 | @item Infix operator | |
5222 | An arithmetic operator that is placed between the operands on which it | |
5223 | performs some operation. | |
5224 | ||
5225 | @item Input stream | |
5226 | A continuous flow of data between devices or programs. | |
5227 | ||
5228 | @item Language construct | |
5229 | One of the typical usage schemas of the language. For example, one of | |
5230 | the constructs of the C language is the @code{if} statement. | |
5231 | @xref{Language and Grammar, ,Languages and Context-Free Grammars}. | |
5232 | ||
5233 | @item Left associativity | |
5234 | Operators having left associativity are analyzed from left to right: | |
5235 | @samp{a+b+c} first computes @samp{a+b} and then combines with | |
5236 | @samp{c}. @xref{Precedence, ,Operator Precedence}. | |
5237 | ||
5238 | @item Left recursion | |
89cab50d AD |
5239 | A rule whose result symbol is also its first component symbol; for |
5240 | example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive | |
5241 | Rules}. | |
bfa74976 RS |
5242 | |
5243 | @item Left-to-right parsing | |
5244 | Parsing a sentence of a language by analyzing it token by token from | |
5245 | left to right. @xref{Algorithm, ,The Bison Parser Algorithm }. | |
5246 | ||
5247 | @item Lexical analyzer (scanner) | |
5248 | A function that reads an input stream and returns tokens one by one. | |
5249 | @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}. | |
5250 | ||
5251 | @item Lexical tie-in | |
5252 | A flag, set by actions in the grammar rules, which alters the way | |
5253 | tokens are parsed. @xref{Lexical Tie-ins}. | |
5254 | ||
931c7513 | 5255 | @item Literal string token |
14ded682 | 5256 | A token which consists of two or more fixed characters. @xref{Symbols}. |
931c7513 | 5257 | |
bfa74976 | 5258 | @item Look-ahead token |
89cab50d AD |
5259 | A token already read but not yet shifted. @xref{Look-Ahead, ,Look-Ahead |
5260 | Tokens}. | |
bfa74976 RS |
5261 | |
5262 | @item LALR(1) | |
5263 | The class of context-free grammars that Bison (like most other parser | |
5264 | generators) can handle; a subset of LR(1). @xref{Mystery Conflicts, , | |
5265 | Mysterious Reduce/Reduce Conflicts}. | |
5266 | ||
5267 | @item LR(1) | |
5268 | The class of context-free grammars in which at most one token of | |
5269 | look-ahead is needed to disambiguate the parsing of any piece of input. | |
5270 | ||
5271 | @item Nonterminal symbol | |
5272 | A grammar symbol standing for a grammatical construct that can | |
5273 | be expressed through rules in terms of smaller constructs; in other | |
5274 | words, a construct that is not a token. @xref{Symbols}. | |
5275 | ||
5276 | @item Parse error | |
5277 | An error encountered during parsing of an input stream due to invalid | |
5278 | syntax. @xref{Error Recovery}. | |
5279 | ||
5280 | @item Parser | |
5281 | A function that recognizes valid sentences of a language by analyzing | |
5282 | the syntax structure of a set of tokens passed to it from a lexical | |
5283 | analyzer. | |
5284 | ||
5285 | @item Postfix operator | |
5286 | An arithmetic operator that is placed after the operands upon which it | |
5287 | performs some operation. | |
5288 | ||
5289 | @item Reduction | |
5290 | Replacing a string of nonterminals and/or terminals with a single | |
89cab50d AD |
5291 | nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison |
5292 | Parser Algorithm }. | |
bfa74976 RS |
5293 | |
5294 | @item Reentrant | |
5295 | A reentrant subprogram is a subprogram which can be in invoked any | |
5296 | number of times in parallel, without interference between the various | |
5297 | invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}. | |
5298 | ||
5299 | @item Reverse polish notation | |
5300 | A language in which all operators are postfix operators. | |
5301 | ||
5302 | @item Right recursion | |
89cab50d AD |
5303 | A rule whose result symbol is also its last component symbol; for |
5304 | example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive | |
5305 | Rules}. | |
bfa74976 RS |
5306 | |
5307 | @item Semantics | |
5308 | In computer languages, the semantics are specified by the actions | |
5309 | taken for each instance of the language, i.e., the meaning of | |
5310 | each statement. @xref{Semantics, ,Defining Language Semantics}. | |
5311 | ||
5312 | @item Shift | |
5313 | A parser is said to shift when it makes the choice of analyzing | |
5314 | further input from the stream rather than reducing immediately some | |
5315 | already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm }. | |
5316 | ||
5317 | @item Single-character literal | |
5318 | A single character that is recognized and interpreted as is. | |
5319 | @xref{Grammar in Bison, ,From Formal Rules to Bison Input}. | |
5320 | ||
5321 | @item Start symbol | |
5322 | The nonterminal symbol that stands for a complete valid utterance in | |
5323 | the language being parsed. The start symbol is usually listed as the | |
13863333 | 5324 | first nonterminal symbol in a language specification. |
bfa74976 RS |
5325 | @xref{Start Decl, ,The Start-Symbol}. |
5326 | ||
5327 | @item Symbol table | |
5328 | A data structure where symbol names and associated data are stored | |
5329 | during parsing to allow for recognition and use of existing | |
5330 | information in repeated uses of a symbol. @xref{Multi-function Calc}. | |
5331 | ||
5332 | @item Token | |
5333 | A basic, grammatically indivisible unit of a language. The symbol | |
5334 | that describes a token in the grammar is a terminal symbol. | |
5335 | The input of the Bison parser is a stream of tokens which comes from | |
5336 | the lexical analyzer. @xref{Symbols}. | |
5337 | ||
5338 | @item Terminal symbol | |
89cab50d AD |
5339 | A grammar symbol that has no rules in the grammar and therefore is |
5340 | grammatically indivisible. The piece of text it represents is a token. | |
5341 | @xref{Language and Grammar, ,Languages and Context-Free Grammars}. | |
bfa74976 RS |
5342 | @end table |
5343 | ||
5344 | @node Index, , Glossary, Top | |
5345 | @unnumbered Index | |
5346 | ||
5347 | @printindex cp | |
5348 | ||
bfa74976 | 5349 | @bye |