首先,如果使用或者升压变体或Utree,然后我会跟他们和解,我会尽量和他们一起解决另一个话题我的问题是容易得多。 但是,我非常希望能够建立一个树一样,我有以下。
背景,忽略,如果你想直来直去的问题:我想是能够建立一个表达式树,它解析像
"({a} == 0) && ({b} > 5)"
或标准数学化表达
"(2 * a) + b"
然后,我将定义哪些a和b之前,我评估我的树,像这样:
a = 10;
double val = myExpression->Evaluate();
我的问题来自当我尝试建立尝试将字符串解析为我的表达式树。 我使用的是抽象类“表达式”,然后得出的“变量”,“常”与“二进制”表达式(它也会做一元,但它不应该影响我的问题。我一直有使用我的规则添加到树问题,所以即时通讯显然做错了什么。有一个很难包装我的头周围的属性林。
我的树如下:(tree.h中):
class BinaryExpression;
typedef double (*func)(double, double);
class Expression
{
public:
virtual double Evaluate() = 0;
};
class BinaryExpression : public Expression
{
private:
Expression* lhs;
Expression* rhs;
func method;
double Evaluate();
public:
BinaryExpression(void);
BinaryExpression(char op, Expression* lhs, Expression* rhs);
BinaryExpression(char op);
void operator()(Expression* lhs, Expression* rhs);
};
class ConstantExpression : public Expression
{
private:
double value;
public:
ConstantExpression(void);
ConstantExpression(char op);
ConstantExpression(double val);
double Evaluate();
};
// Require as many types as there are fields in expression?
static double a;
static double b;
class VariableExpression : public Expression
{
private:
char op;
public:
VariableExpression(char op);
double Evaluate();
};
BOOST_FUSION_ADAPT_STRUCT(
BinaryExpression,
(Expression*, lhs)
(Expression*, rhs)
(func, method)
)
BOOST_FUSION_ADAPT_STRUCT(
VariableExpression,
(char, op)
)
BOOST_FUSION_ADAPT_STRUCT(
ConstantExpression,
(double, op)
)
Tree.cpp
typedef double (*func)(double, double);
/////////////////////////////////////////////////////////////////////////////
// BINARY EXPRESSION
////////////////////////////////////////////////////////////////////////////
BinaryExpression::BinaryExpression(void) {}
BinaryExpression::BinaryExpression(char op, Expression* lhs, Expression* rhs)
{
this->lhs = lhs;
this->rhs = rhs;
// Example, methods are held in another header
if (op == '+')
method = Add;
else if (op == '-')
method = Subtract;
}
double BinaryExpression::Evaluate()
{
return method(lhs->Evaluate(), rhs->Evaluate());
}
BinaryExpression::BinaryExpression(char op)
{
if (op == '+')
method = Add;
else if (op == '-')
method = Subtract;
}
void BinaryExpression::operator()(Expression* lhs, Expression* rhs)
{
this->lhs = lhs;
this->rhs = rhs;
}
/////////////////////////////////////////////////////////////////////////////
// CONSTANT EXPRESSION
////////////////////////////////////////////////////////////////////////////
ConstantExpression::ConstantExpression() {}
ConstantExpression::ConstantExpression(char op)
{
this->value = op - 48;
}
ConstantExpression::ConstantExpression(double val)
{
value = val;
}
double ConstantExpression::Evaluate()
{
return value;
}
/////////////////////////////////////////////////////////////////////////////
// VARIABLE EXPRESSION
////////////////////////////////////////////////////////////////////////////
VariableExpression::VariableExpression(char op)
{
this->op = op;
}
double VariableExpression::Evaluate()
{
// a and b are defined in the header, and are used to fill in the variables we want to evaluate
if (op == 'a')
return a;
if (op == 'b')
return b;
return 0;
}
现在,如果我建立树手动这一切工作正常,所以我不认为那里有它的结构方式的问题。
这里是Grammar.h(从这里我尝试过各种事情很多意见,我可以删除它们,但我可能是值得炫耀什么,我已经试过/我想要去用它)
#include "Tree.h"
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
qi::_1_type _1;
qi::_2_type _2;
// Pass functions to boost
boost::phoenix::function<BinaryExpression> plus = BinaryExpression('+');
boost::phoenix::function<BinaryExpression> minus = BinaryExpression('-');
template <typename Iterator>
struct ExpressionParser : qi::grammar<Iterator, BinaryExpression(), ascii::space_type>
{
ExpressionParser() : ExpressionParser::base_type(expression)
{
qi::_3_type _3;
qi::_4_type _4;
qi::char_type char_;
qi::uint_type uint_;
qi::_val_type _val;
qi::raw_type raw;
qi::lexeme_type lexeme;
qi::alpha_type alpha;
qi::alnum_type alnum;
qi::bool_type bool_;
qi::double_type double_;
expression = //?
additive_expr [_val = _1]
;
//equality_expr =
// relational_expr >>
// *(lit("==") > relational_expr) [/*Semantice action to add to tree*/]
// ;
additive_expr =
primary_expr >>
( '+' > primary_expr) [plus(_val, _1)]
| ( '-' > primary_expr) [minus(_val, _1)]
;
// Also tried "_val = plus(_1, _2)"
primary_expr =
constant [_val = _1]
| variable [_val = _1]
//| '(' > expression > ')' [_val = _1]
;
string %=
'{' >> *(char_ - '}') >> '}'
;
// Returns ConstantExpression
constant =
double_ [_val = _1];
// Returns VariableExpression
variable =
char_ [_val = _1]
;
}
// constant expression = double
// variable expression = string
qi::rule<Iterator, BinaryExpression(), ascii::space_type>
expression;
qi::rule<Iterator, BinaryExpression(), ascii::space_type>
// eventually will deal with all these rules
equality_expr,
relational_expr,
logical_expr,
additive_expr,
multiplicative_expr,
primary_expr
;
qi::rule<Iterator, ConstantExpression(), ascii::space_type>
constant
;
qi::rule<Iterator, VariableExpression(), ascii::space_type>
variable
;
qi::rule<Iterator, std::string(), ascii::space_type>
string
;
};
因此,这是一个真正的黑客分开,但希望它会显示什么即时试图实现。 任何意见或建议将非常感激。 是否有一个地方有人已建成这样的树,而无需使用变体或utree一个例子。
此外抱歉,如果香港专业教育学院破惯例,为我的格式,我试图使它尽可能地易读。
这是我不清楚你的抱怨与(递归)的变体,但在这里是与你的愿望使用动态分配的节点使用“老土”树建筑随之而来的变化:
- http://liveworkspace.org/code/3VS77n$0
我有意地回避了运算符优先级的问题,在你的语法,因为
- 你的语法是不完整
- 我不知道所需的语义(毕竟,你似乎支持布尔评价为好,但我不知道怎么做)
您可以了解这些在其他的答案:
- 在C布尔表达式(语法)分析器++
- 升压::精神表达式解析器
- 用一个boost ::精神解析器编译错误显示了一个可供选择的方法
注意我如何
- 通过使用shared_ptr的删除无处不在的内存泄漏(你可以使用Boost之一,如果你没有一个TR1库)
- 我删除特定的BinaryExpression实例作为凤凰懒演员的误导重用。 相反,我做了一个本地
makebinary
现在的演员。 注意如何运营商的链(1 + 2 + 5 + 6-10)现在被支持:
additive_expr = primary_expr [ _val = _1 ] >> *(char_("-+*/") >> primary_expr) [ _val = makebinary(_1, _val, _2)] ;
我加入{var}
/
, *
和(expr)
支持
用于显示添加了序列化( Print
虚拟方法, operator<<
)(用于显示方便,BinaryExpression存储operator
,而不是将所得method
现在)
- 因此,现在你可以使用BOOST_SPIRIT_DEBUG(取消注释第一行)
- 我已经改名为
Expression
对AbstractExpression
(和去构造保护制) - 我已经改名
PrimaryExpression
来Expression
(这是现在你的主要表达的数据类型 ) - 我展示了如何简单地变量存储在
static
地图 - 一定要看看
qi::symbols
和 - 例如如何增加气::符号在语法<迭代器,双()>?
- (仅适用于使用远不及融合结构适应
variable
了) 使用模板的构造技巧,使其很容易从不同的解析类型构建表达:
struct Expression : AbstractExpression { template <typename E> Expression(E const& e) : _e(make_from(e)) { } // cloning the expression // ... };
例如是足以有效地支持:
primary_expr = ( '(' > expression > ')' ) [ _val = _1 ] | constant [ _val = _1 ] | variable [ _val = _1 ] ;
为了好玩已包括了几个测试案例:
Input: 3*8 + 6 Expression: Expression(BinaryExpression(BinaryExpression(ConstantExpression(3) * ConstantExpression(8)) + ConstantExpression(6))) Parse success: true Remaining unparsed: '' (a, b): 0, 0 Evaluation result: 30 ---------------------------------------- Input: 3*(8+6) Expression: Expression(BinaryExpression(ConstantExpression(3) * BinaryExpression(ConstantExpression(8) + ConstantExpression(6)))) Parse success: true Remaining unparsed: '' (a, b): 0, 0 Evaluation result: 42 ---------------------------------------- Input: 0x1b Expression: Expression(ConstantExpression(27)) Parse success: true Remaining unparsed: '' (a, b): 0, 0 Evaluation result: 27 ---------------------------------------- Input: 1/3 Expression: Expression(BinaryExpression(ConstantExpression(1) / ConstantExpression(3))) Parse success: true Remaining unparsed: '' (a, b): 0, 0 Evaluation result: 0.333333 ---------------------------------------- Input: .3333 * 8e12 Expression: Expression(BinaryExpression(ConstantExpression(0.3333) * ConstantExpression(8e+12))) Parse success: true Remaining unparsed: '' (a, b): 0, 0 Evaluation result: 2.6664e+12 ---------------------------------------- Input: (2 * a) + b Expression: Expression(BinaryExpression(BinaryExpression(ConstantExpression(2) * VariableExpression('a')) + VariableExpression('b'))) Parse success: true Remaining unparsed: '' (a, b): 10, 7 Evaluation result: 27 ---------------------------------------- Input: (2 * a) + b Expression: Expression(BinaryExpression(BinaryExpression(ConstantExpression(2) * VariableExpression('a')) + VariableExpression('b'))) Parse success: true Remaining unparsed: '' (a, b): -10, 800 Evaluation result: 780 ---------------------------------------- Input: (2 * {a}) + b Expression: Expression(BinaryExpression(BinaryExpression(ConstantExpression(2) * VariableExpression('a')) + VariableExpression('b'))) Parse success: true Remaining unparsed: '' (a, b): -10, 800 Evaluation result: 780 ---------------------------------------- Input: {names with spaces} Expression: Expression(VariableExpression('names with spaces')) Parse success: true Remaining unparsed: '' (a, b): 0, 0 Evaluation result: 0 ----------------------------------------
完整的代码
// #define BOOST_SPIRIT_DEBUG
// #define BOOST_RESULT_OF_USE_DECLTYPE
// #define BOOST_SPIRIT_USE_PHOENIX_V3
#include <cassert>
#include <memory>
#include <iostream>
#include <map>
struct AbstractExpression;
typedef std::shared_ptr<AbstractExpression> Ptr;
struct AbstractExpression {
virtual ~AbstractExpression() {}
virtual double Evaluate() const = 0;
virtual std::ostream& Print(std::ostream& os) const = 0;
friend std::ostream& operator<<(std::ostream& os, AbstractExpression const& e)
{ return e.Print(os); }
protected: AbstractExpression() {}
};
template <typename Expr> // general purpose, static Expression cloner
static Ptr make_from(Expr const& t) { return std::make_shared<Expr>(t); }
struct BinaryExpression : AbstractExpression
{
BinaryExpression() {}
template<typename L, typename R>
BinaryExpression(char op, L const& l, R const& r)
: _op(op), _lhs(make_from(l)), _rhs(make_from(r))
{}
double Evaluate() const {
func f = Method(_op);
assert(f && _lhs && _rhs);
return f(_lhs->Evaluate(), _rhs->Evaluate());
}
private:
char _op;
Ptr _lhs, _rhs;
typedef double(*func)(double, double);
static double Add(double a, double b) { return a+b; }
static double Subtract(double a, double b) { return a-b; }
static double Multuply(double a, double b) { return a*b; }
static double Divide(double a, double b) { return a/b; }
static BinaryExpression::func Method(char op)
{
switch(op) {
case '+': return Add;
case '-': return Subtract;
case '*': return Multuply;
case '/': return Divide;
default: return nullptr;
}
}
std::ostream& Print(std::ostream& os) const
{ return os << "BinaryExpression(" << *_lhs << " " << _op << " " << *_rhs << ")"; }
};
struct ConstantExpression : AbstractExpression {
double value;
ConstantExpression(double v = 0) : value(v) {}
double Evaluate() const { return value; }
virtual std::ostream& Print(std::ostream& os) const
{ return os << "ConstantExpression(" << value << ")"; }
};
struct VariableExpression : AbstractExpression {
std::string _name;
static double& get(std::string const& name) {
static std::map<std::string, double> _symbols;
return _symbols[name];
/*switch(name) {
* case 'a': static double a; return a;
* case 'b': static double b; return b;
* default: throw "undefined variable";
*}
*/
}
double Evaluate() const { return get(_name); }
virtual std::ostream& Print(std::ostream& os) const
{ return os << "VariableExpression('" << _name << "')"; }
};
struct Expression : AbstractExpression
{
Expression() { }
template <typename E>
Expression(E const& e) : _e(make_from(e)) { } // cloning the expression
double Evaluate() const { assert(_e); return _e->Evaluate(); }
// special purpose overload to avoid unnecessary wrapping
friend Ptr make_from(Expression const& t) { return t._e; }
private:
Ptr _e;
virtual std::ostream& Print(std::ostream& os) const
{ return os << "Expression(" << *_e << ")"; }
};
//Tree.cpp
/////////////////////////////////////////////////////////////////////////////
// BINARY EXPRESSION
////////////////////////////////////////////////////////////////////////////
//#include "Tree.h"
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/adapted.hpp>
BOOST_FUSION_ADAPT_STRUCT(VariableExpression, (std::string, _name))
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phx = boost::phoenix;
// Pass functions to boost
template <typename Iterator>
struct ExpressionParser : qi::grammar<Iterator, Expression(), ascii::space_type>
{
struct MakeBinaryExpression {
template<typename,typename,typename> struct result { typedef BinaryExpression type; };
template<typename C, typename L, typename R>
BinaryExpression operator()(C op, L const& lhs, R const& rhs) const
{ return BinaryExpression(op, lhs, rhs); }
};
phx::function<MakeBinaryExpression> makebinary;
ExpressionParser() : ExpressionParser::base_type(expression)
{
using namespace qi;
expression =
additive_expr [ _val = _1]
;
additive_expr =
primary_expr [ _val = _1 ]
>> *(char_("-+*/") >> primary_expr) [ _val = makebinary(_1, _val, _2)]
;
primary_expr =
( '(' > expression > ')' ) [ _val = _1 ]
| constant [ _val = _1 ]
| variable [ _val = _1 ]
;
constant = lexeme ["0x" >> hex] | double_ | int_;
string = '{' >> lexeme [ *~char_("}") ] > '}';
variable = string | as_string [ alpha ];
BOOST_SPIRIT_DEBUG_NODE(expression);
BOOST_SPIRIT_DEBUG_NODE(additive_expr);
BOOST_SPIRIT_DEBUG_NODE(primary_expr);
BOOST_SPIRIT_DEBUG_NODE(constant);
BOOST_SPIRIT_DEBUG_NODE(variable);
BOOST_SPIRIT_DEBUG_NODE(string);
}
qi::rule<Iterator, Expression() , ascii::space_type> expression;
qi::rule<Iterator, Expression() , ascii::space_type> additive_expr;
qi::rule<Iterator, Expression() , ascii::space_type> primary_expr;
qi::rule<Iterator, ConstantExpression(), ascii::space_type> constant;
qi::rule<Iterator, VariableExpression(), ascii::space_type> variable;
qi::rule<Iterator, std::string() , ascii::space_type> string;
};
void test(const std::string input, double a=0, double b=0)
{
typedef std::string::const_iterator It;
ExpressionParser<It> p;
Expression e;
It f(input.begin()), l(input.end());
bool ok = qi::phrase_parse(f,l,p,ascii::space,e);
std::cout << "Input: " << input << "\n";
std::cout << "Expression: " << e << "\n";
std::cout << "Parse success: " << std::boolalpha << ok << "\n";
std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
std::cout << "(a, b): " << a << ", " << b << "\n";
VariableExpression::get("a") = a;
VariableExpression::get("b") = b;
std::cout << "Evaluation result: " << e.Evaluate() << "\n";
std::cout << "----------------------------------------\n";
}
int main()
{
test("3*8 + 6");
test("3*(8+6)");
test("0x1b");
test("1/3");
test(".3333 * 8e12");
test("(2 * a) + b", 10, 7);
test("(2 * a) + b", -10, 800);
test("(2 * {a}) + b", -10, 800);
test("{names with spaces}");
}
文章来源: Building a Custom Expression Tree in Spirit:Qi (Without Utree or Boost::Variant)