The C++ code generation target

Note: The C++ target was last synced with the 3.4 version of ANTLR

The C++ target closely follows the C target. The API and runtime behavior are consistent to the extent possible.

Please send bug reports, feedback, patches to the antlr-interest mailing list

Requirements

To use generated code, you'll need to include Cpp runtime package in your include path.

Usage

Selecting Cpp output

Just add language=Cpp; to the options section of your grammar:grammar T;
options {
language=Cpp;
other options
}

...
For a grammar T.g ANTLR3 will then create the files TLexer.hpp, TLexer.cpp, TParser.hpp and TParser.cpp which contain the classes TLexer and TParser. Tree Parsers are not yet supported.

Specifying an C++ namespace  for your recognizer

You can specify that your generated recognizer should be declared within a specific namespace as shown below. By default all recognizers are generated as top-level types with no enclosing namespace. The Parser has to include the Lexer and both the lexer and Parser have to include the traits
grammar MyGrammar;

options
{
language=Cpp;
}

@parser::namespace { UserNamespace } // Or just @namespace { ... }

@lexer::namespace { UserNamespace }

// rest of grammar follows
....lexer grammar MyGrammar;

options
{
language=Cpp;
}
@includes
{
#include "UserTraits.hpp"
}
@namespace { UserNamespace }

// rest of grammar follows
....parser grammar MyGrammar;

options
{
language=Cpp;
}
@includes
{
#include "UserTraits.hpp"
#include "TLexer.hpp"
}
@namespace{ UserNamespace }

// rest of grammar follows
....

Using the generated classes

To use a grammar T.g:

#include <TParser.hpp>

using namespace UserNamespace;
int main(int argc, char* argv[])
{
TTraits::InputStreamType input(fName, ANTLR_ENC_8BIT);
TLexer lxr(&input); // TLexerNew is generated by ANTLR
TTraits::TokenStreamType tstream(ANTLR_SIZE_HINT, lxr.get_tokSource() );
TParser psr(&tstream); // TParserNew is generated by ANTLR3

psr.entry_rule();

}

Actions

This target currently supports the action scopes @lexer and @parser for global actions. The following action names are known:

Unsupported features