Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time
                       *** Flex Bison C++ Example ***

Author: Timo Bingmann (Mail: tb a-with-circle idlebox dot net)
Date: 2007-08-20

*** Summary ***

This example shows how to use both Flex and Bison in C++ mode. This way both
lexer and parser code and data is encapsulated into classes. Thus the lexer and
parser are fully re-entrant, because all state variables are contained in the
class objects. Furthermore multiple different lexer-parser pairs can easily be
linked into one binary, because they have different class names and/or are
located in a different namespace.

*** Website / License ***

The current example package can be downloaded from

The following just mean you can copy the example code into your program or use
it for whatever purpose without crediting me (though I would really like it if
you did):

The parts of the example code written by myself are released into the public
domain or, at your option, under the Do What The Fuck You Want To Public
License (WTFPL), which can be found in the file COPYING. There are some special
GPL license exceptions for the included source files from the Bison and Flex

The idea and method of this example is based on code from

*** Why Use These Old Tools? ***

Well, they are here to stay and they work well. These days there are much more
sophisticated C++ parser generation frameworks around:

  * Most well-known is the Boost.Spirit parser framework
  * and the ANTLR parser generator.
  * Less well known is the Common Text Transformation Library.

All these libraries do good jobs when you need to generate parsers for more
difficult grammars.

However if you write a program with one of the frameworks above, then your
users need that parser framework installed to compile your program. But Flex
and Bison require no compile-time dependencies, because they generate fully
autonomous source code. (And Flex and Bison are installed almost everywhere.) 
So far I have not found any modern parser generator which outputs independent

It is even possible to compile the generated source with Visual C++ on Windows
(worked with 8.0 aka 2005). Flex and Bison need not be installed on the windows
machine. The source package includes a VC++ solution and two project files.

*** Source and Generated Files ***

The src directory contains the following source files. Note that some of them
are automatically generated from others.

  * scanner.ll contains the Flex source for the C++ lexical scanner.
  * is generated from scanner.ll by Flex.
  * scanner.h defines the lexer class example::Scanner.
  * FlexLexer.h copied from Flex distribution. Defines the abstract lexer

  * parser.yy is the example Bison parser grammar.
  * generated from parser.yy by Bison.
  * parser.h generated from parser.yy by Bison.
  * contains nothing. Just forwards to parser.h

  * location.hh installed by Bison. Contains something required by the
    parser class.
  * position.hh same.
  * stack.hh same.

  * driver.h defines the example::Driver class, which puts together lexer
    and parser.
  * implementation for driver.h

  * expression.h defines the example's calculator node classes.
  * contains a main function to run the example calculator.

  * readme.dox doxygen explanation text, which you are reading right now.

So if you wish to create a program using a C++ Flex lexer and Bison parser,
you need to copy the following files:

  * scanner.ll, scanner.h, FlexLexer.h
  * parser.yy,
  * location.hh, position.hh, stack.hh (are created by Bison when run on
    the grammar)
  * driver.h,

--- Namespace and Library ---

The scanner, parser and driver classes are located within the example
namespace. When coding a larger program, I believe it is most convenient to put
all scanner/parser source files into a separate directory and build a static
library. Then all parts of the parser are located in a separate namespace and

*** Code Overview ***

This is a brief overview of the code's structure. Further detailed information
is contained in the doxygen documentation, comments in the source and
ultimately in the code itself.

--- Scanner ---

The input stream is first converted by the lexical scanner into tokens. The
scanner is defined by the list of regular expressions in scanner.ll . From this
file Flex generates the file, which mainly contains a function
called yylex(). This function returns the next token for the parser. For a C++
scanner the yylex() function is contained in a class, which is named
yyFlexLexer by default. It is declared in the FlexLexer.h and is derived from
the abstract FlexLexer class.

By defining the macro yyFlexLexer => ExampleFlexLexer in scanner.h, the default
name of the scanner class is changed. Furthermore to extend yylex()'s parameter
list, the class example::Scanner is derived from the ExampleFlexLexer class. It
is mainly a forwarding class. By defining the macro YY_DECL, the yylex()
function generated by Flex is renamed to example::Scanner::lex().

Another change to the default Flex code is that the token type is changed from
int to the enum example::Parser::token defined by parser.

--- Parser ---

Bison's support for C++ is much more sophisticated. In C++ mode it generates a
class named example::Parser, which is located in and declared in
parser.h . The header file also defines the scanner tokens, which must be
returned by the Flex scanner's regular expression rules. Bison's C++ skeleton
also installs the three .hh files, which contain utility classes required by
the parser.

In the example calculator the Bison code constructs a calculation node
tree. The tree's nodes are derived from CalcNode and are evaluated to output
the parsed expression's result.

--- Driver ---

The example::Driver class brings the two components scanner and parser classes
together. It is the context parameter of the parser class. The hook between
scanner object and parser object is done by defining the yylex() macro to be
"driver.lexer->lex". This way the Bison parser requests the next token from the
scanner object contained within the driver.

The example::Driver object can be accessed by the Bison actions. Therefore it
will contain a reference to the data classes filled by the parser's rules. In
the example it contains a reference to the CalcContext. Thus a refernce to a
CalcContext must be given to the constructor of example::Driver. This
CalcContext object will be filled with the parsed data.

To initiate parsing the example::Driver class contains the three functions
example::Driver::parse_stream(), example::Driver::parse_file() and

*** Example Calculator ***

The example lexer and grammar is a simple floating point arithmetic
calculator. It follows the usual operator precedence rules (sometimes called
BODMAS or PEMDAS): Parentheses, Exponentation, Multiplication/Division,

Besides these simple arithmetic operators, the program also supports
variables. These can be assigned a value and used in subsequent expressions.

It can be started interactively and will process expressions entered on the
console. The expression's parse tree is printed and then evaluated. Here some

--- snip ---
$ ./exprtest
Reading expressions from stdin
input: 4 * 1.5 + 3 * (2 ^ 4 - 4)
+ add
  * multiply
  * multiply
    - subtract
      ^ power
evaluated: 42
input: v = (2 ^ 4 - 4)
Setting variable v = 12
input: 3.5 * a
input:1.6: Unknown variable "a"
input: 3.5 * v
* multiply
evaluated: 42
input: 5 + * 6
input:1.4: syntax error, unexpected '*'
input: 5 + (4 * 4
input:1.10-9: syntax error, unexpected end of file, expecting ')'
--- snap ---

The exprtest can also be used to process text files containing
expressions. Within the file each line is parsed as an expression. Multiple
expressions can be put into one line by terminating them with a semicolon
';'. The exprtest outputs a parse tree for each parsed non-assignment line.

--- snip ---

v = (2 ^ 4 - 4); e = 2.71828

4 * 1.5 + 3 * v

6 * (2 * 2) ^ 2 / 2

--- snap ---

The above example file (included as exprtest.txt) can be processed by calling
./exprtest exprtest.txt. The program outputs the following evaluation:

--- snip ---
Setting variable v = 12
Setting variable e = 2.71828
+ add
  * multiply
  * multiply
evaluated: 42
/ divide
  * multiply
    ^ power
      * multiply
evaluated: 48
--- snap ---


Flex Bison C++ Template/Example







No packages published