X-Git-Url: https://git.saurik.com/bison.git/blobdiff_plain/d3c4e709ff473cd0dd3b4e6cc93be41e812e2586..231897ad21e478b0b0821636aa49fe49ca0f3301:/doc/bison.texinfo?ds=sidebyside diff --git a/doc/bison.texinfo b/doc/bison.texinfo index f3a55080..3ed6b7f5 100644 --- a/doc/bison.texinfo +++ b/doc/bison.texinfo @@ -39,8 +39,8 @@ 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 @@ -119,7 +119,8 @@ Reference sections: * 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 @@ -130,6 +131,8 @@ 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. @@ -143,8 +146,8 @@ Examples 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 @@ -182,15 +185,16 @@ Bison Grammar Files * 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 @@ -202,6 +206,12 @@ 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. @@ -227,9 +237,9 @@ The Lexical Analyzer Function @code{yylex} * 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}). @@ -259,7 +269,7 @@ Handling Context Dependencies * 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. @@ -269,10 +279,13 @@ Invoking Bison * 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 +* How Can I Reset @code{yyparse}:: @code{yyparse} Keeps some State +* Strings are Destroyed:: @code{yylval} Loses Track of Strings Copying This Manual @@ -685,7 +698,10 @@ Let's consider an example, vastly simplified from a C++ grammar. @example %@{ - #define YYSTYPE const char* + #include + #define YYSTYPE char const * + int yylex (void); + void yyerror (char const *); %@} %token TYPENAME ID @@ -783,7 +799,8 @@ stmt : expr ';' %merge and define the @code{stmtMerge} function as: @example -static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1) +static YYSTYPE +stmtMerge (YYSTYPE x0, YYSTYPE x1) @{ printf (" "); return ""; @@ -796,7 +813,7 @@ in the C declarations at the beginning of the file: @example %@{ - #define YYSTYPE const char* + #define YYSTYPE char const * static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1); %@} @end example @@ -813,15 +830,16 @@ as both an @code{expr} and a @code{decl}, and print @cindex @code{incline} @cindex @acronym{GLR} parsers and @code{inline} -Note that the @acronym{GLR} parsers require an ISO C89 compiler. In -addition, they use the @code{inline} keyword, which is not C89, but a -common extension. It is up to the user of these parsers to handle +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 + #include %@} @end example @@ -830,21 +848,21 @@ will suffice. Otherwise, we suggest @example %@{ -#if ! defined __GNUC__ && ! defined inline -# define inline -#endif + #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 @@ -992,6 +1010,9 @@ in every Bison grammar file to separate the sections. 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 @@ -1000,10 +1021,9 @@ semantic values of various symbols. 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 @@ -1070,8 +1090,10 @@ calculator. As in C, comments are placed between @samp{/*@dots{}*/}. /* Reverse polish notation calculator. */ %@{ -#define YYSTYPE double -#include + #define YYSTYPE double + #include + int yylex (void); + void yyerror (char const *); %@} %token NUM @@ -1080,7 +1102,7 @@ calculator. As in C, comments are placed between @samp{/*@dots{}*/}. @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 @@ -1093,6 +1115,12 @@ which is a floating point number. 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 @@ -1381,8 +1409,9 @@ here is the definition we will use: @group #include +/* Called by yyparse on error. */ void -yyerror (const char *s) /* Called by yyparse on error. */ +yyerror (char const *s) @{ printf ("%s\n", s); @} @@ -1482,23 +1511,25 @@ parentheses nested to arbitrary depth. Here is the Bison code for @file{calc.y}, an infix desk-top calculator. @example -/* Infix notation calculator--calc */ +/* Infix notation calculator. */ %@{ -#define YYSTYPE double -#include + #define YYSTYPE double + #include + #include + 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 ; @@ -1628,8 +1659,10 @@ the same as the declarations for the infix notation calculator. /* Location tracking calculator. */ %@{ -#define YYSTYPE int -#include + #define YYSTYPE int + #include + int yylex (void); + void yyerror (char const *); %@} /* Bison declarations. */ @@ -1640,7 +1673,7 @@ the same as the declarations for the infix notation calculator. %left NEG %right '^' -%% /* Grammar follows */ +%% /* The grammar follows. */ @end example @noindent @@ -1863,29 +1896,30 @@ Here are the C and Bison declarations for the multi-function calculator. @smallexample @group %@{ -#include /* For math functions, cos(), sin(), etc. */ -#include "calc.h" /* Contains definition of `symrec' */ + #include /* 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 NUM /* Simple double precision number. */ -%token VAR FNCT /* Variable and Function. */ +%token NUM /* Simple double precision number. */ +%token VAR FNCT /* Variable and Function. */ %type 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. @@ -1946,7 +1980,7 @@ exp: NUM @{ $$ = $1; @} | '(' exp ')' @{ $$ = $2; @} ; @end group -/* End of grammar */ +/* End of grammar. */ %% @end smallexample @@ -1965,33 +1999,33 @@ provides for either functions or variables to be placed in the table. @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 @@ -2003,17 +2037,9 @@ function that initializes the symbol table. Here it is, and #include @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); @} @@ -2022,13 +2048,13 @@ yyerror (const char *s) /* Called by yyparse on error. */ @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, @@ -2042,7 +2068,7 @@ struct init arith_fncts[] = @group /* The symbol table: a chain of `struct symrec'. */ -symrec *sym_table = (symrec *) 0; +symrec *sym_table; @end group @group @@ -2059,6 +2085,15 @@ init_table (void) @} @} @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 @@ -2073,7 +2108,7 @@ found, a pointer to that symbol is returned; otherwise zero is returned. @smallexample symrec * -putsym (char *sym_name, int sym_type) +putsym (char const *sym_name, int sym_type) @{ symrec *ptr; ptr = (symrec *) malloc (sizeof (symrec)); @@ -2087,7 +2122,7 @@ putsym (char *sym_name, int sym_type) @} symrec * -getsym (const char *sym_name) +getsym (char const *sym_name) @{ symrec *ptr; for (ptr = sym_table; ptr != (symrec *) 0; @@ -2245,7 +2280,7 @@ appropriate delimiters: @example %@{ -@var{Prologue} + @var{Prologue} %@} @var{Bison declarations} @@ -2268,7 +2303,7 @@ continues until end of line. * 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 @@ -2292,8 +2327,8 @@ can be done with two @var{Prologue} blocks, one before and one after the @smallexample %@{ -#include -#include "ptypes.h" + #include + #include "ptypes.h" %@} %union @{ @@ -2302,8 +2337,8 @@ can be done with two @var{Prologue} blocks, one before and one after the @} %@{ -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{} @@ -2331,7 +2366,7 @@ There must always be at least one grammar rule, and the first @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 @@ -2341,14 +2376,17 @@ The @var{Epilogue} is copied verbatim to the end of the parser file, just as 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. @@ -3035,8 +3073,8 @@ actually does to implement mid-rule actions. @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, @@ -3066,13 +3104,13 @@ When @code{YYLTYPE} is not defined, Bison uses a default structure type with 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 @@ -3150,17 +3188,23 @@ Actually, actions are not the best place to compute locations. Since 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 @@ -3381,7 +3425,23 @@ This says that the two alternative types are @code{double} and @code{symrec 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 @@ -3439,7 +3499,7 @@ should use @code{$$} to designate the semantic value associated to the (@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 @@ -3500,7 +3560,7 @@ The declaration looks like this: 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. @@ -3522,9 +3582,9 @@ Add an @code{%expect} declaration, copying the number @var{n} from the 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 @@ -3717,7 +3777,8 @@ Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure 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. @@ -3847,19 +3908,20 @@ If you use a reentrant parser, you can optionally pass additional 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 @@ -3904,7 +3966,7 @@ that need it. @xref{Invocation, ,Invoking Bison}. * 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 @@ -4037,8 +4099,8 @@ then the code in @code{yylex} might look like this: @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, , @@ -4081,7 +4143,7 @@ yylex (YYSTYPE *lvalp, YYLTYPE *llocp) @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. @@ -4090,18 +4152,18 @@ If you wish to pass the additional parameter data to @code{yylex}, use @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 @@ -4165,7 +4227,7 @@ The following definition suffices in simple programs: @example @group void -yyerror (const char *s) +yyerror (char const *s) @{ @end group @group @@ -4186,15 +4248,15 @@ parsers, but not for the Yacc parser, for historical reasons. I.e., if @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 @@ -4207,10 +4269,10 @@ convention of @code{yylex} @emph{and} the calling convention of %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 @@ -4221,14 +4283,20 @@ int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, int *nastiness); 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 @@ -4333,7 +4401,7 @@ errors. This is useful primarily in error rules. @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}. @@ -4359,7 +4427,7 @@ 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 @@ -5105,6 +5173,13 @@ structure should generally be adequate. On @acronym{LALR}(1) portions of a 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 @@ -5382,7 +5457,9 @@ as an identifier if it appears in that context. Here is how you can do it: @example @group %@{ -int hexflag; + int hexflag; + int yylex (void); + void yyerror (char const *); %@} %% @dots{} @@ -5530,8 +5607,8 @@ useless: STR; @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 @@ -5553,10 +5630,10 @@ Conflict in state 8 between rule 2 and token '*' resolved as shift. 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 @@ -5768,8 +5845,8 @@ state 7 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 @@ -5980,10 +6057,15 @@ Here is an example of @code{YYPRINT} suitable for the multi-function 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); @@ -6032,10 +6114,15 @@ bison -d -o @var{output.c++} @var{infile.y} @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 @@ -6071,10 +6158,12 @@ Equivalent to @samp{-o y.tab.c}; the parser output file is called @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 @@ -6227,6 +6316,32 @@ the corresponding short option. @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 @@ -6239,6 +6354,8 @@ are addressed. @menu * Parser Stack Overflow:: Breaking the Stack Limits +* How Can I Reset @code{yyparse}:: @code{yyparse} Keeps some State +* Strings are Destroyed:: @code{yylval} Loses Track of Strings @end menu @node Parser Stack Overflow @@ -6252,6 +6369,148 @@ message. What can I do? This question is already addressed elsewhere, @xref{Recursion, ,Recursive Rules}. +@node How Can I Reset @code{yyparse} +@section How Can I Reset @code{yyparse} + +The following phenomenon gives raise to several incarnations, +resulting in the following typical questions: + +@display +I invoke @code{yyparse} several times, and on correct input it works +properly; but when a parse error is found, all the other calls fail +too. How can I reset @code{yyparse}'s error flag? +@end display + +@noindent +or + +@display +My parser includes support for a @samp{#include} like feature, in +which case I run @code{yyparse} from @code{yyparse}. This fails +although I did specify I needed a @code{%pure-parser}. +@end display + +These problems are not related to Bison itself, but with the Lex +generated scanners. Because these scanners use large buffers for +speed, they might not notice a change of input file. As a +demonstration, consider the following source file, +@file{first-line.l}: + +@verbatim +%{ +#include +#include +%} +%% +.*\n ECHO; return 1; +%% +int +yyparse (const char *file) +{ + yyin = fopen (file, "r"); + if (!yyin) + exit (2); + /* One token only. */ + yylex (); + if (!fclose (yyin)) + exit (3); + return 0; +} + +int +main () +{ + yyparse ("input"); + yyparse ("input"); + return 0; +} +@end verbatim + +@noindent +If the file @file{input} contains + +@verbatim +input:1: Hello, +input:2: World! +@end verbatim + +@noindent +then instead of getting twice the first line, you get: + +@example +$ @kbd{flex -ofirst-line.c first-line.l} +$ @kbd{gcc -ofirst-line first-line.c -ll} +$ @kbd{./first-line} +input:1: Hello, +input:2: World! +@end example + +Therefore, whenever you change @code{yyin}, you must tell the Lex +generated scanner to discard its current buffer, and to switch to the +new one. This depends upon your implementation of Lex, see its +documentation for more. For instance, in the case of Flex, a simple +call @samp{yyrestart (yyin)} suffices after each change to +@code{yyin}. + +@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 +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 @@ -6338,8 +6597,8 @@ Macro to pretend that a syntax error has just been detected: call @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. @@ -6357,15 +6616,11 @@ macro is deprecated, and is supported only for Yacc like parsers. @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}. @@ -6390,8 +6645,8 @@ grow its internal stacks. Do @emph{not} define @code{YYSTACK_USE_ALLOCA} 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 @@ -6419,9 +6674,8 @@ 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 @@ -6443,8 +6697,8 @@ External variable in which @code{yylex} should place the line and column 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 @@ -6498,7 +6752,7 @@ Bison declaration to assign left associativity to token(s). @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}. @@ -6530,7 +6784,7 @@ Bison declaration to set the name of the parser file. @xref{Decl 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}}.