|
Boost Users : |
From: Tim Robertson (timr_at_[hidden])
Date: 2004-10-25 15:52:22
Hi,
I'm looking for advice on ways to "nest" spirit grammars that use
semantic actions.
In the past, I have written a spirit grammar that parses 2-dimensional
array data from a file, and puts the data into an array object of my
choosing. To do this, the grammar defines a new functor (array_insert)
and calls the functor whenever a new array element is parsed. The
functor puts the element into a reference to the destination object,
held within the grammar:
struct array_grammar
{
array_grammar(MyMatrix & m) : _inserter(m) {}
struct array_inserter
{
array_inserter(MyMatrix & m) : _m(m) {}
// operator() defined here...
MyMatrix & _m;
}
// ...the usual grammar components...
array_inserter _inserter;
};
This works, as expected. However, I now have to write a parser for a
file containing a collection of 2D arrays, where each array is
delimited by tags (say, "BEGIN" and "END"). I would like to push each
array into a std::vector of MyMatrix objects. Thus, it would be nice
if I could re-use the array_grammar, and write a grammar which uses it
to parse each array in the larger file:
struct multi_array_grammar
{
multi_array_grammar(std::vector<MyMatrix> & v) : _inserter(v) {}
struct array_inserter
{
array_inserter(std::vector<MyMatrix> & v) : _v(v) {}
// ... operator(), etc.
std::vector<MyMatrix> & _v;
};
template <typename ScannerT>
struct definition
{
definition(multi_array_grammar const & self)
{
array_begin = str_p("BEGIN");
array_end = str_p("END");
// Problem: how to create array_grammar with correct
reference?
array_grammar array(???);
r = array_begin >> +array >> array_end;
}
};
array_inserter _inserter;
};
The problem is that I can't figure out how to instantiate an
array_grammar (which requires a reference to the current MyMatrix
object) in order to parse the individual arrays.
I have solved this problem by creating a functor in multi_array_grammar
which calls the parse function for array_grammar directly, but this
seems ugly to me. Do any of you have a better way?
-Tim
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net