Are recursive boost-spirit grammars allowed?

后端 未结 1 1423
清歌不尽
清歌不尽 2021-01-13 07:38

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 t

相关标签:
1条回答
  • 2021-01-13 08:04

    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

    0 讨论(0)
提交回复
热议问题