Skip to content
This repository has been archived by the owner on Aug 8, 2023. It is now read-only.

Commit

Permalink
Implement to_{type} coercion expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
Anand Thakker committed Jul 21, 2017
1 parent ec64905 commit 7b436d8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
9 changes: 8 additions & 1 deletion include/mbgl/style/expression/expression.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,13 @@ class Result : private variant<EvaluationError, T> {
}
};

using EvaluationResult = Result<Value>;
struct EvaluationResult : public Result<Value> {
using Result::Result;

EvaluationResult(const std::array<float, 4>& arr) :
Result(std::vector<Value>(arr.begin(), arr.end()))
{}
};

struct CompileError {
std::string message;
Expand All @@ -80,6 +86,7 @@ class TypedExpression {

virtual bool isFeatureConstant() const { return true; }
virtual bool isZoomConstant() const { return true; }

virtual EvaluationResult evaluate(const EvaluationParameters& params) const = 0;

/*
Expand Down
41 changes: 41 additions & 0 deletions src/mbgl/style/expression/compound_expression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,47 @@ std::unordered_map<std::string, CompoundExpression::Definition> CompoundExpressi
define("boolean", assertion<bool>),
define("array", assertion<std::vector<Value>>), // TODO: [array, type, value], [array, type, length, value]

define("to_string", [](const Value& v) -> Result<std::string> { return stringify(v); }),
define("to_number", [](const Value& v) -> Result<float> {
optional<float> result = v.match(
[](const float f) -> optional<float> { return f; },
[](const std::string& s) -> optional<float> {
try {
return std::stof(s);
} catch(std::exception) {
return optional<float>();
}
},
[](const auto&) { return optional<float>(); }
);
if (!result) {
return EvaluationError {
"Could not convert " + stringify(v) + " to number."
};
}
return *result;
}),
define("to_boolean", [](const Value& v) -> Result<bool> {
return v.match(
[&] (float f) { return (bool)f; },
[&] (const std::string& s) { return s.length() > 0; },
[&] (bool b) { return b; },
[&] (const NullValue&) { return false; },
[&] (const auto&) { return true; }
);
}),
define("to_rgba", [](const mbgl::Color& color) -> Result<std::array<float, 4>> {
return std::array<float, 4> {{ color.r, color.g, color.b, color.a }};
}),

define("parse_color", [](const std::string& colorString) -> Result<mbgl::Color> {
const auto& result = mbgl::Color::parse(colorString);
if (result) return *result;
return EvaluationError {
"Could not parse color from value '" + colorString + "'"
};
}),

std::pair<std::string, Definition>("get", defineGet()),

define("+", [](const Varargs<float>& args) -> Result<float> {
Expand Down

0 comments on commit 7b436d8

Please sign in to comment.