Search code examples
c++parsingboost-spiritrecursive-descenttmp

boost::spirit composing grammars from grammars


I have figured out how to use spirit -- i.e., I have written a moderately complex grammar. I always take the approach of growing a program -- one subsystem at a time. I've written the data structures for a complex model which has 4 types at the highest level.

I would like to use the grammar composed from rules approach to parse the top level types one type at a time -- i.e., I want to write 4 grammars with one top level grammar. If this is possible (which I am beginning to doubt), could someone please post a snippet or a reference to a project that does this.

One top level grammar with 50+ (possible a lot more) rules (for proper error handling) does not sound like fun (TMP code is volatile / slow to compile, and provides useless error messages).


Solution

  • simplified from an actual program, Qi should work the same as Karma.

    template<class Iter>
    struct subgrammar_1
    : karma::grammar<Iter, ...>
    {
        ...
    }
    
    template<class Iter>
    struct top_level_grammar
    : karma::grammar<Iter, ...>
    {
        top_level_grammar() : top_level_grammar::base_type(start)
        {
            start %= r1 | r2;
        }
        karma::rule<Iter, ...> r1;
        subgrammar_1<Iter> r2;
        ...
    }