Learning Spirit 2
Phase Level vs. Character Level
The PARSE function has four forms of overload.
Template
PARSE_INFO
Parse
(
Iteratort Const & First,
Iteratort Const & Last,
Parser
);
Template
PARSE_INFO
Parse
(
Chart Const * STR,
Parser
);
The above two are PARSEs of the character level.
Template
PARSE_INFO
Parse
(
Iteratort Const & First,
Iteratort Const & Last,
Parser
Parser
);
Template
PARSE_INFO
Parse
(
Chart Const * STR,
Parser
Parser
);
The above is the phrase level PARSE.
The phrase level uses a Skip Parser parameter to filter the "blank" symbol in the input (the blank meaning is determined by the SKIP parameter, which can be space, carriage return, or even "/*...//" this C language note) . The character level is strictly analyzed for each character.
E.g:
Parse ("a
123 "
, CH_P ('a') >> INT_P, Space_P) == true; // Phase Level
Parse ("a
123 "
, ch_p ('a') >> int_P) == true; // character Level
Parse ("a
123 "
, CH_P ('a') >> INT_P) == FALSE;
Semantic action
Semantic actions refer to the action executed during the analysis. Each Parser can come with one or more semantic actions. This action will be called when this Parser matches a period of input.
Semantic actions can be a function:
Template
Void Func (Iterator First, Iterator Last);
It can also be an imitation function:
Struct myfunctor
{
Template
Void Operator () (Iterator First, Iterator Last) Const;
}
Note () overloaded Const can't go.
It can be used like this:
Rule <> r = (a >> b) [& func];
Rule <> s = (a [myfunctor ()] | b [& func]) [& func]; special semantic actions:
For some special Parser, for example: int_p, ch_p. In addition to the above semantic actions, semantic actions related to their types are also provided.
For INT_P: Void func (int Val); for CH_P: Void Func (CHAR C).
So, now we can complete the topic of our last tutorial.
#include
#include
#include
Using namespace std;
USING NAMESPACE boost :: spirit;
Struct Assign
{
INT & VAR;
Assign (INT & V): VAR (V) {}
Void Operator () (int val) Const
{
VAR = VAL;
}
}
Struct Increase
{
INT & VAR;
Increase (int & v): var (v) {}
Void Operator () (int val) Const
{
VAR = VAL;
}
}
int main ()
{
INT country;
Rule
= int_P [Assign (count)]
>> * (CH_P (',')
>> INT_P [Increase (count)]);
String Str;
While (GetLine (CIN, STR))
{
PARSE_INFO <> info = parse (str.c_str (), s, space_p);
IF (Info.full)
{
Cout << "Parse Successful." << endl;
COUT << "result is" << count << endl;
}
Else
{
Cout << "Parse Fail." << Endl;
}
}
Return 0;
}