5

I am about to write a parser for a mathematica-like language and have found out, that it would be nice to sometimes invoke my spirit grammar for subparts of the expression to parse.

i.e. If I am about to parse

a+b*c+d 

it would be handy to call parse() on the 'b*c' part while querying the '+' sign.

Is this possible to do while using the same instance of my grammar? (The grammar parameter would be '*this')

Though I am not yet fully convinced whether this is the best way to accomplish this particular task, I find the question rather interesting, since I could not find anything in the docs.

Obvously I should not depend on class-local or global variables if I used this technique. But I would like to know if it is principally allowed by the design of spirit.

EDIT:

My grammar instances look as follows:

class MyGrammar : public boost::spirit::qi::grammar<...>  
{  
    /* a few rules. Some with local and/or inherited attributes */  
    MyGrammar( void )  
    {
         /* assign all the rules, use a few 'on_error' statements */
         // In one or two rules I would like to invoke parse(...,*this,...)  
         // on a subrange of the expression
    }
}  

Thanks!

sehe
  • 374,641
  • 47
  • 450
  • 633
iolo
  • 1,090
  • 1
  • 9
  • 20
  • 1
    This is a highly non-specific question with a meaningless code snippet. Why don't you start with the samples in the documentation: http://boost-spirit.com/home/doc/ – sehe Sep 27 '12 at 13:27
  • @sehe How is this non-specific? I want to know if boost-spirit supports recursive calls to parse() with the same grammar instance. (Yes or no) – iolo Sep 27 '12 at 13:50

1 Answers1

8

Of course you can:

// In one or two rules I would like to invoke parse(...,*this,...)  
// on a subrange of the expression

^ That is not how rules are composed in a declarative grammar. You seem to think of this in procedural terms (which may indicate you could have previous experience writing recursive-descent parsers?).


Off the top of my mind a simple expression grammar in spirit could look like this:

  literal     = +qi::int_;
  variable    = lexeme [ qi::alpha >> *qi::alnum ];
  term        =  literal 
               | variable 
               | (qi::lit('(') > expression >> ')');

  factor      = term >> *(qi::char_("+-") >> term);
  expression  = factor >> *(qi::char_("*/%") >> term);

Note the recursion in the last branch of term: it parsers parenthesized expressions.

This simplistic sample won't actually result in a parse tree that reflects operator precedence. But the samples and tests in the Spirit library contain many examples that do.

See also other answers of mine that show how this works in more detail (with full samples):

Hope that helps

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Ok. Thank you. I actually ended up implementing it using plain rules. (It was easier than I first thought) - But nevertheless. You answered the question! – iolo Sep 27 '12 at 13:52