summaryrefslogtreecommitdiff
path: root/src/mbgl/style/expression/coalesce.cpp
blob: 0373c9626c227c5ccaa50e50b4695e2c01f4981a (plain)
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
#include <mbgl/style/expression/coalesce.hpp>
#include <mbgl/style/expression/check_subtype.hpp>

namespace mbgl {
namespace style {
namespace expression {

EvaluationResult Coalesce::evaluate(const EvaluationContext& params) const {
    EvaluationResult result = Null;
    for (const auto& arg : args) {
        result = arg->evaluate(params);
        if (!result || *result != Null) break;
    }
    return result;
}

void Coalesce::eachChild(const std::function<void(const Expression&)>& visit) const {
    for (const std::unique_ptr<Expression>& arg : args) {
        visit(*arg);
    }
}

bool Coalesce::operator==(const Expression& e) const {
    if (auto rhs = dynamic_cast<const Coalesce*>(&e)) {
        return Expression::childrenEqual(args, rhs->args);
    }
    return false;
}

using namespace mbgl::style::conversion;
ParseResult Coalesce::parse(const Convertible& value, ParsingContext& ctx) {
    assert(isArray(value));
    auto length = arrayLength(value);
    if (length < 2) {
        ctx.error("Expected at least one argument.");
        return ParseResult();
    }
 
    optional<type::Type> outputType;
    optional<type::Type> expectedType = ctx.getExpected();
    if (expectedType && *expectedType != type::Value) {
        outputType = expectedType;
    }

    Coalesce::Args args;
    args.reserve(length - 1);
    for (std::size_t i = 1; i < length; i++) {
        auto parsed = ctx.parse(arrayMember(value, i), i, outputType, ParsingContext::omitTypeAnnotations);
        if (!parsed) {
            return parsed;
        }
        if (!outputType) {
            outputType = (*parsed)->getType();
        }
        args.push_back(std::move(*parsed));
    }
    assert(outputType);

    // Above, we parse arguments without inferred type annotation so that
    // they don't produce a runtime error for `null` input, which would
    // preempt the desired null-coalescing behavior.
    // Thus, if any of our arguments would have needed an annotation, we
    // need to wrap the enclosing coalesce expression with it instead.
    bool needsAnnotation = expectedType &&
        std::any_of(args.begin(), args.end(), [&] (const auto& arg) {
            return type::checkSubtype(*expectedType, arg->getType());
        });

    return ParseResult(std::make_unique<Coalesce>(needsAnnotation ? type::Value : *outputType, std::move(args)));
}

} // namespace expression
} // namespace style
} // namespace mbgl