Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are recursive boost-spirit grammars allowed?

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!

like image 367
iolo Avatar asked Sep 27 '12 08:09

iolo


1 Answers

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):

  • Boost::Spirit Expression Parser

    A fullblown example with links to documentation samples and explanations of improvements of the original code by the asker

  • Boolean expression (grammar) parser in c++

  • Compilation error with a boost::spirit parser yet another approach

Hope that helps

like image 153
sehe Avatar answered Nov 15 '22 12:11

sehe