funcjudge(node ast.Node, m map[string]interface{})bool { if isLeaf(node) { // 断言成二元表达式 expr := node.(*ast.BinaryExpr) x := expr.X.(*ast.Ident) // 左边 y := expr.Y.(*ast.BasicLit) // 右边
// 仅处理表达式 switch expr.Op { case token.GTR: left := cast.ToFloat64(m[x.Name]) right := cast.ToFloat64(y.Value) return left > right
case token.EQL: left, _ := m[x.Name] right := y.Value switch y.Kind { case token.INT: return cast.ToInt64(left) == cast.ToInt64(right) case token.FLOAT: return cast.ToFloat64(left) == cast.ToFloat64(right) case token.IMAG: return cast.ToFloat64(left) == cast.ToFloat64(right) case token.CHAR: return cast.ToInt(left) == cast.ToInt(right) case token.STRING: return cast.ToString(left) == cast.ToString(right) } returnfalse }
returnfalse }
// 不是叶子节点那么一定是 binary expression(我们目前只处理二元表达式) expr, ok := node.(*ast.BinaryExpr) if !ok { returnfalse }
// 递归地计算左节点和右节点的值 switch expr.Op { case token.LAND: return judge(expr.X, m) && judge(expr.Y, m) case token.LOR: return judge(expr.X, m) || judge(expr.Y, m) } returnfalse }