1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
#include <mbgl/style/expression/equals.hpp>
namespace mbgl {
namespace style {
namespace expression {
static bool isComparableType(const type::Type& type) {
return type == type::String ||
type == type::Number ||
type == type::Boolean ||
type == type::Null;
}
Equals::Equals(std::unique_ptr<Expression> lhs_, std::unique_ptr<Expression> rhs_, bool negate_)
: Expression(type::Boolean),
lhs(std::move(lhs_)),
rhs(std::move(rhs_)),
negate(negate_) {
assert(isComparableType(lhs->getType()) || isComparableType(rhs->getType()));
assert(lhs->getType() == rhs->getType() || lhs->getType() == type::Value || rhs->getType() == type::Value);
}
EvaluationResult Equals::evaluate(const EvaluationContext& params) const {
EvaluationResult lhsResult = lhs->evaluate(params);
if (!lhsResult) return lhsResult;
EvaluationResult rhsResult = rhs->evaluate(params);
if (!rhsResult) return lhsResult;
bool result = *lhsResult == *rhsResult;
if (negate) {
result = !result;
}
return result;
}
void Equals::eachChild(const std::function<void(const Expression&)>& visit) const {
visit(*lhs);
visit(*rhs);
}
bool Equals::operator==(const Expression& e) const {
if (auto eq = dynamic_cast<const Equals*>(&e)) {
return eq->negate == negate && *eq->lhs == *lhs && *eq->rhs == *rhs;
}
return false;
}
std::vector<optional<Value>> Equals::possibleOutputs() const {
return {{ true }, { false }};
}
using namespace mbgl::style::conversion;
ParseResult Equals::parse(const Convertible& value, ParsingContext& ctx) {
std::size_t length = arrayLength(value);
if (length != 3) {
ctx.error("Expected two arguments.");
return ParseResult();
}
bool negate = toString(arrayMember(value, 0)) == std::string("!=");
ParseResult lhs = ctx.parse(arrayMember(value, 1), 1, {type::Value});
if (!lhs) return ParseResult();
ParseResult rhs = ctx.parse(arrayMember(value, 2), 2, {type::Value});
if (!rhs) return ParseResult();
type::Type lhsType = (*lhs)->getType();
type::Type rhsType = (*rhs)->getType();
if (!isComparableType(lhsType) && !isComparableType(rhsType)) {
ctx.error("Expected at least one argument to be a string, number, boolean, or null, but found (" +
toString(lhsType) + ", " + toString(rhsType) + ") instead.");
return ParseResult();
}
if (lhsType != rhsType && lhsType != type::Value && rhsType != type::Value) {
ctx.error("Cannot compare " + toString(lhsType) + " and " + toString(rhsType) + ".");
return ParseResult();
}
return ParseResult(std::make_unique<Equals>(std::move(*lhs), std::move(*rhs), negate));
}
} // namespace expression
} // namespace style
} // namespace mbgl
|