This directory contains simple examples of Bison grammar files in C.
Some of them come from the documentation, which should be installed together with Bison. The URLs are provided for convenience.
The first example is that of a simple double-precision Reverse Polish Notation calculator (a calculator using postfix operators). This example provides a good starting point, since operator precedence is not an issue.
Extracted from the documentation: Reverse Polish Notation Calculator.
This example is slightly more complex than rpcalc: it features infix operators (1 + 2
, instead of 1 2 +
in rpcalc), but it does so using a unambiguous grammar of the arithmetic instead of using precedence directives (%left, etc.).
A more complete C example: a multi-function calculator. More complex than the previous example. Using precedence directives to support infix operators.
Extracted from the documentation: Multi-Function Calculator: mfcalc.
The calculator with precedence directives and location tracking. It uses Flex to generate the scanner.
This example builds on top of the previous one to provide a reentrant parser. Such parsers can be called concurrently in different threads, or even recursively. To demonstrate this feature, expressions in parentheses are tokenized as strings, and then recursively parsed from the parser. So (((1)+(2))*((3)+(4)))
uses eight parsers, with a depth of four.
All the previous examples are so called “pull parsers”: the user invokes the parser once, which repeatedly calls the scanner until the input is drained.
This example demonstrates the “push parsers”: the user calls the scanner to fetch the next token, passes it to the parser, and repeats the operation until the input is drained.
This example is a straightforward conversion of the ‘calc’ example to the push-parser model.
This example demonstrates best practices when using Bison.
error
token to signal lexical errors and enter error recovery.yyexpected_tokens
.> 123 456 1.5-7: syntax error: expected end of file or + or - or * or / or ^ before number 1 | 123 456 | ^~~