This manual is for @acronym{GNU} Bison (version @value{VERSION},
@value{UPDATED}), the @acronym{GNU} parser generator.
-Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
-1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 2003,
+1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
@quotation
Permission is granted to copy, distribute and/or modify this document
* Copying This Manual:: License for copying this manual.
* Index:: Cross-references to the text.
-@detailmenu --- The Detailed Node Listing ---
+@detailmenu
+ --- The Detailed Node Listing ---
The Concepts of Bison
a semantic value (the value of an integer,
the name of an identifier, etc.).
* Semantic Actions:: Each rule can have an action containing C code.
+* GLR Parsers:: Writing parsers for general context-free languages
+* Locations Overview:: Tracking Locations.
* Bison Parser:: What are Bison's input and output,
how is the output used?
* Stages:: Stages in writing and running Bison grammars.
Operator precedence is introduced.
* Simple Error Recovery:: Continuing after syntax errors.
* Location Tracking Calc:: Demonstrating the use of @@@var{n} and @@$.
-* Multi-function Calc:: Calculator with memory and trig functions.
- It uses multiple data-types for semantic values.
+* Multi-function Calc:: Calculator with memory and trig functions.
+ It uses multiple data-types for semantic values.
* Exercises:: Ideas for improving the multi-function calculator.
Reverse Polish Notation Calculator
* Rules:: How to write grammar rules.
* Recursion:: Writing recursive rules.
* Semantics:: Semantic values and actions.
+* Locations:: Locations and actions.
* Declarations:: All kinds of Bison declarations are described here.
* Multiple Parsers:: Putting more than one Bison parser in one program.
Outline of a Bison Grammar
-* Prologue:: Syntax and usage of the prologue (declarations section).
+* Prologue:: Syntax and usage of the prologue.
* Bison Declarations:: Syntax and usage of the Bison declarations section.
* Grammar Rules:: Syntax and usage of the grammar rules section.
-* Epilogue:: Syntax and usage of the epilogue (additional code section).
+* Epilogue:: Syntax and usage of the epilogue.
Defining Language Semantics
This says when, why and how to use the exceptional
action in the middle of a rule.
+Tracking Locations
+
+* Location Type:: Specifying a data type for locations.
+* Actions and Locations:: Using locations in actions.
+* Location Default Action:: Defining a general way to compute locations.
+
Bison Declarations
* Token Decl:: Declaring terminal symbols.
* Calling Convention:: How @code{yyparse} calls @code{yylex}.
* Token Values:: How @code{yylex} must return the semantic value
of the token it has read.
-* Token Positions:: How @code{yylex} must return the text position
+* Token Locations:: How @code{yylex} must return the text location
(line number, etc.) of the token, if the
- actions want that.
+ actions want that.
* Pure Calling:: How the calling convention differs
in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
* Tie-in Recovery:: Lexical tie-ins have implications for how
error recovery rules must be written.
-Understanding or Debugging Your Parser
+Debugging Your Parser
* Understanding:: Understanding the structure of your parser.
* Tracing:: Tracing the execution of your parser.
* Bison Options:: All the options described in detail,
in alphabetical order by short options.
* Option Cross Key:: Alphabetical list of long options.
+* Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
Frequently Asked Questions
* Parser Stack Overflow:: Breaking the Stack Limits
+* Strings are Destroyed:: @code{yylval} Loses Track of Strings
Copying This Manual
@cindex generalized @acronym{LR} (@acronym{GLR}) parsing
@cindex ambiguous grammars
@cindex non-deterministic parsing
-Parsers for @acronym{LALR}(1) grammars are @dfn{deterministic},
-meaning roughly that
-the next grammar rule to apply at any point in the input is uniquely
-determined by the preceding input and a fixed, finite portion (called
-a @dfn{look-ahead}) of the remaining input.
-A context-free grammar can be @dfn{ambiguous}, meaning that
-there are multiple ways to apply the grammar rules to get the some inputs.
-Even unambiguous grammars can be @dfn{non-deterministic}, meaning that no
-fixed look-ahead always suffices to determine the next grammar rule to apply.
-With the proper declarations, Bison is also able to parse these more general
-context-free grammars, using a technique known as @acronym{GLR} parsing (for
-Generalized @acronym{LR}). Bison's @acronym{GLR} parsers are able to
-handle any context-free
-grammar for which the number of possible parses of any given string
-is finite.
+
+Parsers for @acronym{LALR}(1) grammars are @dfn{deterministic}, meaning
+roughly that the next grammar rule to apply at any point in the input is
+uniquely determined by the preceding input and a fixed, finite portion
+(called a @dfn{look-ahead}) of the remaining input. A context-free
+grammar can be @dfn{ambiguous}, meaning that there are multiple ways to
+apply the grammar rules to get the some inputs. Even unambiguous
+grammars can be @dfn{non-deterministic}, meaning that no fixed
+look-ahead always suffices to determine the next grammar rule to apply.
+With the proper declarations, Bison is also able to parse these more
+general context-free grammars, using a technique known as @acronym{GLR}
+parsing (for Generalized @acronym{LR}). Bison's @acronym{GLR} parsers
+are able to handle any context-free grammar for which the number of
+possible parses of any given string is finite.
@cindex symbols (abstract)
@cindex token
@cindex syntactic grouping
@cindex grouping, syntactic
-In the formal grammatical rules for a language, each kind of syntactic unit
-or grouping is named by a @dfn{symbol}. Those which are built by grouping
-smaller constructs according to grammatical rules are called
+In the formal grammatical rules for a language, each kind of syntactic
+unit or grouping is named by a @dfn{symbol}. Those which are built by
+grouping smaller constructs according to grammatical rules are called
@dfn{nonterminal symbols}; those which can't be subdivided are called
@dfn{terminal symbols} or @dfn{token types}. We call a piece of input
corresponding to a single terminal symbol a @dfn{token}, and a piece
corresponding to a single nonterminal symbol a @dfn{grouping}.
We can use the C language as an example of what symbols, terminal and
-nonterminal, mean. The tokens of C are identifiers, constants (numeric and
-string), and the various keywords, arithmetic operators and punctuation
-marks. So the terminal symbols of a grammar for C include `identifier',
-`number', `string', plus one symbol for each keyword, operator or
-punctuation mark: `if', `return', `const', `static', `int', `char',
-`plus-sign', `open-brace', `close-brace', `comma' and many more. (These
-tokens can be subdivided into characters, but that is a matter of
+nonterminal, mean. The tokens of C are identifiers, constants (numeric
+and string), and the various keywords, arithmetic operators and
+punctuation marks. So the terminal symbols of a grammar for C include
+`identifier', `number', `string', plus one symbol for each keyword,
+operator or punctuation mark: `if', `return', `const', `static', `int',
+`char', `plus-sign', `open-brace', `close-brace', `comma' and many more.
+(These tokens can be subdivided into characters, but that is a matter of
lexicography, not grammar.)
Here is a simple C function subdivided into tokens:
@cindex conflicts
@cindex shift/reduce conflicts
-In some grammars, there will be cases where Bison's standard @acronym{LALR}(1)
-parsing algorithm cannot decide whether to apply a certain grammar rule
-at a given point. That is, it may not be able to decide (on the basis
-of the input read so far) which of two possible reductions (applications
-of a grammar rule) applies, or whether to apply a reduction or read more
-of the input and apply a reduction later in the input. These are known
-respectively as @dfn{reduce/reduce} conflicts (@pxref{Reduce/Reduce}),
-and @dfn{shift/reduce} conflicts (@pxref{Shift/Reduce}).
-
-To use a grammar that is not easily modified to be @acronym{LALR}(1), a more
-general parsing algorithm is sometimes necessary. If you include
+In some grammars, there will be cases where Bison's standard
+@acronym{LALR}(1) parsing algorithm cannot decide whether to apply a
+certain grammar rule at a given point. That is, it may not be able to
+decide (on the basis of the input read so far) which of two possible
+reductions (applications of a grammar rule) applies, or whether to apply
+a reduction or read more of the input and apply a reduction later in the
+input. These are known respectively as @dfn{reduce/reduce} conflicts
+(@pxref{Reduce/Reduce}), and @dfn{shift/reduce} conflicts
+(@pxref{Shift/Reduce}).
+
+To use a grammar that is not easily modified to be @acronym{LALR}(1), a
+more general parsing algorithm is sometimes necessary. If you include
@code{%glr-parser} among the Bison declarations in your file
-(@pxref{Grammar Outline}), the result will be a Generalized
-@acronym{LR} (@acronym{GLR})
-parser. These parsers handle Bison grammars that contain no unresolved
-conflicts (i.e., after applying precedence declarations) identically to
-@acronym{LALR}(1) parsers. However, when faced with unresolved
-shift/reduce and reduce/reduce conflicts, @acronym{GLR} parsers use
-the simple expedient of doing
-both, effectively cloning the parser to follow both possibilities. Each
-of the resulting parsers can again split, so that at any given time,
-there can be any number of possible parses being explored. The parsers
+(@pxref{Grammar Outline}), the result will be a Generalized @acronym{LR}
+(@acronym{GLR}) parser. These parsers handle Bison grammars that
+contain no unresolved conflicts (i.e., after applying precedence
+declarations) identically to @acronym{LALR}(1) parsers. However, when
+faced with unresolved shift/reduce and reduce/reduce conflicts,
+@acronym{GLR} parsers use the simple expedient of doing both,
+effectively cloning the parser to follow both possibilities. Each of
+the resulting parsers can again split, so that at any given time, there
+can be any number of possible parses being explored. The parsers
proceed in lockstep; that is, all of them consume (shift) a given input
symbol before any of them proceed to the next. Each of the cloned
parsers eventually meets one of two possible fates: either it runs into
@example
%@{
- #define YYSTYPE const char*
+ #include <stdio.h>
+ #define YYSTYPE char const *
+ int yylex (void);
+ void yyerror (char const *);
%@}
%token TYPENAME ID
and define the @code{stmtMerge} function as:
@example
-static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1)
+static YYSTYPE
+stmtMerge (YYSTYPE x0, YYSTYPE x1)
@{
printf ("<OR> ");
return "";
@example
%@{
- #define YYSTYPE const char*
+ #define YYSTYPE char const *
static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
%@}
@end example
"x" y z + T <init-declare> x T <cast> y z + = <OR>
@end example
+@sp 1
+
+@cindex @code{incline}
+@cindex @acronym{GLR} parsers and @code{inline}
+The @acronym{GLR} parsers require a compiler for @acronym{ISO} C89 or
+later. In addition, they use the @code{inline} keyword, which is not
+C89, but is C99 and is a common extension in pre-C99 compilers. It is
+up to the user of these parsers to handle
+portability issues. For instance, if using Autoconf and the Autoconf
+macro @code{AC_C_INLINE}, a mere
+
+@example
+%@{
+ #include <config.h>
+%@}
+@end example
+
+@noindent
+will suffice. Otherwise, we suggest
+
+@example
+%@{
+ #if __STDC_VERSION__ < 199901 && ! defined __GNUC__ && ! defined inline
+ #define inline
+ #endif
+%@}
+@end example
@node Locations Overview
@section Locations
@cindex location
-@cindex textual position
-@cindex position, textual
+@cindex textual location
+@cindex location, textual
Many applications, like interpreters or compilers, have to produce verbose
and useful error messages. To achieve this, one must be able to keep track of
-the @dfn{textual position}, or @dfn{location}, of each syntactic construct.
+the @dfn{textual location}, or @dfn{location}, of each syntactic construct.
Bison provides a mechanism for handling these locations.
Each token has a semantic value. In a similar fashion, each token has an
The prologue may define types and variables used in the actions. You can
also use preprocessor commands to define macros used there, and use
@code{#include} to include header files that do any of these things.
+You need to declare the lexical analyzer @code{yylex} and the error
+printer @code{yyerror} here, along with any other global identifiers
+used by the actions in the grammar rules.
The Bison declarations declare the names of the terminal and nonterminal
symbols, and may also describe operator precedence and the data types of
The grammar rules define how to construct each nonterminal symbol from its
parts.
-The epilogue can contain any code you want to use. Often the definition of
-the lexical analyzer @code{yylex} goes here, plus subroutines called by the
-actions in the grammar rules. In a simple program, all the rest of the
-program can go here.
+The epilogue can contain any code you want to use. Often the
+definitions of functions declared in the prologue go here. In a
+simple program, all the rest of the program can go here.
@node Examples
@chapter Examples
/* Reverse polish notation calculator. */
%@{
-#define YYSTYPE double
-#include <math.h>
+ #define YYSTYPE double
+ #include <math.h>
+ int yylex (void);
+ void yyerror (char const *);
%@}
%token NUM
@end example
The declarations section (@pxref{Prologue, , The prologue}) contains two
-preprocessor directives.
+preprocessor directives and two forward declarations.
The @code{#define} directive defines the macro @code{YYSTYPE}, thus
specifying the C data type for semantic values of both tokens and
The @code{#include} directive is used to declare the exponentiation
function @code{pow}.
+The forward declarations for @code{yylex} and @code{yyerror} are
+needed because the C language requires that functions be declared
+before they are used. These functions will be defined in the
+epilogue, but the parser calls them so they must be declared in the
+prologue.
+
The second section, Bison declarations, provides information to Bison
about the token types (@pxref{Bison Declarations, ,The Bison
Declarations Section}). Each terminal symbol that is not a
When @code{yyparse} detects a syntax error, it calls the error reporting
function @code{yyerror} to print an error message (usually but not
-always @code{"parse error"}). It is up to the programmer to supply
+always @code{"syntax error"}). It is up to the programmer to supply
@code{yyerror} (@pxref{Interface, ,Parser C-Language Interface}), so
here is the definition we will use:
@group
#include <stdio.h>
+/* Called by yyparse on error. */
void
-yyerror (const char *s) /* Called by yyparse on error. */
+yyerror (char const *s)
@{
printf ("%s\n", s);
@}
@file{calc.y}, an infix desk-top calculator.
@example
-/* Infix notation calculator--calc */
+/* Infix notation calculator. */
%@{
-#define YYSTYPE double
-#include <math.h>
+ #define YYSTYPE double
+ #include <math.h>
+ #include <stdio.h>
+ int yylex (void);
+ void yyerror (char const *);
%@}
-/* Bison Declarations */
+/* Bison declarations. */
%token NUM
%left '-' '+'
%left '*' '/'
%left NEG /* negation--unary minus */
-%right '^' /* exponentiation */
+%right '^' /* exponentiation */
-/* Grammar follows */
-%%
-input: /* empty string */
+%% /* The grammar follows. */
+input: /* empty */
| input line
;
@end example
This addition to the grammar allows for simple error recovery in the
-event of a parse error. If an expression that cannot be evaluated is
+event of a syntax error. If an expression that cannot be evaluated is
read, the error will be recognized by the third rule for @code{line},
and parsing will continue. (The @code{yyerror} function is still called
upon to print its message as well.) The action executes the statement
/* Location tracking calculator. */
%@{
-#define YYSTYPE int
-#include <math.h>
+ #define YYSTYPE int
+ #include <math.h>
+ int yylex (void);
+ void yyerror (char const *);
%@}
/* Bison declarations. */
%left NEG
%right '^'
-%% /* Grammar follows */
+%% /* The grammar follows. */
@end example
@noindent
@smallexample
@group
%@{
-#include <math.h> /* For math functions, cos(), sin(), etc. */
-#include "calc.h" /* Contains definition of `symrec' */
+ #include <math.h> /* For math functions, cos(), sin(), etc. */
+ #include "calc.h" /* Contains definition of `symrec'. */
+ int yylex (void);
+ void yyerror (char const *);
%@}
@end group
@group
%union @{
- double val; /* For returning numbers. */
- symrec *tptr; /* For returning symbol-table pointers. */
+ double val; /* For returning numbers. */
+ symrec *tptr; /* For returning symbol-table pointers. */
@}
@end group
-%token <val> NUM /* Simple double precision number. */
-%token <tptr> VAR FNCT /* Variable and Function. */
+%token <val> NUM /* Simple double precision number. */
+%token <tptr> VAR FNCT /* Variable and Function. */
%type <val> exp
@group
%right '='
%left '-' '+'
%left '*' '/'
-%left NEG /* Negation--unary minus */
-%right '^' /* Exponentiation */
+%left NEG /* negation--unary minus */
+%right '^' /* exponentiation */
@end group
-/* Grammar follows */
-%%
+%% /* The grammar follows. */
@end smallexample
The above grammar introduces only two new features of the Bison language.
| '(' exp ')' @{ $$ = $2; @}
;
@end group
-/* End of grammar */
+/* End of grammar. */
%%
@end smallexample
@smallexample
@group
-/* Function type. */
+/* Function type. */
typedef double (*func_t) (double);
@end group
@group
-/* Data type for links in the chain of symbols. */
+/* Data type for links in the chain of symbols. */
struct symrec
@{
- char *name; /* name of symbol */
+ char *name; /* name of symbol */
int type; /* type of symbol: either VAR or FNCT */
union
@{
- double var; /* value of a VAR */
- func_t fnctptr; /* value of a FNCT */
+ double var; /* value of a VAR */
+ func_t fnctptr; /* value of a FNCT */
@} value;
- struct symrec *next; /* link field */
+ struct symrec *next; /* link field */
@};
@end group
@group
typedef struct symrec symrec;
-/* The symbol table: a chain of `struct symrec'. */
+/* The symbol table: a chain of `struct symrec'. */
extern symrec *sym_table;
-symrec *putsym (const char *, func_t);
-symrec *getsym (const char *);
+symrec *putsym (char const *, func_t);
+symrec *getsym (char const *);
@end group
@end smallexample
#include <stdio.h>
@group
-int
-main (void)
-@{
- init_table ();
- return yyparse ();
-@}
-@end group
-
-@group
+/* Called by yyparse on error. */
void
-yyerror (const char *s) /* Called by yyparse on error. */
+yyerror (char const *s)
@{
printf ("%s\n", s);
@}
@group
struct init
@{
- char *fname;
- double (*fnct)(double);
+ char const *fname;
+ double (*fnct) (double);
@};
@end group
@group
-struct init arith_fncts[] =
+struct init const arith_fncts[] =
@{
"sin", sin,
"cos", cos,
@group
/* The symbol table: a chain of `struct symrec'. */
-symrec *sym_table = (symrec *) 0;
+symrec *sym_table;
@end group
@group
@}
@}
@end group
+
+@group
+int
+main (void)
+@{
+ init_table ();
+ return yyparse ();
+@}
+@end group
@end smallexample
By simply editing the initialization list and adding the necessary include
@smallexample
symrec *
-putsym (char *sym_name, int sym_type)
+putsym (char const *sym_name, int sym_type)
@{
symrec *ptr;
ptr = (symrec *) malloc (sizeof (symrec));
@}
symrec *
-getsym (const char *sym_name)
+getsym (char const *sym_name)
@{
symrec *ptr;
for (ptr = sym_table; ptr != (symrec *) 0;
@example
%@{
-@var{Prologue}
+ @var{Prologue}
%@}
@var{Bison declarations}
* Epilogue:: Syntax and usage of the epilogue.
@end menu
-@node Prologue, Bison Declarations, , Grammar Outline
+@node Prologue
@subsection The prologue
@cindex declarations section
@cindex Prologue
@smallexample
%@{
-#include <stdio.h>
-#include "ptypes.h"
+ #include <stdio.h>
+ #include "ptypes.h"
%@}
%union @{
@}
%@{
-static void yyprint(FILE *, int, YYSTYPE);
-#define YYPRINT(F, N, L) yyprint(F, N, L)
+ static void print_token_value (FILE *, int, YYSTYPE);
+ #define YYPRINT(F, N, L) print_token_value (F, N, L)
%@}
@dots{}
@samp{%%} (which precedes the grammar rules) may never be omitted even
if it is the first thing in the file.
-@node Epilogue, , Grammar Rules, Grammar Outline
+@node Epilogue
@subsection The epilogue
@cindex additional C code section
@cindex epilogue
the @var{Prologue} is copied to the beginning. This is the most convenient
place to put anything that you want to have in the parser file but which need
not come before the definition of @code{yyparse}. For example, the
-definitions of @code{yylex} and @code{yyerror} often go here.
+definitions of @code{yylex} and @code{yyerror} often go here. Because
+C requires functions to be declared before being used, you often need
+to declare functions like @code{yylex} and @code{yyerror} in the Prologue,
+even if you define them int he Epilogue.
@xref{Interface, ,Parser C-Language Interface}.
If the last section is empty, you may omit the @samp{%%} that separates it
from the grammar rules.
-The Bison parser itself contains many static variables whose names start
-with @samp{yy} and many macros whose names start with @samp{YY}. It is a
+The Bison parser itself contains many macros and identifiers whose
+names start with @samp{yy} or @samp{YY}, so it is a
good idea to avoid using any such names (except those documented in this
manual) in the epilogue of the grammar file.
@node Locations
@section Tracking Locations
@cindex location
-@cindex textual position
-@cindex position, textual
+@cindex textual location
+@cindex location, textual
Though grammar rules and semantic actions are enough to write a fully
functional parser, it can be useful to process some additional information,
four members:
@example
-struct
+typedef struct YYLTYPE
@{
int first_line;
int first_column;
int last_line;
int last_column;
-@}
+@} YYLTYPE;
@end example
@node Actions and Locations
locations are much more general than semantic values, there is room in
the output parser to redefine the default action to take for each
rule. The @code{YYLLOC_DEFAULT} macro is invoked each time a rule is
-matched, before the associated action is run.
+matched, before the associated action is run. It is also invoked
+while processing a syntax error, to compute the error's location.
Most of the time, this macro is general enough to suppress location
dedicated code from semantic actions.
The @code{YYLLOC_DEFAULT} macro takes three parameters. The first one is
-the location of the grouping (the result of the computation). The second one
-is an array holding locations of all right hand side elements of the rule
-being matched. The last one is the size of the right hand side rule.
+the location of the grouping (the result of the computation). When a
+rule is matched, the second parameter is an array holding locations of
+all right hand side elements of the rule being matched, and the third
+parameter is the size of the rule's right hand side. When processing
+a syntax error, the second parameter is an array holding locations of
+the symbols that were discarded during error processing, and the third
+parameter is the number of discarded symbols.
-By default, it is defined this way for simple @acronym{LALR}(1) parsers:
+By default, @code{YYLLOC_DEFAULT} is defined this way for simple
+@acronym{LALR}(1) parsers:
@example
@group
in the @code{%token} and @code{%type} declarations to pick one of the types
for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
-Note that, unlike making a @code{union} declaration in C, you do not write
+As an extension to @acronym{POSIX}, a tag is allowed after the
+@code{union}. For example:
+
+@example
+@group
+%union value @{
+ double val;
+ symrec *tptr;
+@}
+@end group
+@end example
+
+specifies the union tag @code{value}, so the corresponding C type is
+@code{union value}. If you do not specify a tag, it defaults to
+@code{YYSTYPE}.
+
+Note that, unlike making a @code{union} declaration in C, you need not write
a semicolon after the closing brace.
@node Type Decl
(@pxref{Parser Function, , The Parser Function @code{yyparse}}).
@strong{Warning:} as of Bison 1.875, this feature is still considered as
-experimental, as there was not enough users feedback. In particular,
+experimental, as there was not enough user feedback. In particular,
the syntax might still change.
@end deffn
Here @var{n} is a decimal integer. The declaration says there should be
no warning if there are @var{n} shift/reduce conflicts and no
-reduce/reduce conflicts. An error, instead of the usual warning, is
+reduce/reduce conflicts. The usual warning is
given if there are either more or fewer conflicts, or if there are any
reduce/reduce conflicts.
number which Bison printed.
@end itemize
-Now Bison will stop annoying you about the conflicts you have checked, but
-it will warn you again if changes in the grammar result in additional
-conflicts.
+Now Bison will stop annoying you if you do not change the number of
+conflicts, but it will warn you again if changes in the grammar result
+in more or fewer conflicts.
@node Start Decl
@subsection The Start-Symbol
,Special Features for Use in Actions}). This mode is enabled as soon as
the grammar uses the special @samp{@@@var{n}} tokens, but if your
grammar does not use it, using @samp{%locations} allows for more
-accurate parse error messages.
+accurate syntax error messages.
@end deffn
@deffn {Directive} %name-prefix="@var{prefix}"
Generate an array of token names in the parser file. The name of the
array is @code{yytname}; @code{yytname[@var{i}]} is the name of the
token whose internal Bison token code number is @var{i}. The first
-three elements of @code{yytname} are always @code{"$end"},
+three elements of @code{yytname} correspond to the predefined tokens
+@code{"$end"},
@code{"error"}, and @code{"$undefined"}; after these come the symbols
defined in the grammar file.
parameter information to it in a reentrant way. To do so, use the
declaration @code{%parse-param}:
-@deffn {Directive} %parse-param @var{argument-declaration} @var{argument-name}
+@deffn {Directive} %parse-param @{@var{argument-declaration}@}
@findex %parse-param
-Declare that @code{argument-name} is an additional @code{yyparse}
-argument. This argument is also passed to @code{yyerror}. The
-@var{argument-declaration} is used when declaring functions or
-prototypes.
+Declare that an argument declared by @code{argument-declaration} is an
+additional @code{yyparse} argument.
+The @var{argument-declaration} is used when declaring
+functions or prototypes. The last identifier in
+@var{argument-declaration} must be the argument name.
@end deffn
Here's an example. Write this in the parser:
@example
-%parse-param "int *nastiness" "nastiness"
-%parse-param "int *randomness" "randomness"
+%parse-param @{int *nastiness@}
+%parse-param @{int *randomness@}
@end example
@noindent
* Calling Convention:: How @code{yyparse} calls @code{yylex}.
* Token Values:: How @code{yylex} must return the semantic value
of the token it has read.
-* Token Positions:: How @code{yylex} must return the text position
+* Token Locations:: How @code{yylex} must return the text location
(line number, etc.) of the token, if the
actions want that.
* Pure Calling:: How the calling convention differs
@end group
@end example
-@node Token Positions
-@subsection Textual Positions of Tokens
+@node Token Locations
+@subsection Textual Locations of Tokens
@vindex yylloc
If you are using the @samp{@@@var{n}}-feature (@pxref{Locations, ,
@end example
If the grammar file does not use the @samp{@@} constructs to refer to
-textual positions, then the type @code{YYLTYPE} will not be defined. In
+textual locations, then the type @code{YYLTYPE} will not be defined. In
this case, omit the second argument; @code{yylex} will be called with
only one argument.
@code{%lex-param} just like @code{%parse-param} (@pxref{Parser
Function}).
-@deffn {Directive} lex-param @var{argument-declaration} @var{argument-name}
+@deffn {Directive} lex-param @{@var{argument-declaration}@}
@findex %lex-param
-Declare that @code{argument-name} is an additional @code{yylex}
-argument.
+Declare that @code{argument-declaration} is an additional @code{yylex}
+argument declaration.
@end deffn
For instance:
@example
-%parse-param "int *nastiness" "nastiness"
-%lex-param "int *nastiness" "nastiness"
-%parse-param "int *randomness" "randomness"
+%parse-param @{int *nastiness@}
+%lex-param @{int *nastiness@}
+%parse-param @{int *randomness@}
@end example
@noindent
@cindex parse error
@cindex syntax error
-The Bison parser detects a @dfn{parse error} or @dfn{syntax error}
+The Bison parser detects a @dfn{syntax error} or @dfn{parse error}
whenever it reads a token which cannot satisfy any syntax rule. An
action in the grammar can also explicitly proclaim an error, using the
macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use
The Bison parser expects to report the error by calling an error
reporting function named @code{yyerror}, which you must supply. It is
called by @code{yyparse} whenever a syntax error is found, and it
-receives one argument. For a parse error, the string is normally
-@w{@code{"parse error"}}.
+receives one argument. For a syntax error, the string is normally
+@w{@code{"syntax error"}}.
@findex %error-verbose
If you invoke the directive @code{%error-verbose} in the Bison
declarations section (@pxref{Bison Declarations, ,The Bison Declarations
Section}), then Bison provides a more verbose and specific error message
-string instead of just plain @w{@code{"parse error"}}.
+string instead of just plain @w{@code{"syntax error"}}.
The parser can detect one other kind of error: stack overflow. This
happens when the input contains constructions that are very deeply
@example
@group
void
-yyerror (const char *s)
+yyerror (char const *s)
@{
@end group
@group
@code{yyerror} are:
@example
-void yyerror (const char *msg); /* Yacc parsers. */
-void yyerror (YYLTYPE *locp, const char *msg); /* GLR parsers. */
+void yyerror (char const *msg); /* Yacc parsers. */
+void yyerror (YYLTYPE *locp, char const *msg); /* GLR parsers. */
@end example
-If @samp{%parse-param "int *nastiness" "nastiness"} is used, then:
+If @samp{%parse-param @{int *nastiness@}} is used, then:
@example
-void yyerror (int *randomness, const char *msg); /* Yacc parsers. */
-void yyerror (int *randomness, const char *msg); /* GLR parsers. */
+void yyerror (int *nastiness, char const *msg); /* Yacc parsers. */
+void yyerror (int *nastiness, char const *msg); /* GLR parsers. */
@end example
Finally, GLR and Yacc parsers share the same @code{yyerror} calling
%locations
/* Pure yylex. */
%pure-parser
-%lex-param "int *nastiness" "nastiness"
+%lex-param @{int *nastiness@}
/* Pure yyparse. */
-%parse-param "int *nastiness" "nastiness"
-%parse-param "int *randomness" "randomness"
+%parse-param @{int *nastiness@}
+%parse-param @{int *randomness@}
@end example
@noindent
int yyparse (int *nastiness, int *randomness);
void yyerror (YYLTYPE *locp,
int *nastiness, int *randomness,
- const char *msg);
+ char const *msg);
@end example
@noindent
-Please, note that the prototypes are only indications of how the code
-produced by Bison will use @code{yyerror}; you still have freedom on the
-exit value, and even on making @code{yyerror} a variadic function. It
-is precisely to enable this that the message is always passed last.
+The prototypes are only indications of how the code produced by Bison
+uses @code{yyerror}. Bison-generated code always ignores the returned
+value, so @code{yyerror} can return any type, including @code{void}.
+Also, @code{yyerror} can be a variadic function; that is why the
+message is always passed last.
+
+Traditionally @code{yyerror} returns an @code{int} that is always
+ignored, but this is purely for historical reasons, and @code{void} is
+preferable since it more accurately describes the return type for
+@code{yyerror}.
@vindex yynerrs
The variable @code{yynerrs} contains the number of syntax errors
@deffn {Value} @@$
@findex @@$
-Acts like a structure variable containing information on the textual position
+Acts like a structure variable containing information on the textual location
of the grouping made by the current rule. @xref{Locations, ,
Tracking Locations}.
@deffn {Value} @@@var{n}
@findex @@@var{n}
-Acts like a structure variable containing information on the textual position
+Acts like a structure variable containing information on the textual location
of the @var{n}th component of the current rule. @xref{Locations, ,
Tracking Locations}.
@end deffn
grammar, in particular, it is only slightly slower than with the default
Bison parser.
+For a more detailed exposition of GLR parsers, please see: Elizabeth
+Scott, Adrian Johnstone and Shamsa Sadaf Hussain, Tomita-Style
+Generalised @acronym{LR} Parsers, Royal Holloway, University of
+London, Department of Computer Science, TR-00-12,
+@uref{http://www.cs.rhul.ac.uk/research/languages/publications/tomita_style_1.ps},
+(2000-12-24).
+
@node Stack Overflow
@section Stack Overflow, and How to Avoid It
@cindex stack overflow
@cindex error recovery
@cindex recovery from errors
-It is not usually acceptable to have a program terminate on a parse
+It is not usually acceptable to have a program terminate on a syntax
error. For example, a compiler should recover sufficiently to parse the
rest of the input file and check it for errors; a calculator should accept
another expression.
this token. Write the statement @samp{yyclearin;} in the error rule's
action.
-For example, suppose that on a parse error, an error handling routine is
+For example, suppose that on a syntax error, an error handling routine is
called that advances the input stream to some point where parsing should
once again commence. The next symbol returned by the lexical scanner is
probably correct. The previous look-ahead token ought to be discarded
@example
@group
%@{
-int hexflag;
+ int hexflag;
+ int yylex (void);
+ void yyerror (char const *);
%@}
%%
@dots{}
@example
calc.y: warning: 1 useless nonterminal and 1 useless rule
calc.y:11.1-7: warning: useless nonterminal: useless
-calc.y:11.8-12: warning: useless rule: useless: STR
-calc.y contains 7 shift/reduce conflicts.
+calc.y:11.10-12: warning: useless rule: useless: STR
+calc.y: conflicts: 7 shift/reduce
@end example
When given @option{--report=state}, in addition to @file{calc.tab.c}, it
The next section lists states that still have conflicts.
@example
-State 8 contains 1 shift/reduce conflict.
-State 9 contains 1 shift/reduce conflict.
-State 10 contains 1 shift/reduce conflict.
-State 11 contains 4 shift/reduce conflicts.
+State 8 conflicts: 1 shift/reduce
+State 9 conflicts: 1 shift/reduce
+State 10 conflicts: 1 shift/reduce
+State 11 conflicts: 4 shift/reduce
@end example
@noindent
flow jumps to state 2. If there is no such transition on a nonterminal
symbol, and the lookahead is a @code{NUM}, then this token is shifted on
the parse stack, and the control flow jumps to state 1. Any other
-lookahead triggers a parse error.''
+lookahead triggers a syntax error.''
@cindex core, item set
@cindex item set core
@samp{+}, it will be shifted on the parse stack, and the automaton
control will jump to state 4, corresponding to the item @samp{exp -> exp
'+' . exp}. Since there is no default action, any other token than
-those listed above will trigger a parse error.
+those listed above will trigger a syntax error.
The state 3 is named the @dfn{final state}, or the @dfn{accepting
state}:
exp go to state 11
@end example
-As was announced in beginning of the report, @samp{State 8 contains 1
-shift/reduce conflict}:
+As was announced in beginning of the report, @samp{State 8 conflicts:
+1 shift/reduce}:
@example
state 8
calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
@smallexample
-#define YYPRINT(file, type, value) yyprint (file, type, value)
+%@{
+ static void print_token_value (FILE *, int, YYSTYPE);
+ #define YYPRINT(file, type, value) print_token_value (file, type, value)
+%@}
+
+@dots{} %% @dots{} %% @dots{}
static void
-yyprint (FILE *file, int type, YYSTYPE value)
+print_token_value (FILE *file, int type, YYSTYPE value)
@{
if (type == VAR)
- fprintf (file, " %s", value.tptr->name);
+ fprintf (file, "%s", value.tptr->name);
else if (type == NUM)
- fprintf (file, " %d", value.val);
+ fprintf (file, "%d", value.val);
@}
@end smallexample
@noindent
will produce @file{output.c++} and @file{outfile.h++}.
+For compatibility with @acronym{POSIX}, the standard Bison
+distribution also contains a shell script called @command{yacc} that
+invokes Bison with the @option{-y} option.
+
@menu
* Bison Options:: All the options described in detail,
in alphabetical order by short options.
* Option Cross Key:: Alphabetical list of long options.
+* Yacc Library:: Yacc-compatible @code{yylex} and @code{main}.
@end menu
@node Bison Options
@file{y.tab.c}, and the other outputs are called @file{y.output} and
@file{y.tab.h}. The purpose of this option is to imitate Yacc's output
file name conventions. Thus, the following shell script can substitute
-for Yacc:
+for Yacc, and the Bison distribution contains such a script for
+compatibility with @acronym{POSIX}:
@example
-bison -y $*
+#! /bin/sh
+bison -y "$@"
@end example
@end table
@end example
@end ifinfo
+@node Yacc Library
+@section Yacc Library
+
+The Yacc library contains default implementations of the
+@code{yyerror} and @code{main} functions. These default
+implementations are normally not useful, but @acronym{POSIX} requires
+them. To use the Yacc library, link your program with the
+@option{-ly} option. Note that Bison's implementation of the Yacc
+library is distributed under the terms of the @acronym{GNU} General
+Public License (@pxref{Copying}).
+
+If you use the Yacc library's @code{yyerror} function, you should
+declare @code{yyerror} as follows:
+
+@example
+int yyerror (char const *);
+@end example
+
+Bison ignores the @code{int} value returned by this @code{yyerror}.
+If you use the Yacc library's @code{main} function, your
+@code{yyparse} function should have the following type signature:
+
+@example
+int yyparse (void);
+@end example
+
@c ================================================= Invoking Bison
@node FAQ
@menu
* Parser Stack Overflow:: Breaking the Stack Limits
+* Strings are Destroyed:: @code{yylval} Loses Track of Strings
@end menu
@node Parser Stack Overflow
This question is already addressed elsewhere, @xref{Recursion,
,Recursive Rules}.
+@node Strings are Destroyed
+@section Strings are Destroyed
+
+@display
+My parser seems to destroy old strings, or maybe it losses track of
+them. Instead of reporting @samp{"foo", "bar"}, it reports
+@samp{"bar", "bar"}, or even @samp{"foo\nbar", "bar"}.
+@end display
+
+This error is probably the single most frequent ``bug report'' sent to
+Bison lists, but is only concerned with a misunderstanding of the role
+of scanner. Consider the following Lex code:
+
+@verbatim
+%{
+#include <stdio.h>
+char *yylval = NULL;
+%}
+%%
+.* yylval = yytext; return 1;
+\n /* IGNORE */
+%%
+int
+main ()
+{
+ /* Similar to using $1, $2 in a Bison action. */
+ char *fst = (yylex (), yylval);
+ char *snd = (yylex (), yylval);
+ printf ("\"%s\", \"%s\"\n", fst, snd);
+ return 0;
+}
+@end verbatim
+
+If you compile and run this code, you get:
+
+@example
+$ @kbd{flex -osplit-lines.c split-lines.l}
+$ @kbd{gcc -osplit-lines split-lines.c -ll}
+$ @kbd{printf 'one\ntwo\n' | ./split-lines}
+"one
+two", "two"
+@end example
+
+@noindent
+this is because @code{yytext} is a buffer provided for @emph{reading}
+in the action, but if you want to keep it, you have to duplicate it
+(e.g., using @code{strdup}). Note that the output may depend on how
+your implementation of Lex handles @code{yytext}. For instance, when
+given the Lex compatibility option @option{-l} (which triggers the
+option @samp{%array}) Flex generates a different behavior:
+
+@example
+$ @kbd{flex -l -osplit-lines.c split-lines.l}
+$ @kbd{gcc -osplit-lines split-lines.c -ll}
+$ @kbd{printf 'one\ntwo\n' | ./split-lines}
+"two", "two"
+@end example
+
+
@c ================================================= Table of Symbols
@node Table of Symbols
A token name reserved for error recovery. This token may be used in
grammar rules so as to allow the Bison parser to recognize an error in
the grammar without halting the process. In effect, a sentence
-containing an error may be recognized as valid. On a parse error, the
+containing an error may be recognized as valid. On a syntax error, the
token @code{error} becomes the current look-ahead token. Actions
corresponding to @code{error} are then executed, and the look-ahead
token is reset to the token that originally caused the violation.
@end deffn
@deffn {Macro} YYERROR_VERBOSE
-An obsolete macro that you define with @code{#define} in the Bison
-declarations section to request verbose, specific error message strings
+An obsolete macro that you define with @code{#define} in the prologue
+to request verbose, specific error message strings
when @code{yyerror} is called. It doesn't matter what definition you
use for @code{YYERROR_VERBOSE}, just whether you define it. Using
@code{%error-verbose} is preferred.
@xref{Pure Calling,, Calling Conventions for Pure Parsers}.
@end deffn
-@deffn {Macro} YYLTYPE
-Macro for the data type of @code{yylloc}; a structure with four
+@deffn {Type} YYLTYPE
+Data type of @code{yylloc}; by default, a structure with four
members. @xref{Location Type, , Data Types of Locations}.
@end deffn
-@deffn {Type} yyltype
-Default value for YYLTYPE.
-@end deffn
-
@deffn {Macro} YYMAXDEPTH
Macro for specifying the maximum size of the parser stack. @xref{Stack
Overflow}.
to anything else.
@end deffn
-@deffn {Macro} YYSTYPE
-Macro for the data type of semantic values; @code{int} by default.
+@deffn {Type} YYSTYPE
+Data type of semantic values; @code{int} by default.
@xref{Value Type, ,Data Types of Semantic Values}.
@end deffn
@deffn {Macro} yyerrok
Macro to cause parser to recover immediately to its normal mode
-after a parse error. @xref{Error Recovery}.
+after a syntax error. @xref{Error Recovery}.
@end deffn
@deffn {Function} yyerror
-User-supplied function to be called by @code{yyparse} on error. The
-function receives one argument, a pointer to a character string
-containing an error message. @xref{Error Reporting, ,The Error
+User-supplied function to be called by @code{yyparse} on error.
+@xref{Error Reporting, ,The Error
Reporting Function @code{yyerror}}.
@end deffn
numbers associated with a token. (In a pure parser, it is a local
variable within @code{yyparse}, and its address is passed to
@code{yylex}.) You can ignore this variable if you don't use the
-@samp{@@} feature in the grammar actions. @xref{Token Positions,
-,Textual Positions of Tokens}.
+@samp{@@} feature in the grammar actions. @xref{Token Locations,
+,Textual Locations of Tokens}.
@end deffn
@deffn {Variable} yynerrs
-Global variable which Bison increments each time there is a parse error.
+Global variable which Bison increments each time there is a syntax error.
(In a pure parser, it is a local variable within @code{yyparse}.)
@xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
@end deffn
@xref{Precedence Decl, ,Operator Precedence}.
@end deffn
-@deffn {Directive} %lex-param "@var{argument-declaration}" "@var{argument-name}"
+@deffn {Directive} %lex-param @{@var{argument-declaration}@}
Bison declaration to specifying an additional parameter that
@code{yylex} should accept. @xref{Pure Calling,, Calling Conventions
for Pure Parsers}.
Summary}.
@end deffn
-@deffn {Directive} %parse-param "@var{argument-declaration}" "@var{argument-name}"
+@deffn {Directive} %parse-param @{@var{argument-declaration}@}
Bison declaration to specifying an additional parameter that
@code{yyparse} should accept. @xref{Parser Function,, The Parser
Function @code{yyparse}}.
be expressed through rules in terms of smaller constructs; in other
words, a construct that is not a token. @xref{Symbols}.
-@item Parse error
-An error encountered during parsing of an input stream due to invalid
-syntax. @xref{Error Recovery}.
-
@item Parser
A function that recognizes valid sentences of a language by analyzing
the syntax structure of a set of tokens passed to it from a lexical
during parsing to allow for recognition and use of existing
information in repeated uses of a symbol. @xref{Multi-function Calc}.
+@item Syntax error
+An error encountered during parsing of an input stream due to invalid
+syntax. @xref{Error Recovery}.
+
@item Token
A basic, grammatically indivisible unit of a language. The symbol
that describes a token in the grammar is a terminal symbol.