### Sample installation with --enable-relocatable Source: https://www.gnu.org/software/bison/manual/html_node/Enabling-Relocatability.html Run configure with --enable-relocatable and --prefix=/nonexistent, then make and install with DESTDIR to avoid installing into the nonexistent prefix. This sequence is recommended for reliable relocatable installation. ```shell ./configure --enable-relocatable --prefix=/nonexistent make make install DESTDIR=/tmp/inst$$ ``` -------------------------------- ### Pure Push Parser Usage Example Source: https://www.gnu.org/software/bison/manual/html_node/Push-Decl.html Example of using a pure push parser, which allows multiple instances in memory simultaneously. ```C int status; yypstate *ps = yypstate_new (); do { status = yypush_parse (ps, yylex (), NULL); } while (status == YYPUSH_MORE); yypstate_delete (ps); ``` -------------------------------- ### Initialize Internationalization in Main Source: https://www.gnu.org/software/bison/manual/html_node/D-Parser-Interface.html Example of setting up locale and translation catalogs within the main function. ```D int main() { import core.stdc.locale; // Set up internationalization. setlocale(LC_ALL, ""); // Use Bison's standard translation catalog for error messages // (the generated messages). bindtextdomain("bison-runtime", BISON_LOCALEDIR); // For the translation catalog of your own project, use the // name of your project. bindtextdomain("bison", LOCALEDIR); textdomain("bison"); // usual main content ... } ``` -------------------------------- ### yylex function example Source: https://www.gnu.org/software/bison/manual/html_node/Calling-Convention.html Example implementation of yylex showing how to return token kind codes, including handling end-of-input and character literals. ```APIDOC ## yylex function ### Description This is an example implementation of the yylex function, which must return a positive numeric code for the kind of token it has just found. A zero or negative value signifies end-of-input. ### Method Function call ### Endpoint Not applicable (function) ### Parameters None (void) ### Return Value - **int** - Positive numeric code for the token kind, or zero/negative for end-of-input. ### Example ```c int yylex (void) { … if (c == EOF) /* Detect end-of-input. */ return YYEOF; … else if (c == '+' || c == '-') return c; /* Assume token kind for '+' is '+'. */ … else return INT; /* Return the kind of the token. */ … } ``` ``` -------------------------------- ### Configure Lex scanner to emit start tokens Source: https://www.gnu.org/software/bison/manual/html_node/Multiple-start_002dsymbols.html Inject code into the generated yylex function to return the appropriate start token based on a variable. ```c /* Prologue. */ %% %{ if (start_token) { int t = start_token; start_token = 0; return t; } %} /* The rules. */ ``` -------------------------------- ### Header file symbol definitions Source: https://www.gnu.org/software/bison/manual/html_node/Multiple-Parsers.html Example of how symbols are defined with the prefix in the generated header file. ```c extern CSTYPE clval; int cparse (void); ``` -------------------------------- ### Define api.token.prefix usage Source: https://www.gnu.org/software/bison/manual/html_node/_0025define-Summary.html Example showing how to add a prefix to token names in the generated source files. ```Bison %define api.token.prefix {TOK_} %token FILE for ERROR %% start: FILE for ERROR; ``` -------------------------------- ### Override start symbol with %start Source: https://www.gnu.org/software/bison/manual/html_node/Start-Decl.html Use the %start declaration followed by the desired symbol to define the grammar's start symbol. ```bison %start symbol ``` -------------------------------- ### ltcalc declarations: C and Bison setup Source: https://www.gnu.org/software/bison/manual/html_node/Ltcalc-Declarations.html Declarations for the location tracking calculator, identical to the infix notation calculator. Includes C prologue with math.h and function prototypes, Bison declarations for value type and token, operator precedence, and grammar start marker. No location-specific declarations are needed; the default location type is used. ```c /* Location tracking calculator. */ %{ #include int yylex (void); void yyerror (char const *); %} /* Bison declarations. */ %define api.value.type {int} %token NUM %left '-' '+' %left '*' '/' %precedence NEG %right '^' %% /* The grammar follows. */ ``` -------------------------------- ### Example with %lex-param, %parse-param, and %param Source: https://www.gnu.org/software/bison/manual/html_node/Pure-Calling.html Shows how to use the directives to add parameters to yylex and yyparse, and the resulting signatures. ```APIDOC ## Example: Adding parameters to yylex and yyparse ### Directives %lex-param {scanner_mode *mode} %parse-param {parser_mode *mode} %param {environment_type *env} ### Resulting Signatures (without pure) int yylex (scanner_mode *mode, environment_type *env); int yyparse (parser_mode *mode, environment_type *env); ### Resulting Signatures (with %define api.pure full) int yylex (YYSTYPE *lvalp, scanner_mode *mode, environment_type *env); int yyparse (parser_mode *mode, environment_type *env); ### Resulting Signatures (with %define api.pure full and %locations) int yylex (YYSTYPE *lvalp, YYLTYPE *llocp, scanner_mode *mode, environment_type *env); int yyparse (parser_mode *mode, environment_type *env); ``` -------------------------------- ### Using %initial-action with %parse-param Source: https://www.gnu.org/software/bison/manual/html_node/Initial-Action-Decl.html Example showing how to initialize location information using a file name passed via %parse-param. ```bison %parse-param { char const *file_name }; %initial-action { @$.initialize (file_name); }; ``` -------------------------------- ### Merger Signature Examples Source: https://www.gnu.org/software/bison/manual/html_node/Merging-GLR-Parses.html Examples of merger function signatures based on symbol types. ```c YYSTYPE stmt_merge (YYSTYPE x0, YYSTYPE x1); ``` ```bison %type stmt; ``` ```bison %union { Node *node; ... }; %type stmt; ``` ```c Node *stmt_merge (YYSTYPE x0, YYSTYPE x1); ``` -------------------------------- ### Define Prologue with Macros and Includes Source: https://www.gnu.org/software/bison/manual/html_node/Prologue.html Example of a Prologue section using %{ and %} delimiters to define macros and include header files. ```c %{ #define _GNU_SOURCE #include #include "ptypes.h" %} ``` -------------------------------- ### Dangling Alias Example Source: https://www.gnu.org/software/bison/manual/html_node/Diagnostics.html Example of a string literal incorrectly used as a nonterminal alias. ```bison %type cond "condition" ``` -------------------------------- ### void step() Source: https://www.gnu.org/software/bison/manual/html_node/C_002b_002b-location.html Moves `begin` onto `end`. ```APIDOC ## void step() ### Description Move `begin` onto `end`. ### Method Method on location ### Signature `void step()` ``` -------------------------------- ### Custom Syntax Error Function Example Source: https://www.gnu.org/software/bison/manual/html_node/C_002b_002b-Parser-Context.html Example implementation of report_syntax_error using the context methods. ```APIDOC ## Custom Syntax Error Function Example ### Description Example implementation of report_syntax_error using the context methods. This implementation is inappropriate for internationalization, see the c/bistromathic example for a better alternative. ### Code void yy::parser::report_syntax_error (const context& ctx) { int res = 0; std::cerr << ctx.location () << ": syntax error"; // Report the tokens expected at this point. { enum { TOKENMAX = 5 }; symbol_kind_type expected[TOKENMAX]; int n = ctx.expected_tokens (ctx, expected, TOKENMAX); for (int i = 0; i < n; ++i) std::cerr << i == 0 ? ": expected " : " or " << symbol_name (expected[i]); } // Report the unexpected token. { symbol_kind_type lookahead = ctx.token (); if (lookahead != symbol_kind::S_YYEMPTY) std::cerr << " before " << symbol_name (lookahead)); } std::cerr << '\n'; } ``` -------------------------------- ### yylex with pure parser Source: https://www.gnu.org/software/bison/manual/html_node/Pure-Calling.html Example of yylex signature when using %define api.pure full, showing how to pass values back through pointers. ```APIDOC ## yylex (pure parser) ### Description Defines the yylex function for a pure parser, where global variables yylval and yylloc are replaced by pointer arguments. ### Signature int yylex (YYSTYPE *lvalp, YYLTYPE *llocp) ### Parameters - **lvalp** (YYSTYPE *) - Required - Pointer to store the semantic value of the token. - **llocp** (YYLTYPE *) - Optional - Pointer to store the textual location of the token. Omit if the grammar does not use '@' constructs. ### Return Value Returns the token kind (e.g., INT). ### Example ```c int yylex (YYSTYPE *lvalp, YYLTYPE *llocp) { ... *lvalp = value; /* Put value onto Bison stack. */ return INT; /* Return the kind of the token. */ ... } ``` ``` -------------------------------- ### Pascal type declaration examples Source: https://www.gnu.org/software/bison/manual/html_node/Simple-GLR-Parsers.html Examples of Pascal type declarations that illustrate the ambiguity between subrange and enumerated types. ```pascal type subrange = lo .. hi; type enum = (a, b, c); ``` ```pascal type subrange = (a) .. b; ``` ```pascal type enum = (a); ``` -------------------------------- ### Example session using rpcalc Source: https://www.gnu.org/software/bison/manual/html_node/Rpcalc-Compile.html Shows an interactive session with the rpcalc executable, demonstrating arithmetic operations, unary minus (n), exponentiation (^), and the end-of-file indicator (^D). ```shell $ `rpcalc` `4 9 +` ⇒ 13 `3 7 + 3 4 5 *+-` ⇒ -13 `3 7 + 3 4 5 * + - n` Note the unary minus, ‘n’ ⇒ 13 `5 6 / 4 n +` ⇒ -3.166666667 `3 4 ^` Exponentiation ⇒ 81 `^D` End-of-file indicator $ ``` -------------------------------- ### Typed Midrule Action Example Source: https://www.gnu.org/software/bison/manual/html_node/Typed-Midrule-Actions.html An example of a midrule action with a specified type tag, ensuring proper destructor and printer functionality. ```bison stmt: "let" '(' var ')' { // *** $$ = push_context (); // *** declare_variable ($3); } stmt { $$ = $6; pop_context ($5); // *** } ``` -------------------------------- ### Sample run of calc Source: https://www.gnu.org/software/bison/manual/html_node/Infix-Calc.html Example usage of the compiled calc program showing arithmetic operations and precedence handling. ```bash $ `calc` `4 + 4.5 - (34/(8*3+-3))` 6.880952381 `-56 + 2` -54 `3 ^ 2` 9 ``` -------------------------------- ### driver.hh: CPP guard and includes Source: https://www.gnu.org/software/bison/manual/html_node/Calc_002b_002b-Parsing-Driver.html Starts the driver.hh header with an include guard and standard library includes, plus the parser.hh header. ```cpp #ifndef DRIVER_HH # define DRIVER_HH # include # include # include "parser.hh" ``` -------------------------------- ### Example of an expression grammar rule Source: https://www.gnu.org/software/bison/manual/html_node/Rules-Syntax.html A concrete example showing how two 'exp' groupings and a '+' token form a larger 'exp' grouping. ```bison exp: exp '+' exp; ``` -------------------------------- ### Implementation file macro definitions Source: https://www.gnu.org/software/bison/manual/html_node/Multiple-Parsers.html Shows how api.prefix adds macro definitions to the implementation file to substitute original names with prefixed names. ```c #define YYSTYPE CTYPE #define yyparse cparse #define yylval clval ... YYSTYPE yylval; int yyparse (void); ``` -------------------------------- ### Configure api.prefix and Flex yylex prototype Source: https://www.gnu.org/software/bison/manual/html_node/Multiple-Parsers.html Example of using %define api.prefix to rename symbols and declaring the Flex scanner prototype in the provides section. ```bison %define api.prefix {c} // Emitted in the header file, after the definition of YYSTYPE. %code provides { // Tell Flex the expected prototype of yylex. #define YY_DECL \ int clex (CSTYPE *yylval, CLTYPE *yylloc) // Declare the scanner. YY_DECL; } ``` -------------------------------- ### Untyped Midrule Action Example Source: https://www.gnu.org/software/bison/manual/html_node/Typed-Midrule-Actions.html An example of a midrule action without a specified type tag, which may lead to issues with error recovery and destructors. ```bison stmt: "let" '(' var ')' { $$ = push_context (); // *** declare_variable ($3); } stmt { $$ = $6; pop_context ($5); // *** } ``` -------------------------------- ### Impure Push Parser Usage Example Source: https://www.gnu.org/software/bison/manual/html_node/Push-Decl.html Example of using a nonreentrant push parser, which relies on the global yychar variable and should only have one instance at a time. ```C extern int yychar; int status; yypstate *ps = yypstate_new (); do { yychar = yylex (); status = yypush_parse (ps); } while (status == YYPUSH_MORE); yypstate_delete (ps); ``` -------------------------------- ### Grammar that is not LR(1) (ids.y) Source: https://www.gnu.org/software/bison/manual/html_node/Counterexamples.html An example grammar that is not LR(1) and requires a stronger parser. It is used to show counterexamples when the search cannot find an ambiguous example. ```bison %token ID %% s: a ID a: expr expr: %empty | expr ID ',' ``` -------------------------------- ### int getDebugLevel() Source: https://www.gnu.org/software/bison/manual/html_node/D-Parser-Interface.html Get the tracing level. ```APIDOC ## Method: int getDebugLevel() ### Description Get the tracing level. Currently its value is either 0, no trace, or nonzero, full tracing. ### Returns - int - The current tracing level. ``` -------------------------------- ### Lexical analyzer includes and comments Source: https://www.gnu.org/software/bison/manual/html_node/Rpcalc-Lexer.html Initial setup for the lexical analyzer including necessary headers and documentation comments. ```c /* The lexical analyzer returns a double floating point number on the stack and the token NUM, or the numeric code of the character read if not a number. It skips all blanks and tabs, and returns 0 for end-of-input. */ #include #include ``` -------------------------------- ### %code top example in C Source: https://www.gnu.org/software/bison/manual/html_node/_0025code-Summary.html Shows the %code top qualifier used to insert code near the top of the parser implementation file, e.g., defining _GNU_SOURCE and including stdio.h. This is for C/C++ and is only needed when code must appear much earlier than the default location. ```c %code top { #define _GNU_SOURCE #include } ``` -------------------------------- ### Custom report_syntax_error function Source: https://www.gnu.org/software/bison/manual/html_node/C_002b_002b-Parser-Context.html Example implementation of the required report_syntax_error method for the C++ parser. Uses ctx.location(), ctx.expected_tokens(), ctx.token(), and symbol_name(). Inappropriate for internationalization; see the c/bistromathic example for a better alternative. A yyerror function is still required. ```cpp void yy::parser::report_syntax_error (const context& ctx) { int res = 0; std::cerr << ctx.location () << ": syntax error"; // Report the tokens expected at this point. { enum { TOKENMAX = 5 }; symbol_kind_type expected[TOKENMAX]; int n = ctx.expected_tokens (ctx, expected, TOKENMAX); for (int i = 0; i < n; ++i) std::cerr << i == 0 ? ": expected " : " or " << symbol_name (expected[i]); } // Report the unexpected token. { symbol_kind_type lookahead = ctx.token (); if (lookahead != symbol_kind::S_YYEMPTY) std::cerr << " before " << symbol_name (lookahead)); } std::cerr << '\n'; } ``` -------------------------------- ### Sample session with mfcalc Source: https://www.gnu.org/software/bison/manual/html_node/Multi_002dfunction-Calc.html Shows a sample interactive session with the mfcalc calculator. It demonstrates assigning pi, computing sin(pi), using multiple assignment (alpha = beta1 = 2.3), and nested function calls like exp(ln(beta1)). The output shows the calculator's results with six decimal places. ```text $ `mfcalc` `pi = 3.141592653589` ⇒ 3.1415926536 ``` ```text `sin(pi)` ⇒ 0.0000000000 ``` ```text `alpha = beta1 = 2.3` ⇒ 2.3000000000 `alpha` ⇒ 2.3000000000 `ln(alpha)` ⇒ 0.8329091229 `exp(ln(beta1))` ⇒ 2.3000000000 $ ``` -------------------------------- ### Grammar start marker Source: https://www.gnu.org/software/bison/manual/html_node/Mfcalc-Rules.html The beginning of the grammar section. ```bison %% /* The grammar follows. */ ``` -------------------------------- ### Sample run of mfcalc with debug traces (command and output) Source: https://www.gnu.org/software/bison/manual/html_node/Mfcalc-Traces.html This command runs mfcalc with the -p flag and pipes an expression to it. The output shows the initial trace lines: starting parse, entering state 0, reducing the first rule (line 34) without reading a token, and entering state 1. Traces are sent to standard error. ```shell $ `echo 'sin(1-1)' | ./mfcalc -p` Starting parse Entering state 0 Reducing stack by rule 1 (line 34): -> $$ = nterm input () Stack now 0 Entering state 1 ``` -------------------------------- ### File getDebugStream() Source: https://www.gnu.org/software/bison/manual/html_node/D-Parser-Interface.html Get the stream used for tracing the parsing. ```APIDOC ## Method: File getDebugStream() ### Description Get the stream used for tracing the parsing. It defaults to stderr. ### Returns - File - The current debug stream. ``` -------------------------------- ### driver.cc: includes Source: https://www.gnu.org/software/bison/manual/html_node/Calc_002b_002b-Parsing-Driver.html Includes the driver.hh and parser.hh headers for the implementation. ```cpp #include "driver.hh" #include "parser.hh" ``` -------------------------------- ### boolean getErrorVerbose() Source: https://www.gnu.org/software/bison/manual/html_node/D-Parser-Interface.html Get the option to produce verbose error messages. ```APIDOC ## Method: boolean getErrorVerbose() ### Description Get the option to produce verbose error messages. These are only available with '%define parse.error detailed', which also turns on verbose error messages. ### Returns - boolean - The current verbose error setting. ``` -------------------------------- ### context.location Source: https://www.gnu.org/software/bison/manual/html_node/C_002b_002b-Parser-Context.html Method on context to get the location of the syntax error (that of the lookahead). ```APIDOC ## context.location ### Description The location of the syntax error (that of the lookahead). ### Method const location & location() const ### Return Value const location & - The location of the syntax error. ``` -------------------------------- ### Bison parameter directives Source: https://www.gnu.org/software/bison/manual/html_node/Pure-Calling.html Example of using %lex-param, %parse-param, and %param to pass additional arguments to the parser and lexer. ```bison %lex-param {scanner_mode *mode} %parse-param {parser_mode *mode} %param {environment_type *env} ``` -------------------------------- ### Define pseudo start-symbols in Bison Source: https://www.gnu.org/software/bison/manual/html_node/Multiple-start_002dsymbols.html Introduce new tokens to act as switches from the real start-symbol to simulate multiple entry points. ```bison %token START_FOO START_BAR; %start start; start: START_FOO foo | START_BAR bar; ``` -------------------------------- ### Example reportSyntaxError implementation in D Source: https://www.gnu.org/software/bison/manual/html_node/D-Scanner-Interface.html Shows a user-defined reportSyntaxError method for the Lexer interface, used when '%define parse.error custom' is set. It writes the location and syntax error message, reports expected tokens (up to TOKENMAX=5), and reports the unexpected token. Note: this implementation is not internationalized; see the c/bistromathic example for a better alternative. ```D public void reportSyntaxError(YYParser.Context ctx) { stderr.write(ctx.getLocation(), ": syntax error"); // Report the expected tokens. { immutable int TOKENMAX = 5; YYParser.SymbolKind[] arg = new YYParser.SymbolKind[TOKENMAX]; int n = ctx.getExpectedTokens(arg, TOKENMAX); if (n < TOKENMAX) for (int i = 0; i < n; ++i) stderr.write((i == 0 ? ": expected " : " or "), arg[i]); } // Report the unexpected token which triggered the error. { YYParser.SymbolKind lookahead = ctx.getToken(); stderr.writeln(" before ", lookahead); } } ``` -------------------------------- ### yyparse Source: https://www.gnu.org/software/bison/manual/html_node/Table-of-Symbols.html The parser function produced by Bison; call this function to start parsing. ```APIDOC ## yyparse ### Description The parser function produced by Bison; call this function to start parsing. ### Type Function ``` -------------------------------- ### %define api.namespace example Source: https://www.gnu.org/software/bison/manual/html_node/_0025define-Summary.html Shows how to set the namespace for the parser class. Bison uses the namespace verbatim in references like foo::bar::parser::value_type, but splits it to open namespaces. ```bison %define api.namespace {foo::bar} ``` ```cpp foo::bar::parser::value_type ``` ```cpp namespace foo { namespace bar { class position; class location; } } ``` -------------------------------- ### Midrule-Value Warning Output Source: https://www.gnu.org/software/bison/manual/html_node/Midrule-Action-Translation.html Example output from Bison when midrule-value warnings are triggered. ```text mid.y:2.6-13: **warning**: unset value: $$ 2 | exp: **{ a(); }** "b" { $$ = c(); } { d(); } "e" { f = $1; }; | **^~~~~~~~** ``` ```text mid.y:2.19-31: **warning**: unused value: $3 2 | exp: { a(); } "b" **{ $$ = c(); }** { d(); } "e" { f = $1; }; | **^~~~~~~~~~~~~** ``` -------------------------------- ### Counterexample for reduce/reduce conflict on tokens $end, "word" in sequence.y Source: https://www.gnu.org/software/bison/manual/html_node/Counterexamples.html Shows the counterexample for the reduce/reduce conflict on tokens $end and "word" in sequence.y. It displays the example and both reduce derivations. ```text sequence.y: **warning**: reduce/reduce conflict on tokens $end, "word" [**-Wcounterexamples**] Example: • First reduce derivation sequence ↳ 1: • Example: • Second reduce derivation sequence ↳ 2: maybeword ↳ 4: • ``` -------------------------------- ### Precedence Directive Example Source: https://www.gnu.org/software/bison/manual/html_node/Diagnostics.html Grammar demonstrating useless precedence and associativity directives. ```bison %nonassoc "=" %left "+" %left "*" %precedence "(" ``` ```bison %% stmt: exp | "var" "=" exp ; ``` ```bison exp: exp "+" exp | exp "*" "number" | "(" exp ")" | "number" ; ``` -------------------------------- ### java.io.PrintStream getDebugStream() Source: https://www.gnu.org/software/bison/manual/html_node/Java-Parser-Interface.html Get the stream used for tracing the parsing. It defaults to System.err. ```APIDOC ## java.io.PrintStream getDebugStream() ### Description Get the stream used for tracing the parsing. It defaults to System.err. ### Method getDebugStream ### Endpoint getDebugStream() ### Returns - **java.io.PrintStream** - The current debug stream. ``` -------------------------------- ### driver.cc: constructor Source: https://www.gnu.org/software/bison/manual/html_node/Calc_002b_002b-Parsing-Driver.html Initializes trace_parsing and trace_scanning to false, and sets default variables 'one' and 'two'. ```cpp driver::driver () : trace_parsing (false), trace_scanning (false) { variables["one"] = 1; variables["two"] = 2; } ```