tutorial 1 -- hello world β
This time, let's make the program that displays a text in acceptance of rule.
Do learn about semantic actions.
The Grammar File
%token Hello World; %namespace hello_world; %dont_use_stl; HelloWorld<int> : [Greet] Hello World;
The difference from hello0.cpg
is that a semantic action was specified at Line 5.
By that, if "HelloWorld"
rule was accepted, then the member function Greet
of SemanticAction
will be called.
The Calling File
#include <iostream> #include "hello1.hpp" struct SemanticAction { void syntax_error(){} void stack_overflow(){} void upcast( int& x, int y ) { x = y; } int Greet() { std::cout << "hello world" << std::endl; return 0; } }; int main( int, char** ) { SemanticAction sa; hello_world::Parser< int, SemanticAction > parser( sa ); parser.post( hello_world::token_Hello, 0 ); parser.post( hello_world::token_World, 0 ); parser.post( hello_world::token_eof, 0 ); return 0; }
Two lines added to SemanticAction
.
At Line 7, upcast
is a function to provide conversion
from each type of non-terminal symbols, to the "type of the whole set of semantic values",
given as a template parameter when Parser
is instantiated.
If there is one or more semantic action functions, then you must define this function for safe type conversion.
This upcast
function defines y-to-x conversion.
This time, the acceptance result type of "HelloWorld"
of Greet
defined
in the grammar file, is int.
The type of whole semantic values given as the 1st template paramter of the parser, is also int.
So, "void upcast( int& x, int y ) { x = y; }"
is OK.
Line 9 is the semantic action of this tutorial main theme.
Each type of the parameters and return value of semantic action function are defined by the grammar rule.
Let's see HelloWorld
again.
HelloWorld<int> : [Greet] Hello World;
This definition determines:
- The type of this rule (== the return value of the semantic action) is the int type, specified by
HelloWorld<int>
. - There is no parameter.
Execution
Greet
will be executed at rule acceptance.
"hello world"
will be outputted to the standard output.