-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathternary_step.cc
More file actions
84 lines (67 loc) · 2.49 KB
/
Copy pathternary_step.cc
File metadata and controls
84 lines (67 loc) · 2.49 KB
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
#include "eval/eval/ternary_step.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/statusor.h"
#include "base/handle.h"
#include "base/value.h"
#include "base/values/bool_value.h"
#include "base/values/error_value.h"
#include "base/values/unknown_value.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "eval/internal/interop.h"
#include "eval/public/cel_builtins.h"
namespace google::api::expr::runtime {
namespace {
inline constexpr size_t kTernaryStepCondition = 0;
inline constexpr size_t kTernaryStepTrue = 1;
inline constexpr size_t kTernaryStepFalse = 2;
class TernaryStep : public ExpressionStepBase {
public:
// Constructs FunctionStep that uses overloads specified.
explicit TernaryStep(int64_t expr_id) : ExpressionStepBase(expr_id) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
};
absl::Status TernaryStep::Evaluate(ExecutionFrame* frame) const {
// Must have 3 or more values on the stack.
if (!frame->value_stack().HasEnough(3)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
// Create Span object that contains input arguments to the function.
auto args = frame->value_stack().GetSpan(3);
const auto& condition = args[kTernaryStepCondition];
// As opposed to regular functions, ternary treats unknowns or errors on the
// condition (arg0) as blocking. If we get an error or unknown then we
// ignore the other arguments and forward the condition as the result.
if (frame->enable_unknowns()) {
// Check if unknown?
if (condition->Is<cel::UnknownValue>()) {
frame->value_stack().Pop(2);
return absl::OkStatus();
}
}
if (condition->Is<cel::ErrorValue>()) {
frame->value_stack().Pop(2);
return absl::OkStatus();
}
cel::Handle<cel::Value> result;
if (!condition->Is<cel::BoolValue>()) {
result = cel::interop_internal::CreateErrorValueFromView(
cel::interop_internal::CreateNoMatchingOverloadError(
frame->memory_manager(), builtin::kTernary));
} else if (condition.As<cel::BoolValue>()->value()) {
result = args[kTernaryStepTrue];
} else {
result = args[kTernaryStepFalse];
}
frame->value_stack().Pop(args.size());
frame->value_stack().Push(std::move(result));
return absl::OkStatus();
}
} // namespace
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateTernaryStep(
int64_t expr_id) {
return std::make_unique<TernaryStep>(expr_id);
}
} // namespace google::api::expr::runtime