summaryrefslogtreecommitdiff
path: root/include/mbgl/style/expression/parse.hpp
blob: 1f5802d4fb81b1f0a291c6e50af540897311c598 (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
#pragma once

#include <memory>
#include <mbgl/style/expression/parsing_context.hpp>
#include <mbgl/style/expression/expression.hpp>
#include <mbgl/style/conversion.hpp>

namespace mbgl {
namespace style {
namespace expression {

using namespace mbgl::style;

template <class V>
std::string getJSType(const V& value) {
    using namespace mbgl::style::conversion;
    if (isUndefined(value)) {
        return "undefined";
    }
    if (isArray(value) || isObject(value)) {
        return "object";
    }
    optional<mbgl::Value> v = toValue(value);
    assert(v);
    return v->match(
        [&] (std::string) { return "string"; },
        [&] (bool) { return "boolean"; },
        [&] (auto) { return "number"; }
    );
}

using ParseResult = variant<CompileError, std::unique_ptr<Expression>>;

template <class V>
ParseResult parseExpression(const V& value, const ParsingContext& context)
{
    using namespace mbgl::style::conversion;
    
    if (isArray(value)) {
        if (arrayLength(value) == 0) {
            CompileError error = {
                "Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].",
                context.key()
            };
            return error;
        }
        
        const optional<std::string>& op = toString(arrayMember(value, 0));
        if (!op) {
            CompileError error = {
                "Expression name must be a string, but found " + getJSType(arrayMember(value, 0)) +
                    " instead. If you wanted a literal array, use [\"literal\", [...]].",
                context.key(0)
            };
            return error;
        }
        
        if (*op == "+") return LambdaExpression::parse<PlusExpression>(value, context);
        if (*op == "-") return LambdaExpression::parse<MinusExpression>(value, context);
        if (*op == "*") return LambdaExpression::parse<TimesExpression>(value, context);
        if (*op == "/") return LambdaExpression::parse<DivideExpression>(value, context);

        
        return CompileError {
            std::string("Unknown expression \"") + *op + "\". If you wanted a literal array, use [\"literal\", [...]].",
            context.key(0)
        };
    }
    
    if (isObject(value)) {
        return CompileError {
            "Bare objects invalid. Use [\"literal\", {...}] instead.",
            context.key()
        };
    }
    
    return LiteralExpression::parse(value, context);
}


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