Are recursive boost-spirit grammars allowed?

浪子不回头ぞ 提交于 2019-12-09 03:13:58

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/12616766/are-recursive-boost-spirit-grammars-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!