| 62 | } |
| 63 | |
| 64 | bool MathParser::multexpr(Expression& expr) |
| 65 | { |
| 66 | if (!uminus(expr)) |
| 67 | return false; |
| 68 | |
| 69 | while (true) |
| 70 | { |
| 71 | NodeType type; |
| 72 | if (match(TokenType::Asterisk)) |
| 73 | type = NodeType::Multiply; |
| 74 | else if (match(TokenType::Slash)) |
| 75 | type = NodeType::Divide; |
| 76 | else |
| 77 | return true; |
| 78 | |
| 79 | if (!uminus(expr)) |
| 80 | { |
| 81 | setError("Expected expression following '" + |
| 82 | curToken().sval() + "'."); |
| 83 | return false; |
| 84 | } |
| 85 | |
| 86 | NodePtr right = expr.popNode(); |
| 87 | NodePtr left = expr.popNode(); |
| 88 | |
| 89 | ConstValueNode *leftVal = dynamic_cast<ConstValueNode *>(left.get()); |
| 90 | ConstValueNode *rightVal = dynamic_cast<ConstValueNode *>(right.get()); |
| 91 | |
| 92 | if (leftVal && rightVal) |
| 93 | { |
| 94 | double v; |
| 95 | if (type == NodeType::Multiply) |
| 96 | v = leftVal->value() * rightVal->value(); |
| 97 | else |
| 98 | { |
| 99 | if (rightVal->value() == 0.0) |
| 100 | { |
| 101 | setError("Divide by 0."); |
| 102 | return false; |
| 103 | } |
| 104 | v = leftVal->value() / rightVal->value(); |
| 105 | } |
| 106 | expr.pushNode(NodePtr(new ConstValueNode(v))); |
| 107 | } |
| 108 | else |
| 109 | { |
| 110 | if (left->isBool() || right->isBool()) |
| 111 | { |
| 112 | setError("Can't apply '" + curToken().sval() + "' to " |
| 113 | "logical expression."); |
| 114 | return false; |
| 115 | } |
| 116 | expr.pushNode(NodePtr(new BinMathNode(type, std::move(left), std::move(right)))); |
| 117 | } |
| 118 | } |
| 119 | return true; |
| 120 | } |
| 121 | |