...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Semantic actions may be attached to any point in the grammar specification.
They allow to call a function or function object in order to provide the
value to be output by the parser attached to the semantic action. Semantic
actions are associated with a parser using the syntax p[]
, where p
is an arbitrary parser expression.
// forwards to <boost/spirit/home/qi/action.hpp> #include <boost/spirit/include/qi_action.hpp>
Also, see Include Structure.
Notation
a
, p
Instances of a parser, P
A
Attribute type exposed by a parser, a
fa
A (semantic action) function with signature void(Attrib&, Context, bool&)
. The third parameter is a boolean
flag that can be set to false to force the parser to fail. Both
Context
and the boolean
flag are optional. For more information see below.
Attrib
The attribute obtained from the parse.
Context
The type of the parser execution context. For more information see below.
Semantics of an expression is defined only where it differs from, or is
not defined in UnaryParser
.
Expression |
Semantics |
---|---|
|
If |
The possible signatures for functions to be used as semantic actions are:
template <typename Attrib> void fa(Attrib& attr); template <typename Attrib, typename Context> void fa(Attrib& attr, Context& context); template <typename Attrib, typename Context> void fa(Attrib& attr, Context& context, bool& pass);
The function or function object is expected to return the value to generate
output from by assigning it to the first parameter, attr
.
Here Attrib
is the attribute
type of the parser attached to the semantic action.
The type Context
is the
type of the parser execution context. This type is unspecified and depends
on the context the parser is invoked in. The value, context
used by semantic actions written using Phoenix
to access various context dependent attributes and values. For more information
about Phoenix placeholder
expressions usable in semantic actions see Nonterminal
.
The third parameter, pass
,
can be used by the semantic action to force the associated parser to fail.
If pass is set to false
the
action parser will immediately return false
as well, while not invoking p
and not generating any output.
Expression |
Attribute |
---|---|
|
|
The complexity of the action parser is defined by the complexity of the parser the semantic action is attached to and the complexity of the function or function object used as the semantic action.
Examples for semantic actions can be found here: Examples of Semantic Actions.