summaryrefslogtreecommitdiff
path: root/include/mbgl/style/expression/expression.hpp
blob: 99aaed8a1473e471a056c3ef5ee365a064538a93 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#pragma once

#include <array>
#include <vector>
#include <memory>
#include <mbgl/util/optional.hpp>
#include <mbgl/util/variant.hpp>
#include <mbgl/util/color.hpp>
#include <mbgl/style/expression/type.hpp>
#include <mbgl/style/expression/value.hpp>
#include <mbgl/style/expression/parsing_context.hpp>
#include <mbgl/style/conversion.hpp>


namespace mbgl {

class GeometryTileFeature;


namespace style {
namespace expression {

struct EvaluationError {
    std::string message;
};

struct EvaluationParameters {
    float zoom;
    const GeometryTileFeature& feature;
};

using EvaluationResult = variant<EvaluationError, Value>;

class Expression {
public:
    Expression(std::string key_, type::Type type_) : key(key_), type(type_) {}
    virtual ~Expression() {}
    
    virtual EvaluationResult evaluate(const EvaluationParameters&) const = 0;
    
    // Exposed for use with pure Feature objects (e.g. beyond the context of tiled map data).
    EvaluationResult evaluate(float, const Feature&) const;
    
    type::Type getType() const {
        return type;
    }
    
    type::ValueType getResultType() const {
        return type.match(
            [&] (const type::Lambda& lambdaType) {
                return lambdaType.getResult();
            },
            [&] (const auto& t) -> type::ValueType { return t; }
        );
    }
    
    bool isFeatureConstant() {
        return true;
    }
    
    bool isZoomConstant() {
        return true;
    }
    
private:
    std::string key;
    type::Type type;
};

struct CompileError {
    std::string message;
    std::string key;
};
using ParseResult = variant<CompileError, std::unique_ptr<Expression>>;
template <class V>
ParseResult parseExpression(const V& value, const ParsingContext& context);

using namespace mbgl::style::conversion;

class LiteralExpression : public Expression {
public:
    LiteralExpression(std::string key, type::Type type, Value value_) : Expression(key, type), value(value_) {}

    EvaluationResult evaluate(const EvaluationParameters&) const override {
        return value;
    }
    
    template <class V>
    static ParseResult parse(const V& value, const ParsingContext& ctx) {
        const Value& parsedValue = parseValue(value);
        const type::Type& type = typeOf(parsedValue);
        return std::make_unique<LiteralExpression>(ctx.key(), type, parsedValue);
    }
    
private:
    template <class V>
    static Value parseValue(const V& value) {
        if (isUndefined(value)) return Null;
        if (isObject(value)) {
            std::unordered_map<std::string, Value> result;
            eachMember(value, [&] (const std::string& k, const V& v) -> optional<conversion::Error> {
                result.emplace(k, parseValue(v));
                return {};
            });
            return result;
        }
        if (isArray(value)) {
            std::vector<Value> result;
            const auto length = arrayLength(value);
            for(std::size_t i = 0; i < length; i++) {
                result.emplace_back(parseValue(arrayMember(value, i)));
            }
            return result;
        }
        
        optional<mbgl::Value> v = toValue(value);
        assert(v);
        return v->match(
            [&] (const std::string& s) -> Value { return s; },
            [&] (bool b) -> Value { return b; },
            [&] (auto f) -> Value { return *numericValue<float>(f); }
        );
    }

    Value value;
};

class LambdaExpression : public Expression {
public:
    using Args = std::vector<std::unique_ptr<Expression>>;

    LambdaExpression(std::string key,
                    std::string name_,
                    Args args_,
                    type::Lambda type) :
        Expression(key, type),
        args(std::move(args_)),
        name(name_)
    {}
    
    template <class Expr, class V>
    static ParseResult parse(const V& value, const ParsingContext& ctx) {
        assert(isArray(value));
        auto length = arrayLength(value);
        Args args;
        for(size_t i = 1; i < length; i++) {
            const auto& arg = arrayMember(value, i);
            auto parsedArg = parseExpression(arg, ParsingContext(ctx, i, {}));
            if (parsedArg.template is<std::unique_ptr<Expression>>()) {
                args.push_back(std::move(parsedArg.template get<std::unique_ptr<Expression>>()));
            } else {
                return parsedArg.template get<CompileError>();
            }
        }
        return std::make_unique<Expr>(ctx.key(), std::move(args));
    }
    
protected:
    Args args;
private:
    std::string name;
};

template <typename T, typename Rfunc>
EvaluationResult evaluateBinaryOperator(const EvaluationParameters& params,
                                            const LambdaExpression::Args& args,
                                            optional<T> initial,
                                            Rfunc reduce)
{
    optional<T> memo = initial;
    for(const auto& arg : args) {
        auto argValue = arg->evaluate(params);
        if (argValue.is<EvaluationError>()) {
            return argValue.get<EvaluationError>();
        }
        T value = argValue.get<Value>().get<T>();
        if (!memo) memo = {value};
        else memo = reduce(*memo, value);
    }
    return {*memo};
}

class PlusExpression : public LambdaExpression {
public:
    PlusExpression(std::string key, Args args) :
        LambdaExpression(key, "+", std::move(args),
                        {type::Primitive::Number, {type::NArgs({type::Primitive::Number})}})
    {}
    
    EvaluationResult evaluate(const EvaluationParameters& params) const override {
        return evaluateBinaryOperator<float>(params, args,
            {}, [](float memo, float next) { return memo + next; });
    }
};

class TimesExpression : public LambdaExpression {
public:
    TimesExpression(std::string key, Args args) :
        LambdaExpression(key, "*", std::move(args),
                        {type::Primitive::Number, {type::NArgs({type::Primitive::Number})}})
    {}
    
    EvaluationResult evaluate(const EvaluationParameters& params) const override {
        return evaluateBinaryOperator<float>(params, args,
            {}, [](float memo, float next) { return memo * next; });
    }
};

class MinusExpression : public LambdaExpression {
public:
    MinusExpression(std::string key, Args args) :
        LambdaExpression(key, "-", std::move(args),
                        {type::Primitive::Number, {type::Primitive::Number, type::Primitive::Number}})
    {}
    
    EvaluationResult evaluate(const EvaluationParameters& params) const override {
        return evaluateBinaryOperator<float>(params, args,
            {}, [](float memo, float next) { return memo - next; });
    }
};

class DivideExpression : public LambdaExpression {
public:
    DivideExpression(std::string key, Args args) :
        LambdaExpression(key, "/", std::move(args),
                        {type::Primitive::Number, {type::Primitive::Number, type::Primitive::Number}})
    {}
    
    EvaluationResult evaluate(const EvaluationParameters& params) const override {
        return evaluateBinaryOperator<float>(params, args,
            {}, [](float memo, float next) { return memo / next; });
    }
};



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