使用Boost Spirit的指数运算符的表达式语法

时间:2013-07-12 16:01:51

标签: c++ boost-spirit context-free-grammar boost-spirit-qi associativity

我想将指数运算符添加到expression grammar provided in the Boost spirit samples

BNF语法如下:(请参阅此答案,例如:"Unambiguous grammar for exponentiation operation"

E -> E + T | E - T | T
T -> T * F | T / F | X
X -> X ^ Y | Y
Y -> i | (E)

我将其翻译为Boost精神:

    template <typename Iterator>
struct calculator : qi::grammar<Iterator, ascii::space_type>
{
    calculator() : calculator::base_type(expression)
    {
        qi::uint_type uint_;

        expression =
        term
        >> *(   ('+' >> term            [&do_add])
             |   ('-' >> term            [&do_subt])
             )
        ;

        term =
        factor
        >> *(   ( '*' >> factor          [&do_mult])
             |  ('x' >> factor          [&do_mult])
             |   ('/' >> factor          [&do_div])
             );

        factor= expo >> *( '^' >> expo [&do_power]);

        expo =
           uint_                           [&do_int]
        |  '(' >> expression >> ')'
        |  ('-' >> expo[&do_neg])
        |  ('+' >> expo)

        ;
    }

    qi::rule<Iterator, ascii::space_type> expression, term, factor, expo;
};

问题是这种情况下的^运算符是左关联的,即2 ^ 3 ^ 4被错误地解析为(2 ^ 3) ^ 4而不是2^ (3 ^ 4)

我怎样才能重写语法,以便^成为正确的关联?显然我在factor的定义中使用的Kleene星是不正确的。将语法翻译成Spirit代码的方法是什么?似乎有一种方法可以从左派的语法到精神的实现,但我不能立即看到它。

以更正式的方式,Spirit代码看起来像这样(在我尝试添加指数之前):

E = T ( +T | -T ) *
T = F ( xF | /F ) *
F = int | ( E ) | +F | -F

左边的grammmar是

E  =  T E'
E' = +T E' | -T E' | epsilon
T  =  F T'
T' = *F T' | /F T' | epsilon
F  = ( E ) | int | +F | -F

1 个答案:

答案 0 :(得分:3)

我认为你可以使用正确的递归来获得你想要的东西:

factor= expo >> -('^' >> factor [&do_power]);

我不确定所需的评估顺序;你可能想要像

这样的东西
factor= expo [&do_power] >> -('^' >> factor);

代替。

这是一个简单的测试程序,显示它如何处理 2^(6/2)^4+1

  

修改查看 Coliru

上的
Type an expression...or [q or Q] to quit
2^(6/2)^4+1

push 2
push 6
push 2
divide
push 4
exp
exp
push 1
add
-------------------------
Parsing succeeded

完整代码

#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
#define BOOST_SPIRIT_DEBUG

#include <boost/spirit/include/qi.hpp>

namespace client
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;

    ///////////////////////////////////////////////////////////////////////////////
    //  Semantic actions
    ////////////////////////////////////////////////////////1///////////////////////
    namespace
    {
        void do_int(int n)  { std::cout << "push " << n << std::endl; }
        void do_add()       { std::cout << "add\n"; }
        void do_subt()      { std::cout << "subtract\n"; }
        void do_mult()      { std::cout << "mult\n"; }
        void do_div()       { std::cout << "divide\n"; }
        void do_power()     { std::cout << "exp\n"; }
        void do_neg()       { std::cout << "negate\n"; }
    }

    ///////////////////////////////////////////////////////////////////////////////
    //  Our calculator grammar
    ///////////////////////////////////////////////////////////////////////////////
    template <typename Iterator>
        struct calculator : qi::grammar<Iterator, ascii::space_type>
    {
        calculator() : calculator::base_type(expression)
        {
            qi::uint_type uint_;

            expression = term
                >> *(   ('+' >> term            [&do_add])
                     |  ('-' >> term            [&do_subt])
                     )
                ;

            term = factor
                >> *(   ( '*' >> factor         [&do_mult])
                     |  ('x' >> factor          [&do_mult])
                     |  ('/' >> factor          [&do_div])
                     );

            factor= expo >> -('^' >> factor [&do_power]);

            expo = uint_                        [&do_int]
                |  '(' >> expression >> ')'
                |  ('-' >> expo[&do_neg])
                |  ('+' >> expo)
            ;

            BOOST_SPIRIT_DEBUG_NODES((expression)(term)(factor)(expo));
        }
      private:
        qi::rule<Iterator, ascii::space_type> expression, term, factor, expo;
    };
}

///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Expression parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type an expression...or [q or Q] to quit\n\n";

    typedef std::string::const_iterator iterator_type;
    typedef client::calculator<iterator_type> calculator;

    boost::spirit::ascii::space_type space; // Our skipper
    calculator calc; // Our grammar

    std::string str;
    while (std::getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        std::string::const_iterator iter = str.begin();
        std::string::const_iterator end = str.end();
        bool r = phrase_parse(iter, end, calc, space);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            std::cout << "-------------------------\n";
        }
        else
        {
            std::string rest(iter, end);
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "stopped at: \" " << rest << "\"\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}