解析器表达式看起来没问题。
您对构建 AST 感到困惑。显然,您已决定使用语义动作来做到这一点,但您的努力太粗略,我无法了解如何(甚至决定您基于什么样本)。
本质上:您想对您似乎神奇地“将”到您的规则中的 'ADD'/'SUB' 实例做什么?
现在,您只需将实例直接用作语义操作。这会导致显示的错误消息直接告诉您该实例作为语义操作无效。
我假设您确实想使用 Phoenix 分配将二进制操作分配给暴露的属性。这看起来像:
expression = term
>> *( (lit('+') >> term[ _val = phx::construct<ADD>(_val, _1)])
| (lit('-') >> term[ _val = phx::construct<SUB>(_val, _1)])
);
您会看到这与传统的表达式语法更加匹配。
为了好玩,我根据您的Value
类型改编了一个完整的表达式解析器并创建了这个工作演示: http: //liveworkspace.org/code/3kgPJR$0
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;
namespace phx = boost::phoenix;
typedef std::function<double()> Value;
#define BINARY_FUNCTOR(name, op) \
struct name \
{ \
name(Value x, Value y): x_(x), y_(y) {} \
double operator()() { return x_() op y_(); } \
Value x_, y_; \
};
BINARY_FUNCTOR(ADD, +)
BINARY_FUNCTOR(SUB, -)
BINARY_FUNCTOR(MUL, *)
BINARY_FUNCTOR(DIV, /)
struct LIT
{
LIT(double x): x_(x) {}
double operator()() { return x_; }
double x_;
};
struct NEG
{
NEG(Value x): x_(x) {}
double operator()() { return -x_(); }
Value x_;
};
template <typename It, typename Skipper = qi::space_type>
struct parser : qi::grammar<It, Value(), Skipper>
{
parser() : parser::base_type(expression)
{
using namespace qi;
expression =
term [_val = _1]
>> *( ('+' >> term [_val = phx::construct<ADD>(_val, _1)])
| ('-' >> term [_val = phx::construct<SUB>(_val, _1)])
);
term =
factor [_val = _1]
>> *( ('*' >> factor [_val = phx::construct<MUL>(_val, _1)])
| ('/' >> factor [_val = phx::construct<DIV>(_val, _1)])
);
factor =
double_ [_val = phx::construct<LIT>(_1)]
| '(' >> expression [_val = _1] >> ')'
| ('-' >> factor [_val = phx::construct<NEG>(_1)])
| ('+' >> factor [_val = _1]);
BOOST_SPIRIT_DEBUG_NODE(expression);
BOOST_SPIRIT_DEBUG_NODE(term);
BOOST_SPIRIT_DEBUG_NODE(factor);
}
private:
qi::rule<It, Value(), Skipper> expression, term, factor;
};
Value doParse(const std::string& input)
{
typedef std::string::const_iterator It;
parser<It, qi::space_type> p;
Value eval;
auto f(begin(input)), l(end(input));
if (!qi::phrase_parse(f,l,p,qi::space,eval))
std::cerr << "parse failed: '" << std::string(f,l) << "'\n";
if (f!=l)
std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
return eval;
}
int main()
{
auto area = doParse("2 * (3.1415927 * (10*10))");
std::cout << "Area of a circle r=10: " << area() << "\n";
}
它会打印
Area of a circle r=10: 628.319