ID
stringlengths 36
36
| Language
stringclasses 1
value | Repository Name
stringclasses 13
values | File Name
stringlengths 2
48
| File Path in Repository
stringlengths 11
111
| File Path for Unit Test
stringlengths 13
116
| Code
stringlengths 0
278k
| Unit Test - (Ground Truth)
stringlengths 78
663k
| Code Url
stringlengths 91
198
| Test Code Url
stringlengths 93
203
| Commit Hash
stringclasses 13
values |
---|---|---|---|---|---|---|---|---|---|---|
b5213f53-4bff-4a65-a833-0de7b1b67a3f | cpp | google/cel-cpp | source_position | eval/public/source_position.cc | eval/public/source_position_test.cc | #include "eval/public/source_position.h"
#include <utility>
namespace google {
namespace api {
namespace expr {
namespace runtime {
using google::api::expr::v1alpha1::SourceInfo;
namespace {
std::pair<int, int32_t> GetLineAndLineOffset(const SourceInfo* source_info,
int32_t position) {
int line = 0;
int32_t line_offset = 0;
if (source_info != nullptr) {
for (const auto& curr_line_offset : source_info->line_offsets()) {
if (curr_line_offset > position) {
break;
}
line_offset = curr_line_offset;
line++;
}
}
if (line == 0) {
line++;
}
return std::pair<int, int32_t>(line, line_offset);
}
}
int32_t SourcePosition::line() const {
return GetLineAndLineOffset(source_info_, character_offset()).first;
}
int32_t SourcePosition::column() const {
int32_t position = character_offset();
std::pair<int, int32_t> line_and_offset =
GetLineAndLineOffset(source_info_, position);
return 1 + (position - line_and_offset.second);
}
int32_t SourcePosition::character_offset() const {
if (source_info_ == nullptr) {
return 0;
}
auto position_it = source_info_->positions().find(expr_id_);
return position_it != source_info_->positions().end() ? position_it->second
: 0;
}
}
}
}
} | #include "eval/public/source_position.h"
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "internal/testing.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
using ::testing::Eq;
using google::api::expr::v1alpha1::SourceInfo;
class SourcePositionTest : public testing::Test {
protected:
void SetUp() override {
source_info_.add_line_offsets(0);
source_info_.add_line_offsets(1);
source_info_.add_line_offsets(2);
(*source_info_.mutable_positions())[1] = 2;
source_info_.add_line_offsets(4);
(*source_info_.mutable_positions())[2] = 4;
(*source_info_.mutable_positions())[3] = 7;
source_info_.add_line_offsets(9);
source_info_.add_line_offsets(10);
(*source_info_.mutable_positions())[4] = 10;
(*source_info_.mutable_positions())[5] = 13;
}
SourceInfo source_info_;
};
TEST_F(SourcePositionTest, TestNullSourceInfo) {
SourcePosition position(3, nullptr);
EXPECT_THAT(position.character_offset(), Eq(0));
EXPECT_THAT(position.line(), Eq(1));
EXPECT_THAT(position.column(), Eq(1));
}
TEST_F(SourcePositionTest, TestNoNewlines) {
source_info_.clear_line_offsets();
SourcePosition position(3, &source_info_);
EXPECT_THAT(position.character_offset(), Eq(7));
EXPECT_THAT(position.line(), Eq(1));
EXPECT_THAT(position.column(), Eq(8));
}
TEST_F(SourcePositionTest, TestPosition) {
SourcePosition position(3, &source_info_);
EXPECT_THAT(position.character_offset(), Eq(7));
}
TEST_F(SourcePositionTest, TestLine) {
SourcePosition position1(1, &source_info_);
EXPECT_THAT(position1.line(), Eq(3));
SourcePosition position2(2, &source_info_);
EXPECT_THAT(position2.line(), Eq(4));
SourcePosition position3(3, &source_info_);
EXPECT_THAT(position3.line(), Eq(4));
SourcePosition position4(5, &source_info_);
EXPECT_THAT(position4.line(), Eq(6));
}
TEST_F(SourcePositionTest, TestColumn) {
SourcePosition position1(1, &source_info_);
EXPECT_THAT(position1.column(), Eq(1));
SourcePosition position2(2, &source_info_);
EXPECT_THAT(position2.column(), Eq(1));
SourcePosition position3(3, &source_info_);
EXPECT_THAT(position3.column(), Eq(4));
SourcePosition position4(5, &source_info_);
EXPECT_THAT(position4.column(), Eq(4));
}
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/source_position.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/source_position_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
0f006b4a-ddcc-4597-8679-08dd5fc18a8a | cpp | google/cel-cpp | cel_number | eval/public/cel_number.cc | eval/public/cel_number_test.cc | #include "eval/public/cel_number.h"
#include "eval/public/cel_value.h"
namespace google::api::expr::runtime {
absl::optional<CelNumber> GetNumberFromCelValue(const CelValue& value) {
if (int64_t val; value.GetValue(&val)) {
return CelNumber(val);
} else if (uint64_t val; value.GetValue(&val)) {
return CelNumber(val);
} else if (double val; value.GetValue(&val)) {
return CelNumber(val);
}
return absl::nullopt;
}
} | #include "eval/public/cel_number.h"
#include <cstdint>
#include <limits>
#include "absl/types/optional.h"
#include "eval/public/cel_value.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::testing::Optional;
TEST(CelNumber, GetNumberFromCelValue) {
EXPECT_THAT(GetNumberFromCelValue(CelValue::CreateDouble(1.1)),
Optional(CelNumber::FromDouble(1.1)));
EXPECT_THAT(GetNumberFromCelValue(CelValue::CreateInt64(1)),
Optional(CelNumber::FromDouble(1.0)));
EXPECT_THAT(GetNumberFromCelValue(CelValue::CreateUint64(1)),
Optional(CelNumber::FromDouble(1.0)));
EXPECT_EQ(GetNumberFromCelValue(CelValue::CreateDuration(absl::Seconds(1))),
absl::nullopt);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_number.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_number_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
d99df65f-ba6b-42d7-bf07-86c166969517 | cpp | google/cel-cpp | cel_value | eval/public/cel_value.cc | eval/public/cel_value_test.cc | #include "eval/public/cel_value.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/no_destructor.h"
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/memory.h"
#include "eval/internal/errors.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "extensions/protobuf/memory_manager.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::google::protobuf::Arena;
namespace interop = ::cel::interop_internal;
constexpr absl::string_view kNullTypeName = "null_type";
constexpr absl::string_view kBoolTypeName = "bool";
constexpr absl::string_view kInt64TypeName = "int";
constexpr absl::string_view kUInt64TypeName = "uint";
constexpr absl::string_view kDoubleTypeName = "double";
constexpr absl::string_view kStringTypeName = "string";
constexpr absl::string_view kBytesTypeName = "bytes";
constexpr absl::string_view kDurationTypeName = "google.protobuf.Duration";
constexpr absl::string_view kTimestampTypeName = "google.protobuf.Timestamp";
constexpr absl::string_view kListTypeName = "list";
constexpr absl::string_view kMapTypeName = "map";
constexpr absl::string_view kCelTypeTypeName = "type";
struct DebugStringVisitor {
google::protobuf::Arena* const arena;
std::string operator()(bool arg) { return absl::StrFormat("%d", arg); }
std::string operator()(int64_t arg) { return absl::StrFormat("%lld", arg); }
std::string operator()(uint64_t arg) { return absl::StrFormat("%llu", arg); }
std::string operator()(double arg) { return absl::StrFormat("%f", arg); }
std::string operator()(CelValue::NullType) { return "null"; }
std::string operator()(CelValue::StringHolder arg) {
return absl::StrFormat("%s", arg.value());
}
std::string operator()(CelValue::BytesHolder arg) {
return absl::StrFormat("%s", arg.value());
}
std::string operator()(const MessageWrapper& arg) {
return arg.message_ptr() == nullptr
? "NULL"
: arg.legacy_type_info()->DebugString(arg);
}
std::string operator()(absl::Duration arg) {
return absl::FormatDuration(arg);
}
std::string operator()(absl::Time arg) {
return absl::FormatTime(arg, absl::UTCTimeZone());
}
std::string operator()(const CelList* arg) {
std::vector<std::string> elements;
elements.reserve(arg->size());
for (int i = 0; i < arg->size(); i++) {
elements.push_back(arg->Get(arena, i).DebugString());
}
return absl::StrCat("[", absl::StrJoin(elements, ", "), "]");
}
std::string operator()(const CelMap* arg) {
auto keys_or_error = arg->ListKeys(arena);
if (!keys_or_error.status().ok()) {
return "invalid list keys";
}
const CelList* keys = std::move(keys_or_error.value());
std::vector<std::string> elements;
elements.reserve(keys->size());
for (int i = 0; i < keys->size(); i++) {
const auto& key = (*keys).Get(arena, i);
const auto& optional_value = arg->Get(arena, key);
elements.push_back(absl::StrCat("<", key.DebugString(), ">: <",
optional_value.has_value()
? optional_value->DebugString()
: "nullopt",
">"));
}
return absl::StrCat("{", absl::StrJoin(elements, ", "), "}");
}
std::string operator()(const UnknownSet* arg) {
return "?";
}
std::string operator()(CelValue::CelTypeHolder arg) {
return absl::StrCat(arg.value());
}
std::string operator()(const CelError* arg) { return arg->ToString(); }
};
}
ABSL_CONST_INIT const absl::string_view kPayloadUrlMissingAttributePath =
cel::runtime_internal::kPayloadUrlMissingAttributePath;
CelValue CelValue::CreateDuration(absl::Duration value) {
if (value >= cel::runtime_internal::kDurationHigh ||
value <= cel::runtime_internal::kDurationLow) {
return CelValue(cel::runtime_internal::DurationOverflowError());
}
return CreateUncheckedDuration(value);
}
std::string CelValue::TypeName(Type value_type) {
switch (value_type) {
case Type::kNullType:
return "null_type";
case Type::kBool:
return "bool";
case Type::kInt64:
return "int64";
case Type::kUint64:
return "uint64";
case Type::kDouble:
return "double";
case Type::kString:
return "string";
case Type::kBytes:
return "bytes";
case Type::kMessage:
return "Message";
case Type::kDuration:
return "Duration";
case Type::kTimestamp:
return "Timestamp";
case Type::kList:
return "CelList";
case Type::kMap:
return "CelMap";
case Type::kCelType:
return "CelType";
case Type::kUnknownSet:
return "UnknownSet";
case Type::kError:
return "CelError";
case Type::kAny:
return "Any type";
default:
return "unknown";
}
}
absl::Status CelValue::CheckMapKeyType(const CelValue& key) {
switch (key.type()) {
case CelValue::Type::kString:
case CelValue::Type::kInt64:
case CelValue::Type::kUint64:
case CelValue::Type::kBool:
return absl::OkStatus();
default:
return absl::InvalidArgumentError(absl::StrCat(
"Invalid map key type: '", CelValue::TypeName(key.type()), "'"));
}
}
CelValue CelValue::ObtainCelType() const {
switch (type()) {
case Type::kNullType:
return CreateCelType(CelTypeHolder(kNullTypeName));
case Type::kBool:
return CreateCelType(CelTypeHolder(kBoolTypeName));
case Type::kInt64:
return CreateCelType(CelTypeHolder(kInt64TypeName));
case Type::kUint64:
return CreateCelType(CelTypeHolder(kUInt64TypeName));
case Type::kDouble:
return CreateCelType(CelTypeHolder(kDoubleTypeName));
case Type::kString:
return CreateCelType(CelTypeHolder(kStringTypeName));
case Type::kBytes:
return CreateCelType(CelTypeHolder(kBytesTypeName));
case Type::kMessage: {
MessageWrapper wrapper;
CelValue::GetValue(&wrapper);
if (wrapper.message_ptr() == nullptr) {
return CreateCelType(CelTypeHolder(kNullTypeName));
}
return CreateCelType(
CelTypeHolder(wrapper.legacy_type_info()->GetTypename(wrapper)));
}
case Type::kDuration:
return CreateCelType(CelTypeHolder(kDurationTypeName));
case Type::kTimestamp:
return CreateCelType(CelTypeHolder(kTimestampTypeName));
case Type::kList:
return CreateCelType(CelTypeHolder(kListTypeName));
case Type::kMap:
return CreateCelType(CelTypeHolder(kMapTypeName));
case Type::kCelType:
return CreateCelType(CelTypeHolder(kCelTypeTypeName));
case Type::kUnknownSet:
return *this;
case Type::kError:
return *this;
default: {
static const CelError* invalid_type_error =
new CelError(absl::InvalidArgumentError("Unsupported CelValue type"));
return CreateError(invalid_type_error);
}
}
}
const std::string CelValue::DebugString() const {
google::protobuf::Arena arena;
return absl::StrCat(CelValue::TypeName(type()), ": ",
InternalVisit<std::string>(DebugStringVisitor{&arena}));
}
namespace {
class EmptyCelList final : public CelList {
public:
static const EmptyCelList* Get() {
static const absl::NoDestructor<EmptyCelList> instance;
return &*instance;
}
CelValue operator[](int index) const override {
static const CelError* invalid_argument =
new CelError(absl::InvalidArgumentError("index out of bounds"));
return CelValue::CreateError(invalid_argument);
}
int size() const override { return 0; }
bool empty() const override { return true; }
};
class EmptyCelMap final : public CelMap {
public:
static const EmptyCelMap* Get() {
static const absl::NoDestructor<EmptyCelMap> instance;
return &*instance;
}
absl::optional<CelValue> operator[](CelValue key) const override {
return absl::nullopt;
}
absl::StatusOr<bool> Has(const CelValue& key) const override {
CEL_RETURN_IF_ERROR(CelValue::CheckMapKeyType(key));
return false;
}
int size() const override { return 0; }
bool empty() const override { return true; }
absl::StatusOr<const CelList*> ListKeys() const override {
return EmptyCelList::Get();
}
};
}
CelValue CelValue::CreateList() { return CreateList(EmptyCelList::Get()); }
CelValue CelValue::CreateMap() { return CreateMap(EmptyCelMap::Get()); }
CelValue CreateErrorValue(cel::MemoryManagerRef manager,
absl::string_view message,
absl::StatusCode error_code) {
Arena* arena = cel::extensions::ProtoMemoryManagerArena(manager);
return CreateErrorValue(arena, message, error_code);
}
CelValue CreateErrorValue(cel::MemoryManagerRef manager,
const absl::Status& status) {
Arena* arena = cel::extensions::ProtoMemoryManagerArena(manager);
return CreateErrorValue(arena, status);
}
CelValue CreateErrorValue(Arena* arena, absl::string_view message,
absl::StatusCode error_code) {
CelError* error = Arena::Create<CelError>(arena, error_code, message);
return CelValue::CreateError(error);
}
CelValue CreateErrorValue(Arena* arena, const absl::Status& status) {
CelError* error = Arena::Create<CelError>(arena, status);
return CelValue::CreateError(error);
}
CelValue CreateNoMatchingOverloadError(cel::MemoryManagerRef manager,
absl::string_view fn) {
return CelValue::CreateError(interop::CreateNoMatchingOverloadError(
cel::extensions::ProtoMemoryManagerArena(manager), fn));
}
CelValue CreateNoMatchingOverloadError(google::protobuf::Arena* arena,
absl::string_view fn) {
return CelValue::CreateError(
interop::CreateNoMatchingOverloadError(arena, fn));
}
bool CheckNoMatchingOverloadError(CelValue value) {
return value.IsError() &&
value.ErrorOrDie()->code() == absl::StatusCode::kUnknown &&
absl::StrContains(value.ErrorOrDie()->message(),
cel::runtime_internal::kErrNoMatchingOverload);
}
CelValue CreateNoSuchFieldError(cel::MemoryManagerRef manager,
absl::string_view field) {
return CelValue::CreateError(interop::CreateNoSuchFieldError(
cel::extensions::ProtoMemoryManagerArena(manager), field));
}
CelValue CreateNoSuchFieldError(google::protobuf::Arena* arena, absl::string_view field) {
return CelValue::CreateError(interop::CreateNoSuchFieldError(arena, field));
}
CelValue CreateNoSuchKeyError(cel::MemoryManagerRef manager,
absl::string_view key) {
return CelValue::CreateError(interop::CreateNoSuchKeyError(
cel::extensions::ProtoMemoryManagerArena(manager), key));
}
CelValue CreateNoSuchKeyError(google::protobuf::Arena* arena, absl::string_view key) {
return CelValue::CreateError(interop::CreateNoSuchKeyError(arena, key));
}
bool CheckNoSuchKeyError(CelValue value) {
return value.IsError() &&
absl::StartsWith(value.ErrorOrDie()->message(),
cel::runtime_internal::kErrNoSuchKey);
}
CelValue CreateMissingAttributeError(google::protobuf::Arena* arena,
absl::string_view missing_attribute_path) {
return CelValue::CreateError(
interop::CreateMissingAttributeError(arena, missing_attribute_path));
}
CelValue CreateMissingAttributeError(cel::MemoryManagerRef manager,
absl::string_view missing_attribute_path) {
return CelValue::CreateError(interop::CreateMissingAttributeError(
cel::extensions::ProtoMemoryManagerArena(manager),
missing_attribute_path));
}
bool IsMissingAttributeError(const CelValue& value) {
const CelError* error;
if (!value.GetValue(&error)) return false;
if (error && error->code() == absl::StatusCode::kInvalidArgument) {
auto path = error->GetPayload(
cel::runtime_internal::kPayloadUrlMissingAttributePath);
return path.has_value();
}
return false;
}
CelValue CreateUnknownFunctionResultError(cel::MemoryManagerRef manager,
absl::string_view help_message) {
return CelValue::CreateError(interop::CreateUnknownFunctionResultError(
cel::extensions::ProtoMemoryManagerArena(manager), help_message));
}
CelValue CreateUnknownFunctionResultError(google::protobuf::Arena* arena,
absl::string_view help_message) {
return CelValue::CreateError(
interop::CreateUnknownFunctionResultError(arena, help_message));
}
bool IsUnknownFunctionResult(const CelValue& value) {
const CelError* error;
if (!value.GetValue(&error)) return false;
if (error == nullptr || error->code() != absl::StatusCode::kUnavailable) {
return false;
}
auto payload = error->GetPayload(
cel::runtime_internal::kPayloadUrlUnknownFunctionResult);
return payload.has_value() && payload.value() == "true";
}
} | #include "eval/public/cel_value.h"
#include <cstdint>
#include <string>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "common/memory.h"
#include "eval/internal/errors.h"
#include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/public/testing/matchers.h"
#include "eval/public/unknown_set.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::runtime_internal::kDurationHigh;
using ::cel::runtime_internal::kDurationLow;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::NotNull;
class DummyMap : public CelMap {
public:
absl::optional<CelValue> operator[](CelValue value) const override {
return CelValue::CreateNull();
}
absl::StatusOr<const CelList*> ListKeys() const override {
return absl::UnimplementedError("CelMap::ListKeys is not implemented");
}
int size() const override { return 0; }
};
class DummyList : public CelList {
public:
int size() const override { return 0; }
CelValue operator[](int index) const override {
return CelValue::CreateNull();
}
};
TEST(CelValueTest, TestType) {
::google::protobuf::Arena arena;
CelValue value_null = CelValue::CreateNull();
EXPECT_THAT(value_null.type(), Eq(CelValue::Type::kNullType));
CelValue value_bool = CelValue::CreateBool(false);
EXPECT_THAT(value_bool.type(), Eq(CelValue::Type::kBool));
CelValue value_int64 = CelValue::CreateInt64(0);
EXPECT_THAT(value_int64.type(), Eq(CelValue::Type::kInt64));
CelValue value_uint64 = CelValue::CreateUint64(1);
EXPECT_THAT(value_uint64.type(), Eq(CelValue::Type::kUint64));
CelValue value_double = CelValue::CreateDouble(1.0);
EXPECT_THAT(value_double.type(), Eq(CelValue::Type::kDouble));
std::string str = "test";
CelValue value_str = CelValue::CreateString(&str);
EXPECT_THAT(value_str.type(), Eq(CelValue::Type::kString));
std::string bytes_str = "bytes";
CelValue value_bytes = CelValue::CreateBytes(&bytes_str);
EXPECT_THAT(value_bytes.type(), Eq(CelValue::Type::kBytes));
UnknownSet unknown_set;
CelValue value_unknown = CelValue::CreateUnknownSet(&unknown_set);
EXPECT_THAT(value_unknown.type(), Eq(CelValue::Type::kUnknownSet));
CelValue missing_attribute_error =
CreateMissingAttributeError(&arena, "destination.ip");
EXPECT_TRUE(IsMissingAttributeError(missing_attribute_error));
EXPECT_EQ(missing_attribute_error.ErrorOrDie()->code(),
absl::StatusCode::kInvalidArgument);
EXPECT_EQ(missing_attribute_error.ErrorOrDie()->message(),
"MissingAttributeError: destination.ip");
}
int CountTypeMatch(const CelValue& value) {
int count = 0;
bool value_bool;
count += (value.GetValue(&value_bool)) ? 1 : 0;
int64_t value_int64;
count += (value.GetValue(&value_int64)) ? 1 : 0;
uint64_t value_uint64;
count += (value.GetValue(&value_uint64)) ? 1 : 0;
double value_double;
count += (value.GetValue(&value_double)) ? 1 : 0;
std::string test = "";
CelValue::StringHolder value_str(&test);
count += (value.GetValue(&value_str)) ? 1 : 0;
CelValue::BytesHolder value_bytes(&test);
count += (value.GetValue(&value_bytes)) ? 1 : 0;
const google::protobuf::Message* value_msg;
count += (value.GetValue(&value_msg)) ? 1 : 0;
const CelList* value_list;
count += (value.GetValue(&value_list)) ? 1 : 0;
const CelMap* value_map;
count += (value.GetValue(&value_map)) ? 1 : 0;
const CelError* value_error;
count += (value.GetValue(&value_error)) ? 1 : 0;
const UnknownSet* value_unknown;
count += (value.GetValue(&value_unknown)) ? 1 : 0;
return count;
}
TEST(CelValueTest, TestBool) {
CelValue value = CelValue::CreateBool(true);
EXPECT_TRUE(value.IsBool());
EXPECT_THAT(value.BoolOrDie(), Eq(true));
bool value2 = false;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_EQ(value2, true);
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestInt64) {
int64_t v = 1;
CelValue value = CelValue::CreateInt64(v);
EXPECT_TRUE(value.IsInt64());
EXPECT_THAT(value.Int64OrDie(), Eq(1));
int64_t value2 = 0;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_EQ(value2, 1);
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestUint64) {
uint64_t v = 1;
CelValue value = CelValue::CreateUint64(v);
EXPECT_TRUE(value.IsUint64());
EXPECT_THAT(value.Uint64OrDie(), Eq(1));
uint64_t value2 = 0;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_EQ(value2, 1);
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestDouble) {
double v0 = 1.;
CelValue value = CelValue::CreateDouble(v0);
EXPECT_TRUE(value.IsDouble());
EXPECT_THAT(value.DoubleOrDie(), Eq(v0));
double value2 = 0;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_DOUBLE_EQ(value2, 1);
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestDurationRangeCheck) {
EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(1)),
test::IsCelDuration(absl::Seconds(1)));
EXPECT_THAT(
CelValue::CreateDuration(kDurationHigh),
test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Duration is out of range"))));
EXPECT_THAT(
CelValue::CreateDuration(kDurationLow),
test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Duration is out of range"))));
EXPECT_THAT(CelValue::CreateDuration(kDurationLow + absl::Seconds(1)),
test::IsCelDuration(kDurationLow + absl::Seconds(1)));
}
TEST(CelValueTest, TestString) {
constexpr char kTestStr0[] = "test0";
std::string v = kTestStr0;
CelValue value = CelValue::CreateString(&v);
EXPECT_TRUE(value.IsString());
EXPECT_THAT(value.StringOrDie().value(), Eq(std::string(kTestStr0)));
std::string test = "";
CelValue::StringHolder value2(&test);
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_THAT(value2.value(), Eq(kTestStr0));
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestBytes) {
constexpr char kTestStr0[] = "test0";
std::string v = kTestStr0;
CelValue value = CelValue::CreateBytes(&v);
EXPECT_TRUE(value.IsBytes());
EXPECT_THAT(value.BytesOrDie().value(), Eq(std::string(kTestStr0)));
std::string test = "";
CelValue::BytesHolder value2(&test);
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_THAT(value2.value(), Eq(kTestStr0));
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestList) {
DummyList dummy_list;
CelValue value = CelValue::CreateList(&dummy_list);
EXPECT_TRUE(value.IsList());
EXPECT_THAT(value.ListOrDie(), Eq(&dummy_list));
const CelList* value2;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_THAT(value2, Eq(&dummy_list));
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestEmptyList) {
::google::protobuf::Arena arena;
CelValue value = CelValue::CreateList();
EXPECT_TRUE(value.IsList());
const CelList* value2;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_TRUE(value2->empty());
EXPECT_EQ(value2->size(), 0);
EXPECT_THAT(value2->Get(&arena, 0),
test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument)));
}
TEST(CelValueTest, TestMap) {
DummyMap dummy_map;
CelValue value = CelValue::CreateMap(&dummy_map);
EXPECT_TRUE(value.IsMap());
EXPECT_THAT(value.MapOrDie(), Eq(&dummy_map));
const CelMap* value2;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_THAT(value2, Eq(&dummy_map));
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, TestEmptyMap) {
::google::protobuf::Arena arena;
CelValue value = CelValue::CreateMap();
EXPECT_TRUE(value.IsMap());
const CelMap* value2;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_TRUE(value2->empty());
EXPECT_EQ(value2->size(), 0);
EXPECT_THAT(value2->Has(CelValue::CreateBool(false)), IsOkAndHolds(false));
EXPECT_THAT(value2->Get(&arena, CelValue::CreateBool(false)),
Eq(absl::nullopt));
EXPECT_THAT(value2->ListKeys(&arena), IsOkAndHolds(NotNull()));
}
TEST(CelValueTest, TestCelType) {
::google::protobuf::Arena arena;
CelValue value_null = CelValue::CreateNullTypedValue();
EXPECT_THAT(value_null.ObtainCelType().CelTypeOrDie().value(),
Eq("null_type"));
CelValue value_bool = CelValue::CreateBool(false);
EXPECT_THAT(value_bool.ObtainCelType().CelTypeOrDie().value(), Eq("bool"));
CelValue value_int64 = CelValue::CreateInt64(0);
EXPECT_THAT(value_int64.ObtainCelType().CelTypeOrDie().value(), Eq("int"));
CelValue value_uint64 = CelValue::CreateUint64(0);
EXPECT_THAT(value_uint64.ObtainCelType().CelTypeOrDie().value(), Eq("uint"));
CelValue value_double = CelValue::CreateDouble(1.0);
EXPECT_THAT(value_double.ObtainCelType().CelTypeOrDie().value(),
Eq("double"));
std::string str = "test";
CelValue value_str = CelValue::CreateString(&str);
EXPECT_THAT(value_str.ObtainCelType().CelTypeOrDie().value(), Eq("string"));
std::string bytes_str = "bytes";
CelValue value_bytes = CelValue::CreateBytes(&bytes_str);
EXPECT_THAT(value_bytes.type(), Eq(CelValue::Type::kBytes));
EXPECT_THAT(value_bytes.ObtainCelType().CelTypeOrDie().value(), Eq("bytes"));
std::string msg_type_str = "google.api.expr.runtime.TestMessage";
CelValue msg_type = CelValue::CreateCelTypeView(msg_type_str);
EXPECT_TRUE(msg_type.IsCelType());
EXPECT_THAT(msg_type.CelTypeOrDie().value(),
Eq("google.api.expr.runtime.TestMessage"));
EXPECT_THAT(msg_type.type(), Eq(CelValue::Type::kCelType));
UnknownSet unknown_set;
CelValue value_unknown = CelValue::CreateUnknownSet(&unknown_set);
EXPECT_THAT(value_unknown.type(), Eq(CelValue::Type::kUnknownSet));
EXPECT_TRUE(value_unknown.ObtainCelType().IsUnknownSet());
}
TEST(CelValueTest, TestUnknownSet) {
UnknownSet unknown_set;
CelValue value = CelValue::CreateUnknownSet(&unknown_set);
EXPECT_TRUE(value.IsUnknownSet());
EXPECT_THAT(value.UnknownSetOrDie(), Eq(&unknown_set));
const UnknownSet* value2;
EXPECT_TRUE(value.GetValue(&value2));
EXPECT_THAT(value2, Eq(&unknown_set));
EXPECT_THAT(CountTypeMatch(value), Eq(1));
}
TEST(CelValueTest, SpecialErrorFactories) {
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
CelValue error = CreateNoSuchKeyError(manager, "key");
EXPECT_THAT(error, test::IsCelError(StatusIs(absl::StatusCode::kNotFound)));
EXPECT_TRUE(CheckNoSuchKeyError(error));
error = CreateNoSuchFieldError(manager, "field");
EXPECT_THAT(error, test::IsCelError(StatusIs(absl::StatusCode::kNotFound)));
error = CreateNoMatchingOverloadError(manager, "function");
EXPECT_THAT(error, test::IsCelError(StatusIs(absl::StatusCode::kUnknown)));
EXPECT_TRUE(CheckNoMatchingOverloadError(error));
absl::Status error_status = absl::InternalError("internal error");
error_status.SetPayload("CreateErrorValuePreservesFullStatusMessage",
absl::Cord("more information"));
error = CreateErrorValue(manager, error_status);
EXPECT_THAT(error, test::IsCelError(error_status));
error = CreateErrorValue(&arena, error_status);
EXPECT_THAT(error, test::IsCelError(error_status));
}
TEST(CelValueTest, MissingAttributeErrorsDeprecated) {
google::protobuf::Arena arena;
CelValue missing_attribute_error =
CreateMissingAttributeError(&arena, "destination.ip");
EXPECT_TRUE(IsMissingAttributeError(missing_attribute_error));
EXPECT_TRUE(missing_attribute_error.ObtainCelType().IsError());
}
TEST(CelValueTest, MissingAttributeErrors) {
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
CelValue missing_attribute_error =
CreateMissingAttributeError(manager, "destination.ip");
EXPECT_TRUE(IsMissingAttributeError(missing_attribute_error));
EXPECT_TRUE(missing_attribute_error.ObtainCelType().IsError());
}
TEST(CelValueTest, UnknownFunctionResultErrorsDeprecated) {
google::protobuf::Arena arena;
CelValue value = CreateUnknownFunctionResultError(&arena, "message");
EXPECT_TRUE(value.IsError());
EXPECT_TRUE(IsUnknownFunctionResult(value));
}
TEST(CelValueTest, UnknownFunctionResultErrors) {
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
CelValue value = CreateUnknownFunctionResultError(manager, "message");
EXPECT_TRUE(value.IsError());
EXPECT_TRUE(IsUnknownFunctionResult(value));
}
TEST(CelValueTest, DebugString) {
EXPECT_EQ(CelValue::CreateNull().DebugString(), "null_type: null");
EXPECT_EQ(CelValue::CreateBool(true).DebugString(), "bool: 1");
EXPECT_EQ(CelValue::CreateInt64(-12345).DebugString(), "int64: -12345");
EXPECT_EQ(CelValue::CreateUint64(12345).DebugString(), "uint64: 12345");
EXPECT_TRUE(absl::StartsWith(CelValue::CreateDouble(0.12345).DebugString(),
"double: 0.12345"));
const std::string abc("abc");
EXPECT_EQ(CelValue::CreateString(&abc).DebugString(), "string: abc");
EXPECT_EQ(CelValue::CreateBytes(&abc).DebugString(), "bytes: abc");
EXPECT_EQ(CelValue::CreateDuration(absl::Hours(24)).DebugString(),
"Duration: 24h");
EXPECT_EQ(
CelValue::CreateTimestamp(absl::FromUnixSeconds(86400)).DebugString(),
"Timestamp: 1970-01-02T00:00:00+00:00");
UnknownSet unknown_set;
EXPECT_EQ(CelValue::CreateUnknownSet(&unknown_set).DebugString(),
"UnknownSet: ?");
absl::Status error = absl::InternalError("Blah...");
EXPECT_EQ(CelValue::CreateError(&error).DebugString(),
"CelError: INTERNAL: Blah...");
}
TEST(CelValueTest, Message) {
TestMessage message;
auto value = CelValue::CreateMessageWrapper(
CelValue::MessageWrapper(&message, TrivialTypeInfo::GetInstance()));
EXPECT_TRUE(value.IsMessage());
CelValue::MessageWrapper held;
ASSERT_TRUE(value.GetValue(&held));
EXPECT_TRUE(held.HasFullProto());
EXPECT_EQ(held.message_ptr(),
static_cast<const google::protobuf::MessageLite*>(&message));
EXPECT_EQ(held.legacy_type_info(), TrivialTypeInfo::GetInstance());
EXPECT_EQ(value.ObtainCelType().CelTypeOrDie().value(), "opaque");
EXPECT_EQ(value.DebugString(), "Message: opaque");
}
TEST(CelValueTest, MessageLite) {
TestMessage message;
const google::protobuf::MessageLite* ptr = &message;
auto value = CelValue::CreateMessageWrapper(
CelValue::MessageWrapper(ptr, TrivialTypeInfo::GetInstance()));
EXPECT_TRUE(value.IsMessage());
CelValue::MessageWrapper held;
ASSERT_TRUE(value.GetValue(&held));
EXPECT_FALSE(held.HasFullProto());
EXPECT_EQ(held.message_ptr(), &message);
EXPECT_EQ(held.legacy_type_info(), TrivialTypeInfo::GetInstance());
EXPECT_EQ(value.ObtainCelType().CelTypeOrDie().value(), "opaque");
EXPECT_EQ(value.DebugString(), "Message: opaque");
}
TEST(CelValueTest, Size) {
static_assert(sizeof(CelValue) <= 3 * sizeof(uintptr_t));
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_value.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_value_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
6d7c5496-6c39-4052-b4be-06ee7b55571d | cpp | google/cel-cpp | matchers | eval/public/testing/matchers.cc | eval/public/testing/matchers_test.cc | #include "eval/public/testing/matchers.h"
#include <ostream>
#include <utility>
#include "google/protobuf/message.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "eval/public/set_util.h"
#include "internal/casts.h"
namespace google::api::expr::runtime {
void PrintTo(const CelValue& value, std::ostream* os) {
*os << value.DebugString();
}
namespace test {
namespace {
using ::testing::_;
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
class CelValueEqualImpl : public MatcherInterface<CelValue> {
public:
explicit CelValueEqualImpl(const CelValue& v) : value_(v) {}
bool MatchAndExplain(CelValue arg,
MatchResultListener* listener) const override {
return CelValueEqual(arg, value_);
}
void DescribeTo(std::ostream* os) const override {
*os << value_.DebugString();
}
private:
const CelValue& value_;
};
template <typename UnderlyingType>
class CelValueMatcherImpl : public testing::MatcherInterface<const CelValue&> {
public:
explicit CelValueMatcherImpl(testing::Matcher<UnderlyingType> m)
: underlying_type_matcher_(std::move(m)) {}
bool MatchAndExplain(const CelValue& v,
testing::MatchResultListener* listener) const override {
UnderlyingType arg;
return v.GetValue(&arg) && underlying_type_matcher_.Matches(arg);
}
void DescribeTo(std::ostream* os) const override {
CelValue::Type type =
static_cast<CelValue::Type>(CelValue::IndexOf<UnderlyingType>::value);
*os << absl::StrCat("type is ", CelValue::TypeName(type), " and ");
underlying_type_matcher_.DescribeTo(os);
}
private:
const testing::Matcher<UnderlyingType> underlying_type_matcher_;
};
template <>
class CelValueMatcherImpl<const google::protobuf::Message*>
: public testing::MatcherInterface<const CelValue&> {
public:
explicit CelValueMatcherImpl(testing::Matcher<const google::protobuf::Message*> m)
: underlying_type_matcher_(std::move(m)) {}
bool MatchAndExplain(const CelValue& v,
testing::MatchResultListener* listener) const override {
CelValue::MessageWrapper arg;
return v.GetValue(&arg) && arg.HasFullProto() &&
underlying_type_matcher_.Matches(
cel::internal::down_cast<const google::protobuf::Message*>(
arg.message_ptr()));
}
void DescribeTo(std::ostream* os) const override {
*os << absl::StrCat("type is ",
CelValue::TypeName(CelValue::Type::kMessage), " and ");
underlying_type_matcher_.DescribeTo(os);
}
private:
const testing::Matcher<const google::protobuf::Message*> underlying_type_matcher_;
};
}
CelValueMatcher EqualsCelValue(const CelValue& v) {
return CelValueMatcher(new CelValueEqualImpl(v));
}
CelValueMatcher IsCelNull() {
return CelValueMatcher(new CelValueMatcherImpl<CelValue::NullType>(_));
}
CelValueMatcher IsCelBool(testing::Matcher<bool> m) {
return CelValueMatcher(new CelValueMatcherImpl<bool>(std::move(m)));
}
CelValueMatcher IsCelInt64(testing::Matcher<int64_t> m) {
return CelValueMatcher(new CelValueMatcherImpl<int64_t>(std::move(m)));
}
CelValueMatcher IsCelUint64(testing::Matcher<uint64_t> m) {
return CelValueMatcher(new CelValueMatcherImpl<uint64_t>(std::move(m)));
}
CelValueMatcher IsCelDouble(testing::Matcher<double> m) {
return CelValueMatcher(new CelValueMatcherImpl<double>(std::move(m)));
}
CelValueMatcher IsCelString(testing::Matcher<absl::string_view> m) {
return CelValueMatcher(new CelValueMatcherImpl<CelValue::StringHolder>(
testing::Property(&CelValue::StringHolder::value, m)));
}
CelValueMatcher IsCelBytes(testing::Matcher<absl::string_view> m) {
return CelValueMatcher(new CelValueMatcherImpl<CelValue::BytesHolder>(
testing::Property(&CelValue::BytesHolder::value, m)));
}
CelValueMatcher IsCelMessage(testing::Matcher<const google::protobuf::Message*> m) {
return CelValueMatcher(
new CelValueMatcherImpl<const google::protobuf::Message*>(std::move(m)));
}
CelValueMatcher IsCelDuration(testing::Matcher<absl::Duration> m) {
return CelValueMatcher(new CelValueMatcherImpl<absl::Duration>(std::move(m)));
}
CelValueMatcher IsCelTimestamp(testing::Matcher<absl::Time> m) {
return CelValueMatcher(new CelValueMatcherImpl<absl::Time>(std::move(m)));
}
CelValueMatcher IsCelError(testing::Matcher<absl::Status> m) {
return CelValueMatcher(
new CelValueMatcherImpl<const google::api::expr::runtime::CelError*>(
testing::AllOf(testing::NotNull(), testing::Pointee(m))));
}
}
} | #include "eval/public/testing/matchers.h"
#include "absl/status/status.h"
#include "absl/time/time.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
#include "testutil/util.h"
namespace google::api::expr::runtime::test {
namespace {
using ::testing::Contains;
using ::testing::DoubleEq;
using ::testing::DoubleNear;
using ::testing::ElementsAre;
using ::testing::Gt;
using ::testing::Lt;
using ::testing::Not;
using ::testing::UnorderedElementsAre;
using testutil::EqualsProto;
TEST(IsCelValue, EqualitySmoketest) {
EXPECT_THAT(CelValue::CreateBool(true),
EqualsCelValue(CelValue::CreateBool(true)));
EXPECT_THAT(CelValue::CreateInt64(-1),
EqualsCelValue(CelValue::CreateInt64(-1)));
EXPECT_THAT(CelValue::CreateUint64(2),
EqualsCelValue(CelValue::CreateUint64(2)));
EXPECT_THAT(CelValue::CreateDouble(1.25),
EqualsCelValue(CelValue::CreateDouble(1.25)));
EXPECT_THAT(CelValue::CreateStringView("abc"),
EqualsCelValue(CelValue::CreateStringView("abc")));
EXPECT_THAT(CelValue::CreateBytesView("def"),
EqualsCelValue(CelValue::CreateBytesView("def")));
EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)),
EqualsCelValue(CelValue::CreateDuration(absl::Seconds(2))));
EXPECT_THAT(
CelValue::CreateTimestamp(absl::FromUnixSeconds(1)),
EqualsCelValue(CelValue::CreateTimestamp(absl::FromUnixSeconds(1))));
EXPECT_THAT(CelValue::CreateInt64(-1),
Not(EqualsCelValue(CelValue::CreateBool(true))));
EXPECT_THAT(CelValue::CreateUint64(2),
Not(EqualsCelValue(CelValue::CreateInt64(-1))));
EXPECT_THAT(CelValue::CreateDouble(1.25),
Not(EqualsCelValue(CelValue::CreateUint64(2))));
EXPECT_THAT(CelValue::CreateStringView("abc"),
Not(EqualsCelValue(CelValue::CreateDouble(1.25))));
EXPECT_THAT(CelValue::CreateBytesView("def"),
Not(EqualsCelValue(CelValue::CreateStringView("abc"))));
EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)),
Not(EqualsCelValue(CelValue::CreateBytesView("def"))));
EXPECT_THAT(CelValue::CreateTimestamp(absl::FromUnixSeconds(1)),
Not(EqualsCelValue(CelValue::CreateDuration(absl::Seconds(2)))));
EXPECT_THAT(
CelValue::CreateBool(true),
Not(EqualsCelValue(CelValue::CreateTimestamp(absl::FromUnixSeconds(1)))));
}
TEST(PrimitiveMatchers, Smoketest) {
EXPECT_THAT(CelValue::CreateNull(), IsCelNull());
EXPECT_THAT(CelValue::CreateBool(false), Not(IsCelNull()));
EXPECT_THAT(CelValue::CreateBool(true), IsCelBool(true));
EXPECT_THAT(CelValue::CreateBool(false), IsCelBool(Not(true)));
EXPECT_THAT(CelValue::CreateInt64(1), IsCelInt64(1));
EXPECT_THAT(CelValue::CreateInt64(-1), IsCelInt64(Not(Gt(0))));
EXPECT_THAT(CelValue::CreateUint64(1), IsCelUint64(1));
EXPECT_THAT(CelValue::CreateUint64(2), IsCelUint64(Not(Lt(2))));
EXPECT_THAT(CelValue::CreateDouble(1.5), IsCelDouble(DoubleEq(1.5)));
EXPECT_THAT(CelValue::CreateDouble(1.0 + 0.8),
IsCelDouble(DoubleNear(1.8, 1e-5)));
EXPECT_THAT(CelValue::CreateStringView("abc"), IsCelString("abc"));
EXPECT_THAT(CelValue::CreateStringView("abcdef"),
IsCelString(testing::HasSubstr("def")));
EXPECT_THAT(CelValue::CreateBytesView("abc"), IsCelBytes("abc"));
EXPECT_THAT(CelValue::CreateBytesView("abcdef"),
IsCelBytes(testing::HasSubstr("def")));
EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)),
IsCelDuration(Lt(absl::Minutes(1))));
EXPECT_THAT(CelValue::CreateTimestamp(absl::FromUnixSeconds(20)),
IsCelTimestamp(Lt(absl::FromUnixSeconds(30))));
}
TEST(PrimitiveMatchers, WrongType) {
EXPECT_THAT(CelValue::CreateBool(true), Not(IsCelInt64(1)));
EXPECT_THAT(CelValue::CreateInt64(1), Not(IsCelUint64(1)));
EXPECT_THAT(CelValue::CreateUint64(1), Not(IsCelDouble(1.0)));
EXPECT_THAT(CelValue::CreateDouble(1.5), Not(IsCelString("abc")));
EXPECT_THAT(CelValue::CreateStringView("abc"), Not(IsCelBytes("abc")));
EXPECT_THAT(CelValue::CreateBytesView("abc"),
Not(IsCelDuration(Lt(absl::Minutes(1)))));
EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)),
Not(IsCelTimestamp(Lt(absl::FromUnixSeconds(30)))));
EXPECT_THAT(CelValue::CreateTimestamp(absl::FromUnixSeconds(20)),
Not(IsCelBool(true)));
}
TEST(SpecialMatchers, SmokeTest) {
auto status = absl::InternalError("error");
CelValue error = CelValue::CreateError(&status);
EXPECT_THAT(error, IsCelError(testing::Eq(
absl::Status(absl::StatusCode::kInternal, "error"))));
TestMessage proto_message;
proto_message.add_bool_list(true);
proto_message.add_bool_list(false);
proto_message.add_int64_list(1);
proto_message.add_int64_list(-1);
CelValue message = CelProtoWrapper::CreateMessage(&proto_message, nullptr);
EXPECT_THAT(message, IsCelMessage(EqualsProto(proto_message)));
}
TEST(ListMatchers, NotList) {
EXPECT_THAT(CelValue::CreateInt64(1),
Not(IsCelList(Contains(IsCelInt64(1)))));
}
TEST(ListMatchers, All) {
ContainerBackedListImpl list({
CelValue::CreateInt64(1),
CelValue::CreateInt64(2),
CelValue::CreateInt64(3),
CelValue::CreateInt64(4),
});
CelValue cel_list = CelValue::CreateList(&list);
EXPECT_THAT(cel_list, IsCelList(Contains(IsCelInt64(3))));
EXPECT_THAT(cel_list, IsCelList(Not(Contains(IsCelInt64(0)))));
EXPECT_THAT(cel_list, IsCelList(ElementsAre(IsCelInt64(1), IsCelInt64(2),
IsCelInt64(3), IsCelInt64(4))));
EXPECT_THAT(cel_list,
IsCelList(Not(ElementsAre(IsCelInt64(2), IsCelInt64(1),
IsCelInt64(3), IsCelInt64(4)))));
EXPECT_THAT(cel_list,
IsCelList(UnorderedElementsAre(IsCelInt64(2), IsCelInt64(1),
IsCelInt64(4), IsCelInt64(3))));
EXPECT_THAT(
cel_list,
IsCelList(Not(UnorderedElementsAre(IsCelInt64(2), IsCelInt64(1),
IsCelInt64(4), IsCelInt64(0)))));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/testing/matchers.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/testing/matchers_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
7d226d97-756f-49e0-8122-2a6f998635ce | cpp | google/cel-cpp | protobuf_descriptor_type_provider | eval/public/structs/protobuf_descriptor_type_provider.cc | eval/public/structs/protobuf_descriptor_type_provider_test.cc | #include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include <memory>
#include <utility>
#include "google/protobuf/descriptor.h"
#include "absl/synchronization/mutex.h"
#include "eval/public/structs/proto_message_type_adapter.h"
namespace google::api::expr::runtime {
absl::optional<LegacyTypeAdapter> ProtobufDescriptorProvider::ProvideLegacyType(
absl::string_view name) const {
const ProtoMessageTypeAdapter* result = GetTypeAdapter(name);
if (result == nullptr) {
return absl::nullopt;
}
return LegacyTypeAdapter(result, result);
}
absl::optional<const LegacyTypeInfoApis*>
ProtobufDescriptorProvider::ProvideLegacyTypeInfo(
absl::string_view name) const {
const ProtoMessageTypeAdapter* result = GetTypeAdapter(name);
if (result == nullptr) {
return absl::nullopt;
}
return result;
}
std::unique_ptr<ProtoMessageTypeAdapter>
ProtobufDescriptorProvider::CreateTypeAdapter(absl::string_view name) const {
const google::protobuf::Descriptor* descriptor =
descriptor_pool_->FindMessageTypeByName(name);
if (descriptor == nullptr) {
return nullptr;
}
return std::make_unique<ProtoMessageTypeAdapter>(descriptor,
message_factory_);
}
const ProtoMessageTypeAdapter* ProtobufDescriptorProvider::GetTypeAdapter(
absl::string_view name) const {
absl::MutexLock lock(&mu_);
auto it = type_cache_.find(name);
if (it != type_cache_.end()) {
return it->second.get();
}
auto type_provider = CreateTypeAdapter(name);
const ProtoMessageTypeAdapter* result = type_provider.get();
type_cache_[name] = std::move(type_provider);
return result;
}
} | #include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include <optional>
#include "google/protobuf/wrappers.pb.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "eval/public/testing/matchers.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::extensions::ProtoMemoryManager;
TEST(ProtobufDescriptorProvider, Basic) {
ProtobufDescriptorProvider provider(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory());
google::protobuf::Arena arena;
auto manager = ProtoMemoryManager(&arena);
auto type_adapter = provider.ProvideLegacyType("google.protobuf.Int64Value");
absl::optional<const LegacyTypeInfoApis*> type_info =
provider.ProvideLegacyTypeInfo("google.protobuf.Int64Value");
ASSERT_TRUE(type_adapter.has_value());
ASSERT_TRUE(type_adapter->mutation_apis() != nullptr);
ASSERT_TRUE(type_info.has_value());
ASSERT_TRUE(type_info != nullptr);
google::protobuf::Int64Value int64_value;
CelValue::MessageWrapper int64_cel_value(&int64_value, *type_info);
EXPECT_EQ((*type_info)->GetTypename(int64_cel_value),
"google.protobuf.Int64Value");
ASSERT_TRUE(type_adapter->mutation_apis()->DefinesField("value"));
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder value,
type_adapter->mutation_apis()->NewInstance(manager));
ASSERT_OK(type_adapter->mutation_apis()->SetField(
"value", CelValue::CreateInt64(10), manager, value));
ASSERT_OK_AND_ASSIGN(
CelValue adapted,
type_adapter->mutation_apis()->AdaptFromWellKnownType(manager, value));
EXPECT_THAT(adapted, test::IsCelInt64(10));
}
TEST(ProtobufDescriptorProvider, MemoizesAdapters) {
ProtobufDescriptorProvider provider(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory());
auto type_adapter = provider.ProvideLegacyType("google.protobuf.Int64Value");
ASSERT_TRUE(type_adapter.has_value());
ASSERT_TRUE(type_adapter->mutation_apis() != nullptr);
auto type_adapter2 = provider.ProvideLegacyType("google.protobuf.Int64Value");
ASSERT_TRUE(type_adapter2.has_value());
EXPECT_EQ(type_adapter->mutation_apis(), type_adapter2->mutation_apis());
EXPECT_EQ(type_adapter->access_apis(), type_adapter2->access_apis());
}
TEST(ProtobufDescriptorProvider, NotFound) {
ProtobufDescriptorProvider provider(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory());
auto type_adapter = provider.ProvideLegacyType("UnknownType");
auto type_info = provider.ProvideLegacyTypeInfo("UnknownType");
ASSERT_FALSE(type_adapter.has_value());
ASSERT_FALSE(type_info.has_value());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/protobuf_descriptor_type_provider.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/protobuf_descriptor_type_provider_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
72404f3d-ecd2-4b7c-a0d4-46a6e8782029 | cpp | google/cel-cpp | proto_message_type_adapter | eval/public/structs/proto_message_type_adapter.cc | eval/public/structs/proto_message_type_adapter_test.cc | #include "eval/public/structs/proto_message_type_adapter.h"
#include <cstdint>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "google/protobuf/util/message_differencer.h"
#include "absl/base/no_destructor.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "base/attribute.h"
#include "common/memory.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/internal_field_backed_list_impl.h"
#include "eval/public/containers/internal_field_backed_map_impl.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/cel_proto_wrap_util.h"
#include "eval/public/structs/field_access_impl.h"
#include "eval/public/structs/legacy_type_adapter.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "extensions/protobuf/internal/qualify.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/casts.h"
#include "internal/status_macros.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/map_field.h"
#include "google/protobuf/message.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::extensions::ProtoMemoryManagerArena;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::Message;
using ::google::protobuf::Reflection;
using LegacyQualifyResult = LegacyTypeAccessApis::LegacyQualifyResult;
const std::string& UnsupportedTypeName() {
static absl::NoDestructor<std::string> kUnsupportedTypeName(
"<unknown message>");
return *kUnsupportedTypeName;
}
CelValue MessageCelValueFactory(const google::protobuf::Message* message);
inline absl::StatusOr<const google::protobuf::Message*> UnwrapMessage(
const MessageWrapper& value, absl::string_view op) {
if (!value.HasFullProto() || value.message_ptr() == nullptr) {
return absl::InternalError(
absl::StrCat(op, " called on non-message type."));
}
return static_cast<const google::protobuf::Message*>(value.message_ptr());
}
inline absl::StatusOr<google::protobuf::Message*> UnwrapMessage(
const MessageWrapper::Builder& value, absl::string_view op) {
if (!value.HasFullProto() || value.message_ptr() == nullptr) {
return absl::InternalError(
absl::StrCat(op, " called on non-message type."));
}
return static_cast<google::protobuf::Message*>(value.message_ptr());
}
bool ProtoEquals(const google::protobuf::Message& m1, const google::protobuf::Message& m2) {
if (m1.GetDescriptor() != m2.GetDescriptor()) {
return false;
}
return google::protobuf::util::MessageDifferencer::Equals(m1, m2);
}
bool CelFieldIsPresent(const google::protobuf::Message* message,
const google::protobuf::FieldDescriptor* field_desc,
const google::protobuf::Reflection* reflection) {
if (field_desc->is_map()) {
return reflection->FieldSize(*message, field_desc) != 0;
}
if (field_desc->is_repeated()) {
return reflection->FieldSize(*message, field_desc) != 0;
}
return reflection->HasField(*message, field_desc);
}
absl::StatusOr<bool> HasFieldImpl(const google::protobuf::Message* message,
const google::protobuf::Descriptor* descriptor,
absl::string_view field_name) {
ABSL_ASSERT(descriptor == message->GetDescriptor());
const Reflection* reflection = message->GetReflection();
const FieldDescriptor* field_desc = descriptor->FindFieldByName(field_name);
if (field_desc == nullptr && reflection != nullptr) {
field_desc = reflection->FindKnownExtensionByName(field_name);
}
if (field_desc == nullptr) {
return absl::NotFoundError(absl::StrCat("no_such_field : ", field_name));
}
if (reflection == nullptr) {
return absl::FailedPreconditionError(
"google::protobuf::Reflection unavailble in CEL field access.");
}
return CelFieldIsPresent(message, field_desc, reflection);
}
absl::StatusOr<CelValue> CreateCelValueFromField(
const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_desc,
ProtoWrapperTypeOptions unboxing_option, google::protobuf::Arena* arena) {
if (field_desc->is_map()) {
auto* map = google::protobuf::Arena::Create<internal::FieldBackedMapImpl>(
arena, message, field_desc, &MessageCelValueFactory, arena);
return CelValue::CreateMap(map);
}
if (field_desc->is_repeated()) {
auto* list = google::protobuf::Arena::Create<internal::FieldBackedListImpl>(
arena, message, field_desc, &MessageCelValueFactory, arena);
return CelValue::CreateList(list);
}
CEL_ASSIGN_OR_RETURN(
CelValue result,
internal::CreateValueFromSingleField(message, field_desc, unboxing_option,
&MessageCelValueFactory, arena));
return result;
}
absl::StatusOr<CelValue> GetFieldImpl(const google::protobuf::Message* message,
const google::protobuf::Descriptor* descriptor,
absl::string_view field_name,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager) {
ABSL_ASSERT(descriptor == message->GetDescriptor());
const Reflection* reflection = message->GetReflection();
const FieldDescriptor* field_desc = descriptor->FindFieldByName(field_name);
if (field_desc == nullptr && reflection != nullptr) {
std::string ext_name(field_name);
field_desc = reflection->FindKnownExtensionByName(ext_name);
}
if (field_desc == nullptr) {
return CreateNoSuchFieldError(memory_manager, field_name);
}
google::protobuf::Arena* arena = ProtoMemoryManagerArena(memory_manager);
return CreateCelValueFromField(message, field_desc, unboxing_option, arena);
}
class LegacyQualifyState final
: public cel::extensions::protobuf_internal::ProtoQualifyState {
public:
using ProtoQualifyState::ProtoQualifyState;
LegacyQualifyState(const LegacyQualifyState&) = delete;
LegacyQualifyState& operator=(const LegacyQualifyState&) = delete;
absl::optional<CelValue>& result() { return result_; }
private:
void SetResultFromError(absl::Status status,
cel::MemoryManagerRef memory_manager) override {
result_ = CreateErrorValue(memory_manager, status);
}
void SetResultFromBool(bool value) override {
result_ = CelValue::CreateBool(value);
}
absl::Status SetResultFromField(
const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager) override {
CEL_ASSIGN_OR_RETURN(result_, CreateCelValueFromField(
message, field, unboxing_option,
ProtoMemoryManagerArena(memory_manager)));
return absl::OkStatus();
}
absl::Status SetResultFromRepeatedField(
const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field,
int index, cel::MemoryManagerRef memory_manager) override {
CEL_ASSIGN_OR_RETURN(result_,
internal::CreateValueFromRepeatedField(
message, field, index, &MessageCelValueFactory,
ProtoMemoryManagerArena(memory_manager)));
return absl::OkStatus();
}
absl::Status SetResultFromMapField(
const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field,
const google::protobuf::MapValueConstRef& value,
cel::MemoryManagerRef memory_manager) override {
CEL_ASSIGN_OR_RETURN(result_,
internal::CreateValueFromMapValue(
message, field, &value, &MessageCelValueFactory,
ProtoMemoryManagerArena(memory_manager)));
return absl::OkStatus();
}
absl::optional<CelValue> result_;
};
absl::StatusOr<LegacyQualifyResult> QualifyImpl(
const google::protobuf::Message* message, const google::protobuf::Descriptor* descriptor,
absl::Span<const cel::SelectQualifier> path, bool presence_test,
cel::MemoryManagerRef memory_manager) {
google::protobuf::Arena* arena = ProtoMemoryManagerArena(memory_manager);
ABSL_DCHECK(descriptor == message->GetDescriptor());
LegacyQualifyState qualify_state(message, descriptor,
message->GetReflection());
for (int i = 0; i < path.size() - 1; i++) {
const auto& qualifier = path.at(i);
CEL_RETURN_IF_ERROR(qualify_state.ApplySelectQualifier(
qualifier, ProtoMemoryManagerRef(arena)));
if (qualify_state.result().has_value()) {
LegacyQualifyResult result;
result.value = std::move(qualify_state.result()).value();
result.qualifier_count = result.value.IsError() ? -1 : i + 1;
return result;
}
}
const auto& last_qualifier = path.back();
LegacyQualifyResult result;
result.qualifier_count = -1;
if (presence_test) {
CEL_RETURN_IF_ERROR(qualify_state.ApplyLastQualifierHas(
last_qualifier, ProtoMemoryManagerRef(arena)));
} else {
CEL_RETURN_IF_ERROR(qualify_state.ApplyLastQualifierGet(
last_qualifier, ProtoMemoryManagerRef(arena)));
}
result.value = *qualify_state.result();
return result;
}
std::vector<absl::string_view> ListFieldsImpl(
const CelValue::MessageWrapper& instance) {
if (instance.message_ptr() == nullptr) {
return std::vector<absl::string_view>();
}
ABSL_ASSERT(instance.HasFullProto());
const auto* message =
static_cast<const google::protobuf::Message*>(instance.message_ptr());
const auto* reflect = message->GetReflection();
std::vector<const google::protobuf::FieldDescriptor*> fields;
reflect->ListFields(*message, &fields);
std::vector<absl::string_view> field_names;
field_names.reserve(fields.size());
for (const auto* field : fields) {
field_names.emplace_back(field->name());
}
return field_names;
}
class DucktypedMessageAdapter : public LegacyTypeAccessApis,
public LegacyTypeMutationApis,
public LegacyTypeInfoApis {
public:
absl::StatusOr<bool> HasField(
absl::string_view field_name,
const CelValue::MessageWrapper& value) const override {
CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message,
UnwrapMessage(value, "HasField"));
return HasFieldImpl(message, message->GetDescriptor(), field_name);
}
absl::StatusOr<CelValue> GetField(
absl::string_view field_name, const CelValue::MessageWrapper& instance,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager) const override {
CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message,
UnwrapMessage(instance, "GetField"));
return GetFieldImpl(message, message->GetDescriptor(), field_name,
unboxing_option, memory_manager);
}
absl::StatusOr<LegacyTypeAccessApis::LegacyQualifyResult> Qualify(
absl::Span<const cel::SelectQualifier> qualifiers,
const CelValue::MessageWrapper& instance, bool presence_test,
cel::MemoryManagerRef memory_manager) const override {
CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message,
UnwrapMessage(instance, "Qualify"));
return QualifyImpl(message, message->GetDescriptor(), qualifiers,
presence_test, memory_manager);
}
bool IsEqualTo(
const CelValue::MessageWrapper& instance,
const CelValue::MessageWrapper& other_instance) const override {
absl::StatusOr<const google::protobuf::Message*> lhs =
UnwrapMessage(instance, "IsEqualTo");
absl::StatusOr<const google::protobuf::Message*> rhs =
UnwrapMessage(other_instance, "IsEqualTo");
if (!lhs.ok() || !rhs.ok()) {
return false;
}
return ProtoEquals(**lhs, **rhs);
}
absl::string_view GetTypename(
const MessageWrapper& wrapped_message) const override {
if (!wrapped_message.HasFullProto() ||
wrapped_message.message_ptr() == nullptr) {
return UnsupportedTypeName();
}
auto* message =
static_cast<const google::protobuf::Message*>(wrapped_message.message_ptr());
return message->GetDescriptor()->full_name();
}
std::string DebugString(
const MessageWrapper& wrapped_message) const override {
if (!wrapped_message.HasFullProto() ||
wrapped_message.message_ptr() == nullptr) {
return UnsupportedTypeName();
}
auto* message =
static_cast<const google::protobuf::Message*>(wrapped_message.message_ptr());
return message->ShortDebugString();
}
bool DefinesField(absl::string_view field_name) const override {
return true;
}
absl::StatusOr<CelValue::MessageWrapper::Builder> NewInstance(
cel::MemoryManagerRef memory_manager) const override {
return absl::UnimplementedError("NewInstance is not implemented");
}
absl::StatusOr<CelValue> AdaptFromWellKnownType(
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder instance) const override {
if (!instance.HasFullProto() || instance.message_ptr() == nullptr) {
return absl::UnimplementedError(
"MessageLite is not supported, descriptor is required");
}
return ProtoMessageTypeAdapter(
static_cast<const google::protobuf::Message*>(instance.message_ptr())
->GetDescriptor(),
nullptr)
.AdaptFromWellKnownType(memory_manager, instance);
}
absl::Status SetField(
absl::string_view field_name, const CelValue& value,
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder& instance) const override {
if (!instance.HasFullProto() || instance.message_ptr() == nullptr) {
return absl::UnimplementedError(
"MessageLite is not supported, descriptor is required");
}
return ProtoMessageTypeAdapter(
static_cast<const google::protobuf::Message*>(instance.message_ptr())
->GetDescriptor(),
nullptr)
.SetField(field_name, value, memory_manager, instance);
}
std::vector<absl::string_view> ListFields(
const CelValue::MessageWrapper& instance) const override {
return ListFieldsImpl(instance);
}
const LegacyTypeAccessApis* GetAccessApis(
const MessageWrapper& wrapped_message) const override {
return this;
}
const LegacyTypeMutationApis* GetMutationApis(
const MessageWrapper& wrapped_message) const override {
return this;
}
static const DucktypedMessageAdapter& GetSingleton() {
static absl::NoDestructor<DucktypedMessageAdapter> instance;
return *instance;
}
};
CelValue MessageCelValueFactory(const google::protobuf::Message* message) {
return CelValue::CreateMessageWrapper(
MessageWrapper(message, &DucktypedMessageAdapter::GetSingleton()));
}
}
std::string ProtoMessageTypeAdapter::DebugString(
const MessageWrapper& wrapped_message) const {
if (!wrapped_message.HasFullProto() ||
wrapped_message.message_ptr() == nullptr) {
return UnsupportedTypeName();
}
auto* message =
static_cast<const google::protobuf::Message*>(wrapped_message.message_ptr());
return message->ShortDebugString();
}
absl::string_view ProtoMessageTypeAdapter::GetTypename(
const MessageWrapper& wrapped_message) const {
return descriptor_->full_name();
}
const LegacyTypeMutationApis* ProtoMessageTypeAdapter::GetMutationApis(
const MessageWrapper& wrapped_message) const {
return this;
}
const LegacyTypeAccessApis* ProtoMessageTypeAdapter::GetAccessApis(
const MessageWrapper& wrapped_message) const {
return this;
}
absl::optional<LegacyTypeInfoApis::FieldDescription>
ProtoMessageTypeAdapter::FindFieldByName(absl::string_view field_name) const {
if (descriptor_ == nullptr) {
return absl::nullopt;
}
const google::protobuf::FieldDescriptor* field_descriptor =
descriptor_->FindFieldByName(field_name);
if (field_descriptor == nullptr) {
return absl::nullopt;
}
return LegacyTypeInfoApis::FieldDescription{field_descriptor->number(),
field_descriptor->name()};
}
absl::Status ProtoMessageTypeAdapter::ValidateSetFieldOp(
bool assertion, absl::string_view field, absl::string_view detail) const {
if (!assertion) {
return absl::InvalidArgumentError(
absl::Substitute("SetField failed on message $0, field '$1': $2",
descriptor_->full_name(), field, detail));
}
return absl::OkStatus();
}
absl::StatusOr<CelValue::MessageWrapper::Builder>
ProtoMessageTypeAdapter::NewInstance(
cel::MemoryManagerRef memory_manager) const {
if (message_factory_ == nullptr) {
return absl::UnimplementedError(
absl::StrCat("Cannot create message ", descriptor_->name()));
}
google::protobuf::Arena* arena = ProtoMemoryManagerArena(memory_manager);
const Message* prototype = message_factory_->GetPrototype(descriptor_);
Message* msg = (prototype != nullptr) ? prototype->New(arena) : nullptr;
if (msg == nullptr) {
return absl::InvalidArgumentError(
absl::StrCat("Failed to create message ", descriptor_->name()));
}
return MessageWrapper::Builder(msg);
}
bool ProtoMessageTypeAdapter::DefinesField(absl::string_view field_name) const {
return descriptor_->FindFieldByName(field_name) != nullptr;
}
absl::StatusOr<bool> ProtoMessageTypeAdapter::HasField(
absl::string_view field_name, const CelValue::MessageWrapper& value) const {
CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message,
UnwrapMessage(value, "HasField"));
return HasFieldImpl(message, descriptor_, field_name);
}
absl::StatusOr<CelValue> ProtoMessageTypeAdapter::GetField(
absl::string_view field_name, const CelValue::MessageWrapper& instance,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager) const {
CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message,
UnwrapMessage(instance, "GetField"));
return GetFieldImpl(message, descriptor_, field_name, unboxing_option,
memory_manager);
}
absl::StatusOr<LegacyTypeAccessApis::LegacyQualifyResult>
ProtoMessageTypeAdapter::Qualify(
absl::Span<const cel::SelectQualifier> qualifiers,
const CelValue::MessageWrapper& instance, bool presence_test,
cel::MemoryManagerRef memory_manager) const {
CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message,
UnwrapMessage(instance, "Qualify"));
return QualifyImpl(message, descriptor_, qualifiers, presence_test,
memory_manager);
}
absl::Status ProtoMessageTypeAdapter::SetField(
const google::protobuf::FieldDescriptor* field, const CelValue& value,
google::protobuf::Arena* arena, google::protobuf::Message* message) const {
if (field->is_map()) {
constexpr int kKeyField = 1;
constexpr int kValueField = 2;
const CelMap* cel_map;
CEL_RETURN_IF_ERROR(ValidateSetFieldOp(
value.GetValue<const CelMap*>(&cel_map) && cel_map != nullptr,
field->name(), "value is not CelMap"));
auto entry_descriptor = field->message_type();
CEL_RETURN_IF_ERROR(
ValidateSetFieldOp(entry_descriptor != nullptr, field->name(),
"failed to find map entry descriptor"));
auto key_field_descriptor = entry_descriptor->FindFieldByNumber(kKeyField);
auto value_field_descriptor =
entry_descriptor->FindFieldByNumber(kValueField);
CEL_RETURN_IF_ERROR(
ValidateSetFieldOp(key_field_descriptor != nullptr, field->name(),
"failed to find key field descriptor"));
CEL_RETURN_IF_ERROR(
ValidateSetFieldOp(value_field_descriptor != nullptr, field->name(),
"failed to find value field descriptor"));
CEL_ASSIGN_OR_RETURN(const CelList* key_list, cel_map->ListKeys(arena));
for (int i = 0; i < key_list->size(); i++) {
CelValue key = (*key_list).Get(arena, i);
auto value = (*cel_map).Get(arena, key);
CEL_RETURN_IF_ERROR(ValidateSetFieldOp(value.has_value(), field->name(),
"error serializing CelMap"));
Message* entry_msg = message->GetReflection()->AddMessage(message, field);
CEL_RETURN_IF_ERROR(internal::SetValueToSingleField(
key, key_field_descriptor, entry_msg, arena));
CEL_RETURN_IF_ERROR(internal::SetValueToSingleField(
value.value(), value_field_descriptor, entry_msg, arena));
}
} else if (field->is_repeated()) {
const CelList* cel_list;
CEL_RETURN_IF_ERROR(ValidateSetFieldOp(
value.GetValue<const CelList*>(&cel_list) && cel_list != nullptr,
field->name(), "expected CelList value"));
for (int i = 0; i < cel_list->size(); i++) {
CEL_RETURN_IF_ERROR(internal::AddValueToRepeatedField(
(*cel_list).Get(arena, i), field, message, arena));
}
} else {
CEL_RETURN_IF_ERROR(
internal::SetValueToSingleField(value, field, message, arena));
}
return absl::OkStatus();
}
absl::Status ProtoMessageTypeAdapter::SetField(
absl::string_view field_name, const CelValue& value,
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder& instance) const {
google::protobuf::Arena* arena =
cel::extensions::ProtoMemoryManagerArena(memory_manager);
CEL_ASSIGN_OR_RETURN(google::protobuf::Message * mutable_message,
UnwrapMessage(instance, "SetField"));
const google::protobuf::FieldDescriptor* field_descriptor =
descriptor_->FindFieldByName(field_name);
CEL_RETURN_IF_ERROR(
ValidateSetFieldOp(field_descriptor != nullptr, field_name, "not found"));
return SetField(field_descriptor, value, arena, mutable_message);
}
absl::Status ProtoMessageTypeAdapter::SetFieldByNumber(
int64_t field_number, const CelValue& value,
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder& instance) const {
google::protobuf::Arena* arena =
cel::extensions::ProtoMemoryManagerArena(memory_manager);
CEL_ASSIGN_OR_RETURN(google::protobuf::Message * mutable_message,
UnwrapMessage(instance, "SetField"));
const google::protobuf::FieldDescriptor* field_descriptor =
descriptor_->FindFieldByNumber(field_number);
CEL_RETURN_IF_ERROR(ValidateSetFieldOp(
field_descriptor != nullptr, absl::StrCat(field_number), "not found"));
return SetField(field_descriptor, value, arena, mutable_message);
}
absl::StatusOr<CelValue> ProtoMessageTypeAdapter::AdaptFromWellKnownType(
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder instance) const {
google::protobuf::Arena* arena =
cel::extensions::ProtoMemoryManagerArena(memory_manager);
CEL_ASSIGN_OR_RETURN(google::protobuf::Message * message,
UnwrapMessage(instance, "AdaptFromWellKnownType"));
return internal::UnwrapMessageToValue(message, &MessageCelValueFactory,
arena);
}
bool ProtoMessageTypeAdapter::IsEqualTo(
const CelValue::MessageWrapper& instance,
const CelValue::MessageWrapper& other_instance) const {
absl::StatusOr<const google::protobuf::Message*> lhs =
UnwrapMessage(instance, "IsEqualTo");
absl::StatusOr<const google::protobuf::Message*> rhs =
UnwrapMessage(other_instance, "IsEqualTo");
if (!lhs.ok() || !rhs.ok()) {
return false;
}
return ProtoEquals(**lhs, **rhs);
}
std::vector<absl::string_view> ProtoMessageTypeAdapter::ListFields(
const CelValue::MessageWrapper& instance) const {
return ListFieldsImpl(instance);
}
const LegacyTypeInfoApis& GetGenericProtoTypeInfoInstance() {
return DucktypedMessageAdapter::GetSingleton();
}
} | #include "eval/public/structs/proto_message_type_adapter.h"
#include <vector>
#include "google/protobuf/wrappers.pb.h"
#include "google/protobuf/descriptor.pb.h"
#include "absl/status/status.h"
#include "base/attribute.h"
#include "common/value.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/legacy_type_adapter.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "eval/public/testing/matchers.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/proto_matchers.h"
#include "internal/testing.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::cel::ProtoWrapperTypeOptions;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::internal::test::EqualsProto;
using ::google::protobuf::Int64Value;
using ::testing::_;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Field;
using ::testing::HasSubstr;
using ::testing::Optional;
using ::testing::Truly;
using LegacyQualifyResult = LegacyTypeAccessApis::LegacyQualifyResult;
class ProtoMessageTypeAccessorTest : public testing::TestWithParam<bool> {
public:
ProtoMessageTypeAccessorTest()
: type_specific_instance_(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory()) {}
const LegacyTypeAccessApis& GetAccessApis() {
bool use_generic_instance = GetParam();
if (use_generic_instance) {
return *GetGenericProtoTypeInfoInstance().GetAccessApis(dummy_);
} else {
return type_specific_instance_;
}
}
private:
ProtoMessageTypeAdapter type_specific_instance_;
CelValue::MessageWrapper dummy_;
};
TEST_P(ProtoMessageTypeAccessorTest, HasFieldSingular) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.HasField("int64_value", value), IsOkAndHolds(false));
example.set_int64_value(10);
EXPECT_THAT(accessor.HasField("int64_value", value), IsOkAndHolds(true));
}
TEST_P(ProtoMessageTypeAccessorTest, HasFieldRepeated) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.HasField("int64_list", value), IsOkAndHolds(false));
example.add_int64_list(10);
EXPECT_THAT(accessor.HasField("int64_list", value), IsOkAndHolds(true));
}
TEST_P(ProtoMessageTypeAccessorTest, HasFieldMap) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
example.set_int64_value(10);
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.HasField("int64_int32_map", value), IsOkAndHolds(false));
(*example.mutable_int64_int32_map())[2] = 3;
EXPECT_THAT(accessor.HasField("int64_int32_map", value), IsOkAndHolds(true));
}
TEST_P(ProtoMessageTypeAccessorTest, HasFieldUnknownField) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
example.set_int64_value(10);
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.HasField("unknown_field", value),
StatusIs(absl::StatusCode::kNotFound));
}
TEST_P(ProtoMessageTypeAccessorTest, HasFieldNonMessageType) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
MessageWrapper value(static_cast<const google::protobuf::MessageLite*>(nullptr),
nullptr);
EXPECT_THAT(accessor.HasField("unknown_field", value),
StatusIs(absl::StatusCode::kInternal));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldSingular) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
example.set_int64_value(10);
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.GetField("int64_value", value,
ProtoWrapperTypeOptions::kUnsetNull, manager),
IsOkAndHolds(test::IsCelInt64(10)));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldNoSuchField) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
example.set_int64_value(10);
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.GetField("unknown_field", value,
ProtoWrapperTypeOptions::kUnsetNull, manager),
IsOkAndHolds(test::IsCelError(StatusIs(
absl::StatusCode::kNotFound, HasSubstr("unknown_field")))));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldNotAMessage) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
MessageWrapper value(static_cast<const google::protobuf::MessageLite*>(nullptr),
nullptr);
EXPECT_THAT(accessor.GetField("int64_value", value,
ProtoWrapperTypeOptions::kUnsetNull, manager),
StatusIs(absl::StatusCode::kInternal));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldRepeated) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
example.add_int64_list(10);
example.add_int64_list(20);
MessageWrapper value(&example, nullptr);
ASSERT_OK_AND_ASSIGN(
CelValue result,
accessor.GetField("int64_list", value,
ProtoWrapperTypeOptions::kUnsetNull, manager));
const CelList* held_value;
ASSERT_TRUE(result.GetValue(&held_value)) << result.DebugString();
EXPECT_EQ(held_value->size(), 2);
EXPECT_THAT((*held_value)[0], test::IsCelInt64(10));
EXPECT_THAT((*held_value)[1], test::IsCelInt64(20));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldMap) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
(*example.mutable_int64_int32_map())[10] = 20;
MessageWrapper value(&example, nullptr);
ASSERT_OK_AND_ASSIGN(
CelValue result,
accessor.GetField("int64_int32_map", value,
ProtoWrapperTypeOptions::kUnsetNull, manager));
const CelMap* held_value;
ASSERT_TRUE(result.GetValue(&held_value)) << result.DebugString();
EXPECT_EQ(held_value->size(), 1);
EXPECT_THAT((*held_value)[CelValue::CreateInt64(10)],
Optional(test::IsCelInt64(20)));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldWrapperType) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
example.mutable_int64_wrapper_value()->set_value(10);
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.GetField("int64_wrapper_value", value,
ProtoWrapperTypeOptions::kUnsetNull, manager),
IsOkAndHolds(test::IsCelInt64(10)));
}
TEST_P(ProtoMessageTypeAccessorTest, GetFieldWrapperTypeUnsetNullUnbox) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
MessageWrapper value(&example, nullptr);
EXPECT_THAT(accessor.GetField("int64_wrapper_value", value,
ProtoWrapperTypeOptions::kUnsetNull, manager),
IsOkAndHolds(test::IsCelNull()));
example.mutable_int64_wrapper_value()->clear_value();
EXPECT_THAT(accessor.GetField("int64_wrapper_value", value,
ProtoWrapperTypeOptions::kUnsetNull, manager),
IsOkAndHolds(test::IsCelInt64(_)));
}
TEST_P(ProtoMessageTypeAccessorTest,
GetFieldWrapperTypeUnsetDefaultValueUnbox) {
google::protobuf::Arena arena;
const LegacyTypeAccessApis& accessor = GetAccessApis();
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage example;
MessageWrapper value(&example, nullptr);
EXPECT_THAT(
accessor.GetField("int64_wrapper_value", value,
ProtoWrapperTypeOptions::kUnsetProtoDefault, manager),
IsOkAndHolds(test::IsCelInt64(_)));
example.mutable_int64_wrapper_value()->clear_value();
EXPECT_THAT(
accessor.GetField("int64_wrapper_value", value,
ProtoWrapperTypeOptions::kUnsetProtoDefault, manager),
IsOkAndHolds(test::IsCelInt64(_)));
}
TEST_P(ProtoMessageTypeAccessorTest, IsEqualTo) {
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
example.mutable_int64_wrapper_value()->set_value(10);
TestMessage example2;
example2.mutable_int64_wrapper_value()->set_value(10);
MessageWrapper value(&example, nullptr);
MessageWrapper value2(&example2, nullptr);
EXPECT_TRUE(accessor.IsEqualTo(value, value2));
EXPECT_TRUE(accessor.IsEqualTo(value2, value));
}
TEST_P(ProtoMessageTypeAccessorTest, IsEqualToSameTypeInequal) {
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
example.mutable_int64_wrapper_value()->set_value(10);
TestMessage example2;
example2.mutable_int64_wrapper_value()->set_value(12);
MessageWrapper value(&example, nullptr);
MessageWrapper value2(&example2, nullptr);
EXPECT_FALSE(accessor.IsEqualTo(value, value2));
EXPECT_FALSE(accessor.IsEqualTo(value2, value));
}
TEST_P(ProtoMessageTypeAccessorTest, IsEqualToDifferentTypeInequal) {
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
example.mutable_int64_wrapper_value()->set_value(10);
Int64Value example2;
example2.set_value(10);
MessageWrapper value(&example, nullptr);
MessageWrapper value2(&example2, nullptr);
EXPECT_FALSE(accessor.IsEqualTo(value, value2));
EXPECT_FALSE(accessor.IsEqualTo(value2, value));
}
TEST_P(ProtoMessageTypeAccessorTest, IsEqualToNonMessageInequal) {
const LegacyTypeAccessApis& accessor = GetAccessApis();
TestMessage example;
example.mutable_int64_wrapper_value()->set_value(10);
TestMessage example2;
example2.mutable_int64_wrapper_value()->set_value(10);
MessageWrapper value(&example, nullptr);
MessageWrapper value2(static_cast<const google::protobuf::MessageLite*>(&example2),
nullptr);
EXPECT_FALSE(accessor.IsEqualTo(value, value2));
EXPECT_FALSE(accessor.IsEqualTo(value2, value));
}
INSTANTIATE_TEST_SUITE_P(GenericAndSpecific, ProtoMessageTypeAccessorTest,
testing::Bool());
TEST(GetGenericProtoTypeInfoInstance, GetTypeName) {
const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance();
TestMessage test_message;
CelValue::MessageWrapper wrapped_message(&test_message, nullptr);
EXPECT_EQ(info_api.GetTypename(wrapped_message), test_message.GetTypeName());
}
TEST(GetGenericProtoTypeInfoInstance, DebugString) {
const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance();
TestMessage test_message;
test_message.set_string_value("abcd");
CelValue::MessageWrapper wrapped_message(&test_message, nullptr);
EXPECT_EQ(info_api.DebugString(wrapped_message),
test_message.ShortDebugString());
}
TEST(GetGenericProtoTypeInfoInstance, GetAccessApis) {
const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance();
TestMessage test_message;
test_message.set_string_value("abcd");
CelValue::MessageWrapper wrapped_message(&test_message, nullptr);
auto* accessor = info_api.GetAccessApis(wrapped_message);
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
ASSERT_OK_AND_ASSIGN(
CelValue result,
accessor->GetField("string_value", wrapped_message,
ProtoWrapperTypeOptions::kUnsetNull, manager));
EXPECT_THAT(result, test::IsCelString("abcd"));
}
TEST(GetGenericProtoTypeInfoInstance, FallbackForNonMessage) {
const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance();
TestMessage test_message;
test_message.set_string_value("abcd");
CelValue::MessageWrapper wrapped_message(
static_cast<const google::protobuf::MessageLite*>(&test_message), nullptr);
EXPECT_EQ(info_api.GetTypename(wrapped_message), "<unknown message>");
EXPECT_EQ(info_api.DebugString(wrapped_message), "<unknown message>");
CelValue::MessageWrapper null_message(
static_cast<const google::protobuf::Message*>(nullptr), nullptr);
EXPECT_EQ(info_api.GetTypename(null_message), "<unknown message>");
EXPECT_EQ(info_api.DebugString(null_message), "<unknown message>");
}
TEST(ProtoMessageTypeAdapter, NewInstance) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder result,
adapter.NewInstance(manager));
EXPECT_EQ(result.message_ptr()->SerializeAsString(), "");
}
TEST(ProtoMessageTypeAdapter, NewInstanceUnsupportedDescriptor) {
google::protobuf::Arena arena;
google::protobuf::DescriptorPool pool;
google::protobuf::FileDescriptorProto faked_file;
faked_file.set_name("faked.proto");
faked_file.set_syntax("proto3");
faked_file.set_package("google.api.expr.runtime");
auto msg_descriptor = faked_file.add_message_type();
msg_descriptor->set_name("FakeMessage");
pool.BuildFile(faked_file);
ProtoMessageTypeAdapter adapter(
pool.FindMessageTypeByName("google.api.expr.runtime.FakeMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
EXPECT_THAT(
adapter.NewInstance(manager),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("FakeMessage")));
}
TEST(ProtoMessageTypeAdapter, DefinesField) {
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
EXPECT_TRUE(adapter.DefinesField("int64_value"));
EXPECT_FALSE(adapter.DefinesField("not_a_field"));
}
TEST(ProtoMessageTypeAdapter, SetFieldSingular) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder value,
adapter.NewInstance(manager));
ASSERT_OK(adapter.SetField("int64_value", CelValue::CreateInt64(10), manager,
value));
TestMessage message;
message.set_int64_value(10);
EXPECT_EQ(value.message_ptr()->SerializeAsString(),
message.SerializeAsString());
ASSERT_THAT(adapter.SetField("not_a_field", CelValue::CreateInt64(10),
manager, value),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("field 'not_a_field': not found")));
}
TEST(ProtoMessageTypeAdapter, SetFieldRepeated) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ContainerBackedListImpl list(
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)});
CelValue value_to_set = CelValue::CreateList(&list);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance,
adapter.NewInstance(manager));
ASSERT_OK(adapter.SetField("int64_list", value_to_set, manager, instance));
TestMessage message;
message.add_int64_list(1);
message.add_int64_list(2);
EXPECT_EQ(instance.message_ptr()->SerializeAsString(),
message.SerializeAsString());
}
TEST(ProtoMessageTypeAdapter, SetFieldNotAField) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance,
adapter.NewInstance(manager));
ASSERT_THAT(adapter.SetField("not_a_field", CelValue::CreateInt64(10),
manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("field 'not_a_field': not found")));
}
TEST(ProtoMesssageTypeAdapter, SetFieldWrongType) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ContainerBackedListImpl list(
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)});
CelValue list_value = CelValue::CreateList(&list);
CelMapBuilder builder;
ASSERT_OK(builder.Add(CelValue::CreateInt64(1), CelValue::CreateInt64(2)));
ASSERT_OK(builder.Add(CelValue::CreateInt64(2), CelValue::CreateInt64(4)));
CelValue map_value = CelValue::CreateMap(&builder);
CelValue int_value = CelValue::CreateInt64(42);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance,
adapter.NewInstance(manager));
EXPECT_THAT(adapter.SetField("int64_value", map_value, manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(adapter.SetField("int64_value", list_value, manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
adapter.SetField("int64_int32_map", list_value, manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(adapter.SetField("int64_int32_map", int_value, manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(adapter.SetField("int64_list", int_value, manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(adapter.SetField("int64_list", map_value, manager, instance),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(ProtoMesssageTypeAdapter, SetFieldNotAMessage) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
CelValue int_value = CelValue::CreateInt64(42);
CelValue::MessageWrapper::Builder instance(
static_cast<google::protobuf::MessageLite*>(nullptr));
EXPECT_THAT(adapter.SetField("int64_value", int_value, manager, instance),
StatusIs(absl::StatusCode::kInternal));
}
TEST(ProtoMesssageTypeAdapter, SetFieldNullMessage) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
CelValue int_value = CelValue::CreateInt64(42);
CelValue::MessageWrapper::Builder instance(
static_cast<google::protobuf::Message*>(nullptr));
EXPECT_THAT(adapter.SetField("int64_value", int_value, manager, instance),
StatusIs(absl::StatusCode::kInternal));
}
TEST(ProtoMessageTypeAdapter, AdaptFromWellKnownType) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.protobuf.Int64Value"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance,
adapter.NewInstance(manager));
ASSERT_OK(
adapter.SetField("value", CelValue::CreateInt64(42), manager, instance));
ASSERT_OK_AND_ASSIGN(CelValue value,
adapter.AdaptFromWellKnownType(manager, instance));
EXPECT_THAT(value, test::IsCelInt64(42));
}
TEST(ProtoMessageTypeAdapter, AdaptFromWellKnownTypeUnspecial) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance,
adapter.NewInstance(manager));
ASSERT_OK(adapter.SetField("int64_value", CelValue::CreateInt64(42), manager,
instance));
ASSERT_OK_AND_ASSIGN(CelValue value,
adapter.AdaptFromWellKnownType(manager, instance));
EXPECT_THAT(value, test::IsCelMessage(EqualsProto("int64_value: 42")));
}
TEST(ProtoMessageTypeAdapter, AdaptFromWellKnownTypeNotAMessageError) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
CelValue::MessageWrapper::Builder instance(
static_cast<google::protobuf::MessageLite*>(nullptr));
EXPECT_THAT(adapter.AdaptFromWellKnownType(manager, instance),
StatusIs(absl::StatusCode::kInternal));
}
TEST(ProtoMesssageTypeAdapter, TypeInfoDebug) {
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
TestMessage message;
message.set_int64_value(42);
EXPECT_THAT(adapter.DebugString(MessageWrapper(&message, &adapter)),
HasSubstr(message.ShortDebugString()));
EXPECT_THAT(adapter.DebugString(MessageWrapper()),
HasSubstr("<unknown message>"));
}
TEST(ProtoMesssageTypeAdapter, TypeInfoName) {
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
EXPECT_EQ(adapter.GetTypename(MessageWrapper()),
"google.api.expr.runtime.TestMessage");
}
TEST(ProtoMesssageTypeAdapter, FindFieldFound) {
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
EXPECT_THAT(
adapter.FindFieldByName("int64_value"),
Optional(Truly([](const LegacyTypeInfoApis::FieldDescription& desc) {
return desc.name == "int64_value" && desc.number == 2;
})))
<< "expected field int64_value: 2";
}
TEST(ProtoMesssageTypeAdapter, FindFieldNotFound) {
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
EXPECT_EQ(adapter.FindFieldByName("foo_not_a_field"), absl::nullopt);
}
TEST(ProtoMesssageTypeAdapter, TypeInfoMutator) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
const LegacyTypeMutationApis* api = adapter.GetMutationApis(MessageWrapper());
ASSERT_NE(api, nullptr);
ASSERT_OK_AND_ASSIGN(MessageWrapper::Builder builder,
api->NewInstance(manager));
EXPECT_NE(dynamic_cast<TestMessage*>(builder.message_ptr()), nullptr);
}
TEST(ProtoMesssageTypeAdapter, TypeInfoAccesor) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
EXPECT_THAT(api->GetField("int64_value", wrapped,
ProtoWrapperTypeOptions::kUnsetNull, manager),
IsOkAndHolds(test::IsCelInt64(42)));
}
TEST(ProtoMesssageTypeAdapter, Qualify) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.mutable_message_value()->set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{2, "int64_value"}};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelInt64(42))));
}
TEST(ProtoMesssageTypeAdapter, QualifyDynamicFieldAccessUnsupported) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.mutable_message_value()->set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::AttributeQualifier::OfString("int64_value")};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
StatusIs(absl::StatusCode::kUnimplemented));
}
TEST(ProtoMesssageTypeAdapter, QualifyNoSuchField) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.mutable_message_value()->set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{99, "not_a_field"},
cel::FieldSpecifier{2, "int64_value"}};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value,
test::IsCelError(StatusIs(absl::StatusCode::kNotFound,
HasSubstr("no_such_field"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyHasNoSuchField) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.mutable_message_value()->set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{99, "not_a_field"}};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
true, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value,
test::IsCelError(StatusIs(absl::StatusCode::kNotFound,
HasSubstr("no_such_field"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyNoSuchFieldLeaf) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.mutable_message_value()->set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{99, "not_a_field"}};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value,
test::IsCelError(StatusIs(absl::StatusCode::kNotFound,
HasSubstr("no_such_field"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalSupport) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{210, "string_message_map"},
cel::AttributeQualifier::OfString("@key"),
cel::FieldSpecifier{2, "int64_value"}};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelInt64(42))));
}
TEST(ProtoMesssageTypeAdapter, TypedFieldAccessOnMapUnsupported) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{210, "string_message_map"},
cel::FieldSpecifier{2, "value"}, cel::FieldSpecifier{2, "int64_value"}};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
StatusIs(absl::StatusCode::kUnimplemented));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalWrongKeyType) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{210, "string_message_map"},
cel::AttributeQualifier::OfInt(0), cel::FieldSpecifier{2, "int64_value"}};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value,
test::IsCelError(StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid map key type"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalHasWrongKeyType) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{210, "string_message_map"},
cel::AttributeQualifier::OfInt(0)};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
true, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value,
test::IsCelError(StatusIs(
absl::StatusCode::kUnknown,
HasSubstr("No matching overloads"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalSupportNoSuchKey) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{210, "string_message_map"},
cel::AttributeQualifier::OfString("bad_key"),
cel::FieldSpecifier{2, "int64_value"}};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value,
test::IsCelError(StatusIs(absl::StatusCode::kNotFound,
HasSubstr("Key not found"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalInt32Key) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_int32_int32_map())[0] = 42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{205, "int32_int32_map"},
cel::AttributeQualifier::OfInt(0)};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelInt64(42))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalIntOutOfRange) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_int32_int32_map())[0] = 42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{205, "int32_int32_map"},
cel::AttributeQualifier::OfInt(1LL << 32)};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value,
test::IsCelError(StatusIs(absl::StatusCode::kOutOfRange,
HasSubstr("integer overflow"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalUint32Key) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_uint32_uint32_map())[0] = 42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{206, "uint32_uint32_map"},
cel::AttributeQualifier::OfUint(0)};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelUint64(42))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalUintOutOfRange) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_uint32_uint32_map())[0] = 42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{206, "uint32_uint32_map"},
cel::AttributeQualifier::OfUint(1LL << 32)};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value,
test::IsCelError(StatusIs(absl::StatusCode::kOutOfRange,
HasSubstr("integer overflow"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapTraversalUnexpectedFieldAccess) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{210, "string_message_map"},
cel::FieldSpecifier{0, "field_like_key"}};
auto result = api->Qualify(qualfiers, wrapped,
false, manager);
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
StatusIs(absl::StatusCode::kUnimplemented, _));
}
TEST(ProtoMesssageTypeAdapter, UntypedQualifiersNotYetSupported) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
(*message.mutable_string_message_map())["@key"].set_int64_value(42);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::AttributeQualifier::OfString("string_message_map"),
cel::AttributeQualifier::OfString("@key"),
cel::AttributeQualifier::OfString("int64_value")};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
StatusIs(absl::StatusCode::kUnimplemented, _));
}
TEST(ProtoMesssageTypeAdapter, QualifyRepeatedIndexWrongType) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.add_message_list()->add_int64_list(1);
message.add_message_list()->add_int64_list(2);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{112, "message_list"},
cel::AttributeQualifier::OfBool(false),
cel::FieldSpecifier{102, "int64_list"},
cel::AttributeQualifier::OfInt(0)};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value,
test::IsCelError(StatusIs(
absl::StatusCode::kUnknown,
HasSubstr("No matching overloads found"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyRepeatedTypeCheckError) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
message.add_int64_list(1);
message.add_int64_list(2);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{102, "int64_list"}, cel::AttributeQualifier::OfInt(0),
cel::AttributeQualifier::OfInt(1)};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
StatusIs(absl::StatusCode::kInternal,
HasSubstr("Unexpected qualify intermediate type")));
}
TEST(ProtoMesssageTypeAdapter, QualifyRepeatedLeaf) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
auto* nested = message.mutable_message_value();
nested->add_int64_list(1);
nested->add_int64_list(2);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{102, "int64_list"},
};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value,
test::IsCelList(ElementsAre(test::IsCelInt64(1),
test::IsCelInt64(2))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyRepeatedIndexLeaf) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
auto* nested = message.mutable_message_value();
nested->add_int64_list(1);
nested->add_int64_list(2);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{102, "int64_list"},
cel::AttributeQualifier::OfInt(1)};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelInt64(2))));
}
TEST(ProtoMesssageTypeAdapter, QualifyRepeatedIndexLeafOutOfBounds) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
auto* nested = message.mutable_message_value();
nested->add_int64_list(1);
nested->add_int64_list(2);
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{102, "int64_list"},
cel::AttributeQualifier::OfInt(2)};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value,
test::IsCelError(StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("index out of bounds"))))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapLeaf) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
auto* nested_map =
message.mutable_message_value()->mutable_string_int32_map();
(*nested_map)["@key"] = 42;
(*nested_map)["@key2"] = -42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{203, "string_int32_map"},
};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(
&LegacyQualifyResult::value, Truly([](const CelValue& v) {
return v.IsMap() && v.MapOrDie()->size() == 2;
}))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapIndexLeaf) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
auto* nested_map =
message.mutable_message_value()->mutable_string_int32_map();
(*nested_map)["@key"] = 42;
(*nested_map)["@key2"] = -42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{203, "string_int32_map"},
cel::AttributeQualifier::OfString("@key")};
EXPECT_THAT(
api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelInt64(42))));
}
TEST(ProtoMesssageTypeAdapter, QualifyMapIndexLeafWrongType) {
google::protobuf::Arena arena;
ProtoMessageTypeAdapter adapter(
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.api.expr.runtime.TestMessage"),
google::protobuf::MessageFactory::generated_factory());
auto manager = ProtoMemoryManagerRef(&arena);
TestMessage message;
auto* nested_map =
message.mutable_message_value()->mutable_string_int32_map();
(*nested_map)["@key"] = 42;
(*nested_map)["@key2"] = -42;
CelValue::MessageWrapper wrapped(&message, &adapter);
const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper());
ASSERT_NE(api, nullptr);
std::vector<cel::SelectQualifier> qualfiers{
cel::FieldSpecifier{12, "message_value"},
cel::FieldSpecifier{203, "string_int32_map"},
cel::AttributeQualifier::OfInt(0)};
EXPECT_THAT(api->Qualify(qualfiers, wrapped,
false, manager),
IsOkAndHolds(Field(&LegacyQualifyResult::value,
test::IsCelError(StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid map key type"))))));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/proto_message_type_adapter.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/proto_message_type_adapter_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
2c67b126-fa63-44ac-8f6f-a4423e067344 | cpp | google/cel-cpp | legacy_type_provider | eval/public/structs/legacy_type_provider.cc | eval/public/structs/legacy_type_provider_test.cc | #include "eval/public/structs/legacy_type_provider.h"
#include <cstdint>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "common/any.h"
#include "common/legacy_value.h"
#include "common/memory.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_factory.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/legacy_type_adapter.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using google::api::expr::runtime::LegacyTypeAdapter;
using google::api::expr::runtime::MessageWrapper;
class LegacyStructValueBuilder final : public cel::StructValueBuilder {
public:
LegacyStructValueBuilder(cel::MemoryManagerRef memory_manager,
LegacyTypeAdapter adapter,
MessageWrapper::Builder builder)
: memory_manager_(memory_manager),
adapter_(adapter),
builder_(std::move(builder)) {}
absl::Status SetFieldByName(absl::string_view name,
cel::Value value) override {
CEL_ASSIGN_OR_RETURN(
auto legacy_value,
LegacyValue(cel::extensions::ProtoMemoryManagerArena(memory_manager_),
value));
return adapter_.mutation_apis()->SetField(name, legacy_value,
memory_manager_, builder_);
}
absl::Status SetFieldByNumber(int64_t number, cel::Value value) override {
CEL_ASSIGN_OR_RETURN(
auto legacy_value,
LegacyValue(cel::extensions::ProtoMemoryManagerArena(memory_manager_),
value));
return adapter_.mutation_apis()->SetFieldByNumber(
number, legacy_value, memory_manager_, builder_);
}
absl::StatusOr<cel::StructValue> Build() && override {
CEL_ASSIGN_OR_RETURN(auto message,
adapter_.mutation_apis()->AdaptFromWellKnownType(
memory_manager_, std::move(builder_)));
if (!message.IsMessage()) {
return absl::FailedPreconditionError("expected MessageWrapper");
}
auto message_wrapper = message.MessageWrapperOrDie();
return cel::common_internal::LegacyStructValue{
reinterpret_cast<uintptr_t>(message_wrapper.message_ptr()) |
(message_wrapper.HasFullProto()
? cel::base_internal::kMessageWrapperTagMessageValue
: uintptr_t{0}),
reinterpret_cast<uintptr_t>(message_wrapper.legacy_type_info())};
}
private:
cel::MemoryManagerRef memory_manager_;
LegacyTypeAdapter adapter_;
MessageWrapper::Builder builder_;
};
}
absl::StatusOr<absl::optional<cel::Unique<cel::StructValueBuilder>>>
LegacyTypeProvider::NewStructValueBuilder(cel::ValueFactory& value_factory,
const cel::StructType& type) const {
if (auto type_adapter = ProvideLegacyType(type.name());
type_adapter.has_value()) {
const auto* mutation_apis = type_adapter->mutation_apis();
if (mutation_apis == nullptr) {
return absl::FailedPreconditionError(absl::StrCat(
"LegacyTypeMutationApis missing for type: ", type.name()));
}
CEL_ASSIGN_OR_RETURN(auto builder, mutation_apis->NewInstance(
value_factory.GetMemoryManager()));
return value_factory.GetMemoryManager()
.MakeUnique<LegacyStructValueBuilder>(value_factory.GetMemoryManager(),
*type_adapter,
std::move(builder));
}
return absl::nullopt;
}
absl::StatusOr<absl::optional<cel::Value>>
LegacyTypeProvider::DeserializeValueImpl(cel::ValueFactory& value_factory,
absl::string_view type_url,
const absl::Cord& value) const {
auto type_name = absl::StripPrefix(type_url, cel::kTypeGoogleApisComPrefix);
if (auto type_info = ProvideLegacyTypeInfo(type_name);
type_info.has_value()) {
if (auto type_adapter = ProvideLegacyType(type_name);
type_adapter.has_value()) {
const auto* mutation_apis = type_adapter->mutation_apis();
if (mutation_apis == nullptr) {
return absl::FailedPreconditionError(absl::StrCat(
"LegacyTypeMutationApis missing for type: ", type_name));
}
CEL_ASSIGN_OR_RETURN(auto builder, mutation_apis->NewInstance(
value_factory.GetMemoryManager()));
if (!builder.message_ptr()->ParsePartialFromCord(value)) {
return absl::UnknownError("failed to parse protocol buffer message");
}
CEL_ASSIGN_OR_RETURN(
auto legacy_value,
mutation_apis->AdaptFromWellKnownType(
value_factory.GetMemoryManager(), std::move(builder)));
cel::Value modern_value;
CEL_RETURN_IF_ERROR(ModernValue(cel::extensions::ProtoMemoryManagerArena(
value_factory.GetMemoryManager()),
legacy_value, modern_value));
return modern_value;
}
}
return absl::nullopt;
}
absl::StatusOr<absl::optional<cel::Type>> LegacyTypeProvider::FindTypeImpl(
cel::TypeFactory& type_factory, absl::string_view name) const {
if (auto type_info = ProvideLegacyTypeInfo(name); type_info.has_value()) {
const auto* descriptor = (*type_info)->GetDescriptor(MessageWrapper());
if (descriptor != nullptr) {
return cel::MessageType(descriptor);
}
return cel::common_internal::MakeBasicStructType(
(*type_info)->GetTypename(MessageWrapper()));
}
return absl::nullopt;
}
absl::StatusOr<absl::optional<cel::StructTypeField>>
LegacyTypeProvider::FindStructTypeFieldByNameImpl(
cel::TypeFactory& type_factory, absl::string_view type,
absl::string_view name) const {
if (auto type_info = ProvideLegacyTypeInfo(type); type_info.has_value()) {
if (auto field_desc = (*type_info)->FindFieldByName(name);
field_desc.has_value()) {
return cel::common_internal::BasicStructTypeField(
field_desc->name, field_desc->number, cel::DynType{});
} else {
const auto* mutation_apis =
(*type_info)->GetMutationApis(MessageWrapper());
if (mutation_apis == nullptr || !mutation_apis->DefinesField(name)) {
return absl::nullopt;
}
return cel::common_internal::BasicStructTypeField(name, 0,
cel::DynType{});
}
}
return absl::nullopt;
}
} | #include "eval/public/structs/legacy_type_provider.h"
#include <optional>
#include <string>
#include "absl/strings/string_view.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
class LegacyTypeProviderTestEmpty : public LegacyTypeProvider {
public:
absl::optional<LegacyTypeAdapter> ProvideLegacyType(
absl::string_view name) const override {
return absl::nullopt;
}
};
class LegacyTypeInfoApisEmpty : public LegacyTypeInfoApis {
public:
std::string DebugString(
const MessageWrapper& wrapped_message) const override {
return "";
}
absl::string_view GetTypename(
const MessageWrapper& wrapped_message) const override {
return test_string_;
}
const LegacyTypeAccessApis* GetAccessApis(
const MessageWrapper& wrapped_message) const override {
return nullptr;
}
private:
const std::string test_string_ = "test";
};
class LegacyTypeProviderTestImpl : public LegacyTypeProvider {
public:
explicit LegacyTypeProviderTestImpl(const LegacyTypeInfoApis* test_type_info)
: test_type_info_(test_type_info) {}
absl::optional<LegacyTypeAdapter> ProvideLegacyType(
absl::string_view name) const override {
if (name == "test") {
return LegacyTypeAdapter(nullptr, nullptr);
}
return absl::nullopt;
}
absl::optional<const LegacyTypeInfoApis*> ProvideLegacyTypeInfo(
absl::string_view name) const override {
if (name == "test") {
return test_type_info_;
}
return absl::nullopt;
}
private:
const LegacyTypeInfoApis* test_type_info_ = nullptr;
};
TEST(LegacyTypeProviderTest, EmptyTypeProviderHasProvideTypeInfo) {
LegacyTypeProviderTestEmpty provider;
EXPECT_EQ(provider.ProvideLegacyType("test"), absl::nullopt);
EXPECT_EQ(provider.ProvideLegacyTypeInfo("test"), absl::nullopt);
}
TEST(LegacyTypeProviderTest, NonEmptyTypeProviderProvidesSomeTypes) {
LegacyTypeInfoApisEmpty test_type_info;
LegacyTypeProviderTestImpl provider(&test_type_info);
EXPECT_TRUE(provider.ProvideLegacyType("test").has_value());
EXPECT_TRUE(provider.ProvideLegacyTypeInfo("test").has_value());
EXPECT_EQ(provider.ProvideLegacyType("other"), absl::nullopt);
EXPECT_EQ(provider.ProvideLegacyTypeInfo("other"), absl::nullopt);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/legacy_type_provider.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/legacy_type_provider_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
e7b63123-db7e-4476-8c0c-afa1dc0e5c67 | cpp | google/cel-cpp | cel_proto_descriptor_pool_builder | eval/public/structs/cel_proto_descriptor_pool_builder.cc | eval/public/structs/cel_proto_descriptor_pool_builder_test.cc | #include "eval/public/structs/cel_proto_descriptor_pool_builder.h"
#include <string>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/empty.pb.h"
#include "google/protobuf/field_mask.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/timestamp.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "absl/container/flat_hash_map.h"
#include "internal/proto_util.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
template <class MessageType>
absl::Status AddOrValidateMessageType(google::protobuf::DescriptorPool& descriptor_pool) {
const google::protobuf::Descriptor* descriptor = MessageType::descriptor();
if (descriptor_pool.FindMessageTypeByName(descriptor->full_name()) !=
nullptr) {
return internal::ValidateStandardMessageType<MessageType>(descriptor_pool);
}
google::protobuf::FileDescriptorProto file_descriptor_proto;
descriptor->file()->CopyTo(&file_descriptor_proto);
if (descriptor_pool.BuildFile(file_descriptor_proto) == nullptr) {
return absl::InternalError(
absl::StrFormat("Failed to add descriptor '%s' to descriptor pool",
descriptor->full_name()));
}
return absl::OkStatus();
}
template <class MessageType>
void AddStandardMessageTypeToMap(
absl::flat_hash_map<std::string, google::protobuf::FileDescriptorProto>& fdmap) {
const google::protobuf::Descriptor* descriptor = MessageType::descriptor();
if (fdmap.contains(descriptor->file()->name())) return;
descriptor->file()->CopyTo(&fdmap[descriptor->file()->name()]);
}
}
absl::Status AddStandardMessageTypesToDescriptorPool(
google::protobuf::DescriptorPool& descriptor_pool) {
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Any>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::BoolValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::BytesValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::DoubleValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Duration>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::FloatValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Int32Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Int64Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::ListValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::StringValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Struct>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Timestamp>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::UInt32Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::UInt64Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::FieldMask>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Empty>(descriptor_pool));
return absl::OkStatus();
}
google::protobuf::FileDescriptorSet GetStandardMessageTypesFileDescriptorSet() {
absl::flat_hash_map<std::string, google::protobuf::FileDescriptorProto> files;
AddStandardMessageTypeToMap<google::protobuf::Any>(files);
AddStandardMessageTypeToMap<google::protobuf::BoolValue>(files);
AddStandardMessageTypeToMap<google::protobuf::BytesValue>(files);
AddStandardMessageTypeToMap<google::protobuf::DoubleValue>(files);
AddStandardMessageTypeToMap<google::protobuf::Duration>(files);
AddStandardMessageTypeToMap<google::protobuf::FloatValue>(files);
AddStandardMessageTypeToMap<google::protobuf::Int32Value>(files);
AddStandardMessageTypeToMap<google::protobuf::Int64Value>(files);
AddStandardMessageTypeToMap<google::protobuf::ListValue>(files);
AddStandardMessageTypeToMap<google::protobuf::StringValue>(files);
AddStandardMessageTypeToMap<google::protobuf::Struct>(files);
AddStandardMessageTypeToMap<google::protobuf::Timestamp>(files);
AddStandardMessageTypeToMap<google::protobuf::UInt32Value>(files);
AddStandardMessageTypeToMap<google::protobuf::UInt64Value>(files);
AddStandardMessageTypeToMap<google::protobuf::Value>(files);
AddStandardMessageTypeToMap<google::protobuf::FieldMask>(files);
AddStandardMessageTypeToMap<google::protobuf::Empty>(files);
google::protobuf::FileDescriptorSet fdset;
for (const auto& [name, fdproto] : files) {
*fdset.add_file() = fdproto;
}
return fdset;
}
} | #include "eval/public/structs/cel_proto_descriptor_pool_builder.h"
#include <string>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "absl/container/flat_hash_map.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::testing::HasSubstr;
using ::testing::UnorderedElementsAre;
TEST(DescriptorPoolUtilsTest, PopulatesEmptyDescriptorPool) {
google::protobuf::DescriptorPool descriptor_pool;
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Any"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.BoolValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.BytesValue"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.DoubleValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Duration"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.FloatValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Int32Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Int64Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.ListValue"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.StringValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Struct"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Timestamp"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt32Value"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt64Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.FieldMask"),
nullptr);
ASSERT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool));
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Any"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.BoolValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.BytesValue"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.DoubleValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Duration"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.FloatValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Int32Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Int64Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.ListValue"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.StringValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Struct"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Timestamp"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt32Value"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt64Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.FieldMask"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Empty"),
nullptr);
}
TEST(DescriptorPoolUtilsTest, AcceptsPreAddedStandardTypes) {
google::protobuf::DescriptorPool descriptor_pool;
for (auto proto_name : std::vector<std::string>{
"google.protobuf.Any", "google.protobuf.BoolValue",
"google.protobuf.BytesValue", "google.protobuf.DoubleValue",
"google.protobuf.Duration", "google.protobuf.FloatValue",
"google.protobuf.Int32Value", "google.protobuf.Int64Value",
"google.protobuf.ListValue", "google.protobuf.StringValue",
"google.protobuf.Struct", "google.protobuf.Timestamp",
"google.protobuf.UInt32Value", "google.protobuf.UInt64Value",
"google.protobuf.Value", "google.protobuf.FieldMask",
"google.protobuf.Empty"}) {
const google::protobuf::Descriptor* descriptor =
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
proto_name);
ASSERT_NE(descriptor, nullptr);
google::protobuf::FileDescriptorProto file_descriptor_proto;
descriptor->file()->CopyTo(&file_descriptor_proto);
ASSERT_NE(descriptor_pool.BuildFile(file_descriptor_proto), nullptr);
}
EXPECT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool));
}
TEST(DescriptorPoolUtilsTest, RejectsModifiedStandardType) {
google::protobuf::DescriptorPool descriptor_pool;
const google::protobuf::Descriptor* descriptor =
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.protobuf.Duration");
ASSERT_NE(descriptor, nullptr);
google::protobuf::FileDescriptorProto file_descriptor_proto;
descriptor->file()->CopyTo(&file_descriptor_proto);
google::protobuf::FieldDescriptorProto seconds_desc_proto;
google::protobuf::FieldDescriptorProto nanos_desc_proto;
descriptor->FindFieldByName("seconds")->CopyTo(&seconds_desc_proto);
descriptor->FindFieldByName("nanos")->CopyTo(&nanos_desc_proto);
nanos_desc_proto.set_name("millis");
file_descriptor_proto.mutable_message_type(0)->clear_field();
*file_descriptor_proto.mutable_message_type(0)->add_field() =
seconds_desc_proto;
*file_descriptor_proto.mutable_message_type(0)->add_field() =
nanos_desc_proto;
descriptor_pool.BuildFile(file_descriptor_proto);
EXPECT_THAT(
AddStandardMessageTypesToDescriptorPool(descriptor_pool),
StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("differs")));
}
TEST(DescriptorPoolUtilsTest, GetStandardMessageTypesFileDescriptorSet) {
google::protobuf::FileDescriptorSet fdset = GetStandardMessageTypesFileDescriptorSet();
std::vector<std::string> file_names;
for (int i = 0; i < fdset.file_size(); ++i) {
file_names.push_back(fdset.file(i).name());
}
EXPECT_THAT(
file_names,
UnorderedElementsAre(
"google/protobuf/any.proto", "google/protobuf/struct.proto",
"google/protobuf/wrappers.proto", "google/protobuf/timestamp.proto",
"google/protobuf/duration.proto", "google/protobuf/field_mask.proto",
"google/protobuf/empty.proto"));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/cel_proto_descriptor_pool_builder.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/cel_proto_descriptor_pool_builder_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
1728e1b9-6e09-4311-b043-433a6e8d79b4 | cpp | google/cel-cpp | cel_proto_wrap_util | eval/public/structs/cel_proto_wrap_util.cc | eval/public/structs/cel_proto_wrap_util_test.cc | #include "eval/public/structs/cel_proto_wrap_util.h"
#include <math.h>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/timestamp.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "google/protobuf/message.h"
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "common/any.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/protobuf_value_factory.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/internal/any.h"
#include "extensions/protobuf/internal/duration.h"
#include "extensions/protobuf/internal/struct.h"
#include "extensions/protobuf/internal/timestamp.h"
#include "extensions/protobuf/internal/wrappers.h"
#include "internal/overflow.h"
#include "internal/proto_time_encoding.h"
#include "internal/time.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/message_lite.h"
namespace google::api::expr::runtime::internal {
namespace {
using cel::internal::DecodeDuration;
using cel::internal::DecodeTime;
using cel::internal::EncodeTime;
using google::protobuf::Any;
using google::protobuf::BoolValue;
using google::protobuf::BytesValue;
using google::protobuf::DoubleValue;
using google::protobuf::Duration;
using google::protobuf::FloatValue;
using google::protobuf::Int32Value;
using google::protobuf::Int64Value;
using google::protobuf::ListValue;
using google::protobuf::StringValue;
using google::protobuf::Struct;
using google::protobuf::Timestamp;
using google::protobuf::UInt32Value;
using google::protobuf::UInt64Value;
using google::protobuf::Value;
using google::protobuf::Arena;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::Message;
using google::protobuf::MessageFactory;
constexpr int64_t kMaxIntJSON = (1ll << 53) - 1;
constexpr int64_t kMinIntJSON = -kMaxIntJSON;
static bool IsJSONSafe(int64_t i) {
return i >= kMinIntJSON && i <= kMaxIntJSON;
}
static bool IsJSONSafe(uint64_t i) {
return i <= static_cast<uint64_t>(kMaxIntJSON);
}
class DynamicList : public CelList {
public:
DynamicList(const ListValue* values, ProtobufValueFactory factory,
Arena* arena)
: arena_(arena), factory_(std::move(factory)), values_(values) {}
CelValue operator[](int index) const override;
int size() const override { return values_->values_size(); }
private:
Arena* arena_;
ProtobufValueFactory factory_;
const ListValue* values_;
};
class DynamicMap : public CelMap {
public:
DynamicMap(const Struct* values, ProtobufValueFactory factory, Arena* arena)
: arena_(arena),
factory_(std::move(factory)),
values_(values),
key_list_(values) {}
absl::StatusOr<bool> Has(const CelValue& key) const override {
CelValue::StringHolder str_key;
if (!key.GetValue(&str_key)) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid map key type: '", CelValue::TypeName(key.type()), "'"));
}
return values_->fields().contains(std::string(str_key.value()));
}
absl::optional<CelValue> operator[](CelValue key) const override;
int size() const override { return values_->fields_size(); }
absl::StatusOr<const CelList*> ListKeys() const override {
return &key_list_;
}
private:
class DynamicMapKeyList : public CelList {
public:
explicit DynamicMapKeyList(const Struct* values)
: values_(values), keys_(), initialized_(false) {}
CelValue operator[](int index) const override {
CheckInit();
return keys_[index];
}
int size() const override {
CheckInit();
return values_->fields_size();
}
private:
void CheckInit() const {
absl::MutexLock lock(&mutex_);
if (!initialized_) {
for (const auto& it : values_->fields()) {
keys_.push_back(CelValue::CreateString(&it.first));
}
initialized_ = true;
}
}
const Struct* values_;
mutable absl::Mutex mutex_;
mutable std::vector<CelValue> keys_;
mutable bool initialized_;
};
Arena* arena_;
ProtobufValueFactory factory_;
const Struct* values_;
const DynamicMapKeyList key_list_;
};
class ValueManager {
public:
ValueManager(const ProtobufValueFactory& value_factory,
const google::protobuf::DescriptorPool* descriptor_pool,
google::protobuf::Arena* arena, google::protobuf::MessageFactory* message_factory)
: value_factory_(value_factory),
descriptor_pool_(descriptor_pool),
arena_(arena),
message_factory_(message_factory) {}
ValueManager(const ProtobufValueFactory& value_factory, google::protobuf::Arena* arena)
: value_factory_(value_factory),
descriptor_pool_(DescriptorPool::generated_pool()),
arena_(arena),
message_factory_(MessageFactory::generated_factory()) {}
static CelValue ValueFromDuration(absl::Duration duration) {
return CelValue::CreateDuration(duration);
}
CelValue ValueFromDuration(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicDurationProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromDuration(*status_or_unwrapped);
}
CelValue ValueFromMessage(const Duration* duration) {
return ValueFromDuration(DecodeDuration(*duration));
}
CelValue ValueFromTimestamp(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicTimestampProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromTimestamp(*status_or_unwrapped);
}
static CelValue ValueFromTimestamp(absl::Time timestamp) {
return CelValue::CreateTimestamp(timestamp);
}
CelValue ValueFromMessage(const Timestamp* timestamp) {
return ValueFromTimestamp(DecodeTime(*timestamp));
}
CelValue ValueFromMessage(const ListValue* list_values) {
return CelValue::CreateList(Arena::Create<DynamicList>(
arena_, list_values, value_factory_, arena_));
}
CelValue ValueFromMessage(const Struct* struct_value) {
return CelValue::CreateMap(Arena::Create<DynamicMap>(
arena_, struct_value, value_factory_, arena_));
}
CelValue ValueFromAny(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicAnyProto(*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromAny(status_or_unwrapped->type_url(),
cel::GetAnyValueAsCord(*status_or_unwrapped),
descriptor_pool_, message_factory_);
}
CelValue ValueFromAny(absl::string_view type_url, const absl::Cord& payload,
const DescriptorPool* descriptor_pool,
MessageFactory* message_factory) {
auto pos = type_url.find_last_of('/');
if (pos == absl::string_view::npos) {
return CreateErrorValue(arena_, "Malformed type_url string");
}
std::string full_name = std::string(type_url.substr(pos + 1));
const Descriptor* nested_descriptor =
descriptor_pool->FindMessageTypeByName(full_name);
if (nested_descriptor == nullptr) {
return CreateErrorValue(arena_, "Descriptor not found");
}
const Message* prototype = message_factory->GetPrototype(nested_descriptor);
if (prototype == nullptr) {
return CreateErrorValue(arena_, "Prototype not found");
}
Message* nested_message = prototype->New(arena_);
if (!nested_message->ParseFromCord(payload)) {
return CreateErrorValue(arena_, "Failed to unpack Any into message");
}
return UnwrapMessageToValue(nested_message, value_factory_, arena_);
}
CelValue ValueFromMessage(const Any* any_value,
const DescriptorPool* descriptor_pool,
MessageFactory* message_factory) {
return ValueFromAny(any_value->type_url(), absl::Cord(any_value->value()),
descriptor_pool, message_factory);
}
CelValue ValueFromMessage(const Any* any_value) {
return ValueFromMessage(any_value, descriptor_pool_, message_factory_);
}
CelValue ValueFromBool(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicBoolValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromBool(*status_or_unwrapped);
}
static CelValue ValueFromBool(bool value) {
return CelValue::CreateBool(value);
}
CelValue ValueFromMessage(const BoolValue* wrapper) {
return ValueFromBool(wrapper->value());
}
CelValue ValueFromInt32(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicInt32ValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromInt32(*status_or_unwrapped);
}
static CelValue ValueFromInt32(int32_t value) {
return CelValue::CreateInt64(value);
}
CelValue ValueFromMessage(const Int32Value* wrapper) {
return ValueFromInt32(wrapper->value());
}
CelValue ValueFromUInt32(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicUInt32ValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromUInt32(*status_or_unwrapped);
}
static CelValue ValueFromUInt32(uint32_t value) {
return CelValue::CreateUint64(value);
}
CelValue ValueFromMessage(const UInt32Value* wrapper) {
return ValueFromUInt32(wrapper->value());
}
CelValue ValueFromInt64(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicInt64ValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromInt64(*status_or_unwrapped);
}
static CelValue ValueFromInt64(int64_t value) {
return CelValue::CreateInt64(value);
}
CelValue ValueFromMessage(const Int64Value* wrapper) {
return ValueFromInt64(wrapper->value());
}
CelValue ValueFromUInt64(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicUInt64ValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromUInt64(*status_or_unwrapped);
}
static CelValue ValueFromUInt64(uint64_t value) {
return CelValue::CreateUint64(value);
}
CelValue ValueFromMessage(const UInt64Value* wrapper) {
return ValueFromUInt64(wrapper->value());
}
CelValue ValueFromFloat(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicFloatValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromFloat(*status_or_unwrapped);
}
static CelValue ValueFromFloat(float value) {
return CelValue::CreateDouble(value);
}
CelValue ValueFromMessage(const FloatValue* wrapper) {
return ValueFromFloat(wrapper->value());
}
CelValue ValueFromDouble(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicDoubleValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromDouble(*status_or_unwrapped);
}
static CelValue ValueFromDouble(double value) {
return CelValue::CreateDouble(value);
}
CelValue ValueFromMessage(const DoubleValue* wrapper) {
return ValueFromDouble(wrapper->value());
}
CelValue ValueFromString(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicStringValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromString(*status_or_unwrapped);
}
CelValue ValueFromString(const absl::Cord& value) {
return CelValue::CreateString(
Arena::Create<std::string>(arena_, static_cast<std::string>(value)));
}
static CelValue ValueFromString(const std::string* value) {
return CelValue::CreateString(value);
}
CelValue ValueFromMessage(const StringValue* wrapper) {
return ValueFromString(&wrapper->value());
}
CelValue ValueFromBytes(const google::protobuf::Message* message) {
auto status_or_unwrapped =
cel::extensions::protobuf_internal::UnwrapDynamicBytesValueProto(
*message);
if (!status_or_unwrapped.ok()) {
return CreateErrorValue(arena_, status_or_unwrapped.status());
}
return ValueFromBytes(*status_or_unwrapped);
}
CelValue ValueFromBytes(const absl::Cord& value) {
return CelValue::CreateBytes(
Arena::Create<std::string>(arena_, static_cast<std::string>(value)));
}
static CelValue ValueFromBytes(google::protobuf::Arena* arena, std::string value) {
return CelValue::CreateBytes(
Arena::Create<std::string>(arena, std::move(value)));
}
CelValue ValueFromMessage(const BytesValue* wrapper) {
return CelValue::CreateBytes(
Arena::Create<std::string>(arena_, std::string(wrapper->value())));
}
CelValue ValueFromMessage(const Value* value) {
switch (value->kind_case()) {
case Value::KindCase::kNullValue:
return CelValue::CreateNull();
case Value::KindCase::kNumberValue:
return CelValue::CreateDouble(value->number_value());
case Value::KindCase::kStringValue:
return CelValue::CreateString(&value->string_value());
case Value::KindCase::kBoolValue:
return CelValue::CreateBool(value->bool_value());
case Value::KindCase::kStructValue:
return ValueFromMessage(&value->struct_value());
case Value::KindCase::kListValue:
return ValueFromMessage(&value->list_value());
default:
return CelValue::CreateNull();
}
}
template <typename T>
CelValue ValueFromGeneratedMessageLite(const google::protobuf::Message* message) {
const auto* downcast_message = google::protobuf::DynamicCastToGenerated<T>(message);
if (downcast_message != nullptr) {
return ValueFromMessage(downcast_message);
}
auto* value = google::protobuf::Arena::Create<T>(arena_);
absl::Cord serialized;
if (!message->SerializeToCord(&serialized)) {
return CreateErrorValue(
arena_, absl::UnknownError(
absl::StrCat("failed to serialize dynamic message: ",
message->GetTypeName())));
}
if (!value->ParseFromCord(serialized)) {
return CreateErrorValue(arena_, absl::UnknownError(absl::StrCat(
"failed to parse generated message: ",
value->GetTypeName())));
}
return ValueFromMessage(value);
}
template <typename T>
CelValue ValueFromMessage(const google::protobuf::Message* message) {
if constexpr (std::is_same_v<Any, T>) {
return ValueFromAny(message);
} else if constexpr (std::is_same_v<BoolValue, T>) {
return ValueFromBool(message);
} else if constexpr (std::is_same_v<BytesValue, T>) {
return ValueFromBytes(message);
} else if constexpr (std::is_same_v<DoubleValue, T>) {
return ValueFromDouble(message);
} else if constexpr (std::is_same_v<Duration, T>) {
return ValueFromDuration(message);
} else if constexpr (std::is_same_v<FloatValue, T>) {
return ValueFromFloat(message);
} else if constexpr (std::is_same_v<Int32Value, T>) {
return ValueFromInt32(message);
} else if constexpr (std::is_same_v<Int64Value, T>) {
return ValueFromInt64(message);
} else if constexpr (std::is_same_v<ListValue, T>) {
return ValueFromGeneratedMessageLite<ListValue>(message);
} else if constexpr (std::is_same_v<StringValue, T>) {
return ValueFromString(message);
} else if constexpr (std::is_same_v<Struct, T>) {
return ValueFromGeneratedMessageLite<Struct>(message);
} else if constexpr (std::is_same_v<Timestamp, T>) {
return ValueFromTimestamp(message);
} else if constexpr (std::is_same_v<UInt32Value, T>) {
return ValueFromUInt32(message);
} else if constexpr (std::is_same_v<UInt64Value, T>) {
return ValueFromUInt64(message);
} else if constexpr (std::is_same_v<Value, T>) {
return ValueFromGeneratedMessageLite<Value>(message);
} else {
ABSL_UNREACHABLE();
}
}
private:
const ProtobufValueFactory& value_factory_;
const google::protobuf::DescriptorPool* descriptor_pool_;
google::protobuf::Arena* arena_;
MessageFactory* message_factory_;
};
class ValueFromMessageMaker {
public:
template <class MessageType>
static CelValue CreateWellknownTypeValue(const google::protobuf::Message* msg,
const ProtobufValueFactory& factory,
Arena* arena) {
google::protobuf::MessageFactory* message_factory =
msg->GetReflection()->GetMessageFactory();
const google::protobuf::DescriptorPool* pool = msg->GetDescriptor()->file()->pool();
return ValueManager(factory, pool, arena, message_factory)
.ValueFromMessage<MessageType>(msg);
}
static absl::optional<CelValue> CreateValue(
const google::protobuf::Message* message, const ProtobufValueFactory& factory,
Arena* arena) {
switch (message->GetDescriptor()->well_known_type()) {
case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE:
return CreateWellknownTypeValue<DoubleValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE:
return CreateWellknownTypeValue<FloatValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE:
return CreateWellknownTypeValue<Int64Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE:
return CreateWellknownTypeValue<UInt64Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE:
return CreateWellknownTypeValue<Int32Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE:
return CreateWellknownTypeValue<UInt32Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE:
return CreateWellknownTypeValue<StringValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE:
return CreateWellknownTypeValue<BytesValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE:
return CreateWellknownTypeValue<BoolValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY:
return CreateWellknownTypeValue<Any>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION:
return CreateWellknownTypeValue<Duration>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP:
return CreateWellknownTypeValue<Timestamp>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE:
return CreateWellknownTypeValue<Value>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE:
return CreateWellknownTypeValue<ListValue>(message, factory, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT:
return CreateWellknownTypeValue<Struct>(message, factory, arena);
default:
return absl::nullopt;
}
}
ValueFromMessageMaker(const ValueFromMessageMaker&) = delete;
ValueFromMessageMaker& operator=(const ValueFromMessageMaker&) = delete;
};
CelValue DynamicList::operator[](int index) const {
return ValueManager(factory_, arena_)
.ValueFromMessage(&values_->values(index));
}
absl::optional<CelValue> DynamicMap::operator[](CelValue key) const {
CelValue::StringHolder str_key;
if (!key.GetValue(&str_key)) {
return CreateErrorValue(arena_, absl::InvalidArgumentError(absl::StrCat(
"Invalid map key type: '",
CelValue::TypeName(key.type()), "'")));
}
auto it = values_->fields().find(std::string(str_key.value()));
if (it == values_->fields().end()) {
return absl::nullopt;
}
return ValueManager(factory_, arena_).ValueFromMessage(&it->second);
}
google::protobuf::Message* DurationFromValue(const google::protobuf::Message* prototype,
const CelValue& value,
google::protobuf::Arena* arena) {
absl::Duration val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::ValidateDuration(val).ok()) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicDurationProto(val,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* BoolFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
bool val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicBoolValueProto(val,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* BytesFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
CelValue::BytesHolder view_val;
if (!value.GetValue(&view_val)) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicBytesValueProto(
absl::Cord(view_val.value()), *message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* DoubleFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
double val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicDoubleValueProto(val,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* FloatFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
double val;
if (!value.GetValue(&val)) {
return nullptr;
}
float fval = val;
if (val > std::numeric_limits<float>::max()) {
fval = std::numeric_limits<float>::infinity();
} else if (val < std::numeric_limits<float>::lowest()) {
fval = -std::numeric_limits<float>::infinity();
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicFloatValueProto(fval,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* Int32FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
int64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::CheckedInt64ToInt32(val).ok()) {
return nullptr;
}
int32_t ival = static_cast<int32_t>(val);
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicInt32ValueProto(ival,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* Int64FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
int64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicInt64ValueProto(val,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* StringFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
CelValue::StringHolder view_val;
if (!value.GetValue(&view_val)) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicStringValueProto(
absl::Cord(view_val.value()), *message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* TimestampFromValue(const google::protobuf::Message* prototype,
const CelValue& value,
google::protobuf::Arena* arena) {
absl::Time val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::ValidateTimestamp(val).ok()) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicTimestampProto(val,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* UInt32FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
uint64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
if (!cel::internal::CheckedUint64ToUint32(val).ok()) {
return nullptr;
}
uint32_t ival = static_cast<uint32_t>(val);
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicUInt32ValueProto(ival,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* UInt64FromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
uint64_t val;
if (!value.GetValue(&val)) {
return nullptr;
}
auto* message = prototype->New(arena);
auto status_or_wrapped =
cel::extensions::protobuf_internal::WrapDynamicUInt64ValueProto(val,
*message);
if (!status_or_wrapped.ok()) {
status_or_wrapped.IgnoreError();
return nullptr;
}
return message;
}
google::protobuf::Message* ValueFromValue(google::protobuf::Message* message, const CelValue& value,
google::protobuf::Arena* arena);
google::protobuf::Message* ValueFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
return ValueFromValue(prototype->New(arena), value, arena);
}
google::protobuf::Message* ListFromValue(google::protobuf::Message* message, const CelValue& value,
google::protobuf::Arena* arena) {
if (!value.IsList()) {
return nullptr;
}
const CelList& list = *value.ListOrDie();
for (int i = 0; i < list.size(); i++) {
auto e = list.Get(arena, i);
auto status_or_elem =
cel::extensions::protobuf_internal::DynamicListValueProtoAddElement(
message);
if (!status_or_elem.ok()) {
return nullptr;
}
if (ValueFromValue(*status_or_elem, e, arena) == nullptr) {
return nullptr;
}
}
return message;
}
google::protobuf::Message* ListFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
if (!value.IsList()) {
return nullptr;
}
return ListFromValue(prototype->New(arena), value, arena);
}
google::protobuf::Message* StructFromValue(google::protobuf::Message* message,
const CelValue& value, google::protobuf::Arena* arena) {
if (!value.IsMap()) {
return nullptr;
}
const CelMap& map = *value.MapOrDie();
absl::StatusOr<const CelList*> keys_or = map.ListKeys(arena);
if (!keys_or.ok()) {
return nullptr;
}
const CelList& keys = **keys_or;
for (int i = 0; i < keys.size(); i++) {
auto k = keys.Get(arena, i);
if (!k.IsString()) {
return nullptr;
}
absl::string_view key = k.StringOrDie().value();
auto v = map.Get(arena, k);
if (!v.has_value()) {
return nullptr;
}
auto status_or_value =
cel::extensions::protobuf_internal::DynamicStructValueProtoAddField(
key, message);
if (!status_or_value.ok()) {
return nullptr;
}
if (ValueFromValue(*status_or_value, *v, arena) == nullptr) {
return nullptr;
}
}
return message;
}
google::protobuf::Message* StructFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
if (!value.IsMap()) {
return nullptr;
}
return StructFromValue(prototype->New(arena), value, arena);
}
google::protobuf::Message* ValueFromValue(google::protobuf::Message* message, const CelValue& value,
google::protobuf::Arena* arena) {
switch (value.type()) {
case CelValue::Type::kBool: {
bool val;
if (value.GetValue(&val)) {
if (cel::extensions::protobuf_internal::DynamicValueProtoSetBoolValue(
val, message)
.ok()) {
return message;
}
}
} break;
case CelValue::Type::kBytes: {
CelValue::BytesHolder val;
if (value.GetValue(&val)) {
if (cel::extensions::protobuf_internal::DynamicValueProtoSetStringValue(
absl::Base64Escape(val.value()), message)
.ok()) {
return message;
}
}
} break;
case CelValue::Type::kDouble: {
double val;
if (value.GetValue(&val)) {
if (cel::extensions::protobuf_internal::DynamicValueProtoSetNumberValue(
val, message)
.ok()) {
return message;
}
}
} break;
case CelValue::Type::kDuration: {
absl::Duration val;
if (value.GetValue(&val)) {
auto encode = cel::internal::EncodeDurationToString(val);
if (!encode.ok()) {
return nullptr;
}
if (cel::extensions::protobuf_internal::DynamicValueProtoSetStringValue(
*encode, message)
.ok()) {
return message;
}
}
} break;
case CelValue::Type::kInt64: {
int64_t val;
if (value.GetValue(&val)) {
if (IsJSONSafe(val)) {
if (cel::extensions::protobuf_internal::
DynamicValueProtoSetNumberValue(static_cast<double>(val),
message)
.ok()) {
return message;
}
} else {
if (cel::extensions::protobuf_internal::
DynamicValueProtoSetStringValue(absl::StrCat(val), message)
.ok()) {
return message;
}
}
}
} break;
case CelValue::Type::kString: {
CelValue::StringHolder val;
if (value.GetValue(&val)) {
if (cel::extensions::protobuf_internal::DynamicValueProtoSetStringValue(
val.value(), message)
.ok()) {
return message;
}
}
} break;
case CelValue::Type::kTimestamp: {
absl::Time val;
if (value.GetValue(&val)) {
auto encode = cel::internal::EncodeTimeToString(val);
if (!encode.ok()) {
return nullptr;
}
if (cel::extensions::protobuf_internal::DynamicValueProtoSetStringValue(
*encode, message)
.ok()) {
return message;
}
}
} break;
case CelValue::Type::kUint64: {
uint64_t val;
if (value.GetValue(&val)) {
if (IsJSONSafe(val)) {
if (cel::extensions::protobuf_internal::
DynamicValueProtoSetNumberValue(static_cast<double>(val),
message)
.ok()) {
return message;
}
} else {
if (cel::extensions::protobuf_internal::
DynamicValueProtoSetStringValue(absl::StrCat(val), message)
.ok()) {
return message;
}
}
}
} break;
case CelValue::Type::kList: {
auto status_or_list =
cel::extensions::protobuf_internal::DynamicValueProtoMutableListValue(
message);
if (!status_or_list.ok()) {
return nullptr;
}
if (ListFromValue(*status_or_list, value, arena) != nullptr) {
return message;
}
} break;
case CelValue::Type::kMap: {
auto status_or_struct = cel::extensions::protobuf_internal::
DynamicValueProtoMutableStructValue(message);
if (!status_or_struct.ok()) {
return nullptr;
}
if (StructFromValue(*status_or_struct, value, arena) != nullptr) {
return message;
}
} break;
case CelValue::Type::kNullType:
if (cel::extensions::protobuf_internal::DynamicValueProtoSetNullValue(
message)
.ok()) {
return message;
}
break;
default:
return nullptr;
}
return nullptr;
}
bool ValueFromValue(Value* json, const CelValue& value, google::protobuf::Arena* arena);
bool ListFromValue(ListValue* json_list, const CelValue& value,
google::protobuf::Arena* arena) {
if (!value.IsList()) {
return false;
}
const CelList& list = *value.ListOrDie();
for (int i = 0; i < list.size(); i++) {
auto e = list.Get(arena, i);
Value* elem = json_list->add_values();
if (!ValueFromValue(elem, e, arena)) {
return false;
}
}
return true;
}
bool StructFromValue(Struct* json_struct, const CelValue& value,
google::protobuf::Arena* arena) {
if (!value.IsMap()) {
return false;
}
const CelMap& map = *value.MapOrDie();
absl::StatusOr<const CelList*> keys_or = map.ListKeys(arena);
if (!keys_or.ok()) {
return false;
}
const CelList& keys = **keys_or;
auto fields = json_struct->mutable_fields();
for (int i = 0; i < keys.size(); i++) {
auto k = keys.Get(arena, i);
if (!k.IsString()) {
return false;
}
absl::string_view key = k.StringOrDie().value();
auto v = map.Get(arena, k);
if (!v.has_value()) {
return false;
}
Value field_value;
if (!ValueFromValue(&field_value, *v, arena)) {
return false;
}
(*fields)[std::string(key)] = field_value;
}
return true;
}
bool ValueFromValue(Value* json, const CelValue& value, google::protobuf::Arena* arena) {
switch (value.type()) {
case CelValue::Type::kBool: {
bool val;
if (value.GetValue(&val)) {
json->set_bool_value(val);
return true;
}
} break;
case CelValue::Type::kBytes: {
CelValue::BytesHolder val;
if (value.GetValue(&val)) {
json->set_string_value(absl::Base64Escape(val.value()));
return true;
}
} break;
case CelValue::Type::kDouble: {
double val;
if (value.GetValue(&val)) {
json->set_number_value(val);
return true;
}
} break;
case CelValue::Type::kDuration: {
absl::Duration val;
if (value.GetValue(&val)) {
auto encode = cel::internal::EncodeDurationToString(val);
if (!encode.ok()) {
return false;
}
json->set_string_value(*encode);
return true;
}
} break;
case CelValue::Type::kInt64: {
int64_t val;
if (value.GetValue(&val)) {
if (IsJSONSafe(val)) {
json->set_number_value(val);
} else {
json->set_string_value(absl::StrCat(val));
}
return true;
}
} break;
case CelValue::Type::kString: {
CelValue::StringHolder val;
if (value.GetValue(&val)) {
json->set_string_value(val.value());
return true;
}
} break;
case CelValue::Type::kTimestamp: {
absl::Time val;
if (value.GetValue(&val)) {
auto encode = cel::internal::EncodeTimeToString(val);
if (!encode.ok()) {
return false;
}
json->set_string_value(*encode);
return true;
}
} break;
case CelValue::Type::kUint64: {
uint64_t val;
if (value.GetValue(&val)) {
if (IsJSONSafe(val)) {
json->set_number_value(val);
} else {
json->set_string_value(absl::StrCat(val));
}
return true;
}
} break;
case CelValue::Type::kList:
return ListFromValue(json->mutable_list_value(), value, arena);
case CelValue::Type::kMap:
return StructFromValue(json->mutable_struct_value(), value, arena);
case CelValue::Type::kNullType:
json->set_null_value(protobuf::NULL_VALUE);
return true;
default:
return false;
}
return false;
}
google::protobuf::Message* AnyFromValue(const google::protobuf::Message* prototype,
const CelValue& value, google::protobuf::Arena* arena) {
std::string type_name;
absl::Cord payload;
switch (value.type()) {
case CelValue::Type::kBool: {
BoolValue v;
type_name = v.GetTypeName();
v.set_value(value.BoolOrDie());
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kBytes: {
BytesValue v;
type_name = v.GetTypeName();
v.set_value(std::string(value.BytesOrDie().value()));
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kDouble: {
DoubleValue v;
type_name = v.GetTypeName();
v.set_value(value.DoubleOrDie());
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kDuration: {
Duration v;
if (!cel::internal::EncodeDuration(value.DurationOrDie(), &v).ok()) {
return nullptr;
}
type_name = v.GetTypeName();
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kInt64: {
Int64Value v;
type_name = v.GetTypeName();
v.set_value(value.Int64OrDie());
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kString: {
StringValue v;
type_name = v.GetTypeName();
v.set_value(std::string(value.StringOrDie().value()));
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kTimestamp: {
Timestamp v;
if (!cel::internal::EncodeTime(value.TimestampOrDie(), &v).ok()) {
return nullptr;
}
type_name = v.GetTypeName();
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kUint64: {
UInt64Value v;
type_name = v.GetTypeName();
v.set_value(value.Uint64OrDie());
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kList: {
ListValue v;
if (!ListFromValue(&v, value, arena)) {
return nullptr;
}
type_name = v.GetTypeName();
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kMap: {
Struct v;
if (!StructFromValue(&v, value, arena)) {
return nullptr;
}
type_name = v.GetTypeName();
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kNullType: {
Value v;
type_name = v.GetTypeName();
v.set_null_value(google::protobuf::NULL_VALUE);
payload = v.SerializeAsCord();
} break;
case CelValue::Type::kMessage: {
type_name = value.MessageWrapperOrDie().message_ptr()->GetTypeName();
payload = value.MessageWrapperOrDie().message_ptr()->SerializeAsCord();
} break;
default:
return nullptr;
}
auto* message = prototype->New(arena);
if (cel::extensions::protobuf_internal::WrapDynamicAnyProto(
absl::StrCat("type.googleapis.com/", type_name), payload, *message)
.ok()) {
return message;
}
return nullptr;
}
bool IsAlreadyWrapped(google::protobuf::Descriptor::WellKnownType wkt,
const CelValue& value) {
if (value.IsMessage()) {
const auto* msg = value.MessageOrDie();
if (wkt == msg->GetDescriptor()->well_known_type()) {
return true;
}
}
return false;
}
class MessageFromValueMaker {
public:
MessageFromValueMaker(const MessageFromValueMaker&) = delete;
MessageFromValueMaker& operator=(const MessageFromValueMaker&) = delete;
static google::protobuf::Message* MaybeWrapMessage(const google::protobuf::Descriptor* descriptor,
google::protobuf::MessageFactory* factory,
const CelValue& value,
Arena* arena) {
switch (descriptor->well_known_type()) {
case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return DoubleFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return FloatFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return Int64FromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return UInt64FromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return Int32FromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return UInt32FromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return StringFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return BytesFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return BoolFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return AnyFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return DurationFromValue(factory->GetPrototype(descriptor), value,
arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return TimestampFromValue(factory->GetPrototype(descriptor), value,
arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return ValueFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return ListFromValue(factory->GetPrototype(descriptor), value, arena);
case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT:
if (IsAlreadyWrapped(descriptor->well_known_type(), value)) {
return nullptr;
}
return StructFromValue(factory->GetPrototype(descriptor), value, arena);
default:
return nullptr;
}
}
};
}
CelValue UnwrapMessageToValue(const google::protobuf::Message* value,
const ProtobufValueFactory& factory,
Arena* arena) {
if (value == nullptr) {
return CelValue::CreateNull();
}
absl::optional<CelValue> special_value =
ValueFromMessageMaker::CreateValue(value, factory, arena);
if (special_value.has_value()) {
return *special_value;
}
return factory(value);
}
const google::protobuf::Message* MaybeWrapValueToMessage(
const google::protobuf::Descriptor* descriptor, google::protobuf::MessageFactory* factory,
const CelValue& value, Arena* arena) {
google::protobuf::Message* msg = MessageFromValueMaker::MaybeWrapMessage(
descriptor, factory, value, arena);
return msg;
}
} | #include "eval/public/structs/cel_proto_wrap_util.h"
#include <cassert>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/empty.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/message.h"
#include "absl/base/no_destructor.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/protobuf_value_factory.h"
#include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/proto_time_encoding.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "testutil/util.h"
namespace google::api::expr::runtime::internal {
namespace {
using ::testing::Eq;
using ::testing::UnorderedPointwise;
using google::protobuf::Duration;
using google::protobuf::ListValue;
using google::protobuf::Struct;
using google::protobuf::Timestamp;
using google::protobuf::Value;
using google::protobuf::Any;
using google::protobuf::BoolValue;
using google::protobuf::BytesValue;
using google::protobuf::DoubleValue;
using google::protobuf::FloatValue;
using google::protobuf::Int32Value;
using google::protobuf::Int64Value;
using google::protobuf::StringValue;
using google::protobuf::UInt32Value;
using google::protobuf::UInt64Value;
using google::protobuf::Arena;
CelValue ProtobufValueFactoryImpl(const google::protobuf::Message* m) {
return CelValue::CreateMessageWrapper(
CelValue::MessageWrapper(m, TrivialTypeInfo::GetInstance()));
}
class CelProtoWrapperTest : public ::testing::Test {
protected:
CelProtoWrapperTest() {}
void ExpectWrappedMessage(const CelValue& value,
const google::protobuf::Message& message) {
auto* result = MaybeWrapValueToMessage(
message.GetDescriptor(), message.GetReflection()->GetMessageFactory(),
value, arena());
EXPECT_TRUE(result != nullptr);
EXPECT_THAT(result, testutil::EqualsProto(message));
auto* identity = MaybeWrapValueToMessage(
message.GetDescriptor(), message.GetReflection()->GetMessageFactory(),
ProtobufValueFactoryImpl(result), arena());
EXPECT_TRUE(identity == nullptr);
result = MaybeWrapValueToMessage(
ReflectedCopy(message)->GetDescriptor(),
ReflectedCopy(message)->GetReflection()->GetMessageFactory(), value,
arena());
EXPECT_TRUE(result != nullptr);
EXPECT_THAT(result, testutil::EqualsProto(message));
}
void ExpectNotWrapped(const CelValue& value, const google::protobuf::Message& message) {
auto result = MaybeWrapValueToMessage(
message.GetDescriptor(), message.GetReflection()->GetMessageFactory(),
value, arena());
EXPECT_TRUE(result == nullptr);
}
template <class T>
void ExpectUnwrappedPrimitive(const google::protobuf::Message& message, T result) {
CelValue cel_value =
UnwrapMessageToValue(&message, &ProtobufValueFactoryImpl, arena());
T value;
EXPECT_TRUE(cel_value.GetValue(&value));
EXPECT_THAT(value, Eq(result));
T dyn_value;
CelValue cel_dyn_value = UnwrapMessageToValue(
ReflectedCopy(message).get(), &ProtobufValueFactoryImpl, arena());
EXPECT_THAT(cel_dyn_value.type(), Eq(cel_value.type()));
EXPECT_TRUE(cel_dyn_value.GetValue(&dyn_value));
EXPECT_THAT(value, Eq(dyn_value));
}
void ExpectUnwrappedMessage(const google::protobuf::Message& message,
google::protobuf::Message* result) {
CelValue cel_value =
UnwrapMessageToValue(&message, &ProtobufValueFactoryImpl, arena());
if (result == nullptr) {
EXPECT_TRUE(cel_value.IsNull());
return;
}
EXPECT_TRUE(cel_value.IsMessage());
EXPECT_THAT(cel_value.MessageOrDie(), testutil::EqualsProto(*result));
}
std::unique_ptr<google::protobuf::Message> ReflectedCopy(
const google::protobuf::Message& message) {
std::unique_ptr<google::protobuf::Message> dynamic_value(
factory_.GetPrototype(message.GetDescriptor())->New());
dynamic_value->CopyFrom(message);
return dynamic_value;
}
Arena* arena() { return &arena_; }
private:
Arena arena_;
google::protobuf::DynamicMessageFactory factory_;
};
TEST_F(CelProtoWrapperTest, TestType) {
Duration msg_duration;
msg_duration.set_seconds(2);
msg_duration.set_nanos(3);
CelValue value_duration2 =
UnwrapMessageToValue(&msg_duration, &ProtobufValueFactoryImpl, arena());
EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration));
Timestamp msg_timestamp;
msg_timestamp.set_seconds(2);
msg_timestamp.set_nanos(3);
CelValue value_timestamp2 =
UnwrapMessageToValue(&msg_timestamp, &ProtobufValueFactoryImpl, arena());
EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp));
}
TEST_F(CelProtoWrapperTest, TestDuration) {
Duration msg_duration;
msg_duration.set_seconds(2);
msg_duration.set_nanos(3);
CelValue value =
UnwrapMessageToValue(&msg_duration, &ProtobufValueFactoryImpl, arena());
EXPECT_THAT(value.type(), Eq(CelValue::Type::kDuration));
Duration out;
auto status = cel::internal::EncodeDuration(value.DurationOrDie(), &out);
EXPECT_TRUE(status.ok());
EXPECT_THAT(out, testutil::EqualsProto(msg_duration));
}
TEST_F(CelProtoWrapperTest, TestTimestamp) {
Timestamp msg_timestamp;
msg_timestamp.set_seconds(2);
msg_timestamp.set_nanos(3);
CelValue value =
UnwrapMessageToValue(&msg_timestamp, &ProtobufValueFactoryImpl, arena());
EXPECT_TRUE(value.IsTimestamp());
Timestamp out;
auto status = cel::internal::EncodeTime(value.TimestampOrDie(), &out);
EXPECT_TRUE(status.ok());
EXPECT_THAT(out, testutil::EqualsProto(msg_timestamp));
}
TEST_F(CelProtoWrapperTest, UnwrapMessageToValueNull) {
Value json;
json.set_null_value(google::protobuf::NullValue::NULL_VALUE);
ExpectUnwrappedMessage(json, nullptr);
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicValueNull) {
Value value_msg;
value_msg.set_null_value(protobuf::NULL_VALUE);
CelValue value = UnwrapMessageToValue(ReflectedCopy(value_msg).get(),
&ProtobufValueFactoryImpl, arena());
EXPECT_TRUE(value.IsNull());
}
TEST_F(CelProtoWrapperTest, UnwrapMessageToValueBool) {
bool value = true;
Value json;
json.set_bool_value(true);
ExpectUnwrappedPrimitive(json, value);
}
TEST_F(CelProtoWrapperTest, UnwrapMessageToValueNumber) {
double value = 1.0;
Value json;
json.set_number_value(value);
ExpectUnwrappedPrimitive(json, value);
}
TEST_F(CelProtoWrapperTest, UnwrapMessageToValueString) {
const std::string test = "test";
auto value = CelValue::StringHolder(&test);
Value json;
json.set_string_value(test);
ExpectUnwrappedPrimitive(json, value);
}
TEST_F(CelProtoWrapperTest, UnwrapMessageToValueStruct) {
const std::vector<std::string> kFields = {"field1", "field2", "field3"};
Struct value_struct;
auto& value1 = (*value_struct.mutable_fields())[kFields[0]];
value1.set_bool_value(true);
auto& value2 = (*value_struct.mutable_fields())[kFields[1]];
value2.set_number_value(1.0);
auto& value3 = (*value_struct.mutable_fields())[kFields[2]];
value3.set_string_value("test");
CelValue value =
UnwrapMessageToValue(&value_struct, &ProtobufValueFactoryImpl, arena());
ASSERT_TRUE(value.IsMap());
const CelMap* cel_map = value.MapOrDie();
CelValue field1 = CelValue::CreateString(&kFields[0]);
auto field1_presence = cel_map->Has(field1);
ASSERT_OK(field1_presence);
EXPECT_TRUE(*field1_presence);
auto lookup1 = (*cel_map)[field1];
ASSERT_TRUE(lookup1.has_value());
ASSERT_TRUE(lookup1->IsBool());
EXPECT_EQ(lookup1->BoolOrDie(), true);
CelValue field2 = CelValue::CreateString(&kFields[1]);
auto field2_presence = cel_map->Has(field2);
ASSERT_OK(field2_presence);
EXPECT_TRUE(*field2_presence);
auto lookup2 = (*cel_map)[field2];
ASSERT_TRUE(lookup2.has_value());
ASSERT_TRUE(lookup2->IsDouble());
EXPECT_DOUBLE_EQ(lookup2->DoubleOrDie(), 1.0);
CelValue field3 = CelValue::CreateString(&kFields[2]);
auto field3_presence = cel_map->Has(field3);
ASSERT_OK(field3_presence);
EXPECT_TRUE(*field3_presence);
auto lookup3 = (*cel_map)[field3];
ASSERT_TRUE(lookup3.has_value());
ASSERT_TRUE(lookup3->IsString());
EXPECT_EQ(lookup3->StringOrDie().value(), "test");
std::string missing = "missing_field";
CelValue missing_field = CelValue::CreateString(&missing);
auto missing_field_presence = cel_map->Has(missing_field);
ASSERT_OK(missing_field_presence);
EXPECT_FALSE(*missing_field_presence);
const CelList* key_list = cel_map->ListKeys().value();
ASSERT_EQ(key_list->size(), kFields.size());
std::vector<std::string> result_keys;
for (int i = 0; i < key_list->size(); i++) {
CelValue key = (*key_list)[i];
ASSERT_TRUE(key.IsString());
result_keys.push_back(std::string(key.StringOrDie().value()));
}
EXPECT_THAT(result_keys, UnorderedPointwise(Eq(), kFields));
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicStruct) {
Struct struct_msg;
const std::string kFieldInt = "field_int";
const std::string kFieldBool = "field_bool";
(*struct_msg.mutable_fields())[kFieldInt].set_number_value(1.);
(*struct_msg.mutable_fields())[kFieldBool].set_bool_value(true);
CelValue value = UnwrapMessageToValue(ReflectedCopy(struct_msg).get(),
&ProtobufValueFactoryImpl, arena());
EXPECT_TRUE(value.IsMap());
const CelMap* cel_map = value.MapOrDie();
ASSERT_TRUE(cel_map != nullptr);
{
auto lookup = (*cel_map)[CelValue::CreateString(&kFieldInt)];
ASSERT_TRUE(lookup.has_value());
auto v = lookup.value();
ASSERT_TRUE(v.IsDouble());
EXPECT_THAT(v.DoubleOrDie(), testing::DoubleEq(1.));
}
{
auto lookup = (*cel_map)[CelValue::CreateString(&kFieldBool)];
ASSERT_TRUE(lookup.has_value());
auto v = lookup.value();
ASSERT_TRUE(v.IsBool());
EXPECT_EQ(v.BoolOrDie(), true);
}
{
auto presence = cel_map->Has(CelValue::CreateBool(true));
ASSERT_FALSE(presence.ok());
EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument);
auto lookup = (*cel_map)[CelValue::CreateBool(true)];
ASSERT_TRUE(lookup.has_value());
auto v = lookup.value();
ASSERT_TRUE(v.IsError());
}
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicValueStruct) {
const std::string kField1 = "field1";
const std::string kField2 = "field2";
Value value_msg;
(*value_msg.mutable_struct_value()->mutable_fields())[kField1]
.set_number_value(1);
(*value_msg.mutable_struct_value()->mutable_fields())[kField2]
.set_number_value(2);
CelValue value = UnwrapMessageToValue(ReflectedCopy(value_msg).get(),
&ProtobufValueFactoryImpl, arena());
EXPECT_TRUE(value.IsMap());
EXPECT_TRUE(
(*value.MapOrDie())[CelValue::CreateString(&kField1)].has_value());
EXPECT_TRUE(
(*value.MapOrDie())[CelValue::CreateString(&kField2)].has_value());
}
TEST_F(CelProtoWrapperTest, UnwrapMessageToValueList) {
const std::vector<std::string> kFields = {"field1", "field2", "field3"};
ListValue list_value;
list_value.add_values()->set_bool_value(true);
list_value.add_values()->set_number_value(1.0);
list_value.add_values()->set_string_value("test");
CelValue value =
UnwrapMessageToValue(&list_value, &ProtobufValueFactoryImpl, arena());
ASSERT_TRUE(value.IsList());
const CelList* cel_list = value.ListOrDie();
ASSERT_EQ(cel_list->size(), 3);
CelValue value1 = (*cel_list)[0];
ASSERT_TRUE(value1.IsBool());
EXPECT_EQ(value1.BoolOrDie(), true);
auto value2 = (*cel_list)[1];
ASSERT_TRUE(value2.IsDouble());
EXPECT_DOUBLE_EQ(value2.DoubleOrDie(), 1.0);
auto value3 = (*cel_list)[2];
ASSERT_TRUE(value3.IsString());
EXPECT_EQ(value3.StringOrDie().value(), "test");
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicValueListValue) {
Value value_msg;
value_msg.mutable_list_value()->add_values()->set_number_value(1.);
value_msg.mutable_list_value()->add_values()->set_number_value(2.);
CelValue value = UnwrapMessageToValue(ReflectedCopy(value_msg).get(),
&ProtobufValueFactoryImpl, arena());
EXPECT_TRUE(value.IsList());
EXPECT_THAT((*value.ListOrDie())[0].DoubleOrDie(), testing::DoubleEq(1));
EXPECT_THAT((*value.ListOrDie())[1].DoubleOrDie(), testing::DoubleEq(2));
}
TEST_F(CelProtoWrapperTest, UnwrapAnyValue) {
TestMessage test_message;
test_message.set_string_value("test");
Any any;
any.PackFrom(test_message);
ExpectUnwrappedMessage(any, &test_message);
}
TEST_F(CelProtoWrapperTest, UnwrapInvalidAny) {
Any any;
CelValue value =
UnwrapMessageToValue(&any, &ProtobufValueFactoryImpl, arena());
ASSERT_TRUE(value.IsError());
any.set_type_url("/");
ASSERT_TRUE(
UnwrapMessageToValue(&any, &ProtobufValueFactoryImpl, arena()).IsError());
any.set_type_url("/invalid.proto.name");
ASSERT_TRUE(
UnwrapMessageToValue(&any, &ProtobufValueFactoryImpl, arena()).IsError());
}
TEST_F(CelProtoWrapperTest, UnwrapBoolWrapper) {
bool value = true;
BoolValue wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapInt32Wrapper) {
int64_t value = 12;
Int32Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapUInt32Wrapper) {
uint64_t value = 12;
UInt32Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapInt64Wrapper) {
int64_t value = 12;
Int64Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapUInt64Wrapper) {
uint64_t value = 12;
UInt64Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapFloatWrapper) {
double value = 42.5;
FloatValue wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapDoubleWrapper) {
double value = 42.5;
DoubleValue wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapStringWrapper) {
std::string text = "42";
auto value = CelValue::StringHolder(&text);
StringValue wrapper;
wrapper.set_value(text);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapBytesWrapper) {
std::string text = "42";
auto value = CelValue::BytesHolder(&text);
BytesValue wrapper;
wrapper.set_value("42");
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, WrapNull) {
auto cel_value = CelValue::CreateNull();
Value json;
json.set_null_value(protobuf::NULL_VALUE);
ExpectWrappedMessage(cel_value, json);
Any any;
any.PackFrom(json);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapBool) {
auto cel_value = CelValue::CreateBool(true);
Value json;
json.set_bool_value(true);
ExpectWrappedMessage(cel_value, json);
BoolValue wrapper;
wrapper.set_value(true);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapBytes) {
std::string str = "hello world";
auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str));
BytesValue wrapper;
wrapper.set_value(str);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapBytesToValue) {
std::string str = "hello world";
auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str));
Value json;
json.set_string_value("aGVsbG8gd29ybGQ=");
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapDuration) {
auto cel_value = CelValue::CreateDuration(absl::Seconds(300));
Duration d;
d.set_seconds(300);
ExpectWrappedMessage(cel_value, d);
Any any;
any.PackFrom(d);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapDurationToValue) {
auto cel_value = CelValue::CreateDuration(absl::Seconds(300));
Value json;
json.set_string_value("300s");
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapDouble) {
double num = 1.5;
auto cel_value = CelValue::CreateDouble(num);
Value json;
json.set_number_value(num);
ExpectWrappedMessage(cel_value, json);
DoubleValue wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapDoubleToFloatValue) {
double num = 1.5;
auto cel_value = CelValue::CreateDouble(num);
FloatValue wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
double small_num = -9.9e-100;
wrapper.set_value(small_num);
cel_value = CelValue::CreateDouble(small_num);
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapDoubleOverflow) {
double lowest_double = std::numeric_limits<double>::lowest();
auto cel_value = CelValue::CreateDouble(lowest_double);
FloatValue wrapper;
wrapper.set_value(-std::numeric_limits<float>::infinity());
ExpectWrappedMessage(cel_value, wrapper);
double max_double = std::numeric_limits<double>::max();
cel_value = CelValue::CreateDouble(max_double);
wrapper.set_value(std::numeric_limits<float>::infinity());
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapInt64) {
int32_t num = std::numeric_limits<int32_t>::lowest();
auto cel_value = CelValue::CreateInt64(num);
Value json;
json.set_number_value(static_cast<double>(num));
ExpectWrappedMessage(cel_value, json);
Int64Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapInt64ToInt32Value) {
int32_t num = std::numeric_limits<int32_t>::lowest();
auto cel_value = CelValue::CreateInt64(num);
Int32Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapFailureInt64ToInt32Value) {
int64_t num = std::numeric_limits<int64_t>::lowest();
auto cel_value = CelValue::CreateInt64(num);
Int32Value wrapper;
ExpectNotWrapped(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapInt64ToValue) {
int64_t max = std::numeric_limits<int64_t>::max();
auto cel_value = CelValue::CreateInt64(max);
Value json;
json.set_string_value(absl::StrCat(max));
ExpectWrappedMessage(cel_value, json);
int64_t min = std::numeric_limits<int64_t>::min();
cel_value = CelValue::CreateInt64(min);
json.set_string_value(absl::StrCat(min));
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapUint64) {
uint32_t num = std::numeric_limits<uint32_t>::max();
auto cel_value = CelValue::CreateUint64(num);
Value json;
json.set_number_value(static_cast<double>(num));
ExpectWrappedMessage(cel_value, json);
UInt64Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapUint64ToUint32Value) {
uint32_t num = std::numeric_limits<uint32_t>::max();
auto cel_value = CelValue::CreateUint64(num);
UInt32Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapUint64ToValue) {
uint64_t num = std::numeric_limits<uint64_t>::max();
auto cel_value = CelValue::CreateUint64(num);
Value json;
json.set_string_value(absl::StrCat(num));
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapFailureUint64ToUint32Value) {
uint64_t num = std::numeric_limits<uint64_t>::max();
auto cel_value = CelValue::CreateUint64(num);
UInt32Value wrapper;
ExpectNotWrapped(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapString) {
std::string str = "test";
auto cel_value = CelValue::CreateString(CelValue::StringHolder(&str));
Value json;
json.set_string_value(str);
ExpectWrappedMessage(cel_value, json);
StringValue wrapper;
wrapper.set_value(str);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapTimestamp) {
absl::Time ts = absl::FromUnixSeconds(1615852799);
auto cel_value = CelValue::CreateTimestamp(ts);
Timestamp t;
t.set_seconds(1615852799);
ExpectWrappedMessage(cel_value, t);
Any any;
any.PackFrom(t);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapTimestampToValue) {
absl::Time ts = absl::FromUnixSeconds(1615852799);
auto cel_value = CelValue::CreateTimestamp(ts);
Value json;
json.set_string_value("2021-03-15T23:59:59Z");
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapList) {
std::vector<CelValue> list_elems = {
CelValue::CreateDouble(1.5),
CelValue::CreateInt64(-2L),
};
ContainerBackedListImpl list(std::move(list_elems));
auto cel_value = CelValue::CreateList(&list);
Value json;
json.mutable_list_value()->add_values()->set_number_value(1.5);
json.mutable_list_value()->add_values()->set_number_value(-2.);
ExpectWrappedMessage(cel_value, json);
ExpectWrappedMessage(cel_value, json.list_value());
Any any;
any.PackFrom(json.list_value());
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapFailureListValueBadJSON) {
TestMessage message;
std::vector<CelValue> list_elems = {
CelValue::CreateDouble(1.5),
UnwrapMessageToValue(&message, &ProtobufValueFactoryImpl, arena()),
};
ContainerBackedListImpl list(std::move(list_elems));
auto cel_value = CelValue::CreateList(&list);
Value json;
ExpectNotWrapped(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapStruct) {
const std::string kField1 = "field1";
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(CelValue::StringHolder(&kField1)),
CelValue::CreateBool(true)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
auto cel_value = CelValue::CreateMap(cel_map.get());
Value json;
(*json.mutable_struct_value()->mutable_fields())[kField1].set_bool_value(
true);
ExpectWrappedMessage(cel_value, json);
ExpectWrappedMessage(cel_value, json.struct_value());
Any any;
any.PackFrom(json.struct_value());
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapFailureStructBadKeyType) {
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateInt64(1L), CelValue::CreateBool(true)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
auto cel_value = CelValue::CreateMap(cel_map.get());
Value json;
ExpectNotWrapped(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapFailureStructBadValueType) {
const std::string kField1 = "field1";
TestMessage bad_value;
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(CelValue::StringHolder(&kField1)),
UnwrapMessageToValue(&bad_value, &ProtobufValueFactoryImpl, arena())}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
auto cel_value = CelValue::CreateMap(cel_map.get());
Value json;
ExpectNotWrapped(cel_value, json);
}
class TestMap : public CelMapBuilder {
public:
absl::StatusOr<const CelList*> ListKeys() const override {
return absl::UnimplementedError("test");
}
};
TEST_F(CelProtoWrapperTest, WrapFailureStructListKeysUnimplemented) {
const std::string kField1 = "field1";
TestMap map;
ASSERT_OK(map.Add(CelValue::CreateString(CelValue::StringHolder(&kField1)),
CelValue::CreateString(CelValue::StringHolder(&kField1))));
auto cel_value = CelValue::CreateMap(&map);
Value json;
ExpectNotWrapped(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapFailureWrongType) {
auto cel_value = CelValue::CreateNull();
std::vector<const google::protobuf::Message*> wrong_types = {
&BoolValue::default_instance(), &BytesValue::default_instance(),
&DoubleValue::default_instance(), &Duration::default_instance(),
&FloatValue::default_instance(), &Int32Value::default_instance(),
&Int64Value::default_instance(), &ListValue::default_instance(),
&StringValue::default_instance(), &Struct::default_instance(),
&Timestamp::default_instance(), &UInt32Value::default_instance(),
&UInt64Value::default_instance(),
};
for (const auto* wrong_type : wrong_types) {
ExpectNotWrapped(cel_value, *wrong_type);
}
}
TEST_F(CelProtoWrapperTest, WrapFailureErrorToAny) {
auto cel_value = CreateNoSuchFieldError(arena(), "error_field");
ExpectNotWrapped(cel_value, Any::default_instance());
}
TEST_F(CelProtoWrapperTest, DebugString) {
google::protobuf::Empty e;
EXPECT_EQ(UnwrapMessageToValue(&e, &ProtobufValueFactoryImpl, arena())
.DebugString(),
"Message: opaque");
ListValue list_value;
list_value.add_values()->set_bool_value(true);
list_value.add_values()->set_number_value(1.0);
list_value.add_values()->set_string_value("test");
CelValue value =
UnwrapMessageToValue(&list_value, &ProtobufValueFactoryImpl, arena());
EXPECT_EQ(value.DebugString(),
"CelList: [bool: 1, double: 1.000000, string: test]");
Struct value_struct;
auto& value1 = (*value_struct.mutable_fields())["a"];
value1.set_bool_value(true);
auto& value2 = (*value_struct.mutable_fields())["b"];
value2.set_number_value(1.0);
auto& value3 = (*value_struct.mutable_fields())["c"];
value3.set_string_value("test");
value =
UnwrapMessageToValue(&value_struct, &ProtobufValueFactoryImpl, arena());
EXPECT_THAT(
value.DebugString(),
testing::AllOf(testing::StartsWith("CelMap: {"),
testing::HasSubstr("<string: a>: <bool: 1>"),
testing::HasSubstr("<string: b>: <double: 1.0"),
testing::HasSubstr("<string: c>: <string: test>")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/cel_proto_wrap_util.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/cel_proto_wrap_util_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
3f3c60b9-ff73-42be-a9ee-70a0a1e549dc | cpp | google/cel-cpp | cel_proto_wrapper | eval/public/structs/cel_proto_wrapper.cc | eval/public/structs/cel_proto_wrapper_test.cc | #include "eval/public/structs/cel_proto_wrapper.h"
#include "absl/types/optional.h"
#include "eval/public/cel_value.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/cel_proto_wrap_util.h"
#include "eval/public/structs/proto_message_type_adapter.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
namespace google::api::expr::runtime {
namespace {
using ::google::protobuf::Arena;
using ::google::protobuf::Descriptor;
using ::google::protobuf::Message;
}
CelValue CelProtoWrapper::InternalWrapMessage(const Message* message) {
return CelValue::CreateMessageWrapper(
MessageWrapper(message, &GetGenericProtoTypeInfoInstance()));
}
CelValue CelProtoWrapper::CreateMessage(const Message* value, Arena* arena) {
return internal::UnwrapMessageToValue(value, &InternalWrapMessage, arena);
}
absl::optional<CelValue> CelProtoWrapper::MaybeWrapValue(
const Descriptor* descriptor, google::protobuf::MessageFactory* factory,
const CelValue& value, Arena* arena) {
const Message* msg =
internal::MaybeWrapValueToMessage(descriptor, factory, value, arena);
if (msg != nullptr) {
return InternalWrapMessage(msg);
} else {
return absl::nullopt;
}
}
} | #include "eval/public/structs/cel_proto_wrapper.h"
#include <cassert>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/empty.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/message.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/proto_time_encoding.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "testutil/util.h"
namespace google::api::expr::runtime {
namespace {
using ::testing::Eq;
using ::testing::UnorderedPointwise;
using google::protobuf::Duration;
using google::protobuf::ListValue;
using google::protobuf::Struct;
using google::protobuf::Timestamp;
using google::protobuf::Value;
using google::protobuf::Any;
using google::protobuf::BoolValue;
using google::protobuf::BytesValue;
using google::protobuf::DoubleValue;
using google::protobuf::FloatValue;
using google::protobuf::Int32Value;
using google::protobuf::Int64Value;
using google::protobuf::StringValue;
using google::protobuf::UInt32Value;
using google::protobuf::UInt64Value;
using google::protobuf::Arena;
class CelProtoWrapperTest : public ::testing::Test {
protected:
CelProtoWrapperTest() {}
void ExpectWrappedMessage(const CelValue& value,
const google::protobuf::Message& message) {
auto result = CelProtoWrapper::MaybeWrapValue(
message.GetDescriptor(), message.GetReflection()->GetMessageFactory(),
value, arena());
EXPECT_TRUE(result.has_value());
EXPECT_TRUE((*result).IsMessage());
EXPECT_THAT((*result).MessageOrDie(), testutil::EqualsProto(message));
auto identity = CelProtoWrapper::MaybeWrapValue(
message.GetDescriptor(), message.GetReflection()->GetMessageFactory(),
*result, arena());
EXPECT_FALSE(identity.has_value());
result = CelProtoWrapper::MaybeWrapValue(
ReflectedCopy(message)->GetDescriptor(),
ReflectedCopy(message)->GetReflection()->GetMessageFactory(), value,
arena());
EXPECT_TRUE(result.has_value());
EXPECT_TRUE((*result).IsMessage());
EXPECT_THAT((*result).MessageOrDie(), testutil::EqualsProto(message));
}
void ExpectNotWrapped(const CelValue& value, const google::protobuf::Message& message) {
auto result = CelProtoWrapper::MaybeWrapValue(
message.GetDescriptor(), message.GetReflection()->GetMessageFactory(),
value, arena());
EXPECT_FALSE(result.has_value());
}
template <class T>
void ExpectUnwrappedPrimitive(const google::protobuf::Message& message, T result) {
CelValue cel_value = CelProtoWrapper::CreateMessage(&message, arena());
T value;
EXPECT_TRUE(cel_value.GetValue(&value));
EXPECT_THAT(value, Eq(result));
T dyn_value;
CelValue cel_dyn_value =
CelProtoWrapper::CreateMessage(ReflectedCopy(message).get(), arena());
EXPECT_THAT(cel_dyn_value.type(), Eq(cel_value.type()));
EXPECT_TRUE(cel_dyn_value.GetValue(&dyn_value));
EXPECT_THAT(value, Eq(dyn_value));
}
void ExpectUnwrappedMessage(const google::protobuf::Message& message,
google::protobuf::Message* result) {
CelValue cel_value = CelProtoWrapper::CreateMessage(&message, arena());
if (result == nullptr) {
EXPECT_TRUE(cel_value.IsNull());
return;
}
EXPECT_TRUE(cel_value.IsMessage());
EXPECT_THAT(cel_value.MessageOrDie(), testutil::EqualsProto(*result));
}
std::unique_ptr<google::protobuf::Message> ReflectedCopy(
const google::protobuf::Message& message) {
std::unique_ptr<google::protobuf::Message> dynamic_value(
factory_.GetPrototype(message.GetDescriptor())->New());
dynamic_value->CopyFrom(message);
return dynamic_value;
}
Arena* arena() { return &arena_; }
private:
Arena arena_;
google::protobuf::DynamicMessageFactory factory_;
};
TEST_F(CelProtoWrapperTest, TestType) {
Duration msg_duration;
msg_duration.set_seconds(2);
msg_duration.set_nanos(3);
CelValue value_duration1 = CelProtoWrapper::CreateDuration(&msg_duration);
EXPECT_THAT(value_duration1.type(), Eq(CelValue::Type::kDuration));
CelValue value_duration2 =
CelProtoWrapper::CreateMessage(&msg_duration, arena());
EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration));
Timestamp msg_timestamp;
msg_timestamp.set_seconds(2);
msg_timestamp.set_nanos(3);
CelValue value_timestamp1 = CelProtoWrapper::CreateTimestamp(&msg_timestamp);
EXPECT_THAT(value_timestamp1.type(), Eq(CelValue::Type::kTimestamp));
CelValue value_timestamp2 =
CelProtoWrapper::CreateMessage(&msg_timestamp, arena());
EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp));
}
TEST_F(CelProtoWrapperTest, TestDuration) {
Duration msg_duration;
msg_duration.set_seconds(2);
msg_duration.set_nanos(3);
CelValue value_duration1 = CelProtoWrapper::CreateDuration(&msg_duration);
EXPECT_THAT(value_duration1.type(), Eq(CelValue::Type::kDuration));
CelValue value_duration2 =
CelProtoWrapper::CreateMessage(&msg_duration, arena());
EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration));
CelValue value = CelProtoWrapper::CreateDuration(&msg_duration);
EXPECT_TRUE(value.IsDuration());
Duration out;
auto status = cel::internal::EncodeDuration(value.DurationOrDie(), &out);
EXPECT_TRUE(status.ok());
EXPECT_THAT(out, testutil::EqualsProto(msg_duration));
}
TEST_F(CelProtoWrapperTest, TestTimestamp) {
Timestamp msg_timestamp;
msg_timestamp.set_seconds(2);
msg_timestamp.set_nanos(3);
CelValue value_timestamp1 = CelProtoWrapper::CreateTimestamp(&msg_timestamp);
EXPECT_THAT(value_timestamp1.type(), Eq(CelValue::Type::kTimestamp));
CelValue value_timestamp2 =
CelProtoWrapper::CreateMessage(&msg_timestamp, arena());
EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp));
CelValue value = CelProtoWrapper::CreateTimestamp(&msg_timestamp);
EXPECT_TRUE(value.IsTimestamp());
Timestamp out;
auto status = cel::internal::EncodeTime(value.TimestampOrDie(), &out);
EXPECT_TRUE(status.ok());
EXPECT_THAT(out, testutil::EqualsProto(msg_timestamp));
}
TEST_F(CelProtoWrapperTest, UnwrapValueNull) {
Value json;
json.set_null_value(google::protobuf::NullValue::NULL_VALUE);
ExpectUnwrappedMessage(json, nullptr);
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicValueNull) {
Value value_msg;
value_msg.set_null_value(protobuf::NULL_VALUE);
CelValue value =
CelProtoWrapper::CreateMessage(ReflectedCopy(value_msg).get(), arena());
EXPECT_TRUE(value.IsNull());
}
TEST_F(CelProtoWrapperTest, UnwrapValueBool) {
bool value = true;
Value json;
json.set_bool_value(true);
ExpectUnwrappedPrimitive(json, value);
}
TEST_F(CelProtoWrapperTest, UnwrapValueNumber) {
double value = 1.0;
Value json;
json.set_number_value(value);
ExpectUnwrappedPrimitive(json, value);
}
TEST_F(CelProtoWrapperTest, UnwrapValueString) {
const std::string test = "test";
auto value = CelValue::StringHolder(&test);
Value json;
json.set_string_value(test);
ExpectUnwrappedPrimitive(json, value);
}
TEST_F(CelProtoWrapperTest, UnwrapValueStruct) {
const std::vector<std::string> kFields = {"field1", "field2", "field3"};
Struct value_struct;
auto& value1 = (*value_struct.mutable_fields())[kFields[0]];
value1.set_bool_value(true);
auto& value2 = (*value_struct.mutable_fields())[kFields[1]];
value2.set_number_value(1.0);
auto& value3 = (*value_struct.mutable_fields())[kFields[2]];
value3.set_string_value("test");
CelValue value = CelProtoWrapper::CreateMessage(&value_struct, arena());
ASSERT_TRUE(value.IsMap());
const CelMap* cel_map = value.MapOrDie();
CelValue field1 = CelValue::CreateString(&kFields[0]);
auto field1_presence = cel_map->Has(field1);
ASSERT_OK(field1_presence);
EXPECT_TRUE(*field1_presence);
auto lookup1 = (*cel_map)[field1];
ASSERT_TRUE(lookup1.has_value());
ASSERT_TRUE(lookup1->IsBool());
EXPECT_EQ(lookup1->BoolOrDie(), true);
CelValue field2 = CelValue::CreateString(&kFields[1]);
auto field2_presence = cel_map->Has(field2);
ASSERT_OK(field2_presence);
EXPECT_TRUE(*field2_presence);
auto lookup2 = (*cel_map)[field2];
ASSERT_TRUE(lookup2.has_value());
ASSERT_TRUE(lookup2->IsDouble());
EXPECT_DOUBLE_EQ(lookup2->DoubleOrDie(), 1.0);
CelValue field3 = CelValue::CreateString(&kFields[2]);
auto field3_presence = cel_map->Has(field3);
ASSERT_OK(field3_presence);
EXPECT_TRUE(*field3_presence);
auto lookup3 = (*cel_map)[field3];
ASSERT_TRUE(lookup3.has_value());
ASSERT_TRUE(lookup3->IsString());
EXPECT_EQ(lookup3->StringOrDie().value(), "test");
std::string missing = "missing_field";
CelValue missing_field = CelValue::CreateString(&missing);
auto missing_field_presence = cel_map->Has(missing_field);
ASSERT_OK(missing_field_presence);
EXPECT_FALSE(*missing_field_presence);
const CelList* key_list = cel_map->ListKeys().value();
ASSERT_EQ(key_list->size(), kFields.size());
std::vector<std::string> result_keys;
for (int i = 0; i < key_list->size(); i++) {
CelValue key = (*key_list)[i];
ASSERT_TRUE(key.IsString());
result_keys.push_back(std::string(key.StringOrDie().value()));
}
EXPECT_THAT(result_keys, UnorderedPointwise(Eq(), kFields));
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicStruct) {
Struct struct_msg;
const std::string kFieldInt = "field_int";
const std::string kFieldBool = "field_bool";
(*struct_msg.mutable_fields())[kFieldInt].set_number_value(1.);
(*struct_msg.mutable_fields())[kFieldBool].set_bool_value(true);
CelValue value =
CelProtoWrapper::CreateMessage(ReflectedCopy(struct_msg).get(), arena());
EXPECT_TRUE(value.IsMap());
const CelMap* cel_map = value.MapOrDie();
ASSERT_TRUE(cel_map != nullptr);
{
auto lookup = (*cel_map)[CelValue::CreateString(&kFieldInt)];
ASSERT_TRUE(lookup.has_value());
auto v = lookup.value();
ASSERT_TRUE(v.IsDouble());
EXPECT_THAT(v.DoubleOrDie(), testing::DoubleEq(1.));
}
{
auto lookup = (*cel_map)[CelValue::CreateString(&kFieldBool)];
ASSERT_TRUE(lookup.has_value());
auto v = lookup.value();
ASSERT_TRUE(v.IsBool());
EXPECT_EQ(v.BoolOrDie(), true);
}
{
auto presence = cel_map->Has(CelValue::CreateBool(true));
ASSERT_FALSE(presence.ok());
EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument);
auto lookup = (*cel_map)[CelValue::CreateBool(true)];
ASSERT_TRUE(lookup.has_value());
auto v = lookup.value();
ASSERT_TRUE(v.IsError());
}
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicValueStruct) {
const std::string kField1 = "field1";
const std::string kField2 = "field2";
Value value_msg;
(*value_msg.mutable_struct_value()->mutable_fields())[kField1]
.set_number_value(1);
(*value_msg.mutable_struct_value()->mutable_fields())[kField2]
.set_number_value(2);
CelValue value =
CelProtoWrapper::CreateMessage(ReflectedCopy(value_msg).get(), arena());
EXPECT_TRUE(value.IsMap());
EXPECT_TRUE(
(*value.MapOrDie())[CelValue::CreateString(&kField1)].has_value());
EXPECT_TRUE(
(*value.MapOrDie())[CelValue::CreateString(&kField2)].has_value());
}
TEST_F(CelProtoWrapperTest, UnwrapValueList) {
const std::vector<std::string> kFields = {"field1", "field2", "field3"};
ListValue list_value;
list_value.add_values()->set_bool_value(true);
list_value.add_values()->set_number_value(1.0);
list_value.add_values()->set_string_value("test");
CelValue value = CelProtoWrapper::CreateMessage(&list_value, arena());
ASSERT_TRUE(value.IsList());
const CelList* cel_list = value.ListOrDie();
ASSERT_EQ(cel_list->size(), 3);
CelValue value1 = (*cel_list)[0];
ASSERT_TRUE(value1.IsBool());
EXPECT_EQ(value1.BoolOrDie(), true);
auto value2 = (*cel_list)[1];
ASSERT_TRUE(value2.IsDouble());
EXPECT_DOUBLE_EQ(value2.DoubleOrDie(), 1.0);
auto value3 = (*cel_list)[2];
ASSERT_TRUE(value3.IsString());
EXPECT_EQ(value3.StringOrDie().value(), "test");
}
TEST_F(CelProtoWrapperTest, UnwrapDynamicValueListValue) {
Value value_msg;
value_msg.mutable_list_value()->add_values()->set_number_value(1.);
value_msg.mutable_list_value()->add_values()->set_number_value(2.);
CelValue value =
CelProtoWrapper::CreateMessage(ReflectedCopy(value_msg).get(), arena());
EXPECT_TRUE(value.IsList());
EXPECT_THAT((*value.ListOrDie())[0].DoubleOrDie(), testing::DoubleEq(1));
EXPECT_THAT((*value.ListOrDie())[1].DoubleOrDie(), testing::DoubleEq(2));
}
TEST_F(CelProtoWrapperTest, UnwrapAnyValue) {
TestMessage test_message;
test_message.set_string_value("test");
Any any;
any.PackFrom(test_message);
ExpectUnwrappedMessage(any, &test_message);
}
TEST_F(CelProtoWrapperTest, UnwrapInvalidAny) {
Any any;
CelValue value = CelProtoWrapper::CreateMessage(&any, arena());
ASSERT_TRUE(value.IsError());
any.set_type_url("/");
ASSERT_TRUE(CelProtoWrapper::CreateMessage(&any, arena()).IsError());
any.set_type_url("/invalid.proto.name");
ASSERT_TRUE(CelProtoWrapper::CreateMessage(&any, arena()).IsError());
}
TEST_F(CelProtoWrapperTest, UnwrapBoolWrapper) {
bool value = true;
BoolValue wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapInt32Wrapper) {
int64_t value = 12;
Int32Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapUInt32Wrapper) {
uint64_t value = 12;
UInt32Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapInt64Wrapper) {
int64_t value = 12;
Int64Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapUInt64Wrapper) {
uint64_t value = 12;
UInt64Value wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapFloatWrapper) {
double value = 42.5;
FloatValue wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapDoubleWrapper) {
double value = 42.5;
DoubleValue wrapper;
wrapper.set_value(value);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapStringWrapper) {
std::string text = "42";
auto value = CelValue::StringHolder(&text);
StringValue wrapper;
wrapper.set_value(text);
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, UnwrapBytesWrapper) {
std::string text = "42";
auto value = CelValue::BytesHolder(&text);
BytesValue wrapper;
wrapper.set_value("42");
ExpectUnwrappedPrimitive(wrapper, value);
}
TEST_F(CelProtoWrapperTest, WrapNull) {
auto cel_value = CelValue::CreateNull();
Value json;
json.set_null_value(protobuf::NULL_VALUE);
ExpectWrappedMessage(cel_value, json);
Any any;
any.PackFrom(json);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapBool) {
auto cel_value = CelValue::CreateBool(true);
Value json;
json.set_bool_value(true);
ExpectWrappedMessage(cel_value, json);
BoolValue wrapper;
wrapper.set_value(true);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapBytes) {
std::string str = "hello world";
auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str));
BytesValue wrapper;
wrapper.set_value(str);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapBytesToValue) {
std::string str = "hello world";
auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str));
Value json;
json.set_string_value("aGVsbG8gd29ybGQ=");
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapDuration) {
auto cel_value = CelValue::CreateDuration(absl::Seconds(300));
Duration d;
d.set_seconds(300);
ExpectWrappedMessage(cel_value, d);
Any any;
any.PackFrom(d);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapDurationToValue) {
auto cel_value = CelValue::CreateDuration(absl::Seconds(300));
Value json;
json.set_string_value("300s");
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapDouble) {
double num = 1.5;
auto cel_value = CelValue::CreateDouble(num);
Value json;
json.set_number_value(num);
ExpectWrappedMessage(cel_value, json);
DoubleValue wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapDoubleToFloatValue) {
double num = 1.5;
auto cel_value = CelValue::CreateDouble(num);
FloatValue wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
double small_num = -9.9e-100;
wrapper.set_value(small_num);
cel_value = CelValue::CreateDouble(small_num);
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapDoubleOverflow) {
double lowest_double = std::numeric_limits<double>::lowest();
auto cel_value = CelValue::CreateDouble(lowest_double);
FloatValue wrapper;
wrapper.set_value(-std::numeric_limits<float>::infinity());
ExpectWrappedMessage(cel_value, wrapper);
double max_double = std::numeric_limits<double>::max();
cel_value = CelValue::CreateDouble(max_double);
wrapper.set_value(std::numeric_limits<float>::infinity());
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapInt64) {
int32_t num = std::numeric_limits<int32_t>::lowest();
auto cel_value = CelValue::CreateInt64(num);
Value json;
json.set_number_value(static_cast<double>(num));
ExpectWrappedMessage(cel_value, json);
Int64Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapInt64ToInt32Value) {
int32_t num = std::numeric_limits<int32_t>::lowest();
auto cel_value = CelValue::CreateInt64(num);
Int32Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapFailureInt64ToInt32Value) {
int64_t num = std::numeric_limits<int64_t>::lowest();
auto cel_value = CelValue::CreateInt64(num);
Int32Value wrapper;
ExpectNotWrapped(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapInt64ToValue) {
int64_t max = std::numeric_limits<int64_t>::max();
auto cel_value = CelValue::CreateInt64(max);
Value json;
json.set_string_value(absl::StrCat(max));
ExpectWrappedMessage(cel_value, json);
int64_t min = std::numeric_limits<int64_t>::min();
cel_value = CelValue::CreateInt64(min);
json.set_string_value(absl::StrCat(min));
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapUint64) {
uint32_t num = std::numeric_limits<uint32_t>::max();
auto cel_value = CelValue::CreateUint64(num);
Value json;
json.set_number_value(static_cast<double>(num));
ExpectWrappedMessage(cel_value, json);
UInt64Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapUint64ToUint32Value) {
uint32_t num = std::numeric_limits<uint32_t>::max();
auto cel_value = CelValue::CreateUint64(num);
UInt32Value wrapper;
wrapper.set_value(num);
ExpectWrappedMessage(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapUint64ToValue) {
uint64_t num = std::numeric_limits<uint64_t>::max();
auto cel_value = CelValue::CreateUint64(num);
Value json;
json.set_string_value(absl::StrCat(num));
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapFailureUint64ToUint32Value) {
uint64_t num = std::numeric_limits<uint64_t>::max();
auto cel_value = CelValue::CreateUint64(num);
UInt32Value wrapper;
ExpectNotWrapped(cel_value, wrapper);
}
TEST_F(CelProtoWrapperTest, WrapString) {
std::string str = "test";
auto cel_value = CelValue::CreateString(CelValue::StringHolder(&str));
Value json;
json.set_string_value(str);
ExpectWrappedMessage(cel_value, json);
StringValue wrapper;
wrapper.set_value(str);
ExpectWrappedMessage(cel_value, wrapper);
Any any;
any.PackFrom(wrapper);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapTimestamp) {
absl::Time ts = absl::FromUnixSeconds(1615852799);
auto cel_value = CelValue::CreateTimestamp(ts);
Timestamp t;
t.set_seconds(1615852799);
ExpectWrappedMessage(cel_value, t);
Any any;
any.PackFrom(t);
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapTimestampToValue) {
absl::Time ts = absl::FromUnixSeconds(1615852799);
auto cel_value = CelValue::CreateTimestamp(ts);
Value json;
json.set_string_value("2021-03-15T23:59:59Z");
ExpectWrappedMessage(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapList) {
std::vector<CelValue> list_elems = {
CelValue::CreateDouble(1.5),
CelValue::CreateInt64(-2L),
};
ContainerBackedListImpl list(std::move(list_elems));
auto cel_value = CelValue::CreateList(&list);
Value json;
json.mutable_list_value()->add_values()->set_number_value(1.5);
json.mutable_list_value()->add_values()->set_number_value(-2.);
ExpectWrappedMessage(cel_value, json);
ExpectWrappedMessage(cel_value, json.list_value());
Any any;
any.PackFrom(json.list_value());
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapFailureListValueBadJSON) {
TestMessage message;
std::vector<CelValue> list_elems = {
CelValue::CreateDouble(1.5),
CelProtoWrapper::CreateMessage(&message, arena()),
};
ContainerBackedListImpl list(std::move(list_elems));
auto cel_value = CelValue::CreateList(&list);
Value json;
ExpectNotWrapped(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapStruct) {
const std::string kField1 = "field1";
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(CelValue::StringHolder(&kField1)),
CelValue::CreateBool(true)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
auto cel_value = CelValue::CreateMap(cel_map.get());
Value json;
(*json.mutable_struct_value()->mutable_fields())[kField1].set_bool_value(
true);
ExpectWrappedMessage(cel_value, json);
ExpectWrappedMessage(cel_value, json.struct_value());
Any any;
any.PackFrom(json.struct_value());
ExpectWrappedMessage(cel_value, any);
}
TEST_F(CelProtoWrapperTest, WrapFailureStructBadKeyType) {
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateInt64(1L), CelValue::CreateBool(true)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
auto cel_value = CelValue::CreateMap(cel_map.get());
Value json;
ExpectNotWrapped(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapFailureStructBadValueType) {
const std::string kField1 = "field1";
TestMessage bad_value;
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(CelValue::StringHolder(&kField1)),
CelProtoWrapper::CreateMessage(&bad_value, arena())}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
auto cel_value = CelValue::CreateMap(cel_map.get());
Value json;
ExpectNotWrapped(cel_value, json);
}
TEST_F(CelProtoWrapperTest, WrapFailureWrongType) {
auto cel_value = CelValue::CreateNull();
std::vector<const google::protobuf::Message*> wrong_types = {
&BoolValue::default_instance(), &BytesValue::default_instance(),
&DoubleValue::default_instance(), &Duration::default_instance(),
&FloatValue::default_instance(), &Int32Value::default_instance(),
&Int64Value::default_instance(), &ListValue::default_instance(),
&StringValue::default_instance(), &Struct::default_instance(),
&Timestamp::default_instance(), &UInt32Value::default_instance(),
&UInt64Value::default_instance(),
};
for (const auto* wrong_type : wrong_types) {
ExpectNotWrapped(cel_value, *wrong_type);
}
}
TEST_F(CelProtoWrapperTest, WrapFailureErrorToAny) {
auto cel_value = CreateNoSuchFieldError(arena(), "error_field");
ExpectNotWrapped(cel_value, Any::default_instance());
}
class InvalidListKeysCelMapBuilder : public CelMapBuilder {
public:
absl::StatusOr<const CelList*> ListKeys() const override {
return absl::InternalError("Error while invoking ListKeys()");
}
};
TEST_F(CelProtoWrapperTest, DebugString) {
google::protobuf::Empty e;
EXPECT_THAT(CelProtoWrapper::CreateMessage(&e, arena()).DebugString(),
testing::StartsWith("Message: "));
ListValue list_value;
list_value.add_values()->set_bool_value(true);
list_value.add_values()->set_number_value(1.0);
list_value.add_values()->set_string_value("test");
CelValue value = CelProtoWrapper::CreateMessage(&list_value, arena());
EXPECT_EQ(value.DebugString(),
"CelList: [bool: 1, double: 1.000000, string: test]");
Struct value_struct;
auto& value1 = (*value_struct.mutable_fields())["a"];
value1.set_bool_value(true);
auto& value2 = (*value_struct.mutable_fields())["b"];
value2.set_number_value(1.0);
auto& value3 = (*value_struct.mutable_fields())["c"];
value3.set_string_value("test");
value = CelProtoWrapper::CreateMessage(&value_struct, arena());
EXPECT_THAT(
value.DebugString(),
testing::AllOf(testing::StartsWith("CelMap: {"),
testing::HasSubstr("<string: a>: <bool: 1>"),
testing::HasSubstr("<string: b>: <double: 1.0"),
testing::HasSubstr("<string: c>: <string: test>")));
InvalidListKeysCelMapBuilder invalid_cel_map;
auto cel_map_value = CelValue::CreateMap(&invalid_cel_map);
EXPECT_EQ(cel_map_value.DebugString(), "CelMap: invalid list keys");
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/cel_proto_wrapper.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/cel_proto_wrapper_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
772caff1-e862-49bd-948f-2822a6bfb7e6 | cpp | google/cel-cpp | field_access_impl | eval/public/structs/field_access_impl.cc | eval/public/structs/field_access_impl_test.cc | #include "eval/public/structs/field_access_impl.h"
#include <cstdint>
#include <string>
#include <type_traits>
#include <utility>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/map_field.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "eval/public/structs/cel_proto_wrap_util.h"
#include "internal/casts.h"
#include "internal/overflow.h"
namespace google::api::expr::runtime::internal {
namespace {
using ::google::protobuf::Arena;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::MapValueConstRef;
using ::google::protobuf::Message;
using ::google::protobuf::Reflection;
template <class Derived>
class FieldAccessor {
public:
bool GetBool() const { return static_cast<const Derived*>(this)->GetBool(); }
int64_t GetInt32() const {
return static_cast<const Derived*>(this)->GetInt32();
}
uint64_t GetUInt32() const {
return static_cast<const Derived*>(this)->GetUInt32();
}
int64_t GetInt64() const {
return static_cast<const Derived*>(this)->GetInt64();
}
uint64_t GetUInt64() const {
return static_cast<const Derived*>(this)->GetUInt64();
}
double GetFloat() const {
return static_cast<const Derived*>(this)->GetFloat();
}
double GetDouble() const {
return static_cast<const Derived*>(this)->GetDouble();
}
absl::string_view GetString(std::string* buffer) const {
return static_cast<const Derived*>(this)->GetString(buffer);
}
const Message* GetMessage() const {
return static_cast<const Derived*>(this)->GetMessage();
}
int64_t GetEnumValue() const {
return static_cast<const Derived*>(this)->GetEnumValue();
}
absl::StatusOr<CelValue> CreateValueFromFieldAccessor(Arena* arena) {
switch (field_desc_->cpp_type()) {
case FieldDescriptor::CPPTYPE_BOOL: {
bool value = GetBool();
return CelValue::CreateBool(value);
}
case FieldDescriptor::CPPTYPE_INT32: {
int64_t value = GetInt32();
return CelValue::CreateInt64(value);
}
case FieldDescriptor::CPPTYPE_INT64: {
int64_t value = GetInt64();
return CelValue::CreateInt64(value);
}
case FieldDescriptor::CPPTYPE_UINT32: {
uint64_t value = GetUInt32();
return CelValue::CreateUint64(value);
}
case FieldDescriptor::CPPTYPE_UINT64: {
uint64_t value = GetUInt64();
return CelValue::CreateUint64(value);
}
case FieldDescriptor::CPPTYPE_FLOAT: {
double value = GetFloat();
return CelValue::CreateDouble(value);
}
case FieldDescriptor::CPPTYPE_DOUBLE: {
double value = GetDouble();
return CelValue::CreateDouble(value);
}
case FieldDescriptor::CPPTYPE_STRING: {
std::string buffer;
absl::string_view value = GetString(&buffer);
if (value.data() == buffer.data() && value.size() == buffer.size()) {
value = absl::string_view(
*google::protobuf::Arena::Create<std::string>(arena, std::move(buffer)));
}
switch (field_desc_->type()) {
case FieldDescriptor::TYPE_STRING:
return CelValue::CreateStringView(value);
case FieldDescriptor::TYPE_BYTES:
return CelValue::CreateBytesView(value);
default:
return absl::Status(absl::StatusCode::kInvalidArgument,
"Error handling C++ string conversion");
}
break;
}
case FieldDescriptor::CPPTYPE_MESSAGE: {
const google::protobuf::Message* msg_value = GetMessage();
return UnwrapMessageToValue(msg_value, protobuf_value_factory_, arena);
}
case FieldDescriptor::CPPTYPE_ENUM: {
int enum_value = GetEnumValue();
return CelValue::CreateInt64(enum_value);
}
default:
return absl::Status(absl::StatusCode::kInvalidArgument,
"Unhandled C++ type conversion");
}
return absl::Status(absl::StatusCode::kInvalidArgument,
"Unhandled C++ type conversion");
}
protected:
FieldAccessor(const Message* msg, const FieldDescriptor* field_desc,
const ProtobufValueFactory& protobuf_value_factory)
: msg_(msg),
field_desc_(field_desc),
protobuf_value_factory_(protobuf_value_factory) {}
const Message* msg_;
const FieldDescriptor* field_desc_;
const ProtobufValueFactory& protobuf_value_factory_;
};
const absl::flat_hash_set<std::string>& WellKnownWrapperTypes() {
static auto* wrapper_types = new absl::flat_hash_set<std::string>{
"google.protobuf.BoolValue", "google.protobuf.DoubleValue",
"google.protobuf.FloatValue", "google.protobuf.Int64Value",
"google.protobuf.Int32Value", "google.protobuf.UInt64Value",
"google.protobuf.UInt32Value", "google.protobuf.StringValue",
"google.protobuf.BytesValue",
};
return *wrapper_types;
}
bool IsWrapperType(const FieldDescriptor* field_descriptor) {
return WellKnownWrapperTypes().find(
field_descriptor->message_type()->full_name()) !=
WellKnownWrapperTypes().end();
}
class ScalarFieldAccessor : public FieldAccessor<ScalarFieldAccessor> {
public:
ScalarFieldAccessor(const Message* msg, const FieldDescriptor* field_desc,
bool unset_wrapper_as_null,
const ProtobufValueFactory& factory)
: FieldAccessor(msg, field_desc, factory),
unset_wrapper_as_null_(unset_wrapper_as_null) {}
bool GetBool() const { return GetReflection()->GetBool(*msg_, field_desc_); }
int64_t GetInt32() const {
return GetReflection()->GetInt32(*msg_, field_desc_);
}
uint64_t GetUInt32() const {
return GetReflection()->GetUInt32(*msg_, field_desc_);
}
int64_t GetInt64() const {
return GetReflection()->GetInt64(*msg_, field_desc_);
}
uint64_t GetUInt64() const {
return GetReflection()->GetUInt64(*msg_, field_desc_);
}
double GetFloat() const {
return GetReflection()->GetFloat(*msg_, field_desc_);
}
double GetDouble() const {
return GetReflection()->GetDouble(*msg_, field_desc_);
}
absl::string_view GetString(std::string* buffer) const {
return GetReflection()->GetStringReference(*msg_, field_desc_, buffer);
}
const Message* GetMessage() const {
if (unset_wrapper_as_null_ &&
!GetReflection()->HasField(*msg_, field_desc_) &&
IsWrapperType(field_desc_)) {
return nullptr;
}
return &GetReflection()->GetMessage(*msg_, field_desc_);
}
int64_t GetEnumValue() const {
return GetReflection()->GetEnumValue(*msg_, field_desc_);
}
const Reflection* GetReflection() const { return msg_->GetReflection(); }
private:
bool unset_wrapper_as_null_;
};
class RepeatedFieldAccessor : public FieldAccessor<RepeatedFieldAccessor> {
public:
RepeatedFieldAccessor(const Message* msg, const FieldDescriptor* field_desc,
int index, const ProtobufValueFactory& factory)
: FieldAccessor(msg, field_desc, factory), index_(index) {}
bool GetBool() const {
return GetReflection()->GetRepeatedBool(*msg_, field_desc_, index_);
}
int64_t GetInt32() const {
return GetReflection()->GetRepeatedInt32(*msg_, field_desc_, index_);
}
uint64_t GetUInt32() const {
return GetReflection()->GetRepeatedUInt32(*msg_, field_desc_, index_);
}
int64_t GetInt64() const {
return GetReflection()->GetRepeatedInt64(*msg_, field_desc_, index_);
}
uint64_t GetUInt64() const {
return GetReflection()->GetRepeatedUInt64(*msg_, field_desc_, index_);
}
double GetFloat() const {
return GetReflection()->GetRepeatedFloat(*msg_, field_desc_, index_);
}
double GetDouble() const {
return GetReflection()->GetRepeatedDouble(*msg_, field_desc_, index_);
}
absl::string_view GetString(std::string* buffer) const {
return GetReflection()->GetRepeatedStringReference(*msg_, field_desc_,
index_, buffer);
}
const Message* GetMessage() const {
return &GetReflection()->GetRepeatedMessage(*msg_, field_desc_, index_);
}
int64_t GetEnumValue() const {
return GetReflection()->GetRepeatedEnumValue(*msg_, field_desc_, index_);
}
const Reflection* GetReflection() const { return msg_->GetReflection(); }
private:
int index_;
};
class MapValueAccessor : public FieldAccessor<MapValueAccessor> {
public:
MapValueAccessor(const Message* msg, const FieldDescriptor* field_desc,
const MapValueConstRef* value_ref,
const ProtobufValueFactory& factory)
: FieldAccessor(msg, field_desc, factory), value_ref_(value_ref) {}
bool GetBool() const { return value_ref_->GetBoolValue(); }
int64_t GetInt32() const { return value_ref_->GetInt32Value(); }
uint64_t GetUInt32() const { return value_ref_->GetUInt32Value(); }
int64_t GetInt64() const { return value_ref_->GetInt64Value(); }
uint64_t GetUInt64() const { return value_ref_->GetUInt64Value(); }
double GetFloat() const { return value_ref_->GetFloatValue(); }
double GetDouble() const { return value_ref_->GetDoubleValue(); }
absl::string_view GetString(std::string* ) const {
return value_ref_->GetStringValue();
}
const Message* GetMessage() const { return &value_ref_->GetMessageValue(); }
int64_t GetEnumValue() const { return value_ref_->GetEnumValue(); }
const Reflection* GetReflection() const { return msg_->GetReflection(); }
private:
const MapValueConstRef* value_ref_;
};
template <class Derived>
class FieldSetter {
public:
bool AssignBool(const CelValue& cel_value) const {
bool value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetBool(value);
return true;
}
bool AssignInt32(const CelValue& cel_value) const {
int64_t value;
if (!cel_value.GetValue(&value)) {
return false;
}
absl::StatusOr<int32_t> checked_cast =
cel::internal::CheckedInt64ToInt32(value);
if (!checked_cast.ok()) {
return false;
}
static_cast<const Derived*>(this)->SetInt32(*checked_cast);
return true;
}
bool AssignUInt32(const CelValue& cel_value) const {
uint64_t value;
if (!cel_value.GetValue(&value)) {
return false;
}
if (!cel::internal::CheckedUint64ToUint32(value).ok()) {
return false;
}
static_cast<const Derived*>(this)->SetUInt32(value);
return true;
}
bool AssignInt64(const CelValue& cel_value) const {
int64_t value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetInt64(value);
return true;
}
bool AssignUInt64(const CelValue& cel_value) const {
uint64_t value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetUInt64(value);
return true;
}
bool AssignFloat(const CelValue& cel_value) const {
double value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetFloat(value);
return true;
}
bool AssignDouble(const CelValue& cel_value) const {
double value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetDouble(value);
return true;
}
bool AssignString(const CelValue& cel_value) const {
CelValue::StringHolder value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetString(value);
return true;
}
bool AssignBytes(const CelValue& cel_value) const {
CelValue::BytesHolder value;
if (!cel_value.GetValue(&value)) {
return false;
}
static_cast<const Derived*>(this)->SetBytes(value);
return true;
}
bool AssignEnum(const CelValue& cel_value) const {
int64_t value;
if (!cel_value.GetValue(&value)) {
return false;
}
if (!cel::internal::CheckedInt64ToInt32(value).ok()) {
return false;
}
static_cast<const Derived*>(this)->SetEnum(value);
return true;
}
bool AssignMessage(const google::protobuf::Message* message) const {
return static_cast<const Derived*>(this)->SetMessage(message);
}
bool SetFieldFromCelValue(const CelValue& value) {
switch (field_desc_->cpp_type()) {
case FieldDescriptor::CPPTYPE_BOOL: {
return AssignBool(value);
}
case FieldDescriptor::CPPTYPE_INT32: {
return AssignInt32(value);
}
case FieldDescriptor::CPPTYPE_INT64: {
return AssignInt64(value);
}
case FieldDescriptor::CPPTYPE_UINT32: {
return AssignUInt32(value);
}
case FieldDescriptor::CPPTYPE_UINT64: {
return AssignUInt64(value);
}
case FieldDescriptor::CPPTYPE_FLOAT: {
return AssignFloat(value);
}
case FieldDescriptor::CPPTYPE_DOUBLE: {
return AssignDouble(value);
}
case FieldDescriptor::CPPTYPE_STRING: {
switch (field_desc_->type()) {
case FieldDescriptor::TYPE_STRING:
return AssignString(value);
case FieldDescriptor::TYPE_BYTES:
return AssignBytes(value);
default:
return false;
}
break;
}
case FieldDescriptor::CPPTYPE_MESSAGE: {
const google::protobuf::Message* wrapped_value = MaybeWrapValueToMessage(
field_desc_->message_type(),
msg_->GetReflection()->GetMessageFactory(), value, arena_);
if (wrapped_value == nullptr) {
if (value.IsNull()) {
return true;
}
if (CelValue::MessageWrapper wrapper;
value.GetValue(&wrapper) && wrapper.HasFullProto()) {
wrapped_value =
static_cast<const google::protobuf::Message*>(wrapper.message_ptr());
} else {
return false;
}
}
return AssignMessage(wrapped_value);
}
case FieldDescriptor::CPPTYPE_ENUM: {
return AssignEnum(value);
}
default:
return false;
}
return true;
}
protected:
FieldSetter(Message* msg, const FieldDescriptor* field_desc, Arena* arena)
: msg_(msg), field_desc_(field_desc), arena_(arena) {}
Message* msg_;
const FieldDescriptor* field_desc_;
Arena* arena_;
};
bool MergeFromWithSerializeFallback(const google::protobuf::Message& value,
google::protobuf::Message& field) {
if (field.GetDescriptor() == value.GetDescriptor()) {
field.MergeFrom(value);
return true;
}
return field.MergeFromString(value.SerializeAsString());
}
class ScalarFieldSetter : public FieldSetter<ScalarFieldSetter> {
public:
ScalarFieldSetter(Message* msg, const FieldDescriptor* field_desc,
Arena* arena)
: FieldSetter(msg, field_desc, arena) {}
bool SetBool(bool value) const {
GetReflection()->SetBool(msg_, field_desc_, value);
return true;
}
bool SetInt32(int32_t value) const {
GetReflection()->SetInt32(msg_, field_desc_, value);
return true;
}
bool SetUInt32(uint32_t value) const {
GetReflection()->SetUInt32(msg_, field_desc_, value);
return true;
}
bool SetInt64(int64_t value) const {
GetReflection()->SetInt64(msg_, field_desc_, value);
return true;
}
bool SetUInt64(uint64_t value) const {
GetReflection()->SetUInt64(msg_, field_desc_, value);
return true;
}
bool SetFloat(float value) const {
GetReflection()->SetFloat(msg_, field_desc_, value);
return true;
}
bool SetDouble(double value) const {
GetReflection()->SetDouble(msg_, field_desc_, value);
return true;
}
bool SetString(CelValue::StringHolder value) const {
GetReflection()->SetString(msg_, field_desc_, std::string(value.value()));
return true;
}
bool SetBytes(CelValue::BytesHolder value) const {
GetReflection()->SetString(msg_, field_desc_, std::string(value.value()));
return true;
}
bool SetMessage(const Message* value) const {
if (!value) {
ABSL_LOG(ERROR) << "Message is NULL";
return true;
}
if (value->GetDescriptor()->full_name() ==
field_desc_->message_type()->full_name()) {
auto* assignable_field_msg =
GetReflection()->MutableMessage(msg_, field_desc_);
return MergeFromWithSerializeFallback(*value, *assignable_field_msg);
}
return false;
}
bool SetEnum(const int64_t value) const {
GetReflection()->SetEnumValue(msg_, field_desc_, value);
return true;
}
const Reflection* GetReflection() const { return msg_->GetReflection(); }
};
class RepeatedFieldSetter : public FieldSetter<RepeatedFieldSetter> {
public:
RepeatedFieldSetter(Message* msg, const FieldDescriptor* field_desc,
Arena* arena)
: FieldSetter(msg, field_desc, arena) {}
bool SetBool(bool value) const {
GetReflection()->AddBool(msg_, field_desc_, value);
return true;
}
bool SetInt32(int32_t value) const {
GetReflection()->AddInt32(msg_, field_desc_, value);
return true;
}
bool SetUInt32(uint32_t value) const {
GetReflection()->AddUInt32(msg_, field_desc_, value);
return true;
}
bool SetInt64(int64_t value) const {
GetReflection()->AddInt64(msg_, field_desc_, value);
return true;
}
bool SetUInt64(uint64_t value) const {
GetReflection()->AddUInt64(msg_, field_desc_, value);
return true;
}
bool SetFloat(float value) const {
GetReflection()->AddFloat(msg_, field_desc_, value);
return true;
}
bool SetDouble(double value) const {
GetReflection()->AddDouble(msg_, field_desc_, value);
return true;
}
bool SetString(CelValue::StringHolder value) const {
GetReflection()->AddString(msg_, field_desc_, std::string(value.value()));
return true;
}
bool SetBytes(CelValue::BytesHolder value) const {
GetReflection()->AddString(msg_, field_desc_, std::string(value.value()));
return true;
}
bool SetMessage(const Message* value) const {
if (!value) return true;
if (value->GetDescriptor()->full_name() !=
field_desc_->message_type()->full_name()) {
return false;
}
auto* assignable_message = GetReflection()->AddMessage(msg_, field_desc_);
return MergeFromWithSerializeFallback(*value, *assignable_message);
}
bool SetEnum(const int64_t value) const {
GetReflection()->AddEnumValue(msg_, field_desc_, value);
return true;
}
private:
const Reflection* GetReflection() const { return msg_->GetReflection(); }
};
}
absl::StatusOr<CelValue> CreateValueFromSingleField(
const google::protobuf::Message* msg, const FieldDescriptor* desc,
ProtoWrapperTypeOptions options, const ProtobufValueFactory& factory,
google::protobuf::Arena* arena) {
ScalarFieldAccessor accessor(
msg, desc, (options == ProtoWrapperTypeOptions::kUnsetNull), factory);
return accessor.CreateValueFromFieldAccessor(arena);
}
absl::StatusOr<CelValue> CreateValueFromRepeatedField(
const google::protobuf::Message* msg, const FieldDescriptor* desc, int index,
const ProtobufValueFactory& factory, google::protobuf::Arena* arena) {
RepeatedFieldAccessor accessor(msg, desc, index, factory);
return accessor.CreateValueFromFieldAccessor(arena);
}
absl::StatusOr<CelValue> CreateValueFromMapValue(
const google::protobuf::Message* msg, const FieldDescriptor* desc,
const MapValueConstRef* value_ref, const ProtobufValueFactory& factory,
google::protobuf::Arena* arena) {
MapValueAccessor accessor(msg, desc, value_ref, factory);
return accessor.CreateValueFromFieldAccessor(arena);
}
absl::Status SetValueToSingleField(const CelValue& value,
const FieldDescriptor* desc, Message* msg,
Arena* arena) {
ScalarFieldSetter setter(msg, desc, arena);
return (setter.SetFieldFromCelValue(value))
? absl::OkStatus()
: absl::InvalidArgumentError(absl::Substitute(
"Could not assign supplied argument to message \"$0\" field "
"\"$1\" of type $2: value type \"$3\"",
msg->GetDescriptor()->name(), desc->name(),
desc->type_name(), CelValue::TypeName(value.type())));
}
absl::Status AddValueToRepeatedField(const CelValue& value,
const FieldDescriptor* desc, Message* msg,
Arena* arena) {
RepeatedFieldSetter setter(msg, desc, arena);
return (setter.SetFieldFromCelValue(value))
? absl::OkStatus()
: absl::InvalidArgumentError(absl::Substitute(
"Could not add supplied argument to message \"$0\" field "
"\"$1\" of type $2: value type \"$3\"",
msg->GetDescriptor()->name(), desc->name(),
desc->type_name(), CelValue::TypeName(value.type())));
}
} | #include "eval/public/structs/field_access_impl.h"
#include <array>
#include <limits>
#include <string>
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/testing/matchers.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
#include "internal/time.h"
#include "testutil/util.h"
#include "proto/test/v1/proto3/test_all_types.pb.h"
namespace google::api::expr::runtime::internal {
namespace {
using ::absl_testing::StatusIs;
using ::cel::internal::MaxDuration;
using ::cel::internal::MaxTimestamp;
using ::google::api::expr::test::v1::proto3::TestAllTypes;
using ::google::protobuf::Arena;
using ::google::protobuf::FieldDescriptor;
using ::testing::HasSubstr;
using testutil::EqualsProto;
TEST(FieldAccessTest, SetDuration) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_duration");
auto status = SetValueToSingleField(CelValue::CreateDuration(MaxDuration()),
field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
TEST(FieldAccessTest, SetDurationBadDuration) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_duration");
auto status = SetValueToSingleField(
CelValue::CreateDuration(MaxDuration() + absl::Seconds(1)), field, &msg,
&arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetDurationBadInputType) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_duration");
auto status =
SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetTimestamp) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_timestamp");
auto status = SetValueToSingleField(CelValue::CreateTimestamp(MaxTimestamp()),
field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
TEST(FieldAccessTest, SetTimestampBadTime) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_timestamp");
auto status = SetValueToSingleField(
CelValue::CreateTimestamp(MaxTimestamp() + absl::Seconds(1)), field, &msg,
&arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetTimestampBadInputType) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_timestamp");
auto status =
SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetInt32Overflow) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_int32");
EXPECT_THAT(
SetValueToSingleField(
CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L),
field, &msg, &arena),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Could not assign")));
}
TEST(FieldAccessTest, SetUint32Overflow) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_uint32");
EXPECT_THAT(
SetValueToSingleField(
CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1L),
field, &msg, &arena),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Could not assign")));
}
TEST(FieldAccessTest, SetMessage) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("standalone_message");
TestAllTypes::NestedMessage* nested_msg =
google::protobuf::Arena::Create<TestAllTypes::NestedMessage>(&arena);
nested_msg->set_bb(1);
auto status = SetValueToSingleField(
CelProtoWrapper::CreateMessage(nested_msg, &arena), field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
TEST(FieldAccessTest, SetMessageWithNull) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("standalone_message");
auto status =
SetValueToSingleField(CelValue::CreateNull(), field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
struct AccessFieldTestParam {
absl::string_view field_name;
absl::string_view message_textproto;
CelValue cel_value;
};
std::string GetTestName(
const testing::TestParamInfo<AccessFieldTestParam>& info) {
return std::string(info.param.field_name);
}
class SingleFieldTest : public testing::TestWithParam<AccessFieldTestParam> {
public:
absl::string_view field_name() const { return GetParam().field_name; }
absl::string_view message_textproto() const {
return GetParam().message_textproto;
}
CelValue cel_value() const { return GetParam().cel_value; }
};
TEST_P(SingleFieldTest, Getter) {
TestAllTypes test_message;
ASSERT_TRUE(
google::protobuf::TextFormat::ParseFromString(message_textproto(), &test_message));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(
CelValue accessed_value,
CreateValueFromSingleField(
&test_message,
test_message.GetDescriptor()->FindFieldByName(field_name()),
ProtoWrapperTypeOptions::kUnsetProtoDefault,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(accessed_value, test::EqualsCelValue(cel_value()));
}
TEST_P(SingleFieldTest, Setter) {
TestAllTypes test_message;
CelValue to_set = cel_value();
google::protobuf::Arena arena;
ASSERT_OK(SetValueToSingleField(
to_set, test_message.GetDescriptor()->FindFieldByName(field_name()),
&test_message, &arena));
EXPECT_THAT(test_message, EqualsProto(message_textproto()));
}
INSTANTIATE_TEST_SUITE_P(
AllTypes, SingleFieldTest,
testing::ValuesIn<AccessFieldTestParam>({
{"single_int32", "single_int32: 1", CelValue::CreateInt64(1)},
{"single_int64", "single_int64: 1", CelValue::CreateInt64(1)},
{"single_uint32", "single_uint32: 1", CelValue::CreateUint64(1)},
{"single_uint64", "single_uint64: 1", CelValue::CreateUint64(1)},
{"single_sint32", "single_sint32: 1", CelValue::CreateInt64(1)},
{"single_sint64", "single_sint64: 1", CelValue::CreateInt64(1)},
{"single_fixed32", "single_fixed32: 1", CelValue::CreateUint64(1)},
{"single_fixed64", "single_fixed64: 1", CelValue::CreateUint64(1)},
{"single_sfixed32", "single_sfixed32: 1", CelValue::CreateInt64(1)},
{"single_sfixed64", "single_sfixed64: 1", CelValue::CreateInt64(1)},
{"single_float", "single_float: 1.0", CelValue::CreateDouble(1.0)},
{"single_double", "single_double: 1.0", CelValue::CreateDouble(1.0)},
{"single_bool", "single_bool: true", CelValue::CreateBool(true)},
{"single_string", "single_string: 'abcd'",
CelValue::CreateStringView("abcd")},
{"single_bytes", "single_bytes: 'asdf'",
CelValue::CreateBytesView("asdf")},
{"standalone_enum", "standalone_enum: BAZ", CelValue::CreateInt64(2)},
{"single_int64_wrapper", "single_int64_wrapper { value: 20 }",
CelValue::CreateInt64(20)},
{"single_value", "single_value { null_value: NULL_VALUE }",
CelValue::CreateNull()},
}),
&GetTestName);
TEST(CreateValueFromSingleFieldTest, GetMessage) {
TestAllTypes test_message;
google::protobuf::Arena arena;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
"standalone_message { bb: 10 }", &test_message));
ASSERT_OK_AND_ASSIGN(
CelValue accessed_value,
CreateValueFromSingleField(
&test_message,
test_message.GetDescriptor()->FindFieldByName("standalone_message"),
ProtoWrapperTypeOptions::kUnsetProtoDefault,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(accessed_value, test::IsCelMessage(EqualsProto("bb: 10")));
}
TEST(SetValueToSingleFieldTest, WrongType) {
TestAllTypes test_message;
google::protobuf::Arena arena;
EXPECT_THAT(SetValueToSingleField(
CelValue::CreateDouble(1.0),
test_message.GetDescriptor()->FindFieldByName("single_int32"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(SetValueToSingleFieldTest, IntOutOfRange) {
CelValue out_of_range = CelValue::CreateInt64(1LL << 31);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
google::protobuf::Arena arena;
EXPECT_THAT(SetValueToSingleField(out_of_range,
descriptor->FindFieldByName("single_int32"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(SetValueToSingleField(
out_of_range, descriptor->FindFieldByName("standalone_enum"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(SetValueToSingleFieldTest, UintOutOfRange) {
CelValue out_of_range = CelValue::CreateUint64(1LL << 32);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
google::protobuf::Arena arena;
EXPECT_THAT(SetValueToSingleField(
out_of_range, descriptor->FindFieldByName("single_uint32"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(SetValueToSingleFieldTest, SetMessage) {
TestAllTypes::NestedMessage nested_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
bb: 42
)",
&nested_message));
google::protobuf::Arena arena;
CelValue nested_value =
CelProtoWrapper::CreateMessage(&nested_message, &arena);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
ASSERT_OK(SetValueToSingleField(
nested_value, descriptor->FindFieldByName("standalone_message"),
&test_message, &arena));
EXPECT_THAT(test_message, EqualsProto("standalone_message { bb: 42 }"));
}
TEST(SetValueToSingleFieldTest, SetAnyMessage) {
TestAllTypes::NestedMessage nested_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
bb: 42
)",
&nested_message));
google::protobuf::Arena arena;
CelValue nested_value =
CelProtoWrapper::CreateMessage(&nested_message, &arena);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
ASSERT_OK(SetValueToSingleField(nested_value,
descriptor->FindFieldByName("single_any"),
&test_message, &arena));
TestAllTypes::NestedMessage unpacked;
test_message.single_any().UnpackTo(&unpacked);
EXPECT_THAT(unpacked, EqualsProto("bb: 42"));
}
TEST(SetValueToSingleFieldTest, SetMessageToNullNoop) {
google::protobuf::Arena arena;
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
ASSERT_OK(SetValueToSingleField(
CelValue::CreateNull(), descriptor->FindFieldByName("standalone_message"),
&test_message, &arena));
EXPECT_THAT(test_message, EqualsProto(test_message.default_instance()));
}
class RepeatedFieldTest : public testing::TestWithParam<AccessFieldTestParam> {
public:
absl::string_view field_name() const { return GetParam().field_name; }
absl::string_view message_textproto() const {
return GetParam().message_textproto;
}
CelValue cel_value() const { return GetParam().cel_value; }
};
TEST_P(RepeatedFieldTest, GetFirstElem) {
TestAllTypes test_message;
ASSERT_TRUE(
google::protobuf::TextFormat::ParseFromString(message_textproto(), &test_message));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(
CelValue accessed_value,
CreateValueFromRepeatedField(
&test_message,
test_message.GetDescriptor()->FindFieldByName(field_name()), 0,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(accessed_value, test::EqualsCelValue(cel_value()));
}
TEST_P(RepeatedFieldTest, AppendElem) {
TestAllTypes test_message;
CelValue to_add = cel_value();
google::protobuf::Arena arena;
ASSERT_OK(AddValueToRepeatedField(
to_add, test_message.GetDescriptor()->FindFieldByName(field_name()),
&test_message, &arena));
EXPECT_THAT(test_message, EqualsProto(message_textproto()));
}
INSTANTIATE_TEST_SUITE_P(
AllTypes, RepeatedFieldTest,
testing::ValuesIn<AccessFieldTestParam>(
{{"repeated_int32", "repeated_int32: 1", CelValue::CreateInt64(1)},
{"repeated_int64", "repeated_int64: 1", CelValue::CreateInt64(1)},
{"repeated_uint32", "repeated_uint32: 1", CelValue::CreateUint64(1)},
{"repeated_uint64", "repeated_uint64: 1", CelValue::CreateUint64(1)},
{"repeated_sint32", "repeated_sint32: 1", CelValue::CreateInt64(1)},
{"repeated_sint64", "repeated_sint64: 1", CelValue::CreateInt64(1)},
{"repeated_fixed32", "repeated_fixed32: 1", CelValue::CreateUint64(1)},
{"repeated_fixed64", "repeated_fixed64: 1", CelValue::CreateUint64(1)},
{"repeated_sfixed32", "repeated_sfixed32: 1",
CelValue::CreateInt64(1)},
{"repeated_sfixed64", "repeated_sfixed64: 1",
CelValue::CreateInt64(1)},
{"repeated_float", "repeated_float: 1.0", CelValue::CreateDouble(1.0)},
{"repeated_double", "repeated_double: 1.0",
CelValue::CreateDouble(1.0)},
{"repeated_bool", "repeated_bool: true", CelValue::CreateBool(true)},
{"repeated_string", "repeated_string: 'abcd'",
CelValue::CreateStringView("abcd")},
{"repeated_bytes", "repeated_bytes: 'asdf'",
CelValue::CreateBytesView("asdf")},
{"repeated_nested_enum", "repeated_nested_enum: BAZ",
CelValue::CreateInt64(2)}}),
&GetTestName);
TEST(RepeatedFieldTest, GetMessage) {
TestAllTypes test_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
"repeated_nested_message { bb: 30 }", &test_message));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue accessed_value,
CreateValueFromRepeatedField(
&test_message,
test_message.GetDescriptor()->FindFieldByName(
"repeated_nested_message"),
0, &CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(accessed_value, test::IsCelMessage(EqualsProto("bb: 30")));
}
TEST(AddValueToRepeatedFieldTest, WrongType) {
TestAllTypes test_message;
google::protobuf::Arena arena;
EXPECT_THAT(
AddValueToRepeatedField(
CelValue::CreateDouble(1.0),
test_message.GetDescriptor()->FindFieldByName("repeated_int32"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(AddValueToRepeatedFieldTest, IntOutOfRange) {
CelValue out_of_range = CelValue::CreateInt64(1LL << 31);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
google::protobuf::Arena arena;
EXPECT_THAT(AddValueToRepeatedField(
out_of_range, descriptor->FindFieldByName("repeated_int32"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
AddValueToRepeatedField(
out_of_range, descriptor->FindFieldByName("repeated_nested_enum"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(AddValueToRepeatedFieldTest, UintOutOfRange) {
CelValue out_of_range = CelValue::CreateUint64(1LL << 32);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
google::protobuf::Arena arena;
EXPECT_THAT(AddValueToRepeatedField(
out_of_range, descriptor->FindFieldByName("repeated_uint32"),
&test_message, &arena),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(AddValueToRepeatedFieldTest, AddMessage) {
TestAllTypes::NestedMessage nested_message;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
bb: 42
)",
&nested_message));
google::protobuf::Arena arena;
CelValue nested_value =
CelProtoWrapper::CreateMessage(&nested_message, &arena);
TestAllTypes test_message;
const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor();
ASSERT_OK(AddValueToRepeatedField(
nested_value, descriptor->FindFieldByName("repeated_nested_message"),
&test_message, &arena));
EXPECT_THAT(test_message, EqualsProto("repeated_nested_message { bb: 42 }"));
}
constexpr std::array<const char*, 9> kWrapperFieldNames = {
"single_bool_wrapper", "single_int64_wrapper", "single_int32_wrapper",
"single_uint64_wrapper", "single_uint32_wrapper", "single_double_wrapper",
"single_float_wrapper", "single_string_wrapper", "single_bytes_wrapper"};
TEST(CreateValueFromFieldTest, UnsetWrapperTypesNullIfEnabled) {
CelValue result;
TestAllTypes test_message;
google::protobuf::Arena arena;
for (const auto& field : kWrapperFieldNames) {
ASSERT_OK_AND_ASSIGN(
result, CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(field),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
ASSERT_TRUE(result.IsNull()) << field << ": " << result.DebugString();
}
}
TEST(CreateValueFromFieldTest, UnsetWrapperTypesDefaultValueIfDisabled) {
CelValue result;
TestAllTypes test_message;
google::protobuf::Arena arena;
for (const auto& field : kWrapperFieldNames) {
ASSERT_OK_AND_ASSIGN(
result, CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(field),
ProtoWrapperTypeOptions::kUnsetProtoDefault,
&CelProtoWrapper::InternalWrapMessage, &arena));
ASSERT_FALSE(result.IsNull()) << field << ": " << result.DebugString();
}
}
TEST(CreateValueFromFieldTest, SetWrapperTypesDefaultValue) {
CelValue result;
TestAllTypes test_message;
google::protobuf::Arena arena;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
single_bool_wrapper {}
single_int64_wrapper {}
single_int32_wrapper {}
single_uint64_wrapper {}
single_uint32_wrapper {}
single_double_wrapper {}
single_float_wrapper {}
single_string_wrapper {}
single_bytes_wrapper {}
)pb",
&test_message));
ASSERT_OK_AND_ASSIGN(
result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_bool_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelBool(false));
ASSERT_OK_AND_ASSIGN(result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_int64_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelInt64(0));
ASSERT_OK_AND_ASSIGN(result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_int32_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelInt64(0));
ASSERT_OK_AND_ASSIGN(
result,
CreateValueFromSingleField(&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_uint64_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage,
&arena));
EXPECT_THAT(result, test::IsCelUint64(0));
ASSERT_OK_AND_ASSIGN(
result,
CreateValueFromSingleField(&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_uint32_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage,
&arena));
EXPECT_THAT(result, test::IsCelUint64(0));
ASSERT_OK_AND_ASSIGN(result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_double_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelDouble(0.0f));
ASSERT_OK_AND_ASSIGN(result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_float_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelDouble(0.0f));
ASSERT_OK_AND_ASSIGN(result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_string_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelString(""));
ASSERT_OK_AND_ASSIGN(result,
CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName(
"single_bytes_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&CelProtoWrapper::InternalWrapMessage, &arena));
EXPECT_THAT(result, test::IsCelBytes(""));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/field_access_impl.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/field_access_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
d5168485-2112-465c-ac4b-17cbb673ffaa | cpp | google/cel-cpp | internal_field_backed_map_impl | eval/public/containers/internal_field_backed_map_impl.cc | eval/public/containers/internal_field_backed_map_impl_test.cc | #include "eval/public/containers/internal_field_backed_map_impl.h"
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include "google/protobuf/descriptor.h"
#include "google/protobuf/map_field.h"
#include "google/protobuf/message.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/field_access_impl.h"
#include "eval/public/structs/protobuf_value_factory.h"
#include "extensions/protobuf/internal/map_reflection.h"
namespace google::api::expr::runtime::internal {
namespace {
using google::protobuf::Descriptor;
using google::protobuf::FieldDescriptor;
using google::protobuf::MapValueConstRef;
using google::protobuf::Message;
constexpr int kKeyTag = 1;
constexpr int kValueTag = 2;
class KeyList : public CelList {
public:
KeyList(const google::protobuf::Message* message,
const google::protobuf::FieldDescriptor* descriptor,
const ProtobufValueFactory& factory, google::protobuf::Arena* arena)
: message_(message),
descriptor_(descriptor),
reflection_(message_->GetReflection()),
factory_(factory),
arena_(arena) {}
int size() const override {
return reflection_->FieldSize(*message_, descriptor_);
}
CelValue operator[](int index) const override {
const Message* entry =
&reflection_->GetRepeatedMessage(*message_, descriptor_, index);
if (entry == nullptr) {
return CelValue::CreateNull();
}
const Descriptor* entry_descriptor = entry->GetDescriptor();
const FieldDescriptor* key_desc =
entry_descriptor->FindFieldByNumber(kKeyTag);
absl::StatusOr<CelValue> key_value = CreateValueFromSingleField(
entry, key_desc, ProtoWrapperTypeOptions::kUnsetProtoDefault, factory_,
arena_);
if (!key_value.ok()) {
return CreateErrorValue(arena_, key_value.status());
}
return *key_value;
}
private:
const google::protobuf::Message* message_;
const google::protobuf::FieldDescriptor* descriptor_;
const google::protobuf::Reflection* reflection_;
const ProtobufValueFactory& factory_;
google::protobuf::Arena* arena_;
};
bool MatchesMapKeyType(const FieldDescriptor* key_desc, const CelValue& key) {
switch (key_desc->cpp_type()) {
case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
return key.IsBool();
case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
return key.IsInt64();
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
return key.IsUint64();
case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
return key.IsString();
default:
return false;
}
}
absl::Status InvalidMapKeyType(absl::string_view key_type) {
return absl::InvalidArgumentError(
absl::StrCat("Invalid map key type: '", key_type, "'"));
}
}
FieldBackedMapImpl::FieldBackedMapImpl(
const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* descriptor,
ProtobufValueFactory factory, google::protobuf::Arena* arena)
: message_(message),
descriptor_(descriptor),
key_desc_(descriptor_->message_type()->FindFieldByNumber(kKeyTag)),
value_desc_(descriptor_->message_type()->FindFieldByNumber(kValueTag)),
reflection_(message_->GetReflection()),
factory_(std::move(factory)),
arena_(arena),
key_list_(
std::make_unique<KeyList>(message, descriptor, factory_, arena)) {}
int FieldBackedMapImpl::size() const {
return reflection_->FieldSize(*message_, descriptor_);
}
absl::StatusOr<const CelList*> FieldBackedMapImpl::ListKeys() const {
return key_list_.get();
}
absl::StatusOr<bool> FieldBackedMapImpl::Has(const CelValue& key) const {
MapValueConstRef value_ref;
return LookupMapValue(key, &value_ref);
}
absl::optional<CelValue> FieldBackedMapImpl::operator[](CelValue key) const {
MapValueConstRef value_ref;
auto lookup_result = LookupMapValue(key, &value_ref);
if (!lookup_result.ok()) {
return CreateErrorValue(arena_, lookup_result.status());
}
if (!*lookup_result) {
return absl::nullopt;
}
absl::StatusOr<CelValue> result = CreateValueFromMapValue(
message_, value_desc_, &value_ref, factory_, arena_);
if (!result.ok()) {
return CreateErrorValue(arena_, result.status());
}
return *result;
}
absl::StatusOr<bool> FieldBackedMapImpl::LookupMapValue(
const CelValue& key, MapValueConstRef* value_ref) const {
if (!MatchesMapKeyType(key_desc_, key)) {
return InvalidMapKeyType(key_desc_->cpp_type_name());
}
std::string map_key_string;
google::protobuf::MapKey proto_key;
switch (key_desc_->cpp_type()) {
case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
bool key_value;
key.GetValue(&key_value);
proto_key.SetBoolValue(key_value);
} break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
int64_t key_value;
key.GetValue(&key_value);
if (key_value > std::numeric_limits<int32_t>::max() ||
key_value < std::numeric_limits<int32_t>::lowest()) {
return absl::OutOfRangeError("integer overflow");
}
proto_key.SetInt32Value(key_value);
} break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
int64_t key_value;
key.GetValue(&key_value);
proto_key.SetInt64Value(key_value);
} break;
case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
CelValue::StringHolder key_value;
key.GetValue(&key_value);
map_key_string.assign(key_value.value().data(), key_value.value().size());
proto_key.SetStringValue(map_key_string);
} break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
uint64_t key_value;
key.GetValue(&key_value);
if (key_value > std::numeric_limits<uint32_t>::max()) {
return absl::OutOfRangeError("unsigned integer overlow");
}
proto_key.SetUInt32Value(key_value);
} break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
uint64_t key_value;
key.GetValue(&key_value);
proto_key.SetUInt64Value(key_value);
} break;
default:
return InvalidMapKeyType(key_desc_->cpp_type_name());
}
return cel::extensions::protobuf_internal::LookupMapValue(
*reflection_, *message_, *descriptor_, proto_key, value_ref);
}
absl::StatusOr<bool> FieldBackedMapImpl::LegacyHasMapValue(
const CelValue& key) const {
auto lookup_result = LegacyLookupMapValue(key);
if (!lookup_result.has_value()) {
return false;
}
auto result = *lookup_result;
if (result.IsError()) {
return *(result.ErrorOrDie());
}
return true;
}
absl::optional<CelValue> FieldBackedMapImpl::LegacyLookupMapValue(
const CelValue& key) const {
if (!MatchesMapKeyType(key_desc_, key)) {
return CreateErrorValue(arena_,
InvalidMapKeyType(key_desc_->cpp_type_name()));
}
int map_size = size();
for (int i = 0; i < map_size; i++) {
const Message* entry =
&reflection_->GetRepeatedMessage(*message_, descriptor_, i);
if (entry == nullptr) continue;
absl::StatusOr<CelValue> key_value = CreateValueFromSingleField(
entry, key_desc_, ProtoWrapperTypeOptions::kUnsetProtoDefault, factory_,
arena_);
if (!key_value.ok()) {
return CreateErrorValue(arena_, key_value.status());
}
bool match = false;
switch (key_desc_->cpp_type()) {
case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
match = key.BoolOrDie() == key_value->BoolOrDie();
break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
match = key.Int64OrDie() == key_value->Int64OrDie();
break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
match = key.Uint64OrDie() == key_value->Uint64OrDie();
break;
case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
match = key.StringOrDie() == key_value->StringOrDie();
break;
default:
break;
}
if (match) {
absl::StatusOr<CelValue> value_cel_value = CreateValueFromSingleField(
entry, value_desc_, ProtoWrapperTypeOptions::kUnsetProtoDefault,
factory_, arena_);
if (!value_cel_value.ok()) {
return CreateErrorValue(arena_, value_cel_value.status());
}
return *value_cel_value;
}
}
return {};
}
} | #include "eval/public/containers/internal_field_backed_map_impl.h"
#include <array>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace google::api::expr::runtime::internal {
namespace {
using ::absl_testing::StatusIs;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::UnorderedPointwise;
class FieldBackedMapTestImpl : public FieldBackedMapImpl {
public:
FieldBackedMapTestImpl(const google::protobuf::Message* message,
const google::protobuf::FieldDescriptor* descriptor,
google::protobuf::Arena* arena)
: FieldBackedMapImpl(message, descriptor,
&CelProtoWrapper::InternalWrapMessage, arena) {}
using FieldBackedMapImpl::LegacyHasMapValue;
using FieldBackedMapImpl::LegacyLookupMapValue;
};
std::unique_ptr<FieldBackedMapTestImpl> CreateMap(const TestMessage* message,
const std::string& field,
google::protobuf::Arena* arena) {
const google::protobuf::FieldDescriptor* field_desc =
message->GetDescriptor()->FindFieldByName(field);
return std::make_unique<FieldBackedMapTestImpl>(message, field_desc, arena);
}
TEST(FieldBackedMapImplTest, BadKeyTypeTest) {
TestMessage message;
google::protobuf::Arena arena;
constexpr std::array<absl::string_view, 6> map_types = {
"int64_int32_map", "uint64_int32_map", "string_int32_map",
"bool_int32_map", "int32_int32_map", "uint32_uint32_map",
};
for (auto map_type : map_types) {
auto cel_map = CreateMap(&message, std::string(map_type), &arena);
auto result = cel_map->Has(CelValue::CreateNull());
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kInvalidArgument));
result = cel_map->LegacyHasMapValue(CelValue::CreateNull());
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kInvalidArgument));
auto lookup = (*cel_map)[CelValue::CreateNull()];
EXPECT_TRUE(lookup.has_value());
EXPECT_TRUE(lookup->IsError());
EXPECT_THAT(lookup->ErrorOrDie()->code(),
Eq(absl::StatusCode::kInvalidArgument));
lookup = cel_map->LegacyLookupMapValue(CelValue::CreateNull());
EXPECT_TRUE(lookup.has_value());
EXPECT_TRUE(lookup->IsError());
EXPECT_THAT(lookup->ErrorOrDie()->code(),
Eq(absl::StatusCode::kInvalidArgument));
}
}
TEST(FieldBackedMapImplTest, Int32KeyTest) {
TestMessage message;
auto field_map = message.mutable_int32_int32_map();
(*field_map)[0] = 1;
(*field_map)[1] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "int32_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateInt64(1)).value_or(false));
EXPECT_TRUE(
cel_map->LegacyHasMapValue(CelValue::CreateInt64(1)).value_or(false));
EXPECT_FALSE((*cel_map)[CelValue::CreateInt64(3)].has_value());
EXPECT_FALSE(cel_map->Has(CelValue::CreateInt64(3)).value_or(true));
EXPECT_FALSE(
cel_map->LegacyHasMapValue(CelValue::CreateInt64(3)).value_or(true));
}
TEST(FieldBackedMapImplTest, Int32KeyOutOfRangeTest) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "int32_int32_map", &arena);
auto result = cel_map->Has(
CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L));
EXPECT_THAT(result.status(),
StatusIs(absl::StatusCode::kOutOfRange, HasSubstr("overflow")));
result = cel_map->Has(
CelValue::CreateInt64(std::numeric_limits<int32_t>::lowest() - 1L));
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kOutOfRange));
}
TEST(FieldBackedMapImplTest, Int64KeyTest) {
TestMessage message;
auto field_map = message.mutable_int64_int32_map();
(*field_map)[0] = 1;
(*field_map)[1] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "int64_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateInt64(1)).value_or(false));
EXPECT_EQ(
cel_map->LegacyLookupMapValue(CelValue::CreateInt64(1))->Int64OrDie(), 2);
EXPECT_TRUE(
cel_map->LegacyHasMapValue(CelValue::CreateInt64(1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(3)].has_value(), false);
}
TEST(FieldBackedMapImplTest, BoolKeyTest) {
TestMessage message;
auto field_map = message.mutable_bool_int32_map();
(*field_map)[false] = 1;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "bool_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateBool(false)]->Int64OrDie(), 1);
EXPECT_TRUE(cel_map->Has(CelValue::CreateBool(false)).value_or(false));
EXPECT_TRUE(
cel_map->LegacyHasMapValue(CelValue::CreateBool(false)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateBool(true)].has_value(), false);
(*field_map)[true] = 2;
EXPECT_EQ((*cel_map)[CelValue::CreateBool(true)]->Int64OrDie(), 2);
}
TEST(FieldBackedMapImplTest, Uint32KeyTest) {
TestMessage message;
auto field_map = message.mutable_uint32_uint32_map();
(*field_map)[0] = 1u;
(*field_map)[1] = 2u;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "uint32_uint32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(0)]->Uint64OrDie(), 1UL);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(1)]->Uint64OrDie(), 2UL);
EXPECT_TRUE(cel_map->Has(CelValue::CreateUint64(1)).value_or(false));
EXPECT_TRUE(
cel_map->LegacyHasMapValue(CelValue::CreateUint64(1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(3)].has_value(), false);
EXPECT_EQ(cel_map->Has(CelValue::CreateUint64(3)).value_or(true), false);
}
TEST(FieldBackedMapImplTest, Uint32KeyOutOfRangeTest) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "uint32_uint32_map", &arena);
auto result = cel_map->Has(
CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1UL));
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kOutOfRange));
}
TEST(FieldBackedMapImplTest, Uint64KeyTest) {
TestMessage message;
auto field_map = message.mutable_uint64_int32_map();
(*field_map)[0] = 1;
(*field_map)[1] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "uint64_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateUint64(1)).value_or(false));
EXPECT_TRUE(
cel_map->LegacyHasMapValue(CelValue::CreateUint64(1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(3)].has_value(), false);
}
TEST(FieldBackedMapImplTest, StringKeyTest) {
TestMessage message;
auto field_map = message.mutable_string_int32_map();
(*field_map)["test0"] = 1;
(*field_map)["test1"] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
std::string test0 = "test0";
std::string test1 = "test1";
std::string test_notfound = "test_notfound";
EXPECT_EQ((*cel_map)[CelValue::CreateString(&test0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateString(&test1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateString(&test1)).value_or(false));
EXPECT_TRUE(cel_map->LegacyHasMapValue(CelValue::CreateString(&test1))
.value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateString(&test_notfound)].has_value(),
false);
}
TEST(FieldBackedMapImplTest, EmptySizeTest) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
EXPECT_EQ(cel_map->size(), 0);
}
TEST(FieldBackedMapImplTest, RepeatedAddTest) {
TestMessage message;
auto field_map = message.mutable_string_int32_map();
(*field_map)["test0"] = 1;
(*field_map)["test1"] = 2;
(*field_map)["test0"] = 3;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
EXPECT_EQ(cel_map->size(), 2);
}
TEST(FieldBackedMapImplTest, KeyListTest) {
TestMessage message;
auto field_map = message.mutable_string_int32_map();
std::vector<std::string> keys;
std::vector<std::string> keys1;
for (int i = 0; i < 100; i++) {
keys.push_back(absl::StrCat("test", i));
(*field_map)[keys.back()] = i;
}
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
const CelList* key_list = cel_map->ListKeys().value();
EXPECT_EQ(key_list->size(), 100);
for (int i = 0; i < key_list->size(); i++) {
keys1.push_back(std::string((*key_list)[i].StringOrDie().value()));
}
EXPECT_THAT(keys, UnorderedPointwise(Eq(), keys1));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/internal_field_backed_map_impl.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/internal_field_backed_map_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
7cbce453-224d-4a29-a1d3-b3103ddb6369 | cpp | google/cel-cpp | container_backed_map_impl | eval/public/containers/container_backed_map_impl.cc | eval/public/containers/container_backed_map_impl_test.cc | #include "eval/public/containers/container_backed_map_impl.h"
#include <memory>
#include <utility>
#include "absl/container/node_hash_map.h"
#include "absl/hash/hash.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "eval/public/cel_value.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
class HasherOp {
public:
template <class T>
size_t operator()(const T& arg) {
return std::hash<T>()(arg);
}
size_t operator()(const absl::Time arg) {
return absl::Hash<absl::Time>()(arg);
}
size_t operator()(const absl::Duration arg) {
return absl::Hash<absl::Duration>()(arg);
}
size_t operator()(const CelValue::StringHolder& arg) {
return absl::Hash<absl::string_view>()(arg.value());
}
size_t operator()(const CelValue::BytesHolder& arg) {
return absl::Hash<absl::string_view>()(arg.value());
}
size_t operator()(const CelValue::CelTypeHolder& arg) {
return absl::Hash<absl::string_view>()(arg.value());
}
size_t operator()(const std::nullptr_t&) { return 0; }
};
template <class T>
class EqualOp {
public:
explicit EqualOp(const T& arg) : arg_(arg) {}
template <class U>
bool operator()(const U&) const {
return false;
}
bool operator()(const T& other) const { return other == arg_; }
private:
const T& arg_;
};
class CelValueEq {
public:
explicit CelValueEq(const CelValue& other) : other_(other) {}
template <class Type>
bool operator()(const Type& arg) {
return other_.template Visit<bool>(EqualOp<Type>(arg));
}
private:
const CelValue& other_;
};
}
absl::optional<CelValue> CelMapBuilder::operator[](CelValue cel_key) const {
auto item = values_map_.find(cel_key);
if (item == values_map_.end()) {
return absl::nullopt;
}
return item->second;
}
absl::Status CelMapBuilder::Add(CelValue key, CelValue value) {
auto [unused, inserted] = values_map_.emplace(key, value);
if (!inserted) {
return absl::InvalidArgumentError("duplicate map keys");
}
key_list_.Add(key);
return absl::OkStatus();
}
size_t CelMapBuilder::Hasher::operator()(const CelValue& key) const {
return key.template Visit<size_t>(HasherOp());
}
bool CelMapBuilder::Equal::operator()(const CelValue& key1,
const CelValue& key2) const {
if (key1.type() != key2.type()) {
return false;
}
return key1.template Visit<bool>(CelValueEq(key2));
}
absl::StatusOr<std::unique_ptr<CelMap>> CreateContainerBackedMap(
absl::Span<const std::pair<CelValue, CelValue>> key_values) {
auto map = std::make_unique<CelMapBuilder>();
for (const auto& key_value : key_values) {
CEL_RETURN_IF_ERROR(map->Add(key_value.first, key_value.second));
}
return map;
}
}
}
}
} | #include "eval/public/containers/container_backed_map_impl.h"
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "eval/public/cel_value.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::testing::Eq;
using ::testing::IsNull;
using ::testing::Not;
TEST(ContainerBackedMapImplTest, TestMapInt64) {
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(2), CelValue::CreateInt64(3)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
ASSERT_THAT(cel_map, Not(IsNull()));
EXPECT_THAT(cel_map->size(), Eq(2));
auto lookup1 = (*cel_map)[CelValue::CreateInt64(1)];
ASSERT_TRUE(lookup1);
CelValue cel_value = lookup1.value();
ASSERT_TRUE(cel_value.IsInt64());
EXPECT_THAT(cel_value.Int64OrDie(), 2);
auto lookup2 = (*cel_map)[CelValue::CreateUint64(1)];
ASSERT_FALSE(lookup2);
auto lookup3 = (*cel_map)[CelValue::CreateInt64(3)];
ASSERT_FALSE(lookup3);
}
TEST(ContainerBackedMapImplTest, TestMapUint64) {
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateUint64(1), CelValue::CreateInt64(2)},
{CelValue::CreateUint64(2), CelValue::CreateInt64(3)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
ASSERT_THAT(cel_map, Not(IsNull()));
EXPECT_THAT(cel_map->size(), Eq(2));
auto lookup1 = (*cel_map)[CelValue::CreateUint64(1)];
ASSERT_TRUE(lookup1);
CelValue cel_value = lookup1.value();
ASSERT_TRUE(cel_value.IsInt64());
EXPECT_THAT(cel_value.Int64OrDie(), 2);
auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)];
ASSERT_FALSE(lookup2);
auto lookup3 = (*cel_map)[CelValue::CreateUint64(3)];
ASSERT_FALSE(lookup3);
}
TEST(ContainerBackedMapImplTest, TestMapString) {
const std::string kKey1 = "1";
const std::string kKey2 = "2";
const std::string kKey3 = "3";
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)},
{CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}};
auto cel_map =
CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size()))
.value();
ASSERT_THAT(cel_map, Not(IsNull()));
EXPECT_THAT(cel_map->size(), Eq(2));
auto lookup1 = (*cel_map)[CelValue::CreateString(&kKey1)];
ASSERT_TRUE(lookup1);
CelValue cel_value = lookup1.value();
ASSERT_TRUE(cel_value.IsInt64());
EXPECT_THAT(cel_value.Int64OrDie(), 2);
auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)];
ASSERT_FALSE(lookup2);
auto lookup3 = (*cel_map)[CelValue::CreateString(&kKey3)];
ASSERT_FALSE(lookup3);
}
TEST(CelMapBuilder, TestMapString) {
const std::string kKey1 = "1";
const std::string kKey2 = "2";
const std::string kKey3 = "3";
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)},
{CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}};
CelMapBuilder builder;
ASSERT_OK(
builder.Add(CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)));
ASSERT_OK(
builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)));
CelMap* cel_map = &builder;
ASSERT_THAT(cel_map, Not(IsNull()));
EXPECT_THAT(cel_map->size(), Eq(2));
auto lookup1 = (*cel_map)[CelValue::CreateString(&kKey1)];
ASSERT_TRUE(lookup1);
CelValue cel_value = lookup1.value();
ASSERT_TRUE(cel_value.IsInt64());
EXPECT_THAT(cel_value.Int64OrDie(), 2);
auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)];
ASSERT_FALSE(lookup2);
auto lookup3 = (*cel_map)[CelValue::CreateString(&kKey3)];
ASSERT_FALSE(lookup3);
}
TEST(CelMapBuilder, RepeatKeysFail) {
const std::string kKey1 = "1";
const std::string kKey2 = "2";
std::vector<std::pair<CelValue, CelValue>> args = {
{CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)},
{CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}};
CelMapBuilder builder;
ASSERT_OK(
builder.Add(CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)));
ASSERT_OK(
builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)));
EXPECT_THAT(
builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)),
StatusIs(absl::StatusCode::kInvalidArgument, "duplicate map keys"));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/container_backed_map_impl.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/container_backed_map_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
7c09d3ef-e487-42e4-a509-9fceb37513e6 | cpp | google/cel-cpp | field_access | eval/public/containers/field_access.cc | eval/public/containers/field_access_test.cc | #include "eval/public/containers/field_access.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/map_field.h"
#include "absl/status/status.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/structs/field_access_impl.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
using ::google::protobuf::Arena;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::MapValueConstRef;
using ::google::protobuf::Message;
absl::Status CreateValueFromSingleField(const google::protobuf::Message* msg,
const FieldDescriptor* desc,
google::protobuf::Arena* arena,
CelValue* result) {
return CreateValueFromSingleField(
msg, desc, ProtoWrapperTypeOptions::kUnsetProtoDefault, arena, result);
}
absl::Status CreateValueFromSingleField(const google::protobuf::Message* msg,
const FieldDescriptor* desc,
ProtoWrapperTypeOptions options,
google::protobuf::Arena* arena,
CelValue* result) {
CEL_ASSIGN_OR_RETURN(
*result,
internal::CreateValueFromSingleField(
msg, desc, options, &CelProtoWrapper::InternalWrapMessage, arena));
return absl::OkStatus();
}
absl::Status CreateValueFromRepeatedField(const google::protobuf::Message* msg,
const FieldDescriptor* desc,
google::protobuf::Arena* arena, int index,
CelValue* result) {
CEL_ASSIGN_OR_RETURN(
*result,
internal::CreateValueFromRepeatedField(
msg, desc, index, &CelProtoWrapper::InternalWrapMessage, arena));
return absl::OkStatus();
}
absl::Status CreateValueFromMapValue(const google::protobuf::Message* msg,
const FieldDescriptor* desc,
const MapValueConstRef* value_ref,
google::protobuf::Arena* arena, CelValue* result) {
CEL_ASSIGN_OR_RETURN(
*result,
internal::CreateValueFromMapValue(
msg, desc, value_ref, &CelProtoWrapper::InternalWrapMessage, arena));
return absl::OkStatus();
}
absl::Status SetValueToSingleField(const CelValue& value,
const FieldDescriptor* desc, Message* msg,
Arena* arena) {
return internal::SetValueToSingleField(value, desc, msg, arena);
}
absl::Status AddValueToRepeatedField(const CelValue& value,
const FieldDescriptor* desc, Message* msg,
Arena* arena) {
return internal::AddValueToRepeatedField(value, desc, msg, arena);
}
} | #include "eval/public/containers/field_access.h"
#include <array>
#include <limits>
#include "google/protobuf/arena.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/testing/matchers.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
#include "internal/time.h"
#include "proto/test/v1/proto3/test_all_types.pb.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::internal::MaxDuration;
using ::cel::internal::MaxTimestamp;
using ::google::api::expr::test::v1::proto3::TestAllTypes;
using ::google::protobuf::Arena;
using ::google::protobuf::FieldDescriptor;
using ::testing::HasSubstr;
TEST(FieldAccessTest, SetDuration) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_duration");
auto status = SetValueToSingleField(CelValue::CreateDuration(MaxDuration()),
field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
TEST(FieldAccessTest, SetDurationBadDuration) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_duration");
auto status = SetValueToSingleField(
CelValue::CreateDuration(MaxDuration() + absl::Seconds(1)), field, &msg,
&arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetDurationBadInputType) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_duration");
auto status =
SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetTimestamp) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_timestamp");
auto status = SetValueToSingleField(CelValue::CreateTimestamp(MaxTimestamp()),
field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
TEST(FieldAccessTest, SetTimestampBadTime) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_timestamp");
auto status = SetValueToSingleField(
CelValue::CreateTimestamp(MaxTimestamp() + absl::Seconds(1)), field, &msg,
&arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetTimestampBadInputType) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_timestamp");
auto status =
SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument);
}
TEST(FieldAccessTest, SetInt32Overflow) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_int32");
EXPECT_THAT(
SetValueToSingleField(
CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L),
field, &msg, &arena),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Could not assign")));
}
TEST(FieldAccessTest, SetUint32Overflow) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("single_uint32");
EXPECT_THAT(
SetValueToSingleField(
CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1L),
field, &msg, &arena),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Could not assign")));
}
TEST(FieldAccessTest, SetMessage) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("standalone_message");
TestAllTypes::NestedMessage* nested_msg =
google::protobuf::Arena::Create<TestAllTypes::NestedMessage>(&arena);
nested_msg->set_bb(1);
auto status = SetValueToSingleField(
CelProtoWrapper::CreateMessage(nested_msg, &arena), field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
TEST(FieldAccessTest, SetMessageWithNul) {
Arena arena;
TestAllTypes msg;
const FieldDescriptor* field =
TestAllTypes::descriptor()->FindFieldByName("standalone_message");
auto status =
SetValueToSingleField(CelValue::CreateNull(), field, &msg, &arena);
EXPECT_TRUE(status.ok());
}
constexpr std::array<const char*, 9> kWrapperFieldNames = {
"single_bool_wrapper", "single_int64_wrapper", "single_int32_wrapper",
"single_uint64_wrapper", "single_uint32_wrapper", "single_double_wrapper",
"single_float_wrapper", "single_string_wrapper", "single_bytes_wrapper"};
TEST(CreateValueFromFieldTest, UnsetWrapperTypesNullIfEnabled) {
CelValue result;
TestAllTypes test_message;
google::protobuf::Arena arena;
for (const auto& field : kWrapperFieldNames) {
ASSERT_OK(CreateValueFromSingleField(
&test_message, TestAllTypes::GetDescriptor()->FindFieldByName(field),
ProtoWrapperTypeOptions::kUnsetNull, &arena, &result))
<< field;
ASSERT_TRUE(result.IsNull()) << field << ": " << result.DebugString();
}
}
TEST(CreateValueFromFieldTest, UnsetWrapperTypesDefaultValueIfDisabled) {
CelValue result;
TestAllTypes test_message;
google::protobuf::Arena arena;
for (const auto& field : kWrapperFieldNames) {
ASSERT_OK(CreateValueFromSingleField(
&test_message, TestAllTypes::GetDescriptor()->FindFieldByName(field),
ProtoWrapperTypeOptions::kUnsetProtoDefault, &arena, &result))
<< field;
ASSERT_FALSE(result.IsNull()) << field << ": " << result.DebugString();
}
}
TEST(CreateValueFromFieldTest, SetWrapperTypesDefaultValue) {
CelValue result;
TestAllTypes test_message;
google::protobuf::Arena arena;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
single_bool_wrapper {}
single_int64_wrapper {}
single_int32_wrapper {}
single_uint64_wrapper {}
single_uint32_wrapper {}
single_double_wrapper {}
single_float_wrapper {}
single_string_wrapper {}
single_bytes_wrapper {}
)pb",
&test_message));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_bool_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull, &arena, &result));
EXPECT_THAT(result, test::IsCelBool(false));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_int64_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull, &arena, &result));
EXPECT_THAT(result, test::IsCelInt64(0));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_int32_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull, &arena, &result));
EXPECT_THAT(result, test::IsCelInt64(0));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_uint64_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull, &arena, &result));
EXPECT_THAT(result, test::IsCelUint64(0));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_uint32_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull, &arena, &result));
EXPECT_THAT(result, test::IsCelUint64(0));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_double_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&arena, &result));
EXPECT_THAT(result, test::IsCelDouble(0.0f));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_float_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&arena, &result));
EXPECT_THAT(result, test::IsCelDouble(0.0f));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_string_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&arena, &result));
EXPECT_THAT(result, test::IsCelString(""));
ASSERT_OK(CreateValueFromSingleField(
&test_message,
TestAllTypes::GetDescriptor()->FindFieldByName("single_bytes_wrapper"),
ProtoWrapperTypeOptions::kUnsetNull,
&arena, &result));
EXPECT_THAT(result, test::IsCelBytes(""));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/field_access.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/field_access_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5d5ceec1-cfc9-48bb-8370-fd4852f50c2f | cpp | google/cel-cpp | internal_field_backed_list_impl | eval/public/containers/internal_field_backed_list_impl.cc | eval/public/containers/internal_field_backed_list_impl_test.cc | #include "eval/public/containers/internal_field_backed_list_impl.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/field_access_impl.h"
namespace google::api::expr::runtime::internal {
int FieldBackedListImpl::size() const {
return reflection_->FieldSize(*message_, descriptor_);
}
CelValue FieldBackedListImpl::operator[](int index) const {
auto result = CreateValueFromRepeatedField(message_, descriptor_, index,
factory_, arena_);
if (!result.ok()) {
CreateErrorValue(arena_, result.status().ToString());
}
return *result;
}
} | #include "eval/public/containers/internal_field_backed_list_impl.h"
#include <memory>
#include <string>
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
#include "testutil/util.h"
namespace google::api::expr::runtime::internal {
namespace {
using ::google::api::expr::testutil::EqualsProto;
using ::testing::DoubleEq;
using ::testing::Eq;
std::unique_ptr<CelList> CreateList(const TestMessage* message,
const std::string& field,
google::protobuf::Arena* arena) {
const google::protobuf::FieldDescriptor* field_desc =
message->GetDescriptor()->FindFieldByName(field);
return std::make_unique<FieldBackedListImpl>(
message, field_desc, &CelProtoWrapper::InternalWrapMessage, arena);
}
TEST(FieldBackedListImplTest, BoolDatatypeTest) {
TestMessage message;
message.add_bool_list(true);
message.add_bool_list(false);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "bool_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].BoolOrDie(), true);
EXPECT_EQ((*cel_list)[1].BoolOrDie(), false);
}
TEST(FieldBackedListImplTest, TestLength0) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), 0);
}
TEST(FieldBackedListImplTest, TestLength1) {
TestMessage message;
message.add_int32_list(1);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), 1);
EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1);
}
TEST(FieldBackedListImplTest, TestLength100000) {
TestMessage message;
const int kLen = 100000;
for (int i = 0; i < kLen; i++) {
message.add_int32_list(i);
}
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), kLen);
for (int i = 0; i < kLen; i++) {
EXPECT_EQ((*cel_list)[i].Int64OrDie(), i);
}
}
TEST(FieldBackedListImplTest, Int32DatatypeTest) {
TestMessage message;
message.add_int32_list(1);
message.add_int32_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Int64OrDie(), 2);
}
TEST(FieldBackedListImplTest, Int64DatatypeTest) {
TestMessage message;
message.add_int64_list(1);
message.add_int64_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int64_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Int64OrDie(), 2);
}
TEST(FieldBackedListImplTest, Uint32DatatypeTest) {
TestMessage message;
message.add_uint32_list(1);
message.add_uint32_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "uint32_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Uint64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Uint64OrDie(), 2);
}
TEST(FieldBackedListImplTest, Uint64DatatypeTest) {
TestMessage message;
message.add_uint64_list(1);
message.add_uint64_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "uint64_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Uint64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Uint64OrDie(), 2);
}
TEST(FieldBackedListImplTest, FloatDatatypeTest) {
TestMessage message;
message.add_float_list(1);
message.add_float_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "float_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT((*cel_list)[0].DoubleOrDie(), DoubleEq(1));
EXPECT_THAT((*cel_list)[1].DoubleOrDie(), DoubleEq(2));
}
TEST(FieldBackedListImplTest, DoubleDatatypeTest) {
TestMessage message;
message.add_double_list(1);
message.add_double_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "double_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT((*cel_list)[0].DoubleOrDie(), DoubleEq(1));
EXPECT_THAT((*cel_list)[1].DoubleOrDie(), DoubleEq(2));
}
TEST(FieldBackedListImplTest, StringDatatypeTest) {
TestMessage message;
message.add_string_list("1");
message.add_string_list("2");
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "string_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].StringOrDie().value(), "1");
EXPECT_EQ((*cel_list)[1].StringOrDie().value(), "2");
}
TEST(FieldBackedListImplTest, BytesDatatypeTest) {
TestMessage message;
message.add_bytes_list("1");
message.add_bytes_list("2");
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "bytes_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].BytesOrDie().value(), "1");
EXPECT_EQ((*cel_list)[1].BytesOrDie().value(), "2");
}
TEST(FieldBackedListImplTest, MessageDatatypeTest) {
TestMessage message;
TestMessage* msg1 = message.add_message_list();
TestMessage* msg2 = message.add_message_list();
msg1->set_string_value("1");
msg2->set_string_value("2");
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "message_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT(*msg1, EqualsProto(*((*cel_list)[0].MessageOrDie())));
EXPECT_THAT(*msg2, EqualsProto(*((*cel_list)[1].MessageOrDie())));
}
TEST(FieldBackedListImplTest, EnumDatatypeTest) {
TestMessage message;
message.add_enum_list(TestMessage::TEST_ENUM_1);
message.add_enum_list(TestMessage::TEST_ENUM_2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "enum_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT((*cel_list)[0].Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
EXPECT_THAT((*cel_list)[1].Int64OrDie(), Eq(TestMessage::TEST_ENUM_2));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/internal_field_backed_list_impl.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/internal_field_backed_list_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
65052c89-6330-4bd5-a6a6-108f90936938 | cpp | google/cel-cpp | function_step | eval/eval/function_step.cc | eval/eval/function_step_test.cc | #include "eval/eval/function_step.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/inlined_vector.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "base/ast_internal/expr.h"
#include "base/function.h"
#include "base/function_descriptor.h"
#include "base/kind.h"
#include "common/casting.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "internal/status_macros.h"
#include "runtime/activation_interface.h"
#include "runtime/function_overload_reference.h"
#include "runtime/function_provider.h"
#include "runtime/function_registry.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::FunctionEvaluationContext;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ValueKindToKind;
bool ShouldAcceptOverload(const cel::FunctionDescriptor& descriptor,
absl::Span<const cel::Value> arguments) {
for (size_t i = 0; i < arguments.size(); i++) {
if (arguments[i]->Is<cel::UnknownValue>() ||
arguments[i]->Is<cel::ErrorValue>()) {
return !descriptor.is_strict();
}
}
return true;
}
bool ArgumentKindsMatch(const cel::FunctionDescriptor& descriptor,
absl::Span<const cel::Value> arguments) {
auto types_size = descriptor.types().size();
if (types_size != arguments.size()) {
return false;
}
for (size_t i = 0; i < types_size; i++) {
const auto& arg = arguments[i];
cel::Kind param_kind = descriptor.types()[i];
if (arg->kind() != param_kind && param_kind != cel::Kind::kAny) {
return false;
}
}
return true;
}
std::string ToLegacyKindName(absl::string_view type_name) {
if (type_name == "int" || type_name == "uint") {
return absl::StrCat(type_name, "64");
}
return std::string(type_name);
}
std::string CallArgTypeString(absl::Span<const cel::Value> args) {
std::string call_sig_string = "";
for (size_t i = 0; i < args.size(); i++) {
const auto& arg = args[i];
if (!call_sig_string.empty()) {
absl::StrAppend(&call_sig_string, ", ");
}
absl::StrAppend(
&call_sig_string,
ToLegacyKindName(cel::KindToString(ValueKindToKind(arg->kind()))));
}
return absl::StrCat("(", call_sig_string, ")");
}
std::vector<cel::Value> CheckForPartialUnknowns(
ExecutionFrame* frame, absl::Span<const cel::Value> args,
absl::Span<const AttributeTrail> attrs) {
std::vector<cel::Value> result;
result.reserve(args.size());
for (size_t i = 0; i < args.size(); i++) {
const AttributeTrail& trail = attrs.subspan(i, 1)[0];
if (frame->attribute_utility().CheckForUnknown(trail,
true)) {
result.push_back(
frame->attribute_utility().CreateUnknownSet(trail.attribute()));
} else {
result.push_back(args.at(i));
}
}
return result;
}
bool IsUnknownFunctionResultError(const Value& result) {
if (!result->Is<cel::ErrorValue>()) {
return false;
}
const auto& status = result.GetError().NativeValue();
if (status.code() != absl::StatusCode::kUnavailable) {
return false;
}
auto payload = status.GetPayload(
cel::runtime_internal::kPayloadUrlUnknownFunctionResult);
return payload.has_value() && payload.value() == "true";
}
using ResolveResult = absl::optional<cel::FunctionOverloadReference>;
class AbstractFunctionStep : public ExpressionStepBase {
public:
AbstractFunctionStep(const std::string& name, size_t num_arguments,
int64_t expr_id)
: ExpressionStepBase(expr_id),
name_(name),
num_arguments_(num_arguments) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
absl::StatusOr<Value> DoEvaluate(ExecutionFrame* frame) const;
virtual absl::StatusOr<ResolveResult> ResolveFunction(
absl::Span<const cel::Value> args, const ExecutionFrame* frame) const = 0;
protected:
std::string name_;
size_t num_arguments_;
};
inline absl::StatusOr<Value> Invoke(
const cel::FunctionOverloadReference& overload, int64_t expr_id,
absl::Span<const cel::Value> args, ExecutionFrameBase& frame) {
FunctionEvaluationContext context(frame.value_manager());
CEL_ASSIGN_OR_RETURN(Value result,
overload.implementation.Invoke(context, args));
if (frame.unknown_function_results_enabled() &&
IsUnknownFunctionResultError(result)) {
return frame.attribute_utility().CreateUnknownSet(overload.descriptor,
expr_id, args);
}
return result;
}
Value NoOverloadResult(absl::string_view name,
absl::Span<const cel::Value> args,
ExecutionFrameBase& frame) {
for (size_t i = 0; i < args.size(); i++) {
const auto& arg = args[i];
if (cel::InstanceOf<cel::ErrorValue>(arg)) {
return arg;
}
}
if (frame.unknown_processing_enabled()) {
absl::optional<UnknownValue> unknown_set =
frame.attribute_utility().MergeUnknowns(args);
if (unknown_set.has_value()) {
return *unknown_set;
}
}
return frame.value_manager().CreateErrorValue(
cel::runtime_internal::CreateNoMatchingOverloadError(
absl::StrCat(name, CallArgTypeString(args))));
}
absl::StatusOr<Value> AbstractFunctionStep::DoEvaluate(
ExecutionFrame* frame) const {
auto input_args = frame->value_stack().GetSpan(num_arguments_);
std::vector<cel::Value> unknowns_args;
if (frame->enable_unknowns()) {
auto input_attrs = frame->value_stack().GetAttributeSpan(num_arguments_);
unknowns_args = CheckForPartialUnknowns(frame, input_args, input_attrs);
input_args = absl::MakeConstSpan(unknowns_args);
}
CEL_ASSIGN_OR_RETURN(ResolveResult matched_function,
ResolveFunction(input_args, frame));
if (matched_function.has_value() &&
ShouldAcceptOverload(matched_function->descriptor, input_args)) {
return Invoke(*matched_function, id(), input_args, *frame);
}
return NoOverloadResult(name_, input_args, *frame);
}
absl::Status AbstractFunctionStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(num_arguments_)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
CEL_ASSIGN_OR_RETURN(auto result, DoEvaluate(frame));
frame->value_stack().PopAndPush(num_arguments_, std::move(result));
return absl::OkStatus();
}
absl::StatusOr<ResolveResult> ResolveStatic(
absl::Span<const cel::Value> input_args,
absl::Span<const cel::FunctionOverloadReference> overloads) {
ResolveResult result = absl::nullopt;
for (const auto& overload : overloads) {
if (ArgumentKindsMatch(overload.descriptor, input_args)) {
if (result.has_value()) {
return absl::Status(absl::StatusCode::kInternal,
"Cannot resolve overloads");
}
result.emplace(overload);
}
}
return result;
}
absl::StatusOr<ResolveResult> ResolveLazy(
absl::Span<const cel::Value> input_args, absl::string_view name,
bool receiver_style,
absl::Span<const cel::FunctionRegistry::LazyOverload> providers,
const ExecutionFrameBase& frame) {
ResolveResult result = absl::nullopt;
std::vector<cel::Kind> arg_types(input_args.size());
std::transform(
input_args.begin(), input_args.end(), arg_types.begin(),
[](const cel::Value& value) { return ValueKindToKind(value->kind()); });
cel::FunctionDescriptor matcher{name, receiver_style, arg_types};
const cel::ActivationInterface& activation = frame.activation();
for (auto provider : providers) {
if (!ArgumentKindsMatch(provider.descriptor, input_args)) {
continue;
}
CEL_ASSIGN_OR_RETURN(auto overload,
provider.provider.GetFunction(matcher, activation));
if (overload.has_value()) {
if (result.has_value()) {
return absl::Status(absl::StatusCode::kInternal,
"Cannot resolve overloads");
}
result.emplace(overload.value());
}
}
return result;
}
class EagerFunctionStep : public AbstractFunctionStep {
public:
EagerFunctionStep(std::vector<cel::FunctionOverloadReference> overloads,
const std::string& name, size_t num_args, int64_t expr_id)
: AbstractFunctionStep(name, num_args, expr_id),
overloads_(std::move(overloads)) {}
absl::StatusOr<ResolveResult> ResolveFunction(
absl::Span<const cel::Value> input_args,
const ExecutionFrame* frame) const override {
return ResolveStatic(input_args, overloads_);
}
private:
std::vector<cel::FunctionOverloadReference> overloads_;
};
class LazyFunctionStep : public AbstractFunctionStep {
public:
LazyFunctionStep(const std::string& name, size_t num_args,
bool receiver_style,
std::vector<cel::FunctionRegistry::LazyOverload> providers,
int64_t expr_id)
: AbstractFunctionStep(name, num_args, expr_id),
receiver_style_(receiver_style),
providers_(std::move(providers)) {}
absl::StatusOr<ResolveResult> ResolveFunction(
absl::Span<const cel::Value> input_args,
const ExecutionFrame* frame) const override;
private:
bool receiver_style_;
std::vector<cel::FunctionRegistry::LazyOverload> providers_;
};
absl::StatusOr<ResolveResult> LazyFunctionStep::ResolveFunction(
absl::Span<const cel::Value> input_args,
const ExecutionFrame* frame) const {
return ResolveLazy(input_args, name_, receiver_style_, providers_, *frame);
}
class StaticResolver {
public:
explicit StaticResolver(std::vector<cel::FunctionOverloadReference> overloads)
: overloads_(std::move(overloads)) {}
absl::StatusOr<ResolveResult> Resolve(ExecutionFrameBase& frame,
absl::Span<const Value> input) const {
return ResolveStatic(input, overloads_);
}
private:
std::vector<cel::FunctionOverloadReference> overloads_;
};
class LazyResolver {
public:
explicit LazyResolver(
std::vector<cel::FunctionRegistry::LazyOverload> providers,
std::string name, bool receiver_style)
: providers_(std::move(providers)),
name_(std::move(name)),
receiver_style_(receiver_style) {}
absl::StatusOr<ResolveResult> Resolve(ExecutionFrameBase& frame,
absl::Span<const Value> input) const {
return ResolveLazy(input, name_, receiver_style_, providers_, frame);
}
private:
std::vector<cel::FunctionRegistry::LazyOverload> providers_;
std::string name_;
bool receiver_style_;
};
template <typename Resolver>
class DirectFunctionStepImpl : public DirectExpressionStep {
public:
DirectFunctionStepImpl(
int64_t expr_id, const std::string& name,
std::vector<std::unique_ptr<DirectExpressionStep>> arg_steps,
Resolver&& resolver)
: DirectExpressionStep(expr_id),
name_(name),
arg_steps_(std::move(arg_steps)),
resolver_(std::forward<Resolver>(resolver)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& trail) const override {
absl::InlinedVector<Value, 2> args;
absl::InlinedVector<AttributeTrail, 2> arg_trails;
args.resize(arg_steps_.size());
arg_trails.resize(arg_steps_.size());
for (size_t i = 0; i < arg_steps_.size(); i++) {
CEL_RETURN_IF_ERROR(
arg_steps_[i]->Evaluate(frame, args[i], arg_trails[i]));
}
if (frame.unknown_processing_enabled()) {
for (size_t i = 0; i < arg_trails.size(); i++) {
if (frame.attribute_utility().CheckForUnknown(arg_trails[i],
true)) {
args[i] = frame.attribute_utility().CreateUnknownSet(
arg_trails[i].attribute());
}
}
}
CEL_ASSIGN_OR_RETURN(ResolveResult resolved_function,
resolver_.Resolve(frame, args));
if (resolved_function.has_value() &&
ShouldAcceptOverload(resolved_function->descriptor, args)) {
CEL_ASSIGN_OR_RETURN(result,
Invoke(*resolved_function, expr_id_, args, frame));
return absl::OkStatus();
}
result = NoOverloadResult(name_, args, frame);
return absl::OkStatus();
}
absl::optional<std::vector<const DirectExpressionStep*>> GetDependencies()
const override {
std::vector<const DirectExpressionStep*> dependencies;
dependencies.reserve(arg_steps_.size());
for (const auto& arg_step : arg_steps_) {
dependencies.push_back(arg_step.get());
}
return dependencies;
}
absl::optional<std::vector<std::unique_ptr<DirectExpressionStep>>>
ExtractDependencies() override {
return std::move(arg_steps_);
}
private:
friend Resolver;
std::string name_;
std::vector<std::unique_ptr<DirectExpressionStep>> arg_steps_;
Resolver resolver_;
};
}
std::unique_ptr<DirectExpressionStep> CreateDirectFunctionStep(
int64_t expr_id, const cel::ast_internal::Call& call,
std::vector<std::unique_ptr<DirectExpressionStep>> deps,
std::vector<cel::FunctionOverloadReference> overloads) {
return std::make_unique<DirectFunctionStepImpl<StaticResolver>>(
expr_id, call.function(), std::move(deps),
StaticResolver(std::move(overloads)));
}
std::unique_ptr<DirectExpressionStep> CreateDirectLazyFunctionStep(
int64_t expr_id, const cel::ast_internal::Call& call,
std::vector<std::unique_ptr<DirectExpressionStep>> deps,
std::vector<cel::FunctionRegistry::LazyOverload> providers) {
return std::make_unique<DirectFunctionStepImpl<LazyResolver>>(
expr_id, call.function(), std::move(deps),
LazyResolver(std::move(providers), call.function(), call.has_target()));
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateFunctionStep(
const cel::ast_internal::Call& call_expr, int64_t expr_id,
std::vector<cel::FunctionRegistry::LazyOverload> lazy_overloads) {
bool receiver_style = call_expr.has_target();
size_t num_args = call_expr.args().size() + (receiver_style ? 1 : 0);
const std::string& name = call_expr.function();
return std::make_unique<LazyFunctionStep>(name, num_args, receiver_style,
std::move(lazy_overloads), expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateFunctionStep(
const cel::ast_internal::Call& call_expr, int64_t expr_id,
std::vector<cel::FunctionOverloadReference> overloads) {
bool receiver_style = call_expr.has_target();
size_t num_args = call_expr.args().size() + (receiver_style ? 1 : 0);
const std::string& name = call_expr.function();
return std::make_unique<EagerFunctionStep>(std::move(overloads), name,
num_args, expr_id);
}
} | #include "eval/eval/function_step.h"
#include <cmath>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "base/ast_internal/expr.h"
#include "base/builtins.h"
#include "base/type_provider.h"
#include "common/kind.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/internal/interop.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_function.h"
#include "eval/public/cel_function_registry.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "eval/public/portable_cel_function_adapter.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/testing/matchers.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
#include "runtime/function_overload_reference.h"
#include "runtime/function_registry.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "runtime/standard_functions.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::IsOk;
using ::absl_testing::StatusIs;
using ::cel::TypeProvider;
using ::cel::ast_internal::Call;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::Ident;
using ::testing::Eq;
using ::testing::Not;
using ::testing::Truly;
int GetExprId() {
static int id = 0;
id++;
return id;
}
class ConstFunction : public CelFunction {
public:
explicit ConstFunction(const CelValue& value, absl::string_view name)
: CelFunction(CreateDescriptor(name)), value_(value) {}
static CelFunctionDescriptor CreateDescriptor(absl::string_view name) {
return CelFunctionDescriptor{name, false, {}};
}
static Call MakeCall(absl::string_view name) {
Call call;
call.set_function(std::string(name));
call.set_target(nullptr);
return call;
}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (!args.empty()) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Bad arguments number");
}
*result = value_;
return absl::OkStatus();
}
private:
CelValue value_;
};
enum class ShouldReturnUnknown : bool { kYes = true, kNo = false };
class AddFunction : public CelFunction {
public:
AddFunction()
: CelFunction(CreateDescriptor()), should_return_unknown_(false) {}
explicit AddFunction(ShouldReturnUnknown should_return_unknown)
: CelFunction(CreateDescriptor()),
should_return_unknown_(static_cast<bool>(should_return_unknown)) {}
static CelFunctionDescriptor CreateDescriptor() {
return CelFunctionDescriptor{
"_+_", false, {CelValue::Type::kInt64, CelValue::Type::kInt64}};
}
static Call MakeCall() {
Call call;
call.set_function("_+_");
call.mutable_args().emplace_back();
call.mutable_args().emplace_back();
call.set_target(nullptr);
return call;
}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (args.size() != 2 || !args[0].IsInt64() || !args[1].IsInt64()) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Mismatched arguments passed to method");
}
if (should_return_unknown_) {
*result =
CreateUnknownFunctionResultError(arena, "Add can't be resolved.");
return absl::OkStatus();
}
int64_t arg0 = args[0].Int64OrDie();
int64_t arg1 = args[1].Int64OrDie();
*result = CelValue::CreateInt64(arg0 + arg1);
return absl::OkStatus();
}
private:
bool should_return_unknown_;
};
class SinkFunction : public CelFunction {
public:
explicit SinkFunction(CelValue::Type type, bool is_strict = true)
: CelFunction(CreateDescriptor(type, is_strict)) {}
static CelFunctionDescriptor CreateDescriptor(CelValue::Type type,
bool is_strict = true) {
return CelFunctionDescriptor{"Sink", false, {type}, is_strict};
}
static Call MakeCall() {
Call call;
call.set_function("Sink");
call.mutable_args().emplace_back();
call.set_target(nullptr);
return call;
}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
*result = CelValue::CreateInt64(0);
return absl::OkStatus();
}
};
void AddDefaults(CelFunctionRegistry& registry) {
static UnknownSet* unknown_set = new UnknownSet();
EXPECT_TRUE(registry
.Register(std::make_unique<ConstFunction>(
CelValue::CreateInt64(3), "Const3"))
.ok());
EXPECT_TRUE(registry
.Register(std::make_unique<ConstFunction>(
CelValue::CreateInt64(2), "Const2"))
.ok());
EXPECT_TRUE(registry
.Register(std::make_unique<ConstFunction>(
CelValue::CreateUnknownSet(unknown_set), "ConstUnknown"))
.ok());
EXPECT_TRUE(registry.Register(std::make_unique<AddFunction>()).ok());
EXPECT_TRUE(
registry.Register(std::make_unique<SinkFunction>(CelValue::Type::kList))
.ok());
EXPECT_TRUE(
registry.Register(std::make_unique<SinkFunction>(CelValue::Type::kMap))
.ok());
EXPECT_TRUE(
registry
.Register(std::make_unique<SinkFunction>(CelValue::Type::kMessage))
.ok());
}
std::vector<CelValue::Type> ArgumentMatcher(int argument_count) {
std::vector<CelValue::Type> argument_matcher(argument_count);
for (int i = 0; i < argument_count; i++) {
argument_matcher[i] = CelValue::Type::kAny;
}
return argument_matcher;
}
std::vector<CelValue::Type> ArgumentMatcher(const Call& call) {
return ArgumentMatcher(call.has_target() ? call.args().size() + 1
: call.args().size());
}
std::unique_ptr<CelExpressionFlatImpl> CreateExpressionImpl(
const cel::RuntimeOptions& options,
std::unique_ptr<DirectExpressionStep> expr) {
ExecutionPath path;
path.push_back(std::make_unique<WrappedDirectStep>(std::move(expr), -1));
return std::make_unique<CelExpressionFlatImpl>(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> MakeTestFunctionStep(
const Call& call, const CelFunctionRegistry& registry) {
auto argument_matcher = ArgumentMatcher(call);
auto lazy_overloads = registry.ModernFindLazyOverloads(
call.function(), call.has_target(), argument_matcher);
if (!lazy_overloads.empty()) {
return CreateFunctionStep(call, GetExprId(), lazy_overloads);
}
auto overloads = registry.FindStaticOverloads(
call.function(), call.has_target(), argument_matcher);
return CreateFunctionStep(call, GetExprId(), overloads);
}
class FunctionStepTest
: public testing::TestWithParam<UnknownProcessingOptions> {
public:
std::unique_ptr<CelExpressionFlatImpl> GetExpression(ExecutionPath&& path) {
cel::RuntimeOptions options;
options.unknown_processing = GetParam();
return std::make_unique<CelExpressionFlatImpl>(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
}
};
TEST_P(FunctionStepTest, SimpleFunctionTest) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
Call call1 = ConstFunction::MakeCall("Const3");
Call call2 = ConstFunction::MakeCall("Const2");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsInt64());
EXPECT_THAT(value.Int64OrDie(), Eq(5));
}
TEST_P(FunctionStepTest, TestStackUnderflow) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
AddFunction add_func;
Call call1 = ConstFunction::MakeCall("Const3");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
EXPECT_THAT(impl->Evaluate(activation, &arena), Not(IsOk()));
}
TEST_P(FunctionStepTest, TestNoMatchingOverloadsDuringEvaluation) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
ASSERT_TRUE(registry
.Register(std::make_unique<ConstFunction>(
CelValue::CreateUint64(4), "Const4"))
.ok());
Call call1 = ConstFunction::MakeCall("Const3");
Call call2 = ConstFunction::MakeCall("Const4");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsError());
EXPECT_THAT(*value.ErrorOrDie(),
StatusIs(absl::StatusCode::kUnknown,
testing::HasSubstr("_+_(int64, uint64)")));
}
TEST_P(FunctionStepTest, TestNoMatchingOverloadsUnexpectedArgCount) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
Call call1 = ConstFunction::MakeCall("Const3");
Call add_call = AddFunction::MakeCall();
add_call.mutable_args().emplace_back();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(
auto step3,
CreateFunctionStep(add_call, -1,
registry.FindStaticOverloads(
add_call.function(), false,
{cel::Kind::kInt64, cel::Kind::kInt64})));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
path.push_back(std::move(step3));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsError());
EXPECT_THAT(*value.ErrorOrDie(),
StatusIs(absl::StatusCode::kUnknown,
testing::HasSubstr("_+_(int64, int64, int64)")));
}
TEST_P(FunctionStepTest,
TestNoMatchingOverloadsDuringEvaluationErrorForwarding) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
CelError error0 = absl::CancelledError();
CelError error1 = absl::CancelledError();
ASSERT_TRUE(registry
.Register(std::make_unique<ConstFunction>(
CelValue::CreateError(&error0), "ConstError1"))
.ok());
ASSERT_TRUE(registry
.Register(std::make_unique<ConstFunction>(
CelValue::CreateError(&error1), "ConstError2"))
.ok());
Call call1 = ConstFunction::MakeCall("ConstError1");
Call call2 = ConstFunction::MakeCall("ConstError2");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsError());
EXPECT_THAT(*value.ErrorOrDie(), Eq(error0));
}
TEST_P(FunctionStepTest, LazyFunctionTest) {
ExecutionPath path;
Activation activation;
CelFunctionRegistry registry;
ASSERT_OK(
registry.RegisterLazyFunction(ConstFunction::CreateDescriptor("Const3")));
ASSERT_OK(activation.InsertFunction(
std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3")));
ASSERT_OK(
registry.RegisterLazyFunction(ConstFunction::CreateDescriptor("Const2")));
ASSERT_OK(activation.InsertFunction(
std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2")));
ASSERT_OK(registry.Register(std::make_unique<AddFunction>()));
Call call1 = ConstFunction::MakeCall("Const3");
Call call2 = ConstFunction::MakeCall("Const2");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsInt64());
EXPECT_THAT(value.Int64OrDie(), Eq(5));
}
TEST_P(FunctionStepTest, LazyFunctionOverloadingTest) {
ExecutionPath path;
Activation activation;
CelFunctionRegistry registry;
auto floor_int = PortableUnaryFunctionAdapter<int64_t, int64_t>::Create(
"Floor", false, [](google::protobuf::Arena*, int64_t val) { return val; });
auto floor_double = PortableUnaryFunctionAdapter<int64_t, double>::Create(
"Floor", false,
[](google::protobuf::Arena*, double val) { return std::floor(val); });
ASSERT_OK(registry.RegisterLazyFunction(floor_int->descriptor()));
ASSERT_OK(activation.InsertFunction(std::move(floor_int)));
ASSERT_OK(registry.RegisterLazyFunction(floor_double->descriptor()));
ASSERT_OK(activation.InsertFunction(std::move(floor_double)));
ASSERT_OK(registry.Register(
PortableBinaryFunctionAdapter<bool, int64_t, int64_t>::Create(
"_<_", false, [](google::protobuf::Arena*, int64_t lhs, int64_t rhs) -> bool {
return lhs < rhs;
})));
cel::ast_internal::Constant lhs;
lhs.set_int64_value(20);
cel::ast_internal::Constant rhs;
rhs.set_double_value(21.9);
cel::ast_internal::Call call1;
call1.mutable_args().emplace_back();
call1.set_function("Floor");
cel::ast_internal::Call call2;
call2.mutable_args().emplace_back();
call2.set_function("Floor");
cel::ast_internal::Call lt_call;
lt_call.mutable_args().emplace_back();
lt_call.mutable_args().emplace_back();
lt_call.set_function("_<_");
ASSERT_OK_AND_ASSIGN(
auto step0,
CreateConstValueStep(cel::interop_internal::CreateIntValue(20), -1));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(
auto step2,
CreateConstValueStep(cel::interop_internal::CreateDoubleValue(21.9), -1));
ASSERT_OK_AND_ASSIGN(auto step3, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step4, MakeTestFunctionStep(lt_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
path.push_back(std::move(step3));
path.push_back(std::move(step4));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsBool());
EXPECT_TRUE(value.BoolOrDie());
}
TEST_P(FunctionStepTest,
TestNoMatchingOverloadsDuringEvaluationErrorForwardingLazy) {
ExecutionPath path;
Activation activation;
google::protobuf::Arena arena;
CelFunctionRegistry registry;
AddDefaults(registry);
CelError error0 = absl::CancelledError();
CelError error1 = absl::CancelledError();
ASSERT_OK(registry.RegisterLazyFunction(
ConstFunction::CreateDescriptor("ConstError1")));
ASSERT_OK(activation.InsertFunction(std::make_unique<ConstFunction>(
CelValue::CreateError(&error0), "ConstError1")));
ASSERT_OK(registry.RegisterLazyFunction(
ConstFunction::CreateDescriptor("ConstError2")));
ASSERT_OK(activation.InsertFunction(std::make_unique<ConstFunction>(
CelValue::CreateError(&error1), "ConstError2")));
Call call1 = ConstFunction::MakeCall("ConstError1");
Call call2 = ConstFunction::MakeCall("ConstError2");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsError());
EXPECT_THAT(*value.ErrorOrDie(), Eq(error0));
}
std::string TestNameFn(testing::TestParamInfo<UnknownProcessingOptions> opt) {
switch (opt.param) {
case UnknownProcessingOptions::kDisabled:
return "disabled";
case UnknownProcessingOptions::kAttributeOnly:
return "attribute_only";
case UnknownProcessingOptions::kAttributeAndFunction:
return "attribute_and_function";
}
return "";
}
INSTANTIATE_TEST_SUITE_P(
UnknownSupport, FunctionStepTest,
testing::Values(UnknownProcessingOptions::kDisabled,
UnknownProcessingOptions::kAttributeOnly,
UnknownProcessingOptions::kAttributeAndFunction),
&TestNameFn);
class FunctionStepTestUnknowns
: public testing::TestWithParam<UnknownProcessingOptions> {
public:
std::unique_ptr<CelExpressionFlatImpl> GetExpression(ExecutionPath&& path) {
cel::RuntimeOptions options;
options.unknown_processing = GetParam();
return std::make_unique<CelExpressionFlatImpl>(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
}
};
TEST_P(FunctionStepTestUnknowns, PassedUnknownTest) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
Call call1 = ConstFunction::MakeCall("Const3");
Call call2 = ConstFunction::MakeCall("ConstUnknown");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsUnknownSet());
}
TEST_P(FunctionStepTestUnknowns, PartialUnknownHandlingTest) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
Ident ident1;
ident1.set_name("param");
Call call1 = SinkFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident1, GetExprId()));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call1, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
TestMessage msg;
google::protobuf::Arena arena;
activation.InsertValue("param", CelProtoWrapper::CreateMessage(&msg, &arena));
CelAttributePattern pattern(
"param",
{CreateCelAttributeQualifierPattern(CelValue::CreateBool(true))});
activation.set_unknown_attribute_patterns({pattern});
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsUnknownSet());
}
TEST_P(FunctionStepTestUnknowns, UnknownVsErrorPrecedenceTest) {
ExecutionPath path;
CelFunctionRegistry registry;
AddDefaults(registry);
CelError error0 = absl::CancelledError();
CelValue error_value = CelValue::CreateError(&error0);
ASSERT_TRUE(
registry
.Register(std::make_unique<ConstFunction>(error_value, "ConstError"))
.ok());
Call call1 = ConstFunction::MakeCall("ConstError");
Call call2 = ConstFunction::MakeCall("ConstUnknown");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena));
ASSERT_TRUE(value.IsError());
ASSERT_EQ(*value.ErrorOrDie(), *error_value.ErrorOrDie());
}
INSTANTIATE_TEST_SUITE_P(
UnknownFunctionSupport, FunctionStepTestUnknowns,
testing::Values(UnknownProcessingOptions::kAttributeOnly,
UnknownProcessingOptions::kAttributeAndFunction),
&TestNameFn);
TEST(FunctionStepTestUnknownFunctionResults, CaptureArgs) {
ExecutionPath path;
CelFunctionRegistry registry;
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2")));
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3")));
ASSERT_OK(registry.Register(
std::make_unique<AddFunction>(ShouldReturnUnknown::kYes)));
Call call1 = ConstFunction::MakeCall("Const2");
Call call2 = ConstFunction::MakeCall("Const3");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
cel::RuntimeOptions options;
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena));
ASSERT_TRUE(value.IsUnknownSet());
}
TEST(FunctionStepTestUnknownFunctionResults, MergeDownCaptureArgs) {
ExecutionPath path;
CelFunctionRegistry registry;
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2")));
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3")));
ASSERT_OK(registry.Register(
std::make_unique<AddFunction>(ShouldReturnUnknown::kYes)));
Call call1 = ConstFunction::MakeCall("Const2");
Call call2 = ConstFunction::MakeCall("Const3");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
ASSERT_OK_AND_ASSIGN(auto step3, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step4, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step5, MakeTestFunctionStep(add_call, registry));
ASSERT_OK_AND_ASSIGN(auto step6, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
path.push_back(std::move(step3));
path.push_back(std::move(step4));
path.push_back(std::move(step5));
path.push_back(std::move(step6));
cel::RuntimeOptions options;
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena));
ASSERT_TRUE(value.IsUnknownSet());
}
TEST(FunctionStepTestUnknownFunctionResults, MergeCaptureArgs) {
ExecutionPath path;
CelFunctionRegistry registry;
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2")));
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3")));
ASSERT_OK(registry.Register(
std::make_unique<AddFunction>(ShouldReturnUnknown::kYes)));
Call call1 = ConstFunction::MakeCall("Const2");
Call call2 = ConstFunction::MakeCall("Const3");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
ASSERT_OK_AND_ASSIGN(auto step3, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step4, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step5, MakeTestFunctionStep(add_call, registry));
ASSERT_OK_AND_ASSIGN(auto step6, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
path.push_back(std::move(step3));
path.push_back(std::move(step4));
path.push_back(std::move(step5));
path.push_back(std::move(step6));
cel::RuntimeOptions options;
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena));
ASSERT_TRUE(value.IsUnknownSet()) << *(value.ErrorOrDie());
}
TEST(FunctionStepTestUnknownFunctionResults, UnknownVsErrorPrecedenceTest) {
ExecutionPath path;
CelFunctionRegistry registry;
CelError error0 = absl::CancelledError();
CelValue error_value = CelValue::CreateError(&error0);
UnknownSet unknown_set;
CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set);
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(error_value, "ConstError")));
ASSERT_OK(registry.Register(
std::make_unique<ConstFunction>(unknown_value, "ConstUnknown")));
ASSERT_OK(registry.Register(
std::make_unique<AddFunction>(ShouldReturnUnknown::kYes)));
Call call1 = ConstFunction::MakeCall("ConstError");
Call call2 = ConstFunction::MakeCall("ConstUnknown");
Call add_call = AddFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry));
ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry));
ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
cel::RuntimeOptions options;
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena));
ASSERT_TRUE(value.IsError());
ASSERT_EQ(*value.ErrorOrDie(), *error_value.ErrorOrDie());
}
class MessageFunction : public CelFunction {
public:
MessageFunction()
: CelFunction(
CelFunctionDescriptor("Fn", false, {CelValue::Type::kMessage})) {}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (args.size() != 1 || !args.at(0).IsMessage()) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Bad arguments number");
}
*result = CelValue::CreateStringView("message");
return absl::OkStatus();
}
};
class MessageIdentityFunction : public CelFunction {
public:
MessageIdentityFunction()
: CelFunction(
CelFunctionDescriptor("Fn", false, {CelValue::Type::kMessage})) {}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (args.size() != 1 || !args.at(0).IsMessage()) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Bad arguments number");
}
*result = args.at(0);
return absl::OkStatus();
}
};
class NullFunction : public CelFunction {
public:
NullFunction()
: CelFunction(
CelFunctionDescriptor("Fn", false, {CelValue::Type::kNullType})) {}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (args.size() != 1 || args.at(0).type() != CelValue::Type::kNullType) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Bad arguments number");
}
*result = CelValue::CreateStringView("null");
return absl::OkStatus();
}
};
TEST(FunctionStepStrictnessTest,
IfFunctionStrictAndGivenUnknownSkipsInvocation) {
UnknownSet unknown_set;
CelFunctionRegistry registry;
ASSERT_OK(registry.Register(std::make_unique<ConstFunction>(
CelValue::CreateUnknownSet(&unknown_set), "ConstUnknown")));
ASSERT_OK(registry.Register(std::make_unique<SinkFunction>(
CelValue::Type::kUnknownSet, true)));
ExecutionPath path;
Call call0 = ConstFunction::MakeCall("ConstUnknown");
Call call1 = SinkFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(std::unique_ptr<ExpressionStep> step0,
MakeTestFunctionStep(call0, registry));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<ExpressionStep> step1,
MakeTestFunctionStep(call1, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
cel::RuntimeOptions options;
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena));
ASSERT_TRUE(value.IsUnknownSet());
}
TEST(FunctionStepStrictnessTest, IfFunctionNonStrictAndGivenUnknownInvokesIt) {
UnknownSet unknown_set;
CelFunctionRegistry registry;
ASSERT_OK(registry.Register(std::make_unique<ConstFunction>(
CelValue::CreateUnknownSet(&unknown_set), "ConstUnknown")));
ASSERT_OK(registry.Register(std::make_unique<SinkFunction>(
CelValue::Type::kUnknownSet, false)));
ExecutionPath path;
Call call0 = ConstFunction::MakeCall("ConstUnknown");
Call call1 = SinkFunction::MakeCall();
ASSERT_OK_AND_ASSIGN(std::unique_ptr<ExpressionStep> step0,
MakeTestFunctionStep(call0, registry));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<ExpressionStep> step1,
MakeTestFunctionStep(call1, registry));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
Expr placeholder_expr;
cel::RuntimeOptions options;
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena));
ASSERT_THAT(value, test::IsCelInt64(Eq(0)));
}
class DirectFunctionStepTest : public testing::Test {
public:
DirectFunctionStepTest()
: value_factory_(TypeProvider::Builtin(),
cel::extensions::ProtoMemoryManagerRef(&arena_)) {}
void SetUp() override {
ASSERT_OK(cel::RegisterStandardFunctions(registry_, options_));
}
std::vector<cel::FunctionOverloadReference> GetOverloads(
absl::string_view name, int64_t arguments_size) {
std::vector<cel::Kind> matcher;
matcher.resize(arguments_size, cel::Kind::kAny);
return registry_.FindStaticOverloads(name, false, matcher);
}
std::vector<std::unique_ptr<DirectExpressionStep>> MakeDeps(
std::unique_ptr<DirectExpressionStep> dep,
std::unique_ptr<DirectExpressionStep> dep2) {
std::vector<std::unique_ptr<DirectExpressionStep>> result;
result.reserve(2);
result.push_back(std::move(dep));
result.push_back(std::move(dep2));
return result;
};
protected:
cel::FunctionRegistry registry_;
cel::RuntimeOptions options_;
google::protobuf::Arena arena_;
cel::ManagedValueFactory value_factory_;
};
TEST_F(DirectFunctionStepTest, SimpleCall) {
value_factory_.get().CreateIntValue(1);
cel::ast_internal::Call call;
call.set_function(cel::builtin::kAdd);
call.mutable_args().emplace_back();
call.mutable_args().emplace_back();
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1)));
deps.push_back(
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1)));
auto expr = CreateDirectFunctionStep(-1, call, std::move(deps),
GetOverloads(cel::builtin::kAdd, 2));
auto plan = CreateExpressionImpl(options_, std::move(expr));
Activation activation;
ASSERT_OK_AND_ASSIGN(auto value, plan->Evaluate(activation, &arena_));
EXPECT_THAT(value, test::IsCelInt64(2));
}
TEST_F(DirectFunctionStepTest, RecursiveCall) {
value_factory_.get().CreateIntValue(1);
cel::ast_internal::Call call;
call.set_function(cel::builtin::kAdd);
call.mutable_args().emplace_back();
call.mutable_args().emplace_back();
auto overloads = GetOverloads(cel::builtin::kAdd, 2);
auto MakeLeaf = [&]() {
return CreateDirectFunctionStep(
-1, call,
MakeDeps(
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1)),
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1))),
overloads);
};
auto expr = CreateDirectFunctionStep(
-1, call,
MakeDeps(CreateDirectFunctionStep(
-1, call, MakeDeps(MakeLeaf(), MakeLeaf()), overloads),
CreateDirectFunctionStep(
-1, call, MakeDeps(MakeLeaf(), MakeLeaf()), overloads)),
overloads);
auto plan = CreateExpressionImpl(options_, std::move(expr));
Activation activation;
ASSERT_OK_AND_ASSIGN(auto value, plan->Evaluate(activation, &arena_));
EXPECT_THAT(value, test::IsCelInt64(8));
}
TEST_F(DirectFunctionStepTest, ErrorHandlingCall) {
value_factory_.get().CreateIntValue(1);
cel::ast_internal::Call add_call;
add_call.set_function(cel::builtin::kAdd);
add_call.mutable_args().emplace_back();
add_call.mutable_args().emplace_back();
cel::ast_internal::Call div_call;
div_call.set_function(cel::builtin::kDivide);
div_call.mutable_args().emplace_back();
div_call.mutable_args().emplace_back();
auto add_overloads = GetOverloads(cel::builtin::kAdd, 2);
auto div_overloads = GetOverloads(cel::builtin::kDivide, 2);
auto error_expr = CreateDirectFunctionStep(
-1, div_call,
MakeDeps(
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1)),
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(0))),
div_overloads);
auto expr = CreateDirectFunctionStep(
-1, add_call,
MakeDeps(
std::move(error_expr),
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1))),
add_overloads);
auto plan = CreateExpressionImpl(options_, std::move(expr));
Activation activation;
ASSERT_OK_AND_ASSIGN(auto value, plan->Evaluate(activation, &arena_));
EXPECT_THAT(value,
test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument,
testing::HasSubstr("divide by zero"))));
}
TEST_F(DirectFunctionStepTest, NoOverload) {
value_factory_.get().CreateIntValue(1);
cel::ast_internal::Call call;
call.set_function(cel::builtin::kAdd);
call.mutable_args().emplace_back();
call.mutable_args().emplace_back();
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(
CreateConstValueDirectStep(value_factory_.get().CreateIntValue(1)));
deps.push_back(CreateConstValueDirectStep(
value_factory_.get().CreateUncheckedStringValue("2")));
auto expr = CreateDirectFunctionStep(-1, call, std::move(deps),
GetOverloads(cel::builtin::kAdd, 2));
auto plan = CreateExpressionImpl(options_, std::move(expr));
Activation activation;
ASSERT_OK_AND_ASSIGN(auto value, plan->Evaluate(activation, &arena_));
EXPECT_THAT(value, Truly(CheckNoMatchingOverloadError));
}
TEST_F(DirectFunctionStepTest, NoOverload0Args) {
value_factory_.get().CreateIntValue(1);
cel::ast_internal::Call call;
call.set_function(cel::builtin::kAdd);
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
auto expr = CreateDirectFunctionStep(-1, call, std::move(deps),
GetOverloads(cel::builtin::kAdd, 2));
auto plan = CreateExpressionImpl(options_, std::move(expr));
Activation activation;
ASSERT_OK_AND_ASSIGN(auto value, plan->Evaluate(activation, &arena_));
EXPECT_THAT(value, Truly(CheckNoMatchingOverloadError));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/function_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/function_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
4de906d9-9497-4934-a017-1a1942bc3514 | cpp | google/cel-cpp | select_step | eval/eval/select_step.cc | eval/eval/select_step_test.cc | #include "eval/eval/select_step.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/log/absl_log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "base/kind.h"
#include "common/casting.h"
#include "common/native_type.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "internal/casts.h"
#include "internal/status_macros.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::MapValue;
using ::cel::NullValue;
using ::cel::OptionalValue;
using ::cel::ProtoWrapperTypeOptions;
using ::cel::StringValue;
using ::cel::StructValue;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ValueKind;
absl::Status InvalidSelectTargetError() {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Applying SELECT to non-message type");
}
absl::optional<Value> CheckForMarkedAttributes(const AttributeTrail& trail,
ExecutionFrameBase& frame) {
if (frame.unknown_processing_enabled() &&
frame.attribute_utility().CheckForUnknownExact(trail)) {
return frame.attribute_utility().CreateUnknownSet(trail.attribute());
}
if (frame.missing_attribute_errors_enabled() &&
frame.attribute_utility().CheckForMissingAttribute(trail)) {
auto result = frame.attribute_utility().CreateMissingAttributeError(
trail.attribute());
if (result.ok()) {
return std::move(result).value();
}
ABSL_LOG(ERROR) << "Invalid attribute pattern matched select path: "
<< result.status().ToString();
return frame.value_manager().CreateErrorValue(std::move(result).status());
}
return absl::nullopt;
}
void TestOnlySelect(const StructValue& msg, const std::string& field,
cel::ValueManager& value_factory, Value& result) {
absl::StatusOr<bool> has_field = msg.HasFieldByName(field);
if (!has_field.ok()) {
result = value_factory.CreateErrorValue(std::move(has_field).status());
return;
}
result = BoolValue{*has_field};
}
void TestOnlySelect(const MapValue& map, const StringValue& field_name,
cel::ValueManager& value_factory, Value& result) {
absl::Status presence = map.Has(value_factory, field_name, result);
if (!presence.ok()) {
result = value_factory.CreateErrorValue(std::move(presence));
return;
}
}
class SelectStep : public ExpressionStepBase {
public:
SelectStep(StringValue value, bool test_field_presence, int64_t expr_id,
bool enable_wrapper_type_null_unboxing, bool enable_optional_types)
: ExpressionStepBase(expr_id),
field_value_(std::move(value)),
field_(field_value_.ToString()),
test_field_presence_(test_field_presence),
unboxing_option_(enable_wrapper_type_null_unboxing
? ProtoWrapperTypeOptions::kUnsetNull
: ProtoWrapperTypeOptions::kUnsetProtoDefault),
enable_optional_types_(enable_optional_types) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
absl::Status PerformTestOnlySelect(ExecutionFrame* frame,
const Value& arg) const;
absl::StatusOr<bool> PerformSelect(ExecutionFrame* frame, const Value& arg,
Value& result) const;
cel::StringValue field_value_;
std::string field_;
bool test_field_presence_;
ProtoWrapperTypeOptions unboxing_option_;
bool enable_optional_types_;
};
absl::Status SelectStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(1)) {
return absl::Status(absl::StatusCode::kInternal,
"No arguments supplied for Select-type expression");
}
const Value& arg = frame->value_stack().Peek();
const AttributeTrail& trail = frame->value_stack().PeekAttribute();
if (InstanceOf<UnknownValue>(arg) || InstanceOf<ErrorValue>(arg)) {
return absl::OkStatus();
}
AttributeTrail result_trail;
if (frame->enable_unknowns() || frame->enable_missing_attribute_errors()) {
result_trail = trail.Step(&field_);
}
if (arg->Is<NullValue>()) {
frame->value_stack().PopAndPush(
frame->value_factory().CreateErrorValue(
cel::runtime_internal::CreateError("Message is NULL")),
std::move(result_trail));
return absl::OkStatus();
}
const cel::OptionalValueInterface* optional_arg = nullptr;
if (enable_optional_types_ &&
cel::NativeTypeId::Of(arg) ==
cel::NativeTypeId::For<cel::OptionalValueInterface>()) {
optional_arg = cel::internal::down_cast<const cel::OptionalValueInterface*>(
cel::Cast<cel::OpaqueValue>(arg).operator->());
}
if (!(optional_arg != nullptr || arg->Is<MapValue>() ||
arg->Is<StructValue>())) {
frame->value_stack().PopAndPush(
frame->value_factory().CreateErrorValue(InvalidSelectTargetError()),
std::move(result_trail));
return absl::OkStatus();
}
absl::optional<Value> marked_attribute_check =
CheckForMarkedAttributes(result_trail, *frame);
if (marked_attribute_check.has_value()) {
frame->value_stack().PopAndPush(std::move(marked_attribute_check).value(),
std::move(result_trail));
return absl::OkStatus();
}
if (test_field_presence_) {
if (optional_arg != nullptr) {
if (!optional_arg->HasValue()) {
frame->value_stack().PopAndPush(cel::BoolValue{false});
return absl::OkStatus();
}
return PerformTestOnlySelect(frame, optional_arg->Value());
}
return PerformTestOnlySelect(frame, arg);
}
if (optional_arg != nullptr) {
if (!optional_arg->HasValue()) {
return absl::OkStatus();
}
Value result;
bool ok;
CEL_ASSIGN_OR_RETURN(ok,
PerformSelect(frame, optional_arg->Value(), result));
if (!ok) {
frame->value_stack().PopAndPush(cel::OptionalValue::None(),
std::move(result_trail));
return absl::OkStatus();
}
frame->value_stack().PopAndPush(
cel::OptionalValue::Of(frame->memory_manager(), std::move(result)),
std::move(result_trail));
return absl::OkStatus();
}
switch (arg->kind()) {
case ValueKind::kStruct: {
Value result;
CEL_RETURN_IF_ERROR(arg.GetStruct().GetFieldByName(
frame->value_factory(), field_, result, unboxing_option_));
frame->value_stack().PopAndPush(std::move(result),
std::move(result_trail));
return absl::OkStatus();
}
case ValueKind::kMap: {
Value result;
CEL_RETURN_IF_ERROR(
arg.GetMap().Get(frame->value_factory(), field_value_, result));
frame->value_stack().PopAndPush(std::move(result),
std::move(result_trail));
return absl::OkStatus();
}
default:
return InvalidSelectTargetError();
}
}
absl::Status SelectStep::PerformTestOnlySelect(ExecutionFrame* frame,
const Value& arg) const {
switch (arg->kind()) {
case ValueKind::kMap: {
Value result;
TestOnlySelect(arg.GetMap(), field_value_, frame->value_factory(),
result);
frame->value_stack().PopAndPush(std::move(result));
return absl::OkStatus();
}
case ValueKind::kMessage: {
Value result;
TestOnlySelect(arg.GetStruct(), field_, frame->value_factory(), result);
frame->value_stack().PopAndPush(std::move(result));
return absl::OkStatus();
}
default:
return InvalidSelectTargetError();
}
}
absl::StatusOr<bool> SelectStep::PerformSelect(ExecutionFrame* frame,
const Value& arg,
Value& result) const {
switch (arg->kind()) {
case ValueKind::kStruct: {
const auto& struct_value = arg.GetStruct();
CEL_ASSIGN_OR_RETURN(auto ok, struct_value.HasFieldByName(field_));
if (!ok) {
result = NullValue{};
return false;
}
CEL_RETURN_IF_ERROR(struct_value.GetFieldByName(
frame->value_factory(), field_, result, unboxing_option_));
return true;
}
case ValueKind::kMap: {
return arg.GetMap().Find(frame->value_factory(), field_value_, result);
}
default:
return InvalidSelectTargetError();
}
}
class DirectSelectStep : public DirectExpressionStep {
public:
DirectSelectStep(int64_t expr_id,
std::unique_ptr<DirectExpressionStep> operand,
StringValue field, bool test_only,
bool enable_wrapper_type_null_unboxing,
bool enable_optional_types)
: DirectExpressionStep(expr_id),
operand_(std::move(operand)),
field_value_(std::move(field)),
field_(field_value_.ToString()),
test_only_(test_only),
unboxing_option_(enable_wrapper_type_null_unboxing
? ProtoWrapperTypeOptions::kUnsetNull
: ProtoWrapperTypeOptions::kUnsetProtoDefault),
enable_optional_types_(enable_optional_types) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override {
CEL_RETURN_IF_ERROR(operand_->Evaluate(frame, result, attribute));
if (InstanceOf<ErrorValue>(result) || InstanceOf<UnknownValue>(result)) {
return absl::OkStatus();
}
if (frame.attribute_tracking_enabled()) {
attribute = attribute.Step(&field_);
absl::optional<Value> value = CheckForMarkedAttributes(attribute, frame);
if (value.has_value()) {
result = std::move(value).value();
return absl::OkStatus();
}
}
const cel::OptionalValueInterface* optional_arg = nullptr;
if (enable_optional_types_ &&
cel::NativeTypeId::Of(result) ==
cel::NativeTypeId::For<cel::OptionalValueInterface>()) {
optional_arg =
cel::internal::down_cast<const cel::OptionalValueInterface*>(
cel::Cast<cel::OpaqueValue>(result).operator->());
}
switch (result.kind()) {
case ValueKind::kStruct:
case ValueKind::kMap:
break;
case ValueKind::kNull:
result = frame.value_manager().CreateErrorValue(
cel::runtime_internal::CreateError("Message is NULL"));
return absl::OkStatus();
default:
if (optional_arg != nullptr) {
break;
}
result =
frame.value_manager().CreateErrorValue(InvalidSelectTargetError());
return absl::OkStatus();
}
if (test_only_) {
if (optional_arg != nullptr) {
if (!optional_arg->HasValue()) {
result = cel::BoolValue{false};
return absl::OkStatus();
}
PerformTestOnlySelect(frame, optional_arg->Value(), result);
return absl::OkStatus();
}
PerformTestOnlySelect(frame, result, result);
return absl::OkStatus();
}
if (optional_arg != nullptr) {
if (!optional_arg->HasValue()) {
return absl::OkStatus();
}
return PerformOptionalSelect(frame, optional_arg->Value(), result);
}
return PerformSelect(frame, result, result);
}
private:
std::unique_ptr<DirectExpressionStep> operand_;
void PerformTestOnlySelect(ExecutionFrameBase& frame, const Value& value,
Value& result) const;
absl::Status PerformOptionalSelect(ExecutionFrameBase& frame,
const Value& value, Value& result) const;
absl::Status PerformSelect(ExecutionFrameBase& frame, const Value& value,
Value& result) const;
StringValue field_value_;
std::string field_;
bool test_only_;
ProtoWrapperTypeOptions unboxing_option_;
bool enable_optional_types_;
};
void DirectSelectStep::PerformTestOnlySelect(ExecutionFrameBase& frame,
const cel::Value& value,
Value& result) const {
switch (value.kind()) {
case ValueKind::kMap:
TestOnlySelect(Cast<MapValue>(value), field_value_, frame.value_manager(),
result);
return;
case ValueKind::kMessage:
TestOnlySelect(Cast<StructValue>(value), field_, frame.value_manager(),
result);
return;
default:
result =
frame.value_manager().CreateErrorValue(InvalidSelectTargetError());
return;
}
}
absl::Status DirectSelectStep::PerformOptionalSelect(ExecutionFrameBase& frame,
const Value& value,
Value& result) const {
switch (value.kind()) {
case ValueKind::kStruct: {
auto struct_value = Cast<StructValue>(value);
CEL_ASSIGN_OR_RETURN(auto ok, struct_value.HasFieldByName(field_));
if (!ok) {
result = OptionalValue::None();
return absl::OkStatus();
}
CEL_RETURN_IF_ERROR(struct_value.GetFieldByName(
frame.value_manager(), field_, result, unboxing_option_));
result = OptionalValue::Of(frame.value_manager().GetMemoryManager(),
std::move(result));
return absl::OkStatus();
}
case ValueKind::kMap: {
CEL_ASSIGN_OR_RETURN(auto found,
Cast<MapValue>(value).Find(frame.value_manager(),
field_value_, result));
if (!found) {
result = OptionalValue::None();
return absl::OkStatus();
}
result = OptionalValue::Of(frame.value_manager().GetMemoryManager(),
std::move(result));
return absl::OkStatus();
}
default:
return InvalidSelectTargetError();
}
}
absl::Status DirectSelectStep::PerformSelect(ExecutionFrameBase& frame,
const cel::Value& value,
Value& result) const {
switch (value.kind()) {
case ValueKind::kStruct:
return Cast<StructValue>(value).GetFieldByName(
frame.value_manager(), field_, result, unboxing_option_);
case ValueKind::kMap:
return Cast<MapValue>(value).Get(frame.value_manager(), field_value_,
result);
default:
return InvalidSelectTargetError();
}
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectSelectStep(
std::unique_ptr<DirectExpressionStep> operand, StringValue field,
bool test_only, int64_t expr_id, bool enable_wrapper_type_null_unboxing,
bool enable_optional_types) {
return std::make_unique<DirectSelectStep>(
expr_id, std::move(operand), std::move(field), test_only,
enable_wrapper_type_null_unboxing, enable_optional_types);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateSelectStep(
const cel::ast_internal::Select& select_expr, int64_t expr_id,
bool enable_wrapper_type_null_unboxing, cel::ValueManager& value_factory,
bool enable_optional_types) {
return std::make_unique<SelectStep>(
value_factory.CreateUncheckedStringValue(select_expr.field()),
select_expr.test_only(), expr_id, enable_wrapper_type_null_unboxing,
enable_optional_types);
}
} | #include "eval/eval/select_step.h"
#include <string>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "base/ast_internal/expr.h"
#include "base/attribute.h"
#include "base/attribute_set.h"
#include "base/type_provider.h"
#include "common/casting.h"
#include "common/legacy_value.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/value_testing.h"
#include "common/values/legacy_value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/structs/legacy_type_adapter.h"
#include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/public/testing/matchers.h"
#include "eval/testutil/test_extensions.pb.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "extensions/protobuf/value.h"
#include "internal/proto_matchers.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "proto/test/v1/proto3/test_all_types.pb.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::Attribute;
using ::cel::AttributeQualifier;
using ::cel::AttributeSet;
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ManagedValueFactory;
using ::cel::OptionalValue;
using ::cel::RuntimeOptions;
using ::cel::TypeProvider;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ast_internal::Expr;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::extensions::ProtoMessageToValue;
using ::cel::internal::test::EqualsProto;
using ::cel::test::IntValueIs;
using ::google::api::expr::test::v1::proto3::TestAllTypes;
using ::testing::_;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Return;
using ::testing::UnorderedElementsAre;
struct RunExpressionOptions {
bool enable_unknowns = false;
bool enable_wrapper_type_null_unboxing = false;
};
class MockAccessor : public LegacyTypeAccessApis, public LegacyTypeInfoApis {
public:
MOCK_METHOD(absl::StatusOr<bool>, HasField,
(absl::string_view field_name,
const CelValue::MessageWrapper& value),
(const, override));
MOCK_METHOD(absl::StatusOr<CelValue>, GetField,
(absl::string_view field_name,
const CelValue::MessageWrapper& instance,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager),
(const, override));
MOCK_METHOD(absl::string_view, GetTypename,
(const CelValue::MessageWrapper& instance), (const, override));
MOCK_METHOD(std::string, DebugString,
(const CelValue::MessageWrapper& instance), (const, override));
MOCK_METHOD(std::vector<absl::string_view>, ListFields,
(const CelValue::MessageWrapper& value), (const, override));
const LegacyTypeAccessApis* GetAccessApis(
const CelValue::MessageWrapper& instance) const override {
return this;
}
};
class SelectStepTest : public testing::Test {
public:
SelectStepTest()
: value_factory_(ProtoMemoryManagerRef(&arena_),
cel::TypeProvider::Builtin()) {}
absl::StatusOr<CelValue> RunExpression(const CelValue target,
absl::string_view field, bool test,
absl::string_view unknown_path,
RunExpressionOptions options) {
ExecutionPath path;
Expr expr;
auto& select = expr.mutable_select_expr();
select.set_field(std::string(field));
select.set_test_only(test);
Expr& expr0 = select.mutable_operand();
auto& ident = expr0.mutable_ident_expr();
ident.set_name("target");
CEL_ASSIGN_OR_RETURN(auto step0, CreateIdentStep(ident, expr0.id()));
CEL_ASSIGN_OR_RETURN(
auto step1, CreateSelectStep(select, expr.id(),
options.enable_wrapper_type_null_unboxing,
value_factory_));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
cel::RuntimeOptions runtime_options;
if (options.enable_unknowns) {
runtime_options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), runtime_options));
Activation activation;
activation.InsertValue("target", target);
return cel_expr.Evaluate(activation, &arena_);
}
absl::StatusOr<CelValue> RunExpression(const TestExtensions* message,
absl::string_view field, bool test,
RunExpressionOptions options) {
return RunExpression(CelProtoWrapper::CreateMessage(message, &arena_),
field, test, "", options);
}
absl::StatusOr<CelValue> RunExpression(const TestMessage* message,
absl::string_view field, bool test,
absl::string_view unknown_path,
RunExpressionOptions options) {
return RunExpression(CelProtoWrapper::CreateMessage(message, &arena_),
field, test, unknown_path, options);
}
absl::StatusOr<CelValue> RunExpression(const TestMessage* message,
absl::string_view field, bool test,
RunExpressionOptions options) {
return RunExpression(message, field, test, "", options);
}
absl::StatusOr<CelValue> RunExpression(const CelMap* map_value,
absl::string_view field, bool test,
absl::string_view unknown_path,
RunExpressionOptions options) {
return RunExpression(CelValue::CreateMap(map_value), field, test,
unknown_path, options);
}
absl::StatusOr<CelValue> RunExpression(const CelMap* map_value,
absl::string_view field, bool test,
RunExpressionOptions options) {
return RunExpression(map_value, field, test, "", options);
}
protected:
google::protobuf::Arena arena_;
cel::common_internal::LegacyValueManager value_factory_;
};
class SelectStepConformanceTest : public SelectStepTest,
public testing::WithParamInterface<bool> {};
TEST_P(SelectStepConformanceTest, SelectMessageIsNull) {
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(static_cast<const TestMessage*>(nullptr),
"bool_value", true, options));
ASSERT_TRUE(result.IsError());
}
TEST_P(SelectStepConformanceTest, SelectTargetNotStructOrMap) {
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(CelValue::CreateStringView("some_value"), "some_field",
false,
"", options));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Applying SELECT to non-message type")));
}
TEST_P(SelectStepConformanceTest, PresenseIsFalseTest) {
TestMessage message;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "bool_value", true, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), false);
}
TEST_P(SelectStepConformanceTest, PresenseIsTrueTest) {
RunExpressionOptions options;
options.enable_unknowns = GetParam();
TestMessage message;
message.set_bool_value(true);
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "bool_value", true, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
}
TEST_P(SelectStepConformanceTest, ExtensionsPresenceIsTrueTest) {
TestExtensions exts;
TestExtensions* nested = exts.MutableExtension(nested_ext);
nested->set_name("nested");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts, "google.api.expr.runtime.nested_ext", true,
options));
ASSERT_TRUE(result.IsBool());
EXPECT_TRUE(result.BoolOrDie());
}
TEST_P(SelectStepConformanceTest, ExtensionsPresenceIsFalseTest) {
TestExtensions exts;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts, "google.api.expr.runtime.nested_ext", true,
options));
ASSERT_TRUE(result.IsBool());
EXPECT_FALSE(result.BoolOrDie());
}
TEST_P(SelectStepConformanceTest, MapPresenseIsFalseTest) {
RunExpressionOptions options;
options.enable_unknowns = GetParam();
std::string key1 = "key1";
std::vector<std::pair<CelValue, CelValue>> key_values{
{CelValue::CreateString(&key1), CelValue::CreateInt64(1)}};
auto map_value = CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(key_values))
.value();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(map_value.get(), "key2", true, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), false);
}
TEST_P(SelectStepConformanceTest, MapPresenseIsTrueTest) {
RunExpressionOptions options;
options.enable_unknowns = GetParam();
std::string key1 = "key1";
std::vector<std::pair<CelValue, CelValue>> key_values{
{CelValue::CreateString(&key1), CelValue::CreateInt64(1)}};
auto map_value = CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(key_values))
.value();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(map_value.get(), "key1", true, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
}
TEST_F(SelectStepTest, MapPresenseIsErrorTest) {
TestMessage message;
Expr select_expr;
auto& select = select_expr.mutable_select_expr();
select.set_field("1");
select.set_test_only(true);
Expr& expr1 = select.mutable_operand();
auto& select_map = expr1.mutable_select_expr();
select_map.set_field("int32_int32_map");
Expr& expr0 = select_map.mutable_operand();
auto& ident = expr0.mutable_ident_expr();
ident.set_name("target");
ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id()));
ASSERT_OK_AND_ASSIGN(
auto step1, CreateSelectStep(select_map, expr1.id(),
false,
value_factory_));
ASSERT_OK_AND_ASSIGN(
auto step2, CreateSelectStep(select, select_expr.id(),
false,
value_factory_));
ExecutionPath path;
path.push_back(std::move(step0));
path.push_back(std::move(step1));
path.push_back(std::move(step2));
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
Activation activation;
activation.InsertValue("target",
CelProtoWrapper::CreateMessage(&message, &arena_));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_));
EXPECT_TRUE(result.IsError());
EXPECT_EQ(result.ErrorOrDie()->code(), absl::StatusCode::kInvalidArgument);
}
TEST_F(SelectStepTest, MapPresenseIsTrueWithUnknownTest) {
UnknownSet unknown_set;
std::string key1 = "key1";
std::vector<std::pair<CelValue, CelValue>> key_values{
{CelValue::CreateString(&key1),
CelValue::CreateUnknownSet(&unknown_set)}};
auto map_value = CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(key_values))
.value();
RunExpressionOptions options;
options.enable_unknowns = true;
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(map_value.get(), "key1", true, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
}
TEST_P(SelectStepConformanceTest, FieldIsNotPresentInProtoTest) {
TestMessage message;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "fake_field", false, options));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(result.ErrorOrDie()->code(), Eq(absl::StatusCode::kNotFound));
}
TEST_P(SelectStepConformanceTest, FieldIsNotSetTest) {
TestMessage message;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "bool_value", false, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), false);
}
TEST_P(SelectStepConformanceTest, SimpleBoolTest) {
TestMessage message;
message.set_bool_value(true);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "bool_value", false, options));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
}
TEST_P(SelectStepConformanceTest, SimpleInt32Test) {
TestMessage message;
message.set_int32_value(1);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "int32_value", false, options));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 1);
}
TEST_P(SelectStepConformanceTest, SimpleInt64Test) {
TestMessage message;
message.set_int64_value(1);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "int64_value", false, options));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 1);
}
TEST_P(SelectStepConformanceTest, SimpleUInt32Test) {
TestMessage message;
message.set_uint32_value(1);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "uint32_value", false, options));
ASSERT_TRUE(result.IsUint64());
EXPECT_EQ(result.Uint64OrDie(), 1);
}
TEST_P(SelectStepConformanceTest, SimpleUint64Test) {
TestMessage message;
message.set_uint64_value(1);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "uint64_value", false, options));
ASSERT_TRUE(result.IsUint64());
EXPECT_EQ(result.Uint64OrDie(), 1);
}
TEST_P(SelectStepConformanceTest, SimpleStringTest) {
TestMessage message;
std::string value = "test";
message.set_string_value(value);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "string_value", false, options));
ASSERT_TRUE(result.IsString());
EXPECT_EQ(result.StringOrDie().value(), "test");
}
TEST_P(SelectStepConformanceTest, WrapperTypeNullUnboxingEnabledTest) {
TestMessage message;
message.mutable_string_wrapper_value()->set_value("test");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
options.enable_wrapper_type_null_unboxing = true;
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&message, "string_wrapper_value", false, options));
ASSERT_TRUE(result.IsString());
EXPECT_EQ(result.StringOrDie().value(), "test");
ASSERT_OK_AND_ASSIGN(
result, RunExpression(&message, "int32_wrapper_value", false, options));
EXPECT_TRUE(result.IsNull());
}
TEST_P(SelectStepConformanceTest, WrapperTypeNullUnboxingDisabledTest) {
TestMessage message;
message.mutable_string_wrapper_value()->set_value("test");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
options.enable_wrapper_type_null_unboxing = false;
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&message, "string_wrapper_value", false, options));
ASSERT_TRUE(result.IsString());
EXPECT_EQ(result.StringOrDie().value(), "test");
ASSERT_OK_AND_ASSIGN(
result, RunExpression(&message, "int32_wrapper_value", false, options));
EXPECT_TRUE(result.IsInt64());
}
TEST_P(SelectStepConformanceTest, SimpleBytesTest) {
TestMessage message;
std::string value = "test";
message.set_bytes_value(value);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "bytes_value", false, options));
ASSERT_TRUE(result.IsBytes());
EXPECT_EQ(result.BytesOrDie().value(), "test");
}
TEST_P(SelectStepConformanceTest, SimpleMessageTest) {
TestMessage message;
TestMessage* message2 = message.mutable_message_value();
message2->set_int32_value(1);
message2->set_string_value("test");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "message_value",
false, options));
ASSERT_TRUE(result.IsMessage());
EXPECT_THAT(*message2, EqualsProto(*result.MessageOrDie()));
}
TEST_P(SelectStepConformanceTest, GlobalExtensionsIntTest) {
TestExtensions exts;
exts.SetExtension(int32_ext, 42);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&exts, "google.api.expr.runtime.int32_ext",
false, options));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 42L);
}
TEST_P(SelectStepConformanceTest, GlobalExtensionsMessageTest) {
TestExtensions exts;
TestExtensions* nested = exts.MutableExtension(nested_ext);
nested->set_name("nested");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts, "google.api.expr.runtime.nested_ext", false,
options));
ASSERT_TRUE(result.IsMessage());
EXPECT_THAT(result.MessageOrDie(), Eq(nested));
}
TEST_P(SelectStepConformanceTest, GlobalExtensionsMessageUnsetTest) {
TestExtensions exts;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts, "google.api.expr.runtime.nested_ext", false,
options));
ASSERT_TRUE(result.IsMessage());
EXPECT_THAT(result.MessageOrDie(), Eq(&TestExtensions::default_instance()));
}
TEST_P(SelectStepConformanceTest, GlobalExtensionsWrapperTest) {
TestExtensions exts;
google::protobuf::Int32Value* wrapper =
exts.MutableExtension(int32_wrapper_ext);
wrapper->set_value(42);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts, "google.api.expr.runtime.int32_wrapper_ext", false,
options));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(42L));
}
TEST_P(SelectStepConformanceTest, GlobalExtensionsWrapperUnsetTest) {
TestExtensions exts;
RunExpressionOptions options;
options.enable_wrapper_type_null_unboxing = true;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts, "google.api.expr.runtime.int32_wrapper_ext", false,
options));
ASSERT_TRUE(result.IsNull());
}
TEST_P(SelectStepConformanceTest, MessageExtensionsEnumTest) {
TestExtensions exts;
exts.SetExtension(TestMessageExtensions::enum_ext, TestExtEnum::TEST_EXT_1);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&exts,
"google.api.expr.runtime.TestMessageExtensions.enum_ext",
false, options));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestExtEnum::TEST_EXT_1));
}
TEST_P(SelectStepConformanceTest, MessageExtensionsRepeatedStringTest) {
TestExtensions exts;
exts.AddExtension(TestMessageExtensions::repeated_string_exts, "test1");
exts.AddExtension(TestMessageExtensions::repeated_string_exts, "test2");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(
&exts,
"google.api.expr.runtime.TestMessageExtensions.repeated_string_exts",
false, options));
ASSERT_TRUE(result.IsList());
const CelList* cel_list = result.ListOrDie();
EXPECT_THAT(cel_list->size(), Eq(2));
}
TEST_P(SelectStepConformanceTest, MessageExtensionsRepeatedStringUnsetTest) {
TestExtensions exts;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(
&exts,
"google.api.expr.runtime.TestMessageExtensions.repeated_string_exts",
false, options));
ASSERT_TRUE(result.IsList());
const CelList* cel_list = result.ListOrDie();
EXPECT_THAT(cel_list->size(), Eq(0));
}
TEST_P(SelectStepConformanceTest, NullMessageAccessor) {
TestMessage message;
TestMessage* message2 = message.mutable_message_value();
message2->set_int32_value(1);
message2->set_string_value("test");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
CelValue value = CelValue::CreateMessageWrapper(
CelValue::MessageWrapper(&message, TrivialTypeInfo::GetInstance()));
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(value, "message_value",
false,
"", options));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kNotFound));
ASSERT_OK_AND_ASSIGN(result, RunExpression(value, "message_value",
true,
"", options));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kNotFound));
}
TEST_P(SelectStepConformanceTest, CustomAccessor) {
TestMessage message;
TestMessage* message2 = message.mutable_message_value();
message2->set_int32_value(1);
message2->set_string_value("test");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
testing::NiceMock<MockAccessor> accessor;
CelValue value = CelValue::CreateMessageWrapper(
CelValue::MessageWrapper(&message, &accessor));
ON_CALL(accessor, GetField(_, _, _, _))
.WillByDefault(Return(CelValue::CreateInt64(2)));
ON_CALL(accessor, HasField(_, _)).WillByDefault(Return(false));
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(value, "message_value",
false,
"", options));
EXPECT_THAT(result, test::IsCelInt64(2));
ASSERT_OK_AND_ASSIGN(result, RunExpression(value, "message_value",
true,
"", options));
EXPECT_THAT(result, test::IsCelBool(false));
}
TEST_P(SelectStepConformanceTest, CustomAccessorErrorHandling) {
TestMessage message;
TestMessage* message2 = message.mutable_message_value();
message2->set_int32_value(1);
message2->set_string_value("test");
RunExpressionOptions options;
options.enable_unknowns = GetParam();
testing::NiceMock<MockAccessor> accessor;
CelValue value = CelValue::CreateMessageWrapper(
CelValue::MessageWrapper(&message, &accessor));
ON_CALL(accessor, GetField(_, _, _, _))
.WillByDefault(Return(absl::InternalError("bad data")));
ON_CALL(accessor, HasField(_, _))
.WillByDefault(Return(absl::NotFoundError("not found")));
ASSERT_THAT(RunExpression(value, "message_value",
false,
"", options),
StatusIs(absl::StatusCode::kInternal));
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(value, "message_value",
true,
"", options));
EXPECT_THAT(result, test::IsCelError(StatusIs(absl::StatusCode::kNotFound)));
}
TEST_P(SelectStepConformanceTest, SimpleEnumTest) {
TestMessage message;
message.set_enum_value(TestMessage::TEST_ENUM_1);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "enum_value", false, options));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
}
TEST_P(SelectStepConformanceTest, SimpleListTest) {
TestMessage message;
message.add_int32_list(1);
message.add_int32_list(2);
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(&message, "int32_list", false, options));
ASSERT_TRUE(result.IsList());
const CelList* cel_list = result.ListOrDie();
EXPECT_THAT(cel_list->size(), Eq(2));
}
TEST_P(SelectStepConformanceTest, SimpleMapTest) {
TestMessage message;
auto map_field = message.mutable_string_int32_map();
(*map_field)["test0"] = 1;
(*map_field)["test1"] = 2;
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(
CelValue result,
RunExpression(&message, "string_int32_map", false, options));
ASSERT_TRUE(result.IsMap());
const CelMap* cel_map = result.MapOrDie();
EXPECT_THAT(cel_map->size(), Eq(2));
}
TEST_P(SelectStepConformanceTest, MapSimpleInt32Test) {
std::string key1 = "key1";
std::string key2 = "key2";
std::vector<std::pair<CelValue, CelValue>> key_values{
{CelValue::CreateString(&key1), CelValue::CreateInt64(1)},
{CelValue::CreateString(&key2), CelValue::CreateInt64(2)}};
auto map_value = CreateContainerBackedMap(
absl::Span<std::pair<CelValue, CelValue>>(key_values))
.value();
RunExpressionOptions options;
options.enable_unknowns = GetParam();
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(map_value.get(), "key1", false, options));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 1);
}
TEST_P(SelectStepConformanceTest, CelErrorAsArgument) {
ExecutionPath path;
Expr dummy_expr;
auto& select = dummy_expr.mutable_select_expr();
select.set_field("position");
select.set_test_only(false);
Expr& expr0 = select.mutable_operand();
auto& ident = expr0.mutable_ident_expr();
ident.set_name("message");
ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id()));
ASSERT_OK_AND_ASSIGN(
auto step1, CreateSelectStep(select, dummy_expr.id(),
false,
value_factory_));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
CelError error = absl::CancelledError();
cel::RuntimeOptions options;
if (GetParam()) {
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
Activation activation;
activation.InsertValue("message", CelValue::CreateError(&error));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(), Eq(error));
}
TEST_F(SelectStepTest, DisableMissingAttributeOK) {
TestMessage message;
message.set_bool_value(true);
ExecutionPath path;
Expr dummy_expr;
auto& select = dummy_expr.mutable_select_expr();
select.set_field("bool_value");
select.set_test_only(false);
Expr& expr0 = select.mutable_operand();
auto& ident = expr0.mutable_ident_expr();
ident.set_name("message");
ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id()));
ASSERT_OK_AND_ASSIGN(
auto step1, CreateSelectStep(select, dummy_expr.id(),
false,
value_factory_));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
CelAttributePattern pattern("message", {});
activation.set_missing_attribute_patterns({pattern});
ASSERT_OK_AND_ASSIGN(result, cel_expr.Evaluate(activation, &arena_));
EXPECT_EQ(result.BoolOrDie(), true);
}
TEST_F(SelectStepTest, UnrecoverableUnknownValueProducesError) {
TestMessage message;
message.set_bool_value(true);
ExecutionPath path;
Expr dummy_expr;
auto& select = dummy_expr.mutable_select_expr();
select.set_field("bool_value");
select.set_test_only(false);
Expr& expr0 = select.mutable_operand();
auto& ident = expr0.mutable_ident_expr();
ident.set_name("message");
ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id()));
ASSERT_OK_AND_ASSIGN(
auto step1, CreateSelectStep(select, dummy_expr.id(),
false,
value_factory_));
path.push_back(std::move(step0));
path.push_back(std::move(step1));
cel::RuntimeOptions options;
options.enable_missing_attribute_errors = true;
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
CelAttributePattern pattern("message",
{CreateCelAttributeQualifierPattern(
CelValue::CreateStringView("bool_value"))});
activation.set_missing_attribute_patterns({pattern});
ASSERT_OK_AND_ASSIGN(result, cel_expr.Evaluate(activation, &arena_));
EXPECT_THAT(*result.ErrorOrDie(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("MissingAttributeError: message.bool_value")));
}
TEST_F(SelectStepTest, UnknownPatternResolvesToUnknown) {
TestMessage message;
message.set_bool_value(true);
ExecutionPath path;
Expr dummy_expr;
auto& select = dummy_expr.mutable_select_expr();
select.set_field("bool_value");
select.set_test_only(false);
Expr& expr0 = select.mutable_operand();
auto& ident = expr0.mutable_ident_expr();
ident.set_name("message");
auto step0_status = CreateIdentStep(ident, expr0.id());
auto step1_status = CreateSelectStep(
select, dummy_expr.id(),
false, value_factory_);
ASSERT_OK(step0_status);
ASSERT_OK(step1_status);
path.push_back(*std::move(step0_status));
path.push_back(*std::move(step1_status));
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
{
std::vector<CelAttributePattern> unknown_patterns;
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
activation.set_unknown_attribute_patterns(unknown_patterns);
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
}
const std::string kSegmentCorrect1 = "bool_value";
const std::string kSegmentIncorrect = "message_value";
{
std::vector<CelAttributePattern> unknown_patterns;
unknown_patterns.push_back(CelAttributePattern("message", {}));
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
activation.set_unknown_attribute_patterns(unknown_patterns);
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsUnknownSet());
}
{
std::vector<CelAttributePattern> unknown_patterns;
unknown_patterns.push_back(CelAttributePattern(
"message", {CreateCelAttributeQualifierPattern(
CelValue::CreateString(&kSegmentCorrect1))}));
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
activation.set_unknown_attribute_patterns(unknown_patterns);
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsUnknownSet());
}
{
std::vector<CelAttributePattern> unknown_patterns;
unknown_patterns.push_back(CelAttributePattern(
"message", {CelAttributeQualifierPattern::CreateWildcard()}));
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
activation.set_unknown_attribute_patterns(unknown_patterns);
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsUnknownSet());
}
{
std::vector<CelAttributePattern> unknown_patterns;
unknown_patterns.push_back(CelAttributePattern(
"message", {CreateCelAttributeQualifierPattern(
CelValue::CreateString(&kSegmentIncorrect))}));
Activation activation;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena_));
activation.set_unknown_attribute_patterns(unknown_patterns);
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr.Evaluate(activation, &arena_));
ASSERT_TRUE(result.IsBool());
EXPECT_EQ(result.BoolOrDie(), true);
}
}
INSTANTIATE_TEST_SUITE_P(UnknownsEnabled, SelectStepConformanceTest,
testing::Bool());
class DirectSelectStepTest : public testing::Test {
public:
DirectSelectStepTest()
: value_manager_(TypeProvider::Builtin(),
ProtoMemoryManagerRef(&arena_)) {}
cel::Value TestWrapMessage(const google::protobuf::Message* message) {
CelValue value = CelProtoWrapper::CreateMessage(message, &arena_);
auto result = cel::interop_internal::FromLegacyValue(&arena_, value);
ABSL_DCHECK_OK(result.status());
return std::move(result).value();
}
std::vector<std::string> AttributeStrings(const UnknownValue& v) {
std::vector<std::string> result;
for (const Attribute& attr : v.attribute_set()) {
auto attr_str = attr.AsString();
ABSL_DCHECK_OK(attr_str.status());
result.push_back(std::move(attr_str).value());
}
return result;
}
protected:
google::protobuf::Arena arena_;
ManagedValueFactory value_manager_;
};
TEST_F(DirectSelectStepTest, SelectFromMap) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("one"),
false, -1,
true);
ASSERT_OK_AND_ASSIGN(auto map_builder,
value_manager_.get().NewMapValueBuilder(
value_manager_.get().GetDynDynMapType()));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("one"), IntValue(1)));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("two"), IntValue(2)));
activation.InsertOrAssignValue("map_val", std::move(*map_builder).Build());
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 1);
}
TEST_F(DirectSelectStepTest, HasMap) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("two"),
true, -1,
true);
ASSERT_OK_AND_ASSIGN(auto map_builder,
value_manager_.get().NewMapValueBuilder(
value_manager_.get().GetDynDynMapType()));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("one"), IntValue(1)));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("two"), IntValue(2)));
activation.InsertOrAssignValue("map_val", std::move(*map_builder).Build());
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<BoolValue>(result));
EXPECT_TRUE(Cast<BoolValue>(result).NativeValue());
}
TEST_F(DirectSelectStepTest, SelectFromOptionalMap) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("one"),
false, -1,
true,
true);
ASSERT_OK_AND_ASSIGN(auto map_builder,
value_manager_.get().NewMapValueBuilder(
value_manager_.get().GetDynDynMapType()));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("one"), IntValue(1)));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("two"), IntValue(2)));
activation.InsertOrAssignValue(
"map_val", OptionalValue::Of(value_manager_.get().GetMemoryManager(),
std::move(*map_builder).Build()));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<OptionalValue>(result));
EXPECT_THAT(Cast<OptionalValue>(static_cast<const Value&>(result)).Value(),
IntValueIs(1));
}
TEST_F(DirectSelectStepTest, SelectFromOptionalMapAbsent) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("three"),
false, -1,
true,
true);
ASSERT_OK_AND_ASSIGN(auto map_builder,
value_manager_.get().NewMapValueBuilder(
value_manager_.get().GetDynDynMapType()));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("one"), IntValue(1)));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("two"), IntValue(2)));
activation.InsertOrAssignValue(
"map_val", OptionalValue::Of(value_manager_.get().GetMemoryManager(),
std::move(*map_builder).Build()));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<OptionalValue>(result));
EXPECT_FALSE(
Cast<OptionalValue>(static_cast<const Value&>(result)).HasValue());
}
TEST_F(DirectSelectStepTest, SelectFromOptionalStruct) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("struct_val", -1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true,
true);
TestAllTypes message;
message.set_single_int64(1);
ASSERT_OK_AND_ASSIGN(
Value struct_val,
ProtoMessageToValue(value_manager_.get(), std::move(message)));
activation.InsertOrAssignValue(
"struct_val",
OptionalValue::Of(value_manager_.get().GetMemoryManager(), struct_val));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<OptionalValue>(result));
EXPECT_THAT(Cast<OptionalValue>(static_cast<const Value&>(result)).Value(),
IntValueIs(1));
}
TEST_F(DirectSelectStepTest, SelectFromOptionalStructFieldNotSet) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("struct_val", -1),
value_manager_.get().CreateUncheckedStringValue("single_string"),
false, -1,
true,
true);
TestAllTypes message;
message.set_single_int64(1);
ASSERT_OK_AND_ASSIGN(
Value struct_val,
ProtoMessageToValue(value_manager_.get(), std::move(message)));
activation.InsertOrAssignValue(
"struct_val",
OptionalValue::Of(value_manager_.get().GetMemoryManager(), struct_val));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<OptionalValue>(result));
EXPECT_FALSE(
Cast<OptionalValue>(static_cast<const Value&>(result)).HasValue());
}
TEST_F(DirectSelectStepTest, SelectFromEmptyOptional) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("one"),
false, -1,
true,
true);
activation.InsertOrAssignValue("map_val", OptionalValue::None());
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<OptionalValue>(result));
EXPECT_FALSE(
cel::Cast<OptionalValue>(static_cast<const Value&>(result)).HasValue());
}
TEST_F(DirectSelectStepTest, HasOptional) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("two"),
true, -1,
true,
true);
ASSERT_OK_AND_ASSIGN(auto map_builder,
value_manager_.get().NewMapValueBuilder(
value_manager_.get().GetDynDynMapType()));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("one"), IntValue(1)));
ASSERT_OK(map_builder->Put(
value_manager_.get().CreateUncheckedStringValue("two"), IntValue(2)));
activation.InsertOrAssignValue(
"map_val", OptionalValue::Of(value_manager_.get().GetMemoryManager(),
std::move(*map_builder).Build()));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<BoolValue>(result));
EXPECT_TRUE(Cast<BoolValue>(result).NativeValue());
}
TEST_F(DirectSelectStepTest, HasEmptyOptional) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("map_val", -1),
value_manager_.get().CreateUncheckedStringValue("two"),
true, -1,
true,
true);
activation.InsertOrAssignValue("map_val", OptionalValue::None());
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<BoolValue>(result));
EXPECT_FALSE(Cast<BoolValue>(result).NativeValue());
}
TEST_F(DirectSelectStepTest, SelectFromStruct) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("test_all_types", -1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true);
TestAllTypes message;
message.set_single_int64(1);
activation.InsertOrAssignValue("test_all_types", TestWrapMessage(&message));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 1);
}
TEST_F(DirectSelectStepTest, HasStruct) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("test_all_types", -1),
value_manager_.get().CreateUncheckedStringValue("single_string"),
true, -1,
true);
TestAllTypes message;
message.set_single_int64(1);
activation.InsertOrAssignValue("test_all_types", TestWrapMessage(&message));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<BoolValue>(result));
EXPECT_FALSE(Cast<BoolValue>(result).NativeValue());
}
TEST_F(DirectSelectStepTest, SelectFromUnsupportedType) {
cel::Activation activation;
RuntimeOptions options;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("bool_val", -1),
value_manager_.get().CreateUncheckedStringValue("one"),
false, -1,
true);
activation.InsertOrAssignValue("bool_val", BoolValue(false));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Applying SELECT to non-message type")));
}
TEST_F(DirectSelectStepTest, AttributeUpdatedIfRequested) {
cel::Activation activation;
RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("test_all_types", -1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true);
TestAllTypes message;
message.set_single_int64(1);
activation.InsertOrAssignValue("test_all_types", TestWrapMessage(&message));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 1);
ASSERT_OK_AND_ASSIGN(std::string attr_str, attr.attribute().AsString());
EXPECT_EQ(attr_str, "test_all_types.single_int64");
}
TEST_F(DirectSelectStepTest, MissingAttributesToErrors) {
cel::Activation activation;
RuntimeOptions options;
options.enable_missing_attribute_errors = true;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("test_all_types", -1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true);
TestAllTypes message;
message.set_single_int64(1);
activation.InsertOrAssignValue("test_all_types", TestWrapMessage(&message));
activation.SetMissingPatterns({cel::AttributePattern(
"test_all_types",
{cel::AttributeQualifierPattern::OfString("single_int64")})});
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("test_all_types.single_int64")));
}
TEST_F(DirectSelectStepTest, IdentifiesUnknowns) {
cel::Activation activation;
RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
auto step = CreateDirectSelectStep(
CreateDirectIdentStep("test_all_types", -1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true);
TestAllTypes message;
message.set_single_int64(1);
activation.InsertOrAssignValue("test_all_types", TestWrapMessage(&message));
activation.SetUnknownPatterns({cel::AttributePattern(
"test_all_types",
{cel::AttributeQualifierPattern::OfString("single_int64")})});
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<UnknownValue>(result));
EXPECT_THAT(AttributeStrings(Cast<UnknownValue>(result)),
UnorderedElementsAre("test_all_types.single_int64"));
}
TEST_F(DirectSelectStepTest, ForwardErrorValue) {
cel::Activation activation;
RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
auto step = CreateDirectSelectStep(
CreateConstValueDirectStep(
value_manager_.get().CreateErrorValue(absl::InternalError("test1")),
-1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true);
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInternal, HasSubstr("test1")));
}
TEST_F(DirectSelectStepTest, ForwardUnknownOperand) {
cel::Activation activation;
RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
AttributeSet attr_set({Attribute("attr", {AttributeQualifier::OfInt(0)})});
auto step = CreateDirectSelectStep(
CreateConstValueDirectStep(
value_manager_.get().CreateUnknownValue(std::move(attr_set)), -1),
value_manager_.get().CreateUncheckedStringValue("single_int64"),
false, -1,
true);
TestAllTypes message;
message.set_single_int64(1);
activation.InsertOrAssignValue("test_all_types", TestWrapMessage(&message));
ExecutionFrameBase frame(activation, options, value_manager_.get());
Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<UnknownValue>(result));
EXPECT_THAT(AttributeStrings(Cast<UnknownValue>(result)),
UnorderedElementsAre("attr[0]"));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/select_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/select_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
90e4c0d3-86b4-4bd3-b131-1140cb425e65 | cpp | google/cel-cpp | optional_or_step | eval/eval/optional_or_step.cc | eval/eval/optional_or_step_test.cc | #include "eval/eval/optional_or_step.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/base/optimization.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "common/casting.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/eval/jump_step.h"
#include "internal/status_macros.h"
#include "runtime/internal/errors.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::As;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::OptionalValue;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::runtime_internal::CreateNoMatchingOverloadError;
enum class OptionalOrKind { kOrOptional, kOrValue };
ErrorValue MakeNoOverloadError(OptionalOrKind kind) {
switch (kind) {
case OptionalOrKind::kOrOptional:
return ErrorValue(CreateNoMatchingOverloadError("or"));
case OptionalOrKind::kOrValue:
return ErrorValue(CreateNoMatchingOverloadError("orValue"));
}
ABSL_UNREACHABLE();
}
class OptionalHasValueJumpStep final : public JumpStepBase {
public:
OptionalHasValueJumpStep(int64_t expr_id, OptionalOrKind kind)
: JumpStepBase({}, expr_id), kind_(kind) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
if (!frame->value_stack().HasEnough(1)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
const auto& value = frame->value_stack().Peek();
auto optional_value = As<OptionalValue>(value);
const bool should_jump =
(optional_value.has_value() && optional_value->HasValue()) ||
(!optional_value.has_value() && (cel::InstanceOf<ErrorValue>(value) ||
cel::InstanceOf<UnknownValue>(value)));
if (should_jump) {
if (kind_ == OptionalOrKind::kOrValue && optional_value.has_value()) {
frame->value_stack().PopAndPush(optional_value->Value());
}
return Jump(frame);
}
return absl::OkStatus();
}
private:
const OptionalOrKind kind_;
};
class OptionalOrStep : public ExpressionStepBase {
public:
explicit OptionalOrStep(int64_t expr_id, OptionalOrKind kind)
: ExpressionStepBase(expr_id), kind_(kind) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
const OptionalOrKind kind_;
};
absl::Status EvalOptionalOr(OptionalOrKind kind, const Value& lhs,
const Value& rhs, const AttributeTrail& lhs_attr,
const AttributeTrail& rhs_attr, Value& result,
AttributeTrail& result_attr) {
if (InstanceOf<ErrorValue>(lhs) || InstanceOf<UnknownValue>(lhs)) {
result = lhs;
result_attr = lhs_attr;
return absl::OkStatus();
}
auto lhs_optional_value = As<OptionalValue>(lhs);
if (!lhs_optional_value.has_value()) {
result = MakeNoOverloadError(kind);
result_attr = AttributeTrail();
return absl::OkStatus();
}
if (lhs_optional_value->HasValue()) {
if (kind == OptionalOrKind::kOrValue) {
result = lhs_optional_value->Value();
} else {
result = lhs;
}
result_attr = lhs_attr;
return absl::OkStatus();
}
if (kind == OptionalOrKind::kOrOptional && !InstanceOf<ErrorValue>(rhs) &&
!InstanceOf<UnknownValue>(rhs) && !InstanceOf<OptionalValue>(rhs)) {
result = MakeNoOverloadError(kind);
result_attr = AttributeTrail();
return absl::OkStatus();
}
result = rhs;
result_attr = rhs_attr;
return absl::OkStatus();
}
absl::Status OptionalOrStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(2)) {
return absl::InternalError("Value stack underflow");
}
absl::Span<const Value> args = frame->value_stack().GetSpan(2);
absl::Span<const AttributeTrail> args_attr =
frame->value_stack().GetAttributeSpan(2);
Value result;
AttributeTrail result_attr;
CEL_RETURN_IF_ERROR(EvalOptionalOr(kind_, args[0], args[1], args_attr[0],
args_attr[1], result, result_attr));
frame->value_stack().PopAndPush(2, std::move(result), std::move(result_attr));
return absl::OkStatus();
}
class ExhaustiveDirectOptionalOrStep : public DirectExpressionStep {
public:
ExhaustiveDirectOptionalOrStep(
int64_t expr_id, std::unique_ptr<DirectExpressionStep> optional,
std::unique_ptr<DirectExpressionStep> alternative, OptionalOrKind kind)
: DirectExpressionStep(expr_id),
kind_(kind),
optional_(std::move(optional)),
alternative_(std::move(alternative)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override;
private:
OptionalOrKind kind_;
std::unique_ptr<DirectExpressionStep> optional_;
std::unique_ptr<DirectExpressionStep> alternative_;
};
absl::Status ExhaustiveDirectOptionalOrStep::Evaluate(
ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const {
CEL_RETURN_IF_ERROR(optional_->Evaluate(frame, result, attribute));
Value rhs;
AttributeTrail rhs_attr;
CEL_RETURN_IF_ERROR(alternative_->Evaluate(frame, rhs, rhs_attr));
CEL_RETURN_IF_ERROR(EvalOptionalOr(kind_, result, rhs, attribute, rhs_attr,
result, attribute));
return absl::OkStatus();
}
class DirectOptionalOrStep : public DirectExpressionStep {
public:
DirectOptionalOrStep(int64_t expr_id,
std::unique_ptr<DirectExpressionStep> optional,
std::unique_ptr<DirectExpressionStep> alternative,
OptionalOrKind kind)
: DirectExpressionStep(expr_id),
kind_(kind),
optional_(std::move(optional)),
alternative_(std::move(alternative)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override;
private:
OptionalOrKind kind_;
std::unique_ptr<DirectExpressionStep> optional_;
std::unique_ptr<DirectExpressionStep> alternative_;
};
absl::Status DirectOptionalOrStep::Evaluate(ExecutionFrameBase& frame,
Value& result,
AttributeTrail& attribute) const {
CEL_RETURN_IF_ERROR(optional_->Evaluate(frame, result, attribute));
if (InstanceOf<UnknownValue>(result) || InstanceOf<ErrorValue>(result)) {
return absl::OkStatus();
}
auto optional_value = As<OptionalValue>(static_cast<const Value&>(result));
if (!optional_value.has_value()) {
result = MakeNoOverloadError(kind_);
return absl::OkStatus();
}
if (optional_value->HasValue()) {
if (kind_ == OptionalOrKind::kOrValue) {
result = optional_value->Value();
}
return absl::OkStatus();
}
CEL_RETURN_IF_ERROR(alternative_->Evaluate(frame, result, attribute));
if (kind_ == OptionalOrKind::kOrOptional) {
if (!InstanceOf<OptionalValue>(result) && !InstanceOf<ErrorValue>(result) &&
!InstanceOf<UnknownValue>(result)) {
result = MakeNoOverloadError(kind_);
}
}
return absl::OkStatus();
}
}
absl::StatusOr<std::unique_ptr<JumpStepBase>> CreateOptionalHasValueJumpStep(
bool or_value, int64_t expr_id) {
return std::make_unique<OptionalHasValueJumpStep>(
expr_id,
or_value ? OptionalOrKind::kOrValue : OptionalOrKind::kOrOptional);
}
std::unique_ptr<ExpressionStep> CreateOptionalOrStep(bool is_or_value,
int64_t expr_id) {
return std::make_unique<OptionalOrStep>(
expr_id,
is_or_value ? OptionalOrKind::kOrValue : OptionalOrKind::kOrOptional);
}
std::unique_ptr<DirectExpressionStep> CreateDirectOptionalOrStep(
int64_t expr_id, std::unique_ptr<DirectExpressionStep> optional,
std::unique_ptr<DirectExpressionStep> alternative, bool is_or_value,
bool short_circuiting) {
auto kind =
is_or_value ? OptionalOrKind::kOrValue : OptionalOrKind::kOrOptional;
if (short_circuiting) {
return std::make_unique<DirectOptionalOrStep>(expr_id, std::move(optional),
std::move(alternative), kind);
} else {
return std::make_unique<ExhaustiveDirectOptionalOrStep>(
expr_id, std::move(optional), std::move(alternative), kind);
}
}
} | #include "eval/eval/optional_or_step.h"
#include <memory>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "common/casting.h"
#include "common/memory.h"
#include "common/type_reflector.h"
#include "common/value.h"
#include "common/value_kind.h"
#include "common/value_testing.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/internal/errors.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::Activation;
using ::cel::As;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ManagedValueFactory;
using ::cel::MemoryManagerRef;
using ::cel::OptionalValue;
using ::cel::RuntimeOptions;
using ::cel::TypeReflector;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ValueKind;
using ::cel::test::ErrorValueIs;
using ::cel::test::IntValueIs;
using ::cel::test::OptionalValueIs;
using ::cel::test::ValueKindIs;
using ::testing::HasSubstr;
using ::testing::NiceMock;
class MockDirectStep : public DirectExpressionStep {
public:
MOCK_METHOD(absl::Status, Evaluate,
(ExecutionFrameBase & frame, Value& result,
AttributeTrail& scratch),
(const, override));
};
std::unique_ptr<DirectExpressionStep> MockNeverCalledDirectStep() {
auto* mock = new NiceMock<MockDirectStep>();
EXPECT_CALL(*mock, Evaluate).Times(0);
return absl::WrapUnique(mock);
}
std::unique_ptr<DirectExpressionStep> MockExpectCallDirectStep() {
auto* mock = new NiceMock<MockDirectStep>();
EXPECT_CALL(*mock, Evaluate)
.Times(1)
.WillRepeatedly(
[](ExecutionFrameBase& frame, Value& result, AttributeTrail& attr) {
result = ErrorValue(absl::InternalError("expected to be unused"));
return absl::OkStatus();
});
return absl::WrapUnique(mock);
}
class OptionalOrTest : public testing::Test {
public:
OptionalOrTest()
: value_factory_(TypeReflector::Builtin(),
MemoryManagerRef::ReferenceCounting()) {}
protected:
ManagedValueFactory value_factory_;
Activation empty_activation_;
};
TEST_F(OptionalOrTest, OptionalOrLeftPresentShortcutRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1,
CreateConstValueDirectStep(OptionalValue::Of(
value_factory_.get().GetMemoryManager(), IntValue(42))),
MockNeverCalledDirectStep(),
false,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, OptionalValueIs(IntValueIs(42)));
}
TEST_F(OptionalOrTest, OptionalOrLeftErrorShortcutsRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1,
CreateConstValueDirectStep(ErrorValue(absl::InternalError("error"))),
MockNeverCalledDirectStep(),
false,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, ValueKindIs(ValueKind::kError));
}
TEST_F(OptionalOrTest, OptionalOrLeftErrorExhaustiveRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1,
CreateConstValueDirectStep(ErrorValue(absl::InternalError("error"))),
MockExpectCallDirectStep(),
false,
false);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, ValueKindIs(ValueKind::kError));
}
TEST_F(OptionalOrTest, OptionalOrLeftUnknownShortcutsRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(UnknownValue()),
MockNeverCalledDirectStep(),
false,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, ValueKindIs(ValueKind::kUnknown));
}
TEST_F(OptionalOrTest, OptionalOrLeftUnknownExhaustiveRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(UnknownValue()),
MockExpectCallDirectStep(),
false,
false);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, ValueKindIs(ValueKind::kUnknown));
}
TEST_F(OptionalOrTest, OptionalOrLeftAbsentReturnRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(OptionalValue::None()),
CreateConstValueDirectStep(OptionalValue::Of(
value_factory_.get().GetMemoryManager(), IntValue(42))),
false,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, OptionalValueIs(IntValueIs(42)));
}
TEST_F(OptionalOrTest, OptionalOrLeftWrongType) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(IntValue(42)),
MockNeverCalledDirectStep(),
false,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result,
ErrorValueIs(StatusIs(
absl::StatusCode::kUnknown,
HasSubstr(cel::runtime_internal::kErrNoMatchingOverload))));
}
TEST_F(OptionalOrTest, OptionalOrRightWrongType) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(OptionalValue::None()),
CreateConstValueDirectStep(IntValue(42)),
false,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result,
ErrorValueIs(StatusIs(
absl::StatusCode::kUnknown,
HasSubstr(cel::runtime_internal::kErrNoMatchingOverload))));
}
TEST_F(OptionalOrTest, OptionalOrValueLeftPresentShortcutRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1,
CreateConstValueDirectStep(OptionalValue::Of(
value_factory_.get().GetMemoryManager(), IntValue(42))),
MockNeverCalledDirectStep(),
true,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, IntValueIs(42));
}
TEST_F(OptionalOrTest, OptionalOrValueLeftPresentExhaustiveRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1,
CreateConstValueDirectStep(OptionalValue::Of(
value_factory_.get().GetMemoryManager(), IntValue(42))),
MockExpectCallDirectStep(),
true,
false);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, IntValueIs(42));
}
TEST_F(OptionalOrTest, OptionalOrValueLeftErrorShortcutsRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1,
CreateConstValueDirectStep(ErrorValue(absl::InternalError("error"))),
MockNeverCalledDirectStep(),
true,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, ValueKindIs(ValueKind::kError));
}
TEST_F(OptionalOrTest, OptionalOrValueLeftUnknownShortcutsRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(UnknownValue()),
MockNeverCalledDirectStep(), true, true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, ValueKindIs(ValueKind::kUnknown));
}
TEST_F(OptionalOrTest, OptionalOrValueLeftAbsentReturnRight) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(OptionalValue::None()),
CreateConstValueDirectStep(IntValue(42)),
true,
true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result, IntValueIs(42));
}
TEST_F(OptionalOrTest, OptionalOrValueLeftWrongType) {
RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, options, value_factory_.get());
std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep(
-1, CreateConstValueDirectStep(IntValue(42)),
MockNeverCalledDirectStep(), true, true);
Value result;
AttributeTrail scratch;
ASSERT_OK(step->Evaluate(frame, result, scratch));
EXPECT_THAT(result,
ErrorValueIs(StatusIs(
absl::StatusCode::kUnknown,
HasSubstr(cel::runtime_internal::kErrNoMatchingOverload))));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/optional_or_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/optional_or_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
08a67a1f-f0f3-4b9c-a899-9e6205fa1417 | cpp | google/cel-cpp | container_access_step | eval/eval/container_access_step.cc | eval/eval/container_access_step_test.cc | #include "eval/eval/container_access_step.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "base/ast_internal/expr.h"
#include "base/attribute.h"
#include "base/kind.h"
#include "common/casting.h"
#include "common/native_type.h"
#include "common/value.h"
#include "common/value_kind.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/attribute_utility.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "internal/casts.h"
#include "internal/number.h"
#include "internal/status_macros.h"
#include "runtime/internal/errors.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::AttributeQualifier;
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::DoubleValue;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ListValue;
using ::cel::MapValue;
using ::cel::StringValue;
using ::cel::UintValue;
using ::cel::Value;
using ::cel::ValueKind;
using ::cel::ValueKindToString;
using ::cel::internal::Number;
using ::cel::runtime_internal::CreateNoSuchKeyError;
inline constexpr int kNumContainerAccessArguments = 2;
absl::optional<Number> CelNumberFromValue(const Value& value) {
switch (value->kind()) {
case ValueKind::kInt64:
return Number::FromInt64(value.GetInt().NativeValue());
case ValueKind::kUint64:
return Number::FromUint64(value.GetUint().NativeValue());
case ValueKind::kDouble:
return Number::FromDouble(value.GetDouble().NativeValue());
default:
return absl::nullopt;
}
}
absl::Status CheckMapKeyType(const Value& key) {
ValueKind kind = key->kind();
switch (kind) {
case ValueKind::kString:
case ValueKind::kInt64:
case ValueKind::kUint64:
case ValueKind::kBool:
return absl::OkStatus();
default:
return absl::InvalidArgumentError(absl::StrCat(
"Invalid map key type: '", ValueKindToString(kind), "'"));
}
}
AttributeQualifier AttributeQualifierFromValue(const Value& v) {
switch (v->kind()) {
case ValueKind::kString:
return AttributeQualifier::OfString(v.GetString().ToString());
case ValueKind::kInt64:
return AttributeQualifier::OfInt(v.GetInt().NativeValue());
case ValueKind::kUint64:
return AttributeQualifier::OfUint(v.GetUint().NativeValue());
case ValueKind::kBool:
return AttributeQualifier::OfBool(v.GetBool().NativeValue());
default:
return AttributeQualifier();
}
}
void LookupInMap(const MapValue& cel_map, const Value& key,
ExecutionFrameBase& frame, Value& result) {
if (frame.options().enable_heterogeneous_equality) {
absl::optional<Number> number = CelNumberFromValue(key);
if (number.has_value()) {
if (key->Is<UintValue>()) {
auto lookup = cel_map.Find(frame.value_manager(), key, result);
if (!lookup.ok()) {
result = frame.value_manager().CreateErrorValue(
std::move(lookup).status());
return;
}
if (*lookup) {
return;
}
}
if (number->LosslessConvertibleToInt()) {
auto lookup = cel_map.Find(
frame.value_manager(),
frame.value_manager().CreateIntValue(number->AsInt()), result);
if (!lookup.ok()) {
result = frame.value_manager().CreateErrorValue(
std::move(lookup).status());
return;
}
if (*lookup) {
return;
}
}
if (number->LosslessConvertibleToUint()) {
auto lookup = cel_map.Find(
frame.value_manager(),
frame.value_manager().CreateUintValue(number->AsUint()), result);
if (!lookup.ok()) {
result = frame.value_manager().CreateErrorValue(
std::move(lookup).status());
return;
}
if (*lookup) {
return;
}
}
result = frame.value_manager().CreateErrorValue(
CreateNoSuchKeyError(key->DebugString()));
return;
}
}
absl::Status status = CheckMapKeyType(key);
if (!status.ok()) {
result = frame.value_manager().CreateErrorValue(std::move(status));
return;
}
absl::Status lookup = cel_map.Get(frame.value_manager(), key, result);
if (!lookup.ok()) {
result = frame.value_manager().CreateErrorValue(std::move(lookup));
}
}
void LookupInList(const ListValue& cel_list, const Value& key,
ExecutionFrameBase& frame, Value& result) {
absl::optional<int64_t> maybe_idx;
if (frame.options().enable_heterogeneous_equality) {
auto number = CelNumberFromValue(key);
if (number.has_value() && number->LosslessConvertibleToInt()) {
maybe_idx = number->AsInt();
}
} else if (InstanceOf<IntValue>(key)) {
maybe_idx = key.GetInt().NativeValue();
}
if (!maybe_idx.has_value()) {
result = frame.value_manager().CreateErrorValue(absl::UnknownError(
absl::StrCat("Index error: expected integer type, got ",
cel::KindToString(ValueKindToKind(key->kind())))));
return;
}
int64_t idx = *maybe_idx;
auto size = cel_list.Size();
if (!size.ok()) {
result = frame.value_manager().CreateErrorValue(size.status());
return;
}
if (idx < 0 || idx >= *size) {
result = frame.value_manager().CreateErrorValue(absl::UnknownError(
absl::StrCat("Index error: index=", idx, " size=", *size)));
return;
}
absl::Status lookup = cel_list.Get(frame.value_manager(), idx, result);
if (!lookup.ok()) {
result = frame.value_manager().CreateErrorValue(std::move(lookup));
}
}
void LookupInContainer(const Value& container, const Value& key,
ExecutionFrameBase& frame, Value& result) {
switch (container.kind()) {
case ValueKind::kMap: {
LookupInMap(Cast<MapValue>(container), key, frame, result);
return;
}
case ValueKind::kList: {
LookupInList(Cast<ListValue>(container), key, frame, result);
return;
}
default:
result =
frame.value_manager().CreateErrorValue(absl::InvalidArgumentError(
absl::StrCat("Invalid container type: '",
ValueKindToString(container->kind()), "'")));
return;
}
}
void PerformLookup(ExecutionFrameBase& frame, const Value& container,
const Value& key, const AttributeTrail& container_trail,
bool enable_optional_types, Value& result,
AttributeTrail& trail) {
if (frame.unknown_processing_enabled()) {
AttributeUtility::Accumulator unknowns =
frame.attribute_utility().CreateAccumulator();
unknowns.MaybeAdd(container);
unknowns.MaybeAdd(key);
if (!unknowns.IsEmpty()) {
result = std::move(unknowns).Build();
return;
}
trail = container_trail.Step(AttributeQualifierFromValue(key));
if (frame.attribute_utility().CheckForUnknownExact(trail)) {
result = frame.attribute_utility().CreateUnknownSet(trail.attribute());
return;
}
}
if (InstanceOf<ErrorValue>(container)) {
result = container;
return;
}
if (InstanceOf<ErrorValue>(key)) {
result = key;
return;
}
if (enable_optional_types &&
cel::NativeTypeId::Of(container) ==
cel::NativeTypeId::For<cel::OptionalValueInterface>()) {
const auto& optional_value =
*cel::internal::down_cast<const cel::OptionalValueInterface*>(
cel::Cast<cel::OpaqueValue>(container).operator->());
if (!optional_value.HasValue()) {
result = cel::OptionalValue::None();
return;
}
LookupInContainer(optional_value.Value(), key, frame, result);
if (auto error_value = cel::As<cel::ErrorValue>(result);
error_value && cel::IsNoSuchKey(*error_value)) {
result = cel::OptionalValue::None();
return;
}
result = cel::OptionalValue::Of(frame.value_manager().GetMemoryManager(),
std::move(result));
return;
}
LookupInContainer(container, key, frame, result);
}
class ContainerAccessStep : public ExpressionStepBase {
public:
ContainerAccessStep(int64_t expr_id, bool enable_optional_types)
: ExpressionStepBase(expr_id),
enable_optional_types_(enable_optional_types) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
bool enable_optional_types_;
};
absl::Status ContainerAccessStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(kNumContainerAccessArguments)) {
return absl::Status(
absl::StatusCode::kInternal,
"Insufficient arguments supplied for ContainerAccess-type expression");
}
Value result;
AttributeTrail result_trail;
auto args = frame->value_stack().GetSpan(kNumContainerAccessArguments);
const AttributeTrail& container_trail =
frame->value_stack().GetAttributeSpan(kNumContainerAccessArguments)[0];
PerformLookup(*frame, args[0], args[1], container_trail,
enable_optional_types_, result, result_trail);
frame->value_stack().PopAndPush(kNumContainerAccessArguments,
std::move(result), std::move(result_trail));
return absl::OkStatus();
}
class DirectContainerAccessStep : public DirectExpressionStep {
public:
DirectContainerAccessStep(
std::unique_ptr<DirectExpressionStep> container_step,
std::unique_ptr<DirectExpressionStep> key_step,
bool enable_optional_types, int64_t expr_id)
: DirectExpressionStep(expr_id),
container_step_(std::move(container_step)),
key_step_(std::move(key_step)),
enable_optional_types_(enable_optional_types) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& trail) const override;
private:
std::unique_ptr<DirectExpressionStep> container_step_;
std::unique_ptr<DirectExpressionStep> key_step_;
bool enable_optional_types_;
};
absl::Status DirectContainerAccessStep::Evaluate(ExecutionFrameBase& frame,
Value& result,
AttributeTrail& trail) const {
Value container;
Value key;
AttributeTrail container_trail;
AttributeTrail key_trail;
CEL_RETURN_IF_ERROR(
container_step_->Evaluate(frame, container, container_trail));
CEL_RETURN_IF_ERROR(key_step_->Evaluate(frame, key, key_trail));
PerformLookup(frame, container, key, container_trail, enable_optional_types_,
result, trail);
return absl::OkStatus();
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectContainerAccessStep(
std::unique_ptr<DirectExpressionStep> container_step,
std::unique_ptr<DirectExpressionStep> key_step, bool enable_optional_types,
int64_t expr_id) {
return std::make_unique<DirectContainerAccessStep>(
std::move(container_step), std::move(key_step), enable_optional_types,
expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateContainerAccessStep(
const cel::ast_internal::Call& call, int64_t expr_id,
bool enable_optional_types) {
int arg_count = call.args().size() + (call.has_target() ? 1 : 0);
if (arg_count != kNumContainerAccessArguments) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid argument count for index operation: ", arg_count));
}
return std::make_unique<ContainerAccessStep>(expr_id, enable_optional_types);
}
} | #include "eval/eval/container_access_step.h"
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/struct.pb.h"
#include "absl/status/status.h"
#include "base/builtins.h"
#include "base/type_provider.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_expr_builder_factory.h"
#include "eval/public/cel_expression.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/testing/matchers.h"
#include "eval/public/unknown_set.h"
#include "internal/testing.h"
#include "parser/parser.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::TypeProvider;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::SourceInfo;
using ::google::api::expr::v1alpha1::ParsedExpr;
using ::google::protobuf::Struct;
using ::testing::_;
using ::testing::AllOf;
using ::testing::HasSubstr;
using TestParamType = std::tuple<bool, bool, bool>;
CelValue EvaluateAttributeHelper(
google::protobuf::Arena* arena, CelValue container, CelValue key,
bool use_recursive_impl, bool receiver_style, bool enable_unknown,
const std::vector<CelAttributePattern>& patterns) {
ExecutionPath path;
Expr expr;
SourceInfo source_info;
auto& call = expr.mutable_call_expr();
call.set_function(cel::builtin::kIndex);
call.mutable_args().reserve(2);
Expr& container_expr = (receiver_style) ? call.mutable_target()
: call.mutable_args().emplace_back();
Expr& key_expr = call.mutable_args().emplace_back();
container_expr.mutable_ident_expr().set_name("container");
key_expr.mutable_ident_expr().set_name("key");
if (use_recursive_impl) {
path.push_back(std::make_unique<WrappedDirectStep>(
CreateDirectContainerAccessStep(CreateDirectIdentStep("container", 1),
CreateDirectIdentStep("key", 2),
false, 3),
3));
} else {
path.push_back(
std::move(CreateIdentStep(container_expr.ident_expr(), 1).value()));
path.push_back(
std::move(CreateIdentStep(key_expr.ident_expr(), 2).value()));
path.push_back(std::move(CreateContainerAccessStep(call, 3).value()));
}
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
options.enable_heterogeneous_equality = false;
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
Activation activation;
activation.InsertValue("container", container);
activation.InsertValue("key", key);
activation.set_unknown_attribute_patterns(patterns);
auto result = cel_expr.Evaluate(activation, arena);
return *result;
}
class ContainerAccessStepTest : public ::testing::Test {
protected:
ContainerAccessStepTest() = default;
void SetUp() override {}
CelValue EvaluateAttribute(
CelValue container, CelValue key, bool receiver_style,
bool enable_unknown, bool use_recursive_impl = false,
const std::vector<CelAttributePattern>& patterns = {}) {
return EvaluateAttributeHelper(&arena_, container, key, receiver_style,
enable_unknown, use_recursive_impl,
patterns);
}
google::protobuf::Arena arena_;
};
class ContainerAccessStepUniformityTest
: public ::testing::TestWithParam<TestParamType> {
protected:
ContainerAccessStepUniformityTest() = default;
void SetUp() override {}
bool receiver_style() {
TestParamType params = GetParam();
return std::get<0>(params);
}
bool enable_unknown() {
TestParamType params = GetParam();
return std::get<1>(params);
}
bool use_recursive_impl() {
TestParamType params = GetParam();
return std::get<2>(params);
}
CelValue EvaluateAttribute(
CelValue container, CelValue key, bool receiver_style,
bool enable_unknown, bool use_recursive_impl = false,
const std::vector<CelAttributePattern>& patterns = {}) {
return EvaluateAttributeHelper(&arena_, container, key, receiver_style,
enable_unknown, use_recursive_impl,
patterns);
}
google::protobuf::Arena arena_;
};
TEST_P(ContainerAccessStepUniformityTest, TestListIndexAccess) {
ContainerBackedListImpl cel_list({CelValue::CreateInt64(1),
CelValue::CreateInt64(2),
CelValue::CreateInt64(3)});
CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(1),
receiver_style(), enable_unknown());
ASSERT_TRUE(result.IsInt64());
ASSERT_EQ(result.Int64OrDie(), 2);
}
TEST_P(ContainerAccessStepUniformityTest, TestListIndexAccessOutOfBounds) {
ContainerBackedListImpl cel_list({CelValue::CreateInt64(1),
CelValue::CreateInt64(2),
CelValue::CreateInt64(3)});
CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(0),
receiver_style(), enable_unknown());
ASSERT_TRUE(result.IsInt64());
result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(2), receiver_style(),
enable_unknown());
ASSERT_TRUE(result.IsInt64());
result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(-1), receiver_style(),
enable_unknown());
ASSERT_TRUE(result.IsError());
result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(3), receiver_style(),
enable_unknown());
ASSERT_TRUE(result.IsError());
}
TEST_P(ContainerAccessStepUniformityTest, TestListIndexAccessNotAnInt) {
ContainerBackedListImpl cel_list({CelValue::CreateInt64(1),
CelValue::CreateInt64(2),
CelValue::CreateInt64(3)});
CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateUint64(1),
receiver_style(), enable_unknown());
ASSERT_TRUE(result.IsError());
}
TEST_P(ContainerAccessStepUniformityTest, TestMapKeyAccess) {
const std::string kKey0 = "testkey0";
const std::string kKey1 = "testkey1";
const std::string kKey2 = "testkey2";
Struct cel_struct;
(*cel_struct.mutable_fields())[kKey0].set_string_value("value0");
(*cel_struct.mutable_fields())[kKey1].set_string_value("value1");
(*cel_struct.mutable_fields())[kKey2].set_string_value("value2");
CelValue result = EvaluateAttribute(
CelProtoWrapper::CreateMessage(&cel_struct, &arena_),
CelValue::CreateString(&kKey0), receiver_style(), enable_unknown());
ASSERT_TRUE(result.IsString());
ASSERT_EQ(result.StringOrDie().value(), "value0");
}
TEST_P(ContainerAccessStepUniformityTest, TestBoolKeyType) {
CelMapBuilder cel_map;
ASSERT_OK(cel_map.Add(CelValue::CreateBool(true),
CelValue::CreateStringView("value_true")));
CelValue result = EvaluateAttribute(CelValue::CreateMap(&cel_map),
CelValue::CreateBool(true),
receiver_style(), enable_unknown());
ASSERT_THAT(result, test::IsCelString("value_true"));
}
TEST_P(ContainerAccessStepUniformityTest, TestMapKeyAccessNotFound) {
const std::string kKey0 = "testkey0";
const std::string kKey1 = "testkey1";
Struct cel_struct;
(*cel_struct.mutable_fields())[kKey0].set_string_value("value0");
CelValue result = EvaluateAttribute(
CelProtoWrapper::CreateMessage(&cel_struct, &arena_),
CelValue::CreateString(&kKey1), receiver_style(), enable_unknown());
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(),
StatusIs(absl::StatusCode::kNotFound,
AllOf(HasSubstr("Key not found in map : "),
HasSubstr("testkey1"))));
}
TEST_F(ContainerAccessStepTest, TestInvalidReceiverCreateContainerAccessStep) {
Expr expr;
auto& call = expr.mutable_call_expr();
call.set_function(cel::builtin::kIndex);
Expr& container_expr = call.mutable_target();
container_expr.mutable_ident_expr().set_name("container");
call.mutable_args().reserve(2);
Expr& key_expr = call.mutable_args().emplace_back();
key_expr.mutable_ident_expr().set_name("key");
Expr& extra_arg = call.mutable_args().emplace_back();
extra_arg.mutable_const_expr().set_bool_value(true);
EXPECT_THAT(CreateContainerAccessStep(call, 0).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid argument count")));
}
TEST_F(ContainerAccessStepTest, TestInvalidGlobalCreateContainerAccessStep) {
Expr expr;
auto& call = expr.mutable_call_expr();
call.set_function(cel::builtin::kIndex);
call.mutable_args().reserve(3);
Expr& container_expr = call.mutable_args().emplace_back();
container_expr.mutable_ident_expr().set_name("container");
Expr& key_expr = call.mutable_args().emplace_back();
key_expr.mutable_ident_expr().set_name("key");
Expr& extra_arg = call.mutable_args().emplace_back();
extra_arg.mutable_const_expr().set_bool_value(true);
EXPECT_THAT(CreateContainerAccessStep(call, 0).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid argument count")));
}
TEST_F(ContainerAccessStepTest, TestListIndexAccessUnknown) {
ContainerBackedListImpl cel_list({CelValue::CreateInt64(1),
CelValue::CreateInt64(2),
CelValue::CreateInt64(3)});
CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(1), true, true, {});
ASSERT_TRUE(result.IsInt64());
ASSERT_EQ(result.Int64OrDie(), 2);
std::vector<CelAttributePattern> patterns = {CelAttributePattern(
"container",
{CreateCelAttributeQualifierPattern(CelValue::CreateInt64(1))})};
result =
EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateInt64(1), true, true, false, patterns);
ASSERT_TRUE(result.IsUnknownSet());
}
TEST_F(ContainerAccessStepTest, TestListUnknownKey) {
ContainerBackedListImpl cel_list({CelValue::CreateInt64(1),
CelValue::CreateInt64(2),
CelValue::CreateInt64(3)});
UnknownSet unknown_set;
CelValue result =
EvaluateAttribute(CelValue::CreateList(&cel_list),
CelValue::CreateUnknownSet(&unknown_set), true, true);
ASSERT_TRUE(result.IsUnknownSet());
}
TEST_F(ContainerAccessStepTest, TestMapInvalidKey) {
const std::string kKey0 = "testkey0";
const std::string kKey1 = "testkey1";
const std::string kKey2 = "testkey2";
Struct cel_struct;
(*cel_struct.mutable_fields())[kKey0].set_string_value("value0");
(*cel_struct.mutable_fields())[kKey1].set_string_value("value1");
(*cel_struct.mutable_fields())[kKey2].set_string_value("value2");
CelValue result =
EvaluateAttribute(CelProtoWrapper::CreateMessage(&cel_struct, &arena_),
CelValue::CreateDouble(1.0), true, true);
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid map key type: 'double'")));
}
TEST_F(ContainerAccessStepTest, TestMapUnknownKey) {
const std::string kKey0 = "testkey0";
const std::string kKey1 = "testkey1";
const std::string kKey2 = "testkey2";
Struct cel_struct;
(*cel_struct.mutable_fields())[kKey0].set_string_value("value0");
(*cel_struct.mutable_fields())[kKey1].set_string_value("value1");
(*cel_struct.mutable_fields())[kKey2].set_string_value("value2");
UnknownSet unknown_set;
CelValue result =
EvaluateAttribute(CelProtoWrapper::CreateMessage(&cel_struct, &arena_),
CelValue::CreateUnknownSet(&unknown_set), true, true);
ASSERT_TRUE(result.IsUnknownSet());
}
TEST_F(ContainerAccessStepTest, TestUnknownContainer) {
UnknownSet unknown_set;
CelValue result = EvaluateAttribute(CelValue::CreateUnknownSet(&unknown_set),
CelValue::CreateInt64(1), true, true);
ASSERT_TRUE(result.IsUnknownSet());
}
TEST_F(ContainerAccessStepTest, TestInvalidContainerType) {
CelValue result = EvaluateAttribute(CelValue::CreateInt64(1),
CelValue::CreateInt64(0), true, true);
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid container type: 'int")));
}
INSTANTIATE_TEST_SUITE_P(
CombinedContainerTest, ContainerAccessStepUniformityTest,
testing::Combine( testing::Bool(),
testing::Bool(),
testing::Bool()));
class ContainerAccessHeterogeneousLookupsTest : public testing::Test {
public:
ContainerAccessHeterogeneousLookupsTest() {
options_.enable_heterogeneous_equality = true;
builder_ = CreateCelExpressionBuilder(options_);
}
protected:
InterpreterOptions options_;
std::unique_ptr<CelExpressionBuilder> builder_;
google::protobuf::Arena arena_;
Activation activation_;
};
TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleMapKeyInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.0]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelInt64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleMapKeyNotAnInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.1]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleMapKeyUint) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1.0]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelUint64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleListIndex) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.0]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelInt64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleListIndexNotAnInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.1]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, UintKeyAsUint) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u, 1: 2}[1u]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelUint64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, UintKeyAsInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1u]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelInt64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, IntKeyAsUint) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelUint64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, UintListIndex) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][2u]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelInt64(3));
}
TEST_F(ContainerAccessHeterogeneousLookupsTest, StringKeyUnaffected) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2, '1': 3}['1']"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelInt64(3));
}
class ContainerAccessHeterogeneousLookupsDisabledTest : public testing::Test {
public:
ContainerAccessHeterogeneousLookupsDisabledTest() {
options_.enable_heterogeneous_equality = false;
builder_ = CreateCelExpressionBuilder(options_);
}
protected:
InterpreterOptions options_;
std::unique_ptr<CelExpressionBuilder> builder_;
google::protobuf::Arena arena_;
Activation activation_;
};
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleMapKeyInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.0]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleMapKeyNotAnInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.1]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleMapKeyUint) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1.0]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleListIndex) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.0]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest,
DoubleListIndexNotAnInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.1]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, UintKeyAsUint) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u, 1: 2}[1u]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelUint64(2));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, UintKeyAsInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1u]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, IntKeyAsUint) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, UintListIndex) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][2u]"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelError(_));
}
TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, StringKeyUnaffected) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2, '1': 3}['1']"));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression(
&expr.expr(), &expr.source_info()));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation_, &arena_));
EXPECT_THAT(result, test::IsCelInt64(3));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/container_access_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/container_access_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
549e11be-6e45-424a-9e28-1f27ebc88b6f | cpp | google/cel-cpp | attribute_utility | eval/eval/attribute_utility.cc | eval/eval/attribute_utility_test.cc | #include "eval/eval/attribute_utility.h"
#include <cstdint>
#include <string>
#include <utility>
#include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "base/attribute.h"
#include "base/attribute_set.h"
#include "base/function_descriptor.h"
#include "base/function_result.h"
#include "base/function_result_set.h"
#include "base/internal/unknown_set.h"
#include "common/casting.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/internal/errors.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
using ::cel::AttributeSet;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::FunctionResult;
using ::cel::FunctionResultSet;
using ::cel::InstanceOf;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::base_internal::UnknownSet;
using Accumulator = AttributeUtility::Accumulator;
bool AttributeUtility::CheckForMissingAttribute(
const AttributeTrail& trail) const {
if (trail.empty()) {
return false;
}
for (const auto& pattern : missing_attribute_patterns_) {
if (pattern.IsMatch(trail.attribute()) ==
cel::AttributePattern::MatchType::FULL) {
return true;
}
}
return false;
}
bool AttributeUtility::CheckForUnknown(const AttributeTrail& trail,
bool use_partial) const {
if (trail.empty()) {
return false;
}
for (const auto& pattern : unknown_patterns_) {
auto current_match = pattern.IsMatch(trail.attribute());
if (current_match == cel::AttributePattern::MatchType::FULL ||
(use_partial &&
current_match == cel::AttributePattern::MatchType::PARTIAL)) {
return true;
}
}
return false;
}
absl::optional<UnknownValue> AttributeUtility::MergeUnknowns(
absl::Span<const cel::Value> args) const {
absl::optional<UnknownSet> result_set;
for (const auto& value : args) {
if (!value->Is<cel::UnknownValue>()) continue;
if (!result_set.has_value()) {
result_set.emplace();
}
const auto& current_set = value.GetUnknown();
cel::base_internal::UnknownSetAccess::Add(
*result_set, UnknownSet(current_set.attribute_set(),
current_set.function_result_set()));
}
if (!result_set.has_value()) {
return absl::nullopt;
}
return value_factory_.CreateUnknownValue(
result_set->unknown_attributes(), result_set->unknown_function_results());
}
UnknownValue AttributeUtility::MergeUnknownValues(
const UnknownValue& left, const UnknownValue& right) const {
AttributeSet attributes;
FunctionResultSet function_results;
attributes.Add(left.attribute_set());
function_results.Add(left.function_result_set());
attributes.Add(right.attribute_set());
function_results.Add(right.function_result_set());
return value_factory_.CreateUnknownValue(std::move(attributes),
std::move(function_results));
}
AttributeSet AttributeUtility::CheckForUnknowns(
absl::Span<const AttributeTrail> args, bool use_partial) const {
AttributeSet attribute_set;
for (const auto& trail : args) {
if (CheckForUnknown(trail, use_partial)) {
attribute_set.Add(trail.attribute());
}
}
return attribute_set;
}
absl::optional<UnknownValue> AttributeUtility::IdentifyAndMergeUnknowns(
absl::Span<const cel::Value> args, absl::Span<const AttributeTrail> attrs,
bool use_partial) const {
absl::optional<UnknownSet> result_set;
cel::AttributeSet attr_set = CheckForUnknowns(attrs, use_partial);
if (!attr_set.empty()) {
result_set.emplace(std::move(attr_set));
}
absl::optional<UnknownValue> arg_unknowns = MergeUnknowns(args);
if (!result_set.has_value()) {
return arg_unknowns;
}
if (arg_unknowns.has_value()) {
cel::base_internal::UnknownSetAccess::Add(
*result_set, UnknownSet((*arg_unknowns).attribute_set(),
(*arg_unknowns).function_result_set()));
}
return value_factory_.CreateUnknownValue(
result_set->unknown_attributes(), result_set->unknown_function_results());
}
UnknownValue AttributeUtility::CreateUnknownSet(cel::Attribute attr) const {
return value_factory_.CreateUnknownValue(AttributeSet({std::move(attr)}));
}
absl::StatusOr<ErrorValue> AttributeUtility::CreateMissingAttributeError(
const cel::Attribute& attr) const {
CEL_ASSIGN_OR_RETURN(std::string message, attr.AsString());
return value_factory_.CreateErrorValue(
cel::runtime_internal::CreateMissingAttributeError(message));
}
UnknownValue AttributeUtility::CreateUnknownSet(
const cel::FunctionDescriptor& fn_descriptor, int64_t expr_id,
absl::Span<const cel::Value> args) const {
return value_factory_.CreateUnknownValue(
FunctionResultSet(FunctionResult(fn_descriptor, expr_id)));
}
void AttributeUtility::Add(Accumulator& a, const cel::UnknownValue& v) const {
a.attribute_set_.Add(v.attribute_set());
a.function_result_set_.Add(v.function_result_set());
}
void AttributeUtility::Add(Accumulator& a, const AttributeTrail& attr) const {
a.attribute_set_.Add(attr.attribute());
}
void Accumulator::Add(const UnknownValue& value) {
unknown_present_ = true;
parent_.Add(*this, value);
}
void Accumulator::Add(const AttributeTrail& attr) { parent_.Add(*this, attr); }
void Accumulator::MaybeAdd(const Value& v) {
if (InstanceOf<UnknownValue>(v)) {
Add(Cast<UnknownValue>(v));
}
}
bool Accumulator::IsEmpty() const {
return !unknown_present_ && attribute_set_.empty() &&
function_result_set_.empty();
}
cel::UnknownValue Accumulator::Build() && {
return parent_.value_manager().CreateUnknownValue(
std::move(attribute_set_), std::move(function_result_set_));
}
} | #include "eval/eval/attribute_utility.h"
#include <vector>
#include "base/attribute_set.h"
#include "base/type_provider.h"
#include "common/type_factory.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_value.h"
#include "eval/public/unknown_attribute_set.h"
#include "eval/public/unknown_set.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
using ::cel::AttributeSet;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::testing::Eq;
using ::testing::SizeIs;
using ::testing::UnorderedPointwise;
class AttributeUtilityTest : public ::testing::Test {
public:
AttributeUtilityTest()
: value_factory_(ProtoMemoryManagerRef(&arena_),
cel::TypeProvider::Builtin()) {}
protected:
google::protobuf::Arena arena_;
cel::common_internal::LegacyValueManager value_factory_;
};
TEST_F(AttributeUtilityTest, UnknownsUtilityCheckUnknowns) {
std::vector<CelAttributePattern> unknown_patterns = {
CelAttributePattern("unknown0", {CreateCelAttributeQualifierPattern(
CelValue::CreateInt64(1))}),
CelAttributePattern("unknown0", {CreateCelAttributeQualifierPattern(
CelValue::CreateInt64(2))}),
CelAttributePattern("unknown1", {}),
CelAttributePattern("unknown2", {}),
};
std::vector<CelAttributePattern> missing_attribute_patterns;
AttributeUtility utility(unknown_patterns, missing_attribute_patterns,
value_factory_);
ASSERT_FALSE(utility.CheckForUnknown(AttributeTrail(), true));
ASSERT_FALSE(utility.CheckForUnknown(AttributeTrail(), false));
AttributeTrail unknown_trail0("unknown0");
{ ASSERT_FALSE(utility.CheckForUnknown(unknown_trail0, false)); }
{ ASSERT_TRUE(utility.CheckForUnknown(unknown_trail0, true)); }
{
ASSERT_TRUE(utility.CheckForUnknown(
unknown_trail0.Step(
CreateCelAttributeQualifier(CelValue::CreateInt64(1))),
false));
}
{
ASSERT_TRUE(utility.CheckForUnknown(
unknown_trail0.Step(
CreateCelAttributeQualifier(CelValue::CreateInt64(1))),
true));
}
}
TEST_F(AttributeUtilityTest, UnknownsUtilityMergeUnknownsFromValues) {
std::vector<CelAttributePattern> unknown_patterns;
std::vector<CelAttributePattern> missing_attribute_patterns;
CelAttribute attribute0("unknown0", {});
CelAttribute attribute1("unknown1", {});
AttributeUtility utility(unknown_patterns, missing_attribute_patterns,
value_factory_);
UnknownValue unknown_set0 =
value_factory_.CreateUnknownValue(AttributeSet({attribute0}));
UnknownValue unknown_set1 =
value_factory_.CreateUnknownValue(AttributeSet({attribute1}));
std::vector<cel::Value> values = {
unknown_set0,
unknown_set1,
value_factory_.CreateBoolValue(true),
value_factory_.CreateIntValue(1),
};
absl::optional<UnknownValue> unknown_set = utility.MergeUnknowns(values);
ASSERT_TRUE(unknown_set.has_value());
EXPECT_THAT((*unknown_set).attribute_set(),
UnorderedPointwise(
Eq(), std::vector<CelAttribute>{attribute0, attribute1}));
}
TEST_F(AttributeUtilityTest, UnknownsUtilityCheckForUnknownsFromAttributes) {
std::vector<CelAttributePattern> unknown_patterns = {
CelAttributePattern("unknown0",
{CelAttributeQualifierPattern::CreateWildcard()}),
};
std::vector<CelAttributePattern> missing_attribute_patterns;
AttributeTrail trail0("unknown0");
AttributeTrail trail1("unknown1");
CelAttribute attribute1("unknown1", {});
UnknownSet unknown_set1(UnknownAttributeSet({attribute1}));
AttributeUtility utility(unknown_patterns, missing_attribute_patterns,
value_factory_);
UnknownSet unknown_attr_set(utility.CheckForUnknowns(
{
AttributeTrail(),
trail0.Step(CreateCelAttributeQualifier(CelValue::CreateInt64(1))),
trail0.Step(CreateCelAttributeQualifier(CelValue::CreateInt64(2))),
},
false));
UnknownSet unknown_set(unknown_set1, unknown_attr_set);
ASSERT_THAT(unknown_set.unknown_attributes(), SizeIs(3));
}
TEST_F(AttributeUtilityTest, UnknownsUtilityCheckForMissingAttributes) {
std::vector<CelAttributePattern> unknown_patterns;
std::vector<CelAttributePattern> missing_attribute_patterns;
AttributeTrail trail("destination");
trail =
trail.Step(CreateCelAttributeQualifier(CelValue::CreateStringView("ip")));
AttributeUtility utility0(unknown_patterns, missing_attribute_patterns,
value_factory_);
EXPECT_FALSE(utility0.CheckForMissingAttribute(trail));
missing_attribute_patterns.push_back(CelAttributePattern(
"destination",
{CreateCelAttributeQualifierPattern(CelValue::CreateStringView("ip"))}));
AttributeUtility utility1(unknown_patterns, missing_attribute_patterns,
value_factory_);
EXPECT_TRUE(utility1.CheckForMissingAttribute(trail));
}
TEST_F(AttributeUtilityTest, CreateUnknownSet) {
AttributeTrail trail("destination");
trail =
trail.Step(CreateCelAttributeQualifier(CelValue::CreateStringView("ip")));
std::vector<CelAttributePattern> empty_patterns;
AttributeUtility utility(empty_patterns, empty_patterns, value_factory_);
UnknownValue set = utility.CreateUnknownSet(trail.attribute());
ASSERT_THAT(set.attribute_set(), SizeIs(1));
ASSERT_OK_AND_ASSIGN(auto elem, set.attribute_set().begin()->AsString());
EXPECT_EQ(elem, "destination.ip");
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/attribute_utility.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/attribute_utility_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5faa292a-7336-44ec-befc-743505f72bdc | cpp | google/cel-cpp | lazy_init_step | eval/eval/lazy_init_step.cc | eval/eval/lazy_init_step_test.cc | #include "eval/eval/lazy_init_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include "google/api/expr/v1alpha1/value.pb.h"
#include "absl/base/nullability.h"
#include "absl/status/status.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Value;
class LazyInitStep final : public ExpressionStepBase {
public:
LazyInitStep(size_t slot_index, size_t subexpression_index, int64_t expr_id)
: ExpressionStepBase(expr_id),
slot_index_(slot_index),
subexpression_index_(subexpression_index) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
if (auto* slot = frame->comprehension_slots().Get(slot_index_);
slot != nullptr) {
frame->value_stack().Push(slot->value, slot->attribute);
} else {
frame->Call(slot_index_, subexpression_index_);
}
return absl::OkStatus();
}
private:
const size_t slot_index_;
const size_t subexpression_index_;
};
class DirectLazyInitStep final : public DirectExpressionStep {
public:
DirectLazyInitStep(size_t slot_index,
const DirectExpressionStep* subexpression, int64_t expr_id)
: DirectExpressionStep(expr_id),
slot_index_(slot_index),
subexpression_(subexpression) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override {
if (auto* slot = frame.comprehension_slots().Get(slot_index_);
slot != nullptr) {
result = slot->value;
attribute = slot->attribute;
} else {
CEL_RETURN_IF_ERROR(subexpression_->Evaluate(frame, result, attribute));
frame.comprehension_slots().Set(slot_index_, result, attribute);
}
return absl::OkStatus();
}
private:
const size_t slot_index_;
const absl::Nonnull<const DirectExpressionStep*> subexpression_;
};
class BindStep : public DirectExpressionStep {
public:
BindStep(size_t slot_index,
std::unique_ptr<DirectExpressionStep> subexpression, int64_t expr_id)
: DirectExpressionStep(expr_id),
slot_index_(slot_index),
subexpression_(std::move(subexpression)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override {
CEL_RETURN_IF_ERROR(subexpression_->Evaluate(frame, result, attribute));
frame.comprehension_slots().ClearSlot(slot_index_);
return absl::OkStatus();
}
private:
size_t slot_index_;
std::unique_ptr<DirectExpressionStep> subexpression_;
};
class AssignSlotAndPopStepStep final : public ExpressionStepBase {
public:
explicit AssignSlotAndPopStepStep(size_t slot_index)
: ExpressionStepBase(-1, false),
slot_index_(slot_index) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
if (!frame->value_stack().HasEnough(1)) {
return absl::InternalError("Stack underflow assigning lazy value");
}
frame->comprehension_slots().Set(slot_index_, frame->value_stack().Peek(),
frame->value_stack().PeekAttribute());
frame->value_stack().Pop(1);
return absl::OkStatus();
}
private:
const size_t slot_index_;
};
class ClearSlotStep : public ExpressionStepBase {
public:
explicit ClearSlotStep(size_t slot_index, int64_t expr_id)
: ExpressionStepBase(expr_id), slot_index_(slot_index) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
frame->comprehension_slots().ClearSlot(slot_index_);
return absl::OkStatus();
}
private:
size_t slot_index_;
};
class ClearSlotsStep final : public ExpressionStepBase {
public:
explicit ClearSlotsStep(size_t slot_index, size_t slot_count, int64_t expr_id)
: ExpressionStepBase(expr_id),
slot_index_(slot_index),
slot_count_(slot_count) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
for (size_t i = 0; i < slot_count_; ++i) {
frame->comprehension_slots().ClearSlot(slot_index_ + i);
}
return absl::OkStatus();
}
private:
const size_t slot_index_;
const size_t slot_count_;
};
}
std::unique_ptr<DirectExpressionStep> CreateDirectBindStep(
size_t slot_index, std::unique_ptr<DirectExpressionStep> expression,
int64_t expr_id) {
return std::make_unique<BindStep>(slot_index, std::move(expression), expr_id);
}
std::unique_ptr<DirectExpressionStep> CreateDirectLazyInitStep(
size_t slot_index, absl::Nonnull<const DirectExpressionStep*> subexpression,
int64_t expr_id) {
return std::make_unique<DirectLazyInitStep>(slot_index, subexpression,
expr_id);
}
std::unique_ptr<ExpressionStep> CreateLazyInitStep(size_t slot_index,
size_t subexpression_index,
int64_t expr_id) {
return std::make_unique<LazyInitStep>(slot_index, subexpression_index,
expr_id);
}
std::unique_ptr<ExpressionStep> CreateAssignSlotAndPopStep(size_t slot_index) {
return std::make_unique<AssignSlotAndPopStepStep>(slot_index);
}
std::unique_ptr<ExpressionStep> CreateClearSlotStep(size_t slot_index,
int64_t expr_id) {
return std::make_unique<ClearSlotStep>(slot_index, expr_id);
}
std::unique_ptr<ExpressionStep> CreateClearSlotsStep(size_t slot_index,
size_t slot_count,
int64_t expr_id) {
ABSL_DCHECK_GT(slot_count, 0);
return std::make_unique<ClearSlotsStep>(slot_index, slot_count, expr_id);
}
} | #include "eval/eval/lazy_init_step.h"
#include <cstddef>
#include <vector>
#include "base/type_provider.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/evaluator_core.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Activation;
using ::cel::IntValue;
using ::cel::ManagedValueFactory;
using ::cel::RuntimeOptions;
using ::cel::TypeProvider;
using ::cel::ValueManager;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::testing::IsNull;
class LazyInitStepTest : public testing::Test {
private:
static constexpr size_t kValueStack = 5;
static constexpr size_t kComprehensionSlotCount = 3;
public:
LazyInitStepTest()
: value_factory_(TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)),
evaluator_state_(kValueStack, kComprehensionSlotCount,
value_factory_.get()) {}
protected:
ValueManager& value_factory() { return value_factory_.get(); };
google::protobuf::Arena arena_;
ManagedValueFactory value_factory_;
FlatExpressionEvaluatorState evaluator_state_;
RuntimeOptions runtime_options_;
Activation activation_;
};
TEST_F(LazyInitStepTest, CreateCheckInitStepDoesInit) {
ExecutionPath path;
ExecutionPath subpath;
path.push_back(CreateLazyInitStep(0,
1, -1));
ASSERT_OK_AND_ASSIGN(
subpath.emplace_back(),
CreateConstValueStep(value_factory().CreateIntValue(42), -1, false));
std::vector<ExecutionPathView> expression_table{path, subpath};
ExecutionFrame frame(expression_table, activation_, runtime_options_,
evaluator_state_);
ASSERT_OK_AND_ASSIGN(auto value, frame.Evaluate());
EXPECT_TRUE(value->Is<IntValue>() && value.GetInt().NativeValue() == 42);
}
TEST_F(LazyInitStepTest, CreateCheckInitStepSkipInit) {
ExecutionPath path;
ExecutionPath subpath;
path.push_back(CreateLazyInitStep(0, -1, -1));
ASSERT_OK_AND_ASSIGN(
subpath.emplace_back(),
CreateConstValueStep(value_factory().CreateIntValue(42), -1, false));
std::vector<ExecutionPathView> expression_table{path, subpath};
ExecutionFrame frame(expression_table, activation_, runtime_options_,
evaluator_state_);
frame.comprehension_slots().Set(0, value_factory().CreateIntValue(42));
ASSERT_OK_AND_ASSIGN(auto value, frame.Evaluate());
EXPECT_TRUE(value->Is<IntValue>() && value.GetInt().NativeValue() == 42);
}
TEST_F(LazyInitStepTest, CreateAssignSlotAndPopStepBasic) {
ExecutionPath path;
path.push_back(CreateAssignSlotAndPopStep(0));
ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_);
frame.comprehension_slots().ClearSlot(0);
frame.value_stack().Push(value_factory().CreateIntValue(42));
frame.Evaluate().IgnoreError();
auto* slot = frame.comprehension_slots().Get(0);
ASSERT_TRUE(slot != nullptr);
EXPECT_TRUE(slot->value->Is<IntValue>() &&
slot->value.GetInt().NativeValue() == 42);
EXPECT_TRUE(frame.value_stack().empty());
}
TEST_F(LazyInitStepTest, CreateClearSlotStepBasic) {
ExecutionPath path;
path.push_back(CreateClearSlotStep(0, -1));
ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_);
frame.comprehension_slots().Set(0, value_factory().CreateIntValue(42));
frame.Evaluate().IgnoreError();
auto* slot = frame.comprehension_slots().Get(0);
ASSERT_TRUE(slot == nullptr);
}
TEST_F(LazyInitStepTest, CreateClearSlotsStepBasic) {
ExecutionPath path;
path.push_back(CreateClearSlotsStep(0, 2, -1));
ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_);
frame.comprehension_slots().Set(0, value_factory().CreateIntValue(42));
frame.comprehension_slots().Set(1, value_factory().CreateIntValue(42));
frame.Evaluate().IgnoreError();
EXPECT_THAT(frame.comprehension_slots().Get(0), IsNull());
EXPECT_THAT(frame.comprehension_slots().Get(1), IsNull());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/lazy_init_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/lazy_init_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
4a87b44a-4717-441e-a13c-b109bc1d14e6 | cpp | google/cel-cpp | create_struct_step | eval/eval/create_struct_step.cc | eval/eval/create_struct_step_test.cc | #include "eval/eval/create_struct_step.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/casting.h"
#include "common/memory.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::StructValueBuilderInterface;
using ::cel::UnknownValue;
using ::cel::Value;
class CreateStructStepForStruct final : public ExpressionStepBase {
public:
CreateStructStepForStruct(int64_t expr_id, std::string name,
std::vector<std::string> entries,
absl::flat_hash_set<int32_t> optional_indices)
: ExpressionStepBase(expr_id),
name_(std::move(name)),
entries_(std::move(entries)),
optional_indices_(std::move(optional_indices)) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
absl::StatusOr<Value> DoEvaluate(ExecutionFrame* frame) const;
std::string name_;
std::vector<std::string> entries_;
absl::flat_hash_set<int32_t> optional_indices_;
};
absl::StatusOr<Value> CreateStructStepForStruct::DoEvaluate(
ExecutionFrame* frame) const {
int entries_size = entries_.size();
auto args = frame->value_stack().GetSpan(entries_size);
if (frame->enable_unknowns()) {
absl::optional<UnknownValue> unknown_set =
frame->attribute_utility().IdentifyAndMergeUnknowns(
args, frame->value_stack().GetAttributeSpan(entries_size),
true);
if (unknown_set.has_value()) {
return *unknown_set;
}
}
auto builder_or_status = frame->value_manager().NewValueBuilder(name_);
if (!builder_or_status.ok()) {
return builder_or_status.status();
}
auto maybe_builder = std::move(*builder_or_status);
if (!maybe_builder.has_value()) {
return absl::NotFoundError(absl::StrCat("Unable to find builder: ", name_));
}
auto builder = std::move(*maybe_builder);
for (int i = 0; i < entries_size; ++i) {
const auto& entry = entries_[i];
auto& arg = args[i];
if (optional_indices_.contains(static_cast<int32_t>(i))) {
if (auto optional_arg = cel::As<cel::OptionalValue>(arg); optional_arg) {
if (!optional_arg->HasValue()) {
continue;
}
CEL_RETURN_IF_ERROR(
builder->SetFieldByName(entry, optional_arg->Value()));
}
} else {
CEL_RETURN_IF_ERROR(builder->SetFieldByName(entry, std::move(arg)));
}
}
return std::move(*builder).Build();
}
absl::Status CreateStructStepForStruct::Evaluate(ExecutionFrame* frame) const {
if (frame->value_stack().size() < entries_.size()) {
return absl::InternalError("CreateStructStepForStruct: stack underflow");
}
Value result;
auto status_or_result = DoEvaluate(frame);
if (status_or_result.ok()) {
result = std::move(status_or_result).value();
} else {
result = frame->value_factory().CreateErrorValue(status_or_result.status());
}
frame->value_stack().PopAndPush(entries_.size(), std::move(result));
return absl::OkStatus();
}
class DirectCreateStructStep : public DirectExpressionStep {
public:
DirectCreateStructStep(
int64_t expr_id, std::string name, std::vector<std::string> field_keys,
std::vector<std::unique_ptr<DirectExpressionStep>> deps,
absl::flat_hash_set<int32_t> optional_indices)
: DirectExpressionStep(expr_id),
name_(std::move(name)),
field_keys_(std::move(field_keys)),
deps_(std::move(deps)),
optional_indices_(std::move(optional_indices)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& trail) const override;
private:
std::string name_;
std::vector<std::string> field_keys_;
std::vector<std::unique_ptr<DirectExpressionStep>> deps_;
absl::flat_hash_set<int32_t> optional_indices_;
};
absl::Status DirectCreateStructStep::Evaluate(ExecutionFrameBase& frame,
Value& result,
AttributeTrail& trail) const {
Value field_value;
AttributeTrail field_attr;
auto unknowns = frame.attribute_utility().CreateAccumulator();
auto builder_or_status = frame.value_manager().NewValueBuilder(name_);
if (!builder_or_status.ok()) {
result = frame.value_manager().CreateErrorValue(builder_or_status.status());
return absl::OkStatus();
}
if (!builder_or_status->has_value()) {
result = frame.value_manager().CreateErrorValue(
absl::NotFoundError(absl::StrCat("Unable to find builder: ", name_)));
return absl::OkStatus();
}
auto& builder = **builder_or_status;
for (int i = 0; i < field_keys_.size(); i++) {
CEL_RETURN_IF_ERROR(deps_[i]->Evaluate(frame, field_value, field_attr));
if (InstanceOf<ErrorValue>(field_value)) {
result = std::move(field_value);
return absl::OkStatus();
}
if (frame.unknown_processing_enabled()) {
if (InstanceOf<UnknownValue>(field_value)) {
unknowns.Add(Cast<UnknownValue>(field_value));
} else if (frame.attribute_utility().CheckForUnknownPartial(field_attr)) {
unknowns.Add(field_attr);
}
}
if (!unknowns.IsEmpty()) {
continue;
}
if (optional_indices_.contains(static_cast<int32_t>(i))) {
if (auto optional_arg = cel::As<cel::OptionalValue>(
static_cast<const Value&>(field_value));
optional_arg) {
if (!optional_arg->HasValue()) {
continue;
}
auto status =
builder->SetFieldByName(field_keys_[i], optional_arg->Value());
if (!status.ok()) {
result = frame.value_manager().CreateErrorValue(std::move(status));
return absl::OkStatus();
}
}
continue;
}
auto status =
builder->SetFieldByName(field_keys_[i], std::move(field_value));
if (!status.ok()) {
result = frame.value_manager().CreateErrorValue(std::move(status));
return absl::OkStatus();
}
}
if (!unknowns.IsEmpty()) {
result = std::move(unknowns).Build();
return absl::OkStatus();
}
result = std::move(*builder).Build();
return absl::OkStatus();
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectCreateStructStep(
std::string resolved_name, std::vector<std::string> field_keys,
std::vector<std::unique_ptr<DirectExpressionStep>> deps,
absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) {
return std::make_unique<DirectCreateStructStep>(
expr_id, std::move(resolved_name), std::move(field_keys), std::move(deps),
std::move(optional_indices));
}
std::unique_ptr<ExpressionStep> CreateCreateStructStep(
std::string name, std::vector<std::string> field_keys,
absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) {
return std::make_unique<CreateStructStepForStruct>(
expr_id, std::move(name), std::move(field_keys),
std::move(optional_indices));
}
} | #include "eval/eval/create_struct_step.h"
#include <cstdint>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "base/ast_internal/expr.h"
#include "base/type_provider.h"
#include "common/values/legacy_value_manager.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_type_registry.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include "eval/public/unknown_set.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/proto_matchers.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::TypeProvider;
using ::cel::ast_internal::Expr;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::internal::test::EqualsProto;
using ::google::protobuf::Arena;
using ::google::protobuf::Message;
using ::testing::Eq;
using ::testing::IsNull;
using ::testing::Not;
using ::testing::Pointwise;
absl::StatusOr<ExecutionPath> MakeStackMachinePath(absl::string_view field) {
ExecutionPath path;
Expr expr0;
auto& ident = expr0.mutable_ident_expr();
ident.set_name("message");
CEL_ASSIGN_OR_RETURN(auto step0, CreateIdentStep(ident, expr0.id()));
auto step1 = CreateCreateStructStep("google.api.expr.runtime.TestMessage",
{std::string(field)},
{},
-1);
path.push_back(std::move(step0));
path.push_back(std::move(step1));
return path;
}
absl::StatusOr<ExecutionPath> MakeRecursivePath(absl::string_view field) {
ExecutionPath path;
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateDirectIdentStep("message", -1));
auto step1 =
CreateDirectCreateStructStep("google.api.expr.runtime.TestMessage",
{std::string(field)}, std::move(deps),
{},
-1);
path.push_back(std::make_unique<WrappedDirectStep>(std::move(step1), -1));
return path;
}
absl::StatusOr<CelValue> RunExpression(absl::string_view field,
const CelValue& value,
google::protobuf::Arena* arena,
bool enable_unknowns,
bool enable_recursive_planning) {
CelTypeRegistry type_registry;
type_registry.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
auto memory_manager = ProtoMemoryManagerRef(arena);
cel::common_internal::LegacyValueManager type_manager(
memory_manager, type_registry.GetTypeProvider());
CEL_ASSIGN_OR_RETURN(
auto maybe_type,
type_manager.FindType("google.api.expr.runtime.TestMessage"));
if (!maybe_type.has_value()) {
return absl::Status(absl::StatusCode::kFailedPrecondition,
"missing proto message type");
}
cel::RuntimeOptions options;
if (enable_unknowns) {
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
}
ExecutionPath path;
if (enable_recursive_planning) {
CEL_ASSIGN_OR_RETURN(path, MakeRecursivePath(field));
} else {
CEL_ASSIGN_OR_RETURN(path, MakeStackMachinePath(field));
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
type_registry.GetTypeProvider(), options));
Activation activation;
activation.InsertValue("message", value);
return cel_expr.Evaluate(activation, arena);
}
void RunExpressionAndGetMessage(absl::string_view field, const CelValue& value,
google::protobuf::Arena* arena, TestMessage* test_msg,
bool enable_unknowns,
bool enable_recursive_planning) {
ASSERT_OK_AND_ASSIGN(auto result,
RunExpression(field, value, arena, enable_unknowns,
enable_recursive_planning));
ASSERT_TRUE(result.IsMessage()) << result.DebugString();
const Message* msg = result.MessageOrDie();
ASSERT_THAT(msg, Not(IsNull()));
ASSERT_EQ(msg->GetDescriptor(), TestMessage::descriptor());
test_msg->MergeFrom(*msg);
}
void RunExpressionAndGetMessage(absl::string_view field,
std::vector<CelValue> values,
google::protobuf::Arena* arena, TestMessage* test_msg,
bool enable_unknowns,
bool enable_recursive_planning) {
ContainerBackedListImpl cel_list(std::move(values));
CelValue value = CelValue::CreateList(&cel_list);
ASSERT_OK_AND_ASSIGN(auto result,
RunExpression(field, value, arena, enable_unknowns,
enable_recursive_planning));
ASSERT_TRUE(result.IsMessage()) << result.DebugString();
const Message* msg = result.MessageOrDie();
ASSERT_THAT(msg, Not(IsNull()));
ASSERT_EQ(msg->GetDescriptor(), TestMessage::descriptor());
test_msg->MergeFrom(*msg);
}
class CreateCreateStructStepTest
: public testing::TestWithParam<std::tuple<bool, bool>> {
public:
bool enable_unknowns() { return std::get<0>(GetParam()); }
bool enable_recursive_planning() { return std::get<1>(GetParam()); }
};
TEST_P(CreateCreateStructStepTest, TestEmptyMessageCreation) {
ExecutionPath path;
CelTypeRegistry type_registry;
type_registry.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
google::protobuf::Arena arena;
auto memory_manager = ProtoMemoryManagerRef(&arena);
cel::common_internal::LegacyValueManager type_manager(
memory_manager, type_registry.GetTypeProvider());
auto adapter =
type_registry.FindTypeAdapter("google.api.expr.runtime.TestMessage");
ASSERT_TRUE(adapter.has_value() && adapter->mutation_apis() != nullptr);
ASSERT_OK_AND_ASSIGN(
auto maybe_type,
type_manager.FindType("google.api.expr.runtime.TestMessage"));
ASSERT_TRUE(maybe_type.has_value());
if (enable_recursive_planning()) {
auto step =
CreateDirectCreateStructStep("google.api.expr.runtime.TestMessage",
{},
{},
{},
-1);
path.push_back(
std::make_unique<WrappedDirectStep>(std::move(step), -1));
} else {
auto step = CreateCreateStructStep("google.api.expr.runtime.TestMessage",
{},
{},
-1);
path.push_back(std::move(step));
}
cel::RuntimeOptions options;
if (enable_unknowns(), enable_recursive_planning()) {
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
type_registry.GetTypeProvider(), options));
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena));
ASSERT_TRUE(result.IsMessage()) << result.DebugString();
const Message* msg = result.MessageOrDie();
ASSERT_THAT(msg, Not(IsNull()));
ASSERT_EQ(msg->GetDescriptor(), TestMessage::descriptor());
}
TEST(CreateCreateStructStepTest, TestMessageCreateWithUnknown) {
Arena arena;
TestMessage test_msg;
UnknownSet unknown_set;
auto eval_status =
RunExpression("bool_value", CelValue::CreateUnknownSet(&unknown_set),
&arena, true, false);
ASSERT_OK(eval_status);
ASSERT_TRUE(eval_status->IsUnknownSet());
}
TEST(CreateCreateStructStepTest, TestMessageCreateWithUnknownRecursive) {
Arena arena;
TestMessage test_msg;
UnknownSet unknown_set;
auto eval_status =
RunExpression("bool_value", CelValue::CreateUnknownSet(&unknown_set),
&arena, true, true);
ASSERT_OK(eval_status);
ASSERT_TRUE(eval_status->IsUnknownSet()) << eval_status->DebugString();
}
TEST_P(CreateCreateStructStepTest, TestSetBoolField) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"bool_value", CelValue::CreateBool(true), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
ASSERT_EQ(test_msg.bool_value(), true);
}
TEST_P(CreateCreateStructStepTest, TestSetInt32Field) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"int32_value", CelValue::CreateInt64(1), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
ASSERT_EQ(test_msg.int32_value(), 1);
}
TEST_P(CreateCreateStructStepTest, TestSetUInt32Field) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"uint32_value", CelValue::CreateUint64(1), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
ASSERT_EQ(test_msg.uint32_value(), 1);
}
TEST_P(CreateCreateStructStepTest, TestSetInt64Field) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"int64_value", CelValue::CreateInt64(1), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
EXPECT_EQ(test_msg.int64_value(), 1);
}
TEST_P(CreateCreateStructStepTest, TestSetUInt64Field) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"uint64_value", CelValue::CreateUint64(1), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
EXPECT_EQ(test_msg.uint64_value(), 1);
}
TEST_P(CreateCreateStructStepTest, TestSetFloatField) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"float_value", CelValue::CreateDouble(2.0), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
EXPECT_DOUBLE_EQ(test_msg.float_value(), 2.0);
}
TEST_P(CreateCreateStructStepTest, TestSetDoubleField) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"double_value", CelValue::CreateDouble(2.0), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
EXPECT_DOUBLE_EQ(test_msg.double_value(), 2.0);
}
TEST_P(CreateCreateStructStepTest, TestSetStringField) {
const std::string kTestStr = "test";
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"string_value", CelValue::CreateString(&kTestStr), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
EXPECT_EQ(test_msg.string_value(), kTestStr);
}
TEST_P(CreateCreateStructStepTest, TestSetBytesField) {
Arena arena;
const std::string kTestStr = "test";
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"bytes_value", CelValue::CreateBytes(&kTestStr), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
EXPECT_EQ(test_msg.bytes_value(), kTestStr);
}
TEST_P(CreateCreateStructStepTest, TestSetDurationField) {
Arena arena;
google::protobuf::Duration test_duration;
test_duration.set_seconds(2);
test_duration.set_nanos(3);
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"duration_value", CelProtoWrapper::CreateDuration(&test_duration), &arena,
&test_msg, enable_unknowns(), enable_recursive_planning()));
EXPECT_THAT(test_msg.duration_value(), EqualsProto(test_duration));
}
TEST_P(CreateCreateStructStepTest, TestSetTimestampField) {
Arena arena;
google::protobuf::Timestamp test_timestamp;
test_timestamp.set_seconds(2);
test_timestamp.set_nanos(3);
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"timestamp_value", CelProtoWrapper::CreateTimestamp(&test_timestamp),
&arena, &test_msg, enable_unknowns(), enable_recursive_planning()));
EXPECT_THAT(test_msg.timestamp_value(), EqualsProto(test_timestamp));
}
TEST_P(CreateCreateStructStepTest, TestSetMessageField) {
Arena arena;
TestMessage orig_msg;
orig_msg.set_bool_value(true);
orig_msg.set_string_value("test");
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"message_value", CelProtoWrapper::CreateMessage(&orig_msg, &arena),
&arena, &test_msg, enable_unknowns(), enable_recursive_planning()));
EXPECT_THAT(test_msg.message_value(), EqualsProto(orig_msg));
}
TEST_P(CreateCreateStructStepTest, TestSetAnyField) {
Arena arena;
TestMessage orig_embedded_msg;
orig_embedded_msg.set_bool_value(true);
orig_embedded_msg.set_string_value("embedded");
TestMessage orig_msg;
orig_msg.mutable_any_value()->PackFrom(orig_embedded_msg);
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"any_value", CelProtoWrapper::CreateMessage(&orig_embedded_msg, &arena),
&arena, &test_msg, enable_unknowns(), enable_recursive_planning()));
EXPECT_THAT(test_msg, EqualsProto(orig_msg));
TestMessage test_embedded_msg;
ASSERT_TRUE(test_msg.any_value().UnpackTo(&test_embedded_msg));
EXPECT_THAT(test_embedded_msg, EqualsProto(orig_embedded_msg));
}
TEST_P(CreateCreateStructStepTest, TestSetEnumField) {
Arena arena;
TestMessage test_msg;
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"enum_value", CelValue::CreateInt64(TestMessage::TEST_ENUM_2), &arena,
&test_msg, enable_unknowns(), enable_recursive_planning()));
EXPECT_EQ(test_msg.enum_value(), TestMessage::TEST_ENUM_2);
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedBoolField) {
Arena arena;
TestMessage test_msg;
std::vector<bool> kValues = {true, false};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateBool(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"bool_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.bool_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedInt32Field) {
Arena arena;
TestMessage test_msg;
std::vector<int32_t> kValues = {23, 12};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateInt64(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"int32_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.int32_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedUInt32Field) {
Arena arena;
TestMessage test_msg;
std::vector<uint32_t> kValues = {23, 12};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateUint64(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"uint32_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.uint32_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedInt64Field) {
Arena arena;
TestMessage test_msg;
std::vector<int64_t> kValues = {23, 12};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateInt64(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"int64_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.int64_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedUInt64Field) {
Arena arena;
TestMessage test_msg;
std::vector<uint64_t> kValues = {23, 12};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateUint64(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"uint64_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.uint64_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedFloatField) {
Arena arena;
TestMessage test_msg;
std::vector<float> kValues = {23, 12};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateDouble(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"float_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.float_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedDoubleField) {
Arena arena;
TestMessage test_msg;
std::vector<double> kValues = {23, 12};
std::vector<CelValue> values;
for (auto value : kValues) {
values.push_back(CelValue::CreateDouble(value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"double_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.double_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedStringField) {
Arena arena;
TestMessage test_msg;
std::vector<std::string> kValues = {"test1", "test2"};
std::vector<CelValue> values;
for (const auto& value : kValues) {
values.push_back(CelValue::CreateString(&value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"string_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.string_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedBytesField) {
Arena arena;
TestMessage test_msg;
std::vector<std::string> kValues = {"test1", "test2"};
std::vector<CelValue> values;
for (const auto& value : kValues) {
values.push_back(CelValue::CreateBytes(&value));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"bytes_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.bytes_list(), Pointwise(Eq(), kValues));
}
TEST_P(CreateCreateStructStepTest, TestSetRepeatedMessageField) {
Arena arena;
TestMessage test_msg;
std::vector<TestMessage> kValues(2);
kValues[0].set_string_value("test1");
kValues[1].set_string_value("test2");
std::vector<CelValue> values;
for (const auto& value : kValues) {
values.push_back(CelProtoWrapper::CreateMessage(&value, &arena));
}
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"message_list", values, &arena, &test_msg, enable_unknowns(),
enable_recursive_planning()));
ASSERT_THAT(test_msg.message_list()[0], EqualsProto(kValues[0]));
ASSERT_THAT(test_msg.message_list()[1], EqualsProto(kValues[1]));
}
TEST_P(CreateCreateStructStepTest, TestSetStringMapField) {
Arena arena;
TestMessage test_msg;
std::vector<std::pair<CelValue, CelValue>> entries;
const std::vector<std::string> kKeys = {"test2", "test1"};
entries.push_back(
{CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)});
entries.push_back(
{CelValue::CreateString(&kKeys[1]), CelValue::CreateInt64(1)});
auto cel_map =
*CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>(
entries.data(), entries.size()));
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"string_int32_map", CelValue::CreateMap(cel_map.get()), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
ASSERT_EQ(test_msg.string_int32_map().size(), 2);
ASSERT_EQ(test_msg.string_int32_map().at(kKeys[0]), 2);
ASSERT_EQ(test_msg.string_int32_map().at(kKeys[1]), 1);
}
TEST_P(CreateCreateStructStepTest, TestSetInt64MapField) {
Arena arena;
TestMessage test_msg;
std::vector<std::pair<CelValue, CelValue>> entries;
const std::vector<int64_t> kKeys = {3, 4};
entries.push_back(
{CelValue::CreateInt64(kKeys[0]), CelValue::CreateInt64(1)});
entries.push_back(
{CelValue::CreateInt64(kKeys[1]), CelValue::CreateInt64(2)});
auto cel_map =
*CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>(
entries.data(), entries.size()));
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"int64_int32_map", CelValue::CreateMap(cel_map.get()), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
ASSERT_EQ(test_msg.int64_int32_map().size(), 2);
ASSERT_EQ(test_msg.int64_int32_map().at(kKeys[0]), 1);
ASSERT_EQ(test_msg.int64_int32_map().at(kKeys[1]), 2);
}
TEST_P(CreateCreateStructStepTest, TestSetUInt64MapField) {
Arena arena;
TestMessage test_msg;
std::vector<std::pair<CelValue, CelValue>> entries;
const std::vector<uint64_t> kKeys = {3, 4};
entries.push_back(
{CelValue::CreateUint64(kKeys[0]), CelValue::CreateInt64(1)});
entries.push_back(
{CelValue::CreateUint64(kKeys[1]), CelValue::CreateInt64(2)});
auto cel_map =
*CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>(
entries.data(), entries.size()));
ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage(
"uint64_int32_map", CelValue::CreateMap(cel_map.get()), &arena, &test_msg,
enable_unknowns(), enable_recursive_planning()));
ASSERT_EQ(test_msg.uint64_int32_map().size(), 2);
ASSERT_EQ(test_msg.uint64_int32_map().at(kKeys[0]), 1);
ASSERT_EQ(test_msg.uint64_int32_map().at(kKeys[1]), 2);
}
INSTANTIATE_TEST_SUITE_P(CombinedCreateStructTest, CreateCreateStructStepTest,
testing::Combine(testing::Bool(), testing::Bool()));
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/create_struct_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/create_struct_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5a78cd31-7e4a-41ac-97e8-3fcb5cc4806a | cpp | google/cel-cpp | comprehension_step | eval/eval/comprehension_step.cc | eval/eval/comprehension_step_test.cc | #include "eval/eval/comprehension_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "base/attribute.h"
#include "base/kind.h"
#include "common/casting.h"
#include "common/value.h"
#include "common/value_kind.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/comprehension_slots.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "eval/public/cel_attribute.h"
#include "internal/status_macros.h"
#include "runtime/internal/mutable_list_impl.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ListValue;
using ::cel::MapValue;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::runtime_internal::CreateNoMatchingOverloadError;
using ::cel::runtime_internal::MutableListValue;
class ComprehensionFinish : public ExpressionStepBase {
public:
ComprehensionFinish(size_t accu_slot, int64_t expr_id);
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
size_t accu_slot_;
};
ComprehensionFinish::ComprehensionFinish(size_t accu_slot, int64_t expr_id)
: ExpressionStepBase(expr_id), accu_slot_(accu_slot) {}
absl::Status ComprehensionFinish::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(3)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
Value result = frame->value_stack().Peek();
frame->value_stack().Pop(3);
if (frame->enable_comprehension_list_append() &&
MutableListValue::Is(result)) {
MutableListValue& list_value = MutableListValue::Cast(result);
CEL_ASSIGN_OR_RETURN(result, std::move(list_value).Build());
}
frame->value_stack().Push(std::move(result));
frame->comprehension_slots().ClearSlot(accu_slot_);
return absl::OkStatus();
}
class ComprehensionInitStep : public ExpressionStepBase {
public:
explicit ComprehensionInitStep(int64_t expr_id)
: ExpressionStepBase(expr_id, false) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
absl::Status ProjectKeys(ExecutionFrame* frame) const;
};
absl::StatusOr<Value> ProjectKeysImpl(ExecutionFrameBase& frame,
const MapValue& range,
const AttributeTrail& trail) {
if (frame.unknown_processing_enabled()) {
if (frame.attribute_utility().CheckForUnknownPartial(trail)) {
return frame.attribute_utility().CreateUnknownSet(trail.attribute());
}
}
return range.ListKeys(frame.value_manager());
}
absl::Status ComprehensionInitStep::ProjectKeys(ExecutionFrame* frame) const {
const auto& map_value = Cast<MapValue>(frame->value_stack().Peek());
CEL_ASSIGN_OR_RETURN(
Value keys,
ProjectKeysImpl(*frame, map_value, frame->value_stack().PeekAttribute()));
frame->value_stack().PopAndPush(std::move(keys));
return absl::OkStatus();
}
absl::Status ComprehensionInitStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(1)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
if (frame->value_stack().Peek()->Is<cel::MapValue>()) {
CEL_RETURN_IF_ERROR(ProjectKeys(frame));
}
const auto& range = frame->value_stack().Peek();
if (!range->Is<cel::ListValue>() && !range->Is<cel::ErrorValue>() &&
!range->Is<cel::UnknownValue>()) {
frame->value_stack().PopAndPush(frame->value_factory().CreateErrorValue(
CreateNoMatchingOverloadError("<iter_range>")));
}
frame->value_stack().Push(frame->value_factory().CreateIntValue(-1));
return absl::OkStatus();
}
class ComprehensionDirectStep : public DirectExpressionStep {
public:
explicit ComprehensionDirectStep(
size_t iter_slot, size_t accu_slot,
std::unique_ptr<DirectExpressionStep> range,
std::unique_ptr<DirectExpressionStep> accu_init,
std::unique_ptr<DirectExpressionStep> loop_step,
std::unique_ptr<DirectExpressionStep> condition_step,
std::unique_ptr<DirectExpressionStep> result_step, bool shortcircuiting,
int64_t expr_id)
: DirectExpressionStep(expr_id),
iter_slot_(iter_slot),
accu_slot_(accu_slot),
range_(std::move(range)),
accu_init_(std::move(accu_init)),
loop_step_(std::move(loop_step)),
condition_(std::move(condition_step)),
result_step_(std::move(result_step)),
shortcircuiting_(shortcircuiting) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& trail) const override;
private:
size_t iter_slot_;
size_t accu_slot_;
std::unique_ptr<DirectExpressionStep> range_;
std::unique_ptr<DirectExpressionStep> accu_init_;
std::unique_ptr<DirectExpressionStep> loop_step_;
std::unique_ptr<DirectExpressionStep> condition_;
std::unique_ptr<DirectExpressionStep> result_step_;
bool shortcircuiting_;
};
absl::Status ComprehensionDirectStep::Evaluate(ExecutionFrameBase& frame,
Value& result,
AttributeTrail& trail) const {
cel::Value range;
AttributeTrail range_attr;
CEL_RETURN_IF_ERROR(range_->Evaluate(frame, range, range_attr));
if (InstanceOf<MapValue>(range)) {
const auto& map_value = Cast<MapValue>(range);
CEL_ASSIGN_OR_RETURN(range, ProjectKeysImpl(frame, map_value, range_attr));
}
switch (range.kind()) {
case cel::ValueKind::kError:
case cel::ValueKind::kUnknown:
result = range;
return absl::OkStatus();
break;
default:
if (!InstanceOf<ListValue>(range)) {
result = frame.value_manager().CreateErrorValue(
CreateNoMatchingOverloadError("<iter_range>"));
return absl::OkStatus();
}
}
const auto& range_list = Cast<ListValue>(range);
Value accu_init;
AttributeTrail accu_init_attr;
CEL_RETURN_IF_ERROR(accu_init_->Evaluate(frame, accu_init, accu_init_attr));
frame.comprehension_slots().Set(accu_slot_, std::move(accu_init),
accu_init_attr);
ComprehensionSlots::Slot* accu_slot =
frame.comprehension_slots().Get(accu_slot_);
ABSL_DCHECK(accu_slot != nullptr);
frame.comprehension_slots().Set(iter_slot_);
ComprehensionSlots::Slot* iter_slot =
frame.comprehension_slots().Get(iter_slot_);
ABSL_DCHECK(iter_slot != nullptr);
Value condition;
AttributeTrail condition_attr;
bool should_skip_result = false;
CEL_RETURN_IF_ERROR(range_list.ForEach(
frame.value_manager(),
[&](size_t index, const Value& v) -> absl::StatusOr<bool> {
CEL_RETURN_IF_ERROR(frame.IncrementIterations());
CEL_RETURN_IF_ERROR(
condition_->Evaluate(frame, condition, condition_attr));
if (condition.kind() == cel::ValueKind::kError ||
condition.kind() == cel::ValueKind::kUnknown) {
result = std::move(condition);
should_skip_result = true;
return false;
}
if (condition.kind() != cel::ValueKind::kBool) {
result = frame.value_manager().CreateErrorValue(
CreateNoMatchingOverloadError("<loop_condition>"));
should_skip_result = true;
return false;
}
if (shortcircuiting_ && !Cast<BoolValue>(condition).NativeValue()) {
return false;
}
iter_slot->value = v;
if (frame.unknown_processing_enabled()) {
iter_slot->attribute =
range_attr.Step(CelAttributeQualifier::OfInt(index));
if (frame.attribute_utility().CheckForUnknownExact(
iter_slot->attribute)) {
iter_slot->value = frame.attribute_utility().CreateUnknownSet(
iter_slot->attribute.attribute());
}
}
CEL_RETURN_IF_ERROR(loop_step_->Evaluate(frame, accu_slot->value,
accu_slot->attribute));
return true;
}));
frame.comprehension_slots().ClearSlot(iter_slot_);
if (should_skip_result) {
frame.comprehension_slots().ClearSlot(accu_slot_);
return absl::OkStatus();
}
CEL_RETURN_IF_ERROR(result_step_->Evaluate(frame, result, trail));
if (frame.options().enable_comprehension_list_append &&
MutableListValue::Is(result)) {
MutableListValue& list_value = MutableListValue::Cast(result);
CEL_ASSIGN_OR_RETURN(result, std::move(list_value).Build());
}
frame.comprehension_slots().ClearSlot(accu_slot_);
return absl::OkStatus();
}
}
ComprehensionNextStep::ComprehensionNextStep(size_t iter_slot, size_t accu_slot,
int64_t expr_id)
: ExpressionStepBase(expr_id, false),
iter_slot_(iter_slot),
accu_slot_(accu_slot) {}
void ComprehensionNextStep::set_jump_offset(int offset) {
jump_offset_ = offset;
}
void ComprehensionNextStep::set_error_jump_offset(int offset) {
error_jump_offset_ = offset;
}
absl::Status ComprehensionNextStep::Evaluate(ExecutionFrame* frame) const {
enum {
POS_ITER_RANGE,
POS_CURRENT_INDEX,
POS_LOOP_STEP_ACCU,
};
constexpr int kStackSize = 3;
if (!frame->value_stack().HasEnough(kStackSize)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
absl::Span<const Value> state = frame->value_stack().GetSpan(kStackSize);
const cel::Value& iter_range = state[POS_ITER_RANGE];
if (!iter_range->Is<cel::ListValue>()) {
if (iter_range->Is<cel::ErrorValue>() ||
iter_range->Is<cel::UnknownValue>()) {
frame->value_stack().PopAndPush(kStackSize, std::move(iter_range));
} else {
frame->value_stack().PopAndPush(
kStackSize, frame->value_factory().CreateErrorValue(
CreateNoMatchingOverloadError("<iter_range>")));
}
return frame->JumpTo(error_jump_offset_);
}
const ListValue& iter_range_list = Cast<ListValue>(iter_range);
const auto& current_index_value = state[POS_CURRENT_INDEX];
if (!InstanceOf<IntValue>(current_index_value)) {
return absl::InternalError(absl::StrCat(
"ComprehensionNextStep: want int, got ",
cel::KindToString(ValueKindToKind(current_index_value->kind()))));
}
CEL_RETURN_IF_ERROR(frame->IncrementIterations());
int64_t next_index = Cast<IntValue>(current_index_value).NativeValue() + 1;
frame->comprehension_slots().Set(accu_slot_, state[POS_LOOP_STEP_ACCU]);
CEL_ASSIGN_OR_RETURN(auto iter_range_list_size, iter_range_list.Size());
if (next_index >= static_cast<int64_t>(iter_range_list_size)) {
frame->comprehension_slots().ClearSlot(iter_slot_);
frame->value_stack().Pop(1);
return frame->JumpTo(jump_offset_);
}
AttributeTrail iter_trail;
if (frame->enable_unknowns()) {
iter_trail =
frame->value_stack().GetAttributeSpan(kStackSize)[POS_ITER_RANGE].Step(
cel::AttributeQualifier::OfInt(next_index));
}
Value current_value;
if (frame->enable_unknowns() && frame->attribute_utility().CheckForUnknown(
iter_trail, false)) {
current_value =
frame->attribute_utility().CreateUnknownSet(iter_trail.attribute());
} else {
CEL_ASSIGN_OR_RETURN(current_value,
iter_range_list.Get(frame->value_factory(),
static_cast<size_t>(next_index)));
}
frame->value_stack().PopAndPush(
2, frame->value_factory().CreateIntValue(next_index));
frame->comprehension_slots().Set(iter_slot_, std::move(current_value),
std::move(iter_trail));
return absl::OkStatus();
}
ComprehensionCondStep::ComprehensionCondStep(size_t iter_slot, size_t accu_slot,
bool shortcircuiting,
int64_t expr_id)
: ExpressionStepBase(expr_id, false),
iter_slot_(iter_slot),
accu_slot_(accu_slot),
shortcircuiting_(shortcircuiting) {}
void ComprehensionCondStep::set_jump_offset(int offset) {
jump_offset_ = offset;
}
void ComprehensionCondStep::set_error_jump_offset(int offset) {
error_jump_offset_ = offset;
}
absl::Status ComprehensionCondStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(3)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
auto& loop_condition_value = frame->value_stack().Peek();
if (!loop_condition_value->Is<cel::BoolValue>()) {
if (loop_condition_value->Is<cel::ErrorValue>() ||
loop_condition_value->Is<cel::UnknownValue>()) {
frame->value_stack().PopAndPush(3, std::move(loop_condition_value));
} else {
frame->value_stack().PopAndPush(
3, frame->value_factory().CreateErrorValue(
CreateNoMatchingOverloadError("<loop_condition>")));
}
frame->comprehension_slots().ClearSlot(iter_slot_);
frame->comprehension_slots().ClearSlot(accu_slot_);
return frame->JumpTo(error_jump_offset_);
}
bool loop_condition = loop_condition_value.GetBool().NativeValue();
frame->value_stack().Pop(1);
if (!loop_condition && shortcircuiting_) {
return frame->JumpTo(jump_offset_);
}
return absl::OkStatus();
}
std::unique_ptr<DirectExpressionStep> CreateDirectComprehensionStep(
size_t iter_slot, size_t accu_slot,
std::unique_ptr<DirectExpressionStep> range,
std::unique_ptr<DirectExpressionStep> accu_init,
std::unique_ptr<DirectExpressionStep> loop_step,
std::unique_ptr<DirectExpressionStep> condition_step,
std::unique_ptr<DirectExpressionStep> result_step, bool shortcircuiting,
int64_t expr_id) {
return std::make_unique<ComprehensionDirectStep>(
iter_slot, accu_slot, std::move(range), std::move(accu_init),
std::move(loop_step), std::move(condition_step), std::move(result_step),
shortcircuiting, expr_id);
}
std::unique_ptr<ExpressionStep> CreateComprehensionFinishStep(size_t accu_slot,
int64_t expr_id) {
return std::make_unique<ComprehensionFinish>(accu_slot, expr_id);
}
std::unique_ptr<ExpressionStep> CreateComprehensionInitStep(int64_t expr_id) {
return std::make_unique<ComprehensionInitStep>(expr_id);
}
} | #include "eval/eval/comprehension_step.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/struct.pb.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "base/ast_internal/expr.h"
#include "base/type_provider.h"
#include "common/value.h"
#include "common/value_testing.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/comprehension_slots.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::BoolValue;
using ::cel::IntValue;
using ::cel::TypeProvider;
using ::cel::Value;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::Ident;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::test::BoolValueIs;
using ::google::protobuf::ListValue;
using ::google::protobuf::Struct;
using ::google::protobuf::Arena;
using ::testing::_;
using ::testing::Eq;
using ::testing::Return;
using ::testing::SizeIs;
Ident CreateIdent(const std::string& var) {
Ident expr;
expr.set_name(var);
return expr;
}
class ListKeysStepTest : public testing::Test {
public:
ListKeysStepTest() = default;
std::unique_ptr<CelExpressionFlatImpl> MakeExpression(
ExecutionPath&& path, bool unknown_attributes = false) {
cel::RuntimeOptions options;
if (unknown_attributes) {
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeAndFunction;
}
return std::make_unique<CelExpressionFlatImpl>(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
}
private:
Expr dummy_expr_;
};
class GetListKeysResultStep : public ExpressionStepBase {
public:
GetListKeysResultStep() : ExpressionStepBase(-1, false) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
frame->value_stack().Pop(1);
return absl::OkStatus();
}
};
MATCHER_P(CelStringValue, val, "") {
const CelValue& to_match = arg;
absl::string_view value = val;
return to_match.IsString() && to_match.StringOrDie().value() == value;
}
TEST_F(ListKeysStepTest, ListPassedThrough) {
ExecutionPath path;
Ident ident = CreateIdent("var");
auto result = CreateIdentStep(ident, 0);
ASSERT_OK(result);
path.push_back(*std::move(result));
result = CreateComprehensionInitStep(1);
ASSERT_OK(result);
path.push_back(*std::move(result));
path.push_back(std::make_unique<GetListKeysResultStep>());
auto expression = MakeExpression(std::move(path));
Activation activation;
Arena arena;
ListValue value;
value.add_values()->set_number_value(1.0);
value.add_values()->set_number_value(2.0);
value.add_values()->set_number_value(3.0);
activation.InsertValue("var", CelProtoWrapper::CreateMessage(&value, &arena));
auto eval_result = expression->Evaluate(activation, &arena);
ASSERT_OK(eval_result);
ASSERT_TRUE(eval_result->IsList());
EXPECT_THAT(*eval_result->ListOrDie(), SizeIs(3));
}
TEST_F(ListKeysStepTest, MapToKeyList) {
ExecutionPath path;
Ident ident = CreateIdent("var");
auto result = CreateIdentStep(ident, 0);
ASSERT_OK(result);
path.push_back(*std::move(result));
result = CreateComprehensionInitStep(1);
ASSERT_OK(result);
path.push_back(*std::move(result));
path.push_back(std::make_unique<GetListKeysResultStep>());
auto expression = MakeExpression(std::move(path));
Activation activation;
Arena arena;
Struct value;
(*value.mutable_fields())["key1"].set_number_value(1.0);
(*value.mutable_fields())["key2"].set_number_value(2.0);
(*value.mutable_fields())["key3"].set_number_value(3.0);
activation.InsertValue("var", CelProtoWrapper::CreateMessage(&value, &arena));
auto eval_result = expression->Evaluate(activation, &arena);
ASSERT_OK(eval_result);
ASSERT_TRUE(eval_result->IsList());
EXPECT_THAT(*eval_result->ListOrDie(), SizeIs(3));
std::vector<CelValue> keys;
keys.reserve(eval_result->ListOrDie()->size());
for (int i = 0; i < eval_result->ListOrDie()->size(); i++) {
keys.push_back(eval_result->ListOrDie()->operator[](i));
}
EXPECT_THAT(keys, testing::UnorderedElementsAre(CelStringValue("key1"),
CelStringValue("key2"),
CelStringValue("key3")));
}
TEST_F(ListKeysStepTest, MapPartiallyUnknown) {
ExecutionPath path;
Ident ident = CreateIdent("var");
auto result = CreateIdentStep(ident, 0);
ASSERT_OK(result);
path.push_back(*std::move(result));
result = CreateComprehensionInitStep(1);
ASSERT_OK(result);
path.push_back(*std::move(result));
path.push_back(std::make_unique<GetListKeysResultStep>());
auto expression =
MakeExpression(std::move(path), true);
Activation activation;
Arena arena;
Struct value;
(*value.mutable_fields())["key1"].set_number_value(1.0);
(*value.mutable_fields())["key2"].set_number_value(2.0);
(*value.mutable_fields())["key3"].set_number_value(3.0);
activation.InsertValue("var", CelProtoWrapper::CreateMessage(&value, &arena));
activation.set_unknown_attribute_patterns({CelAttributePattern(
"var",
{CreateCelAttributeQualifierPattern(CelValue::CreateStringView("key2")),
CreateCelAttributeQualifierPattern(CelValue::CreateStringView("foo")),
CelAttributeQualifierPattern::CreateWildcard()})});
auto eval_result = expression->Evaluate(activation, &arena);
ASSERT_OK(eval_result);
ASSERT_TRUE(eval_result->IsUnknownSet());
const auto& attrs = eval_result->UnknownSetOrDie()->unknown_attributes();
EXPECT_THAT(attrs, SizeIs(1));
EXPECT_THAT(attrs.begin()->variable_name(), Eq("var"));
EXPECT_THAT(attrs.begin()->qualifier_path(), SizeIs(0));
}
TEST_F(ListKeysStepTest, ErrorPassedThrough) {
ExecutionPath path;
Ident ident = CreateIdent("var");
auto result = CreateIdentStep(ident, 0);
ASSERT_OK(result);
path.push_back(*std::move(result));
result = CreateComprehensionInitStep(1);
ASSERT_OK(result);
path.push_back(*std::move(result));
path.push_back(std::make_unique<GetListKeysResultStep>());
auto expression = MakeExpression(std::move(path));
Activation activation;
Arena arena;
auto eval_result = expression->Evaluate(activation, &arena);
ASSERT_OK(eval_result);
ASSERT_TRUE(eval_result->IsError());
EXPECT_THAT(eval_result->ErrorOrDie()->message(),
testing::HasSubstr("\"var\""));
EXPECT_EQ(eval_result->ErrorOrDie()->code(), absl::StatusCode::kUnknown);
}
TEST_F(ListKeysStepTest, UnknownSetPassedThrough) {
ExecutionPath path;
Ident ident = CreateIdent("var");
auto result = CreateIdentStep(ident, 0);
ASSERT_OK(result);
path.push_back(*std::move(result));
result = CreateComprehensionInitStep(1);
ASSERT_OK(result);
path.push_back(*std::move(result));
path.push_back(std::make_unique<GetListKeysResultStep>());
auto expression =
MakeExpression(std::move(path), true);
Activation activation;
Arena arena;
activation.set_unknown_attribute_patterns({CelAttributePattern("var", {})});
auto eval_result = expression->Evaluate(activation, &arena);
ASSERT_OK(eval_result);
ASSERT_TRUE(eval_result->IsUnknownSet());
EXPECT_THAT(eval_result->UnknownSetOrDie()->unknown_attributes(), SizeIs(1));
}
class MockDirectStep : public DirectExpressionStep {
public:
MockDirectStep() : DirectExpressionStep(-1) {}
MOCK_METHOD(absl::Status, Evaluate,
(ExecutionFrameBase&, Value&, AttributeTrail&),
(const, override));
};
class DirectComprehensionTest : public testing::Test {
public:
DirectComprehensionTest()
: value_manager_(TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)),
slots_(2) {}
absl::StatusOr<cel::ListValue> MakeList() {
CEL_ASSIGN_OR_RETURN(auto builder,
value_manager_.get().NewListValueBuilder(
value_manager_.get().GetDynListType()));
CEL_RETURN_IF_ERROR(builder->Add(IntValue(1)));
CEL_RETURN_IF_ERROR(builder->Add(IntValue(2)));
return std::move(*builder).Build();
}
protected:
google::protobuf::Arena arena_;
cel::ManagedValueFactory value_manager_;
ComprehensionSlots slots_;
cel::Activation empty_activation_;
};
TEST_F(DirectComprehensionTest, PropagateRangeNonOkStatus) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto range_step = std::make_unique<MockDirectStep>();
MockDirectStep* mock = range_step.get();
ON_CALL(*mock, Evaluate(_, _, _))
.WillByDefault(Return(absl::InternalError("test range error")));
auto compre_step = CreateDirectComprehensionStep(
0, 1,
std::move(range_step),
CreateConstValueDirectStep(BoolValue(false)),
CreateConstValueDirectStep(BoolValue(false)),
CreateConstValueDirectStep(BoolValue(true)),
CreateDirectSlotIdentStep("__result__", 1, -1),
true, -1);
Value result;
AttributeTrail trail;
EXPECT_THAT(compre_step->Evaluate(frame, result, trail),
StatusIs(absl::StatusCode::kInternal, "test range error"));
}
TEST_F(DirectComprehensionTest, PropagateAccuInitNonOkStatus) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto accu_init = std::make_unique<MockDirectStep>();
MockDirectStep* mock = accu_init.get();
ON_CALL(*mock, Evaluate(_, _, _))
.WillByDefault(Return(absl::InternalError("test accu init error")));
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
std::move(accu_init),
CreateConstValueDirectStep(BoolValue(false)),
CreateConstValueDirectStep(BoolValue(true)),
CreateDirectSlotIdentStep("__result__", 1, -1),
true, -1);
Value result;
AttributeTrail trail;
EXPECT_THAT(compre_step->Evaluate(frame, result, trail),
StatusIs(absl::StatusCode::kInternal, "test accu init error"));
}
TEST_F(DirectComprehensionTest, PropagateLoopNonOkStatus) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto loop_step = std::make_unique<MockDirectStep>();
MockDirectStep* mock = loop_step.get();
ON_CALL(*mock, Evaluate(_, _, _))
.WillByDefault(Return(absl::InternalError("test loop error")));
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
CreateConstValueDirectStep(BoolValue(false)),
std::move(loop_step),
CreateConstValueDirectStep(BoolValue(true)),
CreateDirectSlotIdentStep("__result__", 1, -1),
true, -1);
Value result;
AttributeTrail trail;
EXPECT_THAT(compre_step->Evaluate(frame, result, trail),
StatusIs(absl::StatusCode::kInternal, "test loop error"));
}
TEST_F(DirectComprehensionTest, PropagateConditionNonOkStatus) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto condition = std::make_unique<MockDirectStep>();
MockDirectStep* mock = condition.get();
ON_CALL(*mock, Evaluate(_, _, _))
.WillByDefault(Return(absl::InternalError("test condition error")));
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
CreateConstValueDirectStep(BoolValue(false)),
CreateConstValueDirectStep(BoolValue(false)),
std::move(condition),
CreateDirectSlotIdentStep("__result__", 1, -1),
true, -1);
Value result;
AttributeTrail trail;
EXPECT_THAT(compre_step->Evaluate(frame, result, trail),
StatusIs(absl::StatusCode::kInternal, "test condition error"));
}
TEST_F(DirectComprehensionTest, PropagateResultNonOkStatus) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto result_step = std::make_unique<MockDirectStep>();
MockDirectStep* mock = result_step.get();
ON_CALL(*mock, Evaluate(_, _, _))
.WillByDefault(Return(absl::InternalError("test result error")));
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
CreateConstValueDirectStep(BoolValue(false)),
CreateConstValueDirectStep(BoolValue(false)),
CreateConstValueDirectStep(BoolValue(true)),
std::move(result_step),
true, -1);
Value result;
AttributeTrail trail;
EXPECT_THAT(compre_step->Evaluate(frame, result, trail),
StatusIs(absl::StatusCode::kInternal, "test result error"));
}
TEST_F(DirectComprehensionTest, Shortcircuit) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto loop_step = std::make_unique<MockDirectStep>();
MockDirectStep* mock = loop_step.get();
EXPECT_CALL(*mock, Evaluate(_, _, _))
.Times(0)
.WillRepeatedly([](ExecutionFrameBase&, Value& result, AttributeTrail&) {
result = BoolValue(false);
return absl::OkStatus();
});
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
CreateConstValueDirectStep(BoolValue(false)),
std::move(loop_step),
CreateConstValueDirectStep(BoolValue(false)),
CreateDirectSlotIdentStep("__result__", 1, -1),
true, -1);
Value result;
AttributeTrail trail;
ASSERT_OK(compre_step->Evaluate(frame, result, trail));
EXPECT_THAT(result, BoolValueIs(false));
}
TEST_F(DirectComprehensionTest, IterationLimit) {
cel::RuntimeOptions options;
options.comprehension_max_iterations = 2;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto loop_step = std::make_unique<MockDirectStep>();
MockDirectStep* mock = loop_step.get();
EXPECT_CALL(*mock, Evaluate(_, _, _))
.Times(1)
.WillRepeatedly([](ExecutionFrameBase&, Value& result, AttributeTrail&) {
result = BoolValue(false);
return absl::OkStatus();
});
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
CreateConstValueDirectStep(BoolValue(false)),
std::move(loop_step),
CreateConstValueDirectStep(BoolValue(true)),
CreateDirectSlotIdentStep("__result__", 1, -1),
true, -1);
Value result;
AttributeTrail trail;
EXPECT_THAT(compre_step->Evaluate(frame, result, trail),
StatusIs(absl::StatusCode::kInternal));
}
TEST_F(DirectComprehensionTest, Exhaustive) {
cel::RuntimeOptions options;
ExecutionFrameBase frame(empty_activation_, nullptr, options,
value_manager_.get(), slots_);
auto loop_step = std::make_unique<MockDirectStep>();
MockDirectStep* mock = loop_step.get();
EXPECT_CALL(*mock, Evaluate(_, _, _))
.Times(2)
.WillRepeatedly([](ExecutionFrameBase&, Value& result, AttributeTrail&) {
result = BoolValue(false);
return absl::OkStatus();
});
ASSERT_OK_AND_ASSIGN(auto list, MakeList());
auto compre_step = CreateDirectComprehensionStep(
0, 1,
CreateConstValueDirectStep(std::move(list)),
CreateConstValueDirectStep(BoolValue(false)),
std::move(loop_step),
CreateConstValueDirectStep(BoolValue(false)),
CreateDirectSlotIdentStep("__result__", 1, -1),
false, -1);
Value result;
AttributeTrail trail;
ASSERT_OK(compre_step->Evaluate(frame, result, trail));
EXPECT_THAT(result, BoolValueIs(false));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/comprehension_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/comprehension_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
fcf11a49-e7c8-4437-8649-1838443687e3 | cpp | google/cel-cpp | const_value_step | eval/eval/const_value_step.cc | eval/eval/const_value_step_test.cc | #include "eval/eval/const_value_step.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/statusor.h"
#include "base/ast_internal/expr.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/compiler_constant_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "internal/status_macros.h"
#include "runtime/internal/convert_constant.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::ast_internal::Constant;
using ::cel::runtime_internal::ConvertConstant;
}
std::unique_ptr<DirectExpressionStep> CreateConstValueDirectStep(
cel::Value value, int64_t id) {
return std::make_unique<DirectCompilerConstantStep>(std::move(value), id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateConstValueStep(
cel::Value value, int64_t expr_id, bool comes_from_ast) {
return std::make_unique<CompilerConstantStep>(std::move(value), expr_id,
comes_from_ast);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateConstValueStep(
const Constant& value, int64_t expr_id, cel::ValueManager& value_factory,
bool comes_from_ast) {
CEL_ASSIGN_OR_RETURN(cel::Value converted_value,
ConvertConstant(value, value_factory));
return std::make_unique<CompilerConstantStep>(std::move(converted_value),
expr_id, comes_from_ast);
}
} | #include "eval/eval/const_value_step.h"
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "base/ast_internal/expr.h"
#include "base/type_provider.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/evaluator_core.h"
#include "eval/internal/errors.h"
#include "eval/public/activation.h"
#include "eval/public/cel_value.h"
#include "eval/public/testing/matchers.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::TypeProvider;
using ::cel::ast_internal::Constant;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::NullValue;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::testing::Eq;
using ::testing::HasSubstr;
absl::StatusOr<CelValue> RunConstantExpression(
const Expr* expr, const Constant& const_expr, google::protobuf::Arena* arena,
cel::ValueManager& value_factory) {
CEL_ASSIGN_OR_RETURN(
auto step, CreateConstValueStep(const_expr, expr->id(), value_factory));
google::api::expr::runtime::ExecutionPath path;
path.push_back(std::move(step));
CelExpressionFlatImpl impl(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
google::api::expr::runtime::Activation activation;
return impl.Evaluate(activation, arena);
}
class ConstValueStepTest : public ::testing::Test {
public:
ConstValueStepTest()
: value_factory_(ProtoMemoryManagerRef(&arena_),
cel::TypeProvider::Builtin()) {}
protected:
google::protobuf::Arena arena_;
cel::common_internal::LegacyValueManager value_factory_;
};
TEST_F(ConstValueStepTest, TestEvaluationConstInt64) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_int64_value(1);
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsInt64());
EXPECT_THAT(value.Int64OrDie(), Eq(1));
}
TEST_F(ConstValueStepTest, TestEvaluationConstUint64) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_uint64_value(1);
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsUint64());
EXPECT_THAT(value.Uint64OrDie(), Eq(1));
}
TEST_F(ConstValueStepTest, TestEvaluationConstBool) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_bool_value(true);
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsBool());
EXPECT_THAT(value.BoolOrDie(), Eq(true));
}
TEST_F(ConstValueStepTest, TestEvaluationConstNull) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_null_value(nullptr);
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
EXPECT_TRUE(value.IsNull());
}
TEST_F(ConstValueStepTest, TestEvaluationConstString) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_string_value("test");
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsString());
EXPECT_THAT(value.StringOrDie().value(), Eq("test"));
}
TEST_F(ConstValueStepTest, TestEvaluationConstDouble) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_double_value(1.0);
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsDouble());
EXPECT_THAT(value.DoubleOrDie(), testing::DoubleEq(1.0));
}
TEST_F(ConstValueStepTest, TestEvaluationConstBytes) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_bytes_value("test");
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsBytes());
EXPECT_THAT(value.BytesOrDie().value(), Eq("test"));
}
TEST_F(ConstValueStepTest, TestEvaluationConstDuration) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_duration_value(absl::Seconds(5) + absl::Nanoseconds(2000));
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
EXPECT_THAT(value,
test::IsCelDuration(absl::Seconds(5) + absl::Nanoseconds(2000)));
}
TEST_F(ConstValueStepTest, TestEvaluationConstDurationOutOfRange) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_duration_value(cel::runtime_internal::kDurationHigh);
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
EXPECT_THAT(value,
test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("out of range"))));
}
TEST_F(ConstValueStepTest, TestEvaluationConstTimestamp) {
Expr expr;
auto& const_expr = expr.mutable_const_expr();
const_expr.set_time_value(absl::FromUnixSeconds(3600) +
absl::Nanoseconds(1000));
auto status =
RunConstantExpression(&expr, const_expr, &arena_, value_factory_);
ASSERT_OK(status);
auto value = status.value();
EXPECT_THAT(value, test::IsCelTimestamp(absl::FromUnixSeconds(3600) +
absl::Nanoseconds(1000)));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/const_value_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/const_value_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5ff5ffc2-ffe7-4983-91e4-849fceabbab5 | cpp | google/cel-cpp | attribute_trail | eval/eval/attribute_trail.cc | eval/eval/attribute_trail_test.cc | #include "eval/eval/attribute_trail.h"
#include <algorithm>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
#include "base/attribute.h"
namespace google::api::expr::runtime {
AttributeTrail AttributeTrail::Step(cel::AttributeQualifier qualifier) const {
if (empty()) return AttributeTrail();
std::vector<cel::AttributeQualifier> qualifiers;
qualifiers.reserve(attribute_->qualifier_path().size() + 1);
std::copy_n(attribute_->qualifier_path().begin(),
attribute_->qualifier_path().size(),
std::back_inserter(qualifiers));
qualifiers.push_back(std::move(qualifier));
return AttributeTrail(cel::Attribute(std::string(attribute_->variable_name()),
std::move(qualifiers)));
}
} | #include "eval/eval/attribute_trail.h"
#include <string>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_value.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
TEST(AttributeTrailTest, AttributeTrailEmptyStep) {
std::string step = "step";
CelValue step_value = CelValue::CreateString(&step);
AttributeTrail trail;
ASSERT_TRUE(trail.Step(&step).empty());
ASSERT_TRUE(trail.Step(CreateCelAttributeQualifier(step_value)).empty());
}
TEST(AttributeTrailTest, AttributeTrailStep) {
std::string step = "step";
CelValue step_value = CelValue::CreateString(&step);
AttributeTrail trail = AttributeTrail("ident").Step(&step);
ASSERT_EQ(trail.attribute(),
CelAttribute("ident", {CreateCelAttributeQualifier(step_value)}));
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/attribute_trail.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/attribute_trail_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
7d452a69-88af-4529-984c-856044aa2621 | cpp | google/cel-cpp | logic_step | eval/eval/logic_step.cc | eval/eval/logic_step_test.cc | #include "eval/eval/logic_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "base/builtins.h"
#include "common/casting.h"
#include "common/value.h"
#include "common/value_kind.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "internal/status_macros.h"
#include "runtime/internal/errors.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ValueKind;
using ::cel::runtime_internal::CreateNoMatchingOverloadError;
enum class OpType { kAnd, kOr };
absl::Status ReturnLogicResult(ExecutionFrameBase& frame, OpType op_type,
Value& lhs_result, Value& rhs_result,
AttributeTrail& attribute_trail,
AttributeTrail& rhs_attr) {
ValueKind lhs_kind = lhs_result.kind();
ValueKind rhs_kind = rhs_result.kind();
if (frame.unknown_processing_enabled()) {
if (lhs_kind == ValueKind::kUnknown && rhs_kind == ValueKind::kUnknown) {
lhs_result = frame.attribute_utility().MergeUnknownValues(
Cast<UnknownValue>(lhs_result), Cast<UnknownValue>(rhs_result));
attribute_trail = AttributeTrail();
return absl::OkStatus();
} else if (lhs_kind == ValueKind::kUnknown) {
return absl::OkStatus();
} else if (rhs_kind == ValueKind::kUnknown) {
lhs_result = std::move(rhs_result);
attribute_trail = std::move(rhs_attr);
return absl::OkStatus();
}
}
if (lhs_kind == ValueKind::kError) {
return absl::OkStatus();
} else if (rhs_kind == ValueKind::kError) {
lhs_result = std::move(rhs_result);
attribute_trail = std::move(rhs_attr);
return absl::OkStatus();
}
if (lhs_kind == ValueKind::kBool && rhs_kind == ValueKind::kBool) {
return absl::OkStatus();
}
attribute_trail = AttributeTrail();
lhs_result =
frame.value_manager().CreateErrorValue(CreateNoMatchingOverloadError(
op_type == OpType::kOr ? cel::builtin::kOr : cel::builtin::kAnd));
return absl::OkStatus();
}
class ExhaustiveDirectLogicStep : public DirectExpressionStep {
public:
explicit ExhaustiveDirectLogicStep(std::unique_ptr<DirectExpressionStep> lhs,
std::unique_ptr<DirectExpressionStep> rhs,
OpType op_type, int64_t expr_id)
: DirectExpressionStep(expr_id),
lhs_(std::move(lhs)),
rhs_(std::move(rhs)),
op_type_(op_type) {}
absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& attribute_trail) const override;
private:
std::unique_ptr<DirectExpressionStep> lhs_;
std::unique_ptr<DirectExpressionStep> rhs_;
OpType op_type_;
};
absl::Status ExhaustiveDirectLogicStep::Evaluate(
ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& attribute_trail) const {
CEL_RETURN_IF_ERROR(lhs_->Evaluate(frame, result, attribute_trail));
ValueKind lhs_kind = result.kind();
Value rhs_result;
AttributeTrail rhs_attr;
CEL_RETURN_IF_ERROR(rhs_->Evaluate(frame, rhs_result, attribute_trail));
ValueKind rhs_kind = rhs_result.kind();
if (lhs_kind == ValueKind::kBool) {
bool lhs_bool = Cast<BoolValue>(result).NativeValue();
if ((op_type_ == OpType::kOr && lhs_bool) ||
(op_type_ == OpType::kAnd && !lhs_bool)) {
return absl::OkStatus();
}
}
if (rhs_kind == ValueKind::kBool) {
bool rhs_bool = Cast<BoolValue>(rhs_result).NativeValue();
if ((op_type_ == OpType::kOr && rhs_bool) ||
(op_type_ == OpType::kAnd && !rhs_bool)) {
result = std::move(rhs_result);
attribute_trail = std::move(rhs_attr);
return absl::OkStatus();
}
}
return ReturnLogicResult(frame, op_type_, result, rhs_result, attribute_trail,
rhs_attr);
}
class DirectLogicStep : public DirectExpressionStep {
public:
explicit DirectLogicStep(std::unique_ptr<DirectExpressionStep> lhs,
std::unique_ptr<DirectExpressionStep> rhs,
OpType op_type, int64_t expr_id)
: DirectExpressionStep(expr_id),
lhs_(std::move(lhs)),
rhs_(std::move(rhs)),
op_type_(op_type) {}
absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& attribute_trail) const override;
private:
std::unique_ptr<DirectExpressionStep> lhs_;
std::unique_ptr<DirectExpressionStep> rhs_;
OpType op_type_;
};
absl::Status DirectLogicStep::Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute_trail) const {
CEL_RETURN_IF_ERROR(lhs_->Evaluate(frame, result, attribute_trail));
ValueKind lhs_kind = result.kind();
if (lhs_kind == ValueKind::kBool) {
bool lhs_bool = Cast<BoolValue>(result).NativeValue();
if ((op_type_ == OpType::kOr && lhs_bool) ||
(op_type_ == OpType::kAnd && !lhs_bool)) {
return absl::OkStatus();
}
}
Value rhs_result;
AttributeTrail rhs_attr;
CEL_RETURN_IF_ERROR(rhs_->Evaluate(frame, rhs_result, attribute_trail));
ValueKind rhs_kind = rhs_result.kind();
if (rhs_kind == ValueKind::kBool) {
bool rhs_bool = Cast<BoolValue>(rhs_result).NativeValue();
if ((op_type_ == OpType::kOr && rhs_bool) ||
(op_type_ == OpType::kAnd && !rhs_bool)) {
result = std::move(rhs_result);
attribute_trail = std::move(rhs_attr);
return absl::OkStatus();
}
}
return ReturnLogicResult(frame, op_type_, result, rhs_result, attribute_trail,
rhs_attr);
}
class LogicalOpStep : public ExpressionStepBase {
public:
LogicalOpStep(OpType op_type, int64_t expr_id)
: ExpressionStepBase(expr_id), op_type_(op_type) {
shortcircuit_ = (op_type_ == OpType::kOr);
}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
void Calculate(ExecutionFrame* frame, absl::Span<const Value> args,
Value& result) const {
bool bool_args[2];
bool has_bool_args[2];
for (size_t i = 0; i < args.size(); i++) {
has_bool_args[i] = args[i]->Is<BoolValue>();
if (has_bool_args[i]) {
bool_args[i] = args[i].GetBool().NativeValue();
if (bool_args[i] == shortcircuit_) {
result = BoolValue{bool_args[i]};
return;
}
}
}
if (has_bool_args[0] && has_bool_args[1]) {
switch (op_type_) {
case OpType::kAnd:
result = BoolValue{bool_args[0] && bool_args[1]};
return;
case OpType::kOr:
result = BoolValue{bool_args[0] || bool_args[1]};
return;
}
}
if (frame->enable_unknowns()) {
absl::optional<cel::UnknownValue> unknown_set =
frame->attribute_utility().MergeUnknowns(args);
if (unknown_set.has_value()) {
result = std::move(*unknown_set);
return;
}
}
if (args[0]->Is<cel::ErrorValue>()) {
result = args[0];
return;
} else if (args[1]->Is<cel::ErrorValue>()) {
result = args[1];
return;
}
result =
frame->value_factory().CreateErrorValue(CreateNoMatchingOverloadError(
(op_type_ == OpType::kOr) ? cel::builtin::kOr
: cel::builtin::kAnd));
}
const OpType op_type_;
bool shortcircuit_;
};
absl::Status LogicalOpStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(2)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
auto args = frame->value_stack().GetSpan(2);
Value result;
Calculate(frame, args, result);
frame->value_stack().PopAndPush(args.size(), std::move(result));
return absl::OkStatus();
}
std::unique_ptr<DirectExpressionStep> CreateDirectLogicStep(
std::unique_ptr<DirectExpressionStep> lhs,
std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id, OpType op_type,
bool shortcircuiting) {
if (shortcircuiting) {
return std::make_unique<DirectLogicStep>(std::move(lhs), std::move(rhs),
op_type, expr_id);
} else {
return std::make_unique<ExhaustiveDirectLogicStep>(
std::move(lhs), std::move(rhs), op_type, expr_id);
}
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectAndStep(
std::unique_ptr<DirectExpressionStep> lhs,
std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id,
bool shortcircuiting) {
return CreateDirectLogicStep(std::move(lhs), std::move(rhs), expr_id,
OpType::kAnd, shortcircuiting);
}
std::unique_ptr<DirectExpressionStep> CreateDirectOrStep(
std::unique_ptr<DirectExpressionStep> lhs,
std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id,
bool shortcircuiting) {
return CreateDirectLogicStep(std::move(lhs), std::move(rhs), expr_id,
OpType::kOr, shortcircuiting);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateAndStep(int64_t expr_id) {
return std::make_unique<LogicalOpStep>(OpType::kAnd, expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateOrStep(int64_t expr_id) {
return std::make_unique<LogicalOpStep>(OpType::kOr, expr_id);
}
} | #include "eval/eval/logic_step.h"
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "base/ast_internal/expr.h"
#include "base/attribute.h"
#include "base/attribute_set.h"
#include "base/type_provider.h"
#include "common/casting.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_value.h"
#include "eval/public/unknown_attribute_set.h"
#include "eval/public/unknown_set.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Attribute;
using ::cel::AttributeSet;
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ManagedValueFactory;
using ::cel::TypeProvider;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ValueManager;
using ::cel::ast_internal::Expr;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::google::protobuf::Arena;
using ::testing::Eq;
class LogicStepTest : public testing::TestWithParam<bool> {
public:
absl::Status EvaluateLogic(CelValue arg0, CelValue arg1, bool is_or,
CelValue* result, bool enable_unknown) {
Expr expr0;
auto& ident_expr0 = expr0.mutable_ident_expr();
ident_expr0.set_name("name0");
Expr expr1;
auto& ident_expr1 = expr1.mutable_ident_expr();
ident_expr1.set_name("name1");
ExecutionPath path;
CEL_ASSIGN_OR_RETURN(auto step, CreateIdentStep(ident_expr0, expr0.id()));
path.push_back(std::move(step));
CEL_ASSIGN_OR_RETURN(step, CreateIdentStep(ident_expr1, expr1.id()));
path.push_back(std::move(step));
CEL_ASSIGN_OR_RETURN(step, (is_or) ? CreateOrStep(2) : CreateAndStep(2));
path.push_back(std::move(step));
auto dummy_expr = std::make_unique<Expr>();
cel::RuntimeOptions options;
if (enable_unknown) {
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl impl(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
Activation activation;
activation.InsertValue("name0", arg0);
activation.InsertValue("name1", arg1);
CEL_ASSIGN_OR_RETURN(CelValue value, impl.Evaluate(activation, &arena_));
*result = value;
return absl::OkStatus();
}
private:
Arena arena_;
};
TEST_P(LogicStepTest, TestAndLogic) {
CelValue result;
absl::Status status =
EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(true),
false, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status =
EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(false),
false, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
status =
EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(true),
false, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
status =
EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(false),
false, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
TEST_P(LogicStepTest, TestOrLogic) {
CelValue result;
absl::Status status =
EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(true),
true, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status =
EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(false),
true, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status = EvaluateLogic(CelValue::CreateBool(false),
CelValue::CreateBool(true), true, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status =
EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(false),
true, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
TEST_P(LogicStepTest, TestAndLogicErrorHandling) {
CelValue result;
CelError error = absl::CancelledError();
CelValue error_value = CelValue::CreateError(&error);
absl::Status status = EvaluateLogic(error_value, CelValue::CreateBool(true),
false, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsError());
status = EvaluateLogic(CelValue::CreateBool(true), error_value, false,
&result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsError());
status = EvaluateLogic(CelValue::CreateBool(false), error_value, false,
&result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
status = EvaluateLogic(error_value, CelValue::CreateBool(false), false,
&result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
TEST_P(LogicStepTest, TestOrLogicErrorHandling) {
CelValue result;
CelError error = absl::CancelledError();
CelValue error_value = CelValue::CreateError(&error);
absl::Status status = EvaluateLogic(error_value, CelValue::CreateBool(false),
true, &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsError());
status = EvaluateLogic(CelValue::CreateBool(false), error_value, true,
&result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsError());
status = EvaluateLogic(CelValue::CreateBool(true), error_value, true, &result,
GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status = EvaluateLogic(error_value, CelValue::CreateBool(true), true, &result,
GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
TEST_F(LogicStepTest, TestAndLogicUnknownHandling) {
CelValue result;
UnknownSet unknown_set;
CelError cel_error = absl::CancelledError();
CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set);
CelValue error_value = CelValue::CreateError(&cel_error);
absl::Status status = EvaluateLogic(unknown_value, CelValue::CreateBool(true),
false, &result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
status = EvaluateLogic(CelValue::CreateBool(true), unknown_value, false,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
status = EvaluateLogic(CelValue::CreateBool(false), unknown_value, false,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
status = EvaluateLogic(unknown_value, CelValue::CreateBool(false), false,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
status = EvaluateLogic(error_value, unknown_value, false, &result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
status = EvaluateLogic(unknown_value, error_value, false, &result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
Expr expr0;
auto& ident_expr0 = expr0.mutable_ident_expr();
ident_expr0.set_name("name0");
Expr expr1;
auto& ident_expr1 = expr1.mutable_ident_expr();
ident_expr1.set_name("name1");
CelAttribute attr0(expr0.ident_expr().name(), {}),
attr1(expr1.ident_expr().name(), {});
UnknownAttributeSet unknown_attr_set0({attr0});
UnknownAttributeSet unknown_attr_set1({attr1});
UnknownSet unknown_set0(unknown_attr_set0);
UnknownSet unknown_set1(unknown_attr_set1);
EXPECT_THAT(unknown_attr_set0.size(), Eq(1));
EXPECT_THAT(unknown_attr_set1.size(), Eq(1));
status = EvaluateLogic(CelValue::CreateUnknownSet(&unknown_set0),
CelValue::CreateUnknownSet(&unknown_set1), false,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
ASSERT_THAT(result.UnknownSetOrDie()->unknown_attributes().size(), Eq(2));
}
TEST_F(LogicStepTest, TestOrLogicUnknownHandling) {
CelValue result;
UnknownSet unknown_set;
CelError cel_error = absl::CancelledError();
CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set);
CelValue error_value = CelValue::CreateError(&cel_error);
absl::Status status = EvaluateLogic(
unknown_value, CelValue::CreateBool(false), true, &result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
status = EvaluateLogic(CelValue::CreateBool(false), unknown_value, true,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
status = EvaluateLogic(CelValue::CreateBool(true), unknown_value, true,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status = EvaluateLogic(unknown_value, CelValue::CreateBool(true), true,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status = EvaluateLogic(unknown_value, error_value, true, &result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
status = EvaluateLogic(error_value, unknown_value, true, &result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
Expr expr0;
auto& ident_expr0 = expr0.mutable_ident_expr();
ident_expr0.set_name("name0");
Expr expr1;
auto& ident_expr1 = expr1.mutable_ident_expr();
ident_expr1.set_name("name1");
CelAttribute attr0(expr0.ident_expr().name(), {}),
attr1(expr1.ident_expr().name(), {});
UnknownAttributeSet unknown_attr_set0({attr0});
UnknownAttributeSet unknown_attr_set1({attr1});
UnknownSet unknown_set0(unknown_attr_set0);
UnknownSet unknown_set1(unknown_attr_set1);
EXPECT_THAT(unknown_attr_set0.size(), Eq(1));
EXPECT_THAT(unknown_attr_set1.size(), Eq(1));
status = EvaluateLogic(CelValue::CreateUnknownSet(&unknown_set0),
CelValue::CreateUnknownSet(&unknown_set1), true,
&result, true);
ASSERT_OK(status);
ASSERT_TRUE(result.IsUnknownSet());
ASSERT_THAT(result.UnknownSetOrDie()->unknown_attributes().size(), Eq(2));
}
INSTANTIATE_TEST_SUITE_P(LogicStepTest, LogicStepTest, testing::Bool());
enum class Op { kAnd, kOr };
enum class OpArg {
kTrue,
kFalse,
kUnknown,
kError,
kInt
};
enum class OpResult {
kTrue,
kFalse,
kUnknown,
kError,
};
struct TestCase {
std::string name;
Op op;
OpArg arg0;
OpArg arg1;
OpResult result;
};
class DirectLogicStepTest
: public testing::TestWithParam<std::tuple<bool, TestCase>> {
public:
DirectLogicStepTest()
: value_factory_(TypeProvider::Builtin(),
ProtoMemoryManagerRef(&arena_)) {}
bool ShortcircuitingEnabled() { return std::get<0>(GetParam()); }
const TestCase& GetTestCase() { return std::get<1>(GetParam()); }
ValueManager& value_manager() { return value_factory_.get(); }
UnknownValue MakeUnknownValue(std::string attr) {
std::vector<Attribute> attrs;
attrs.push_back(Attribute(std::move(attr)));
return value_manager().CreateUnknownValue(AttributeSet(attrs));
}
protected:
Arena arena_;
ManagedValueFactory value_factory_;
};
TEST_P(DirectLogicStepTest, TestCases) {
const TestCase& test_case = GetTestCase();
auto MakeArg =
[&](OpArg arg,
absl::string_view name) -> std::unique_ptr<DirectExpressionStep> {
switch (arg) {
case OpArg::kTrue:
return CreateConstValueDirectStep(BoolValue(true));
case OpArg::kFalse:
return CreateConstValueDirectStep(BoolValue(false));
case OpArg::kUnknown:
return CreateConstValueDirectStep(MakeUnknownValue(std::string(name)));
case OpArg::kError:
return CreateConstValueDirectStep(
value_manager().CreateErrorValue(absl::InternalError(name)));
case OpArg::kInt:
return CreateConstValueDirectStep(IntValue(42));
}
};
std::unique_ptr<DirectExpressionStep> lhs = MakeArg(test_case.arg0, "lhs");
std::unique_ptr<DirectExpressionStep> rhs = MakeArg(test_case.arg1, "rhs");
std::unique_ptr<DirectExpressionStep> op =
(test_case.op == Op::kAnd)
? CreateDirectAndStep(std::move(lhs), std::move(rhs), -1,
ShortcircuitingEnabled())
: CreateDirectOrStep(std::move(lhs), std::move(rhs), -1,
ShortcircuitingEnabled());
cel::Activation activation;
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
ExecutionFrameBase frame(activation, options, value_manager());
Value value;
AttributeTrail attr;
ASSERT_OK(op->Evaluate(frame, value, attr));
switch (test_case.result) {
case OpResult::kTrue:
ASSERT_TRUE(InstanceOf<BoolValue>(value));
EXPECT_TRUE(Cast<BoolValue>(value).NativeValue());
break;
case OpResult::kFalse:
ASSERT_TRUE(InstanceOf<BoolValue>(value));
EXPECT_FALSE(Cast<BoolValue>(value).NativeValue());
break;
case OpResult::kUnknown:
EXPECT_TRUE(InstanceOf<UnknownValue>(value));
break;
case OpResult::kError:
EXPECT_TRUE(InstanceOf<ErrorValue>(value));
break;
}
}
INSTANTIATE_TEST_SUITE_P(
DirectLogicStepTest, DirectLogicStepTest,
testing::Combine(testing::Bool(),
testing::ValuesIn<std::vector<TestCase>>({
{
"AndFalseFalse",
Op::kAnd,
OpArg::kFalse,
OpArg::kFalse,
OpResult::kFalse,
},
{
"AndFalseTrue",
Op::kAnd,
OpArg::kFalse,
OpArg::kTrue,
OpResult::kFalse,
},
{
"AndTrueFalse",
Op::kAnd,
OpArg::kTrue,
OpArg::kFalse,
OpResult::kFalse,
},
{
"AndTrueTrue",
Op::kAnd,
OpArg::kTrue,
OpArg::kTrue,
OpResult::kTrue,
},
{
"AndTrueError",
Op::kAnd,
OpArg::kTrue,
OpArg::kError,
OpResult::kError,
},
{
"AndErrorTrue",
Op::kAnd,
OpArg::kError,
OpArg::kTrue,
OpResult::kError,
},
{
"AndFalseError",
Op::kAnd,
OpArg::kFalse,
OpArg::kError,
OpResult::kFalse,
},
{
"AndErrorFalse",
Op::kAnd,
OpArg::kError,
OpArg::kFalse,
OpResult::kFalse,
},
{
"AndErrorError",
Op::kAnd,
OpArg::kError,
OpArg::kError,
OpResult::kError,
},
{
"AndTrueUnknown",
Op::kAnd,
OpArg::kTrue,
OpArg::kUnknown,
OpResult::kUnknown,
},
{
"AndUnknownTrue",
Op::kAnd,
OpArg::kUnknown,
OpArg::kTrue,
OpResult::kUnknown,
},
{
"AndFalseUnknown",
Op::kAnd,
OpArg::kFalse,
OpArg::kUnknown,
OpResult::kFalse,
},
{
"AndUnknownFalse",
Op::kAnd,
OpArg::kUnknown,
OpArg::kFalse,
OpResult::kFalse,
},
{
"AndUnknownUnknown",
Op::kAnd,
OpArg::kUnknown,
OpArg::kUnknown,
OpResult::kUnknown,
},
{
"AndUnknownError",
Op::kAnd,
OpArg::kUnknown,
OpArg::kError,
OpResult::kUnknown,
},
{
"AndErrorUnknown",
Op::kAnd,
OpArg::kError,
OpArg::kUnknown,
OpResult::kUnknown,
},
})),
[](const testing::TestParamInfo<DirectLogicStepTest::ParamType>& info)
-> std::string {
bool shortcircuiting_enabled = std::get<0>(info.param);
absl::string_view name = std::get<1>(info.param).name;
return absl::StrCat(
name, (shortcircuiting_enabled ? "ShortcircuitingEnabled" : ""));
});
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/logic_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/logic_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
da2a6451-f55a-441f-80f9-ef5b7e5838ea | cpp | google/cel-cpp | compiler_constant_step | eval/eval/compiler_constant_step.cc | eval/eval/compiler_constant_step_test.cc | #include "eval/eval/compiler_constant_step.h"
#include "absl/status/status.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/evaluator_core.h"
namespace google::api::expr::runtime {
using ::cel::Value;
absl::Status DirectCompilerConstantStep::Evaluate(
ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const {
result = value_;
return absl::OkStatus();
}
absl::Status CompilerConstantStep::Evaluate(ExecutionFrame* frame) const {
frame->value_stack().Push(value_);
return absl::OkStatus();
}
} | #include "eval/eval/compiler_constant_step.h"
#include <memory>
#include "base/type_provider.h"
#include "common/native_type.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/eval/evaluator_core.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::extensions::ProtoMemoryManagerRef;
class CompilerConstantStepTest : public testing::Test {
public:
CompilerConstantStepTest()
: value_factory_(ProtoMemoryManagerRef(&arena_),
cel::TypeProvider::Builtin()),
state_(2, 0, cel::TypeProvider::Builtin(),
ProtoMemoryManagerRef(&arena_)) {}
protected:
google::protobuf::Arena arena_;
cel::common_internal::LegacyValueManager value_factory_;
FlatExpressionEvaluatorState state_;
cel::Activation empty_activation_;
cel::RuntimeOptions options_;
};
TEST_F(CompilerConstantStepTest, Evaluate) {
ExecutionPath path;
path.push_back(std::make_unique<CompilerConstantStep>(
value_factory_.CreateIntValue(42), -1, false));
ExecutionFrame frame(path, empty_activation_, options_, state_);
ASSERT_OK_AND_ASSIGN(cel::Value result, frame.Evaluate());
EXPECT_EQ(result.GetInt().NativeValue(), 42);
}
TEST_F(CompilerConstantStepTest, TypeId) {
CompilerConstantStep step(value_factory_.CreateIntValue(42), -1, false);
ExpressionStep& abstract_step = step;
EXPECT_EQ(abstract_step.GetNativeTypeId(),
cel::NativeTypeId::For<CompilerConstantStep>());
}
TEST_F(CompilerConstantStepTest, Value) {
CompilerConstantStep step(value_factory_.CreateIntValue(42), -1, false);
EXPECT_EQ(step.value().GetInt().NativeValue(), 42);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/compiler_constant_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/compiler_constant_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
fde120b0-1aa9-42e2-bdb5-409300d0c5d4 | cpp | google/cel-cpp | shadowable_value_step | eval/eval/shadowable_value_step.cc | eval/eval/shadowable_value_step_test.cc | #include "eval/eval/shadowable_value_step.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Value;
class ShadowableValueStep : public ExpressionStepBase {
public:
ShadowableValueStep(std::string identifier, cel::Value value, int64_t expr_id)
: ExpressionStepBase(expr_id),
identifier_(std::move(identifier)),
value_(std::move(value)) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
std::string identifier_;
Value value_;
};
absl::Status ShadowableValueStep::Evaluate(ExecutionFrame* frame) const {
cel::Value result;
CEL_ASSIGN_OR_RETURN(auto found,
frame->modern_activation().FindVariable(
frame->value_factory(), identifier_, result));
if (found) {
frame->value_stack().Push(std::move(result));
} else {
frame->value_stack().Push(value_);
}
return absl::OkStatus();
}
class DirectShadowableValueStep : public DirectExpressionStep {
public:
DirectShadowableValueStep(std::string identifier, cel::Value value,
int64_t expr_id)
: DirectExpressionStep(expr_id),
identifier_(std::move(identifier)),
value_(std::move(value)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override;
private:
std::string identifier_;
Value value_;
};
absl::Status DirectShadowableValueStep::Evaluate(
ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const {
CEL_ASSIGN_OR_RETURN(auto found,
frame.activation().FindVariable(frame.value_manager(),
identifier_, result));
if (!found) {
result = value_;
}
return absl::OkStatus();
}
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateShadowableValueStep(
std::string identifier, cel::Value value, int64_t expr_id) {
return absl::make_unique<ShadowableValueStep>(std::move(identifier),
std::move(value), expr_id);
}
std::unique_ptr<DirectExpressionStep> CreateDirectShadowableValueStep(
std::string identifier, cel::Value value, int64_t expr_id) {
return std::make_unique<DirectShadowableValueStep>(std::move(identifier),
std::move(value), expr_id);
}
} | #include "eval/eval/shadowable_value_step.h"
#include <string>
#include <utility>
#include "absl/status/statusor.h"
#include "base/type_provider.h"
#include "common/value.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/evaluator_core.h"
#include "eval/internal/interop.h"
#include "eval/public/activation.h"
#include "eval/public/cel_value.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::TypeProvider;
using ::cel::interop_internal::CreateTypeValueFromView;
using ::google::protobuf::Arena;
using ::testing::Eq;
absl::StatusOr<CelValue> RunShadowableExpression(std::string identifier,
cel::Value value,
const Activation& activation,
Arena* arena) {
CEL_ASSIGN_OR_RETURN(
auto step,
CreateShadowableValueStep(std::move(identifier), std::move(value), 1));
ExecutionPath path;
path.push_back(std::move(step));
CelExpressionFlatImpl impl(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
return impl.Evaluate(activation, arena);
}
TEST(ShadowableValueStepTest, TestEvaluateNoShadowing) {
std::string type_name = "google.api.expr.runtime.TestMessage";
Activation activation;
Arena arena;
auto type_value = CreateTypeValueFromView(&arena, type_name);
auto status =
RunShadowableExpression(type_name, type_value, activation, &arena);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsCelType());
EXPECT_THAT(value.CelTypeOrDie().value(), Eq(type_name));
}
TEST(ShadowableValueStepTest, TestEvaluateShadowedIdentifier) {
std::string type_name = "int";
auto shadow_value = CelValue::CreateInt64(1024L);
Activation activation;
activation.InsertValue(type_name, shadow_value);
Arena arena;
auto type_value = CreateTypeValueFromView(&arena, type_name);
auto status =
RunShadowableExpression(type_name, type_value, activation, &arena);
ASSERT_OK(status);
auto value = status.value();
ASSERT_TRUE(value.IsInt64());
EXPECT_THAT(value.Int64OrDie(), Eq(1024L));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/shadowable_value_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/shadowable_value_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
fc3560e5-2b8f-44c2-a833-d7c51b00604e | cpp | google/cel-cpp | ternary_step | eval/eval/ternary_step.cc | eval/eval/ternary_step_test.cc | #include "eval/eval/ternary_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "base/builtins.h"
#include "common/casting.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::UnknownValue;
using ::cel::builtin::kTernary;
using ::cel::runtime_internal::CreateNoMatchingOverloadError;
inline constexpr size_t kTernaryStepCondition = 0;
inline constexpr size_t kTernaryStepTrue = 1;
inline constexpr size_t kTernaryStepFalse = 2;
class ExhaustiveDirectTernaryStep : public DirectExpressionStep {
public:
ExhaustiveDirectTernaryStep(std::unique_ptr<DirectExpressionStep> condition,
std::unique_ptr<DirectExpressionStep> left,
std::unique_ptr<DirectExpressionStep> right,
int64_t expr_id)
: DirectExpressionStep(expr_id),
condition_(std::move(condition)),
left_(std::move(left)),
right_(std::move(right)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& attribute) const override {
cel::Value condition;
cel::Value lhs;
cel::Value rhs;
AttributeTrail condition_attr;
AttributeTrail lhs_attr;
AttributeTrail rhs_attr;
CEL_RETURN_IF_ERROR(condition_->Evaluate(frame, condition, condition_attr));
CEL_RETURN_IF_ERROR(left_->Evaluate(frame, lhs, lhs_attr));
CEL_RETURN_IF_ERROR(right_->Evaluate(frame, rhs, rhs_attr));
if (InstanceOf<ErrorValue>(condition) ||
InstanceOf<UnknownValue>(condition)) {
result = std::move(condition);
attribute = std::move(condition_attr);
return absl::OkStatus();
}
if (!InstanceOf<BoolValue>(condition)) {
result = frame.value_manager().CreateErrorValue(
CreateNoMatchingOverloadError(kTernary));
return absl::OkStatus();
}
if (Cast<BoolValue>(condition).NativeValue()) {
result = std::move(lhs);
attribute = std::move(lhs_attr);
} else {
result = std::move(rhs);
attribute = std::move(rhs_attr);
}
return absl::OkStatus();
}
private:
std::unique_ptr<DirectExpressionStep> condition_;
std::unique_ptr<DirectExpressionStep> left_;
std::unique_ptr<DirectExpressionStep> right_;
};
class ShortcircuitingDirectTernaryStep : public DirectExpressionStep {
public:
ShortcircuitingDirectTernaryStep(
std::unique_ptr<DirectExpressionStep> condition,
std::unique_ptr<DirectExpressionStep> left,
std::unique_ptr<DirectExpressionStep> right, int64_t expr_id)
: DirectExpressionStep(expr_id),
condition_(std::move(condition)),
left_(std::move(left)),
right_(std::move(right)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& attribute) const override {
cel::Value condition;
AttributeTrail condition_attr;
CEL_RETURN_IF_ERROR(condition_->Evaluate(frame, condition, condition_attr));
if (InstanceOf<ErrorValue>(condition) ||
InstanceOf<UnknownValue>(condition)) {
result = std::move(condition);
attribute = std::move(condition_attr);
return absl::OkStatus();
}
if (!InstanceOf<BoolValue>(condition)) {
result = frame.value_manager().CreateErrorValue(
CreateNoMatchingOverloadError(kTernary));
return absl::OkStatus();
}
if (Cast<BoolValue>(condition).NativeValue()) {
return left_->Evaluate(frame, result, attribute);
}
return right_->Evaluate(frame, result, attribute);
}
private:
std::unique_ptr<DirectExpressionStep> condition_;
std::unique_ptr<DirectExpressionStep> left_;
std::unique_ptr<DirectExpressionStep> right_;
};
class TernaryStep : public ExpressionStepBase {
public:
explicit TernaryStep(int64_t expr_id) : ExpressionStepBase(expr_id) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
};
absl::Status TernaryStep::Evaluate(ExecutionFrame* frame) const {
if (!frame->value_stack().HasEnough(3)) {
return absl::Status(absl::StatusCode::kInternal, "Value stack underflow");
}
auto args = frame->value_stack().GetSpan(3);
const auto& condition = args[kTernaryStepCondition];
if (frame->enable_unknowns()) {
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::Value result;
if (!condition->Is<cel::BoolValue>()) {
result = frame->value_factory().CreateErrorValue(
CreateNoMatchingOverloadError(kTernary));
} else if (condition.GetBool().NativeValue()) {
result = args[kTernaryStepTrue];
} else {
result = args[kTernaryStepFalse];
}
frame->value_stack().PopAndPush(args.size(), std::move(result));
return absl::OkStatus();
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectTernaryStep(
std::unique_ptr<DirectExpressionStep> condition,
std::unique_ptr<DirectExpressionStep> left,
std::unique_ptr<DirectExpressionStep> right, int64_t expr_id,
bool shortcircuiting) {
if (shortcircuiting) {
return std::make_unique<ShortcircuitingDirectTernaryStep>(
std::move(condition), std::move(left), std::move(right), expr_id);
}
return std::make_unique<ExhaustiveDirectTernaryStep>(
std::move(condition), std::move(left), std::move(right), expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateTernaryStep(
int64_t expr_id) {
return std::make_unique<TernaryStep>(expr_id);
}
} | #include "eval/eval/ternary_step.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/status/status.h"
#include "base/ast_internal/expr.h"
#include "base/attribute.h"
#include "base/attribute_set.h"
#include "base/type_provider.h"
#include "common/casting.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_value.h"
#include "eval/public/unknown_attribute_set.h"
#include "eval/public/unknown_set.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::RuntimeOptions;
using ::cel::TypeProvider;
using ::cel::UnknownValue;
using ::cel::ValueManager;
using ::cel::ast_internal::Expr;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::google::protobuf::Arena;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Truly;
class LogicStepTest : public testing::TestWithParam<bool> {
public:
absl::Status EvaluateLogic(CelValue arg0, CelValue arg1, CelValue arg2,
CelValue* result, bool enable_unknown) {
Expr expr0;
expr0.set_id(1);
auto& ident_expr0 = expr0.mutable_ident_expr();
ident_expr0.set_name("name0");
Expr expr1;
expr1.set_id(2);
auto& ident_expr1 = expr1.mutable_ident_expr();
ident_expr1.set_name("name1");
Expr expr2;
expr2.set_id(3);
auto& ident_expr2 = expr2.mutable_ident_expr();
ident_expr2.set_name("name2");
ExecutionPath path;
CEL_ASSIGN_OR_RETURN(auto step, CreateIdentStep(ident_expr0, expr0.id()));
path.push_back(std::move(step));
CEL_ASSIGN_OR_RETURN(step, CreateIdentStep(ident_expr1, expr1.id()));
path.push_back(std::move(step));
CEL_ASSIGN_OR_RETURN(step, CreateIdentStep(ident_expr2, expr2.id()));
path.push_back(std::move(step));
CEL_ASSIGN_OR_RETURN(step, CreateTernaryStep(4));
path.push_back(std::move(step));
cel::RuntimeOptions options;
if (enable_unknown) {
options.unknown_processing =
cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl impl(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
Activation activation;
std::string value("test");
activation.InsertValue("name0", arg0);
activation.InsertValue("name1", arg1);
activation.InsertValue("name2", arg2);
auto status0 = impl.Evaluate(activation, &arena_);
if (!status0.ok()) return status0.status();
*result = status0.value();
return absl::OkStatus();
}
private:
Arena arena_;
};
TEST_P(LogicStepTest, TestBoolCond) {
CelValue result;
absl::Status status =
EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(true),
CelValue::CreateBool(false), &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
status =
EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(true),
CelValue::CreateBool(false), &result, GetParam());
ASSERT_OK(status);
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
TEST_P(LogicStepTest, TestErrorHandling) {
CelValue result;
CelError error = absl::CancelledError();
CelValue error_value = CelValue::CreateError(&error);
ASSERT_OK(EvaluateLogic(error_value, CelValue::CreateBool(true),
CelValue::CreateBool(false), &result, GetParam()));
ASSERT_TRUE(result.IsError());
ASSERT_OK(EvaluateLogic(CelValue::CreateBool(true), error_value,
CelValue::CreateBool(false), &result, GetParam()));
ASSERT_TRUE(result.IsError());
ASSERT_OK(EvaluateLogic(CelValue::CreateBool(false), error_value,
CelValue::CreateBool(false), &result, GetParam()));
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
TEST_F(LogicStepTest, TestUnknownHandling) {
CelValue result;
UnknownSet unknown_set;
CelError cel_error = absl::CancelledError();
CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set);
CelValue error_value = CelValue::CreateError(&cel_error);
ASSERT_OK(EvaluateLogic(unknown_value, CelValue::CreateBool(true),
CelValue::CreateBool(false), &result, true));
ASSERT_TRUE(result.IsUnknownSet());
ASSERT_OK(EvaluateLogic(CelValue::CreateBool(true), unknown_value,
CelValue::CreateBool(false), &result, true));
ASSERT_TRUE(result.IsUnknownSet());
ASSERT_OK(EvaluateLogic(CelValue::CreateBool(false), unknown_value,
CelValue::CreateBool(false), &result, true));
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
ASSERT_OK(EvaluateLogic(error_value, unknown_value,
CelValue::CreateBool(false), &result, true));
ASSERT_TRUE(result.IsError());
ASSERT_OK(EvaluateLogic(unknown_value, error_value,
CelValue::CreateBool(false), &result, true));
ASSERT_TRUE(result.IsUnknownSet());
Expr expr0;
auto& ident_expr0 = expr0.mutable_ident_expr();
ident_expr0.set_name("name0");
Expr expr1;
auto& ident_expr1 = expr1.mutable_ident_expr();
ident_expr1.set_name("name1");
CelAttribute attr0(expr0.ident_expr().name(), {}),
attr1(expr1.ident_expr().name(), {});
UnknownAttributeSet unknown_attr_set0({attr0});
UnknownAttributeSet unknown_attr_set1({attr1});
UnknownSet unknown_set0(unknown_attr_set0);
UnknownSet unknown_set1(unknown_attr_set1);
EXPECT_THAT(unknown_attr_set0.size(), Eq(1));
EXPECT_THAT(unknown_attr_set1.size(), Eq(1));
ASSERT_OK(EvaluateLogic(CelValue::CreateUnknownSet(&unknown_set0),
CelValue::CreateUnknownSet(&unknown_set1),
CelValue::CreateBool(false), &result, true));
ASSERT_TRUE(result.IsUnknownSet());
const auto& attrs = result.UnknownSetOrDie()->unknown_attributes();
ASSERT_THAT(attrs, testing::SizeIs(1));
EXPECT_THAT(attrs.begin()->variable_name(), Eq("name0"));
}
INSTANTIATE_TEST_SUITE_P(LogicStepTest, LogicStepTest, testing::Bool());
class TernaryStepDirectTest : public testing::TestWithParam<bool> {
public:
TernaryStepDirectTest()
: value_factory_(TypeProvider::Builtin(),
ProtoMemoryManagerRef(&arena_)) {}
bool Shortcircuiting() { return GetParam(); }
ValueManager& value_manager() { return value_factory_.get(); }
protected:
Arena arena_;
cel::ManagedValueFactory value_factory_;
};
TEST_P(TernaryStepDirectTest, ReturnLhs) {
cel::Activation activation;
RuntimeOptions opts;
ExecutionFrameBase frame(activation, opts, value_manager());
std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep(
CreateConstValueDirectStep(BoolValue(true), -1),
CreateConstValueDirectStep(IntValue(1), -1),
CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting());
cel::Value result;
AttributeTrail attr_unused;
ASSERT_OK(step->Evaluate(frame, result, attr_unused));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 1);
}
TEST_P(TernaryStepDirectTest, ReturnRhs) {
cel::Activation activation;
RuntimeOptions opts;
ExecutionFrameBase frame(activation, opts, value_manager());
std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep(
CreateConstValueDirectStep(BoolValue(false), -1),
CreateConstValueDirectStep(IntValue(1), -1),
CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting());
cel::Value result;
AttributeTrail attr_unused;
ASSERT_OK(step->Evaluate(frame, result, attr_unused));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 2);
}
TEST_P(TernaryStepDirectTest, ForwardError) {
cel::Activation activation;
RuntimeOptions opts;
ExecutionFrameBase frame(activation, opts, value_manager());
cel::Value error_value =
value_manager().CreateErrorValue(absl::InternalError("test error"));
std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep(
CreateConstValueDirectStep(error_value, -1),
CreateConstValueDirectStep(IntValue(1), -1),
CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting());
cel::Value result;
AttributeTrail attr_unused;
ASSERT_OK(step->Evaluate(frame, result, attr_unused));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInternal, "test error"));
}
TEST_P(TernaryStepDirectTest, ForwardUnknown) {
cel::Activation activation;
RuntimeOptions opts;
opts.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
ExecutionFrameBase frame(activation, opts, value_manager());
std::vector<cel::Attribute> attrs{{cel::Attribute("var")}};
cel::UnknownValue unknown_value =
value_manager().CreateUnknownValue(cel::AttributeSet(attrs));
std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep(
CreateConstValueDirectStep(unknown_value, -1),
CreateConstValueDirectStep(IntValue(2), -1),
CreateConstValueDirectStep(IntValue(3), -1), -1, Shortcircuiting());
cel::Value result;
AttributeTrail attr_unused;
ASSERT_OK(step->Evaluate(frame, result, attr_unused));
ASSERT_TRUE(InstanceOf<UnknownValue>(result));
EXPECT_THAT(Cast<UnknownValue>(result).NativeValue().unknown_attributes(),
ElementsAre(Truly([](const cel::Attribute& attr) {
return attr.variable_name() == "var";
})));
}
TEST_P(TernaryStepDirectTest, UnexpectedCondtionKind) {
cel::Activation activation;
RuntimeOptions opts;
ExecutionFrameBase frame(activation, opts, value_manager());
std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep(
CreateConstValueDirectStep(IntValue(-1), -1),
CreateConstValueDirectStep(IntValue(1), -1),
CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting());
cel::Value result;
AttributeTrail attr_unused;
ASSERT_OK(step->Evaluate(frame, result, attr_unused));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kUnknown,
HasSubstr("No matching overloads found")));
}
TEST_P(TernaryStepDirectTest, Shortcircuiting) {
class RecordCallStep : public DirectExpressionStep {
public:
explicit RecordCallStep(bool& was_called)
: DirectExpressionStep(-1), was_called_(&was_called) {}
absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result,
AttributeTrail& trail) const override {
*was_called_ = true;
result = IntValue(1);
return absl::OkStatus();
}
private:
absl::Nonnull<bool*> was_called_;
};
bool lhs_was_called = false;
bool rhs_was_called = false;
cel::Activation activation;
RuntimeOptions opts;
ExecutionFrameBase frame(activation, opts, value_manager());
std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep(
CreateConstValueDirectStep(BoolValue(false), -1),
std::make_unique<RecordCallStep>(lhs_was_called),
std::make_unique<RecordCallStep>(rhs_was_called), -1, Shortcircuiting());
cel::Value result;
AttributeTrail attr_unused;
ASSERT_OK(step->Evaluate(frame, result, attr_unused));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_THAT(Cast<IntValue>(result).NativeValue(), Eq(1));
bool expect_eager_eval = !Shortcircuiting();
EXPECT_EQ(lhs_was_called, expect_eager_eval);
EXPECT_TRUE(rhs_was_called);
}
INSTANTIATE_TEST_SUITE_P(TernaryStepDirectTest, TernaryStepDirectTest,
testing::Bool());
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/ternary_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/ternary_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5d32953b-d4e0-443f-b032-8a137a203bae | cpp | google/cel-cpp | evaluator_stack | eval/eval/evaluator_stack.cc | eval/eval/evaluator_stack_test.cc | #include "eval/eval/evaluator_stack.h"
namespace google::api::expr::runtime {
void EvaluatorStack::Clear() {
stack_.clear();
attribute_stack_.clear();
current_size_ = 0;
}
} | #include "eval/eval/evaluator_stack.h"
#include "base/attribute.h"
#include "base/type_provider.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::TypeFactory;
using ::cel::TypeManager;
using ::cel::TypeProvider;
using ::cel::ValueManager;
using ::cel::extensions::ProtoMemoryManagerRef;
TEST(EvaluatorStackTest, StackPushPop) {
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
cel::common_internal::LegacyValueManager value_factory(
manager, TypeProvider::Builtin());
cel::Attribute attribute("name", {});
EvaluatorStack stack(10);
stack.Push(value_factory.CreateIntValue(1));
stack.Push(value_factory.CreateIntValue(2), AttributeTrail());
stack.Push(value_factory.CreateIntValue(3), AttributeTrail("name"));
ASSERT_EQ(stack.Peek().GetInt().NativeValue(), 3);
ASSERT_FALSE(stack.PeekAttribute().empty());
ASSERT_EQ(stack.PeekAttribute().attribute(), attribute);
stack.Pop(1);
ASSERT_EQ(stack.Peek().GetInt().NativeValue(), 2);
ASSERT_TRUE(stack.PeekAttribute().empty());
stack.Pop(1);
ASSERT_EQ(stack.Peek().GetInt().NativeValue(), 1);
ASSERT_TRUE(stack.PeekAttribute().empty());
}
TEST(EvaluatorStackTest, StackBalanced) {
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
cel::common_internal::LegacyValueManager value_factory(
manager, TypeProvider::Builtin());
EvaluatorStack stack(10);
ASSERT_EQ(stack.size(), stack.attribute_size());
stack.Push(value_factory.CreateIntValue(1));
ASSERT_EQ(stack.size(), stack.attribute_size());
stack.Push(value_factory.CreateIntValue(2), AttributeTrail());
stack.Push(value_factory.CreateIntValue(3), AttributeTrail());
ASSERT_EQ(stack.size(), stack.attribute_size());
stack.PopAndPush(value_factory.CreateIntValue(4), AttributeTrail());
ASSERT_EQ(stack.size(), stack.attribute_size());
stack.PopAndPush(value_factory.CreateIntValue(5));
ASSERT_EQ(stack.size(), stack.attribute_size());
stack.Pop(3);
ASSERT_EQ(stack.size(), stack.attribute_size());
}
TEST(EvaluatorStackTest, Clear) {
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
cel::common_internal::LegacyValueManager value_factory(
manager, TypeProvider::Builtin());
EvaluatorStack stack(10);
ASSERT_EQ(stack.size(), stack.attribute_size());
stack.Push(value_factory.CreateIntValue(1));
stack.Push(value_factory.CreateIntValue(2), AttributeTrail());
stack.Push(value_factory.CreateIntValue(3), AttributeTrail());
ASSERT_EQ(stack.size(), 3);
stack.Clear();
ASSERT_EQ(stack.size(), 0);
ASSERT_TRUE(stack.empty());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/evaluator_stack.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/evaluator_stack_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
8c0d2933-3526-4cfe-b392-f834ea6bc8ef | cpp | google/cel-cpp | regex_match_step | eval/eval/regex_match_step.cc | eval/eval/regex_match_step_test.cc | #include "eval/eval/regex_match_step.h"
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "common/casting.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "internal/status_macros.h"
#include "re2/re2.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::BoolValue;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::StringValue;
using ::cel::UnknownValue;
using ::cel::Value;
inline constexpr int kNumRegexMatchArguments = 1;
inline constexpr size_t kRegexMatchStepSubject = 0;
struct MatchesVisitor final {
const RE2& re;
bool operator()(const absl::Cord& value) const {
if (auto flat = value.TryFlat(); flat.has_value()) {
return RE2::PartialMatch(*flat, re);
}
return RE2::PartialMatch(static_cast<std::string>(value), re);
}
bool operator()(absl::string_view value) const {
return RE2::PartialMatch(value, re);
}
};
class RegexMatchStep final : public ExpressionStepBase {
public:
RegexMatchStep(int64_t expr_id, std::shared_ptr<const RE2> re2)
: ExpressionStepBase(expr_id, true),
re2_(std::move(re2)) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
if (!frame->value_stack().HasEnough(kNumRegexMatchArguments)) {
return absl::Status(absl::StatusCode::kInternal,
"Insufficient arguments supplied for regular "
"expression match");
}
auto input_args = frame->value_stack().GetSpan(kNumRegexMatchArguments);
const auto& subject = input_args[kRegexMatchStepSubject];
if (!subject->Is<cel::StringValue>()) {
return absl::Status(absl::StatusCode::kInternal,
"First argument for regular "
"expression match must be a string");
}
bool match = subject.GetString().NativeValue(MatchesVisitor{*re2_});
frame->value_stack().Pop(kNumRegexMatchArguments);
frame->value_stack().Push(frame->value_factory().CreateBoolValue(match));
return absl::OkStatus();
}
private:
const std::shared_ptr<const RE2> re2_;
};
class RegexMatchDirectStep final : public DirectExpressionStep {
public:
RegexMatchDirectStep(int64_t expr_id,
std::unique_ptr<DirectExpressionStep> subject,
std::shared_ptr<const RE2> re2)
: DirectExpressionStep(expr_id),
subject_(std::move(subject)),
re2_(std::move(re2)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override {
AttributeTrail subject_attr;
CEL_RETURN_IF_ERROR(subject_->Evaluate(frame, result, subject_attr));
if (InstanceOf<ErrorValue>(result) ||
cel::InstanceOf<UnknownValue>(result)) {
return absl::OkStatus();
}
if (!InstanceOf<StringValue>(result)) {
return absl::Status(absl::StatusCode::kInternal,
"First argument for regular "
"expression match must be a string");
}
bool match = Cast<StringValue>(result).NativeValue(MatchesVisitor{*re2_});
result = BoolValue(match);
return absl::OkStatus();
}
private:
std::unique_ptr<DirectExpressionStep> subject_;
const std::shared_ptr<const RE2> re2_;
};
}
std::unique_ptr<DirectExpressionStep> CreateDirectRegexMatchStep(
int64_t expr_id, std::unique_ptr<DirectExpressionStep> subject,
std::shared_ptr<const RE2> re2) {
return std::make_unique<RegexMatchDirectStep>(expr_id, std::move(subject),
std::move(re2));
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateRegexMatchStep(
std::shared_ptr<const RE2> re2, int64_t expr_id) {
return std::make_unique<RegexMatchStep>(expr_id, std::move(re2));
}
} | #include "eval/eval/regex_match_step.h"
#include "google/api/expr/v1alpha1/checked.pb.h"
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/arena.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "eval/public/activation.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_expr_builder_factory.h"
#include "eval/public/cel_options.h"
#include "internal/testing.h"
#include "parser/parser.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using google::api::expr::v1alpha1::CheckedExpr;
using google::api::expr::v1alpha1::Reference;
using ::testing::Eq;
using ::testing::HasSubstr;
Reference MakeMatchesStringOverload() {
Reference reference;
reference.add_overload_id("matches_string");
return reference;
}
TEST(RegexMatchStep, Precompiled) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(auto parsed_expr, parser::Parse("foo.matches('hello')"));
CheckedExpr checked_expr;
*checked_expr.mutable_expr() = parsed_expr.expr();
*checked_expr.mutable_source_info() = parsed_expr.source_info();
checked_expr.mutable_reference_map()->insert(
{checked_expr.expr().id(), MakeMatchesStringOverload()});
InterpreterOptions options;
options.enable_regex_precompilation = true;
auto expr_builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(expr_builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto expr,
expr_builder->CreateExpression(&checked_expr));
activation.InsertValue("foo", CelValue::CreateStringView("hello world!"));
ASSERT_OK_AND_ASSIGN(auto result, expr->Evaluate(activation, &arena));
EXPECT_TRUE(result.IsBool());
EXPECT_TRUE(result.BoolOrDie());
}
TEST(RegexMatchStep, PrecompiledInvalidRegex) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(auto parsed_expr, parser::Parse("foo.matches('(')"));
CheckedExpr checked_expr;
*checked_expr.mutable_expr() = parsed_expr.expr();
*checked_expr.mutable_source_info() = parsed_expr.source_info();
checked_expr.mutable_reference_map()->insert(
{checked_expr.expr().id(), MakeMatchesStringOverload()});
InterpreterOptions options;
options.enable_regex_precompilation = true;
auto expr_builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(expr_builder->GetRegistry(), options));
EXPECT_THAT(expr_builder->CreateExpression(&checked_expr),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("invalid_argument")));
}
TEST(RegexMatchStep, PrecompiledInvalidProgramTooLarge) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(auto parsed_expr, parser::Parse("foo.matches('hello')"));
CheckedExpr checked_expr;
*checked_expr.mutable_expr() = parsed_expr.expr();
*checked_expr.mutable_source_info() = parsed_expr.source_info();
checked_expr.mutable_reference_map()->insert(
{checked_expr.expr().id(), MakeMatchesStringOverload()});
InterpreterOptions options;
options.regex_max_program_size = 1;
options.enable_regex_precompilation = true;
auto expr_builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(expr_builder->GetRegistry(), options));
EXPECT_THAT(expr_builder->CreateExpression(&checked_expr),
StatusIs(absl::StatusCode::kInvalidArgument,
Eq("exceeded RE2 max program size")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/regex_match_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/regex_match_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
3c493440-0107-46b2-90da-81f8f83f4b45 | cpp | google/cel-cpp | create_map_step | eval/eval/create_map_step.cc | eval/eval/create_map_step_test.cc | #include "eval/eval/create_map_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/casting.h"
#include "common/memory.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::StructValueBuilderInterface;
using ::cel::UnknownValue;
using ::cel::Value;
class CreateStructStepForMap final : public ExpressionStepBase {
public:
CreateStructStepForMap(int64_t expr_id, size_t entry_count,
absl::flat_hash_set<int32_t> optional_indices)
: ExpressionStepBase(expr_id),
entry_count_(entry_count),
optional_indices_(std::move(optional_indices)) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
absl::StatusOr<Value> DoEvaluate(ExecutionFrame* frame) const;
size_t entry_count_;
absl::flat_hash_set<int32_t> optional_indices_;
};
absl::StatusOr<Value> CreateStructStepForMap::DoEvaluate(
ExecutionFrame* frame) const {
auto args = frame->value_stack().GetSpan(2 * entry_count_);
if (frame->enable_unknowns()) {
absl::optional<UnknownValue> unknown_set =
frame->attribute_utility().IdentifyAndMergeUnknowns(
args, frame->value_stack().GetAttributeSpan(args.size()), true);
if (unknown_set.has_value()) {
return *unknown_set;
}
}
CEL_ASSIGN_OR_RETURN(
auto builder, frame->value_manager().NewMapValueBuilder(cel::MapType{}));
builder->Reserve(entry_count_);
for (size_t i = 0; i < entry_count_; i += 1) {
auto& map_key = args[2 * i];
CEL_RETURN_IF_ERROR(cel::CheckMapKey(map_key));
auto& map_value = args[(2 * i) + 1];
if (optional_indices_.contains(static_cast<int32_t>(i))) {
if (auto optional_map_value = cel::As<cel::OptionalValue>(map_value);
optional_map_value) {
if (!optional_map_value->HasValue()) {
continue;
}
auto key_status =
builder->Put(std::move(map_key), optional_map_value->Value());
if (!key_status.ok()) {
return frame->value_factory().CreateErrorValue(key_status);
}
} else {
return cel::TypeConversionError(map_value.DebugString(),
"optional_type")
.NativeValue();
}
} else {
auto key_status = builder->Put(std::move(map_key), std::move(map_value));
if (!key_status.ok()) {
return frame->value_factory().CreateErrorValue(key_status);
}
}
}
return std::move(*builder).Build();
}
absl::Status CreateStructStepForMap::Evaluate(ExecutionFrame* frame) const {
if (frame->value_stack().size() < 2 * entry_count_) {
return absl::InternalError("CreateStructStepForMap: stack underflow");
}
CEL_ASSIGN_OR_RETURN(auto result, DoEvaluate(frame));
frame->value_stack().PopAndPush(2 * entry_count_, std::move(result));
return absl::OkStatus();
}
class DirectCreateMapStep : public DirectExpressionStep {
public:
DirectCreateMapStep(std::vector<std::unique_ptr<DirectExpressionStep>> deps,
absl::flat_hash_set<int32_t> optional_indices,
int64_t expr_id)
: DirectExpressionStep(expr_id),
deps_(std::move(deps)),
optional_indices_(std::move(optional_indices)),
entry_count_(deps_.size() / 2) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute_trail) const override;
private:
std::vector<std::unique_ptr<DirectExpressionStep>> deps_;
absl::flat_hash_set<int32_t> optional_indices_;
size_t entry_count_;
};
absl::Status DirectCreateMapStep::Evaluate(
ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute_trail) const {
Value key;
Value value;
AttributeTrail tmp_attr;
auto unknowns = frame.attribute_utility().CreateAccumulator();
CEL_ASSIGN_OR_RETURN(auto builder,
frame.value_manager().NewMapValueBuilder(
frame.value_manager().GetDynDynMapType()));
builder->Reserve(entry_count_);
for (size_t i = 0; i < entry_count_; i += 1) {
int map_key_index = 2 * i;
int map_value_index = map_key_index + 1;
CEL_RETURN_IF_ERROR(deps_[map_key_index]->Evaluate(frame, key, tmp_attr));
if (InstanceOf<ErrorValue>(key)) {
result = key;
return absl::OkStatus();
}
if (frame.unknown_processing_enabled()) {
if (InstanceOf<UnknownValue>(key)) {
unknowns.Add(Cast<UnknownValue>(key));
} else if (frame.attribute_utility().CheckForUnknownPartial(tmp_attr)) {
unknowns.Add(tmp_attr);
}
}
CEL_RETURN_IF_ERROR(
deps_[map_value_index]->Evaluate(frame, value, tmp_attr));
if (InstanceOf<ErrorValue>(value)) {
result = value;
return absl::OkStatus();
}
if (frame.unknown_processing_enabled()) {
if (InstanceOf<UnknownValue>(value)) {
unknowns.Add(Cast<UnknownValue>(value));
} else if (frame.attribute_utility().CheckForUnknownPartial(tmp_attr)) {
unknowns.Add(tmp_attr);
}
}
if (!unknowns.IsEmpty()) {
continue;
}
if (optional_indices_.contains(static_cast<int32_t>(i))) {
if (auto optional_map_value =
cel::As<cel::OptionalValue>(static_cast<const Value&>(value));
optional_map_value) {
if (!optional_map_value->HasValue()) {
continue;
}
auto key_status =
builder->Put(std::move(key), optional_map_value->Value());
if (!key_status.ok()) {
result = frame.value_manager().CreateErrorValue(key_status);
return absl::OkStatus();
}
continue;
}
return cel::TypeConversionError(value.DebugString(), "optional_type")
.NativeValue();
}
CEL_RETURN_IF_ERROR(cel::CheckMapKey(key));
auto put_status = builder->Put(std::move(key), std::move(value));
if (!put_status.ok()) {
result = frame.value_manager().CreateErrorValue(put_status);
return absl::OkStatus();
}
}
if (!unknowns.IsEmpty()) {
result = std::move(unknowns).Build();
return absl::OkStatus();
}
result = std::move(*builder).Build();
return absl::OkStatus();
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectCreateMapStep(
std::vector<std::unique_ptr<DirectExpressionStep>> deps,
absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) {
return std::make_unique<DirectCreateMapStep>(
std::move(deps), std::move(optional_indices), expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateCreateStructStepForMap(
size_t entry_count, absl::flat_hash_set<int32_t> optional_indices,
int64_t expr_id) {
return std::make_unique<CreateStructStepForMap>(expr_id, entry_count,
std::move(optional_indices));
}
} | #include "eval/eval/create_map_step.h"
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "base/ast_internal/expr.h"
#include "base/type_provider.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/public/activation.h"
#include "eval/public/cel_value.h"
#include "eval/public/unknown_set.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/runtime_options.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::TypeProvider;
using ::cel::ast_internal::Expr;
using ::google::protobuf::Arena;
absl::StatusOr<ExecutionPath> CreateStackMachineProgram(
const std::vector<std::pair<CelValue, CelValue>>& values,
Activation& activation) {
ExecutionPath path;
Expr expr1;
Expr expr0;
std::vector<Expr> exprs;
exprs.reserve(values.size() * 2);
int index = 0;
auto& create_struct = expr1.mutable_struct_expr();
for (const auto& item : values) {
std::string key_name = absl::StrCat("key", index);
std::string value_name = absl::StrCat("value", index);
auto& key_expr = exprs.emplace_back();
auto& key_ident = key_expr.mutable_ident_expr();
key_ident.set_name(key_name);
CEL_ASSIGN_OR_RETURN(auto step_key,
CreateIdentStep(key_ident, exprs.back().id()));
auto& value_expr = exprs.emplace_back();
auto& value_ident = value_expr.mutable_ident_expr();
value_ident.set_name(value_name);
CEL_ASSIGN_OR_RETURN(auto step_value,
CreateIdentStep(value_ident, exprs.back().id()));
path.push_back(std::move(step_key));
path.push_back(std::move(step_value));
activation.InsertValue(key_name, item.first);
activation.InsertValue(value_name, item.second);
create_struct.mutable_fields().emplace_back();
index++;
}
CEL_ASSIGN_OR_RETURN(
auto step1, CreateCreateStructStepForMap(values.size(), {}, expr1.id()));
path.push_back(std::move(step1));
return path;
}
absl::StatusOr<ExecutionPath> CreateRecursiveProgram(
const std::vector<std::pair<CelValue, CelValue>>& values,
Activation& activation) {
ExecutionPath path;
int index = 0;
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
for (const auto& item : values) {
std::string key_name = absl::StrCat("key", index);
std::string value_name = absl::StrCat("value", index);
deps.push_back(CreateDirectIdentStep(key_name, -1));
deps.push_back(CreateDirectIdentStep(value_name, -1));
activation.InsertValue(key_name, item.first);
activation.InsertValue(value_name, item.second);
index++;
}
path.push_back(std::make_unique<WrappedDirectStep>(
CreateDirectCreateMapStep(std::move(deps), {}, -1), -1));
return path;
}
absl::StatusOr<CelValue> RunCreateMapExpression(
const std::vector<std::pair<CelValue, CelValue>>& values,
google::protobuf::Arena* arena, bool enable_unknowns, bool enable_recursive_program) {
Activation activation;
ExecutionPath path;
if (enable_recursive_program) {
CEL_ASSIGN_OR_RETURN(path, CreateRecursiveProgram(values, activation));
} else {
CEL_ASSIGN_OR_RETURN(path, CreateStackMachineProgram(values, activation));
}
cel::RuntimeOptions options;
if (enable_unknowns) {
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
return cel_expr.Evaluate(activation, arena);
}
class CreateMapStepTest
: public testing::TestWithParam<std::tuple<bool, bool>> {
public:
bool enable_unknowns() { return std::get<0>(GetParam()); }
bool enable_recursive_program() { return std::get<1>(GetParam()); }
absl::StatusOr<CelValue> RunMapExpression(
const std::vector<std::pair<CelValue, CelValue>>& values,
google::protobuf::Arena* arena) {
return RunCreateMapExpression(values, arena, enable_unknowns(),
enable_recursive_program());
}
};
TEST_P(CreateMapStepTest, TestCreateEmptyMap) {
Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, RunMapExpression({}, &arena));
ASSERT_TRUE(result.IsMap());
const CelMap* cel_map = result.MapOrDie();
ASSERT_EQ(cel_map->size(), 0);
}
TEST(CreateMapStepTest, TestMapCreateWithUnknown) {
Arena arena;
UnknownSet unknown_set;
std::vector<std::pair<CelValue, CelValue>> entries;
std::vector<std::string> kKeys = {"test2", "test1"};
entries.push_back(
{CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)});
entries.push_back({CelValue::CreateString(&kKeys[1]),
CelValue::CreateUnknownSet(&unknown_set)});
ASSERT_OK_AND_ASSIGN(CelValue result,
RunCreateMapExpression(entries, &arena, true, false));
ASSERT_TRUE(result.IsUnknownSet());
}
TEST(CreateMapStepTest, TestMapCreateWithUnknownRecursiveProgram) {
Arena arena;
UnknownSet unknown_set;
std::vector<std::pair<CelValue, CelValue>> entries;
std::vector<std::string> kKeys = {"test2", "test1"};
entries.push_back(
{CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)});
entries.push_back({CelValue::CreateString(&kKeys[1]),
CelValue::CreateUnknownSet(&unknown_set)});
ASSERT_OK_AND_ASSIGN(CelValue result,
RunCreateMapExpression(entries, &arena, true, true));
ASSERT_TRUE(result.IsUnknownSet());
}
TEST_P(CreateMapStepTest, TestCreateStringMap) {
Arena arena;
std::vector<std::pair<CelValue, CelValue>> entries;
std::vector<std::string> kKeys = {"test2", "test1"};
entries.push_back(
{CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)});
entries.push_back(
{CelValue::CreateString(&kKeys[1]), CelValue::CreateInt64(1)});
ASSERT_OK_AND_ASSIGN(CelValue result, RunMapExpression(entries, &arena));
ASSERT_TRUE(result.IsMap());
const CelMap* cel_map = result.MapOrDie();
ASSERT_EQ(cel_map->size(), 2);
auto lookup0 = cel_map->Get(&arena, CelValue::CreateString(&kKeys[0]));
ASSERT_TRUE(lookup0.has_value());
ASSERT_TRUE(lookup0->IsInt64()) << lookup0->DebugString();
EXPECT_EQ(lookup0->Int64OrDie(), 2);
auto lookup1 = cel_map->Get(&arena, CelValue::CreateString(&kKeys[1]));
ASSERT_TRUE(lookup1.has_value());
ASSERT_TRUE(lookup1->IsInt64());
EXPECT_EQ(lookup1->Int64OrDie(), 1);
}
INSTANTIATE_TEST_SUITE_P(CreateMapStep, CreateMapStepTest,
testing::Combine(testing::Bool(), testing::Bool()));
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/create_map_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/create_map_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
1560fb68-ac27-4a30-ae6c-29abc590bc38 | cpp | google/cel-cpp | create_list_step | eval/eval/create_list_step.cc | eval/eval/create_list_step_test.cc | #include "eval/eval/create_list_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "base/ast_internal/expr.h"
#include "common/casting.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/attribute_utility.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "internal/status_macros.h"
#include "runtime/internal/mutable_list_impl.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::ListValueBuilderInterface;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::runtime_internal::MutableListValue;
class CreateListStep : public ExpressionStepBase {
public:
CreateListStep(int64_t expr_id, int list_size,
absl::flat_hash_set<int> optional_indices)
: ExpressionStepBase(expr_id),
list_size_(list_size),
optional_indices_(std::move(optional_indices)) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
int list_size_;
absl::flat_hash_set<int32_t> optional_indices_;
};
absl::Status CreateListStep::Evaluate(ExecutionFrame* frame) const {
if (list_size_ < 0) {
return absl::Status(absl::StatusCode::kInternal,
"CreateListStep: list size is <0");
}
if (!frame->value_stack().HasEnough(list_size_)) {
return absl::Status(absl::StatusCode::kInternal,
"CreateListStep: stack underflow");
}
auto args = frame->value_stack().GetSpan(list_size_);
cel::Value result;
for (const auto& arg : args) {
if (arg->Is<cel::ErrorValue>()) {
result = arg;
frame->value_stack().Pop(list_size_);
frame->value_stack().Push(std::move(result));
return absl::OkStatus();
}
}
if (frame->enable_unknowns()) {
absl::optional<UnknownValue> unknown_set =
frame->attribute_utility().IdentifyAndMergeUnknowns(
args, frame->value_stack().GetAttributeSpan(list_size_),
true);
if (unknown_set.has_value()) {
frame->value_stack().Pop(list_size_);
frame->value_stack().Push(std::move(unknown_set).value());
return absl::OkStatus();
}
}
CEL_ASSIGN_OR_RETURN(auto builder,
frame->value_manager().NewListValueBuilder(
frame->value_manager().GetDynListType()));
builder->Reserve(args.size());
for (size_t i = 0; i < args.size(); ++i) {
auto& arg = args[i];
if (optional_indices_.contains(static_cast<int32_t>(i))) {
if (auto optional_arg = cel::As<cel::OptionalValue>(arg); optional_arg) {
if (!optional_arg->HasValue()) {
continue;
}
CEL_RETURN_IF_ERROR(builder->Add(optional_arg->Value()));
} else {
return cel::TypeConversionError(arg.GetTypeName(), "optional_type")
.NativeValue();
}
} else {
CEL_RETURN_IF_ERROR(builder->Add(std::move(arg)));
}
}
frame->value_stack().PopAndPush(list_size_, std::move(*builder).Build());
return absl::OkStatus();
}
absl::flat_hash_set<int32_t> MakeOptionalIndicesSet(
const cel::ast_internal::CreateList& create_list_expr) {
absl::flat_hash_set<int32_t> optional_indices;
for (size_t i = 0; i < create_list_expr.elements().size(); ++i) {
if (create_list_expr.elements()[i].optional()) {
optional_indices.insert(static_cast<int32_t>(i));
}
}
return optional_indices;
}
class CreateListDirectStep : public DirectExpressionStep {
public:
CreateListDirectStep(
std::vector<std::unique_ptr<DirectExpressionStep>> elements,
absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id)
: DirectExpressionStep(expr_id),
elements_(std::move(elements)),
optional_indices_(std::move(optional_indices)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute_trail) const override {
CEL_ASSIGN_OR_RETURN(auto builder,
frame.value_manager().NewListValueBuilder(
frame.value_manager().GetDynListType()));
builder->Reserve(elements_.size());
AttributeUtility::Accumulator unknowns =
frame.attribute_utility().CreateAccumulator();
AttributeTrail tmp_attr;
for (size_t i = 0; i < elements_.size(); ++i) {
const auto& element = elements_[i];
CEL_RETURN_IF_ERROR(element->Evaluate(frame, result, tmp_attr));
if (cel::InstanceOf<ErrorValue>(result)) return absl::OkStatus();
if (frame.attribute_tracking_enabled()) {
if (frame.missing_attribute_errors_enabled()) {
if (frame.attribute_utility().CheckForMissingAttribute(tmp_attr)) {
CEL_ASSIGN_OR_RETURN(
result, frame.attribute_utility().CreateMissingAttributeError(
tmp_attr.attribute()));
return absl::OkStatus();
}
}
if (frame.unknown_processing_enabled()) {
if (InstanceOf<UnknownValue>(result)) {
unknowns.Add(Cast<UnknownValue>(result));
}
if (frame.attribute_utility().CheckForUnknown(tmp_attr,
true)) {
unknowns.Add(tmp_attr);
}
}
}
if (optional_indices_.contains(static_cast<int32_t>(i))) {
if (auto optional_arg =
cel::As<cel::OptionalValue>(static_cast<const Value&>(result));
optional_arg) {
if (!optional_arg->HasValue()) {
continue;
}
CEL_RETURN_IF_ERROR(builder->Add(optional_arg->Value()));
continue;
}
return cel::TypeConversionError(result.GetTypeName(), "optional_type")
.NativeValue();
}
CEL_RETURN_IF_ERROR(builder->Add(std::move(result)));
}
if (!unknowns.IsEmpty()) {
result = std::move(unknowns).Build();
return absl::OkStatus();
}
result = std::move(*builder).Build();
return absl::OkStatus();
}
private:
std::vector<std::unique_ptr<DirectExpressionStep>> elements_;
absl::flat_hash_set<int32_t> optional_indices_;
};
class MutableListStep : public ExpressionStepBase {
public:
explicit MutableListStep(int64_t expr_id) : ExpressionStepBase(expr_id) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
};
absl::Status MutableListStep::Evaluate(ExecutionFrame* frame) const {
CEL_ASSIGN_OR_RETURN(auto builder,
frame->value_manager().NewListValueBuilder(
frame->value_manager().GetDynListType()));
frame->value_stack().Push(cel::OpaqueValue{
frame->value_manager().GetMemoryManager().MakeShared<MutableListValue>(
std::move(builder))});
return absl::OkStatus();
}
class DirectMutableListStep : public DirectExpressionStep {
public:
explicit DirectMutableListStep(int64_t expr_id)
: DirectExpressionStep(expr_id) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override;
};
absl::Status DirectMutableListStep::Evaluate(
ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute_trail) const {
CEL_ASSIGN_OR_RETURN(auto builder,
frame.value_manager().NewListValueBuilder(
frame.value_manager().GetDynListType()));
result = cel::OpaqueValue{
frame.value_manager().GetMemoryManager().MakeShared<MutableListValue>(
std::move(builder))};
return absl::OkStatus();
}
}
std::unique_ptr<DirectExpressionStep> CreateDirectListStep(
std::vector<std::unique_ptr<DirectExpressionStep>> deps,
absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) {
return std::make_unique<CreateListDirectStep>(
std::move(deps), std::move(optional_indices), expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateCreateListStep(
const cel::ast_internal::CreateList& create_list_expr, int64_t expr_id) {
return std::make_unique<CreateListStep>(
expr_id, create_list_expr.elements().size(),
MakeOptionalIndicesSet(create_list_expr));
}
std::unique_ptr<ExpressionStep> CreateMutableListStep(int64_t expr_id) {
return std::make_unique<MutableListStep>(expr_id);
}
std::unique_ptr<DirectExpressionStep> CreateDirectMutableListStep(
int64_t expr_id) {
return std::make_unique<DirectMutableListStep>(expr_id);
}
} | #include "eval/eval/create_list_step.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "base/ast_internal/expr.h"
#include "base/attribute.h"
#include "base/attribute_set.h"
#include "base/type_provider.h"
#include "common/casting.h"
#include "common/memory.h"
#include "common/value.h"
#include "common/value_testing.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/ident_step.h"
#include "eval/internal/interop.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/testing/matchers.h"
#include "eval/public/unknown_attribute_set.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::IsOk;
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::cel::Attribute;
using ::cel::AttributeQualifier;
using ::cel::AttributeSet;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ListValue;
using ::cel::TypeProvider;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ast_internal::Expr;
using ::cel::test::IntValueIs;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Not;
using ::testing::UnorderedElementsAre;
absl::StatusOr<CelValue> RunExpression(const std::vector<int64_t>& values,
google::protobuf::Arena* arena,
bool enable_unknowns) {
ExecutionPath path;
Expr dummy_expr;
auto& create_list = dummy_expr.mutable_list_expr();
for (auto value : values) {
auto& expr0 = create_list.mutable_elements().emplace_back().mutable_expr();
expr0.mutable_const_expr().set_int64_value(value);
CEL_ASSIGN_OR_RETURN(
auto const_step,
CreateConstValueStep(cel::interop_internal::CreateIntValue(value),
-1));
path.push_back(std::move(const_step));
}
CEL_ASSIGN_OR_RETURN(auto step,
CreateCreateListStep(create_list, dummy_expr.id()));
path.push_back(std::move(step));
cel::RuntimeOptions options;
if (enable_unknowns) {
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path),
0, TypeProvider::Builtin(),
options));
Activation activation;
return cel_expr.Evaluate(activation, arena);
}
absl::StatusOr<CelValue> RunExpressionWithCelValues(
const std::vector<CelValue>& values, google::protobuf::Arena* arena,
bool enable_unknowns) {
ExecutionPath path;
Expr dummy_expr;
Activation activation;
auto& create_list = dummy_expr.mutable_list_expr();
int ind = 0;
for (auto value : values) {
std::string var_name = absl::StrCat("name_", ind++);
auto& expr0 = create_list.mutable_elements().emplace_back().mutable_expr();
expr0.set_id(ind);
expr0.mutable_ident_expr().set_name(var_name);
CEL_ASSIGN_OR_RETURN(auto ident_step,
CreateIdentStep(expr0.ident_expr(), expr0.id()));
path.push_back(std::move(ident_step));
activation.InsertValue(var_name, value);
}
CEL_ASSIGN_OR_RETURN(auto step0,
CreateCreateListStep(create_list, dummy_expr.id()));
path.push_back(std::move(step0));
cel::RuntimeOptions options;
if (enable_unknowns) {
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
}
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), options));
return cel_expr.Evaluate(activation, arena);
}
class CreateListStepTest : public testing::TestWithParam<bool> {};
TEST(CreateListStepTest, TestCreateListStackUnderflow) {
ExecutionPath path;
Expr dummy_expr;
auto& create_list = dummy_expr.mutable_list_expr();
auto& expr0 = create_list.mutable_elements().emplace_back().mutable_expr();
expr0.mutable_const_expr().set_int64_value(1);
ASSERT_OK_AND_ASSIGN(auto step0,
CreateCreateListStep(create_list, dummy_expr.id()));
path.push_back(std::move(step0));
CelExpressionFlatImpl cel_expr(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
Activation activation;
google::protobuf::Arena arena;
auto status = cel_expr.Evaluate(activation, &arena);
ASSERT_THAT(status, Not(IsOk()));
}
TEST_P(CreateListStepTest, CreateListEmpty) {
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression({}, &arena, GetParam()));
ASSERT_TRUE(result.IsList());
EXPECT_THAT(result.ListOrDie()->size(), Eq(0));
}
TEST_P(CreateListStepTest, CreateListOne) {
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression({100}, &arena, GetParam()));
ASSERT_TRUE(result.IsList());
const auto& list = *result.ListOrDie();
ASSERT_THAT(list.size(), Eq(1));
const CelValue& value = list.Get(&arena, 0);
EXPECT_THAT(value, test::IsCelInt64(100));
}
TEST_P(CreateListStepTest, CreateListWithError) {
google::protobuf::Arena arena;
std::vector<CelValue> values;
CelError error = absl::InvalidArgumentError("bad arg");
values.push_back(CelValue::CreateError(&error));
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpressionWithCelValues(values, &arena, GetParam()));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(), Eq(absl::InvalidArgumentError("bad arg")));
}
TEST_P(CreateListStepTest, CreateListWithErrorAndUnknown) {
google::protobuf::Arena arena;
std::vector<CelValue> values;
Expr expr0;
expr0.mutable_ident_expr().set_name("name0");
CelAttribute attr0(expr0.ident_expr().name(), {});
UnknownSet unknown_set0(UnknownAttributeSet({attr0}));
values.push_back(CelValue::CreateUnknownSet(&unknown_set0));
CelError error = absl::InvalidArgumentError("bad arg");
values.push_back(CelValue::CreateError(&error));
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpressionWithCelValues(values, &arena, GetParam()));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*result.ErrorOrDie(), Eq(absl::InvalidArgumentError("bad arg")));
}
TEST_P(CreateListStepTest, CreateListHundred) {
google::protobuf::Arena arena;
std::vector<int64_t> values;
for (size_t i = 0; i < 100; i++) {
values.push_back(i);
}
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpression(values, &arena, GetParam()));
ASSERT_TRUE(result.IsList());
const auto& list = *result.ListOrDie();
EXPECT_THAT(list.size(), Eq(static_cast<int>(values.size())));
for (size_t i = 0; i < values.size(); i++) {
EXPECT_THAT(list.Get(&arena, i), test::IsCelInt64(values[i]));
}
}
INSTANTIATE_TEST_SUITE_P(CombinedCreateListTest, CreateListStepTest,
testing::Bool());
TEST(CreateListStepTest, CreateListHundredAnd2Unknowns) {
google::protobuf::Arena arena;
std::vector<CelValue> values;
Expr expr0;
expr0.mutable_ident_expr().set_name("name0");
CelAttribute attr0(expr0.ident_expr().name(), {});
Expr expr1;
expr1.mutable_ident_expr().set_name("name1");
CelAttribute attr1(expr1.ident_expr().name(), {});
UnknownSet unknown_set0(UnknownAttributeSet({attr0}));
UnknownSet unknown_set1(UnknownAttributeSet({attr1}));
for (size_t i = 0; i < 100; i++) {
values.push_back(CelValue::CreateInt64(i));
}
values.push_back(CelValue::CreateUnknownSet(&unknown_set0));
values.push_back(CelValue::CreateUnknownSet(&unknown_set1));
ASSERT_OK_AND_ASSIGN(CelValue result,
RunExpressionWithCelValues(values, &arena, true));
ASSERT_TRUE(result.IsUnknownSet());
const UnknownSet* result_set = result.UnknownSetOrDie();
EXPECT_THAT(result_set->unknown_attributes().size(), Eq(2));
}
TEST(CreateDirectListStep, Basic) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
ExecutionFrameBase frame(activation, options, value_factory.get());
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateConstValueDirectStep(IntValue(1), -1));
deps.push_back(CreateConstValueDirectStep(IntValue(2), -1));
auto step = CreateDirectListStep(std::move(deps), {}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ListValue>(result));
EXPECT_THAT(Cast<ListValue>(result).Size(), IsOkAndHolds(2));
}
TEST(CreateDirectListStep, ForwardFirstError) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
ExecutionFrameBase frame(activation, options, value_factory.get());
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateConstValueDirectStep(
value_factory.get().CreateErrorValue(absl::InternalError("test1")), -1));
deps.push_back(CreateConstValueDirectStep(
value_factory.get().CreateErrorValue(absl::InternalError("test2")), -1));
auto step = CreateDirectListStep(std::move(deps), {}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInternal, "test1"));
}
std::vector<std::string> UnknownAttrNames(const UnknownValue& v) {
std::vector<std::string> names;
names.reserve(v.attribute_set().size());
for (const auto& attr : v.attribute_set()) {
EXPECT_OK(attr.AsString().status());
names.push_back(attr.AsString().value_or("<empty>"));
}
return names;
}
TEST(CreateDirectListStep, MergeUnknowns) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
ExecutionFrameBase frame(activation, options, value_factory.get());
AttributeSet attr_set1({Attribute("var1")});
AttributeSet attr_set2({Attribute("var2")});
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateConstValueDirectStep(
value_factory.get().CreateUnknownValue(std::move(attr_set1)), -1));
deps.push_back(CreateConstValueDirectStep(
value_factory.get().CreateUnknownValue(std::move(attr_set2)), -1));
auto step = CreateDirectListStep(std::move(deps), {}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<UnknownValue>(result));
EXPECT_THAT(UnknownAttrNames(Cast<UnknownValue>(result)),
UnorderedElementsAre("var1", "var2"));
}
TEST(CreateDirectListStep, ErrorBeforeUnknown) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
ExecutionFrameBase frame(activation, options, value_factory.get());
AttributeSet attr_set1({Attribute("var1")});
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateConstValueDirectStep(
value_factory.get().CreateErrorValue(absl::InternalError("test1")), -1));
deps.push_back(CreateConstValueDirectStep(
value_factory.get().CreateErrorValue(absl::InternalError("test2")), -1));
auto step = CreateDirectListStep(std::move(deps), {}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInternal, "test1"));
}
class SetAttrDirectStep : public DirectExpressionStep {
public:
explicit SetAttrDirectStep(Attribute attr)
: DirectExpressionStep(-1), attr_(std::move(attr)) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attr) const override {
result = frame.value_manager().GetNullValue();
attr = AttributeTrail(attr_);
return absl::OkStatus();
}
private:
cel::Attribute attr_;
};
TEST(CreateDirectListStep, MissingAttribute) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
options.enable_missing_attribute_errors = true;
activation.SetMissingPatterns({cel::AttributePattern(
"var1", {cel::AttributeQualifierPattern::OfString("field1")})});
ExecutionFrameBase frame(activation, options, value_factory.get());
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(
CreateConstValueDirectStep(value_factory.get().GetNullValue(), -1));
deps.push_back(std::make_unique<SetAttrDirectStep>(
Attribute("var1", {AttributeQualifier::OfString("field1")})));
auto step = CreateDirectListStep(std::move(deps), {}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(
Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("var1.field1")));
}
TEST(CreateDirectListStep, OptionalPresentSet) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
ExecutionFrameBase frame(activation, options, value_factory.get());
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateConstValueDirectStep(IntValue(1), -1));
deps.push_back(CreateConstValueDirectStep(
cel::OptionalValue::Of(value_factory.get().GetMemoryManager(),
IntValue(2)),
-1));
auto step = CreateDirectListStep(std::move(deps), {1}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ListValue>(result));
auto list = Cast<ListValue>(result);
EXPECT_THAT(list.Size(), IsOkAndHolds(2));
EXPECT_THAT(list.Get(value_factory.get(), 0), IsOkAndHolds(IntValueIs(1)));
EXPECT_THAT(list.Get(value_factory.get(), 1), IsOkAndHolds(IntValueIs(2)));
}
TEST(CreateDirectListStep, OptionalAbsentNotSet) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
ExecutionFrameBase frame(activation, options, value_factory.get());
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(CreateConstValueDirectStep(IntValue(1), -1));
deps.push_back(CreateConstValueDirectStep(cel::OptionalValue::None(), -1));
auto step = CreateDirectListStep(std::move(deps), {1}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<ListValue>(result));
auto list = Cast<ListValue>(result);
EXPECT_THAT(list.Size(), IsOkAndHolds(1));
EXPECT_THAT(list.Get(value_factory.get(), 0), IsOkAndHolds(IntValueIs(1)));
}
TEST(CreateDirectListStep, PartialUnknown) {
cel::ManagedValueFactory value_factory(
cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
activation.SetUnknownPatterns({cel::AttributePattern(
"var1", {cel::AttributeQualifierPattern::OfString("field1")})});
ExecutionFrameBase frame(activation, options, value_factory.get());
std::vector<std::unique_ptr<DirectExpressionStep>> deps;
deps.push_back(
CreateConstValueDirectStep(value_factory.get().CreateIntValue(1), -1));
deps.push_back(std::make_unique<SetAttrDirectStep>(Attribute("var1", {})));
auto step = CreateDirectListStep(std::move(deps), {}, -1);
cel::Value result;
AttributeTrail attr;
ASSERT_OK(step->Evaluate(frame, result, attr));
ASSERT_TRUE(InstanceOf<UnknownValue>(result));
EXPECT_THAT(UnknownAttrNames(Cast<UnknownValue>(result)),
UnorderedElementsAre("var1"));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/create_list_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/create_list_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
df1fb9f3-b27e-4aba-9bd1-117f8935c674 | cpp | google/cel-cpp | evaluator_core | eval/eval/evaluator_core.cc | eval/eval/evaluator_core_test.cc | #include "eval/eval/evaluator_core.h"
#include <cstddef>
#include <limits>
#include <memory>
#include <utility>
#include "absl/base/optimization.h"
#include "absl/log/absl_check.h"
#include "absl/log/absl_log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "absl/utility/utility.h"
#include "base/type_provider.h"
#include "common/memory.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "runtime/activation_interface.h"
#include "runtime/managed_value_factory.h"
namespace google::api::expr::runtime {
FlatExpressionEvaluatorState::FlatExpressionEvaluatorState(
size_t value_stack_size, size_t comprehension_slot_count,
const cel::TypeProvider& type_provider,
cel::MemoryManagerRef memory_manager)
: value_stack_(value_stack_size),
comprehension_slots_(comprehension_slot_count),
managed_value_factory_(absl::in_place, type_provider, memory_manager),
value_factory_(&managed_value_factory_->get()) {}
FlatExpressionEvaluatorState::FlatExpressionEvaluatorState(
size_t value_stack_size, size_t comprehension_slot_count,
cel::ValueManager& value_factory)
: value_stack_(value_stack_size),
comprehension_slots_(comprehension_slot_count),
managed_value_factory_(absl::nullopt),
value_factory_(&value_factory) {}
void FlatExpressionEvaluatorState::Reset() {
value_stack_.Clear();
comprehension_slots_.Reset();
}
const ExpressionStep* ExecutionFrame::Next() {
while (true) {
const size_t end_pos = execution_path_.size();
if (ABSL_PREDICT_TRUE(pc_ < end_pos)) {
const auto* step = execution_path_[pc_++].get();
ABSL_ASSUME(step != nullptr);
return step;
}
if (ABSL_PREDICT_TRUE(pc_ == end_pos)) {
if (!call_stack_.empty()) {
SubFrame& subframe = call_stack_.back();
pc_ = subframe.return_pc;
execution_path_ = subframe.return_expression;
ABSL_DCHECK_EQ(value_stack().size(), subframe.expected_stack_size);
comprehension_slots().Set(subframe.slot_index, value_stack().Peek(),
value_stack().PeekAttribute());
call_stack_.pop_back();
continue;
}
} else {
ABSL_LOG(ERROR) << "Attempting to step beyond the end of execution path.";
}
return nullptr;
}
}
namespace {
class EvaluationStatus final {
public:
explicit EvaluationStatus(absl::Status&& status) {
::new (static_cast<void*>(&status_[0])) absl::Status(std::move(status));
}
EvaluationStatus() = delete;
EvaluationStatus(const EvaluationStatus&) = delete;
EvaluationStatus(EvaluationStatus&&) = delete;
EvaluationStatus& operator=(const EvaluationStatus&) = delete;
EvaluationStatus& operator=(EvaluationStatus&&) = delete;
absl::Status Consume() && {
return std::move(*reinterpret_cast<absl::Status*>(&status_[0]));
}
bool ok() const {
return ABSL_PREDICT_TRUE(
reinterpret_cast<const absl::Status*>(&status_[0])->ok());
}
private:
alignas(absl::Status) char status_[sizeof(absl::Status)];
};
}
absl::StatusOr<cel::Value> ExecutionFrame::Evaluate(
EvaluationListener& listener) {
const size_t initial_stack_size = value_stack().size();
if (!listener) {
for (const ExpressionStep* expr = Next();
ABSL_PREDICT_TRUE(expr != nullptr); expr = Next()) {
if (EvaluationStatus status(expr->Evaluate(this)); !status.ok()) {
return std::move(status).Consume();
}
}
} else {
for (const ExpressionStep* expr = Next();
ABSL_PREDICT_TRUE(expr != nullptr); expr = Next()) {
if (EvaluationStatus status(expr->Evaluate(this)); !status.ok()) {
return std::move(status).Consume();
}
if (pc_ == 0 || !expr->comes_from_ast()) {
continue;
}
if (ABSL_PREDICT_FALSE(value_stack().empty())) {
ABSL_LOG(ERROR) << "Stack is empty after a ExpressionStep.Evaluate. "
"Try to disable short-circuiting.";
continue;
}
if (EvaluationStatus status(
listener(expr->id(), value_stack().Peek(), value_factory()));
!status.ok()) {
return std::move(status).Consume();
}
}
}
const size_t final_stack_size = value_stack().size();
if (ABSL_PREDICT_FALSE(final_stack_size != initial_stack_size + 1 ||
final_stack_size == 0)) {
return absl::InternalError(absl::StrCat(
"Stack error during evaluation: expected=", initial_stack_size + 1,
", actual=", final_stack_size));
}
cel::Value value = std::move(value_stack().Peek());
value_stack().Pop(1);
return value;
}
FlatExpressionEvaluatorState FlatExpression::MakeEvaluatorState(
cel::MemoryManagerRef manager) const {
return FlatExpressionEvaluatorState(path_.size(), comprehension_slots_size_,
type_provider_, manager);
}
FlatExpressionEvaluatorState FlatExpression::MakeEvaluatorState(
cel::ValueManager& value_factory) const {
return FlatExpressionEvaluatorState(path_.size(), comprehension_slots_size_,
value_factory);
}
absl::StatusOr<cel::Value> FlatExpression::EvaluateWithCallback(
const cel::ActivationInterface& activation, EvaluationListener listener,
FlatExpressionEvaluatorState& state) const {
state.Reset();
ExecutionFrame frame(subexpressions_, activation, options_, state,
std::move(listener));
return frame.Evaluate(frame.callback());
}
cel::ManagedValueFactory FlatExpression::MakeValueFactory(
cel::MemoryManagerRef memory_manager) const {
return cel::ManagedValueFactory(type_provider_, memory_manager);
}
} | #include "eval/eval/evaluator_core.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "base/type_provider.h"
#include "eval/compiler/cel_expression_builder_flat_impl.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/internal/interop.h"
#include "eval/public/activation.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_value.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
using ::cel::IntValue;
using ::cel::TypeProvider;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::interop_internal::CreateIntValue;
using ::google::api::expr::v1alpha1::Expr;
using ::google::api::expr::runtime::RegisterBuiltinFunctions;
using ::testing::_;
using ::testing::Eq;
class FakeConstExpressionStep : public ExpressionStep {
public:
FakeConstExpressionStep() : ExpressionStep(0, true) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
frame->value_stack().Push(CreateIntValue(0));
return absl::OkStatus();
}
};
class FakeIncrementExpressionStep : public ExpressionStep {
public:
FakeIncrementExpressionStep() : ExpressionStep(0, true) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
auto value = frame->value_stack().Peek();
frame->value_stack().Pop(1);
EXPECT_TRUE(value->Is<IntValue>());
int64_t val = value.GetInt().NativeValue();
frame->value_stack().Push(CreateIntValue(val + 1));
return absl::OkStatus();
}
};
TEST(EvaluatorCoreTest, ExecutionFrameNext) {
ExecutionPath path;
google::protobuf::Arena arena;
auto manager = ProtoMemoryManagerRef(&arena);
auto const_step = std::make_unique<const FakeConstExpressionStep>();
auto incr_step1 = std::make_unique<const FakeIncrementExpressionStep>();
auto incr_step2 = std::make_unique<const FakeIncrementExpressionStep>();
path.push_back(std::move(const_step));
path.push_back(std::move(incr_step1));
path.push_back(std::move(incr_step2));
auto dummy_expr = std::make_unique<Expr>();
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kDisabled;
cel::Activation activation;
FlatExpressionEvaluatorState state(path.size(),
0,
TypeProvider::Builtin(), manager);
ExecutionFrame frame(path, activation, options, state);
EXPECT_THAT(frame.Next(), Eq(path[0].get()));
EXPECT_THAT(frame.Next(), Eq(path[1].get()));
EXPECT_THAT(frame.Next(), Eq(path[2].get()));
EXPECT_THAT(frame.Next(), Eq(nullptr));
}
TEST(EvaluatorCoreTest, SimpleEvaluatorTest) {
ExecutionPath path;
auto const_step = std::make_unique<FakeConstExpressionStep>();
auto incr_step1 = std::make_unique<FakeIncrementExpressionStep>();
auto incr_step2 = std::make_unique<FakeIncrementExpressionStep>();
path.push_back(std::move(const_step));
path.push_back(std::move(incr_step1));
path.push_back(std::move(incr_step2));
CelExpressionFlatImpl impl(FlatExpression(
std::move(path), 0, cel::TypeProvider::Builtin(), cel::RuntimeOptions{}));
Activation activation;
google::protobuf::Arena arena;
auto status = impl.Evaluate(activation, &arena);
EXPECT_OK(status);
auto value = status.value();
EXPECT_TRUE(value.IsInt64());
EXPECT_THAT(value.Int64OrDie(), Eq(2));
}
class MockTraceCallback {
public:
MOCK_METHOD(void, Call,
(int64_t expr_id, const CelValue& value, google::protobuf::Arena*));
};
TEST(EvaluatorCoreTest, TraceTest) {
Expr expr;
google::api::expr::v1alpha1::SourceInfo source_info;
expr.set_id(1);
auto and_call = expr.mutable_call_expr();
and_call->set_function("_&&_");
auto true_expr = and_call->add_args();
true_expr->set_id(2);
true_expr->mutable_const_expr()->set_int64_value(1);
auto comp_expr = and_call->add_args();
comp_expr->set_id(3);
auto comp = comp_expr->mutable_comprehension_expr();
comp->set_iter_var("x");
comp->set_accu_var("accu");
auto list_expr = comp->mutable_iter_range();
list_expr->set_id(4);
auto el1_expr = list_expr->mutable_list_expr()->add_elements();
el1_expr->set_id(11);
el1_expr->mutable_const_expr()->set_int64_value(1);
auto el2_expr = list_expr->mutable_list_expr()->add_elements();
el2_expr->set_id(12);
el2_expr->mutable_const_expr()->set_int64_value(2);
auto el3_expr = list_expr->mutable_list_expr()->add_elements();
el3_expr->set_id(13);
el3_expr->mutable_const_expr()->set_int64_value(3);
auto accu_init_expr = comp->mutable_accu_init();
accu_init_expr->set_id(20);
accu_init_expr->mutable_const_expr()->set_bool_value(true);
auto loop_cond_expr = comp->mutable_loop_condition();
loop_cond_expr->set_id(21);
loop_cond_expr->mutable_const_expr()->set_bool_value(true);
auto loop_step_expr = comp->mutable_loop_step();
loop_step_expr->set_id(22);
auto condition = loop_step_expr->mutable_call_expr();
condition->set_function("_>_");
auto iter_expr = condition->add_args();
iter_expr->set_id(23);
iter_expr->mutable_ident_expr()->set_name("x");
auto zero_expr = condition->add_args();
zero_expr->set_id(24);
zero_expr->mutable_const_expr()->set_int64_value(0);
auto result_expr = comp->mutable_result();
result_expr->set_id(25);
result_expr->mutable_const_expr()->set_bool_value(true);
cel::RuntimeOptions options;
options.short_circuiting = false;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
Activation activation;
google::protobuf::Arena arena;
MockTraceCallback callback;
EXPECT_CALL(callback, Call(accu_init_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(el1_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(el2_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(el3_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(list_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(loop_cond_expr->id(), _, &arena)).Times(3);
EXPECT_CALL(callback, Call(iter_expr->id(), _, &arena)).Times(3);
EXPECT_CALL(callback, Call(zero_expr->id(), _, &arena)).Times(3);
EXPECT_CALL(callback, Call(loop_step_expr->id(), _, &arena)).Times(3);
EXPECT_CALL(callback, Call(result_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(comp_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(true_expr->id(), _, &arena));
EXPECT_CALL(callback, Call(expr.id(), _, &arena));
auto eval_status = cel_expr->Trace(
activation, &arena,
[&](int64_t expr_id, const CelValue& value, google::protobuf::Arena* arena) {
callback.Call(expr_id, value, arena);
return absl::OkStatus();
});
ASSERT_OK(eval_status);
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/evaluator_core.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/evaluator_core_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
64487d51-1c0d-4732-87e3-c169ab23ba5d | cpp | google/cel-cpp | ident_step | eval/eval/ident_step.cc | eval/eval/ident_step_test.cc | #include "eval/eval/ident_step.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/base/nullability.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "base/ast_internal/expr.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/comprehension_slots.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
#include "eval/internal/errors.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Value;
using ::cel::runtime_internal::CreateError;
class IdentStep : public ExpressionStepBase {
public:
IdentStep(absl::string_view name, int64_t expr_id)
: ExpressionStepBase(expr_id), name_(name) {}
absl::Status Evaluate(ExecutionFrame* frame) const override;
private:
std::string name_;
};
absl::Status LookupIdent(const std::string& name, ExecutionFrameBase& frame,
Value& result, AttributeTrail& attribute) {
if (frame.attribute_tracking_enabled()) {
attribute = AttributeTrail(name);
if (frame.missing_attribute_errors_enabled() &&
frame.attribute_utility().CheckForMissingAttribute(attribute)) {
CEL_ASSIGN_OR_RETURN(
result, frame.attribute_utility().CreateMissingAttributeError(
attribute.attribute()));
return absl::OkStatus();
}
if (frame.unknown_processing_enabled() &&
frame.attribute_utility().CheckForUnknownExact(attribute)) {
result =
frame.attribute_utility().CreateUnknownSet(attribute.attribute());
return absl::OkStatus();
}
}
CEL_ASSIGN_OR_RETURN(auto found, frame.activation().FindVariable(
frame.value_manager(), name, result));
if (found) {
return absl::OkStatus();
}
result = frame.value_manager().CreateErrorValue(CreateError(
absl::StrCat("No value with name \"", name, "\" found in Activation")));
return absl::OkStatus();
}
absl::Status IdentStep::Evaluate(ExecutionFrame* frame) const {
Value value;
AttributeTrail attribute;
CEL_RETURN_IF_ERROR(LookupIdent(name_, *frame, value, attribute));
frame->value_stack().Push(std::move(value), std::move(attribute));
return absl::OkStatus();
}
absl::StatusOr<absl::Nonnull<const ComprehensionSlots::Slot*>> LookupSlot(
absl::string_view name, size_t slot_index, ExecutionFrameBase& frame) {
const ComprehensionSlots::Slot* slot =
frame.comprehension_slots().Get(slot_index);
if (slot == nullptr) {
return absl::InternalError(
absl::StrCat("Comprehension variable accessed out of scope: ", name));
}
return slot;
}
class SlotStep : public ExpressionStepBase {
public:
SlotStep(absl::string_view name, size_t slot_index, int64_t expr_id)
: ExpressionStepBase(expr_id), name_(name), slot_index_(slot_index) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
CEL_ASSIGN_OR_RETURN(const ComprehensionSlots::Slot* slot,
LookupSlot(name_, slot_index_, *frame));
frame->value_stack().Push(slot->value, slot->attribute);
return absl::OkStatus();
}
private:
std::string name_;
size_t slot_index_;
};
class DirectIdentStep : public DirectExpressionStep {
public:
DirectIdentStep(absl::string_view name, int64_t expr_id)
: DirectExpressionStep(expr_id), name_(name) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override {
return LookupIdent(name_, frame, result, attribute);
}
private:
std::string name_;
};
class DirectSlotStep : public DirectExpressionStep {
public:
DirectSlotStep(std::string name, size_t slot_index, int64_t expr_id)
: DirectExpressionStep(expr_id),
name_(std::move(name)),
slot_index_(slot_index) {}
absl::Status Evaluate(ExecutionFrameBase& frame, Value& result,
AttributeTrail& attribute) const override {
CEL_ASSIGN_OR_RETURN(const ComprehensionSlots::Slot* slot,
LookupSlot(name_, slot_index_, frame));
if (frame.attribute_tracking_enabled()) {
attribute = slot->attribute;
}
result = slot->value;
return absl::OkStatus();
}
private:
std::string name_;
size_t slot_index_;
};
}
std::unique_ptr<DirectExpressionStep> CreateDirectIdentStep(
absl::string_view identifier, int64_t expr_id) {
return std::make_unique<DirectIdentStep>(identifier, expr_id);
}
std::unique_ptr<DirectExpressionStep> CreateDirectSlotIdentStep(
absl::string_view identifier, size_t slot_index, int64_t expr_id) {
return std::make_unique<DirectSlotStep>(std::string(identifier), slot_index,
expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateIdentStep(
const cel::ast_internal::Ident& ident_expr, int64_t expr_id) {
return std::make_unique<IdentStep>(ident_expr.name(), expr_id);
}
absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateIdentStepForSlot(
const cel::ast_internal::Ident& ident_expr, size_t slot_index,
int64_t expr_id) {
return std::make_unique<SlotStep>(ident_expr.name(), slot_index, expr_id);
}
} | #include "eval/eval/ident_step.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "base/type_provider.h"
#include "common/casting.h"
#include "common/memory.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/evaluator_core.h"
#include "eval/public/activation.h"
#include "eval/public/cel_attribute.h"
#include "internal/testing.h"
#include "runtime/activation.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::Cast;
using ::cel::ErrorValue;
using ::cel::InstanceOf;
using ::cel::IntValue;
using ::cel::ManagedValueFactory;
using ::cel::MemoryManagerRef;
using ::cel::RuntimeOptions;
using ::cel::TypeProvider;
using ::cel::UnknownValue;
using ::cel::Value;
using ::cel::ast_internal::Expr;
using ::google::protobuf::Arena;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::SizeIs;
TEST(IdentStepTest, TestIdentStep) {
Expr expr;
auto& ident_expr = expr.mutable_ident_expr();
ident_expr.set_name("name0");
ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id()));
ExecutionPath path;
path.push_back(std::move(step));
CelExpressionFlatImpl impl(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
Activation activation;
Arena arena;
std::string value("test");
activation.InsertValue("name0", CelValue::CreateString(&value));
auto status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
CelValue result = status0.value();
ASSERT_TRUE(result.IsString());
EXPECT_THAT(result.StringOrDie().value(), Eq("test"));
}
TEST(IdentStepTest, TestIdentStepNameNotFound) {
Expr expr;
auto& ident_expr = expr.mutable_ident_expr();
ident_expr.set_name("name0");
ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id()));
ExecutionPath path;
path.push_back(std::move(step));
CelExpressionFlatImpl impl(
FlatExpression(std::move(path), 0,
TypeProvider::Builtin(), cel::RuntimeOptions{}));
Activation activation;
Arena arena;
std::string value("test");
auto status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
CelValue result = status0.value();
ASSERT_TRUE(result.IsError());
}
TEST(IdentStepTest, DisableMissingAttributeErrorsOK) {
Expr expr;
auto& ident_expr = expr.mutable_ident_expr();
ident_expr.set_name("name0");
ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id()));
ExecutionPath path;
path.push_back(std::move(step));
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kDisabled;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
Arena arena;
std::string value("test");
activation.InsertValue("name0", CelValue::CreateString(&value));
auto status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
CelValue result = status0.value();
ASSERT_TRUE(result.IsString());
EXPECT_THAT(result.StringOrDie().value(), Eq("test"));
const CelAttributePattern pattern("name0", {});
activation.set_missing_attribute_patterns({pattern});
status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
EXPECT_THAT(status0->StringOrDie().value(), Eq("test"));
}
TEST(IdentStepTest, TestIdentStepMissingAttributeErrors) {
Expr expr;
auto& ident_expr = expr.mutable_ident_expr();
ident_expr.set_name("name0");
ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id()));
ExecutionPath path;
path.push_back(std::move(step));
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kDisabled;
options.enable_missing_attribute_errors = true;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
Arena arena;
std::string value("test");
activation.InsertValue("name0", CelValue::CreateString(&value));
auto status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
CelValue result = status0.value();
ASSERT_TRUE(result.IsString());
EXPECT_THAT(result.StringOrDie().value(), Eq("test"));
CelAttributePattern pattern("name0", {});
activation.set_missing_attribute_patterns({pattern});
status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
EXPECT_EQ(status0->ErrorOrDie()->code(), absl::StatusCode::kInvalidArgument);
EXPECT_EQ(status0->ErrorOrDie()->message(), "MissingAttributeError: name0");
}
TEST(IdentStepTest, TestIdentStepUnknownAttribute) {
Expr expr;
auto& ident_expr = expr.mutable_ident_expr();
ident_expr.set_name("name0");
ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id()));
ExecutionPath path;
path.push_back(std::move(step));
cel::RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
CelExpressionFlatImpl impl(FlatExpression(std::move(path),
0,
TypeProvider::Builtin(), options));
Activation activation;
Arena arena;
std::string value("test");
activation.InsertValue("name0", CelValue::CreateString(&value));
std::vector<CelAttributePattern> unknown_patterns;
unknown_patterns.push_back(CelAttributePattern("name_bad", {}));
activation.set_unknown_attribute_patterns(unknown_patterns);
auto status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
CelValue result = status0.value();
ASSERT_TRUE(result.IsString());
EXPECT_THAT(result.StringOrDie().value(), Eq("test"));
unknown_patterns.push_back(CelAttributePattern("name0", {}));
activation.set_unknown_attribute_patterns(unknown_patterns);
status0 = impl.Evaluate(activation, &arena);
ASSERT_OK(status0);
result = status0.value();
ASSERT_TRUE(result.IsUnknownSet());
}
TEST(DirectIdentStepTest, Basic) {
ManagedValueFactory value_factory(TypeProvider::Builtin(),
MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
RuntimeOptions options;
activation.InsertOrAssignValue("var1", IntValue(42));
ExecutionFrameBase frame(activation, options, value_factory.get());
Value result;
AttributeTrail trail;
auto step = CreateDirectIdentStep("var1", -1);
ASSERT_OK(step->Evaluate(frame, result, trail));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_THAT(Cast<IntValue>(result).NativeValue(), Eq(42));
}
TEST(DirectIdentStepTest, UnknownAttribute) {
ManagedValueFactory value_factory(TypeProvider::Builtin(),
MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
RuntimeOptions options;
options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly;
activation.InsertOrAssignValue("var1", IntValue(42));
activation.SetUnknownPatterns({CreateCelAttributePattern("var1", {})});
ExecutionFrameBase frame(activation, options, value_factory.get());
Value result;
AttributeTrail trail;
auto step = CreateDirectIdentStep("var1", -1);
ASSERT_OK(step->Evaluate(frame, result, trail));
ASSERT_TRUE(InstanceOf<UnknownValue>(result));
EXPECT_THAT(Cast<UnknownValue>(result).attribute_set(), SizeIs(1));
}
TEST(DirectIdentStepTest, MissingAttribute) {
ManagedValueFactory value_factory(TypeProvider::Builtin(),
MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
RuntimeOptions options;
options.enable_missing_attribute_errors = true;
activation.InsertOrAssignValue("var1", IntValue(42));
activation.SetMissingPatterns({CreateCelAttributePattern("var1", {})});
ExecutionFrameBase frame(activation, options, value_factory.get());
Value result;
AttributeTrail trail;
auto step = CreateDirectIdentStep("var1", -1);
ASSERT_OK(step->Evaluate(frame, result, trail));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("var1")));
}
TEST(DirectIdentStepTest, NotFound) {
ManagedValueFactory value_factory(TypeProvider::Builtin(),
MemoryManagerRef::ReferenceCounting());
cel::Activation activation;
RuntimeOptions options;
ExecutionFrameBase frame(activation, options, value_factory.get());
Value result;
AttributeTrail trail;
auto step = CreateDirectIdentStep("var1", -1);
ASSERT_OK(step->Evaluate(frame, result, trail));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kUnknown,
HasSubstr("\"var1\" found in Activation")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/ident_step.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/ident_step_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
4df1949d-aa72-4d9a-8547-771218cf3f33 | cpp | google/cel-cpp | resolver | eval/compiler/resolver.cc | eval/compiler/resolver_test.cc | #include "eval/compiler/resolver.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "base/kind.h"
#include "common/memory.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "internal/status_macros.h"
#include "runtime/function_overload_reference.h"
#include "runtime/function_registry.h"
#include "runtime/type_registry.h"
namespace google::api::expr::runtime {
using ::cel::Value;
Resolver::Resolver(
absl::string_view container, const cel::FunctionRegistry& function_registry,
const cel::TypeRegistry&, cel::ValueManager& value_factory,
const absl::flat_hash_map<std::string, cel::TypeRegistry::Enumeration>&
resolveable_enums,
bool resolve_qualified_type_identifiers)
: namespace_prefixes_(),
enum_value_map_(),
function_registry_(function_registry),
value_factory_(value_factory),
resolveable_enums_(resolveable_enums),
resolve_qualified_type_identifiers_(resolve_qualified_type_identifiers) {
auto container_elements = absl::StrSplit(container, '.');
std::string prefix = "";
namespace_prefixes_.push_back(prefix);
for (const auto& elem : container_elements) {
if (elem.empty()) {
continue;
}
absl::StrAppend(&prefix, elem, ".");
namespace_prefixes_.insert(namespace_prefixes_.begin(), prefix);
}
for (const auto& prefix : namespace_prefixes_) {
for (auto iter = resolveable_enums_.begin();
iter != resolveable_enums_.end(); ++iter) {
absl::string_view enum_name = iter->first;
if (!absl::StartsWith(enum_name, prefix)) {
continue;
}
auto remainder = absl::StripPrefix(enum_name, prefix);
const auto& enum_type = iter->second;
for (const auto& enumerator : enum_type.enumerators) {
auto key = absl::StrCat(remainder, !remainder.empty() ? "." : "",
enumerator.name);
enum_value_map_[key] = value_factory.CreateIntValue(enumerator.number);
}
}
}
}
std::vector<std::string> Resolver::FullyQualifiedNames(absl::string_view name,
int64_t expr_id) const {
std::vector<std::string> names;
if (absl::StartsWith(name, ".")) {
std::string fully_qualified_name = std::string(name.substr(1));
names.push_back(fully_qualified_name);
return names;
}
for (const auto& prefix : namespace_prefixes_) {
std::string fully_qualified_name = absl::StrCat(prefix, name);
names.push_back(fully_qualified_name);
}
return names;
}
absl::optional<cel::Value> Resolver::FindConstant(absl::string_view name,
int64_t expr_id) const {
auto names = FullyQualifiedNames(name, expr_id);
for (const auto& name : names) {
auto enum_entry = enum_value_map_.find(name);
if (enum_entry != enum_value_map_.end()) {
return enum_entry->second;
}
if (resolve_qualified_type_identifiers_ || !absl::StrContains(name, ".")) {
auto type_value = value_factory_.FindType(name);
if (type_value.ok() && type_value->has_value()) {
return value_factory_.CreateTypeValue(**type_value);
}
}
}
return absl::nullopt;
}
std::vector<cel::FunctionOverloadReference> Resolver::FindOverloads(
absl::string_view name, bool receiver_style,
const std::vector<cel::Kind>& types, int64_t expr_id) const {
std::vector<cel::FunctionOverloadReference> funcs;
auto names = FullyQualifiedNames(name, expr_id);
for (auto it = names.begin(); it != names.end(); it++) {
funcs = function_registry_.FindStaticOverloads(*it, receiver_style, types);
if (!funcs.empty()) {
return funcs;
}
}
return funcs;
}
std::vector<cel::FunctionRegistry::LazyOverload> Resolver::FindLazyOverloads(
absl::string_view name, bool receiver_style,
const std::vector<cel::Kind>& types, int64_t expr_id) const {
std::vector<cel::FunctionRegistry::LazyOverload> funcs;
auto names = FullyQualifiedNames(name, expr_id);
for (const auto& name : names) {
funcs = function_registry_.FindLazyOverloads(name, receiver_style, types);
if (!funcs.empty()) {
return funcs;
}
}
return funcs;
}
absl::StatusOr<absl::optional<std::pair<std::string, cel::Type>>>
Resolver::FindType(absl::string_view name, int64_t expr_id) const {
auto qualified_names = FullyQualifiedNames(name, expr_id);
for (auto& qualified_name : qualified_names) {
CEL_ASSIGN_OR_RETURN(auto maybe_type,
value_factory_.FindType(qualified_name));
if (maybe_type.has_value()) {
return std::make_pair(std::move(qualified_name), std::move(*maybe_type));
}
}
return absl::nullopt;
}
} | #include "eval/compiler/resolver.h"
#include <memory>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/types/optional.h"
#include "base/type_provider.h"
#include "common/memory.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/public/cel_function.h"
#include "eval/public/cel_function_registry.h"
#include "eval/public/cel_type_registry.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::IntValue;
using ::cel::TypeFactory;
using ::cel::TypeManager;
using ::cel::TypeValue;
using ::cel::ValueManager;
using ::testing::Eq;
class FakeFunction : public CelFunction {
public:
explicit FakeFunction(const std::string& name)
: CelFunction(CelFunctionDescriptor{name, false, {}}) {}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
return absl::OkStatus();
}
};
class ResolverTest : public testing::Test {
public:
ResolverTest()
: value_factory_(cel::MemoryManagerRef::ReferenceCounting(),
type_registry_.GetTypeProvider()) {}
protected:
CelTypeRegistry type_registry_;
cel::common_internal::LegacyValueManager value_factory_;
};
TEST_F(ResolverTest, TestFullyQualifiedNames) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto names = resolver.FullyQualifiedNames("simple_name");
std::vector<std::string> expected_names(
{"google.api.expr.simple_name", "google.api.simple_name",
"google.simple_name", "simple_name"});
EXPECT_THAT(names, Eq(expected_names));
}
TEST_F(ResolverTest, TestFullyQualifiedNamesPartiallyQualifiedName) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto names = resolver.FullyQualifiedNames("expr.simple_name");
std::vector<std::string> expected_names(
{"google.api.expr.expr.simple_name", "google.api.expr.simple_name",
"google.expr.simple_name", "expr.simple_name"});
EXPECT_THAT(names, Eq(expected_names));
}
TEST_F(ResolverTest, TestFullyQualifiedNamesAbsoluteName) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto names = resolver.FullyQualifiedNames(".google.api.expr.absolute_name");
EXPECT_THAT(names.size(), Eq(1));
EXPECT_THAT(names[0], Eq("google.api.expr.absolute_name"));
}
TEST_F(ResolverTest, TestFindConstantEnum) {
CelFunctionRegistry func_registry;
type_registry_.Register(TestMessage::TestEnum_descriptor());
Resolver resolver("google.api.expr.runtime.TestMessage",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto enum_value = resolver.FindConstant("TestEnum.TEST_ENUM_1", -1);
ASSERT_TRUE(enum_value);
ASSERT_TRUE(enum_value->Is<IntValue>());
EXPECT_THAT(enum_value->GetInt().NativeValue(), Eq(1L));
enum_value = resolver.FindConstant(
".google.api.expr.runtime.TestMessage.TestEnum.TEST_ENUM_2", -1);
ASSERT_TRUE(enum_value);
ASSERT_TRUE(enum_value->Is<IntValue>());
EXPECT_THAT(enum_value->GetInt().NativeValue(), Eq(2L));
}
TEST_F(ResolverTest, TestFindConstantUnqualifiedType) {
CelFunctionRegistry func_registry;
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto type_value = resolver.FindConstant("int", -1);
EXPECT_TRUE(type_value);
EXPECT_TRUE(type_value->Is<TypeValue>());
EXPECT_THAT(type_value->GetType().name(), Eq("int"));
}
TEST_F(ResolverTest, TestFindConstantFullyQualifiedType) {
google::protobuf::LinkMessageReflection<TestMessage>();
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto type_value =
resolver.FindConstant(".google.api.expr.runtime.TestMessage", -1);
ASSERT_TRUE(type_value);
ASSERT_TRUE(type_value->Is<TypeValue>());
EXPECT_THAT(type_value->GetType().name(),
Eq("google.api.expr.runtime.TestMessage"));
}
TEST_F(ResolverTest, TestFindConstantQualifiedTypeDisabled) {
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums(), false);
auto type_value =
resolver.FindConstant(".google.api.expr.runtime.TestMessage", -1);
EXPECT_FALSE(type_value);
}
TEST_F(ResolverTest, FindTypeBySimpleName) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr.runtime",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
ASSERT_OK_AND_ASSIGN(auto type, resolver.FindType("TestMessage", -1));
EXPECT_TRUE(type.has_value());
EXPECT_EQ(type->second.name(), "google.api.expr.runtime.TestMessage");
}
TEST_F(ResolverTest, FindTypeByQualifiedName) {
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("google.api.expr.runtime",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
ASSERT_OK_AND_ASSIGN(
auto type, resolver.FindType(".google.api.expr.runtime.TestMessage", -1));
ASSERT_TRUE(type.has_value());
EXPECT_EQ(type->second.name(), "google.api.expr.runtime.TestMessage");
}
TEST_F(ResolverTest, TestFindDescriptorNotFound) {
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("google.api.expr.runtime",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
ASSERT_OK_AND_ASSIGN(auto type, resolver.FindType("UndefinedMessage", -1));
EXPECT_FALSE(type.has_value()) << type->second;
}
TEST_F(ResolverTest, TestFindOverloads) {
CelFunctionRegistry func_registry;
auto status =
func_registry.Register(std::make_unique<FakeFunction>("fake_func"));
ASSERT_OK(status);
status = func_registry.Register(
std::make_unique<FakeFunction>("cel.fake_ns_func"));
ASSERT_OK(status);
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto overloads =
resolver.FindOverloads("fake_func", false, ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
EXPECT_THAT(overloads[0].descriptor.name(), Eq("fake_func"));
overloads =
resolver.FindOverloads("fake_ns_func", false, ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
EXPECT_THAT(overloads[0].descriptor.name(), Eq("cel.fake_ns_func"));
}
TEST_F(ResolverTest, TestFindLazyOverloads) {
CelFunctionRegistry func_registry;
auto status = func_registry.RegisterLazyFunction(
CelFunctionDescriptor{"fake_lazy_func", false, {}});
ASSERT_OK(status);
status = func_registry.RegisterLazyFunction(
CelFunctionDescriptor{"cel.fake_lazy_ns_func", false, {}});
ASSERT_OK(status);
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto overloads =
resolver.FindLazyOverloads("fake_lazy_func", false, ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
overloads = resolver.FindLazyOverloads("fake_lazy_ns_func", false,
ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/resolver.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/resolver_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
e70903f9-fbb2-42e6-8fd2-9a94528cd959 | cpp | google/cel-cpp | qualified_reference_resolver | eval/compiler/qualified_reference_resolver.cc | eval/compiler/qualified_reference_resolver_test.cc | #include "eval/compiler/qualified_reference_resolver.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "base/ast.h"
#include "base/ast_internal/ast_impl.h"
#include "base/ast_internal/expr.h"
#include "base/builtins.h"
#include "base/kind.h"
#include "common/ast_rewrite.h"
#include "eval/compiler/flat_expr_builder_extensions.h"
#include "eval/compiler/resolver.h"
#include "runtime/internal/issue_collector.h"
#include "runtime/runtime_issue.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::RuntimeIssue;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::Reference;
using ::cel::runtime_internal::IssueCollector;
constexpr absl::string_view kOptionalOr = "or";
constexpr absl::string_view kOptionalOrValue = "orValue";
bool IsSpecialFunction(absl::string_view function_name) {
return function_name == cel::builtin::kAnd ||
function_name == cel::builtin::kOr ||
function_name == cel::builtin::kIndex ||
function_name == cel::builtin::kTernary ||
function_name == kOptionalOr || function_name == kOptionalOrValue ||
function_name == "cel.@block";
}
bool OverloadExists(const Resolver& resolver, absl::string_view name,
const std::vector<cel::Kind>& arguments_matcher,
bool receiver_style = false) {
return !resolver.FindOverloads(name, receiver_style, arguments_matcher)
.empty() ||
!resolver.FindLazyOverloads(name, receiver_style, arguments_matcher)
.empty();
}
absl::optional<std::string> BestOverloadMatch(const Resolver& resolver,
absl::string_view base_name,
int argument_count) {
if (IsSpecialFunction(base_name)) {
return std::string(base_name);
}
auto arguments_matcher = ArgumentsMatcher(argument_count);
auto names = resolver.FullyQualifiedNames(base_name);
for (auto name = names.begin(); name != names.end(); ++name) {
if (OverloadExists(resolver, *name, arguments_matcher)) {
if (base_name[0] == '.') {
return std::string(base_name);
}
return *name;
}
}
return absl::nullopt;
}
class ReferenceResolver : public cel::AstRewriterBase {
public:
ReferenceResolver(
const absl::flat_hash_map<int64_t, Reference>& reference_map,
const Resolver& resolver, IssueCollector& issue_collector)
: reference_map_(reference_map),
resolver_(resolver),
issues_(issue_collector),
progress_status_(absl::OkStatus()) {}
bool PreVisitRewrite(Expr& expr) override {
const Reference* reference = GetReferenceForId(expr.id());
if (reference != nullptr && reference->has_value()) {
if (reference->value().has_int64_value()) {
expr.mutable_const_expr().set_int64_value(
reference->value().int64_value());
return true;
} else {
return false;
}
}
if (reference != nullptr) {
if (expr.has_ident_expr()) {
return MaybeUpdateIdentNode(&expr, *reference);
} else if (expr.has_select_expr()) {
return MaybeUpdateSelectNode(&expr, *reference);
} else {
return false;
}
}
return false;
}
bool PostVisitRewrite(Expr& expr) override {
const Reference* reference = GetReferenceForId(expr.id());
if (expr.has_call_expr()) {
return MaybeUpdateCallNode(&expr, reference);
}
return false;
}
const absl::Status& GetProgressStatus() const { return progress_status_; }
private:
bool MaybeUpdateCallNode(Expr* out, const Reference* reference) {
auto& call_expr = out->mutable_call_expr();
const std::string& function = call_expr.function();
if (reference != nullptr && reference->overload_id().empty()) {
UpdateStatus(issues_.AddIssue(
RuntimeIssue::CreateWarning(absl::InvalidArgumentError(
absl::StrCat("Reference map doesn't provide overloads for ",
out->call_expr().function())))));
}
bool receiver_style = call_expr.has_target();
int arg_num = call_expr.args().size();
if (receiver_style) {
auto maybe_namespace = ToNamespace(call_expr.target());
if (maybe_namespace.has_value()) {
std::string resolved_name =
absl::StrCat(*maybe_namespace, ".", function);
auto resolved_function =
BestOverloadMatch(resolver_, resolved_name, arg_num);
if (resolved_function.has_value()) {
call_expr.set_function(*resolved_function);
call_expr.set_target(nullptr);
return true;
}
}
} else {
auto maybe_resolved_function =
BestOverloadMatch(resolver_, function, arg_num);
if (!maybe_resolved_function.has_value()) {
UpdateStatus(issues_.AddIssue(RuntimeIssue::CreateWarning(
absl::InvalidArgumentError(absl::StrCat(
"No overload found in reference resolve step for ", function)),
RuntimeIssue::ErrorCode::kNoMatchingOverload)));
} else if (maybe_resolved_function.value() != function) {
call_expr.set_function(maybe_resolved_function.value());
return true;
}
}
if (call_expr.has_target() && !IsSpecialFunction(function) &&
!OverloadExists(resolver_, function, ArgumentsMatcher(arg_num + 1),
true)) {
UpdateStatus(issues_.AddIssue(RuntimeIssue::CreateWarning(
absl::InvalidArgumentError(absl::StrCat(
"No overload found in reference resolve step for ", function)),
RuntimeIssue::ErrorCode::kNoMatchingOverload)));
}
return false;
}
bool MaybeUpdateSelectNode(Expr* out, const Reference& reference) {
if (out->select_expr().test_only()) {
UpdateStatus(issues_.AddIssue(RuntimeIssue::CreateWarning(
absl::InvalidArgumentError("Reference map points to a presence "
"test -- has(container.attr)"))));
} else if (!reference.name().empty()) {
out->mutable_ident_expr().set_name(reference.name());
rewritten_reference_.insert(out->id());
return true;
}
return false;
}
bool MaybeUpdateIdentNode(Expr* out, const Reference& reference) {
if (!reference.name().empty() &&
reference.name() != out->ident_expr().name()) {
out->mutable_ident_expr().set_name(reference.name());
rewritten_reference_.insert(out->id());
return true;
}
return false;
}
absl::optional<std::string> ToNamespace(const Expr& expr) {
absl::optional<std::string> maybe_parent_namespace;
if (rewritten_reference_.find(expr.id()) != rewritten_reference_.end()) {
return absl::nullopt;
}
if (expr.has_ident_expr()) {
return expr.ident_expr().name();
} else if (expr.has_select_expr()) {
if (expr.select_expr().test_only()) {
return absl::nullopt;
}
maybe_parent_namespace = ToNamespace(expr.select_expr().operand());
if (!maybe_parent_namespace.has_value()) {
return absl::nullopt;
}
return absl::StrCat(*maybe_parent_namespace, ".",
expr.select_expr().field());
} else {
return absl::nullopt;
}
}
const Reference* GetReferenceForId(int64_t expr_id) {
auto iter = reference_map_.find(expr_id);
if (iter == reference_map_.end()) {
return nullptr;
}
if (expr_id == 0) {
UpdateStatus(issues_.AddIssue(
RuntimeIssue::CreateWarning(absl::InvalidArgumentError(
"reference map entries for expression id 0 are not supported"))));
return nullptr;
}
return &iter->second;
}
void UpdateStatus(absl::Status status) {
if (progress_status_.ok() && !status.ok()) {
progress_status_ = std::move(status);
return;
}
status.IgnoreError();
}
const absl::flat_hash_map<int64_t, Reference>& reference_map_;
const Resolver& resolver_;
IssueCollector& issues_;
absl::Status progress_status_;
absl::flat_hash_set<int64_t> rewritten_reference_;
};
class ReferenceResolverExtension : public AstTransform {
public:
explicit ReferenceResolverExtension(ReferenceResolverOption opt)
: opt_(opt) {}
absl::Status UpdateAst(PlannerContext& context,
cel::ast_internal::AstImpl& ast) const override {
if (opt_ == ReferenceResolverOption::kCheckedOnly &&
ast.reference_map().empty()) {
return absl::OkStatus();
}
return ResolveReferences(context.resolver(), context.issue_collector(), ast)
.status();
}
private:
ReferenceResolverOption opt_;
};
}
absl::StatusOr<bool> ResolveReferences(const Resolver& resolver,
IssueCollector& issues,
cel::ast_internal::AstImpl& ast) {
ReferenceResolver ref_resolver(ast.reference_map(), resolver, issues);
bool was_rewritten = cel::AstRewrite(ast.root_expr(), ref_resolver);
if (!ref_resolver.GetProgressStatus().ok()) {
return ref_resolver.GetProgressStatus();
}
return was_rewritten;
}
std::unique_ptr<AstTransform> NewReferenceResolverExtension(
ReferenceResolverOption option) {
return std::make_unique<ReferenceResolverExtension>(option);
}
} | #include "eval/compiler/qualified_reference_resolver.h"
#include <memory>
#include <string>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/container/flat_hash_map.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "base/ast.h"
#include "base/ast_internal/ast_impl.h"
#include "base/ast_internal/expr.h"
#include "base/builtins.h"
#include "common/memory.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/compiler/resolver.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_function.h"
#include "eval/public/cel_function_registry.h"
#include "extensions/protobuf/ast_converters.h"
#include "internal/casts.h"
#include "internal/testing.h"
#include "runtime/internal/issue_collector.h"
#include "runtime/runtime_issue.h"
#include "runtime/type_registry.h"
#include "google/protobuf/text_format.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::cel::Ast;
using ::cel::RuntimeIssue;
using ::cel::ast_internal::AstImpl;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::SourceInfo;
using ::cel::extensions::internal::ConvertProtoExprToNative;
using ::cel::runtime_internal::IssueCollector;
using ::testing::Contains;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;
constexpr char kExpr[] = R"(
id: 1
call_expr {
function: "_&&_"
args {
id: 2
select_expr {
field: "var1"
operand {
id: 3
select_expr {
field: "bar"
operand {
id: 4
ident_expr { name: "foo" }
}
}
}
}
}
args {
id: 5
select_expr {
field: "var2"
operand {
id: 6
select_expr {
field: "foo"
operand {
id: 7
ident_expr { name: "bar" }
}
}
}
}
}
}
)";
MATCHER_P(StatusCodeIs, x, "") {
const absl::Status& status = arg;
return status.code() == x;
}
std::unique_ptr<AstImpl> ParseTestProto(const std::string& pb) {
google::api::expr::v1alpha1::Expr expr;
EXPECT_TRUE(google::protobuf::TextFormat::ParseFromString(pb, &expr));
return absl::WrapUnique(cel::internal::down_cast<AstImpl*>(
cel::extensions::CreateAstFromParsedExpr(expr).value().release()));
}
std::vector<absl::Status> ExtractIssuesStatus(const IssueCollector& issues) {
std::vector<absl::Status> issues_status;
for (const auto& issue : issues.issues()) {
issues_status.push_back(issue.ToStatus());
}
return issues_status;
}
TEST(ResolveReferences, Basic) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExpr);
expr_ast->reference_map()[2].set_name("foo.bar.var1");
expr_ast->reference_map()[5].set_name("bar.foo.var2");
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 1
call_expr {
function: "_&&_"
args {
id: 2
ident_expr { name: "foo.bar.var1" }
}
args {
id: 5
ident_expr { name: "bar.foo.var2" }
}
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
}
TEST(ResolveReferences, ReturnsFalseIfNoChanges) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExpr);
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
expr_ast->reference_map()[4].set_name("foo");
expr_ast->reference_map()[7].set_name("bar");
result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
}
TEST(ResolveReferences, NamespacedIdent) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExpr);
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[2].set_name("foo.bar.var1");
expr_ast->reference_map()[7].set_name("namespace_x.bar");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(
R"pb(
id: 1
call_expr {
function: "_&&_"
args {
id: 2
ident_expr { name: "foo.bar.var1" }
}
args {
id: 5
select_expr {
field: "var2"
operand {
id: 6
select_expr {
field: "foo"
operand {
id: 7
ident_expr { name: "namespace_x.bar" }
}
}
}
}
}
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
}
TEST(ResolveReferences, WarningOnPresenceTest) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(R"pb(
id: 1
select_expr {
field: "var1"
test_only: true
operand {
id: 2
select_expr {
field: "bar"
operand {
id: 3
ident_expr { name: "foo" }
}
}
}
})pb");
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[1].set_name("foo.bar.var1");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(
ExtractIssuesStatus(issues),
testing::ElementsAre(Eq(absl::Status(
absl::StatusCode::kInvalidArgument,
"Reference map points to a presence test -- has(container.attr)"))));
}
constexpr char kEnumExpr[] = R"(
id: 1
call_expr {
function: "_==_"
args {
id: 2
select_expr {
field: "var1"
operand {
id: 3
select_expr {
field: "bar"
operand {
id: 4
ident_expr { name: "foo" }
}
}
}
}
}
args {
id: 5
ident_expr { name: "bar.foo.Enum.ENUM_VAL1" }
}
}
)";
TEST(ResolveReferences, EnumConstReferenceUsed) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kEnumExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
ASSERT_OK(RegisterBuiltinFunctions(&func_registry));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[2].set_name("foo.bar.var1");
expr_ast->reference_map()[5].set_name("bar.foo.Enum.ENUM_VAL1");
expr_ast->reference_map()[5].mutable_value().set_int64_value(9);
IssueCollector issues(RuntimeIssue::Severity::kError);
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 1
call_expr {
function: "_==_"
args {
id: 2
ident_expr { name: "foo.bar.var1" }
}
args {
id: 5
const_expr { int64_value: 9 }
}
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
}
TEST(ResolveReferences, EnumConstReferenceUsedSelect) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kEnumExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
ASSERT_OK(RegisterBuiltinFunctions(&func_registry));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[2].set_name("foo.bar.var1");
expr_ast->reference_map()[2].mutable_value().set_int64_value(2);
expr_ast->reference_map()[5].set_name("bar.foo.Enum.ENUM_VAL1");
expr_ast->reference_map()[5].mutable_value().set_int64_value(9);
IssueCollector issues(RuntimeIssue::Severity::kError);
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 1
call_expr {
function: "_==_"
args {
id: 2
const_expr { int64_value: 2 }
}
args {
id: 5
const_expr { int64_value: 9 }
}
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
}
TEST(ResolveReferences, ConstReferenceSkipped) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
ASSERT_OK(RegisterBuiltinFunctions(&func_registry));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[2].set_name("foo.bar.var1");
expr_ast->reference_map()[2].mutable_value().set_bool_value(true);
expr_ast->reference_map()[5].set_name("bar.foo.var2");
IssueCollector issues(RuntimeIssue::Severity::kError);
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 1
call_expr {
function: "_&&_"
args {
id: 2
select_expr {
field: "var1"
operand {
id: 3
select_expr {
field: "bar"
operand {
id: 4
ident_expr { name: "foo" }
}
}
}
}
}
args {
id: 5
ident_expr { name: "bar.foo.var2" }
}
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
}
constexpr char kExtensionAndExpr[] = R"(
id: 1
call_expr {
function: "boolean_and"
args {
id: 2
const_expr {
bool_value: true
}
}
args {
id: 3
const_expr {
bool_value: false
}
}
})";
TEST(ResolveReferences, FunctionReferenceBasic) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExtensionAndExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
ASSERT_OK(func_registry.RegisterLazyFunction(
CelFunctionDescriptor("boolean_and", false,
{
CelValue::Type::kBool,
CelValue::Type::kBool,
})));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
IssueCollector issues(RuntimeIssue::Severity::kError);
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
}
TEST(ResolveReferences, FunctionReferenceMissingOverloadDetected) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExtensionAndExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
IssueCollector issues(RuntimeIssue::Severity::kError);
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(ExtractIssuesStatus(issues),
ElementsAre(StatusCodeIs(absl::StatusCode::kInvalidArgument)));
}
TEST(ResolveReferences, SpecialBuiltinsNotWarned) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(R"pb(
id: 1
call_expr {
function: "*"
args {
id: 2
const_expr { bool_value: true }
}
args {
id: 3
const_expr { bool_value: false }
}
})pb");
SourceInfo source_info;
std::vector<const char*> special_builtins{
cel::builtin::kAnd, cel::builtin::kOr, cel::builtin::kTernary,
cel::builtin::kIndex};
for (const char* builtin_fn : special_builtins) {
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
IssueCollector issues(RuntimeIssue::Severity::kError);
expr_ast->reference_map()[1].mutable_overload_id().push_back(
absl::StrCat("builtin.", builtin_fn));
expr_ast->root_expr().mutable_call_expr().set_function(builtin_fn);
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(ExtractIssuesStatus(issues), IsEmpty());
}
}
TEST(ResolveReferences,
FunctionReferenceMissingOverloadDetectedAndMissingReference) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExtensionAndExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
IssueCollector issues(RuntimeIssue::Severity::kError);
expr_ast->reference_map()[1].set_name("udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(
ExtractIssuesStatus(issues),
UnorderedElementsAre(
Eq(absl::InvalidArgumentError(
"No overload found in reference resolve step for boolean_and")),
Eq(absl::InvalidArgumentError(
"Reference map doesn't provide overloads for boolean_and"))));
}
TEST(ResolveReferences, EmulatesEagerFailing) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExtensionAndExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
IssueCollector issues(RuntimeIssue::Severity::kWarning);
expr_ast->reference_map()[1].set_name("udf_boolean_and");
EXPECT_THAT(
ResolveReferences(registry, issues, *expr_ast),
StatusIs(absl::StatusCode::kInvalidArgument,
"Reference map doesn't provide overloads for boolean_and"));
}
TEST(ResolveReferences, FunctionReferenceToWrongExprKind) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kExtensionAndExpr);
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[2].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(ExtractIssuesStatus(issues),
ElementsAre(StatusCodeIs(absl::StatusCode::kInvalidArgument)));
}
constexpr char kReceiverCallExtensionAndExpr[] = R"(
id: 1
call_expr {
function: "boolean_and"
target {
id: 2
ident_expr {
name: "ext"
}
}
args {
id: 3
const_expr {
bool_value: false
}
}
})";
TEST(ResolveReferences, FunctionReferenceWithTargetNoChange) {
std::unique_ptr<AstImpl> expr_ast =
ParseTestProto(kReceiverCallExtensionAndExpr);
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
ASSERT_OK(func_registry.RegisterLazyFunction(CelFunctionDescriptor(
"boolean_and", true, {CelValue::Type::kBool, CelValue::Type::kBool})));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(ExtractIssuesStatus(issues), IsEmpty());
}
TEST(ResolveReferences,
FunctionReferenceWithTargetNoChangeMissingOverloadDetected) {
std::unique_ptr<AstImpl> expr_ast =
ParseTestProto(kReceiverCallExtensionAndExpr);
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
EXPECT_THAT(ExtractIssuesStatus(issues),
ElementsAre(StatusCodeIs(absl::StatusCode::kInvalidArgument)));
}
TEST(ResolveReferences, FunctionReferenceWithTargetToNamespacedFunction) {
std::unique_ptr<AstImpl> expr_ast =
ParseTestProto(kReceiverCallExtensionAndExpr);
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
ASSERT_OK(func_registry.RegisterLazyFunction(CelFunctionDescriptor(
"ext.boolean_and", false, {CelValue::Type::kBool})));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 1
call_expr {
function: "ext.boolean_and"
args {
id: 3
const_expr { bool_value: false }
}
}
)pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
EXPECT_THAT(ExtractIssuesStatus(issues), IsEmpty());
}
TEST(ResolveReferences,
FunctionReferenceWithTargetToNamespacedFunctionInContainer) {
std::unique_ptr<AstImpl> expr_ast =
ParseTestProto(kReceiverCallExtensionAndExpr);
SourceInfo source_info;
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
ASSERT_OK(func_registry.RegisterLazyFunction(CelFunctionDescriptor(
"com.google.ext.boolean_and", false, {CelValue::Type::kBool})));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("com.google", func_registry.InternalGetRegistry(),
type_registry, value_factory,
type_registry.resolveable_enums());
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 1
call_expr {
function: "com.google.ext.boolean_and"
args {
id: 3
const_expr { bool_value: false }
}
}
)pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
EXPECT_THAT(ExtractIssuesStatus(issues), IsEmpty());
}
constexpr char kReceiverCallHasExtensionAndExpr[] = R"(
id: 1
call_expr {
function: "boolean_and"
target {
id: 2
select_expr {
test_only: true
field: "option"
operand {
id: 3
ident_expr {
name: "ext"
}
}
}
}
args {
id: 4
const_expr {
bool_value: false
}
}
})";
TEST(ResolveReferences, FunctionReferenceWithHasTargetNoChange) {
std::unique_ptr<AstImpl> expr_ast =
ParseTestProto(kReceiverCallHasExtensionAndExpr);
SourceInfo source_info;
IssueCollector issues(RuntimeIssue::Severity::kError);
CelFunctionRegistry func_registry;
ASSERT_OK(func_registry.RegisterLazyFunction(CelFunctionDescriptor(
"boolean_and", true, {CelValue::Type::kBool, CelValue::Type::kBool})));
ASSERT_OK(func_registry.RegisterLazyFunction(CelFunctionDescriptor(
"ext.option.boolean_and", true, {CelValue::Type::kBool})));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[1].mutable_overload_id().push_back(
"udf_boolean_and");
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(kReceiverCallHasExtensionAndExpr,
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
EXPECT_THAT(ExtractIssuesStatus(issues), IsEmpty());
}
constexpr char kComprehensionExpr[] = R"(
id:17
comprehension_expr: {
iter_var:"i"
iter_range:{
id:1
list_expr:{
elements:{
id:2
const_expr:{int64_value:1}
}
elements:{
id:3
ident_expr:{name:"ENUM"}
}
elements:{
id:4
const_expr:{int64_value:3}
}
}
}
accu_var:"__result__"
accu_init: {
id:10
const_expr:{bool_value:false}
}
loop_condition:{
id:13
call_expr:{
function:"@not_strictly_false"
args:{
id:12
call_expr:{
function:"!_"
args:{
id:11
ident_expr:{name:"__result__"}
}
}
}
}
}
loop_step:{
id:15
call_expr: {
function:"_||_"
args:{
id:14
ident_expr: {name:"__result__"}
}
args:{
id:8
call_expr:{
function:"_==_"
args:{
id:7 ident_expr:{name:"ENUM"}
}
args:{
id:9 ident_expr:{name:"i"}
}
}
}
}
}
result:{id:16 ident_expr:{name:"__result__"}}
}
)";
TEST(ResolveReferences, EnumConstReferenceUsedInComprehension) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(kComprehensionExpr);
SourceInfo source_info;
CelFunctionRegistry func_registry;
ASSERT_OK(RegisterBuiltinFunctions(&func_registry));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[3].set_name("ENUM");
expr_ast->reference_map()[3].mutable_value().set_int64_value(2);
expr_ast->reference_map()[7].set_name("ENUM");
expr_ast->reference_map()[7].mutable_value().set_int64_value(2);
IssueCollector issues(RuntimeIssue::Severity::kError);
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(true));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(
R"pb(
id: 17
comprehension_expr {
iter_var: "i"
iter_range {
id: 1
list_expr {
elements {
id: 2
const_expr { int64_value: 1 }
}
elements {
id: 3
const_expr { int64_value: 2 }
}
elements {
id: 4
const_expr { int64_value: 3 }
}
}
}
accu_var: "__result__"
accu_init {
id: 10
const_expr { bool_value: false }
}
loop_condition {
id: 13
call_expr {
function: "@not_strictly_false"
args {
id: 12
call_expr {
function: "!_"
args {
id: 11
ident_expr { name: "__result__" }
}
}
}
}
}
loop_step {
id: 15
call_expr {
function: "_||_"
args {
id: 14
ident_expr { name: "__result__" }
}
args {
id: 8
call_expr {
function: "_==_"
args {
id: 7
const_expr { int64_value: 2 }
}
args {
id: 9
ident_expr { name: "i" }
}
}
}
}
}
result {
id: 16
ident_expr { name: "__result__" }
}
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
}
TEST(ResolveReferences, ReferenceToId0Warns) {
std::unique_ptr<AstImpl> expr_ast = ParseTestProto(R"pb(
id: 0
select_expr {
operand {
id: 1
ident_expr { name: "pkg" }
}
field: "var"
})pb");
SourceInfo source_info;
CelFunctionRegistry func_registry;
ASSERT_OK(RegisterBuiltinFunctions(&func_registry));
cel::TypeRegistry type_registry;
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry.GetComposedTypeProvider());
Resolver registry("", func_registry.InternalGetRegistry(), type_registry,
value_factory, type_registry.resolveable_enums());
expr_ast->reference_map()[0].set_name("pkg.var");
IssueCollector issues(RuntimeIssue::Severity::kError);
auto result = ResolveReferences(registry, issues, *expr_ast);
ASSERT_THAT(result, IsOkAndHolds(false));
google::api::expr::v1alpha1::Expr expected_expr;
google::protobuf::TextFormat::ParseFromString(R"pb(
id: 0
select_expr {
operand {
id: 1
ident_expr { name: "pkg" }
}
field: "var"
})pb",
&expected_expr);
EXPECT_EQ(expr_ast->root_expr(),
ConvertProtoExprToNative(expected_expr).value());
EXPECT_THAT(
ExtractIssuesStatus(issues),
Contains(StatusIs(
absl::StatusCode::kInvalidArgument,
"reference map entries for expression id 0 are not supported")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/qualified_reference_resolver.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/qualified_reference_resolver_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
b066412e-e4c6-4b4d-93a2-74a41007ff22 | cpp | google/cel-cpp | regex_precompilation_optimization | eval/compiler/regex_precompilation_optimization.cc | eval/compiler/regex_precompilation_optimization_test.cc | #include "eval/compiler/regex_precompilation_optimization.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "base/ast_internal/ast_impl.h"
#include "base/ast_internal/expr.h"
#include "base/builtins.h"
#include "common/casting.h"
#include "common/native_type.h"
#include "common/value.h"
#include "eval/compiler/flat_expr_builder_extensions.h"
#include "eval/eval/compiler_constant_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/regex_match_step.h"
#include "internal/casts.h"
#include "internal/status_macros.h"
#include "re2/re2.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Cast;
using ::cel::InstanceOf;
using ::cel::NativeTypeId;
using ::cel::StringValue;
using ::cel::Value;
using ::cel::ast_internal::AstImpl;
using ::cel::ast_internal::Call;
using ::cel::ast_internal::Expr;
using ::cel::ast_internal::Reference;
using ::cel::internal::down_cast;
using ReferenceMap = absl::flat_hash_map<int64_t, Reference>;
bool IsFunctionOverload(const Expr& expr, absl::string_view function,
absl::string_view overload, size_t arity,
const ReferenceMap& reference_map) {
if (!expr.has_call_expr()) {
return false;
}
const auto& call_expr = expr.call_expr();
if (call_expr.function() != function) {
return false;
}
if (call_expr.args().size() + (call_expr.has_target() ? 1 : 0) != arity) {
return false;
}
if (reference_map.empty()) {
return true;
}
auto reference = reference_map.find(expr.id());
if (reference != reference_map.end() &&
reference->second.overload_id().size() == 1 &&
reference->second.overload_id().front() == overload) {
return true;
}
return false;
}
class RegexProgramBuilder final {
public:
explicit RegexProgramBuilder(int max_program_size)
: max_program_size_(max_program_size) {}
absl::StatusOr<std::shared_ptr<const RE2>> BuildRegexProgram(
std::string pattern) {
auto existing = programs_.find(pattern);
if (existing != programs_.end()) {
if (auto program = existing->second.lock(); program) {
return program;
}
programs_.erase(existing);
}
auto program = std::make_shared<RE2>(pattern);
if (max_program_size_ > 0 && program->ProgramSize() > max_program_size_) {
return absl::InvalidArgumentError("exceeded RE2 max program size");
}
if (!program->ok()) {
return absl::InvalidArgumentError(
"invalid_argument unsupported RE2 pattern for matches");
}
programs_.insert({std::move(pattern), program});
return program;
}
private:
const int max_program_size_;
absl::flat_hash_map<std::string, std::weak_ptr<const RE2>> programs_;
};
class RegexPrecompilationOptimization : public ProgramOptimizer {
public:
explicit RegexPrecompilationOptimization(const ReferenceMap& reference_map,
int regex_max_program_size)
: reference_map_(reference_map),
regex_program_builder_(regex_max_program_size) {}
absl::Status OnPreVisit(PlannerContext& context, const Expr& node) override {
return absl::OkStatus();
}
absl::Status OnPostVisit(PlannerContext& context, const Expr& node) override {
if (!IsFunctionOverload(node, cel::builtin::kRegexMatch, "matches_string",
2, reference_map_)) {
return absl::OkStatus();
}
ProgramBuilder::Subexpression* subexpression =
context.program_builder().GetSubexpression(&node);
const Call& call_expr = node.call_expr();
const Expr& pattern_expr = call_expr.args().back();
absl::optional<std::string> pattern =
GetConstantString(context, subexpression, node, pattern_expr);
if (!pattern.has_value()) {
return absl::OkStatus();
}
CEL_ASSIGN_OR_RETURN(
std::shared_ptr<const RE2> regex_program,
regex_program_builder_.BuildRegexProgram(std::move(pattern).value()));
if (subexpression == nullptr || subexpression->IsFlattened()) {
return absl::OkStatus();
}
const Expr& subject_expr =
call_expr.has_target() ? call_expr.target() : call_expr.args().front();
return RewritePlan(context, subexpression, node, subject_expr,
std::move(regex_program));
}
private:
absl::optional<std::string> GetConstantString(
PlannerContext& context,
absl::Nullable<ProgramBuilder::Subexpression*> subexpression,
const cel::ast_internal::Expr& call_expr,
const cel::ast_internal::Expr& re_expr) const {
if (re_expr.has_const_expr() && re_expr.const_expr().has_string_value()) {
return re_expr.const_expr().string_value();
}
if (subexpression == nullptr || subexpression->IsFlattened()) {
return absl::nullopt;
}
absl::optional<Value> constant;
if (subexpression->IsRecursive()) {
const auto& program = subexpression->recursive_program();
auto deps = program.step->GetDependencies();
if (deps.has_value() && deps->size() == 2) {
const auto* re_plan =
TryDowncastDirectStep<DirectCompilerConstantStep>(deps->at(1));
if (re_plan != nullptr) {
constant = re_plan->value();
}
}
} else {
ExecutionPathView re_plan = context.GetSubplan(re_expr);
if (re_plan.size() == 1 &&
re_plan[0]->GetNativeTypeId() ==
NativeTypeId::For<CompilerConstantStep>()) {
constant =
down_cast<const CompilerConstantStep*>(re_plan[0].get())->value();
}
}
if (constant.has_value() && InstanceOf<StringValue>(*constant)) {
return Cast<StringValue>(*constant).ToString();
}
return absl::nullopt;
}
absl::Status RewritePlan(
PlannerContext& context,
absl::Nonnull<ProgramBuilder::Subexpression*> subexpression,
const Expr& call, const Expr& subject,
std::shared_ptr<const RE2> regex_program) {
if (subexpression->IsRecursive()) {
return RewriteRecursivePlan(subexpression, call, subject,
std::move(regex_program));
}
return RewriteStackMachinePlan(context, call, subject,
std::move(regex_program));
}
absl::Status RewriteRecursivePlan(
absl::Nonnull<ProgramBuilder::Subexpression*> subexpression,
const Expr& call, const Expr& subject,
std::shared_ptr<const RE2> regex_program) {
auto program = subexpression->ExtractRecursiveProgram();
auto deps = program.step->ExtractDependencies();
if (!deps.has_value() || deps->size() != 2) {
subexpression->set_recursive_program(std::move(program.step),
program.depth);
return absl::OkStatus();
}
subexpression->set_recursive_program(
CreateDirectRegexMatchStep(call.id(), std::move(deps->at(0)),
std::move(regex_program)),
program.depth);
return absl::OkStatus();
}
absl::Status RewriteStackMachinePlan(
PlannerContext& context, const Expr& call, const Expr& subject,
std::shared_ptr<const RE2> regex_program) {
if (context.GetSubplan(subject).empty()) {
return absl::OkStatus();
}
CEL_ASSIGN_OR_RETURN(ExecutionPath new_plan,
context.ExtractSubplan(subject));
CEL_ASSIGN_OR_RETURN(
new_plan.emplace_back(),
CreateRegexMatchStep(std::move(regex_program), call.id()));
return context.ReplaceSubplan(call, std::move(new_plan));
}
const ReferenceMap& reference_map_;
RegexProgramBuilder regex_program_builder_;
};
}
ProgramOptimizerFactory CreateRegexPrecompilationExtension(
int regex_max_program_size) {
return [=](PlannerContext& context, const AstImpl& ast) {
return std::make_unique<RegexPrecompilationOptimization>(
ast.reference_map(), regex_max_program_size);
};
}
} | #include "eval/compiler/regex_precompilation_optimization.h"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "google/api/expr/v1alpha1/checked.pb.h"
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/status/status.h"
#include "base/ast_internal/ast_impl.h"
#include "common/memory.h"
#include "common/values/legacy_value_manager.h"
#include "eval/compiler/cel_expression_builder_flat_impl.h"
#include "eval/compiler/constant_folding.h"
#include "eval/compiler/flat_expr_builder.h"
#include "eval/compiler/flat_expr_builder_extensions.h"
#include "eval/eval/evaluator_core.h"
#include "eval/public/activation.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_expression.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "internal/testing.h"
#include "parser/parser.h"
#include "runtime/internal/issue_collector.h"
#include "runtime/runtime_issue.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::RuntimeIssue;
using ::cel::runtime_internal::IssueCollector;
using ::google::api::expr::parser::Parse;
using ::testing::ElementsAre;
namespace exprpb = google::api::expr::v1alpha1;
class RegexPrecompilationExtensionTest : public testing::TestWithParam<bool> {
public:
RegexPrecompilationExtensionTest()
: type_registry_(*builder_.GetTypeRegistry()),
function_registry_(*builder_.GetRegistry()),
value_factory_(cel::MemoryManagerRef::ReferenceCounting(),
type_registry_.GetTypeProvider()),
resolver_("", function_registry_.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums()),
issue_collector_(RuntimeIssue::Severity::kError) {
if (EnableRecursivePlanning()) {
options_.max_recursion_depth = -1;
options_.enable_recursive_tracing = true;
}
options_.enable_regex = true;
options_.regex_max_program_size = 100;
options_.enable_regex_precompilation = true;
runtime_options_ = ConvertToRuntimeOptions(options_);
}
void SetUp() override {
ASSERT_OK(RegisterBuiltinFunctions(&function_registry_, options_));
}
bool EnableRecursivePlanning() { return GetParam(); }
protected:
CelEvaluationListener RecordStringValues() {
return [this](int64_t, const CelValue& value, google::protobuf::Arena*) {
if (value.IsString()) {
string_values_.push_back(std::string(value.StringOrDie().value()));
}
return absl::OkStatus();
};
}
CelExpressionBuilderFlatImpl builder_;
CelTypeRegistry& type_registry_;
CelFunctionRegistry& function_registry_;
InterpreterOptions options_;
cel::RuntimeOptions runtime_options_;
cel::common_internal::LegacyValueManager value_factory_;
Resolver resolver_;
IssueCollector issue_collector_;
std::vector<std::string> string_values_;
};
TEST_P(RegexPrecompilationExtensionTest, SmokeTest) {
ProgramOptimizerFactory factory =
CreateRegexPrecompilationExtension(options_.regex_max_program_size);
ExecutionPath path;
ProgramBuilder program_builder;
cel::ast_internal::AstImpl ast_impl;
ast_impl.set_is_checked(true);
PlannerContext context(resolver_, runtime_options_, value_factory_,
issue_collector_, program_builder);
ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> optimizer,
factory(context, ast_impl));
}
TEST_P(RegexPrecompilationExtensionTest, OptimizeableExpression) {
builder_.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options_.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(exprpb::ParsedExpr parsed_expr,
Parse("input.matches(r'[a-zA-Z]+[0-9]*')"));
exprpb::CheckedExpr expr;
expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
(*expr.mutable_reference_map())[2].add_overload_id("matches_string");
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder_.CreateExpression(&expr));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("input", CelValue::CreateStringView("input123"));
ASSERT_OK(plan->Trace(activation, &arena, RecordStringValues()));
EXPECT_THAT(string_values_, ElementsAre("input123"));
}
TEST_P(RegexPrecompilationExtensionTest, OptimizeParsedExpr) {
builder_.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options_.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(exprpb::ParsedExpr expr,
Parse("input.matches(r'[a-zA-Z]+[0-9]*')"));
ASSERT_OK_AND_ASSIGN(
std::unique_ptr<CelExpression> plan,
builder_.CreateExpression(&expr.expr(), &expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("input", CelValue::CreateStringView("input123"));
ASSERT_OK(plan->Trace(activation, &arena, RecordStringValues()));
EXPECT_THAT(string_values_, ElementsAre("input123"));
}
TEST_P(RegexPrecompilationExtensionTest, DoesNotOptimizeNonConstRegex) {
builder_.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options_.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(exprpb::ParsedExpr parsed_expr,
Parse("input.matches(input_re)"));
exprpb::CheckedExpr expr;
expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
(*expr.mutable_reference_map())[2].add_overload_id("matches_string");
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder_.CreateExpression(&expr));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("input", CelValue::CreateStringView("input123"));
activation.InsertValue("input_re", CelValue::CreateStringView("input_re"));
ASSERT_OK(plan->Trace(activation, &arena, RecordStringValues()));
EXPECT_THAT(string_values_, ElementsAre("input123", "input_re"));
}
TEST_P(RegexPrecompilationExtensionTest, DoesNotOptimizeCompoundExpr) {
builder_.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options_.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(exprpb::ParsedExpr parsed_expr,
Parse("input.matches('abc' + 'def')"));
exprpb::CheckedExpr expr;
expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
(*expr.mutable_reference_map())[2].add_overload_id("matches_string");
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder_.CreateExpression(&expr));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("input", CelValue::CreateStringView("input123"));
ASSERT_OK(plan->Trace(activation, &arena, RecordStringValues()));
EXPECT_THAT(string_values_, ElementsAre("input123", "abc", "def", "abcdef"));
}
class RegexConstFoldInteropTest : public RegexPrecompilationExtensionTest {
public:
RegexConstFoldInteropTest() : RegexPrecompilationExtensionTest() {
builder_.flat_expr_builder().AddProgramOptimizer(
cel::runtime_internal::CreateConstantFoldingOptimizer(
cel::MemoryManagerRef::ReferenceCounting()));
}
protected:
google::protobuf::Arena arena_;
};
TEST_P(RegexConstFoldInteropTest, StringConstantOptimizeable) {
builder_.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options_.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(exprpb::ParsedExpr parsed_expr,
Parse("input.matches('abc' + 'def')"));
exprpb::CheckedExpr expr;
expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
(*expr.mutable_reference_map())[2].add_overload_id("matches_string");
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder_.CreateExpression(&expr));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("input", CelValue::CreateStringView("input123"));
ASSERT_OK(plan->Trace(activation, &arena, RecordStringValues()));
EXPECT_THAT(string_values_, ElementsAre("input123"));
}
TEST_P(RegexConstFoldInteropTest, WrongTypeNotOptimized) {
builder_.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options_.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(exprpb::ParsedExpr parsed_expr,
Parse("input.matches(123 + 456)"));
exprpb::CheckedExpr expr;
expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
(*expr.mutable_reference_map())[2].add_overload_id("matches_string");
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder_.CreateExpression(&expr));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("input", CelValue::CreateStringView("input123"));
ASSERT_OK_AND_ASSIGN(CelValue result,
plan->Trace(activation, &arena, RecordStringValues()));
EXPECT_THAT(string_values_, ElementsAre("input123"));
EXPECT_TRUE(result.IsError());
EXPECT_TRUE(CheckNoMatchingOverloadError(result));
}
INSTANTIATE_TEST_SUITE_P(RegexPrecompilationExtensionTest,
RegexPrecompilationExtensionTest, testing::Bool());
INSTANTIATE_TEST_SUITE_P(RegexConstFoldInteropTest, RegexConstFoldInteropTest,
testing::Bool());
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/regex_precompilation_optimization.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/regex_precompilation_optimization_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
fcbc8bdc-6acd-472b-9af9-1b6f734351ec | cpp | google/cel-cpp | instrumentation | eval/compiler/instrumentation.cc | eval/compiler/instrumentation_test.cc | #include "eval/compiler/instrumentation.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "base/ast_internal/ast_impl.h"
#include "base/ast_internal/expr.h"
#include "eval/compiler/flat_expr_builder_extensions.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/expression_step_base.h"
namespace google::api::expr::runtime {
namespace {
class InstrumentStep : public ExpressionStepBase {
public:
explicit InstrumentStep(int64_t expr_id, Instrumentation instrumentation)
: ExpressionStepBase(expr_id, false),
expr_id_(expr_id),
instrumentation_(std::move(instrumentation)) {}
absl::Status Evaluate(ExecutionFrame* frame) const override {
if (!frame->value_stack().HasEnough(1)) {
return absl::InternalError("stack underflow in instrument step.");
}
return instrumentation_(expr_id_, frame->value_stack().Peek());
return absl::OkStatus();
}
private:
int64_t expr_id_;
Instrumentation instrumentation_;
};
class InstrumentOptimizer : public ProgramOptimizer {
public:
explicit InstrumentOptimizer(Instrumentation instrumentation)
: instrumentation_(std::move(instrumentation)) {}
absl::Status OnPreVisit(PlannerContext& context,
const cel::ast_internal::Expr& node) override {
return absl::OkStatus();
}
absl::Status OnPostVisit(PlannerContext& context,
const cel::ast_internal::Expr& node) override {
if (context.GetSubplan(node).empty()) {
return absl::OkStatus();
}
return context.AddSubplanStep(
node, std::make_unique<InstrumentStep>(node.id(), instrumentation_));
}
private:
Instrumentation instrumentation_;
};
}
ProgramOptimizerFactory CreateInstrumentationExtension(
InstrumentationFactory factory) {
return [fac = std::move(factory)](PlannerContext&,
const cel::ast_internal::AstImpl& ast)
-> absl::StatusOr<std::unique_ptr<ProgramOptimizer>> {
Instrumentation ins = fac(ast);
if (ins) {
return std::make_unique<InstrumentOptimizer>(std::move(ins));
}
return nullptr;
};
}
} | #include "eval/compiler/instrumentation.h"
#include <cstdint>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "base/ast_internal/ast_impl.h"
#include "common/type.h"
#include "common/value.h"
#include "eval/compiler/constant_folding.h"
#include "eval/compiler/flat_expr_builder.h"
#include "eval/compiler/regex_precompilation_optimization.h"
#include "eval/eval/evaluator_core.h"
#include "extensions/protobuf/ast_converters.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/testing.h"
#include "parser/parser.h"
#include "runtime/activation.h"
#include "runtime/function_registry.h"
#include "runtime/managed_value_factory.h"
#include "runtime/runtime_options.h"
#include "runtime/standard_functions.h"
#include "runtime/type_registry.h"
#include "google/protobuf/arena.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::IntValue;
using ::cel::Value;
using ::google::api::expr::v1alpha1::ParsedExpr;
using ::google::api::expr::parser::Parse;
using ::testing::ElementsAre;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
class InstrumentationTest : public ::testing::Test {
public:
InstrumentationTest()
: managed_value_factory_(
type_registry_.GetComposedTypeProvider(),
cel::extensions::ProtoMemoryManagerRef(&arena_)) {}
void SetUp() override {
ASSERT_OK(cel::RegisterStandardFunctions(function_registry_, options_));
}
protected:
cel::RuntimeOptions options_;
cel::FunctionRegistry function_registry_;
cel::TypeRegistry type_registry_;
google::protobuf::Arena arena_;
cel::ManagedValueFactory managed_value_factory_;
};
MATCHER_P(IsIntValue, expected, "") {
const Value& got = arg;
return got.Is<IntValue>() && got.GetInt().NativeValue() == expected;
}
TEST_F(InstrumentationTest, Basic) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
std::vector<int64_t> expr_ids;
Instrumentation expr_id_recorder =
[&expr_ids](int64_t expr_id, const cel::Value&) -> absl::Status {
expr_ids.push_back(expr_id);
return absl::OkStatus();
};
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return expr_id_recorder;
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("1 + 2 + 3"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 3, 2, 5, 4));
}
TEST_F(InstrumentationTest, BasicWithConstFolding) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
absl::flat_hash_map<int64_t, cel::Value> expr_id_to_value;
Instrumentation expr_id_recorder = [&expr_id_to_value](
int64_t expr_id,
const cel::Value& v) -> absl::Status {
expr_id_to_value[expr_id] = v;
return absl::OkStatus();
};
builder.AddProgramOptimizer(
cel::runtime_internal::CreateConstantFoldingOptimizer(
managed_value_factory_.get().GetMemoryManager()));
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return expr_id_recorder;
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("1 + 2 + 3"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
EXPECT_THAT(
expr_id_to_value,
UnorderedElementsAre(Pair(1, IsIntValue(1)), Pair(3, IsIntValue(2)),
Pair(2, IsIntValue(3)), Pair(5, IsIntValue(3))));
expr_id_to_value.clear();
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(expr_id_to_value, UnorderedElementsAre(Pair(4, IsIntValue(6))));
}
TEST_F(InstrumentationTest, AndShortCircuit) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
std::vector<int64_t> expr_ids;
Instrumentation expr_id_recorder =
[&expr_ids](int64_t expr_id, const cel::Value&) -> absl::Status {
expr_ids.push_back(expr_id);
return absl::OkStatus();
};
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return expr_id_recorder;
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("a && b"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
activation.InsertOrAssignValue(
"a", managed_value_factory_.get().CreateBoolValue(true));
activation.InsertOrAssignValue(
"b", managed_value_factory_.get().CreateBoolValue(false));
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 2, 3));
activation.InsertOrAssignValue(
"a", managed_value_factory_.get().CreateBoolValue(false));
ASSERT_OK_AND_ASSIGN(value, plan.EvaluateWithCallback(
activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 2, 3, 1, 3));
}
TEST_F(InstrumentationTest, OrShortCircuit) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
std::vector<int64_t> expr_ids;
Instrumentation expr_id_recorder =
[&expr_ids](int64_t expr_id, const cel::Value&) -> absl::Status {
expr_ids.push_back(expr_id);
return absl::OkStatus();
};
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return expr_id_recorder;
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("a || b"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
activation.InsertOrAssignValue(
"a", managed_value_factory_.get().CreateBoolValue(false));
activation.InsertOrAssignValue(
"b", managed_value_factory_.get().CreateBoolValue(true));
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 2, 3));
expr_ids.clear();
activation.InsertOrAssignValue(
"a", managed_value_factory_.get().CreateBoolValue(true));
ASSERT_OK_AND_ASSIGN(value, plan.EvaluateWithCallback(
activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 3));
}
TEST_F(InstrumentationTest, Ternary) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
std::vector<int64_t> expr_ids;
Instrumentation expr_id_recorder =
[&expr_ids](int64_t expr_id, const cel::Value&) -> absl::Status {
expr_ids.push_back(expr_id);
return absl::OkStatus();
};
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return expr_id_recorder;
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("(c)? a : b"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
activation.InsertOrAssignValue(
"c", managed_value_factory_.get().CreateBoolValue(true));
activation.InsertOrAssignValue(
"a", managed_value_factory_.get().CreateIntValue(1));
activation.InsertOrAssignValue(
"b", managed_value_factory_.get().CreateIntValue(2));
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 3, 2));
expr_ids.clear();
activation.InsertOrAssignValue(
"c", managed_value_factory_.get().CreateBoolValue(false));
ASSERT_OK_AND_ASSIGN(value, plan.EvaluateWithCallback(
activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 4, 2));
expr_ids.clear();
}
TEST_F(InstrumentationTest, OptimizedStepsNotEvaluated) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
builder.AddProgramOptimizer(CreateRegexPrecompilationExtension(0));
std::vector<int64_t> expr_ids;
Instrumentation expr_id_recorder =
[&expr_ids](int64_t expr_id, const cel::Value&) -> absl::Status {
expr_ids.push_back(expr_id);
return absl::OkStatus();
};
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return expr_id_recorder;
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr,
Parse("r'test_string'.matches(r'[a-z_]+')"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(expr_ids, ElementsAre(1, 2));
EXPECT_TRUE(value.Is<cel::BoolValue>() && value.GetBool().NativeValue());
}
TEST_F(InstrumentationTest, NoopSkipped) {
FlatExprBuilder builder(function_registry_, type_registry_, options_);
builder.AddProgramOptimizer(CreateInstrumentationExtension(
[=](const cel::ast_internal::AstImpl&) -> Instrumentation {
return Instrumentation();
}));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("(c)? a : b"));
ASSERT_OK_AND_ASSIGN(auto ast,
cel::extensions::CreateAstFromParsedExpr(expr));
ASSERT_OK_AND_ASSIGN(auto plan,
builder.CreateExpressionImpl(std::move(ast),
nullptr));
auto state = plan.MakeEvaluatorState(managed_value_factory_.get());
cel::Activation activation;
activation.InsertOrAssignValue(
"c", managed_value_factory_.get().CreateBoolValue(true));
activation.InsertOrAssignValue(
"a", managed_value_factory_.get().CreateIntValue(1));
activation.InsertOrAssignValue(
"b", managed_value_factory_.get().CreateIntValue(2));
ASSERT_OK_AND_ASSIGN(
auto value,
plan.EvaluateWithCallback(activation, EvaluationListener(), state));
EXPECT_THAT(value, IsIntValue(1));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/instrumentation.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/instrumentation_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
3a728add-5ac0-4d23-a38f-13f2c4ccb9dd | cpp | google/cel-cpp | cel_expression_builder_flat_impl | eval/compiler/cel_expression_builder_flat_impl.cc | eval/compiler/cel_expression_builder_flat_impl_test.cc | #include "eval/compiler/cel_expression_builder_flat_impl.h"
#include <memory>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/checked.pb.h"
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/base/macros.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "base/ast.h"
#include "common/native_type.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/public/cel_expression.h"
#include "extensions/protobuf/ast_converters.h"
#include "internal/status_macros.h"
#include "runtime/runtime_issue.h"
namespace google::api::expr::runtime {
using ::cel::Ast;
using ::cel::RuntimeIssue;
using ::google::api::expr::v1alpha1::CheckedExpr;
using ::google::api::expr::v1alpha1::Expr;
using ::google::api::expr::v1alpha1::SourceInfo;
absl::StatusOr<std::unique_ptr<CelExpression>>
CelExpressionBuilderFlatImpl::CreateExpression(
const Expr* expr, const SourceInfo* source_info,
std::vector<absl::Status>* warnings) const {
ABSL_ASSERT(expr != nullptr);
CEL_ASSIGN_OR_RETURN(
std::unique_ptr<Ast> converted_ast,
cel::extensions::CreateAstFromParsedExpr(*expr, source_info));
return CreateExpressionImpl(std::move(converted_ast), warnings);
}
absl::StatusOr<std::unique_ptr<CelExpression>>
CelExpressionBuilderFlatImpl::CreateExpression(
const Expr* expr, const SourceInfo* source_info) const {
return CreateExpression(expr, source_info,
nullptr);
}
absl::StatusOr<std::unique_ptr<CelExpression>>
CelExpressionBuilderFlatImpl::CreateExpression(
const CheckedExpr* checked_expr,
std::vector<absl::Status>* warnings) const {
ABSL_ASSERT(checked_expr != nullptr);
CEL_ASSIGN_OR_RETURN(
std::unique_ptr<Ast> converted_ast,
cel::extensions::CreateAstFromCheckedExpr(*checked_expr));
return CreateExpressionImpl(std::move(converted_ast), warnings);
}
absl::StatusOr<std::unique_ptr<CelExpression>>
CelExpressionBuilderFlatImpl::CreateExpression(
const CheckedExpr* checked_expr) const {
return CreateExpression(checked_expr, nullptr);
}
absl::StatusOr<std::unique_ptr<CelExpression>>
CelExpressionBuilderFlatImpl::CreateExpressionImpl(
std::unique_ptr<Ast> converted_ast,
std::vector<absl::Status>* warnings) const {
std::vector<RuntimeIssue> issues;
auto* issues_ptr = (warnings != nullptr) ? &issues : nullptr;
CEL_ASSIGN_OR_RETURN(FlatExpression impl,
flat_expr_builder_.CreateExpressionImpl(
std::move(converted_ast), issues_ptr));
if (issues_ptr != nullptr) {
for (const auto& issue : issues) {
warnings->push_back(issue.ToStatus());
}
}
if (flat_expr_builder_.options().max_recursion_depth != 0 &&
!impl.subexpressions().empty() &&
impl.subexpressions().front().size() == 1 &&
impl.subexpressions().front().front()->GetNativeTypeId() ==
cel::NativeTypeId::For<WrappedDirectStep>()) {
return CelExpressionRecursiveImpl::Create(std::move(impl));
}
return std::make_unique<CelExpressionFlatImpl>(std::move(impl));
}
} | #include "eval/compiler/cel_expression_builder_flat_impl.h"
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>
#include <vector>
#include "google/api/expr/v1alpha1/checked.pb.h"
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/algorithm/container.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "eval/compiler/constant_folding.h"
#include "eval/compiler/regex_precompilation_optimization.h"
#include "eval/eval/cel_expression_flat_impl.h"
#include "eval/public/activation.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_expression.h"
#include "eval/public/cel_function.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/portable_cel_function_adapter.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include "eval/public/testing/matchers.h"
#include "extensions/bindings_ext.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "parser/macro.h"
#include "parser/parser.h"
#include "runtime/runtime_options.h"
#include "proto/test/v1/proto3/test_all_types.pb.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::google::api::expr::v1alpha1::CheckedExpr;
using ::google::api::expr::v1alpha1::Expr;
using ::google::api::expr::v1alpha1::ParsedExpr;
using ::google::api::expr::v1alpha1::SourceInfo;
using ::google::api::expr::parser::Macro;
using ::google::api::expr::parser::Parse;
using ::google::api::expr::parser::ParseWithMacros;
using ::google::api::expr::test::v1::proto3::NestedTestAllTypes;
using ::google::api::expr::test::v1::proto3::TestAllTypes;
using ::testing::_;
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::IsNull;
using ::testing::NotNull;
TEST(CelExpressionBuilderFlatImplTest, Error) {
Expr expr;
SourceInfo source_info;
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid empty expression")));
}
TEST(CelExpressionBuilderFlatImplTest, ParsedExpr) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("1 + 2"));
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelInt64(3));
}
struct RecursiveTestCase {
std::string test_name;
std::string expr;
test::CelValueMatcher matcher;
};
class RecursivePlanTest : public ::testing::TestWithParam<RecursiveTestCase> {
protected:
absl::Status SetupBuilder(CelExpressionBuilderFlatImpl& builder) {
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
builder.GetTypeRegistry()->RegisterEnum("TestEnum",
{{"FOO", 1}, {"BAR", 2}});
CEL_RETURN_IF_ERROR(RegisterBuiltinFunctions(builder.GetRegistry()));
return builder.GetRegistry()->RegisterLazyFunction(CelFunctionDescriptor(
"LazilyBoundMult", false,
{CelValue::Type::kInt64, CelValue::Type::kInt64}));
}
absl::Status SetupActivation(Activation& activation, google::protobuf::Arena* arena) {
activation.InsertValue("int_1", CelValue::CreateInt64(1));
activation.InsertValue("string_abc", CelValue::CreateStringView("abc"));
activation.InsertValue("string_def", CelValue::CreateStringView("def"));
auto* map = google::protobuf::Arena::Create<CelMapBuilder>(arena);
CEL_RETURN_IF_ERROR(
map->Add(CelValue::CreateStringView("a"), CelValue::CreateInt64(1)));
CEL_RETURN_IF_ERROR(
map->Add(CelValue::CreateStringView("b"), CelValue::CreateInt64(2)));
activation.InsertValue("map_var", CelValue::CreateMap(map));
auto* msg = google::protobuf::Arena::Create<NestedTestAllTypes>(arena);
msg->mutable_child()->mutable_payload()->set_single_int64(42);
activation.InsertValue("struct_var",
CelProtoWrapper::CreateMessage(msg, arena));
activation.InsertValue("TestEnum.BAR", CelValue::CreateInt64(-1));
CEL_RETURN_IF_ERROR(activation.InsertFunction(
PortableBinaryFunctionAdapter<int64_t, int64_t, int64_t>::Create(
"LazilyBoundMult", false,
[](google::protobuf::Arena*, int64_t lhs, int64_t rhs) -> int64_t {
return lhs * rhs;
})));
return absl::OkStatus();
}
};
absl::StatusOr<ParsedExpr> ParseWithBind(absl::string_view cel) {
static const std::vector<Macro>* kMacros = []() {
auto* result = new std::vector<Macro>(Macro::AllMacros());
absl::c_copy(cel::extensions::bindings_macros(),
std::back_inserter(*result));
return result;
}();
return ParseWithMacros(cel, *kMacros, "<input>");
}
TEST_P(RecursivePlanTest, ParsedExprRecursiveImpl) {
const RecursiveTestCase& test_case = GetParam();
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, ParseWithBind(test_case.expr));
cel::RuntimeOptions options;
options.container = "google.api.expr.test.v1.proto3";
google::protobuf::Arena arena;
options.max_recursion_depth = -1;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK(SetupBuilder(builder));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
EXPECT_THAT(dynamic_cast<const CelExpressionRecursiveImpl*>(plan.get()),
NotNull());
Activation activation;
ASSERT_OK(SetupActivation(activation, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test_case.matcher);
}
TEST_P(RecursivePlanTest, ParsedExprRecursiveOptimizedImpl) {
const RecursiveTestCase& test_case = GetParam();
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, ParseWithBind(test_case.expr));
cel::RuntimeOptions options;
options.container = "google.api.expr.test.v1.proto3";
google::protobuf::Arena arena;
options.max_recursion_depth = -1;
options.enable_comprehension_list_append = true;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK(SetupBuilder(builder));
builder.flat_expr_builder().AddProgramOptimizer(
cel::runtime_internal::CreateConstantFoldingOptimizer(
cel::extensions::ProtoMemoryManagerRef(&arena)));
builder.flat_expr_builder().AddProgramOptimizer(
CreateRegexPrecompilationExtension(options.regex_max_program_size));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
EXPECT_THAT(dynamic_cast<const CelExpressionRecursiveImpl*>(plan.get()),
NotNull());
Activation activation;
ASSERT_OK(SetupActivation(activation, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test_case.matcher);
}
TEST_P(RecursivePlanTest, ParsedExprRecursiveTraceSupport) {
const RecursiveTestCase& test_case = GetParam();
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, ParseWithBind(test_case.expr));
cel::RuntimeOptions options;
options.container = "google.api.expr.test.v1.proto3";
google::protobuf::Arena arena;
auto cb = [](int64_t id, const CelValue& value, google::protobuf::Arena* arena) {
return absl::OkStatus();
};
options.max_recursion_depth = -1;
options.enable_recursive_tracing = true;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK(SetupBuilder(builder));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
EXPECT_THAT(dynamic_cast<const CelExpressionRecursiveImpl*>(plan.get()),
NotNull());
Activation activation;
ASSERT_OK(SetupActivation(activation, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Trace(activation, &arena, cb));
EXPECT_THAT(result, test_case.matcher);
}
TEST_P(RecursivePlanTest, Disabled) {
google::protobuf::LinkMessageReflection<TestAllTypes>();
const RecursiveTestCase& test_case = GetParam();
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, ParseWithBind(test_case.expr));
cel::RuntimeOptions options;
options.container = "google.api.expr.test.v1.proto3";
google::protobuf::Arena arena;
options.max_recursion_depth = 0;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK(SetupBuilder(builder));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
EXPECT_THAT(dynamic_cast<const CelExpressionRecursiveImpl*>(plan.get()),
IsNull());
Activation activation;
ASSERT_OK(SetupActivation(activation, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test_case.matcher);
}
INSTANTIATE_TEST_SUITE_P(
RecursivePlanTest, RecursivePlanTest,
testing::ValuesIn(std::vector<RecursiveTestCase>{
{"constant", "'abc'", test::IsCelString("abc")},
{"call", "1 + 2", test::IsCelInt64(3)},
{"nested_call", "1 + 1 + 1 + 1", test::IsCelInt64(4)},
{"and", "true && false", test::IsCelBool(false)},
{"or", "true || false", test::IsCelBool(true)},
{"ternary", "(true || false) ? 2 + 2 : 3 + 3", test::IsCelInt64(4)},
{"create_list", "3 in [1, 2, 3]", test::IsCelBool(true)},
{"create_list_complex", "3 in [2 / 2, 4 / 2, 6 / 2]",
test::IsCelBool(true)},
{"ident", "int_1 == 1", test::IsCelBool(true)},
{"ident_complex", "int_1 + 2 > 4 ? string_abc : string_def",
test::IsCelString("def")},
{"select", "struct_var.child.payload.single_int64",
test::IsCelInt64(42)},
{"nested_select", "[map_var.a, map_var.b].size() == 2",
test::IsCelBool(true)},
{"map_index", "map_var['b']", test::IsCelInt64(2)},
{"list_index", "[1, 2, 3][1]", test::IsCelInt64(2)},
{"compre_exists", "[1, 2, 3, 4].exists(x, x == 3)",
test::IsCelBool(true)},
{"compre_map", "8 in [1, 2, 3, 4].map(x, x * 2)",
test::IsCelBool(true)},
{"map_var_compre_exists", "map_var.exists(key, key == 'b')",
test::IsCelBool(true)},
{"map_compre_exists", "{'a': 1, 'b': 2}.exists(k, k == 'b')",
test::IsCelBool(true)},
{"create_map", "{'a': 42, 'b': 0, 'c': 0}.size()", test::IsCelInt64(3)},
{"create_struct",
"NestedTestAllTypes{payload: TestAllTypes{single_int64: "
"-42}}.payload.single_int64",
test::IsCelInt64(-42)},
{"bind", R"(cel.bind(x, "1", x + x + x + x))",
test::IsCelString("1111")},
{"nested_bind", R"(cel.bind(x, 20, cel.bind(y, 30, x + y)))",
test::IsCelInt64(50)},
{"bind_with_comprehensions",
R"(cel.bind(x, [1, 2], cel.bind(y, x.map(z, z * 2), y.exists(z, z == 4))))",
test::IsCelBool(true)},
{"shadowable_value_default", R"(TestEnum.FOO == 1)",
test::IsCelBool(true)},
{"shadowable_value_shadowed", R"(TestEnum.BAR == -1)",
test::IsCelBool(true)},
{"lazily_resolved_function", "LazilyBoundMult(123, 2) == 246",
test::IsCelBool(true)},
{"re_matches", "matches(string_abc, '[ad][be][cf]')",
test::IsCelBool(true)},
{"re_matches_receiver",
"(string_abc + string_def).matches(r'(123)?' + r'abc' + r'def')",
test::IsCelBool(true)},
}),
[](const testing::TestParamInfo<RecursiveTestCase>& info) -> std::string {
return info.param.test_name;
});
TEST(CelExpressionBuilderFlatImplTest, ParsedExprWithWarnings) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("1 + 2"));
cel::RuntimeOptions options;
options.fail_on_warnings = false;
CelExpressionBuilderFlatImpl builder(options);
std::vector<absl::Status> warnings;
ASSERT_OK_AND_ASSIGN(
std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info(),
&warnings));
EXPECT_THAT(warnings, Contains(StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("No overloads"))));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelError(
StatusIs(_, HasSubstr("No matching overloads"))));
}
TEST(CelExpressionBuilderFlatImplTest, CheckedExpr) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("1 + 2"));
CheckedExpr checked_expr;
checked_expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
checked_expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&checked_expr));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelInt64(3));
}
TEST(CelExpressionBuilderFlatImplTest, CheckedExprWithWarnings) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("1 + 2"));
CheckedExpr checked_expr;
checked_expr.mutable_expr()->Swap(parsed_expr.mutable_expr());
checked_expr.mutable_source_info()->Swap(parsed_expr.mutable_source_info());
cel::RuntimeOptions options;
options.fail_on_warnings = false;
CelExpressionBuilderFlatImpl builder(options);
std::vector<absl::Status> warnings;
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> plan,
builder.CreateExpression(&checked_expr, &warnings));
EXPECT_THAT(warnings, Contains(StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("No overloads"))));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelError(
StatusIs(_, HasSubstr("No matching overloads"))));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/cel_expression_builder_flat_impl.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/cel_expression_builder_flat_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
9c3fc5bd-4746-4545-bf0f-040ceafb6a90 | cpp | google/cel-cpp | flat_expr_builder_extensions | eval/compiler/flat_expr_builder_extensions.cc | eval/compiler/flat_expr_builder_extensions_test.cc | #include "eval/compiler/flat_expr_builder_extensions.h"
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/nullability.h"
#include "absl/log/absl_check.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "base/ast_internal/expr.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
namespace google::api::expr::runtime {
namespace {
using Subexpression = google::api::expr::runtime::ProgramBuilder::Subexpression;
void MaybeReassignChildRecursiveProgram(Subexpression* parent) {
if (parent->IsFlattened() || parent->IsRecursive()) {
return;
}
if (parent->elements().size() != 1) {
return;
}
auto* child_alternative =
absl::get_if<std::unique_ptr<Subexpression>>(&parent->elements()[0]);
if (child_alternative == nullptr) {
return;
}
auto& child_subexpression = *child_alternative;
if (!child_subexpression->IsRecursive()) {
return;
}
auto child_program = child_subexpression->ExtractRecursiveProgram();
parent->set_recursive_program(std::move(child_program.step),
child_program.depth);
}
}
Subexpression::Subexpression(const cel::ast_internal::Expr* self,
ProgramBuilder* owner)
: self_(self), parent_(nullptr), subprogram_map_(owner->subprogram_map_) {}
size_t Subexpression::ComputeSize() const {
if (IsFlattened()) {
return flattened_elements().size();
} else if (IsRecursive()) {
return 1;
}
std::vector<const Subexpression*> to_expand{this};
size_t size = 0;
while (!to_expand.empty()) {
const auto* expr = to_expand.back();
to_expand.pop_back();
if (expr->IsFlattened()) {
size += expr->flattened_elements().size();
continue;
} else if (expr->IsRecursive()) {
size += 1;
continue;
}
for (const auto& elem : expr->elements()) {
if (auto* child = absl::get_if<std::unique_ptr<Subexpression>>(&elem);
child != nullptr) {
to_expand.push_back(child->get());
} else {
size += 1;
}
}
}
return size;
}
absl::optional<int> Subexpression::RecursiveDependencyDepth() const {
auto* tree = absl::get_if<TreePlan>(&program_);
int depth = 0;
if (tree == nullptr) {
return absl::nullopt;
}
for (const auto& element : *tree) {
auto* subexpression =
absl::get_if<std::unique_ptr<Subexpression>>(&element);
if (subexpression == nullptr) {
return absl::nullopt;
}
if (!(*subexpression)->IsRecursive()) {
return absl::nullopt;
}
depth = std::max(depth, (*subexpression)->recursive_program().depth);
}
return depth;
}
std::vector<std::unique_ptr<DirectExpressionStep>>
Subexpression::ExtractRecursiveDependencies() const {
auto* tree = absl::get_if<TreePlan>(&program_);
std::vector<std::unique_ptr<DirectExpressionStep>> dependencies;
if (tree == nullptr) {
return {};
}
for (const auto& element : *tree) {
auto* subexpression =
absl::get_if<std::unique_ptr<Subexpression>>(&element);
if (subexpression == nullptr) {
return {};
}
if (!(*subexpression)->IsRecursive()) {
return {};
}
dependencies.push_back((*subexpression)->ExtractRecursiveProgram().step);
}
return dependencies;
}
Subexpression::~Subexpression() {
auto map_ptr = subprogram_map_.lock();
if (map_ptr == nullptr) {
return;
}
auto it = map_ptr->find(self_);
if (it != map_ptr->end() && it->second == this) {
map_ptr->erase(it);
}
}
std::unique_ptr<Subexpression> Subexpression::ExtractChild(
Subexpression* child) {
if (IsFlattened()) {
return nullptr;
}
for (auto iter = elements().begin(); iter != elements().end(); ++iter) {
Subexpression::Element& element = *iter;
if (!absl::holds_alternative<std::unique_ptr<Subexpression>>(element)) {
continue;
}
auto& subexpression_owner =
absl::get<std::unique_ptr<Subexpression>>(element);
if (subexpression_owner.get() != child) {
continue;
}
std::unique_ptr<Subexpression> result = std::move(subexpression_owner);
elements().erase(iter);
return result;
}
return nullptr;
}
int Subexpression::CalculateOffset(int base, int target) const {
ABSL_DCHECK(!IsFlattened());
ABSL_DCHECK(!IsRecursive());
ABSL_DCHECK_GE(base, 0);
ABSL_DCHECK_GE(target, 0);
ABSL_DCHECK_LE(base, elements().size());
ABSL_DCHECK_LE(target, elements().size());
int sign = 1;
if (target <= base) {
int tmp = base;
base = target - 1;
target = tmp + 1;
sign = -1;
}
int sum = 0;
for (int i = base + 1; i < target; ++i) {
const auto& element = elements()[i];
if (auto* subexpr = absl::get_if<std::unique_ptr<Subexpression>>(&element);
subexpr != nullptr) {
sum += (*subexpr)->ComputeSize();
} else {
sum += 1;
}
}
return sign * sum;
}
void Subexpression::Flatten() {
struct Record {
Subexpression* subexpr;
size_t offset;
};
if (IsFlattened()) {
return;
}
std::vector<std::unique_ptr<const ExpressionStep>> flat;
std::vector<Record> flatten_stack;
flatten_stack.push_back({this, 0});
while (!flatten_stack.empty()) {
Record top = flatten_stack.back();
flatten_stack.pop_back();
size_t offset = top.offset;
auto* subexpr = top.subexpr;
if (subexpr->IsFlattened()) {
absl::c_move(subexpr->flattened_elements(), std::back_inserter(flat));
continue;
} else if (subexpr->IsRecursive()) {
flat.push_back(std::make_unique<WrappedDirectStep>(
std::move(subexpr->ExtractRecursiveProgram().step),
subexpr->self_->id()));
}
size_t size = subexpr->elements().size();
size_t i = offset;
for (; i < size; ++i) {
auto& element = subexpr->elements()[i];
if (auto* child = absl::get_if<std::unique_ptr<Subexpression>>(&element);
child != nullptr) {
flatten_stack.push_back({subexpr, i + 1});
flatten_stack.push_back({child->get(), 0});
break;
} else if (auto* step =
absl::get_if<std::unique_ptr<ExpressionStep>>(&element);
step != nullptr) {
flat.push_back(std::move(*step));
}
}
if (i >= size && subexpr != this) {
subexpr->program_.emplace<std::vector<Subexpression::Element>>();
}
}
program_ = std::move(flat);
}
Subexpression::RecursiveProgram Subexpression::ExtractRecursiveProgram() {
ABSL_DCHECK(IsRecursive());
auto result = std::move(absl::get<RecursiveProgram>(program_));
program_.emplace<std::vector<Subexpression::Element>>();
return result;
}
bool Subexpression::ExtractTo(
std::vector<std::unique_ptr<const ExpressionStep>>& out) {
if (!IsFlattened()) {
return false;
}
out.reserve(out.size() + flattened_elements().size());
absl::c_move(flattened_elements(), std::back_inserter(out));
program_.emplace<std::vector<Element>>();
return true;
}
std::vector<std::unique_ptr<const ExpressionStep>>
ProgramBuilder::FlattenSubexpression(std::unique_ptr<Subexpression> expr) {
std::vector<std::unique_ptr<const ExpressionStep>> out;
if (!expr) {
return out;
}
expr->Flatten();
expr->ExtractTo(out);
return out;
}
ProgramBuilder::ProgramBuilder()
: root_(nullptr),
current_(nullptr),
subprogram_map_(std::make_shared<SubprogramMap>()) {}
ExecutionPath ProgramBuilder::FlattenMain() {
auto out = FlattenSubexpression(std::move(root_));
return out;
}
std::vector<ExecutionPath> ProgramBuilder::FlattenSubexpressions() {
std::vector<ExecutionPath> out;
out.reserve(extracted_subexpressions_.size());
for (auto& subexpression : extracted_subexpressions_) {
out.push_back(FlattenSubexpression(std::move(subexpression)));
}
extracted_subexpressions_.clear();
return out;
}
absl::Nullable<Subexpression*> ProgramBuilder::EnterSubexpression(
const cel::ast_internal::Expr* expr) {
std::unique_ptr<Subexpression> subexpr = MakeSubexpression(expr);
auto* result = subexpr.get();
if (current_ == nullptr) {
root_ = std::move(subexpr);
current_ = result;
return result;
}
current_->AddSubexpression(std::move(subexpr));
result->parent_ = current_->self_;
current_ = result;
return result;
}
absl::Nullable<Subexpression*> ProgramBuilder::ExitSubexpression(
const cel::ast_internal::Expr* expr) {
ABSL_DCHECK(expr == current_->self_);
ABSL_DCHECK(GetSubexpression(expr) == current_);
MaybeReassignChildRecursiveProgram(current_);
Subexpression* result = GetSubexpression(current_->parent_);
ABSL_DCHECK(result != nullptr || current_ == root_.get());
current_ = result;
return result;
}
absl::Nullable<Subexpression*> ProgramBuilder::GetSubexpression(
const cel::ast_internal::Expr* expr) {
auto it = subprogram_map_->find(expr);
if (it == subprogram_map_->end()) {
return nullptr;
}
return it->second;
}
void ProgramBuilder::AddStep(std::unique_ptr<ExpressionStep> step) {
if (current_ == nullptr) {
return;
}
current_->AddStep(std::move(step));
}
int ProgramBuilder::ExtractSubexpression(const cel::ast_internal::Expr* expr) {
auto it = subprogram_map_->find(expr);
if (it == subprogram_map_->end()) {
return -1;
}
auto* subexpression = it->second;
auto parent_it = subprogram_map_->find(subexpression->parent_);
if (parent_it == subprogram_map_->end()) {
return -1;
}
auto* parent = parent_it->second;
std::unique_ptr<Subexpression> subexpression_owner =
parent->ExtractChild(subexpression);
if (subexpression_owner == nullptr) {
return -1;
}
extracted_subexpressions_.push_back(std::move(subexpression_owner));
return extracted_subexpressions_.size() - 1;
}
std::unique_ptr<Subexpression> ProgramBuilder::MakeSubexpression(
const cel::ast_internal::Expr* expr) {
auto* subexpr = new Subexpression(expr, this);
(*subprogram_map_)[expr] = subexpr;
return absl::WrapUnique(subexpr);
}
bool PlannerContext::IsSubplanInspectable(
const cel::ast_internal::Expr& node) const {
return program_builder_.GetSubexpression(&node) != nullptr;
}
ExecutionPathView PlannerContext::GetSubplan(
const cel::ast_internal::Expr& node) {
auto* subexpression = program_builder_.GetSubexpression(&node);
if (subexpression == nullptr) {
return ExecutionPathView();
}
subexpression->Flatten();
return subexpression->flattened_elements();
}
absl::StatusOr<ExecutionPath> PlannerContext::ExtractSubplan(
const cel::ast_internal::Expr& node) {
auto* subexpression = program_builder_.GetSubexpression(&node);
if (subexpression == nullptr) {
return absl::InternalError(
"attempted to update program step for untracked expr node");
}
subexpression->Flatten();
ExecutionPath out;
subexpression->ExtractTo(out);
return out;
}
absl::Status PlannerContext::ReplaceSubplan(const cel::ast_internal::Expr& node,
ExecutionPath path) {
auto* subexpression = program_builder_.GetSubexpression(&node);
if (subexpression == nullptr) {
return absl::InternalError(
"attempted to update program step for untracked expr node");
}
if (!subexpression->IsFlattened()) {
subexpression->Flatten();
}
subexpression->flattened_elements() = std::move(path);
return absl::OkStatus();
}
absl::Status PlannerContext::ReplaceSubplan(
const cel::ast_internal::Expr& node,
std::unique_ptr<DirectExpressionStep> step, int depth) {
auto* subexpression = program_builder_.GetSubexpression(&node);
if (subexpression == nullptr) {
return absl::InternalError(
"attempted to update program step for untracked expr node");
}
subexpression->set_recursive_program(std::move(step), depth);
return absl::OkStatus();
}
absl::Status PlannerContext::AddSubplanStep(
const cel::ast_internal::Expr& node, std::unique_ptr<ExpressionStep> step) {
auto* subexpression = program_builder_.GetSubexpression(&node);
if (subexpression == nullptr) {
return absl::InternalError(
"attempted to update program step for untracked expr node");
}
subexpression->AddStep(std::move(step));
return absl::OkStatus();
}
} | #include "eval/compiler/flat_expr_builder_extensions.h"
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "base/ast_internal/expr.h"
#include "common/memory.h"
#include "common/native_type.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/compiler/resolver.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/function_step.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "runtime/function_registry.h"
#include "runtime/internal/issue_collector.h"
#include "runtime/runtime_issue.h"
#include "runtime/runtime_options.h"
#include "runtime/type_registry.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::RuntimeIssue;
using ::cel::ast_internal::Expr;
using ::cel::runtime_internal::IssueCollector;
using ::testing::ElementsAre;
using ::testing::IsEmpty;
using ::testing::Optional;
using Subexpression = ProgramBuilder::Subexpression;
class PlannerContextTest : public testing::Test {
public:
PlannerContextTest()
: type_registry_(),
function_registry_(),
value_factory_(cel::MemoryManagerRef::ReferenceCounting(),
type_registry_.GetComposedTypeProvider()),
resolver_("", function_registry_, type_registry_, value_factory_,
type_registry_.resolveable_enums()),
issue_collector_(RuntimeIssue::Severity::kError) {}
protected:
cel::TypeRegistry type_registry_;
cel::FunctionRegistry function_registry_;
cel::RuntimeOptions options_;
cel::common_internal::LegacyValueManager value_factory_;
Resolver resolver_;
IssueCollector issue_collector_;
};
MATCHER_P(UniquePtrHolds, ptr, "") {
const auto& got = arg;
return ptr == got.get();
}
struct SimpleTreeSteps {
const ExpressionStep* a;
const ExpressionStep* b;
const ExpressionStep* c;
};
absl::StatusOr<SimpleTreeSteps> InitSimpleTree(
const Expr& a, const Expr& b, const Expr& c,
cel::ValueManager& value_factory, ProgramBuilder& program_builder) {
CEL_ASSIGN_OR_RETURN(auto a_step,
CreateConstValueStep(value_factory.GetNullValue(), -1));
CEL_ASSIGN_OR_RETURN(auto b_step,
CreateConstValueStep(value_factory.GetNullValue(), -1));
CEL_ASSIGN_OR_RETURN(auto c_step,
CreateConstValueStep(value_factory.GetNullValue(), -1));
SimpleTreeSteps result{a_step.get(), b_step.get(), c_step.get()};
program_builder.EnterSubexpression(&a);
program_builder.EnterSubexpression(&b);
program_builder.AddStep(std::move(b_step));
program_builder.ExitSubexpression(&b);
program_builder.EnterSubexpression(&c);
program_builder.AddStep(std::move(c_step));
program_builder.ExitSubexpression(&c);
program_builder.AddStep(std::move(a_step));
program_builder.ExitSubexpression(&a);
return result;
}
TEST_F(PlannerContextTest, GetPlan) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(
auto step_ptrs, InitSimpleTree(a, b, c, value_factory_, program_builder));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
EXPECT_THAT(context.GetSubplan(b), ElementsAre(UniquePtrHolds(step_ptrs.b)));
EXPECT_THAT(context.GetSubplan(c), ElementsAre(UniquePtrHolds(step_ptrs.c)));
EXPECT_THAT(context.GetSubplan(a), ElementsAre(UniquePtrHolds(step_ptrs.b),
UniquePtrHolds(step_ptrs.c),
UniquePtrHolds(step_ptrs.a)));
Expr d;
EXPECT_FALSE(context.IsSubplanInspectable(d));
EXPECT_THAT(context.GetSubplan(d), IsEmpty());
}
TEST_F(PlannerContextTest, ReplacePlan) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(
auto step_ptrs, InitSimpleTree(a, b, c, value_factory_, program_builder));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
EXPECT_THAT(context.GetSubplan(a), ElementsAre(UniquePtrHolds(step_ptrs.b),
UniquePtrHolds(step_ptrs.c),
UniquePtrHolds(step_ptrs.a)));
ExecutionPath new_a;
ASSERT_OK_AND_ASSIGN(auto new_a_step,
CreateConstValueStep(value_factory_.GetNullValue(), -1));
const ExpressionStep* new_a_step_ptr = new_a_step.get();
new_a.push_back(std::move(new_a_step));
ASSERT_OK(context.ReplaceSubplan(a, std::move(new_a)));
EXPECT_THAT(context.GetSubplan(a),
ElementsAre(UniquePtrHolds(new_a_step_ptr)));
EXPECT_THAT(context.GetSubplan(b), IsEmpty());
}
TEST_F(PlannerContextTest, ExtractPlan) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(auto plan_steps, InitSimpleTree(a, b, c, value_factory_,
program_builder));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
EXPECT_TRUE(context.IsSubplanInspectable(a));
EXPECT_TRUE(context.IsSubplanInspectable(b));
ASSERT_OK_AND_ASSIGN(ExecutionPath extracted, context.ExtractSubplan(b));
EXPECT_THAT(extracted, ElementsAre(UniquePtrHolds(plan_steps.b)));
}
TEST_F(PlannerContextTest, ExtractFailsOnReplacedNode) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK(InitSimpleTree(a, b, c, value_factory_, program_builder).status());
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
ASSERT_OK(context.ReplaceSubplan(a, {}));
EXPECT_THAT(context.ExtractSubplan(b), StatusIs(absl::StatusCode::kInternal));
}
TEST_F(PlannerContextTest, ReplacePlanUpdatesParent) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(auto plan_steps, InitSimpleTree(a, b, c, value_factory_,
program_builder));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
EXPECT_TRUE(context.IsSubplanInspectable(a));
ASSERT_OK(context.ReplaceSubplan(c, {}));
EXPECT_THAT(context.GetSubplan(a), ElementsAre(UniquePtrHolds(plan_steps.b),
UniquePtrHolds(plan_steps.a)));
EXPECT_THAT(context.GetSubplan(c), IsEmpty());
}
TEST_F(PlannerContextTest, ReplacePlanUpdatesSibling) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(auto plan_steps, InitSimpleTree(a, b, c, value_factory_,
program_builder));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
ExecutionPath new_b;
ASSERT_OK_AND_ASSIGN(auto b1_step,
CreateConstValueStep(value_factory_.GetNullValue(), -1));
const ExpressionStep* b1_step_ptr = b1_step.get();
new_b.push_back(std::move(b1_step));
ASSERT_OK_AND_ASSIGN(auto b2_step,
CreateConstValueStep(value_factory_.GetNullValue(), -1));
const ExpressionStep* b2_step_ptr = b2_step.get();
new_b.push_back(std::move(b2_step));
ASSERT_OK(context.ReplaceSubplan(b, std::move(new_b)));
EXPECT_THAT(context.GetSubplan(c), ElementsAre(UniquePtrHolds(plan_steps.c)));
EXPECT_THAT(context.GetSubplan(b), ElementsAre(UniquePtrHolds(b1_step_ptr),
UniquePtrHolds(b2_step_ptr)));
EXPECT_THAT(
context.GetSubplan(a),
ElementsAre(UniquePtrHolds(b1_step_ptr), UniquePtrHolds(b2_step_ptr),
UniquePtrHolds(plan_steps.c), UniquePtrHolds(plan_steps.a)));
}
TEST_F(PlannerContextTest, ReplacePlanFailsOnUpdatedNode) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(auto plan_steps, InitSimpleTree(a, b, c, value_factory_,
program_builder));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
EXPECT_THAT(context.GetSubplan(a), ElementsAre(UniquePtrHolds(plan_steps.b),
UniquePtrHolds(plan_steps.c),
UniquePtrHolds(plan_steps.a)));
ASSERT_OK(context.ReplaceSubplan(a, {}));
EXPECT_THAT(context.ReplaceSubplan(b, {}),
StatusIs(absl::StatusCode::kInternal));
}
TEST_F(PlannerContextTest, AddSubplanStep) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(auto plan_steps, InitSimpleTree(a, b, c, value_factory_,
program_builder));
ASSERT_OK_AND_ASSIGN(auto b2_step,
CreateConstValueStep(value_factory_.GetNullValue(), -1));
const ExpressionStep* b2_step_ptr = b2_step.get();
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
ASSERT_OK(context.AddSubplanStep(b, std::move(b2_step)));
EXPECT_THAT(context.GetSubplan(b), ElementsAre(UniquePtrHolds(plan_steps.b),
UniquePtrHolds(b2_step_ptr)));
EXPECT_THAT(context.GetSubplan(c), ElementsAre(UniquePtrHolds(plan_steps.c)));
EXPECT_THAT(
context.GetSubplan(a),
ElementsAre(UniquePtrHolds(plan_steps.b), UniquePtrHolds(b2_step_ptr),
UniquePtrHolds(plan_steps.c), UniquePtrHolds(plan_steps.a)));
}
TEST_F(PlannerContextTest, AddSubplanStepFailsOnUnknownNode) {
Expr a;
Expr b;
Expr c;
Expr d;
ProgramBuilder program_builder;
ASSERT_OK(InitSimpleTree(a, b, c, value_factory_, program_builder).status());
ASSERT_OK_AND_ASSIGN(auto b2_step,
CreateConstValueStep(value_factory_.GetNullValue(), -1));
PlannerContext context(resolver_, options_, value_factory_, issue_collector_,
program_builder);
EXPECT_THAT(context.GetSubplan(d), IsEmpty());
EXPECT_THAT(context.AddSubplanStep(d, std::move(b2_step)),
StatusIs(absl::StatusCode::kInternal));
}
class ProgramBuilderTest : public testing::Test {
public:
ProgramBuilderTest()
: type_registry_(),
function_registry_(),
value_factory_(cel::MemoryManagerRef::ReferenceCounting(),
type_registry_.GetComposedTypeProvider()) {}
protected:
cel::TypeRegistry type_registry_;
cel::FunctionRegistry function_registry_;
cel::common_internal::LegacyValueManager value_factory_;
};
TEST_F(ProgramBuilderTest, ExtractSubexpression) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(
SimpleTreeSteps step_ptrs,
InitSimpleTree(a, b, c, value_factory_, program_builder));
EXPECT_EQ(program_builder.ExtractSubexpression(&c), 0);
EXPECT_EQ(program_builder.ExtractSubexpression(&b), 1);
EXPECT_THAT(program_builder.FlattenMain(),
ElementsAre(UniquePtrHolds(step_ptrs.a)));
EXPECT_THAT(program_builder.FlattenSubexpressions(),
ElementsAre(ElementsAre(UniquePtrHolds(step_ptrs.c)),
ElementsAre(UniquePtrHolds(step_ptrs.b))));
}
TEST_F(ProgramBuilderTest, FlattenRemovesChildrenReferences) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
program_builder.EnterSubexpression(&a);
program_builder.EnterSubexpression(&b);
program_builder.EnterSubexpression(&c);
program_builder.ExitSubexpression(&c);
program_builder.ExitSubexpression(&b);
program_builder.ExitSubexpression(&a);
auto subexpr_b = program_builder.GetSubexpression(&b);
ASSERT_TRUE(subexpr_b != nullptr);
subexpr_b->Flatten();
EXPECT_EQ(program_builder.GetSubexpression(&c), nullptr);
}
TEST_F(ProgramBuilderTest, ExtractReturnsNullOnFlattendExpr) {
Expr a;
Expr b;
ProgramBuilder program_builder;
program_builder.EnterSubexpression(&a);
program_builder.EnterSubexpression(&b);
program_builder.ExitSubexpression(&b);
program_builder.ExitSubexpression(&a);
auto* subexpr_a = program_builder.GetSubexpression(&a);
auto* subexpr_b = program_builder.GetSubexpression(&b);
ASSERT_TRUE(subexpr_a != nullptr);
ASSERT_TRUE(subexpr_b != nullptr);
subexpr_a->Flatten();
EXPECT_EQ(subexpr_a->ExtractChild(subexpr_b), nullptr);
EXPECT_EQ(program_builder.ExtractSubexpression(&b), -1);
}
TEST_F(ProgramBuilderTest, ExtractReturnsNullOnNonChildren) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
program_builder.EnterSubexpression(&a);
program_builder.EnterSubexpression(&b);
program_builder.EnterSubexpression(&c);
program_builder.ExitSubexpression(&c);
program_builder.ExitSubexpression(&b);
program_builder.ExitSubexpression(&a);
auto* subexpr_a = program_builder.GetSubexpression(&a);
auto* subexpr_c = program_builder.GetSubexpression(&c);
ASSERT_TRUE(subexpr_a != nullptr);
ASSERT_TRUE(subexpr_c != nullptr);
EXPECT_EQ(subexpr_a->ExtractChild(subexpr_c), nullptr);
}
TEST_F(ProgramBuilderTest, ExtractWorks) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
program_builder.EnterSubexpression(&a);
program_builder.EnterSubexpression(&b);
program_builder.ExitSubexpression(&b);
ASSERT_OK_AND_ASSIGN(auto a_step,
CreateConstValueStep(value_factory_.GetNullValue(), -1));
program_builder.AddStep(std::move(a_step));
program_builder.EnterSubexpression(&c);
program_builder.ExitSubexpression(&c);
program_builder.ExitSubexpression(&a);
auto* subexpr_a = program_builder.GetSubexpression(&a);
auto* subexpr_c = program_builder.GetSubexpression(&c);
ASSERT_TRUE(subexpr_a != nullptr);
ASSERT_TRUE(subexpr_c != nullptr);
EXPECT_THAT(subexpr_a->ExtractChild(subexpr_c), UniquePtrHolds(subexpr_c));
}
TEST_F(ProgramBuilderTest, ExtractToRequiresFlatten) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
ASSERT_OK_AND_ASSIGN(
SimpleTreeSteps step_ptrs,
InitSimpleTree(a, b, c, value_factory_, program_builder));
auto* subexpr_a = program_builder.GetSubexpression(&a);
ExecutionPath path;
EXPECT_FALSE(subexpr_a->ExtractTo(path));
subexpr_a->Flatten();
EXPECT_TRUE(subexpr_a->ExtractTo(path));
EXPECT_THAT(path, ElementsAre(UniquePtrHolds(step_ptrs.b),
UniquePtrHolds(step_ptrs.c),
UniquePtrHolds(step_ptrs.a)));
}
TEST_F(ProgramBuilderTest, Recursive) {
Expr a;
Expr b;
Expr c;
ProgramBuilder program_builder;
program_builder.EnterSubexpression(&a);
program_builder.EnterSubexpression(&b);
program_builder.current()->set_recursive_program(
CreateConstValueDirectStep(value_factory_.GetNullValue()), 1);
program_builder.ExitSubexpression(&b);
program_builder.EnterSubexpression(&c);
program_builder.current()->set_recursive_program(
CreateConstValueDirectStep(value_factory_.GetNullValue()), 1);
program_builder.ExitSubexpression(&c);
ASSERT_FALSE(program_builder.current()->IsFlattened());
ASSERT_FALSE(program_builder.current()->IsRecursive());
ASSERT_TRUE(program_builder.GetSubexpression(&b)->IsRecursive());
ASSERT_TRUE(program_builder.GetSubexpression(&c)->IsRecursive());
EXPECT_EQ(program_builder.GetSubexpression(&b)->recursive_program().depth, 1);
EXPECT_EQ(program_builder.GetSubexpression(&c)->recursive_program().depth, 1);
cel::ast_internal::Call call_expr;
call_expr.set_function("_==_");
call_expr.mutable_args().emplace_back();
call_expr.mutable_args().emplace_back();
auto max_depth = program_builder.current()->RecursiveDependencyDepth();
EXPECT_THAT(max_depth, Optional(1));
auto deps = program_builder.current()->ExtractRecursiveDependencies();
program_builder.current()->set_recursive_program(
CreateDirectFunctionStep(-1, call_expr, std::move(deps), {}),
*max_depth + 1);
program_builder.ExitSubexpression(&a);
auto path = program_builder.FlattenMain();
ASSERT_THAT(path, testing::SizeIs(1));
EXPECT_TRUE(path[0]->GetNativeTypeId() ==
cel::NativeTypeId::For<WrappedDirectStep>());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/flat_expr_builder_extensions.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/flat_expr_builder_extensions_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
4538cf80-68bd-46c3-8ce6-1a1a490cd832 | cpp | google/cel-cpp | flat_expr_builder | eval/compiler/flat_expr_builder.cc | eval/compiler/flat_expr_builder_test.cc | #include "eval/compiler/flat_expr_builder.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <iterator>
#include <memory>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/node_hash_map.h"
#include "absl/log/absl_check.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "absl/types/variant.h"
#include "base/ast.h"
#include "base/ast_internal/ast_impl.h"
#include "base/ast_internal/expr.h"
#include "base/builtins.h"
#include "common/ast.h"
#include "common/ast_traverse.h"
#include "common/ast_visitor.h"
#include "common/memory.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/compiler/flat_expr_builder_extensions.h"
#include "eval/compiler/resolver.h"
#include "eval/eval/comprehension_step.h"
#include "eval/eval/const_value_step.h"
#include "eval/eval/container_access_step.h"
#include "eval/eval/create_list_step.h"
#include "eval/eval/create_map_step.h"
#include "eval/eval/create_struct_step.h"
#include "eval/eval/direct_expression_step.h"
#include "eval/eval/evaluator_core.h"
#include "eval/eval/function_step.h"
#include "eval/eval/ident_step.h"
#include "eval/eval/jump_step.h"
#include "eval/eval/lazy_init_step.h"
#include "eval/eval/logic_step.h"
#include "eval/eval/optional_or_step.h"
#include "eval/eval/select_step.h"
#include "eval/eval/shadowable_value_step.h"
#include "eval/eval/ternary_step.h"
#include "eval/eval/trace_step.h"
#include "internal/status_macros.h"
#include "runtime/internal/convert_constant.h"
#include "runtime/internal/issue_collector.h"
#include "runtime/runtime_issue.h"
#include "runtime/runtime_options.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::Ast;
using ::cel::AstTraverse;
using ::cel::RuntimeIssue;
using ::cel::StringValue;
using ::cel::Value;
using ::cel::ValueManager;
using ::cel::ast_internal::AstImpl;
using ::cel::runtime_internal::ConvertConstant;
using ::cel::runtime_internal::IssueCollector;
constexpr absl::string_view kOptionalOrFn = "or";
constexpr absl::string_view kOptionalOrValueFn = "orValue";
class FlatExprVisitor;
class IndexManager {
public:
IndexManager() : next_free_slot_(0), max_slot_count_(0) {}
size_t ReserveSlots(size_t n) {
size_t result = next_free_slot_;
next_free_slot_ += n;
if (next_free_slot_ > max_slot_count_) {
max_slot_count_ = next_free_slot_;
}
return result;
}
size_t ReleaseSlots(size_t n) {
next_free_slot_ -= n;
return next_free_slot_;
}
size_t max_slot_count() const { return max_slot_count_; }
private:
size_t next_free_slot_;
size_t max_slot_count_;
};
struct ProgramStepIndex {
int index;
ProgramBuilder::Subexpression* subexpression;
};
class Jump {
public:
explicit Jump() : self_index_{-1, nullptr}, jump_step_(nullptr) {}
Jump(ProgramStepIndex self_index, JumpStepBase* jump_step)
: self_index_(self_index), jump_step_(jump_step) {}
static absl::StatusOr<int> CalculateOffset(ProgramStepIndex base,
ProgramStepIndex target) {
if (target.subexpression != base.subexpression) {
return absl::InternalError(
"Jump target must be contained in the parent"
"subexpression");
}
int offset = base.subexpression->CalculateOffset(base.index, target.index);
return offset;
}
absl::Status set_target(ProgramStepIndex target) {
CEL_ASSIGN_OR_RETURN(int offset, CalculateOffset(self_index_, target));
jump_step_->set_jump_offset(offset);
return absl::OkStatus();
}
bool exists() { return jump_step_ != nullptr; }
private:
ProgramStepIndex self_index_;
JumpStepBase* jump_step_;
};
class CondVisitor {
public:
virtual ~CondVisitor() = default;
virtual void PreVisit(const cel::ast_internal::Expr* expr) = 0;
virtual void PostVisitArg(int arg_num,
const cel::ast_internal::Expr* expr) = 0;
virtual void PostVisit(const cel::ast_internal::Expr* expr) = 0;
virtual void PostVisitTarget(const cel::ast_internal::Expr* expr) {}
};
enum class BinaryCond {
kAnd = 0,
kOr,
kOptionalOr,
kOptionalOrValue,
};
class BinaryCondVisitor : public CondVisitor {
public:
explicit BinaryCondVisitor(FlatExprVisitor* visitor, BinaryCond cond,
bool short_circuiting)
: visitor_(visitor), cond_(cond), short_circuiting_(short_circuiting) {}
void PreVisit(const cel::ast_internal::Expr* expr) override;
void PostVisitArg(int arg_num, const cel::ast_internal::Expr* expr) override;
void PostVisit(const cel::ast_internal::Expr* expr) override;
void PostVisitTarget(const cel::ast_internal::Expr* expr) override;
private:
FlatExprVisitor* visitor_;
const BinaryCond cond_;
Jump jump_step_;
bool short_circuiting_;
};
class TernaryCondVisitor : public CondVisitor {
public:
explicit TernaryCondVisitor(FlatExprVisitor* visitor) : visitor_(visitor) {}
void PreVisit(const cel::ast_internal::Expr* expr) override;
void PostVisitArg(int arg_num, const cel::ast_internal::Expr* expr) override;
void PostVisit(const cel::ast_internal::Expr* expr) override;
private:
FlatExprVisitor* visitor_;
Jump jump_to_second_;
Jump error_jump_;
Jump jump_after_first_;
};
class ExhaustiveTernaryCondVisitor : public CondVisitor {
public:
explicit ExhaustiveTernaryCondVisitor(FlatExprVisitor* visitor)
: visitor_(visitor) {}
void PreVisit(const cel::ast_internal::Expr* expr) override;
void PostVisitArg(int arg_num, const cel::ast_internal::Expr* expr) override {
}
void PostVisit(const cel::ast_internal::Expr* expr) override;
private:
FlatExprVisitor* visitor_;
};
bool IsOptimizableListAppend(
const cel::ast_internal::Comprehension* comprehension,
bool enable_comprehension_list_append) {
if (!enable_comprehension_list_append) {
return false;
}
absl::string_view accu_var = comprehension->accu_var();
if (accu_var.empty() ||
comprehension->result().ident_expr().name() != accu_var) {
return false;
}
if (!comprehension->accu_init().has_list_expr()) {
return false;
}
if (!comprehension->loop_step().has_call_expr()) {
return false;
}
const auto* call_expr = &comprehension->loop_step().call_expr();
if (call_expr->function() == cel::builtin::kTernary &&
call_expr->args().size() == 3) {
if (!call_expr->args()[1].has_call_expr()) {
return false;
}
call_expr = &(call_expr->args()[1].call_expr());
}
return call_expr->function() == cel::builtin::kAdd &&
call_expr->args().size() == 2 &&
call_expr->args()[0].has_ident_expr() &&
call_expr->args()[0].ident_expr().name() == accu_var;
}
bool IsBind(const cel::ast_internal::Comprehension* comprehension) {
static constexpr absl::string_view kUnusedIterVar = "#unused";
return comprehension->loop_condition().const_expr().has_bool_value() &&
comprehension->loop_condition().const_expr().bool_value() == false &&
comprehension->iter_var() == kUnusedIterVar &&
comprehension->iter_range().has_list_expr() &&
comprehension->iter_range().list_expr().elements().empty();
}
bool IsBlock(const cel::ast_internal::Call* call) {
return call->function() == "cel.@block";
}
class ComprehensionVisitor {
public:
explicit ComprehensionVisitor(FlatExprVisitor* visitor, bool short_circuiting,
bool is_trivial, size_t iter_slot,
size_t accu_slot)
: visitor_(visitor),
next_step_(nullptr),
cond_step_(nullptr),
short_circuiting_(short_circuiting),
is_trivial_(is_trivial),
accu_init_extracted_(false),
iter_slot_(iter_slot),
accu_slot_(accu_slot) {}
void PreVisit(const cel::ast_internal::Expr* expr);
absl::Status PostVisitArg(cel::ComprehensionArg arg_num,
const cel::ast_internal::Expr* comprehension_expr) {
if (is_trivial_) {
PostVisitArgTrivial(arg_num, comprehension_expr);
return absl::OkStatus();
} else {
return PostVisitArgDefault(arg_num, comprehension_expr);
}
}
void PostVisit(const cel::ast_internal::Expr* expr);
void MarkAccuInitExtracted() { accu_init_extracted_ = true; }
private:
void PostVisitArgTrivial(cel::ComprehensionArg arg_num,
const cel::ast_internal::Expr* comprehension_expr);
absl::Status PostVisitArgDefault(
cel::ComprehensionArg arg_num,
const cel::ast_internal::Expr* comprehension_expr);
FlatExprVisitor* visitor_;
ComprehensionNextStep* next_step_;
ComprehensionCondStep* cond_step_;
ProgramStepIndex next_step_pos_;
ProgramStepIndex cond_step_pos_;
bool short_circuiting_;
bool is_trivial_;
bool accu_init_extracted_;
size_t iter_slot_;
size_t accu_slot_;
};
absl::flat_hash_set<int32_t> MakeOptionalIndicesSet(
const cel::ast_internal::CreateList& create_list_expr) {
absl::flat_hash_set<int32_t> optional_indices;
for (size_t i = 0; i < create_list_expr.elements().size(); ++i) {
if (create_list_expr.elements()[i].optional()) {
optional_indices.insert(static_cast<int32_t>(i));
}
}
return optional_indices;
}
absl::flat_hash_set<int32_t> MakeOptionalIndicesSet(
const cel::ast_internal::CreateStruct& create_struct_expr) {
absl::flat_hash_set<int32_t> optional_indices;
for (size_t i = 0; i < create_struct_expr.fields().size(); ++i) {
if (create_struct_expr.fields()[i].optional()) {
optional_indices.insert(static_cast<int32_t>(i));
}
}
return optional_indices;
}
absl::flat_hash_set<int32_t> MakeOptionalIndicesSet(
const cel::MapExpr& map_expr) {
absl::flat_hash_set<int32_t> optional_indices;
for (size_t i = 0; i < map_expr.entries().size(); ++i) {
if (map_expr.entries()[i].optional()) {
optional_indices.insert(static_cast<int32_t>(i));
}
}
return optional_indices;
}
class FlatExprVisitor : public cel::AstVisitor {
public:
FlatExprVisitor(
const Resolver& resolver, const cel::RuntimeOptions& options,
std::vector<std::unique_ptr<ProgramOptimizer>> program_optimizers,
const absl::flat_hash_map<int64_t, cel::ast_internal::Reference>&
reference_map,
ValueManager& value_factory, IssueCollector& issue_collector,
ProgramBuilder& program_builder, PlannerContext& extension_context,
bool enable_optional_types)
: resolver_(resolver),
value_factory_(value_factory),
progress_status_(absl::OkStatus()),
resolved_select_expr_(nullptr),
options_(options),
program_optimizers_(std::move(program_optimizers)),
issue_collector_(issue_collector),
program_builder_(program_builder),
extension_context_(extension_context),
enable_optional_types_(enable_optional_types) {}
void PreVisitExpr(const cel::ast_internal::Expr& expr) override {
ValidateOrError(!absl::holds_alternative<cel::UnspecifiedExpr>(expr.kind()),
"Invalid empty expression");
if (!progress_status_.ok()) {
return;
}
if (resume_from_suppressed_branch_ == nullptr &&
suppressed_branches_.find(&expr) != suppressed_branches_.end()) {
resume_from_suppressed_branch_ = &expr;
}
if (block_.has_value()) {
BlockInfo& block = *block_;
if (block.in && block.bindings_set.contains(&expr)) {
block.current_binding = &expr;
}
}
program_builder_.EnterSubexpression(&expr);
for (const std::unique_ptr<ProgramOptimizer>& optimizer :
program_optimizers_) {
absl::Status status = optimizer->OnPreVisit(extension_context_, expr);
if (!status.ok()) {
SetProgressStatusError(status);
}
}
}
void PostVisitExpr(const cel::ast_internal::Expr& expr) override {
if (!progress_status_.ok()) {
return;
}
if (&expr == resume_from_suppressed_branch_) {
resume_from_suppressed_branch_ = nullptr;
}
for (const std::unique_ptr<ProgramOptimizer>& optimizer :
program_optimizers_) {
absl::Status status = optimizer->OnPostVisit(extension_context_, expr);
if (!status.ok()) {
SetProgressStatusError(status);
return;
}
}
auto* subexpression = program_builder_.current();
if (subexpression != nullptr && options_.enable_recursive_tracing &&
subexpression->IsRecursive()) {
auto program = subexpression->ExtractRecursiveProgram();
subexpression->set_recursive_program(
std::make_unique<TraceStep>(std::move(program.step)), program.depth);
}
program_builder_.ExitSubexpression(&expr);
if (!comprehension_stack_.empty() &&
comprehension_stack_.back().is_optimizable_bind &&
(&comprehension_stack_.back().comprehension->accu_init() == &expr)) {
SetProgressStatusError(
MaybeExtractSubexpression(&expr, comprehension_stack_.back()));
}
if (block_.has_value()) {
BlockInfo& block = *block_;
if (block.current_binding == &expr) {
int index = program_builder_.ExtractSubexpression(&expr);
if (index == -1) {
SetProgressStatusError(
absl::InvalidArgumentError("failed to extract subexpression"));
return;
}
block.subexpressions[block.current_index++] = index;
block.current_binding = nullptr;
}
}
}
void PostVisitConst(const cel::ast_internal::Expr& expr,
const cel::ast_internal::Constant& const_expr) override {
if (!progress_status_.ok()) {
return;
}
absl::StatusOr<cel::Value> converted_value =
ConvertConstant(const_expr, value_factory_);
if (!converted_value.ok()) {
SetProgressStatusError(converted_value.status());
return;
}
if (options_.max_recursion_depth > 0 || options_.max_recursion_depth < 0) {
SetRecursiveStep(CreateConstValueDirectStep(
std::move(converted_value).value(), expr.id()),
1);
return;
}
AddStep(
CreateConstValueStep(std::move(converted_value).value(), expr.id()));
}
struct SlotLookupResult {
int slot;
int subexpression;
};
SlotLookupResult LookupSlot(absl::string_view path) {
if (block_.has_value()) {
const BlockInfo& block = *block_;
if (block.in) {
absl::string_view index_suffix = path;
if (absl::ConsumePrefix(&index_suffix, "@index")) {
size_t index;
if (!absl::SimpleAtoi(index_suffix, &index)) {
SetProgressStatusError(
issue_collector_.AddIssue(RuntimeIssue::CreateError(
absl::InvalidArgumentError("bad @index"))));
return {-1, -1};
}
if (index >= block.size) {
SetProgressStatusError(
issue_collector_.AddIssue(RuntimeIssue::CreateError(
absl::InvalidArgumentError(absl::StrCat(
"invalid @index greater than number of bindings: ",
index, " >= ", block.size)))));
return {-1, -1};
}
if (index >= block.current_index) {
SetProgressStatusError(
issue_collector_.AddIssue(RuntimeIssue::CreateError(
absl::InvalidArgumentError(absl::StrCat(
"@index references current or future binding: ", index,
" >= ", block.current_index)))));
return {-1, -1};
}
return {static_cast<int>(block.index + index),
block.subexpressions[index]};
}
}
}
if (!comprehension_stack_.empty()) {
for (int i = comprehension_stack_.size() - 1; i >= 0; i--) {
const ComprehensionStackRecord& record = comprehension_stack_[i];
if (record.iter_var_in_scope &&
record.comprehension->iter_var() == path) {
if (record.is_optimizable_bind) {
SetProgressStatusError(issue_collector_.AddIssue(
RuntimeIssue::CreateWarning(absl::InvalidArgumentError(
"Unexpected iter_var access in trivial comprehension"))));
return {-1, -1};
}
return {static_cast<int>(record.iter_slot), -1};
}
if (record.accu_var_in_scope &&
record.comprehension->accu_var() == path) {
int slot = record.accu_slot;
int subexpression = -1;
if (record.is_optimizable_bind) {
subexpression = record.subexpression;
}
return {slot, subexpression};
}
}
}
if (absl::StartsWith(path, "@it:") || absl::StartsWith(path, "@it2:") ||
absl::StartsWith(path, "@ac:")) {
SetProgressStatusError(
issue_collector_.AddIssue(RuntimeIssue::CreateError(
absl::InvalidArgumentError("out of scope reference to CSE "
"generated comprehension variable"))));
}
return {-1, -1};
}
void PostVisitIdent(const cel::ast_internal::Expr& expr,
const cel::ast_internal::Ident& ident_expr) override {
if (!progress_status_.ok()) {
return;
}
std::string path = ident_expr.name();
if (!ValidateOrError(
!path.empty(),
"Invalid expression: identifier 'name' must not be empty")) {
return;
}
absl::optional<cel::Value> const_value;
int64_t select_root_id = -1;
while (!namespace_stack_.empty()) {
const auto& select_node = namespace_stack_.front();
auto select_expr = select_node.first;
auto qualified_path = absl::StrCat(path, ".", select_node.second);
const_value = resolver_.FindConstant(qualified_path, select_expr->id());
if (const_value) {
resolved_select_expr_ = select_expr;
select_root_id = select_expr->id();
path = qualified_path;
namespace_stack_.clear();
break;
}
namespace_stack_.pop_front();
}
if (!const_value) {
const_value = resolver_.FindConstant(path, expr.id());
select_root_id = expr.id();
}
if (const_value) {
if (options_.max_recursion_depth != 0) {
SetRecursiveStep(CreateDirectShadowableValueStep(
std::move(path), std::move(const_value).value(),
select_root_id),
1);
return;
}
AddStep(CreateShadowableValueStep(
std::move(path), std::move(const_value).value(), select_root_id));
return;
}
SlotLookupResult slot = LookupSlot(path);
if (slot.subexpression >= 0) {
auto* subexpression =
program_builder_.GetExtractedSubexpression(slot.subexpression);
if (subexpression == nullptr) {
SetProgressStatusError(
absl::InternalError("bad subexpression reference"));
return;
}
if (subexpression->IsRecursive()) {
const auto& program = subexpression->recursive_program();
SetRecursiveStep(
CreateDirectLazyInitStep(slot.slot, program.step.get(), expr.id()),
program.depth + 1);
} else {
AddStep(
CreateLazyInitStep(slot.slot, slot.subexpression + 1, expr.id()));
}
return;
} else if (slot.slot >= 0) {
if (options_.max_recursion_depth != 0) {
SetRecursiveStep(
CreateDirectSlotIdentStep(ident_expr.name(), slot.slot, expr.id()),
1);
} else {
AddStep(CreateIdentStepForSlot(ident_expr, slot.slot, expr.id()));
}
return;
}
if (options_.max_recursion_depth != 0) {
SetRecursiveStep(CreateDirectIdentStep(ident_expr.name(), expr.id()), 1);
} else {
AddStep(CreateIdentStep(ident_expr, expr.id()));
}
}
void PreVisitSelect(const cel::ast_internal::Expr& expr,
const cel::ast_internal::Select& select_expr) override {
if (!progress_status_.ok()) {
return;
}
if (!ValidateOrError(
!select_expr.field().empty(),
"Invalid expression: select 'field' must not be empty")) {
return;
}
if (!select_expr.test_only() && (select_expr.operand().has_ident_expr() ||
select_expr.operand().has_select_expr())) {
for (size_t i = 0; i < namespace_stack_.size(); i++) {
auto ns = namespace_stack_[i];
namespace_stack_[i] = {
ns.first, absl::StrCat(select_expr.field(), ".", ns.second)};
}
namespace_stack_.push_back({&expr, select_expr.field()});
} else {
namespace_stack_.clear();
}
}
void PostVisitSelect(const cel::ast_internal::Expr& expr,
const cel::ast_internal::Select& select_expr) override {
if (!progress_status_.ok()) {
return;
}
if (resolved_select_expr_) {
if (&expr == resolved_select_expr_) {
resolved_select_expr_ = nullptr;
}
return;
}
auto depth = RecursionEligible();
if (depth.has_value()) {
auto deps = ExtractRecursiveDependencies();
if (deps.size() != 1) {
SetProgressStatusError(absl::InternalError(
"unexpected number of dependencies for select operation."));
return;
}
StringValue field =
value_factory_.CreateUncheckedStringValue(select_expr.field());
SetRecursiveStep(
CreateDirectSelectStep(std::move(deps[0]), std::move(field),
select_expr.test_only(), expr.id(),
options_.enable_empty_wrapper_null_unboxing,
enable_optional_types_),
*depth + 1);
return;
}
AddStep(CreateSelectStep(select_expr, expr.id(),
options_.enable_empty_wrapper_null_unboxing,
value_factory_, enable_optional_types_));
}
void PreVisitCall(const cel::ast_internal::Expr& expr,
const cel::ast_internal::Call& call_expr) override {
if (!progress_status_.ok()) {
return;
}
std::unique_ptr<CondVisitor> cond_visitor;
if (call_expr.function() == cel::builtin::kAnd) {
cond_visitor = std::make_unique<BinaryCondVisitor>(
this, BinaryCond::kAnd, options_.short_circuiting);
} else if (call_expr.function() == cel::builtin::kOr) {
cond_visitor = std::make_unique<BinaryCondVisitor>(
this, BinaryCond::kOr, options_.short_circuiting);
} else if (call_expr.function() == cel::builtin::kTernary) {
if (options_.short_circuiting) {
cond_visitor = std::make_unique<TernaryCondVisitor>(this);
} else {
cond_visitor = std::make_unique<ExhaustiveTernaryCondVisitor>(this);
}
} else if (enable_optional_types_ &&
call_expr.function() == kOptionalOrFn &&
call_expr.has_target() && call_expr.args().size() == 1) {
cond_visitor = std::make_unique<BinaryCondVisitor>(
this, BinaryCond::kOptionalOr, options_.short_circuiting);
} else if (enable_optional_types_ &&
call_expr.function() == kOptionalOrValueFn &&
call_expr.has_target() && call_expr.args().size() == 1) {
cond_visitor = std::make_unique<BinaryCondVisitor>(
this, BinaryCond::kOptionalOrValue, options_.short_circuiting);
} else if (IsBlock(&call_expr)) {
if (block_.has_value()) {
SetProgressStatusError(
absl::InvalidArgumentError("multiple cel.@block are not allowed"));
return;
}
block_ = BlockInfo();
BlockInfo& block = *block_;
block.in = true;
if (call_expr.args().empty()) {
SetProgressStatusError(absl::InvalidArgumentError(
"malformed cel.@block: missing list of bound expressions"));
return;
}
if (call_expr.args().size() != 2) {
SetProgressStatusError(absl::InvalidArgumentError(
"malformed cel.@block: missing bound expression"));
return;
}
if (!call_expr.args()[0].has_list_expr()) {
SetProgressStatusError(
absl::InvalidArgumentError("malformed cel.@block: first argument "
"is not a list of bound expressions"));
return;
}
const auto& list_expr = call_expr.args().front().list_expr();
block.size = list_expr.elements().size();
if (block.size == 0) {
SetProgressStatusError(absl::InvalidArgumentError(
"malformed cel.@block: list of bound expressions is empty"));
return;
}
block.bindings_set.reserve(block.size);
for (const auto& list_expr_element : list_expr.elements()) {
if (list_expr_element.optional()) {
SetProgressStatusError(
absl::InvalidArgumentError("malformed cel.@block: list of bound "
"expressions contains an optional"));
return;
}
block.bindings_set.insert(&list_expr_element.expr());
}
block.index = index_manager().ReserveSlots(block.size);
block.expr = &expr;
block.bindings = &call_expr.args()[0];
block.bound = &call_expr.args()[1];
block.subexpressions.resize(block.size, -1);
} else {
return;
}
if (cond_visitor) {
cond_visitor->PreVisit(&expr);
cond_visitor_stack_.push({&expr, std::move(cond_visitor)});
}
}
absl::optional<int> RecursionEligible() {
if (program_builder_.current() == nullptr) {
return absl::nullopt;
}
absl::optional<int> depth =
program_builder_.current()->RecursiveDependencyDepth();
if (!depth.has_value()) {
return depth;
}
if (options_.max_recursion_depth < 0 ||
*depth < options_.max_recursion_depth) {
return depth;
}
return absl::nullopt;
}
std::vector<std::unique_ptr<DirectExpressionStep>>
ExtractRecursiveDependencies() {
ABSL_DCHECK(program_builder_.current() != nullptr);
return program_builder_.current()->ExtractRecursiveDependencies();
}
void MaybeMakeTernaryRecursive(const cel::ast_internal::Expr* expr) {
if (options_.max_recursion_depth == 0) {
return;
}
if (expr->call_expr().args().size() != 3) {
SetProgressStatusError(absl::InvalidArgumentError(
"unexpected number of args for builtin ternary"));
}
const cel::ast_internal::Expr* condition_expr =
&expr->call_expr().args()[0];
const cel::ast_internal::Expr* left_expr = &expr->call_expr().args()[1];
const cel::ast_internal::Expr* right_expr = &expr->call_expr().args()[2];
auto* condition_plan = program_builder_.GetSubexpression(condition_expr);
auto* left_plan = program_builder_.GetSubexpression(left_expr);
auto* right_plan = program_builder_.GetSubexpression(right_expr);
int max_depth = 0;
if (condition_plan == nullptr || !condition_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, condition_plan->recursive_program().depth);
if (left_plan == nullptr || !left_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, left_plan->recursive_program().depth);
if (right_plan == nullptr || !right_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, right_plan->recursive_program().depth);
if (options_.max_recursion_depth >= 0 &&
max_depth >= options_.max_recursion_depth) {
return;
}
SetRecursiveStep(
CreateDirectTernaryStep(condition_plan->ExtractRecursiveProgram().step,
left_plan->ExtractRecursiveProgram().step,
right_plan->ExtractRecursiveProgram().step,
expr->id(), options_.short_circuiting),
max_depth + 1);
}
void MaybeMakeShortcircuitRecursive(const cel::ast_internal::Expr* expr,
bool is_or) {
if (options_.max_recursion_depth == 0) {
return;
}
if (expr->call_expr().args().size() != 2) {
SetProgressStatusError(absl::InvalidArgumentError(
"unexpected number of args for builtin boolean operator &&/||"));
}
const cel::ast_internal::Expr* left_expr = &expr->call_expr().args()[0];
const cel::ast_internal::Expr* right_expr = &expr->call_expr().args()[1];
auto* left_plan = program_builder_.GetSubexpression(left_expr);
auto* right_plan = program_builder_.GetSubexpression(right_expr);
int max_depth = 0;
if (left_plan == nullptr || !left_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, left_plan->recursive_program().depth);
if (right_plan == nullptr || !right_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, right_plan->recursive_program().depth);
if (options_.max_recursion_depth >= 0 &&
max_depth >= options_.max_recursion_depth) {
return;
}
if (is_or) {
SetRecursiveStep(
CreateDirectOrStep(left_plan->ExtractRecursiveProgram().step,
right_plan->ExtractRecursiveProgram().step,
expr->id(), options_.short_circuiting),
max_depth + 1);
} else {
SetRecursiveStep(
CreateDirectAndStep(left_plan->ExtractRecursiveProgram().step,
right_plan->ExtractRecursiveProgram().step,
expr->id(), options_.short_circuiting),
max_depth + 1);
}
}
void MaybeMakeOptionalShortcircuitRecursive(
const cel::ast_internal::Expr* expr, bool is_or_value) {
if (options_.max_recursion_depth == 0) {
return;
}
if (!expr->call_expr().has_target() ||
expr->call_expr().args().size() != 1) {
SetProgressStatusError(absl::InvalidArgumentError(
"unexpected number of args for optional.or{Value}"));
}
const cel::ast_internal::Expr* left_expr = &expr->call_expr().target();
const cel::ast_internal::Expr* right_expr = &expr->call_expr().args()[0];
auto* left_plan = program_builder_.GetSubexpression(left_expr);
auto* right_plan = program_builder_.GetSubexpression(right_expr);
int max_depth = 0;
if (left_plan == nullptr || !left_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, left_plan->recursive_program().depth);
if (right_plan == nullptr || !right_plan->IsRecursive()) {
return;
}
max_depth = std::max(max_depth, right_plan->recursive_program().depth);
if (options_.max_recursion_depth >= 0 &&
max_depth >= options_.max_recursion_depth) {
return;
}
SetRecursiveStep(CreateDirectOptionalOrStep(
expr->id(), left_plan->ExtractRecursiveProgram().step,
right_plan->ExtractRecursiveProgram().step,
is_or_value, options_.short_circuiting),
max_depth + 1);
}
void MaybeMakeBindRecursive(
const cel::ast_internal::Expr* expr,
const cel::ast_internal::Comprehension* comprehension, size_t accu_slot) {
if (options_.max_recursion_depth == 0) {
return;
}
auto* result_plan =
program_builder_.GetSubexpression(&comprehension->result());
if (result_plan == nullptr || !result_plan->IsRecursive()) {
return;
}
int result_depth = result_plan->recursive_program().depth;
if (options_.max_recursion_depth > 0 &&
result_depth >= options_.max_recursion_depth) {
return;
}
auto program = result_plan->ExtractRecursiveProgram();
SetRecursiveStep(
CreateDirectBindStep(accu_slot, std::move(program.step), expr->id()),
result_depth + 1);
}
void MaybeMakeComprehensionRecursive(
const cel::ast_internal::Expr* expr,
const cel::ast_internal::Comprehension* comprehension, size_t iter_slot,
size_t accu_slot) {
if (options_.max_recursion_depth == 0) {
return;
}
auto* accu_plan =
program_builder_.GetSubexpression(&comprehension->accu_init());
if (accu_plan == nullptr || !accu_plan->IsRecursive()) {
return;
}
auto* range_plan =
program_builder_.GetSubexpression(&comprehension->iter_range());
if (range_plan == nullptr || !range_plan->IsRecursive()) {
return;
}
auto* loop_plan =
program_builder_.GetSubexpression(&comprehension->loop_step());
if (loop_plan == nullptr || !loop_plan->IsRecursive()) {
return;
}
auto* condition_plan =
program_builder_.GetSubexpression(&comprehension->loop_condition());
if (condition_plan == nullptr || !condition_plan->IsRecursive()) {
return;
}
auto* result_plan =
program_builder_.GetSubexpression(&comprehension->result());
if (result_plan == nullptr || !result_plan->IsRecursive()) {
return;
}
int max_depth = 0;
max_depth = std::max(max_depth, accu_plan->recursive_program().depth);
max_depth = std::max(max_depth, range_plan->recursive_program().depth);
max_depth = std::max(max_depth, loop_plan->recursive_program().depth);
max_depth = std::max(max_depth, condition_plan->recursive_program().depth);
max_depth = std::max(max_depth, result_plan->recursive_program().depth);
if (options_.max_recursion_depth > 0 &&
max_depth >= options_.max_recursion_depth) {
return;
}
auto step = CreateDirectComprehensionStep(
iter_slot, accu_slot, range_plan->ExtractRecursiveProgram().step,
accu_plan->ExtractRecursiveProgram().step,
loop_plan->ExtractRecursiveProgram().step,
condition_plan->ExtractRecursiveProgram().step,
result_plan->ExtractRecursiveProgram().step, options_.short_circuiting,
expr->id());
SetRecursiveStep(std::move(step), max_depth + 1);
}
void PostVisitCall(const cel::ast_internal::Expr& expr,
const cel::ast_internal::Call& call_expr) override {
if (!progress_status_.ok()) {
return;
}
auto cond_visitor = FindCondVisitor(&expr);
if (cond_visitor) {
cond_visitor->PostVisit(&expr);
cond_visitor_stack_.pop();
if (call_expr.function() == cel::builtin::kTernary) {
MaybeMakeTernaryRecursive(&expr);
} else if (call_expr.function() == cel::builtin::kOr) {
MaybeMakeShortcircuitRecursive(&expr, true);
} else if (call_expr.function() == cel::builtin::kAnd) {
MaybeMakeShortcircuitRecursive(&expr, false);
} else if (enable_optional_types_) {
if (call_expr.function() == kOptionalOrFn) {
MaybeMakeOptionalShortcircuitRecursive(&expr,
false);
} else if (call_expr.function() == kOptionalOrValueFn) {
MaybeMakeOptionalShortcircuitRecursive(&expr,
true);
}
}
return;
}
if (call_expr.function() == cel::builtin::kIndex) {
auto depth = RecursionEligible();
if (depth.has_value()) {
auto args = ExtractRecursiveDependencies();
if (args.size() != 2) {
SetProgressStatusError(absl::InvalidArgumentError(
"unexpected number of args for builtin index operator"));
}
SetRecursiveStep(CreateDirectContainerAccessStep(
std::move(args[0]), std::move(args[1]),
enable_optional_types_, expr.id()),
*depth + 1);
return;
}
AddStep(CreateContainerAccessStep(call_expr, expr.id(),
enable_optional_types_));
return;
}
if (block_.has_value()) {
BlockInfo& block = *block_;
if (block.expr == &expr) {
block.in = false;
index_manager().ReleaseSlots(block.size);
AddStep(CreateClearSlotsStep(block.index, block.size, -1));
return;
}
}
absl::string_view function = call_expr.function();
if (!comprehension_stack_.empty() &&
comprehension_stack_.back().is_optimizable_list_append) {
const cel::ast_internal::Comprehension* comprehension =
comprehension_stack_.back().comprehension;
const cel::ast_internal::Expr& loop_step = comprehension->loop_step();
if (&loop_step == &expr) {
function = cel::builtin::kRuntimeListAppend;
}
if (loop_step.has_call_expr() &&
loop_step.call_expr().function() == cel::builtin::kTernary &&
loop_step.call_expr().args().size() == 3 &&
&(loop_step.call_expr().args()[1]) == &expr) {
function = cel::builtin::kRuntimeListAppend;
}
}
AddResolvedFunctionStep(&call_expr, &expr, function);
}
void PreVisitComprehension(
const cel::ast_internal::Expr& expr,
const cel::ast_internal::Comprehension& comprehension) override {
if (!progress_status_.ok()) {
return;
}
if (!ValidateOrError(options_.enable_comprehension,
"Comprehension support is disabled")) {
return;
}
const auto& accu_var = comprehension.accu_var();
const auto& iter_var = comprehension.iter_var();
ValidateOrError(!accu_var.empty(),
"Invalid comprehension: 'accu_var' must not be empty");
ValidateOrError(!iter_var.empty(),
"Invalid comprehension: 'iter_var' must not be empty");
ValidateOrError(
accu_var != iter_var,
"Invalid comprehension: 'accu_var' must not be the same as 'iter_var'");
ValidateOrError(comprehension.has_accu_init(),
"Invalid comprehension: 'accu_init' must be set");
ValidateOrError(comprehension.has_loop_condition(),
"Invalid comprehension: 'loop_condition' must be set");
ValidateOrError(comprehension.has_loop_step(),
"Invalid comprehension: 'loop_step' must be set");
ValidateOrError(comprehension.has_result(),
"Invalid comprehension: 'result' must be set");
size_t iter_slot, accu_slot, slot_count;
bool is_bind = IsBind(&comprehension);
if (is_bind) {
accu_slot = iter_slot = index_manager_.ReserveSlots(1);
slot_count = 1;
} else {
iter_slot = index_manager_.ReserveSlots(2);
accu_slot = iter_slot + 1;
slot_count = 2;
}
for (ComprehensionStackRecord& record : comprehension_stack_) {
if (record.in_accu_init && record.is_optimizable_bind) {
record.slot_count += slot_count;
slot_count = 0;
break;
}
}
comprehension_stack_.push_back(
{&expr, &comprehension, iter_slot, accu_slot, slot_count,
-1,
IsOptimizableListAppend(&comprehension,
options_.enable_comprehension_list_append),
is_bind,
false,
false,
false,
std::make_unique<ComprehensionVisitor>(
this, options_.short_circuiting, is_bind, iter_slot, accu_slot)});
comprehension_stack_.back().visitor->PreVisit(&expr);
}
void PostVisitComprehension(
const cel::ast_internal::Expr& expr,
const cel::ast_internal::Comprehension& comprehension_expr) override {
if (!progress_status_.ok()) {
return;
}
ComprehensionStackRecord& record = comprehension_stack_.back();
if (comprehension_stack_.empty() ||
record.comprehension != &comprehension_expr) {
return;
}
record.visitor->PostVisit(&expr);
index_manager_.ReleaseSlots(record.slot_count);
comprehension_stack_.pop_back();
}
void PreVisitComprehensionSubexpression(
const cel::ast_internal::Expr& expr,
const cel::ast_internal::Comprehension& compr,
cel::ComprehensionArg comprehension_arg) override {
if (!progress_status_.ok()) {
return;
}
if (comprehension_stack_.empty() ||
comprehension_stack_.back().comprehension != &compr) {
return;
}
ComprehensionStackRecord& record = comprehension_stack_.back();
switch (comprehension_arg) {
case cel::ITER_RANGE: {
record.in_accu_init = false;
record.iter_var_in_scope = false;
record.accu_var_in_scope = false;
break;
}
case cel::ACCU_INIT: {
record.in_accu_init = true;
record.iter_var_in_scope = false;
record.accu_var_in_scope = false;
break;
}
case cel::LOOP_CONDITION: {
record.in_accu_init = false;
record.iter_var_in_scope = true;
record.accu_var_in_scope = true;
break;
}
case cel::LOOP_STEP: {
record.in_accu_init = false;
record.iter_var_in_scope = true;
record.accu_var_in_scope = true;
break;
}
case cel::RESULT: {
record.in_accu_init = false;
record.iter_var_in_scope = false;
record.accu_var_in_scope = true;
break;
}
}
}
void PostVisitComprehensionSubexpression(
const cel::ast_internal::Expr& expr,
const cel::ast_internal::Comprehension& compr,
cel::ComprehensionArg comprehension_arg) override {
if (!progress_status_.ok()) {
return;
}
if (comprehension_stack_.empty() ||
comprehension_stack_.back().comprehension != &compr) {
return;
}
SetProgressStatusError(comprehension_stack_.back().visitor->PostVisitArg(
comprehension_arg, comprehension_stack_.back().expr));
}
void PostVisitArg(const cel::ast_internal::Expr& expr, int arg_num) override {
if (!progress_status_.ok()) {
return;
}
auto cond_visitor = FindCondVisitor(&expr);
if (cond_visitor) {
cond_visitor->PostVisitArg(arg_num, &expr);
}
}
void PostVisitTarget(const cel::ast_internal::Expr& expr) override {
if (!progress_status_.ok()) {
return;
}
auto cond_visitor = FindCondVisitor(&expr);
if (cond_visitor) {
cond_visitor->PostVisitTarget(&expr);
}
}
void PostVisitList(const cel::ast_internal::Expr& expr,
const cel::ast_internal::CreateList& list_expr) override {
if (!progress_status_.ok()) {
return;
}
if (block_.has_value()) {
BlockInfo& block = *block_;
if (block.bindings == &expr) {
return;
}
}
if (!comprehension_stack_.empty()) {
const ComprehensionStackRecord& comprehension =
comprehension_stack_.back();
if (comprehension.is_optimizable_list_append &&
&(comprehension.comprehension->accu_init()) == &expr) {
if (options_.max_recursion_depth != 0) {
SetRecursiveStep(CreateDirectMutableListStep(expr.id()), 1);
return;
}
AddStep(CreateMutableListStep(expr.id()));
return;
}
}
absl::optional<int> depth = RecursionEligible();
if (depth.has_value()) {
auto deps = ExtractRecursiveDependencies();
if (deps.size() != list_expr.elements().size()) {
SetProgressStatusError(absl::InternalError(
"Unexpected number of plan elements for CreateList expr"));
return;
}
auto step = CreateDirectListStep(
std::move(deps), MakeOptionalIndicesSet(list_expr), expr.id());
SetRecursiveStep(std::move(step), *depth + 1);
return;
}
AddStep(CreateCreateListStep(list_expr, expr.id()));
}
void PostVisitStruct(
const cel::ast_internal::Expr& expr,
const cel::ast_internal::CreateStruct& struct_expr) override {
if (!progress_status_.ok()) {
return;
}
auto status_or_resolved_fields =
ResolveCreateStructFields(struct_expr, expr.id());
if (!status_or_resolved_fields.ok()) {
SetProgressStatusError(status_or_resolved_fields.status());
return;
}
std::string resolved_name =
std::move(status_or_resolved_fields.value().first);
std::vector<std::string> fields =
std::move(status_or_resolved_fields.value().second);
auto depth = RecursionEligible();
if (depth.has_value()) {
auto deps = ExtractRecursiveDependencies();
if (deps.size() != struct_expr.fields().size()) {
SetProgressStatusError(absl::InternalError(
"Unexpected number of plan elements for CreateStruct expr"));
return;
}
auto step = CreateDirectCreateStructStep(
std::move(resolved_name), std::move(fields), std::move(deps),
MakeOptionalIndicesSet(struct_expr), expr.id());
SetRecursiveStep(std::move(step), *depth + 1);
return;
}
AddStep(CreateCreateStructStep(std::move(resolved_name), std::move(fields),
MakeOptionalIndicesSet(struct_expr),
expr.id()));
}
void PostVisitMap(const cel::ast_internal::Expr& expr,
const cel::MapExpr& map_expr) override {
for (const auto& entry : map_expr.entries()) {
ValidateOrError(entry.has_key(), "Map entry missing key");
ValidateOrError(entry.has_value(), "Map entry missing value");
}
auto depth = RecursionEligible();
if (depth.has_value()) {
auto deps = ExtractRecursiveDependencies();
if (deps.size() != 2 * map_expr.entries().size()) {
SetProgressStatusError(absl::InternalError(
"Unexpected number of plan elements for CreateStruct expr"));
return;
}
auto step = CreateDirectCreateMapStep(
std::move(deps), MakeOptionalIndicesSet(map_expr), expr.id());
SetRecursiveStep(std::move(step), *depth + 1);
return;
}
AddStep(CreateCreateStructStepForMap(map_expr.entries().size(),
MakeOptionalIndicesSet(map_expr),
expr.id()));
}
absl::Status progress_status() const { return progress_status_; }
cel::ValueManager& value_factory() { return value_factory_; }
void SuppressBranch(const cel::ast_internal::Expr* expr) {
suppressed_branches_.insert(expr);
}
void AddResolvedFunctionStep(const cel::ast_internal::Call* call_expr,
const cel::ast_internal::Expr* expr,
absl::string_view function) {
bool receiver_style = call_expr->has_target();
size_t num_args = call_expr->args().size() + (receiver_style ? 1 : 0);
auto arguments_matcher = ArgumentsMatcher(num_args);
auto lazy_overloads = resolver_.FindLazyOverloads(
function, call_expr->has_target(), arguments_matcher, expr->id());
if (!lazy_overloads.empty()) {
auto depth = RecursionEligible();
if (depth.has_value()) {
auto args = program_builder_.current()->ExtractRecursiveDependencies();
SetRecursiveStep(CreateDirectLazyFunctionStep(
expr->id(), *call_expr, std::move(args),
std::move(lazy_overloads)),
*depth + 1);
return;
}
AddStep(CreateFunctionStep(*call_expr, expr->id(),
std::move(lazy_overloads)));
return;
}
auto overloads = resolver_.FindOverloads(function, receiver_style,
arguments_matcher, expr->id());
if (overloads.empty()) {
auto status = issue_collector_.AddIssue(RuntimeIssue::CreateWarning(
absl::InvalidArgumentError(
"No overloads provided for FunctionStep creation"),
RuntimeIssue::ErrorCode::kNoMatchingOverload));
if (!status.ok()) {
SetProgressStatusError(status);
return;
}
}
auto recursion_depth = RecursionEligible();
if (recursion_depth.has_value()) {
ABSL_DCHECK(program_builder_.current() != nullptr);
auto args = program_builder_.current()->ExtractRecursiveDependencies();
SetRecursiveStep(
CreateDirectFunctionStep(expr->id(), *call_expr, std::move(args),
std::move(overloads)),
*recursion_depth + 1);
return;
}
AddStep(CreateFunctionStep(*call_expr, expr->id(), std::move(overloads)));
}
void AddStep(absl::StatusOr<std::unique_ptr<ExpressionStep>> step) {
if (step.ok()) {
AddStep(*std::move(step));
} else {
SetProgressStatusError(step.status());
}
}
void AddStep(std::unique_ptr<ExpressionStep> step) {
if (progress_status_.ok() && !PlanningSuppressed()) {
program_builder_.AddStep(std::move(step));
}
}
void SetRecursiveStep(std::unique_ptr<DirectExpressionStep> step, int depth) {
if (!progress_status_.ok() || PlanningSuppressed()) {
return;
}
if (program_builder_.current() == nullptr) {
SetProgressStatusError(absl::InternalError(
"CEL AST traversal out of order in flat_expr_builder."));
return;
}
program_builder_.current()->set_recursive_program(std::move(step), depth);
}
void SetProgressStatusError(const absl::Status& status) {
if (progress_status_.ok() && !status.ok()) {
progress_status_ = status;
}
}
ProgramStepIndex GetCurrentIndex() const {
ABSL_DCHECK(program_builder_.current() != nullptr);
return {static_cast<int>(program_builder_.current()->elements().size()),
program_builder_.current()};
}
CondVisitor* FindCondVisitor(const cel::ast_internal::Expr* expr) const {
if (cond_visitor_stack_.empty()) {
return nullptr;
}
const auto& latest = cond_visitor_stack_.top();
return (latest.first == expr) ? latest.second.get() : nullptr;
}
IndexManager& index_manager() { return index_manager_; }
size_t slot_count() const { return index_manager_.max_slot_count(); }
void AddOptimizer(std::unique_ptr<ProgramOptimizer> optimizer) {
program_optimizers_.push_back(std::move(optimizer));
}
template <typename... MP>
bool ValidateOrError(bool valid_expression, absl::string_view error_message,
MP... message_parts) {
if (valid_expression) {
return true;
}
SetProgressStatusError(absl::InvalidArgumentError(
absl::StrCat(error_message, message_parts...)));
return false;
}
private:
struct ComprehensionStackRecord {
const cel::ast_internal::Expr* expr;
const cel::ast_internal::Comprehension* comprehension;
size_t iter_slot;
size_t accu_slot;
size_t slot_count;
int subexpression;
bool is_optimizable_list_append;
bool is_optimizable_bind;
bool iter_var_in_scope;
bool accu_var_in_scope;
bool in_accu_init;
std::unique_ptr<ComprehensionVisitor> visitor;
};
struct BlockInfo {
bool in = false;
const cel::ast_internal::Expr* expr = nullptr;
const cel::ast_internal::Expr* bindings = nullptr;
absl::flat_hash_set<const cel::ast_internal::Expr*> bindings_set;
const cel::ast_internal::Expr* bound = nullptr;
size_t size = 0;
size_t index = 0;
size_t current_index = 0;
const cel::ast_internal::Expr* current_binding = nullptr;
std::vector<int> subexpressions;
};
bool PlanningSuppressed() const {
return resume_from_suppressed_branch_ != nullptr;
}
absl::Status MaybeExtractSubexpression(const cel::ast_internal::Expr* expr,
ComprehensionStackRecord& record) {
if (!record.is_optimizable_bind) {
return absl::OkStatus();
}
int index = program_builder_.ExtractSubexpression(expr);
if (index == -1) {
return absl::InternalError("Failed to extract subexpression");
}
record.subexpression = index;
record.visitor->MarkAccuInitExtracted();
return absl::OkStatus();
}
absl::StatusOr<std::pair<std::string, std::vector<std::string>>>
ResolveCreateStructFields(
const cel::ast_internal::CreateStruct& create_struct_expr,
int64_t expr_id) {
absl::string_view ast_name = create_struct_expr.name();
absl::optional<std::pair<std::string, cel::Type>> type;
CEL_ASSIGN_OR_RETURN(type, resolver_.FindType(ast_name, expr_id));
if (!type.has_value()) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid struct creation: missing type info for '", ast_name, "'"));
}
std::string resolved_name = std::move(type).value().first;
std::vector<std::string> fields;
fields.reserve(create_struct_expr.fields().size());
for (const auto& entry : create_struct_expr.fields()) {
if (entry.name().empty()) {
return absl::InvalidArgumentError("Struct field missing name");
}
if (!entry.has_value()) {
return absl::InvalidArgumentError("Struct field missing value");
}
CEL_ASSIGN_OR_RETURN(
auto field, value_factory().FindStructTypeFieldByName(resolved_name,
entry.name()));
if (!field.has_value()) {
return absl::InvalidArgumentError(
absl::StrCat("Invalid message creation: field '", entry.name(),
"' not found in '", resolved_name, "'"));
}
fields.push_back(entry.name());
}
return std::make_pair(std::move(resolved_name), std::move(fields));
}
const Resolver& resolver_;
ValueManager& value_factory_;
absl::Status progress_status_;
std::stack<
std::pair<const cel::ast_internal::Expr*, std::unique_ptr<CondVisitor>>>
cond_visitor_stack_;
std::deque<std::pair<const cel::ast_internal::Expr*, std::string>>
namespace_stack_;
const cel::ast_internal::Expr* resolved_select_expr_;
const cel::RuntimeOptions& options_;
std::vector<ComprehensionStackRecord> comprehension_stack_;
absl::flat_hash_set<const cel::ast_internal::Expr*> suppressed_branches_;
const cel::ast_internal::Expr* resume_from_suppressed_branch_ = nullptr;
std::vector<std::unique_ptr<ProgramOptimizer>> program_optimizers_;
IssueCollector& issue_collector_;
ProgramBuilder& program_builder_;
PlannerContext extension_context_;
IndexManager index_manager_;
bool enable_optional_types_;
absl::optional<BlockInfo> block_;
};
void BinaryCondVisitor::PreVisit(const cel::ast_internal::Expr* expr) {
switch (cond_) {
case BinaryCond::kAnd:
ABSL_FALLTHROUGH_INTENDED;
case BinaryCond::kOr:
visitor_->ValidateOrError(
!expr->call_expr().has_target() &&
expr->call_expr().args().size() == 2,
"Invalid argument count for a binary function call.");
break;
case BinaryCond::kOptionalOr:
ABSL_FALLTHROUGH_INTENDED;
case BinaryCond::kOptionalOrValue:
visitor_->ValidateOrError(expr->call_expr().has_target() &&
expr->call_expr().args().size() == 1,
"Invalid argument count for or/orValue call.");
break;
}
}
void BinaryCondVisitor::PostVisitArg(int arg_num,
const cel::ast_internal::Expr* expr) {
if (short_circuiting_ && arg_num == 0 &&
(cond_ == BinaryCond::kAnd || cond_ == BinaryCond::kOr)) {
absl::StatusOr<std::unique_ptr<JumpStepBase>> jump_step;
switch (cond_) {
case BinaryCond::kAnd:
jump_step = CreateCondJumpStep(false, true, {}, expr->id());
break;
case BinaryCond::kOr:
jump_step = CreateCondJumpStep(true, true, {}, expr->id());
break;
default:
ABSL_UNREACHABLE();
}
if (jump_step.ok()) {
jump_step_ = Jump(visitor_->GetCurrentIndex(), jump_step->get());
}
visitor_->AddStep(std::move(jump_step));
}
}
void BinaryCondVisitor::PostVisitTarget(const cel::ast_internal::Expr* expr) {
if (short_circuiting_ && (cond_ == BinaryCond::kOptionalOr ||
cond_ == BinaryCond::kOptionalOrValue)) {
absl::StatusOr<std::unique_ptr<JumpStepBase>> jump_step;
switch (cond_) {
case BinaryCond::kOptionalOr:
jump_step = CreateOptionalHasValueJumpStep(false, expr->id());
break;
case BinaryCond::kOptionalOrValue:
jump_step = CreateOptionalHasValueJumpStep(true, expr->id());
break;
default:
ABSL_UNREACHABLE();
}
if (jump_step.ok()) {
jump_step_ = Jump(visitor_->GetCurrentIndex(), jump_step->get());
}
visitor_->AddStep(std::move(jump_step));
}
}
void BinaryCondVisitor::PostVisit(const cel::ast_internal::Expr* expr) {
switch (cond_) {
case BinaryCond::kAnd:
visitor_->AddStep(CreateAndStep(expr->id()));
break;
case BinaryCond::kOr:
visitor_->AddStep(CreateOrStep(expr->id()));
break;
case BinaryCond::kOptionalOr:
visitor_->AddStep(
CreateOptionalOrStep(false, expr->id()));
break;
case BinaryCond::kOptionalOrValue:
visitor_->AddStep(CreateOptionalOrStep(true, expr->id()));
break;
default:
ABSL_UNREACHABLE();
}
if (short_circuiting_) {
visitor_->SetProgressStatusError(
jump_step_.set_target(visitor_->GetCurrentIndex()));
}
}
void TernaryCondVisitor::PreVisit(const cel::ast_internal::Expr* expr) {
visitor_->ValidateOrError(
!expr->call_expr().has_target() && expr->call_expr().args().size() == 3,
"Invalid argument count for a ternary function call.");
}
void TernaryCondVisitor::PostVisitArg(int arg_num,
const cel::ast_internal::Expr* expr) {
if (arg_num == 0) {
auto error_jump = CreateBoolCheckJumpStep({}, expr->id());
if (error_jump.ok()) {
error_jump_ = Jump(visitor_->GetCurrentIndex(), error_jump->get());
}
visitor_->AddStep(std::move(error_jump));
auto jump_to_second = CreateCondJumpStep(false, false, {}, expr->id());
if (jump_to_second.ok()) {
jump_to_second_ =
Jump(visitor_->GetCurrentIndex(), jump_to_second->get());
}
visitor_->AddStep(std::move(jump_to_second));
} else if (arg_num == 1) {
auto jump_after_first = CreateJumpStep({}, expr->id());
if (!jump_after_first.ok()) {
visitor_->SetProgressStatusError(jump_after_first.status());
}
jump_after_first_ =
Jump(visitor_->GetCurrentIndex(), jump_after_first->get());
visitor_->AddStep(std::move(jump_after_first));
if (visitor_->ValidateOrError(
jump_to_second_.exists(),
"Error configuring ternary operator: jump_to_second_ is null")) {
visitor_->SetProgressStatusError(
jump_to_second_.set_target(visitor_->GetCurrentIndex()));
}
}
}
void TernaryCondVisitor::PostVisit(const cel::ast_internal::Expr*) {
if (visitor_->ValidateOrError(
error_jump_.exists(),
"Error configuring ternary operator: error_jump_ is null")) {
visitor_->SetProgressStatusError(
error_jump_.set_target(visitor_->GetCurrentIndex()));
}
if (visitor_->ValidateOrError(
jump_after_first_.exists(),
"Error configuring ternary operator: jump_after_first_ is null")) {
visitor_->SetProgressStatusError(
jump_after_first_.set_target(visitor_->GetCurrentIndex()));
}
}
void ExhaustiveTernaryCondVisitor::PreVisit(
const cel::ast_internal::Expr* expr) {
visitor_->ValidateOrError(
!expr->call_expr().has_target() && expr->call_expr().args().size() == 3,
"Invalid argument count for a ternary function call.");
}
void ExhaustiveTernaryCondVisitor::PostVisit(
const cel::ast_internal::Expr* expr) {
visitor_->AddStep(CreateTernaryStep(expr->id()));
}
void ComprehensionVisitor::PreVisit(const cel::ast_internal::Expr* expr) {
if (is_trivial_) {
visitor_->SuppressBranch(&expr->comprehension_expr().iter_range());
visitor_->SuppressBranch(&expr->comprehension_expr().loop_condition());
visitor_->SuppressBranch(&expr->comprehension_expr().loop_step());
}
}
absl::Status ComprehensionVisitor::PostVisitArgDefault(
cel::ComprehensionArg arg_num, const cel::ast_internal::Expr* expr) {
switch (arg_num) {
case cel::ITER_RANGE: {
visitor_->AddStep(CreateComprehensionInitStep(expr->id()));
break;
}
case cel::ACCU_INIT: {
next_step_pos_ = visitor_->GetCurrentIndex();
next_step_ =
new ComprehensionNextStep(iter_slot_, accu_slot_, expr->id());
visitor_->AddStep(std::unique_ptr<ExpressionStep>(next_step_));
break;
}
case cel::LOOP_CONDITION: {
cond_step_pos_ = visitor_->GetCurrentIndex();
cond_step_ = new ComprehensionCondStep(iter_slot_, accu_slot_,
short_circuiting_, expr->id());
visitor_->AddStep(std::unique_ptr<ExpressionStep>(cond_step_));
break;
}
case cel::LOOP_STEP: {
auto jump_to_next = CreateJumpStep({}, expr->id());
Jump jump_helper(visitor_->GetCurrentIndex(), jump_to_next->get());
visitor_->AddStep(std::move(jump_to_next));
visitor_->SetProgressStatusError(jump_helper.set_target(next_step_pos_));
CEL_ASSIGN_OR_RETURN(
int jump_from_cond,
Jump::CalculateOffset(cond_step_pos_, visitor_->GetCurrentIndex()));
cond_step_->set_jump_offset(jump_from_cond);
CEL_ASSIGN_OR_RETURN(
int jump_from_next,
Jump::CalculateOffset(next_step_pos_, visitor_->GetCurrentIndex()));
next_step_->set_jump_offset(jump_from_next);
break;
}
case cel::RESULT: {
visitor_->AddStep(CreateComprehensionFinishStep(accu_slot_, expr->id()));
CEL_ASSIGN_OR_RETURN(
int jump_from_next,
Jump::CalculateOffset(next_step_pos_, visitor_->GetCurrentIndex()));
next_step_->set_error_jump_offset(jump_from_next);
CEL_ASSIGN_OR_RETURN(
int jump_from_cond,
Jump::CalculateOffset(cond_step_pos_, visitor_->GetCurrentIndex()));
cond_step_->set_error_jump_offset(jump_from_cond);
break;
}
}
return absl::OkStatus();
}
void ComprehensionVisitor::PostVisitArgTrivial(
cel::ComprehensionArg arg_num, const cel::ast_internal::Expr* expr) {
switch (arg_num) {
case cel::ITER_RANGE: {
break;
}
case cel::ACCU_INIT: {
if (!accu_init_extracted_) {
visitor_->AddStep(CreateAssignSlotAndPopStep(accu_slot_));
}
break;
}
case cel::LOOP_CONDITION: {
break;
}
case cel::LOOP_STEP: {
break;
}
case cel::RESULT: {
visitor_->AddStep(CreateClearSlotStep(accu_slot_, expr->id()));
break;
}
}
}
void ComprehensionVisitor::PostVisit(const cel::ast_internal::Expr* expr) {
if (is_trivial_) {
visitor_->MaybeMakeBindRecursive(expr, &expr->comprehension_expr(),
accu_slot_);
return;
}
visitor_->MaybeMakeComprehensionRecursive(expr, &expr->comprehension_expr(),
iter_slot_, accu_slot_);
}
std::vector<ExecutionPathView> FlattenExpressionTable(
ProgramBuilder& program_builder, ExecutionPath& main) {
std::vector<std::pair<size_t, size_t>> ranges;
main = program_builder.FlattenMain();
ranges.push_back(std::make_pair(0, main.size()));
std::vector<ExecutionPath> subexpressions =
program_builder.FlattenSubexpressions();
for (auto& subexpression : subexpressions) {
ranges.push_back(std::make_pair(main.size(), subexpression.size()));
absl::c_move(subexpression, std::back_inserter(main));
}
std::vector<ExecutionPathView> subexpression_indexes;
subexpression_indexes.reserve(ranges.size());
for (const auto& range : ranges) {
subexpression_indexes.push_back(
absl::MakeSpan(main).subspan(range.first, range.second));
}
return subexpression_indexes;
}
}
absl::StatusOr<FlatExpression> FlatExprBuilder::CreateExpressionImpl(
std::unique_ptr<Ast> ast, std::vector<RuntimeIssue>* issues) const {
cel::common_internal::LegacyValueManager value_factory(
cel::MemoryManagerRef::ReferenceCounting(),
type_registry_.GetComposedTypeProvider());
RuntimeIssue::Severity max_severity = options_.fail_on_warnings
? RuntimeIssue::Severity::kWarning
: RuntimeIssue::Severity::kError;
IssueCollector issue_collector(max_severity);
Resolver resolver(container_, function_registry_, type_registry_,
value_factory, type_registry_.resolveable_enums(),
options_.enable_qualified_type_identifiers);
ProgramBuilder program_builder;
PlannerContext extension_context(resolver, options_, value_factory,
issue_collector, program_builder);
auto& ast_impl = AstImpl::CastFromPublicAst(*ast);
if (absl::StartsWith(container_, ".") || absl::EndsWith(container_, ".")) {
return absl::InvalidArgumentError(
absl::StrCat("Invalid expression container: '", container_, "'"));
}
for (const std::unique_ptr<AstTransform>& transform : ast_transforms_) {
CEL_RETURN_IF_ERROR(transform->UpdateAst(extension_context, ast_impl));
}
std::vector<std::unique_ptr<ProgramOptimizer>> optimizers;
for (const ProgramOptimizerFactory& optimizer_factory : program_optimizers_) {
CEL_ASSIGN_OR_RETURN(auto optimizer,
optimizer_factory(extension_context, ast_impl));
if (optimizer != nullptr) {
optimizers.push_back(std::move(optimizer));
}
}
FlatExprVisitor visitor(resolver, options_, std::move(optimizers),
ast_impl.reference_map(), value_factory,
issue_collector, program_builder, extension_context,
enable_optional_types_);
cel::TraversalOptions opts;
opts.use_comprehension_callbacks = true;
AstTraverse(ast_impl.root_expr(), visitor, opts);
if (!visitor.progress_status().ok()) {
return visitor.progress_status();
}
if (issues != nullptr) {
(*issues) = issue_collector.ExtractIssues();
}
ExecutionPath execution_path;
std::vector<ExecutionPathView> subexpressions =
FlattenExpressionTable(program_builder, execution_path);
return FlatExpression(std::move(execution_path), std::move(subexpressions),
visitor.slot_count(),
type_registry_.GetComposedTypeProvider(), options_);
}
} | #include "eval/compiler/flat_expr_builder.h"
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/checked.pb.h"
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/field_mask.pb.h"
#include "google/protobuf/descriptor.pb.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "base/function.h"
#include "base/function_descriptor.h"
#include "eval/compiler/cel_expression_builder_flat_impl.h"
#include "eval/compiler/constant_folding.h"
#include "eval/compiler/qualified_reference_resolver.h"
#include "eval/public/activation.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_builtins.h"
#include "eval/public/cel_expr_builder_factory.h"
#include "eval/public/cel_expression.h"
#include "eval/public/cel_function_adapter.h"
#include "eval/public/cel_function_registry.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/portable_cel_function_adapter.h"
#include "eval/public/structs/cel_proto_descriptor_pool_builder.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include "eval/public/testing/matchers.h"
#include "eval/public/unknown_attribute_set.h"
#include "eval/public/unknown_set.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/proto_file_util.h"
#include "internal/proto_matchers.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "parser/parser.h"
#include "runtime/runtime_options.h"
#include "proto/test/v1/proto3/test_all_types.pb.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::cel::Value;
using ::cel::extensions::ProtoMemoryManagerRef;
using ::cel::internal::test::EqualsProto;
using ::cel::internal::test::ReadBinaryProtoFromFile;
using ::google::api::expr::v1alpha1::CheckedExpr;
using ::google::api::expr::v1alpha1::Expr;
using ::google::api::expr::v1alpha1::ParsedExpr;
using ::google::api::expr::v1alpha1::SourceInfo;
using ::google::api::expr::test::v1::proto3::TestAllTypes;
using ::testing::_;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::SizeIs;
using ::testing::Truly;
inline constexpr absl::string_view kSimpleTestMessageDescriptorSetFile =
"eval/testutil/"
"simple_test_message_proto-descriptor-set.proto.bin";
class ConcatFunction : public CelFunction {
public:
explicit ConcatFunction() : CelFunction(CreateDescriptor()) {}
static CelFunctionDescriptor CreateDescriptor() {
return CelFunctionDescriptor{
"concat", false, {CelValue::Type::kString, CelValue::Type::kString}};
}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (args.size() != 2) {
return absl::InvalidArgumentError("Bad arguments number");
}
std::string concat = std::string(args[0].StringOrDie().value()) +
std::string(args[1].StringOrDie().value());
auto* concatenated =
google::protobuf::Arena::Create<std::string>(arena, std::move(concat));
*result = CelValue::CreateString(concatenated);
return absl::OkStatus();
}
};
class RecorderFunction : public CelFunction {
public:
explicit RecorderFunction(const std::string& name, int* count)
: CelFunction(CelFunctionDescriptor{name, false, {}}), count_(count) {}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
if (!args.empty()) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Bad arguments number");
}
(*count_)++;
*result = CelValue::CreateBool(true);
return absl::OkStatus();
}
int* count_;
};
TEST(FlatExprBuilderTest, SimpleEndToEnd) {
Expr expr;
SourceInfo source_info;
auto call_expr = expr.mutable_call_expr();
call_expr->set_function("concat");
auto arg1 = call_expr->add_args();
arg1->mutable_const_expr()->set_string_value("prefix");
auto arg2 = call_expr->add_args();
arg2->mutable_ident_expr()->set_name("value");
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(
builder.GetRegistry()->Register(std::make_unique<ConcatFunction>()));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
std::string variable = "test";
Activation activation;
activation.InsertValue("value", CelValue::CreateString(&variable));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsString());
EXPECT_THAT(result.StringOrDie().value(), Eq("prefixtest"));
}
TEST(FlatExprBuilderTest, ExprUnset) {
Expr expr;
SourceInfo source_info;
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid empty expression")));
}
TEST(FlatExprBuilderTest, ConstValueUnset) {
Expr expr;
SourceInfo source_info;
CelExpressionBuilderFlatImpl builder;
expr.mutable_const_expr();
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("unspecified constant")));
}
TEST(FlatExprBuilderTest, MapKeyValueUnset) {
Expr expr;
SourceInfo source_info;
CelExpressionBuilderFlatImpl builder;
auto* entry = expr.mutable_struct_expr()->add_entries();
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Map entry missing key")));
entry->mutable_map_key()->mutable_const_expr()->set_bool_value(true);
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Map entry missing value")));
}
TEST(FlatExprBuilderTest, MessageFieldValueUnset) {
Expr expr;
SourceInfo source_info;
CelExpressionBuilderFlatImpl builder;
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
auto* create_message = expr.mutable_struct_expr();
create_message->set_message_name("google.protobuf.Value");
auto* entry = create_message->add_entries();
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Struct field missing name")));
entry->set_field_key("bool_value");
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Struct field missing value")));
}
TEST(FlatExprBuilderTest, BinaryCallTooManyArguments) {
Expr expr;
SourceInfo source_info;
CelExpressionBuilderFlatImpl builder;
auto* call = expr.mutable_call_expr();
call->set_function(builtin::kAnd);
call->mutable_target()->mutable_const_expr()->set_string_value("random");
call->add_args()->mutable_const_expr()->set_bool_value(false);
call->add_args()->mutable_const_expr()->set_bool_value(true);
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid argument count")));
}
TEST(FlatExprBuilderTest, TernaryCallTooManyArguments) {
Expr expr;
SourceInfo source_info;
auto* call = expr.mutable_call_expr();
call->set_function(builtin::kTernary);
call->mutable_target()->mutable_const_expr()->set_string_value("random");
call->add_args()->mutable_const_expr()->set_bool_value(false);
call->add_args()->mutable_const_expr()->set_int64_value(1);
call->add_args()->mutable_const_expr()->set_int64_value(2);
{
cel::RuntimeOptions options;
options.short_circuiting = true;
CelExpressionBuilderFlatImpl builder(options);
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid argument count")));
}
{
cel::RuntimeOptions options;
options.short_circuiting = false;
CelExpressionBuilderFlatImpl builder(options);
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid argument count")));
}
}
TEST(FlatExprBuilderTest, DelayedFunctionResolutionErrors) {
Expr expr;
SourceInfo source_info;
auto call_expr = expr.mutable_call_expr();
call_expr->set_function("concat");
auto arg1 = call_expr->add_args();
arg1->mutable_const_expr()->set_string_value("prefix");
auto arg2 = call_expr->add_args();
arg2->mutable_ident_expr()->set_name("value");
cel::RuntimeOptions options;
options.fail_on_warnings = false;
CelExpressionBuilderFlatImpl builder(options);
std::vector<absl::Status> warnings;
ASSERT_OK_AND_ASSIGN(
auto cel_expr, builder.CreateExpression(&expr, &source_info, &warnings));
std::string variable = "test";
Activation activation;
activation.InsertValue("value", CelValue::CreateString(&variable));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(result.ErrorOrDie()->message(),
Eq("No matching overloads found : concat(string, string)"));
ASSERT_THAT(warnings, testing::SizeIs(1));
EXPECT_EQ(warnings[0].code(), absl::StatusCode::kInvalidArgument);
EXPECT_THAT(std::string(warnings[0].message()),
testing::HasSubstr("No overloads provided"));
}
TEST(FlatExprBuilderTest, Shortcircuiting) {
Expr expr;
SourceInfo source_info;
auto call_expr = expr.mutable_call_expr();
call_expr->set_function("_||_");
auto arg1 = call_expr->add_args();
arg1->mutable_call_expr()->set_function("recorder1");
auto arg2 = call_expr->add_args();
arg2->mutable_call_expr()->set_function("recorder2");
Activation activation;
google::protobuf::Arena arena;
{
cel::RuntimeOptions options;
options.short_circuiting = true;
CelExpressionBuilderFlatImpl builder(options);
auto builtin = RegisterBuiltinFunctions(builder.GetRegistry());
int count1 = 0;
int count2 = 0;
ASSERT_OK(builder.GetRegistry()->Register(
std::make_unique<RecorderFunction>("recorder1", &count1)));
ASSERT_OK(builder.GetRegistry()->Register(
std::make_unique<RecorderFunction>("recorder2", &count2)));
ASSERT_OK_AND_ASSIGN(auto cel_expr_on,
builder.CreateExpression(&expr, &source_info));
ASSERT_OK(cel_expr_on->Evaluate(activation, &arena));
EXPECT_THAT(count1, Eq(1));
EXPECT_THAT(count2, Eq(0));
}
{
cel::RuntimeOptions options;
options.short_circuiting = false;
CelExpressionBuilderFlatImpl builder(options);
auto builtin = RegisterBuiltinFunctions(builder.GetRegistry());
int count1 = 0;
int count2 = 0;
ASSERT_OK(builder.GetRegistry()->Register(
std::make_unique<RecorderFunction>("recorder1", &count1)));
ASSERT_OK(builder.GetRegistry()->Register(
std::make_unique<RecorderFunction>("recorder2", &count2)));
ASSERT_OK_AND_ASSIGN(auto cel_expr_off,
builder.CreateExpression(&expr, &source_info));
ASSERT_OK(cel_expr_off->Evaluate(activation, &arena));
EXPECT_THAT(count1, Eq(1));
EXPECT_THAT(count2, Eq(1));
}
}
TEST(FlatExprBuilderTest, ShortcircuitingComprehension) {
Expr expr;
SourceInfo source_info;
auto comprehension_expr = expr.mutable_comprehension_expr();
comprehension_expr->set_iter_var("x");
auto list_expr =
comprehension_expr->mutable_iter_range()->mutable_list_expr();
list_expr->add_elements()->mutable_const_expr()->set_int64_value(1);
list_expr->add_elements()->mutable_const_expr()->set_int64_value(2);
list_expr->add_elements()->mutable_const_expr()->set_int64_value(3);
comprehension_expr->set_accu_var("accu");
comprehension_expr->mutable_accu_init()->mutable_const_expr()->set_bool_value(
false);
comprehension_expr->mutable_loop_condition()
->mutable_const_expr()
->set_bool_value(false);
comprehension_expr->mutable_loop_step()->mutable_call_expr()->set_function(
"recorder_function1");
comprehension_expr->mutable_result()->mutable_const_expr()->set_bool_value(
false);
Activation activation;
google::protobuf::Arena arena;
{
cel::RuntimeOptions options;
options.short_circuiting = true;
CelExpressionBuilderFlatImpl builder(options);
auto builtin = RegisterBuiltinFunctions(builder.GetRegistry());
int count = 0;
ASSERT_OK(builder.GetRegistry()->Register(
std::make_unique<RecorderFunction>("recorder_function1", &count)));
ASSERT_OK_AND_ASSIGN(auto cel_expr_on,
builder.CreateExpression(&expr, &source_info));
ASSERT_OK(cel_expr_on->Evaluate(activation, &arena));
EXPECT_THAT(count, Eq(0));
}
{
cel::RuntimeOptions options;
options.short_circuiting = false;
CelExpressionBuilderFlatImpl builder(options);
auto builtin = RegisterBuiltinFunctions(builder.GetRegistry());
int count = 0;
ASSERT_OK(builder.GetRegistry()->Register(
std::make_unique<RecorderFunction>("recorder_function1", &count)));
ASSERT_OK_AND_ASSIGN(auto cel_expr_off,
builder.CreateExpression(&expr, &source_info));
ASSERT_OK(cel_expr_off->Evaluate(activation, &arena));
EXPECT_THAT(count, Eq(3));
}
}
TEST(FlatExprBuilderTest, IdentExprUnsetName) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(ident_expr {})", &expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'name' must not be empty")));
}
TEST(FlatExprBuilderTest, SelectExprUnsetField) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(select_expr{
operand{ ident_expr {name: 'var'} }
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'field' must not be empty")));
}
TEST(FlatExprBuilderTest, ComprehensionExprUnsetAccuVar) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(comprehension_expr{})", &expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'accu_var' must not be empty")));
}
TEST(FlatExprBuilderTest, ComprehensionExprUnsetIterVar) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr{accu_var: "a"}
)",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'iter_var' must not be empty")));
}
TEST(FlatExprBuilderTest, ComprehensionExprUnsetAccuInit) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr{
accu_var: "a"
iter_var: "b"}
)",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'accu_init' must be set")));
}
TEST(FlatExprBuilderTest, ComprehensionExprUnsetLoopCondition) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr{
accu_var: 'a'
iter_var: 'b'
accu_init {
const_expr {bool_value: true}
}}
)",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'loop_condition' must be set")));
}
TEST(FlatExprBuilderTest, ComprehensionExprUnsetLoopStep) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr{
accu_var: 'a'
iter_var: 'b'
accu_init {
const_expr {bool_value: true}
}
loop_condition {
const_expr {bool_value: true}
}}
)",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'loop_step' must be set")));
}
TEST(FlatExprBuilderTest, ComprehensionExprUnsetResult) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr{
accu_var: 'a'
iter_var: 'b'
accu_init {
const_expr {bool_value: true}
}
loop_condition {
const_expr {bool_value: true}
}
loop_step {
const_expr {bool_value: false}
}}
)",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("'result' must be set")));
}
TEST(FlatExprBuilderTest, MapComprehension) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr {
iter_var: "k"
accu_var: "accu"
accu_init {
const_expr { bool_value: true }
}
loop_condition { ident_expr { name: "accu" } }
result { ident_expr { name: "accu" } }
loop_step {
call_expr {
function: "_&&_"
args {
ident_expr { name: "accu" }
}
args {
call_expr {
function: "_>_"
args { ident_expr { name: "k" } }
args { const_expr { int64_value: 0 } }
}
}
}
}
iter_range {
struct_expr {
entries {
map_key { const_expr { int64_value: 1 } }
value { const_expr { string_value: "" } }
}
entries {
map_key { const_expr { int64_value: 2 } }
value { const_expr { string_value: "" } }
}
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
EXPECT_TRUE(result.BoolOrDie());
}
TEST(FlatExprBuilderTest, InvalidContainer) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
call_expr {
function: "_&&_"
args {
ident_expr {
name: "foo"
}
}
args {
ident_expr {
name: "bar"
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
builder.set_container(".bad");
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("container: '.bad'")));
builder.set_container("bad.");
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("container: 'bad.'")));
}
TEST(FlatExprBuilderTest, ParsedNamespacedFunctionSupport) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("ext.XOr(a, b)"));
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kAlways));
using FunctionAdapterT = FunctionAdapter<bool, bool, bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"ext.XOr", false,
[](google::protobuf::Arena*, bool a, bool b) { return a != b; },
builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(
&expr.expr(), &expr.source_info()));
google::protobuf::Arena arena;
Activation act1;
act1.InsertValue("a", CelValue::CreateBool(false));
act1.InsertValue("b", CelValue::CreateBool(true));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelBool(true));
Activation act2;
act2.InsertValue("a", CelValue::CreateBool(true));
act2.InsertValue("b", CelValue::CreateBool(true));
ASSERT_OK_AND_ASSIGN(result, cel_expr->Evaluate(act2, &arena));
EXPECT_THAT(result, test::IsCelBool(false));
}
TEST(FlatExprBuilderTest, ParsedNamespacedFunctionSupportWithContainer) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("XOr(a, b)"));
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kAlways));
builder.set_container("ext");
using FunctionAdapterT = FunctionAdapter<bool, bool, bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"ext.XOr", false,
[](google::protobuf::Arena*, bool a, bool b) { return a != b; },
builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(
&expr.expr(), &expr.source_info()));
google::protobuf::Arena arena;
Activation act1;
act1.InsertValue("a", CelValue::CreateBool(false));
act1.InsertValue("b", CelValue::CreateBool(true));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelBool(true));
Activation act2;
act2.InsertValue("a", CelValue::CreateBool(true));
act2.InsertValue("b", CelValue::CreateBool(true));
ASSERT_OK_AND_ASSIGN(result, cel_expr->Evaluate(act2, &arena));
EXPECT_THAT(result, test::IsCelBool(false));
}
TEST(FlatExprBuilderTest, ParsedNamespacedFunctionResolutionOrder) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("c.d.Get()"));
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kAlways));
builder.set_container("a.b");
using FunctionAdapterT = FunctionAdapter<bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"a.b.c.d.Get", false,
[](google::protobuf::Arena*) { return true; }, builder.GetRegistry()));
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"c.d.Get", false, [](google::protobuf::Arena*) { return false; },
builder.GetRegistry()));
ASSERT_OK((FunctionAdapter<bool, bool>::CreateAndRegister(
"Get",
true, [](google::protobuf::Arena*, bool) { return false; },
builder.GetRegistry())));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(
&expr.expr(), &expr.source_info()));
google::protobuf::Arena arena;
Activation act1;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelBool(true));
}
TEST(FlatExprBuilderTest,
ParsedNamespacedFunctionResolutionOrderParentContainer) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("c.d.Get()"));
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kAlways));
builder.set_container("a.b");
using FunctionAdapterT = FunctionAdapter<bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"a.c.d.Get", false,
[](google::protobuf::Arena*) { return true; }, builder.GetRegistry()));
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"c.d.Get", false, [](google::protobuf::Arena*) { return false; },
builder.GetRegistry()));
ASSERT_OK((FunctionAdapter<bool, bool>::CreateAndRegister(
"Get",
true, [](google::protobuf::Arena*, bool) { return false; },
builder.GetRegistry())));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(
&expr.expr(), &expr.source_info()));
google::protobuf::Arena arena;
Activation act1;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelBool(true));
}
TEST(FlatExprBuilderTest,
ParsedNamespacedFunctionResolutionOrderExplicitGlobal) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse(".c.d.Get()"));
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kAlways));
builder.set_container("a.b");
using FunctionAdapterT = FunctionAdapter<bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"a.c.d.Get", false,
[](google::protobuf::Arena*) { return false; }, builder.GetRegistry()));
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"c.d.Get", false, [](google::protobuf::Arena*) { return true; },
builder.GetRegistry()));
ASSERT_OK((FunctionAdapter<bool, bool>::CreateAndRegister(
"Get",
true, [](google::protobuf::Arena*, bool) { return false; },
builder.GetRegistry())));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(
&expr.expr(), &expr.source_info()));
google::protobuf::Arena arena;
Activation act1;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelBool(true));
}
TEST(FlatExprBuilderTest, ParsedNamespacedFunctionResolutionOrderReceiverCall) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("e.Get()"));
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kAlways));
builder.set_container("a.b");
using FunctionAdapterT = FunctionAdapter<bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"a.c.d.Get", false,
[](google::protobuf::Arena*) { return false; }, builder.GetRegistry()));
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"c.d.Get", false, [](google::protobuf::Arena*) { return false; },
builder.GetRegistry()));
ASSERT_OK((FunctionAdapter<bool, bool>::CreateAndRegister(
"Get",
true, [](google::protobuf::Arena*, bool) { return true; },
builder.GetRegistry())));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(
&expr.expr(), &expr.source_info()));
google::protobuf::Arena arena;
Activation act1;
act1.InsertValue("e", CelValue::CreateBool(false));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelBool(true));
}
TEST(FlatExprBuilderTest, ParsedNamespacedFunctionSupportDisabled) {
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("ext.XOr(a, b)"));
cel::RuntimeOptions options;
options.fail_on_warnings = false;
CelExpressionBuilderFlatImpl builder(options);
std::vector<absl::Status> build_warnings;
builder.set_container("ext");
using FunctionAdapterT = FunctionAdapter<bool, bool, bool>;
ASSERT_OK(FunctionAdapterT::CreateAndRegister(
"ext.XOr", false,
[](google::protobuf::Arena*, bool a, bool b) { return a != b; },
builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(
auto cel_expr, builder.CreateExpression(&expr.expr(), &expr.source_info(),
&build_warnings));
google::protobuf::Arena arena;
Activation act1;
act1.InsertValue("a", CelValue::CreateBool(false));
act1.InsertValue("b", CelValue::CreateBool(true));
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(act1, &arena));
EXPECT_THAT(result, test::IsCelError(StatusIs(absl::StatusCode::kUnknown,
HasSubstr("ext"))));
}
TEST(FlatExprBuilderTest, BasicCheckedExprSupport) {
CheckedExpr expr;
google::protobuf::TextFormat::ParseFromString(R"(
expr {
id: 1
call_expr {
function: "_&&_"
args {
id: 2
ident_expr {
name: "foo"
}
}
args {
id: 3
ident_expr {
name: "bar"
}
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(&expr));
Activation activation;
activation.InsertValue("foo", CelValue::CreateBool(true));
activation.InsertValue("bar", CelValue::CreateBool(true));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
EXPECT_TRUE(result.BoolOrDie());
}
TEST(FlatExprBuilderTest, CheckedExprWithReferenceMap) {
CheckedExpr expr;
google::protobuf::TextFormat::ParseFromString(R"(
reference_map {
key: 2
value {
name: "foo.var1"
}
}
reference_map {
key: 4
value {
name: "bar.var2"
}
}
expr {
id: 1
call_expr {
function: "_&&_"
args {
id: 2
select_expr {
field: "var1"
operand {
id: 3
ident_expr {
name: "foo"
}
}
}
}
args {
id: 4
select_expr {
field: "var2"
operand {
ident_expr {
name: "bar"
}
}
}
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kCheckedOnly));
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(&expr));
Activation activation;
activation.InsertValue("foo.var1", CelValue::CreateBool(true));
activation.InsertValue("bar.var2", CelValue::CreateBool(true));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
EXPECT_TRUE(result.BoolOrDie());
}
TEST(FlatExprBuilderTest, CheckedExprWithReferenceMapFunction) {
CheckedExpr expr;
google::protobuf::TextFormat::ParseFromString(R"(
reference_map {
key: 1
value {
overload_id: "com.foo.ext.and"
}
}
reference_map {
key: 3
value {
name: "com.foo.var1"
}
}
reference_map {
key: 4
value {
name: "bar.var2"
}
}
expr {
id: 1
call_expr {
function: "and"
target {
id: 2
ident_expr {
name: "ext"
}
}
args {
id: 3
ident_expr {
name: "var1"
}
}
args {
id: 4
select_expr {
field: "var2"
operand {
id: 5
ident_expr {
name: "bar"
}
}
}
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kCheckedOnly));
builder.set_container("com.foo");
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK((FunctionAdapter<bool, bool, bool>::CreateAndRegister(
"com.foo.ext.and", false,
[](google::protobuf::Arena*, bool lhs, bool rhs) { return lhs && rhs; },
builder.GetRegistry())));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(&expr));
Activation activation;
activation.InsertValue("com.foo.var1", CelValue::CreateBool(true));
activation.InsertValue("bar.var2", CelValue::CreateBool(true));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
EXPECT_TRUE(result.BoolOrDie());
}
TEST(FlatExprBuilderTest, CheckedExprActivationMissesReferences) {
CheckedExpr expr;
google::protobuf::TextFormat::ParseFromString(R"(
reference_map {
key: 2
value {
name: "foo.var1"
}
}
reference_map {
key: 5
value {
name: "bar"
}
}
expr {
id: 1
call_expr {
function: "_&&_"
args {
id: 2
select_expr {
field: "var1"
operand {
id: 3
ident_expr {
name: "foo"
}
}
}
}
args {
id: 4
select_expr {
field: "var2"
operand {
id: 5
ident_expr {
name: "bar"
}
}
}
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kCheckedOnly));
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(&expr));
Activation activation;
activation.InsertValue("foo.var1", CelValue::CreateBool(true));
activation.InsertValue("bar.var2", CelValue::CreateBool(true));
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(*(result.ErrorOrDie()),
StatusIs(absl::StatusCode::kUnknown,
HasSubstr("No value with name \"bar\" found")));
std::vector<std::pair<CelValue, CelValue>> map_pairs{
{CelValue::CreateStringView("var2"), CelValue::CreateBool(false)}};
std::unique_ptr<CelMap> map_value =
*CreateContainerBackedMap(absl::MakeSpan(map_pairs));
activation.InsertValue("bar", CelValue::CreateMap(map_value.get()));
ASSERT_OK_AND_ASSIGN(result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
EXPECT_FALSE(result.BoolOrDie());
}
TEST(FlatExprBuilderTest, CheckedExprWithReferenceMapAndConstantFolding) {
CheckedExpr expr;
google::protobuf::TextFormat::ParseFromString(R"(
reference_map {
key: 3
value {
name: "var1"
value {
int64_value: 1
}
}
}
expr {
id: 1
struct_expr {
entries {
id: 2
map_key {
id: 3
ident_expr {
name: "var1"
}
}
value {
id: 4
const_expr {
string_value: "hello"
}
}
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
builder.flat_expr_builder().AddAstTransform(
NewReferenceResolverExtension(ReferenceResolverOption::kCheckedOnly));
google::protobuf::Arena arena;
auto memory_manager = ProtoMemoryManagerRef(&arena);
builder.flat_expr_builder().AddProgramOptimizer(
cel::runtime_internal::CreateConstantFoldingOptimizer(memory_manager));
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(&expr));
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsMap());
auto m = result.MapOrDie();
auto v = m->Get(&arena, CelValue::CreateInt64(1L));
EXPECT_THAT(v->StringOrDie().value(), Eq("hello"));
}
TEST(FlatExprBuilderTest, ComprehensionWorksForError) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
id: 4
comprehension_expr {
iter_var: "x"
iter_range {
id: 2
call_expr {
function: "_[_]"
args {
id: 1
struct_expr {
}
}
args {
id: 3
const_expr {
int64_value: 0
}
}
}
}
accu_var: "__result__"
accu_init {
id: 7
const_expr {
bool_value: true
}
}
loop_condition {
id: 8
call_expr {
function: "__not_strictly_false__"
args {
id: 9
ident_expr {
name: "__result__"
}
}
}
}
loop_step {
id: 10
call_expr {
function: "_&&_"
args {
id: 11
ident_expr {
name: "__result__"
}
}
args {
id: 6
ident_expr {
name: "x"
}
}
}
}
result {
id: 12
ident_expr {
name: "__result__"
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsError());
}
TEST(FlatExprBuilderTest, ComprehensionWorksForNonContainer) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
id: 4
comprehension_expr {
iter_var: "x"
iter_range {
id: 2
const_expr {
int64_value: 0
}
}
accu_var: "__result__"
accu_init {
id: 7
const_expr {
bool_value: true
}
}
loop_condition {
id: 8
call_expr {
function: "__not_strictly_false__"
args {
id: 9
ident_expr {
name: "__result__"
}
}
}
}
loop_step {
id: 10
call_expr {
function: "_&&_"
args {
id: 11
ident_expr {
name: "__result__"
}
}
args {
id: 6
ident_expr {
name: "x"
}
}
}
}
result {
id: 12
ident_expr {
name: "__result__"
}
}
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsError());
EXPECT_THAT(result.ErrorOrDie()->message(),
Eq("No matching overloads found : <iter_range>"));
}
TEST(FlatExprBuilderTest, ComprehensionBudget) {
Expr expr;
SourceInfo source_info;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
comprehension_expr {
iter_var: "k"
accu_var: "accu"
accu_init {
const_expr { bool_value: true }
}
loop_condition { ident_expr { name: "accu" } }
result { ident_expr { name: "accu" } }
loop_step {
call_expr {
function: "_&&_"
args {
ident_expr { name: "accu" }
}
args {
call_expr {
function: "_>_"
args { ident_expr { name: "k" } }
args { const_expr { int64_value: 0 } }
}
}
}
}
iter_range {
list_expr {
elements { const_expr { int64_value: 1 } }
elements { const_expr { int64_value: 2 } }
}
}
})",
&expr));
cel::RuntimeOptions options;
options.comprehension_max_iterations = 1;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
Activation activation;
google::protobuf::Arena arena;
EXPECT_THAT(cel_expr->Evaluate(activation, &arena).status(),
StatusIs(absl::StatusCode::kInternal,
HasSubstr("Iteration budget exceeded")));
}
TEST(FlatExprBuilderTest, SimpleEnumTest) {
TestMessage message;
Expr expr;
SourceInfo source_info;
constexpr char enum_name[] =
"google.api.expr.runtime.TestMessage.TestEnum.TEST_ENUM_1";
std::vector<std::string> enum_name_parts = absl::StrSplit(enum_name, '.');
Expr* cur_expr = &expr;
for (int i = enum_name_parts.size() - 1; i > 0; i--) {
auto select_expr = cur_expr->mutable_select_expr();
select_expr->set_field(enum_name_parts[i]);
cur_expr = select_expr->mutable_operand();
}
cur_expr->mutable_ident_expr()->set_name(enum_name_parts[0]);
CelExpressionBuilderFlatImpl builder;
builder.GetTypeRegistry()->Register(TestMessage::TestEnum_descriptor());
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
}
TEST(FlatExprBuilderTest, SimpleEnumIdentTest) {
TestMessage message;
Expr expr;
SourceInfo source_info;
constexpr char enum_name[] =
"google.api.expr.runtime.TestMessage.TestEnum.TEST_ENUM_1";
Expr* cur_expr = &expr;
cur_expr->mutable_ident_expr()->set_name(enum_name);
CelExpressionBuilderFlatImpl builder;
builder.GetTypeRegistry()->Register(TestMessage::TestEnum_descriptor());
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
}
TEST(FlatExprBuilderTest, ContainerStringFormat) {
Expr expr;
SourceInfo source_info;
expr.mutable_ident_expr()->set_name("ident");
CelExpressionBuilderFlatImpl builder;
builder.set_container("");
ASSERT_OK(builder.CreateExpression(&expr, &source_info));
builder.set_container("random.namespace");
ASSERT_OK(builder.CreateExpression(&expr, &source_info));
builder.set_container(".random.namespace");
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid expression container")));
builder.set_container("random.namespace.");
EXPECT_THAT(builder.CreateExpression(&expr, &source_info).status(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid expression container")));
}
void EvalExpressionWithEnum(absl::string_view enum_name,
absl::string_view container, CelValue* result) {
TestMessage message;
Expr expr;
SourceInfo source_info;
std::vector<std::string> enum_name_parts = absl::StrSplit(enum_name, '.');
Expr* cur_expr = &expr;
for (int i = enum_name_parts.size() - 1; i > 0; i--) {
auto select_expr = cur_expr->mutable_select_expr();
select_expr->set_field(enum_name_parts[i]);
cur_expr = select_expr->mutable_operand();
}
cur_expr->mutable_ident_expr()->set_name(enum_name_parts[0]);
CelExpressionBuilderFlatImpl builder;
builder.GetTypeRegistry()->Register(TestMessage::TestEnum_descriptor());
builder.GetTypeRegistry()->Register(TestEnum_descriptor());
builder.set_container(std::string(container));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
google::protobuf::Arena arena;
Activation activation;
auto eval = cel_expr->Evaluate(activation, &arena);
ASSERT_OK(eval);
*result = eval.value();
}
TEST(FlatExprBuilderTest, ShortEnumResolution) {
CelValue result;
ASSERT_NO_FATAL_FAILURE(EvalExpressionWithEnum(
"TestEnum.TEST_ENUM_1", "google.api.expr.runtime.TestMessage", &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
}
TEST(FlatExprBuilderTest, FullEnumNameWithContainerResolution) {
CelValue result;
ASSERT_NO_FATAL_FAILURE(EvalExpressionWithEnum(
"google.api.expr.runtime.TestMessage.TestEnum.TEST_ENUM_1",
"very.random.Namespace", &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
}
TEST(FlatExprBuilderTest, SameShortNameEnumResolution) {
CelValue result;
ASSERT_TRUE(static_cast<int>(TestEnum::TEST_ENUM_1) !=
static_cast<int>(TestMessage::TEST_ENUM_1));
ASSERT_NO_FATAL_FAILURE(EvalExpressionWithEnum(
"TestEnum.TEST_ENUM_1", "google.api.expr.runtime.TestMessage", &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
ASSERT_NO_FATAL_FAILURE(EvalExpressionWithEnum(
"TestEnum.TEST_ENUM_3", "google.api.expr.runtime.TestMessage", &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestEnum::TEST_ENUM_3));
ASSERT_NO_FATAL_FAILURE(EvalExpressionWithEnum(
"TestEnum.TEST_ENUM_1", "google.api.expr.runtime", &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestEnum::TEST_ENUM_1));
}
TEST(FlatExprBuilderTest, PartialQualifiedEnumResolution) {
CelValue result;
ASSERT_NO_FATAL_FAILURE(EvalExpressionWithEnum(
"runtime.TestMessage.TestEnum.TEST_ENUM_1", "google.api.expr", &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
}
TEST(FlatExprBuilderTest, MapFieldPresence) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
id: 1,
select_expr{
operand {
id: 2
ident_expr{ name: "msg" }
}
field: "string_int32_map"
test_only: true
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
google::protobuf::Arena arena;
{
TestMessage message;
auto strMap = message.mutable_string_int32_map();
strMap->insert({"key", 1});
Activation activation;
activation.InsertValue("msg",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
{
TestMessage message;
Activation activation;
activation.InsertValue("msg",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
}
TEST(FlatExprBuilderTest, RepeatedFieldPresence) {
Expr expr;
SourceInfo source_info;
google::protobuf::TextFormat::ParseFromString(R"(
id: 1,
select_expr{
operand {
id: 2
ident_expr{ name: "msg" }
}
field: "int32_list"
test_only: true
})",
&expr);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
google::protobuf::Arena arena;
{
TestMessage message;
message.add_int32_list(1);
Activation activation;
activation.InsertValue("msg",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
{
TestMessage message;
Activation activation;
activation.InsertValue("msg",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_FALSE(result.BoolOrDie());
}
}
absl::Status RunTernaryExpression(CelValue selector, CelValue value1,
CelValue value2, google::protobuf::Arena* arena,
CelValue* result) {
Expr expr;
SourceInfo source_info;
auto call_expr = expr.mutable_call_expr();
call_expr->set_function(builtin::kTernary);
auto arg0 = call_expr->add_args();
arg0->mutable_ident_expr()->set_name("selector");
auto arg1 = call_expr->add_args();
arg1->mutable_ident_expr()->set_name("value1");
auto arg2 = call_expr->add_args();
arg2->mutable_ident_expr()->set_name("value2");
CelExpressionBuilderFlatImpl builder;
CEL_ASSIGN_OR_RETURN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
std::string variable = "test";
Activation activation;
activation.InsertValue("selector", selector);
activation.InsertValue("value1", value1);
activation.InsertValue("value2", value2);
CEL_ASSIGN_OR_RETURN(auto eval, cel_expr->Evaluate(activation, arena));
*result = eval;
return absl::OkStatus();
}
TEST(FlatExprBuilderTest, Ternary) {
Expr expr;
SourceInfo source_info;
auto call_expr = expr.mutable_call_expr();
call_expr->set_function(builtin::kTernary);
auto arg0 = call_expr->add_args();
arg0->mutable_ident_expr()->set_name("selector");
auto arg1 = call_expr->add_args();
arg1->mutable_ident_expr()->set_name("value1");
auto arg2 = call_expr->add_args();
arg2->mutable_ident_expr()->set_name("value1");
CelExpressionBuilderFlatImpl builder;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder.CreateExpression(&expr, &source_info));
google::protobuf::Arena arena;
{
CelValue result;
ASSERT_OK(RunTernaryExpression(CelValue::CreateBool(true),
CelValue::CreateInt64(1),
CelValue::CreateInt64(2), &arena, &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(1));
UnknownSet unknown_set;
ASSERT_OK(RunTernaryExpression(CelValue::CreateBool(true),
CelValue::CreateUnknownSet(&unknown_set),
CelValue::CreateInt64(2), &arena, &result));
ASSERT_TRUE(result.IsUnknownSet());
ASSERT_OK(RunTernaryExpression(
CelValue::CreateBool(true), CelValue::CreateInt64(1),
CelValue::CreateUnknownSet(&unknown_set), &arena, &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(1));
}
{
CelValue result;
ASSERT_OK(RunTernaryExpression(CelValue::CreateBool(false),
CelValue::CreateInt64(1),
CelValue::CreateInt64(2), &arena, &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(2));
UnknownSet unknown_set;
ASSERT_OK(RunTernaryExpression(CelValue::CreateBool(false),
CelValue::CreateUnknownSet(&unknown_set),
CelValue::CreateInt64(2), &arena, &result));
ASSERT_TRUE(result.IsInt64());
EXPECT_THAT(result.Int64OrDie(), Eq(2));
ASSERT_OK(RunTernaryExpression(
CelValue::CreateBool(false), CelValue::CreateInt64(1),
CelValue::CreateUnknownSet(&unknown_set), &arena, &result));
ASSERT_TRUE(result.IsUnknownSet());
}
{
CelValue result;
ASSERT_OK(RunTernaryExpression(CreateErrorValue(&arena, "error"),
CelValue::CreateInt64(1),
CelValue::CreateInt64(2), &arena, &result));
ASSERT_TRUE(result.IsError());
}
{
UnknownSet unknown_set;
CelValue result;
ASSERT_OK(RunTernaryExpression(CelValue::CreateUnknownSet(&unknown_set),
CelValue::CreateInt64(1),
CelValue::CreateInt64(2), &arena, &result));
ASSERT_TRUE(result.IsUnknownSet());
EXPECT_THAT(unknown_set, Eq(*result.UnknownSetOrDie()));
}
{
CelAttribute selector_attr("selector", {});
CelAttribute value1_attr("value1", {});
CelAttribute value2_attr("value2", {});
UnknownSet unknown_selector(UnknownAttributeSet({selector_attr}));
UnknownSet unknown_value1(UnknownAttributeSet({value1_attr}));
UnknownSet unknown_value2(UnknownAttributeSet({value2_attr}));
CelValue result;
ASSERT_OK(RunTernaryExpression(
CelValue::CreateUnknownSet(&unknown_selector),
CelValue::CreateUnknownSet(&unknown_value1),
CelValue::CreateUnknownSet(&unknown_value2), &arena, &result));
ASSERT_TRUE(result.IsUnknownSet());
const UnknownSet* result_set = result.UnknownSetOrDie();
EXPECT_THAT(result_set->unknown_attributes().size(), Eq(1));
EXPECT_THAT(result_set->unknown_attributes().begin()->variable_name(),
Eq("selector"));
}
}
TEST(FlatExprBuilderTest, EmptyCallList) {
std::vector<std::string> operators = {"_&&_", "_||_", "_?_:_"};
for (const auto& op : operators) {
Expr expr;
SourceInfo source_info;
auto call_expr = expr.mutable_call_expr();
call_expr->set_function(op);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
auto build = builder.CreateExpression(&expr, &source_info);
ASSERT_FALSE(build.ok());
}
}
TEST(FlatExprBuilderTest, HeterogeneousListsAllowed) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("[17, 'seventeen']"));
cel::RuntimeOptions options;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsList()) << result.DebugString();
const auto& list = *result.ListOrDie();
ASSERT_EQ(list.size(), 2);
CelValue elem0 = list.Get(&arena, 0);
CelValue elem1 = list.Get(&arena, 1);
EXPECT_THAT(elem0, test::IsCelInt64(17));
EXPECT_THAT(elem1, test::IsCelString("seventeen"));
}
TEST(FlatExprBuilderTest, NullUnboxingEnabled) {
TestMessage message;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("message.int32_wrapper_value"));
cel::RuntimeOptions options;
options.enable_empty_wrapper_null_unboxing = true;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_TRUE(result.IsNull());
}
TEST(FlatExprBuilderTest, TypeResolve) {
TestMessage message;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("type(message) == runtime.TestMessage"));
cel::RuntimeOptions options;
options.enable_qualified_type_identifiers = true;
CelExpressionBuilderFlatImpl builder(options);
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
builder.set_container("google.api.expr");
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool()) << result.DebugString();
EXPECT_TRUE(result.BoolOrDie());
}
TEST(FlatExprBuilderTest, AnyPackingList) {
google::protobuf::LinkMessageReflection<TestAllTypes>();
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("TestAllTypes{single_any: [1, 2, 3]}"));
cel::RuntimeOptions options;
CelExpressionBuilderFlatImpl builder(options);
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
builder.set_container("google.api.expr.test.v1.proto3");
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result,
test::IsCelMessage(EqualsProto(
R"pb(single_any {
[type.googleapis.com/google.protobuf.ListValue] {
values { number_value: 1 }
values { number_value: 2 }
values { number_value: 3 }
}
})pb")))
<< result.DebugString();
}
TEST(FlatExprBuilderTest, AnyPackingNestedNumbers) {
google::protobuf::LinkMessageReflection<TestAllTypes>();
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("TestAllTypes{single_any: [1, 2.3]}"));
cel::RuntimeOptions options;
CelExpressionBuilderFlatImpl builder(options);
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
builder.set_container("google.api.expr.test.v1.proto3");
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result,
test::IsCelMessage(EqualsProto(
R"pb(single_any {
[type.googleapis.com/google.protobuf.ListValue] {
values { number_value: 1 }
values { number_value: 2.3 }
}
})pb")))
<< result.DebugString();
}
TEST(FlatExprBuilderTest, AnyPackingInt) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("TestAllTypes{single_any: 1}"));
cel::RuntimeOptions options;
CelExpressionBuilderFlatImpl builder(options);
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
builder.set_container("google.api.expr.test.v1.proto3");
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(
result,
test::IsCelMessage(EqualsProto(
R"pb(single_any {
[type.googleapis.com/google.protobuf.Int64Value] { value: 1 }
})pb")))
<< result.DebugString();
}
TEST(FlatExprBuilderTest, AnyPackingMap) {
ASSERT_OK_AND_ASSIGN(
ParsedExpr parsed_expr,
parser::Parse("TestAllTypes{single_any: {'key': 'value'}}"));
cel::RuntimeOptions options;
CelExpressionBuilderFlatImpl builder(options);
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
builder.set_container("google.api.expr.test.v1.proto3");
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelMessage(EqualsProto(
R"pb(single_any {
[type.googleapis.com/google.protobuf.Struct] {
fields {
key: "key"
value { string_value: "value" }
}
}
})pb")))
<< result.DebugString();
}
TEST(FlatExprBuilderTest, NullUnboxingDisabled) {
TestMessage message;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("message.int32_wrapper_value"));
cel::RuntimeOptions options;
options.enable_empty_wrapper_null_unboxing = false;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(&message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelInt64(0));
}
TEST(FlatExprBuilderTest, HeterogeneousEqualityEnabled) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("{1: 2, 2u: 3}[1.0]"));
cel::RuntimeOptions options;
options.enable_heterogeneous_equality = true;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelInt64(2));
}
TEST(FlatExprBuilderTest, HeterogeneousEqualityDisabled) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("{1: 2, 2u: 3}[1.0]"));
cel::RuntimeOptions options;
options.enable_heterogeneous_equality = false;
CelExpressionBuilderFlatImpl builder(options);
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result,
test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Invalid map key type"))));
}
TEST(FlatExprBuilderTest, CustomDescriptorPoolForCreateStruct) {
ASSERT_OK_AND_ASSIGN(
ParsedExpr parsed_expr,
parser::Parse("google.api.expr.runtime.SimpleTestMessage{}"));
CelExpressionBuilderFlatImpl builder;
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument));
google::protobuf::DescriptorPool desc_pool;
google::protobuf::FileDescriptorSet filedesc_set;
ASSERT_OK(ReadBinaryProtoFromFile(kSimpleTestMessageDescriptorSetFile,
filedesc_set));
ASSERT_EQ(filedesc_set.file_size(), 1);
desc_pool.BuildFile(filedesc_set.file(0));
google::protobuf::DynamicMessageFactory message_factory(&desc_pool);
CelExpressionBuilderFlatImpl builder2;
builder2.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(&desc_pool,
&message_factory));
ASSERT_OK_AND_ASSIGN(auto expression,
builder2.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsMessage());
EXPECT_EQ(result.MessageOrDie()->GetTypeName(),
"google.api.expr.runtime.SimpleTestMessage");
}
TEST(FlatExprBuilderTest, CustomDescriptorPoolForSelect) {
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("message.int64_value"));
google::protobuf::DescriptorPool desc_pool;
google::protobuf::FileDescriptorSet filedesc_set;
ASSERT_OK(ReadBinaryProtoFromFile(kSimpleTestMessageDescriptorSetFile,
filedesc_set));
ASSERT_EQ(filedesc_set.file_size(), 1);
desc_pool.BuildFile(filedesc_set.file(0));
google::protobuf::DynamicMessageFactory message_factory(&desc_pool);
const google::protobuf::Descriptor* desc = desc_pool.FindMessageTypeByName(
"google.api.expr.runtime.SimpleTestMessage");
const google::protobuf::Message* message_prototype = message_factory.GetPrototype(desc);
google::protobuf::Message* message = message_prototype->New();
const google::protobuf::Reflection* refl = message->GetReflection();
const google::protobuf::FieldDescriptor* field = desc->FindFieldByName("int64_value");
refl->SetInt64(message, field, 123);
CelExpressionBuilderFlatImpl builder;
ASSERT_OK_AND_ASSIGN(auto expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
google::protobuf::Arena arena;
activation.InsertValue("message",
CelProtoWrapper::CreateMessage(message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result, test::IsCelInt64(123));
delete message;
}
std::pair<google::protobuf::Message*, const google::protobuf::Reflection*> CreateTestMessage(
const google::protobuf::DescriptorPool& descriptor_pool,
google::protobuf::MessageFactory& message_factory, absl::string_view name) {
const google::protobuf::Descriptor* desc = descriptor_pool.FindMessageTypeByName(name);
const google::protobuf::Message* message_prototype = message_factory.GetPrototype(desc);
google::protobuf::Message* message = message_prototype->New();
const google::protobuf::Reflection* refl = message->GetReflection();
return std::make_pair(message, refl);
}
struct CustomDescriptorPoolTestParam final {
using SetterFunction =
std::function<void(google::protobuf::Message*, const google::protobuf::Reflection*,
const google::protobuf::FieldDescriptor*)>;
std::string message_type;
std::string field_name;
SetterFunction setter;
test::CelValueMatcher matcher;
};
class CustomDescriptorPoolTest
: public ::testing::TestWithParam<CustomDescriptorPoolTestParam> {};
TEST_P(CustomDescriptorPoolTest, TestType) {
const CustomDescriptorPoolTestParam& p = GetParam();
google::protobuf::DescriptorPool descriptor_pool;
google::protobuf::Arena arena;
ASSERT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool));
google::protobuf::DynamicMessageFactory message_factory(&descriptor_pool);
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse("m"));
CelExpressionBuilderFlatImpl builder;
builder.GetTypeRegistry()->RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(&descriptor_pool,
&message_factory));
ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry()));
auto [message, reflection] =
CreateTestMessage(descriptor_pool, message_factory, p.message_type);
const google::protobuf::FieldDescriptor* field =
message->GetDescriptor()->FindFieldByName(p.field_name);
p.setter(message, reflection, field);
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelExpression> expression,
builder.CreateExpression(&parsed_expr.expr(),
&parsed_expr.source_info()));
Activation activation;
activation.InsertValue("m", CelProtoWrapper::CreateMessage(message, &arena));
ASSERT_OK_AND_ASSIGN(CelValue result,
expression->Evaluate(activation, &arena));
EXPECT_THAT(result, p.matcher);
delete message;
}
INSTANTIATE_TEST_SUITE_P(
ValueTypes, CustomDescriptorPoolTest,
::testing::ValuesIn(std::vector<CustomDescriptorPoolTestParam>{
{"google.protobuf.Duration", "seconds",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetInt64(message, field, 10);
},
test::IsCelDuration(absl::Seconds(10))},
{"google.protobuf.DoubleValue", "value",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetDouble(message, field, 1.2);
},
test::IsCelDouble(1.2)},
{"google.protobuf.Int64Value", "value",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetInt64(message, field, -23);
},
test::IsCelInt64(-23)},
{"google.protobuf.UInt64Value", "value",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetUInt64(message, field, 42);
},
test::IsCelUint64(42)},
{"google.protobuf.BoolValue", "value",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetBool(message, field, true);
},
test::IsCelBool(true)},
{"google.protobuf.StringValue", "value",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetString(message, field, "foo");
},
test::IsCelString("foo")},
{"google.protobuf.BytesValue", "value",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetString(message, field, "bar");
},
test::IsCelBytes("bar")},
{"google.protobuf.Timestamp", "seconds",
[](google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
const google::protobuf::FieldDescriptor* field) {
reflection->SetInt64(message, field, 20);
},
test::IsCelTimestamp(absl::FromUnixSeconds(20))}}));
struct ConstantFoldingTestCase {
std::string test_name;
std::string expr;
test::CelValueMatcher matcher;
absl::flat_hash_map<std::string, int64_t> values;
};
class UnknownFunctionImpl : public cel::Function {
absl::StatusOr<Value> Invoke(const cel::Function::InvokeContext& ctx,
absl::Span<const Value> args) const override {
return ctx.value_factory().CreateUnknownValue();
}
};
absl::StatusOr<std::unique_ptr<CelExpressionBuilder>>
CreateConstantFoldingConformanceTestExprBuilder(
const InterpreterOptions& options) {
auto builder =
google::api::expr::runtime::CreateCelExpressionBuilder(options);
CEL_RETURN_IF_ERROR(
RegisterBuiltinFunctions(builder->GetRegistry(), options));
CEL_RETURN_IF_ERROR(builder->GetRegistry()->RegisterLazyFunction(
cel::FunctionDescriptor("LazyFunction", false, {})));
CEL_RETURN_IF_ERROR(builder->GetRegistry()->RegisterLazyFunction(
cel::FunctionDescriptor("LazyFunction", false, {cel::Kind::kBool})));
CEL_RETURN_IF_ERROR(builder->GetRegistry()->Register(
cel::FunctionDescriptor("UnknownFunction", false, {}),
std::make_unique<UnknownFunctionImpl>()));
return builder;
}
class ConstantFoldingConformanceTest
: public ::testing::TestWithParam<ConstantFoldingTestCase> {
protected:
google::protobuf::Arena arena_;
};
TEST_P(ConstantFoldingConformanceTest, Updated) {
InterpreterOptions options;
options.constant_folding = true;
options.constant_arena = &arena_;
options.enable_comprehension_list_append = true;
const ConstantFoldingTestCase& p = GetParam();
ASSERT_OK_AND_ASSIGN(
auto builder, CreateConstantFoldingConformanceTestExprBuilder(options));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse(p.expr));
ASSERT_OK_AND_ASSIGN(
auto plan, builder->CreateExpression(&expr.expr(), &expr.source_info()));
Activation activation;
ASSERT_OK(activation.InsertFunction(
PortableUnaryFunctionAdapter<bool, bool>::Create(
"LazyFunction", false,
[](google::protobuf::Arena* arena, bool val) { return val; })));
for (auto iter = p.values.begin(); iter != p.values.end(); ++iter) {
activation.InsertValue(iter->first, CelValue::CreateInt64(iter->second));
}
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena_));
ASSERT_OK_AND_ASSIGN(result, plan->Evaluate(activation, &arena_));
EXPECT_THAT(result, p.matcher);
}
INSTANTIATE_TEST_SUITE_P(
Exprs, ConstantFoldingConformanceTest,
::testing::ValuesIn(std::vector<ConstantFoldingTestCase>{
{"simple_add", "1 + 2 + 3", test::IsCelInt64(6)},
{"add_with_var",
"1 + (2 + (3 + id))",
test::IsCelInt64(10),
{{"id", 4}}},
{"const_list", "[1, 2, 3, 4]", test::IsCelList(_)},
{"mixed_const_list",
"[1, 2, 3, 4] + [id]",
test::IsCelList(_),
{{"id", 5}}},
{"create_struct", "{'abc': 'def', 'def': 'efg', 'efg': 'hij'}",
Truly([](const CelValue& v) { return v.IsMap(); })},
{"field_selection", "{'abc': 123}.abc == 123", test::IsCelBool(true)},
{"type_coverage",
R"cel(
[type(bool),
type(123),
type(123u),
type(12.3),
type(b'123'),
type('123'),
type(null),
type(timestamp(0)),
type(duration('1h'))
])cel",
test::IsCelList(SizeIs(9))},
{"lazy_function", "true || LazyFunction()", test::IsCelBool(true)},
{"lazy_function_called", "LazyFunction(true) || false",
test::IsCelBool(true)},
{"unknown_function", "UnknownFunction() && false",
test::IsCelBool(false)},
{"nested_comprehension",
"[1, 2, 3, 4].all(x, [5, 6, 7, 8].all(y, x < y))",
test::IsCelBool(true)},
{"map", "[1, 2, 3, 4].map(x, x * 2).size() == 4",
test::IsCelBool(true)},
{"str_cat",
"'1234567890' + '1234567890' + '1234567890' + '1234567890' + "
"'1234567890'",
test::IsCelString(
"12345678901234567890123456789012345678901234567890")}}));
TEST(UpdatedConstantFolding, FoldsLists) {
InterpreterOptions options;
google::protobuf::Arena arena;
options.constant_folding = true;
options.constant_arena = &arena;
ASSERT_OK_AND_ASSIGN(
auto builder, CreateConstantFoldingConformanceTestExprBuilder(options));
ASSERT_OK_AND_ASSIGN(ParsedExpr expr,
parser::Parse("[1] + [2] + [3] + [4] + [5] + [6] + [7] "
"+ [8] + [9] + [10] + [11] + [12]"));
ASSERT_OK_AND_ASSIGN(
auto plan, builder->CreateExpression(&expr.expr(), &expr.source_info()));
Activation activation;
int before_size = arena.SpaceUsed();
ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena));
EXPECT_LE(arena.SpaceUsed() - before_size, 512);
EXPECT_THAT(result, test::IsCelList(SizeIs(12)));
}
TEST(FlatExprBuilderTest, BlockBadIndex) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args {
list_expr: { elements { const_expr: { string_value: "foo" } } }
}
args { ident_expr: { name: "@index-1" } }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("bad @index")));
}
TEST(FlatExprBuilderTest, OutOfRangeBlockIndex) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args {
list_expr: { elements { const_expr: { string_value: "foo" } } }
}
args { ident_expr: { name: "@index1" } }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("invalid @index greater than number of bindings:")));
}
TEST(FlatExprBuilderTest, EarlyBlockIndex) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args { list_expr: { elements { ident_expr: { name: "@index0" } } } }
args { ident_expr: { name: "@index0" } }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("@index references current or future binding:")));
}
TEST(FlatExprBuilderTest, OutOfScopeCSE) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: { ident_expr: { name: "@ac:0:0" } }
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("out of scope reference to CSE generated "
"comprehension variable")));
}
TEST(FlatExprBuilderTest, BlockMissingBindings) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: { call_expr: { function: "cel.@block" } }
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr(
"malformed cel.@block: missing list of bound expressions")));
}
TEST(FlatExprBuilderTest, BlockMissingExpression) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args { list_expr: {} }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("malformed cel.@block: missing bound expression")));
}
TEST(FlatExprBuilderTest, BlockNotListOfBoundExpressions) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args { ident_expr: { name: "@index0" } }
args { ident_expr: { name: "@index0" } }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("malformed cel.@block: first argument is not a list "
"of bound expressions")));
}
TEST(FlatExprBuilderTest, BlockEmptyListOfBoundExpressions) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args { list_expr: {} }
args { ident_expr: { name: "@index0" } }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr(
"malformed cel.@block: list of bound expressions is empty")));
}
TEST(FlatExprBuilderTest, BlockOptionalListOfBoundExpressions) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args {
list_expr: {
elements { const_expr: { string_value: "foo" } }
optional_indices: [ 0 ]
}
}
args { ident_expr: { name: "@index0" } }
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("malformed cel.@block: list of bound expressions "
"contains an optional")));
}
TEST(FlatExprBuilderTest, BlockNested) {
ParsedExpr parsed_expr;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
R"pb(
expr: {
call_expr: {
function: "cel.@block"
args {
list_expr: { elements { const_expr: { string_value: "foo" } } }
}
args {
call_expr: {
function: "cel.@block"
args {
list_expr: {
elements { const_expr: { string_value: "foo" } }
}
}
args { ident_expr: { name: "@index1" } }
}
}
}
}
)pb",
&parsed_expr));
CelExpressionBuilderFlatImpl builder;
EXPECT_THAT(
builder.CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info()),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("multiple cel.@block are not allowed")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/flat_expr_builder.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/flat_expr_builder_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
b26549bb-b46f-41f7-a477-29175952794c | cpp | google/cel-cpp | ast_impl | base/ast_internal/ast_impl.cc | base/ast_internal/ast_impl_test.cc | #include "base/ast_internal/ast_impl.h"
#include <cstdint>
#include "absl/container/flat_hash_map.h"
namespace cel::ast_internal {
namespace {
const Type& DynSingleton() {
static auto* singleton = new Type(TypeKind(DynamicType()));
return *singleton;
}
}
const Type& AstImpl::GetType(int64_t expr_id) const {
auto iter = type_map_.find(expr_id);
if (iter == type_map_.end()) {
return DynSingleton();
}
return iter->second;
}
const Type& AstImpl::GetReturnType() const { return GetType(root_expr().id()); }
const Reference* AstImpl::GetReference(int64_t expr_id) const {
auto iter = reference_map_.find(expr_id);
if (iter == reference_map_.end()) {
return nullptr;
}
return &iter->second;
}
} | #include "base/ast_internal/ast_impl.h"
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "base/ast.h"
#include "base/ast_internal/expr.h"
#include "internal/testing.h"
namespace cel::ast_internal {
namespace {
using ::testing::Pointee;
using ::testing::Truly;
TEST(AstImpl, RawExprCtor) {
Expr expr;
auto& call = expr.mutable_call_expr();
expr.set_id(5);
call.set_function("_==_");
auto& eq_lhs = call.mutable_args().emplace_back();
eq_lhs.mutable_call_expr().set_function("_+_");
eq_lhs.set_id(3);
auto& sum_lhs = eq_lhs.mutable_call_expr().mutable_args().emplace_back();
sum_lhs.mutable_const_expr().set_int_value(2);
sum_lhs.set_id(1);
auto& sum_rhs = eq_lhs.mutable_call_expr().mutable_args().emplace_back();
sum_rhs.mutable_const_expr().set_int_value(1);
sum_rhs.set_id(2);
auto& eq_rhs = call.mutable_args().emplace_back();
eq_rhs.mutable_const_expr().set_int_value(3);
eq_rhs.set_id(4);
SourceInfo source_info;
source_info.mutable_positions()[5] = 6;
AstImpl ast_impl(std::move(expr), std::move(source_info));
Ast& ast = ast_impl;
ASSERT_FALSE(ast.IsChecked());
EXPECT_EQ(ast_impl.GetType(1), Type(DynamicType()));
EXPECT_EQ(ast_impl.GetReturnType(), Type(DynamicType()));
EXPECT_EQ(ast_impl.GetReference(1), nullptr);
EXPECT_TRUE(ast_impl.root_expr().has_call_expr());
EXPECT_EQ(ast_impl.root_expr().call_expr().function(), "_==_");
EXPECT_EQ(ast_impl.root_expr().id(), 5);
EXPECT_EQ(ast_impl.source_info().positions().at(5), 6);
}
TEST(AstImpl, CheckedExprCtor) {
Expr expr;
expr.mutable_ident_expr().set_name("int_value");
expr.set_id(1);
Reference ref;
ref.set_name("com.int_value");
AstImpl::ReferenceMap reference_map;
reference_map[1] = Reference(ref);
AstImpl::TypeMap type_map;
type_map[1] = Type(PrimitiveType::kInt64);
SourceInfo source_info;
source_info.set_syntax_version("1.0");
AstImpl ast_impl(std::move(expr), std::move(source_info),
std::move(reference_map), std::move(type_map), "1.0");
Ast& ast = ast_impl;
ASSERT_TRUE(ast.IsChecked());
EXPECT_EQ(ast_impl.GetType(1), Type(PrimitiveType::kInt64));
EXPECT_THAT(ast_impl.GetReference(1),
Pointee(Truly([&ref](const Reference& arg) {
return arg.name() == ref.name();
})));
EXPECT_EQ(ast_impl.GetReturnType(), Type(PrimitiveType::kInt64));
EXPECT_TRUE(ast_impl.root_expr().has_ident_expr());
EXPECT_EQ(ast_impl.root_expr().ident_expr().name(), "int_value");
EXPECT_EQ(ast_impl.root_expr().id(), 1);
EXPECT_EQ(ast_impl.source_info().syntax_version(), "1.0");
EXPECT_EQ(ast_impl.expr_version(), "1.0");
}
TEST(AstImpl, CheckedExprDeepCopy) {
Expr root;
root.set_id(3);
root.mutable_call_expr().set_function("_==_");
root.mutable_call_expr().mutable_args().resize(2);
auto& lhs = root.mutable_call_expr().mutable_args()[0];
auto& rhs = root.mutable_call_expr().mutable_args()[1];
AstImpl::TypeMap type_map;
AstImpl::ReferenceMap reference_map;
SourceInfo source_info;
type_map[3] = Type(PrimitiveType::kBool);
lhs.mutable_ident_expr().set_name("int_value");
lhs.set_id(1);
Reference ref;
ref.set_name("com.int_value");
reference_map[1] = std::move(ref);
type_map[1] = Type(PrimitiveType::kInt64);
rhs.mutable_const_expr().set_int_value(2);
rhs.set_id(2);
type_map[2] = Type(PrimitiveType::kInt64);
source_info.set_syntax_version("1.0");
AstImpl ast_impl(std::move(root), std::move(source_info),
std::move(reference_map), std::move(type_map), "1.0");
Ast& ast = ast_impl;
ASSERT_TRUE(ast.IsChecked());
EXPECT_EQ(ast_impl.GetType(1), Type(PrimitiveType::kInt64));
EXPECT_THAT(ast_impl.GetReference(1), Pointee(Truly([](const Reference& arg) {
return arg.name() == "com.int_value";
})));
EXPECT_EQ(ast_impl.GetReturnType(), Type(PrimitiveType::kBool));
EXPECT_TRUE(ast_impl.root_expr().has_call_expr());
EXPECT_EQ(ast_impl.root_expr().call_expr().function(), "_==_");
EXPECT_EQ(ast_impl.root_expr().id(), 3);
EXPECT_EQ(ast_impl.source_info().syntax_version(), "1.0");
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/ast_internal/ast_impl.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/ast_internal/ast_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
718a66b1-78f4-4b2a-a875-0a7f0a41e8b3 | cpp | google/cel-cpp | unknown_set | base/internal/unknown_set.cc | eval/public/unknown_set_test.cc | #include "base/internal/unknown_set.h"
#include "absl/base/no_destructor.h"
namespace cel::base_internal {
const AttributeSet& EmptyAttributeSet() {
static const absl::NoDestructor<AttributeSet> empty_attribute_set;
return *empty_attribute_set;
}
const FunctionResultSet& EmptyFunctionResultSet() {
static const absl::NoDestructor<FunctionResultSet> empty_function_result_set;
return *empty_function_result_set;
}
} | #include "eval/public/unknown_set.h"
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/arena.h"
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_function.h"
#include "eval/public/unknown_attribute_set.h"
#include "eval/public/unknown_function_result_set.h"
#include "internal/testing.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
using ::google::protobuf::Arena;
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;
UnknownFunctionResultSet MakeFunctionResult(Arena* arena, int64_t id) {
CelFunctionDescriptor desc("OneInt", false, {CelValue::Type::kInt64});
return UnknownFunctionResultSet(UnknownFunctionResult(desc, 0));
}
UnknownAttributeSet MakeAttribute(Arena* arena, int64_t id) {
std::vector<CelAttributeQualifier> attr_trail{
CreateCelAttributeQualifier(CelValue::CreateInt64(id))};
return UnknownAttributeSet({CelAttribute("x", std::move(attr_trail))});
}
MATCHER_P(UnknownAttributeIs, id, "") {
const CelAttribute& attr = arg;
if (attr.qualifier_path().size() != 1) {
return false;
}
auto maybe_qualifier = attr.qualifier_path()[0].GetInt64Key();
if (!maybe_qualifier.has_value()) {
return false;
}
return maybe_qualifier.value() == id;
}
TEST(UnknownSet, AttributesMerge) {
Arena arena;
UnknownSet a(MakeAttribute(&arena, 1));
UnknownSet b(MakeAttribute(&arena, 2));
UnknownSet c(MakeAttribute(&arena, 2));
UnknownSet d(a, b);
UnknownSet e(c, d);
EXPECT_THAT(
d.unknown_attributes(),
UnorderedElementsAre(UnknownAttributeIs(1), UnknownAttributeIs(2)));
EXPECT_THAT(
e.unknown_attributes(),
UnorderedElementsAre(UnknownAttributeIs(1), UnknownAttributeIs(2)));
}
TEST(UnknownSet, DefaultEmpty) {
UnknownSet empty_set;
EXPECT_THAT(empty_set.unknown_attributes(), IsEmpty());
EXPECT_THAT(empty_set.unknown_function_results(), IsEmpty());
}
TEST(UnknownSet, MixedMerges) {
Arena arena;
UnknownSet a(MakeAttribute(&arena, 1), MakeFunctionResult(&arena, 1));
UnknownSet b(MakeFunctionResult(&arena, 2));
UnknownSet c(MakeAttribute(&arena, 2));
UnknownSet d(a, b);
UnknownSet e(c, d);
EXPECT_THAT(d.unknown_attributes(),
UnorderedElementsAre(UnknownAttributeIs(1)));
EXPECT_THAT(
e.unknown_attributes(),
UnorderedElementsAre(UnknownAttributeIs(1), UnknownAttributeIs(2)));
}
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/internal/unknown_set.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/unknown_set_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
deff4997-313c-46ca-95fa-0d88650e66ce | cpp | google/cel-cpp | validation_result | checker/validation_result.h | checker/validation_result_test.cc | #ifndef THIRD_PARTY_CEL_CPP_CHECKER_VALIDATION_RESULT_H_
#define THIRD_PARTY_CEL_CPP_CHECKER_VALIDATION_RESULT_H_
#include <memory>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "checker/type_check_issue.h"
#include "common/ast.h"
namespace cel {
class ValidationResult {
public:
ValidationResult(std::unique_ptr<Ast> ast, std::vector<TypeCheckIssue> issues)
: ast_(std::move(ast)), issues_(std::move(issues)) {}
explicit ValidationResult(std::vector<TypeCheckIssue> issues)
: ast_(nullptr), issues_(std::move(issues)) {}
bool IsValid() const { return ast_ != nullptr; }
absl::Nullable<const Ast*> GetAst() const { return ast_.get(); }
absl::StatusOr<std::unique_ptr<Ast>> ReleaseAst() {
if (ast_ == nullptr) {
return absl::FailedPreconditionError(
"ValidationResult is empty. Check for TypeCheckIssues.");
}
return std::move(ast_);
}
absl::Span<const TypeCheckIssue> GetIssues() const { return issues_; }
private:
absl::Nullable<std::unique_ptr<Ast>> ast_;
std::vector<TypeCheckIssue> issues_;
};
}
#endif | #include "checker/validation_result.h"
#include <memory>
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "base/ast_internal/ast_impl.h"
#include "checker/type_check_issue.h"
#include "internal/testing.h"
namespace cel {
namespace {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::cel::ast_internal::AstImpl;
using ::testing::_;
using ::testing::IsNull;
using ::testing::NotNull;
using ::testing::SizeIs;
using Severity = TypeCheckIssue::Severity;
TEST(ValidationResultTest, IsValidWithAst) {
ValidationResult result(std::make_unique<AstImpl>(), {});
EXPECT_TRUE(result.IsValid());
EXPECT_THAT(result.GetAst(), NotNull());
EXPECT_THAT(result.ReleaseAst(), IsOkAndHolds(NotNull()));
}
TEST(ValidationResultTest, IsNotValidWithoutAst) {
ValidationResult result({});
EXPECT_FALSE(result.IsValid());
EXPECT_THAT(result.GetAst(), IsNull());
EXPECT_THAT(result.ReleaseAst(),
StatusIs(absl::StatusCode::kFailedPrecondition, _));
}
TEST(ValidationResultTest, GetIssues) {
ValidationResult result(
{TypeCheckIssue::CreateError({-1, -1}, "Issue1"),
TypeCheckIssue(Severity::kInformation, {-1, -1}, "Issue2")});
EXPECT_FALSE(result.IsValid());
ASSERT_THAT(result.GetIssues(), SizeIs(2));
EXPECT_THAT(result.GetIssues()[0].message(), "Issue1");
EXPECT_THAT(result.GetIssues()[0].severity(), Severity::kError);
EXPECT_THAT(result.GetIssues()[1].message(), "Issue2");
EXPECT_THAT(result.GetIssues()[1].severity(), Severity::kInformation);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/validation_result.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/validation_result_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
041b580d-8df5-43b4-8016-2a8c94f4e2bf | cpp | google/cel-cpp | function_adapter | base/function_adapter.h | runtime/internal/function_adapter_test.cc | #ifndef THIRD_PARTY_CEL_CPP_BASE_FUNCTION_ADAPTER_H_
#define THIRD_PARTY_CEL_CPP_BASE_FUNCTION_ADAPTER_H_
#include "runtime/function_adapter.h"
#endif | #include "runtime/internal/function_adapter.h"
#include <cstdint>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "common/casting.h"
#include "common/kind.h"
#include "common/memory.h"
#include "common/value.h"
#include "common/values/legacy_type_reflector.h"
#include "common/values/legacy_value_manager.h"
#include "internal/testing.h"
namespace cel::runtime_internal {
namespace {
using ::absl_testing::StatusIs;
static_assert(AdaptedKind<int64_t>() == Kind::kInt, "int adapts to int64_t");
static_assert(AdaptedKind<uint64_t>() == Kind::kUint,
"uint adapts to uint64_t");
static_assert(AdaptedKind<double>() == Kind::kDouble,
"double adapts to double");
static_assert(AdaptedKind<bool>() == Kind::kBool, "bool adapts to bool");
static_assert(AdaptedKind<absl::Time>() == Kind::kTimestamp,
"timestamp adapts to absl::Time");
static_assert(AdaptedKind<absl::Duration>() == Kind::kDuration,
"duration adapts to absl::Duration");
static_assert(AdaptedKind<Value>() == Kind::kAny, "any adapts to Value");
static_assert(AdaptedKind<StringValue>() == Kind::kString,
"string adapts to String");
static_assert(AdaptedKind<BytesValue>() == Kind::kBytes,
"bytes adapts to Bytes");
static_assert(AdaptedKind<StructValue>() == Kind::kStruct,
"struct adapts to StructValue");
static_assert(AdaptedKind<ListValue>() == Kind::kList,
"list adapts to ListValue");
static_assert(AdaptedKind<MapValue>() == Kind::kMap, "map adapts to MapValue");
static_assert(AdaptedKind<NullValue>() == Kind::kNullType,
"null adapts to NullValue");
static_assert(AdaptedKind<const Value&>() == Kind::kAny,
"any adapts to const Value&");
static_assert(AdaptedKind<const StringValue&>() == Kind::kString,
"string adapts to const String&");
static_assert(AdaptedKind<const BytesValue&>() == Kind::kBytes,
"bytes adapts to const Bytes&");
static_assert(AdaptedKind<const StructValue&>() == Kind::kStruct,
"struct adapts to const StructValue&");
static_assert(AdaptedKind<const ListValue&>() == Kind::kList,
"list adapts to const ListValue&");
static_assert(AdaptedKind<const MapValue&>() == Kind::kMap,
"map adapts to const MapValue&");
static_assert(AdaptedKind<const NullValue&>() == Kind::kNullType,
"null adapts to const NullValue&");
class ValueFactoryTestBase : public testing::Test {
public:
ValueFactoryTestBase()
: type_reflector_(),
value_manager_(MemoryManagerRef::ReferenceCounting(), type_reflector_) {
}
ValueFactory& value_factory() { return value_manager_; }
private:
common_internal::LegacyTypeReflector type_reflector_;
common_internal::LegacyValueManager value_manager_;
};
class HandleToAdaptedVisitorTest : public ValueFactoryTestBase {};
TEST_F(HandleToAdaptedVisitorTest, Int) {
Value v = value_factory().CreateIntValue(10);
int64_t out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out, 10);
}
TEST_F(HandleToAdaptedVisitorTest, IntWrongKind) {
Value v = value_factory().CreateUintValue(10);
int64_t out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected int value"));
}
TEST_F(HandleToAdaptedVisitorTest, Uint) {
Value v = value_factory().CreateUintValue(11);
uint64_t out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out, 11);
}
TEST_F(HandleToAdaptedVisitorTest, UintWrongKind) {
Value v = value_factory().CreateIntValue(11);
uint64_t out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected uint value"));
}
TEST_F(HandleToAdaptedVisitorTest, Double) {
Value v = value_factory().CreateDoubleValue(12.0);
double out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out, 12.0);
}
TEST_F(HandleToAdaptedVisitorTest, DoubleWrongKind) {
Value v = value_factory().CreateUintValue(10);
double out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected double value"));
}
TEST_F(HandleToAdaptedVisitorTest, Bool) {
Value v = value_factory().CreateBoolValue(false);
bool out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out, false);
}
TEST_F(HandleToAdaptedVisitorTest, BoolWrongKind) {
Value v = value_factory().CreateUintValue(10);
bool out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected bool value"));
}
TEST_F(HandleToAdaptedVisitorTest, Timestamp) {
ASSERT_OK_AND_ASSIGN(Value v, value_factory().CreateTimestampValue(
absl::UnixEpoch() + absl::Seconds(1)));
absl::Time out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out, absl::UnixEpoch() + absl::Seconds(1));
}
TEST_F(HandleToAdaptedVisitorTest, TimestampWrongKind) {
Value v = value_factory().CreateUintValue(10);
absl::Time out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected timestamp value"));
}
TEST_F(HandleToAdaptedVisitorTest, Duration) {
ASSERT_OK_AND_ASSIGN(Value v,
value_factory().CreateDurationValue(absl::Seconds(5)));
absl::Duration out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out, absl::Seconds(5));
}
TEST_F(HandleToAdaptedVisitorTest, DurationWrongKind) {
Value v = value_factory().CreateUintValue(10);
absl::Duration out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected duration value"));
}
TEST_F(HandleToAdaptedVisitorTest, String) {
ASSERT_OK_AND_ASSIGN(Value v, value_factory().CreateStringValue("string"));
StringValue out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out.ToString(), "string");
}
TEST_F(HandleToAdaptedVisitorTest, StringWrongKind) {
Value v = value_factory().CreateUintValue(10);
StringValue out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected string value"));
}
TEST_F(HandleToAdaptedVisitorTest, Bytes) {
ASSERT_OK_AND_ASSIGN(Value v, value_factory().CreateBytesValue("bytes"));
BytesValue out;
ASSERT_OK(HandleToAdaptedVisitor{v}(&out));
EXPECT_EQ(out.ToString(), "bytes");
}
TEST_F(HandleToAdaptedVisitorTest, BytesWrongKind) {
Value v = value_factory().CreateUintValue(10);
BytesValue out;
EXPECT_THAT(
HandleToAdaptedVisitor{v}(&out),
StatusIs(absl::StatusCode::kInvalidArgument, "expected bytes value"));
}
class AdaptedToHandleVisitorTest : public ValueFactoryTestBase {};
TEST_F(AdaptedToHandleVisitorTest, Int) {
int64_t value = 10;
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 10);
}
TEST_F(AdaptedToHandleVisitorTest, Double) {
double value = 10;
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<DoubleValue>(result));
EXPECT_EQ(Cast<DoubleValue>(result).NativeValue(), 10.0);
}
TEST_F(AdaptedToHandleVisitorTest, Uint) {
uint64_t value = 10;
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<UintValue>(result));
EXPECT_EQ(Cast<UintValue>(result).NativeValue(), 10);
}
TEST_F(AdaptedToHandleVisitorTest, Bool) {
bool value = true;
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<BoolValue>(result));
EXPECT_EQ(Cast<BoolValue>(result).NativeValue(), true);
}
TEST_F(AdaptedToHandleVisitorTest, Timestamp) {
absl::Time value = absl::UnixEpoch() + absl::Seconds(10);
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<TimestampValue>(result));
EXPECT_EQ(Cast<TimestampValue>(result).NativeValue(),
absl::UnixEpoch() + absl::Seconds(10));
}
TEST_F(AdaptedToHandleVisitorTest, Duration) {
absl::Duration value = absl::Seconds(5);
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<DurationValue>(result));
EXPECT_EQ(Cast<DurationValue>(result).NativeValue(), absl::Seconds(5));
}
TEST_F(AdaptedToHandleVisitorTest, String) {
ASSERT_OK_AND_ASSIGN(StringValue value,
value_factory().CreateStringValue("str"));
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<StringValue>(result));
EXPECT_EQ(Cast<StringValue>(result).ToString(), "str");
}
TEST_F(AdaptedToHandleVisitorTest, Bytes) {
ASSERT_OK_AND_ASSIGN(BytesValue value,
value_factory().CreateBytesValue("bytes"));
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<BytesValue>(result));
EXPECT_EQ(Cast<BytesValue>(result).ToString(), "bytes");
}
TEST_F(AdaptedToHandleVisitorTest, StatusOrValue) {
absl::StatusOr<int64_t> value = 10;
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(value));
ASSERT_TRUE(InstanceOf<IntValue>(result));
EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 10);
}
TEST_F(AdaptedToHandleVisitorTest, StatusOrError) {
absl::StatusOr<int64_t> value = absl::InternalError("test_error");
EXPECT_THAT(AdaptedToHandleVisitor{}(value).status(),
StatusIs(absl::StatusCode::kInternal, "test_error"));
}
TEST_F(AdaptedToHandleVisitorTest, Any) {
auto handle =
value_factory().CreateErrorValue(absl::InternalError("test_error"));
ASSERT_OK_AND_ASSIGN(auto result, AdaptedToHandleVisitor{}(handle));
ASSERT_TRUE(InstanceOf<ErrorValue>(result));
EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(),
StatusIs(absl::StatusCode::kInternal, "test_error"));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/function_adapter.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/internal/function_adapter_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
09a57f31-d339-4157-a72f-009e87e78a55 | cpp | google/cel-cpp | issue_collector | runtime/internal/issue_collector.h | runtime/internal/issue_collector_test.cc | #ifndef THIRD_PARTY_CEL_CPP_RUNTIME_INTERNAL_ISSUE_COLLECTOR_H_
#define THIRD_PARTY_CEL_CPP_RUNTIME_INTERNAL_ISSUE_COLLECTOR_H_
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/types/span.h"
#include "runtime/runtime_issue.h"
namespace cel::runtime_internal {
class IssueCollector {
public:
explicit IssueCollector(RuntimeIssue::Severity severity_limit)
: severity_limit_(severity_limit) {}
IssueCollector(const IssueCollector&) = delete;
IssueCollector& operator=(const IssueCollector&) = delete;
IssueCollector(IssueCollector&&) = default;
IssueCollector& operator=(IssueCollector&&) = default;
absl::Status AddIssue(RuntimeIssue issue) {
issues_.push_back(std::move(issue));
if (issues_.back().severity() >= severity_limit_) {
return issues_.back().ToStatus();
}
return absl::OkStatus();
}
absl::Span<const RuntimeIssue> issues() const { return issues_; }
std::vector<RuntimeIssue> ExtractIssues() { return std::move(issues_); }
private:
RuntimeIssue::Severity severity_limit_;
std::vector<RuntimeIssue> issues_;
};
}
#endif | #include "runtime/internal/issue_collector.h"
#include "absl/status/status.h"
#include "internal/testing.h"
#include "runtime/runtime_issue.h"
namespace cel::runtime_internal {
namespace {
using ::absl_testing::StatusIs;
using ::testing::ElementsAre;
using ::testing::Truly;
template <typename Matcher, typename T>
bool ApplyMatcher(Matcher m, const T& t) {
return static_cast<testing::Matcher<T>>(m).Matches(t);
}
TEST(IssueCollector, CollectsIssues) {
IssueCollector issue_collector(RuntimeIssue::Severity::kError);
EXPECT_THAT(issue_collector.AddIssue(
RuntimeIssue::CreateError(absl::InvalidArgumentError("e1"))),
StatusIs(absl::StatusCode::kInvalidArgument, "e1"));
ASSERT_OK(issue_collector.AddIssue(RuntimeIssue::CreateWarning(
absl::InvalidArgumentError("w1"),
RuntimeIssue::ErrorCode::kNoMatchingOverload)));
EXPECT_THAT(
issue_collector.issues(),
ElementsAre(
Truly([](const RuntimeIssue& issue) {
return issue.severity() == RuntimeIssue::Severity::kError &&
issue.error_code() == RuntimeIssue::ErrorCode::kOther &&
ApplyMatcher(
StatusIs(absl::StatusCode::kInvalidArgument, "e1"),
issue.ToStatus());
}),
Truly([](const RuntimeIssue& issue) {
return issue.severity() == RuntimeIssue::Severity::kWarning &&
issue.error_code() ==
RuntimeIssue::ErrorCode::kNoMatchingOverload &&
ApplyMatcher(
StatusIs(absl::StatusCode::kInvalidArgument, "w1"),
issue.ToStatus());
})));
}
TEST(IssueCollector, ReturnsStatusAtLimit) {
IssueCollector issue_collector(RuntimeIssue::Severity::kWarning);
EXPECT_THAT(issue_collector.AddIssue(
RuntimeIssue::CreateError(absl::InvalidArgumentError("e1"))),
StatusIs(absl::StatusCode::kInvalidArgument, "e1"));
EXPECT_THAT(issue_collector.AddIssue(RuntimeIssue::CreateWarning(
absl::InvalidArgumentError("w1"),
RuntimeIssue::ErrorCode::kNoMatchingOverload)),
StatusIs(absl::StatusCode::kInvalidArgument, "w1"));
EXPECT_THAT(
issue_collector.issues(),
ElementsAre(
Truly([](const RuntimeIssue& issue) {
return issue.severity() == RuntimeIssue::Severity::kError &&
issue.error_code() == RuntimeIssue::ErrorCode::kOther &&
ApplyMatcher(
StatusIs(absl::StatusCode::kInvalidArgument, "e1"),
issue.ToStatus());
}),
Truly([](const RuntimeIssue& issue) {
return issue.severity() == RuntimeIssue::Severity::kWarning &&
issue.error_code() ==
RuntimeIssue::ErrorCode::kNoMatchingOverload &&
ApplyMatcher(
StatusIs(absl::StatusCode::kInvalidArgument, "w1"),
issue.ToStatus());
})));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/internal/issue_collector.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/internal/issue_collector_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
781f69a4-78b6-4034-b79d-a1bec23c3e92 | cpp | google/cel-cpp | align | internal/align.h | internal/align_test.cc | #ifndef THIRD_PARTY_CEL_CPP_INTERNAL_ALIGN_H_
#define THIRD_PARTY_CEL_CPP_INTERNAL_ALIGN_H_
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include "absl/base/casts.h"
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/numeric/bits.h"
namespace cel::internal {
template <typename T>
constexpr std::enable_if_t<
std::conjunction_v<std::is_integral<T>, std::is_unsigned<T>>, T>
AlignmentMask(T alignment) {
ABSL_ASSERT(absl::has_single_bit(alignment));
return alignment - T{1};
}
template <typename T>
std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_unsigned<T>>,
T>
AlignDown(T x, size_t alignment) {
ABSL_ASSERT(absl::has_single_bit(alignment));
#if ABSL_HAVE_BUILTIN(__builtin_align_up)
return __builtin_align_down(x, alignment);
#else
using C = std::common_type_t<T, size_t>;
return static_cast<T>(static_cast<C>(x) &
~AlignmentMask(static_cast<C>(alignment)));
#endif
}
template <typename T>
std::enable_if_t<std::is_pointer_v<T>, T> AlignDown(T x, size_t alignment) {
return absl::bit_cast<T>(AlignDown(absl::bit_cast<uintptr_t>(x), alignment));
}
template <typename T>
std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_unsigned<T>>,
T>
AlignUp(T x, size_t alignment) {
ABSL_ASSERT(absl::has_single_bit(alignment));
#if ABSL_HAVE_BUILTIN(__builtin_align_up)
return __builtin_align_up(x, alignment);
#else
using C = std::common_type_t<T, size_t>;
return static_cast<T>(AlignDown(
static_cast<C>(x) + AlignmentMask(static_cast<C>(alignment)), alignment));
#endif
}
template <typename T>
std::enable_if_t<std::is_pointer_v<T>, T> AlignUp(T x, size_t alignment) {
return absl::bit_cast<T>(AlignUp(absl::bit_cast<uintptr_t>(x), alignment));
}
template <typename T>
constexpr std::enable_if_t<
std::conjunction_v<std::is_integral<T>, std::is_unsigned<T>>, bool>
IsAligned(T x, size_t alignment) {
ABSL_ASSERT(absl::has_single_bit(alignment));
#if ABSL_HAVE_BUILTIN(__builtin_is_aligned)
return __builtin_is_aligned(x, alignment);
#else
using C = std::common_type_t<T, size_t>;
return (static_cast<C>(x) & AlignmentMask(static_cast<C>(alignment))) == C{0};
#endif
}
template <typename T>
std::enable_if_t<std::is_pointer_v<T>, bool> IsAligned(T x, size_t alignment) {
return IsAligned(absl::bit_cast<uintptr_t>(x), alignment);
}
}
#endif | #include "internal/align.h"
#include <cstddef>
#include <cstdint>
#include "internal/testing.h"
namespace cel::internal {
namespace {
TEST(AlignmentMask, Masks) {
EXPECT_EQ(AlignmentMask(size_t{1}), size_t{0});
EXPECT_EQ(AlignmentMask(size_t{2}), size_t{1});
EXPECT_EQ(AlignmentMask(size_t{4}), size_t{3});
}
TEST(AlignDown, Aligns) {
EXPECT_EQ(AlignDown(uintptr_t{3}, 4), 0);
EXPECT_EQ(AlignDown(uintptr_t{0}, 4), 0);
EXPECT_EQ(AlignDown(uintptr_t{5}, 4), 4);
EXPECT_EQ(AlignDown(uintptr_t{4}, 4), 4);
uint64_t val = 0;
EXPECT_EQ(AlignDown(&val, alignof(val)), &val);
}
TEST(AlignUp, Aligns) {
EXPECT_EQ(AlignUp(uintptr_t{0}, 4), 0);
EXPECT_EQ(AlignUp(uintptr_t{3}, 4), 4);
EXPECT_EQ(AlignUp(uintptr_t{5}, 4), 8);
uint64_t val = 0;
EXPECT_EQ(AlignUp(&val, alignof(val)), &val);
}
TEST(IsAligned, Aligned) {
EXPECT_TRUE(IsAligned(uintptr_t{0}, 4));
EXPECT_TRUE(IsAligned(uintptr_t{4}, 4));
EXPECT_FALSE(IsAligned(uintptr_t{3}, 4));
EXPECT_FALSE(IsAligned(uintptr_t{5}, 4));
uint64_t val = 0;
EXPECT_TRUE(IsAligned(&val, alignof(val)));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/align.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/align_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
47921c4c-501b-4155-a145-ae15dcab82ac | cpp | google/cel-cpp | message_type_name | internal/message_type_name.h | internal/message_type_name_test.cc | #ifndef THIRD_PARTY_CEL_CPP_INTERNAL_MESSAGE_TYPE_NAME_H_
#define THIRD_PARTY_CEL_CPP_INTERNAL_MESSAGE_TYPE_NAME_H_
#include <string>
#include <type_traits>
#include "absl/base/no_destructor.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/message.h"
#include "google/protobuf/message_lite.h"
namespace cel::internal {
template <typename T>
std::enable_if_t<
std::conjunction_v<std::is_base_of<google::protobuf::MessageLite, T>,
std::negation<std::is_base_of<google::protobuf::Message, T>>>,
absl::string_view>
MessageTypeNameFor() {
static_assert(!std::is_const_v<T>, "T must not be const qualified");
static_assert(!std::is_volatile_v<T>, "T must not be volatile qualified");
static_assert(!std::is_reference_v<T>, "T must not be a reference");
static const absl::NoDestructor<std::string> kTypeName(T().GetTypeName());
return *kTypeName;
}
template <typename T>
std::enable_if_t<std::is_base_of_v<google::protobuf::Message, T>, absl::string_view>
MessageTypeNameFor() {
static_assert(!std::is_const_v<T>, "T must not be const qualified");
static_assert(!std::is_volatile_v<T>, "T must not be volatile qualified");
static_assert(!std::is_reference_v<T>, "T must not be a reference");
return T::descriptor()->full_name();
}
}
#endif | #include "internal/message_type_name.h"
#include "google/protobuf/any.pb.h"
#include "internal/testing.h"
namespace cel::internal {
namespace {
TEST(MessageTypeNameFor, Generated) {
EXPECT_EQ(MessageTypeNameFor<google::protobuf::Any>(), "google.protobuf.Any");
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/message_type_name.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/message_type_name_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
61403832-c7b7-416d-abcd-da425f14f1b7 | cpp | google/cel-cpp | to_address | internal/to_address.h | internal/to_address_test.cc | #ifndef THIRD_PARTY_CEL_CPP_INTERNAL_TO_ADDRESS_H_
#define THIRD_PARTY_CEL_CPP_INTERNAL_TO_ADDRESS_H_
#include <memory>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/meta/type_traits.h"
namespace cel::internal {
#if defined(__cpp_lib_to_address) && __cpp_lib_to_address >= 201711L
using std::to_address;
#else
template <typename T>
constexpr T* to_address(T* ptr) noexcept {
static_assert(!std::is_function<T>::value, "T must not be a function");
return ptr;
}
template <typename T, typename = void>
struct PointerTraitsToAddress {
static constexpr auto Dispatch(
const T& p ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept {
return internal::to_address(p.operator->());
}
};
template <typename T>
struct PointerTraitsToAddress<
T, absl::void_t<decltype(std::pointer_traits<T>::to_address(
std::declval<const T&>()))> > {
static constexpr auto Dispatch(
const T& p ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept {
return std::pointer_traits<T>::to_address(p);
}
};
template <typename T>
constexpr auto to_address(const T& ptr ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept {
return PointerTraitsToAddress<T>::Dispatch(ptr);
}
#endif
}
#endif | #include "internal/to_address.h"
#include <memory>
#include "internal/testing.h"
namespace cel {
namespace {
TEST(ToAddress, RawPointer) {
char c;
EXPECT_EQ(internal::to_address(&c), &c);
}
struct ImplicitFancyPointer {
using element_type = char;
char* operator->() const { return ptr; }
char* ptr;
};
struct ExplicitFancyPointer {
char* ptr;
};
}
}
namespace std {
template <>
struct pointer_traits<cel::ExplicitFancyPointer> : pointer_traits<char*> {
static constexpr char* to_address(
const cel::ExplicitFancyPointer& efp) noexcept {
return efp.ptr;
}
};
}
namespace cel {
namespace {
TEST(ToAddress, FancyPointerNoPointerTraits) {
char c;
ImplicitFancyPointer ip{&c};
EXPECT_EQ(internal::to_address(ip), &c);
}
TEST(ToAddress, FancyPointerWithPointerTraits) {
char c;
ExplicitFancyPointer ip{&c};
EXPECT_EQ(internal::to_address(ip), &c);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/to_address.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/to_address_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
721cbde5-7ea7-4461-a9c7-5f9a290fb85e | cpp | google/cel-cpp | copy_on_write | internal/copy_on_write.h | internal/copy_on_write_test.cc | #ifndef THIRD_PARTY_CEL_CPP_INTERNAL_COPY_ON_WRITE_H_
#define THIRD_PARTY_CEL_CPP_INTERNAL_COPY_ON_WRITE_H_
#include <algorithm>
#include <atomic>
#include <memory>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/log/absl_check.h"
namespace cel::internal {
template <typename T>
class ABSL_ATTRIBUTE_TRIVIAL_ABI CopyOnWrite final {
private:
struct Rep final {
Rep() = default;
template <typename... Args,
typename = std::enable_if_t<std::is_constructible_v<T, Args...>>>
explicit Rep(Args&&... args) : value(std::forward<Args>(value)...) {}
Rep(const Rep&) = delete;
Rep(Rep&&) = delete;
Rep& operator=(const Rep&) = delete;
Rep& operator=(Rep&&) = delete;
std::atomic<int32_t> refs = 1;
T value;
void Ref() {
const auto count = refs.fetch_add(1, std::memory_order_relaxed);
ABSL_DCHECK_GT(count, 0);
}
void Unref() {
const auto count = refs.fetch_sub(1, std::memory_order_acq_rel);
ABSL_DCHECK_GT(count, 0);
if (count == 1) {
delete this;
}
}
bool Unique() const {
const auto count = refs.load(std::memory_order_acquire);
ABSL_DCHECK_GT(count, 0);
return count == 1;
}
};
public:
static_assert(std::is_copy_constructible_v<T>,
"T must be copy constructible");
static_assert(std::is_destructible_v<T>, "T must be destructible");
template <typename = std::enable_if_t<std::is_default_constructible_v<T>>>
CopyOnWrite() : rep_(new Rep()) {}
CopyOnWrite(const CopyOnWrite<T>& other) : rep_(other.rep_) { rep_->Ref(); }
CopyOnWrite(CopyOnWrite<T>&& other) noexcept : rep_(other.rep_) {
other.rep_ = nullptr;
}
~CopyOnWrite() {
if (rep_ != nullptr) {
rep_->Unref();
}
}
CopyOnWrite<T>& operator=(const CopyOnWrite<T>& other) {
ABSL_DCHECK_NE(this, std::addressof(other));
other.rep_->Ref();
rep_->Unref();
rep_ = other.rep_;
return *this;
}
CopyOnWrite<T>& operator=(CopyOnWrite<T>&& other) noexcept {
ABSL_DCHECK_NE(this, std::addressof(other));
rep_->Unref();
rep_ = other.rep_;
other.rep_ = nullptr;
return *this;
}
T& mutable_get() ABSL_ATTRIBUTE_LIFETIME_BOUND {
ABSL_DCHECK(rep_ != nullptr) << "Object in moved-from state.";
if (ABSL_PREDICT_FALSE(!rep_->Unique())) {
auto* rep = new Rep(static_cast<const T&>(rep_->value));
rep_->Unref();
rep_ = rep;
}
return rep_->value;
}
const T& get() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
ABSL_DCHECK(rep_ != nullptr) << "Object in moved-from state.";
return rep_->value;
}
void swap(CopyOnWrite<T>& other) noexcept {
using std::swap;
swap(rep_, other.rep_);
}
private:
Rep* rep_;
};
template <typename T>
void swap(CopyOnWrite<T>& lhs, CopyOnWrite<T>& rhs) noexcept {
lhs.swap(rhs);
}
}
#endif | #include "internal/copy_on_write.h"
#include <cstdint>
#include "internal/testing.h"
namespace cel::internal {
namespace {
TEST(CopyOnWrite, Basic) {
CopyOnWrite<int32_t> original;
EXPECT_EQ(&original.mutable_get(), &original.get());
{
auto duplicate = original;
EXPECT_EQ(&duplicate.get(), &original.get());
EXPECT_NE(&duplicate.mutable_get(), &original.get());
}
EXPECT_EQ(&original.mutable_get(), &original.get());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/copy_on_write.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/copy_on_write_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
b804e38d-6c4c-4a92-943d-a3e71a5cf3d9 | cpp | google/cel-cpp | number | internal/number.h | internal/number_test.cc | #ifndef THIRD_PARTY_CEL_CPP_INTERNAL_NUMBER_H_
#define THIRD_PARTY_CEL_CPP_INTERNAL_NUMBER_H_
#include <cmath>
#include <cstdint>
#include <limits>
#include "absl/types/variant.h"
namespace cel::internal {
constexpr int64_t kInt64Max = std::numeric_limits<int64_t>::max();
constexpr int64_t kInt64Min = std::numeric_limits<int64_t>::lowest();
constexpr uint64_t kUint64Max = std::numeric_limits<uint64_t>::max();
constexpr uint64_t kUintToIntMax = static_cast<uint64_t>(kInt64Max);
constexpr double kDoubleToIntMax = static_cast<double>(kInt64Max);
constexpr double kDoubleToIntMin = static_cast<double>(kInt64Min);
constexpr double kDoubleToUintMax = static_cast<double>(kUint64Max);
template <typename T>
constexpr int RoundingError() {
return 1 << (std::numeric_limits<T>::digits -
std::numeric_limits<double>::digits - 1);
}
constexpr double kMaxDoubleRepresentableAsInt =
static_cast<double>(kInt64Max - RoundingError<int64_t>());
constexpr double kMaxDoubleRepresentableAsUint =
static_cast<double>(kUint64Max - RoundingError<uint64_t>());
#define CEL_ABSL_VISIT_CONSTEXPR
using NumberVariant = absl::variant<double, uint64_t, int64_t>;
enum class ComparisonResult {
kLesser,
kEqual,
kGreater,
kNanInequal
};
constexpr ComparisonResult Invert(ComparisonResult result) {
switch (result) {
case ComparisonResult::kLesser:
return ComparisonResult::kGreater;
case ComparisonResult::kGreater:
return ComparisonResult::kLesser;
case ComparisonResult::kEqual:
return ComparisonResult::kEqual;
case ComparisonResult::kNanInequal:
return ComparisonResult::kNanInequal;
}
}
template <typename OutType>
struct ConversionVisitor {
template <typename InType>
constexpr OutType operator()(InType v) {
return static_cast<OutType>(v);
}
};
template <typename T>
constexpr ComparisonResult Compare(T a, T b) {
return (a > b) ? ComparisonResult::kGreater
: (a == b) ? ComparisonResult::kEqual
: ComparisonResult::kLesser;
}
constexpr ComparisonResult DoubleCompare(double a, double b) {
if (!(a == a) || !(b == b)) {
return ComparisonResult::kNanInequal;
}
return Compare(a, b);
}
struct DoubleCompareVisitor {
constexpr explicit DoubleCompareVisitor(double v) : v(v) {}
constexpr ComparisonResult operator()(double other) const {
return DoubleCompare(v, other);
}
constexpr ComparisonResult operator()(uint64_t other) const {
if (v > kDoubleToUintMax) {
return ComparisonResult::kGreater;
} else if (v < 0) {
return ComparisonResult::kLesser;
} else {
return DoubleCompare(v, static_cast<double>(other));
}
}
constexpr ComparisonResult operator()(int64_t other) const {
if (v > kDoubleToIntMax) {
return ComparisonResult::kGreater;
} else if (v < kDoubleToIntMin) {
return ComparisonResult::kLesser;
} else {
return DoubleCompare(v, static_cast<double>(other));
}
}
double v;
};
struct UintCompareVisitor {
constexpr explicit UintCompareVisitor(uint64_t v) : v(v) {}
constexpr ComparisonResult operator()(double other) const {
return Invert(DoubleCompareVisitor(other)(v));
}
constexpr ComparisonResult operator()(uint64_t other) const {
return Compare(v, other);
}
constexpr ComparisonResult operator()(int64_t other) const {
if (v > kUintToIntMax || other < 0) {
return ComparisonResult::kGreater;
} else {
return Compare(v, static_cast<uint64_t>(other));
}
}
uint64_t v;
};
struct IntCompareVisitor {
constexpr explicit IntCompareVisitor(int64_t v) : v(v) {}
constexpr ComparisonResult operator()(double other) {
return Invert(DoubleCompareVisitor(other)(v));
}
constexpr ComparisonResult operator()(uint64_t other) {
return Invert(UintCompareVisitor(other)(v));
}
constexpr ComparisonResult operator()(int64_t other) {
return Compare(v, other);
}
int64_t v;
};
struct CompareVisitor {
explicit constexpr CompareVisitor(NumberVariant rhs) : rhs(rhs) {}
CEL_ABSL_VISIT_CONSTEXPR ComparisonResult operator()(double v) {
return absl::visit(DoubleCompareVisitor(v), rhs);
}
CEL_ABSL_VISIT_CONSTEXPR ComparisonResult operator()(uint64_t v) {
return absl::visit(UintCompareVisitor(v), rhs);
}
CEL_ABSL_VISIT_CONSTEXPR ComparisonResult operator()(int64_t v) {
return absl::visit(IntCompareVisitor(v), rhs);
}
NumberVariant rhs;
};
struct LosslessConvertibleToIntVisitor {
constexpr bool operator()(double value) const {
return value >= kDoubleToIntMin && value <= kMaxDoubleRepresentableAsInt &&
value == static_cast<double>(static_cast<int64_t>(value));
}
constexpr bool operator()(uint64_t value) const {
return value <= kUintToIntMax;
}
constexpr bool operator()(int64_t value) const { return true; }
};
struct LosslessConvertibleToUintVisitor {
constexpr bool operator()(double value) const {
return value >= 0 && value <= kMaxDoubleRepresentableAsUint &&
value == static_cast<double>(static_cast<uint64_t>(value));
}
constexpr bool operator()(uint64_t value) const { return true; }
constexpr bool operator()(int64_t value) const { return value >= 0; }
};
class Number {
public:
static constexpr Number FromInt64(int64_t value) { return Number(value); }
static constexpr Number FromUint64(uint64_t value) { return Number(value); }
static constexpr Number FromDouble(double value) { return Number(value); }
constexpr explicit Number(double double_value) : value_(double_value) {}
constexpr explicit Number(int64_t int_value) : value_(int_value) {}
constexpr explicit Number(uint64_t uint_value) : value_(uint_value) {}
CEL_ABSL_VISIT_CONSTEXPR double AsDouble() const {
return absl::visit(internal::ConversionVisitor<double>(), value_);
}
CEL_ABSL_VISIT_CONSTEXPR int64_t AsInt() const {
return absl::visit(internal::ConversionVisitor<int64_t>(), value_);
}
CEL_ABSL_VISIT_CONSTEXPR uint64_t AsUint() const {
return absl::visit(internal::ConversionVisitor<uint64_t>(), value_);
}
CEL_ABSL_VISIT_CONSTEXPR bool LosslessConvertibleToInt() const {
return absl::visit(internal::LosslessConvertibleToIntVisitor(), value_);
}
CEL_ABSL_VISIT_CONSTEXPR bool LosslessConvertibleToUint() const {
return absl::visit(internal::LosslessConvertibleToUintVisitor(), value_);
}
CEL_ABSL_VISIT_CONSTEXPR bool operator<(Number other) const {
return Compare(other) == internal::ComparisonResult::kLesser;
}
CEL_ABSL_VISIT_CONSTEXPR bool operator<=(Number other) const {
internal::ComparisonResult cmp = Compare(other);
return cmp != internal::ComparisonResult::kGreater &&
cmp != internal::ComparisonResult::kNanInequal;
}
CEL_ABSL_VISIT_CONSTEXPR bool operator>(Number other) const {
return Compare(other) == internal::ComparisonResult::kGreater;
}
CEL_ABSL_VISIT_CONSTEXPR bool operator>=(Number other) const {
internal::ComparisonResult cmp = Compare(other);
return cmp != internal::ComparisonResult::kLesser &&
cmp != internal::ComparisonResult::kNanInequal;
}
CEL_ABSL_VISIT_CONSTEXPR bool operator==(Number other) const {
return Compare(other) == internal::ComparisonResult::kEqual;
}
CEL_ABSL_VISIT_CONSTEXPR bool operator!=(Number other) const {
return Compare(other) != internal::ComparisonResult::kEqual;
}
template <typename T, typename Op>
T visit(Op&& op) const {
return absl::visit(std::forward<Op>(op), value_);
}
private:
internal::NumberVariant value_;
CEL_ABSL_VISIT_CONSTEXPR internal::ComparisonResult Compare(
Number other) const {
return absl::visit(internal::CompareVisitor(other.value_), value_);
}
};
}
#endif | #include "internal/number.h"
#include <cstdint>
#include <limits>
#include "internal/testing.h"
namespace cel::internal {
namespace {
constexpr double kNan = std::numeric_limits<double>::quiet_NaN();
constexpr double kInfinity = std::numeric_limits<double>::infinity();
TEST(Number, Basic) {
EXPECT_GT(Number(1.1), Number::FromInt64(1));
EXPECT_LT(Number::FromUint64(1), Number(1.1));
EXPECT_EQ(Number(1.1), Number(1.1));
EXPECT_EQ(Number::FromUint64(1), Number::FromUint64(1));
EXPECT_EQ(Number::FromInt64(1), Number::FromUint64(1));
EXPECT_GT(Number::FromUint64(1), Number::FromInt64(-1));
EXPECT_EQ(Number::FromInt64(-1), Number::FromInt64(-1));
}
TEST(Number, Conversions) {
EXPECT_TRUE(Number::FromDouble(1.0).LosslessConvertibleToInt());
EXPECT_TRUE(Number::FromDouble(1.0).LosslessConvertibleToUint());
EXPECT_FALSE(Number::FromDouble(1.1).LosslessConvertibleToInt());
EXPECT_FALSE(Number::FromDouble(1.1).LosslessConvertibleToUint());
EXPECT_TRUE(Number::FromDouble(-1.0).LosslessConvertibleToInt());
EXPECT_FALSE(Number::FromDouble(-1.0).LosslessConvertibleToUint());
EXPECT_TRUE(Number::FromDouble(kDoubleToIntMin).LosslessConvertibleToInt());
EXPECT_FALSE(Number::FromDouble(kMaxDoubleRepresentableAsUint +
RoundingError<uint64_t>())
.LosslessConvertibleToUint());
EXPECT_FALSE(Number::FromDouble(kMaxDoubleRepresentableAsInt +
RoundingError<int64_t>())
.LosslessConvertibleToInt());
EXPECT_FALSE(
Number::FromDouble(kDoubleToIntMin - 1025).LosslessConvertibleToInt());
EXPECT_EQ(Number::FromInt64(1).AsUint(), 1u);
EXPECT_EQ(Number::FromUint64(1).AsInt(), 1);
EXPECT_EQ(Number::FromDouble(1.0).AsUint(), 1);
EXPECT_EQ(Number::FromDouble(1.0).AsInt(), 1);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/number.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/number_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
4a05b0eb-d44a-4a63-8905-bc98c7271120 | cpp | google/cel-cpp | benchmark | internal/benchmark.h | eval/tests/benchmark_test.cc | #ifndef THIRD_PARTY_CEL_CPP_INTERNAL_BENCHMARK_H_
#define THIRD_PARTY_CEL_CPP_INTERNAL_BENCHMARK_H_
#include "benchmark/benchmark.h"
#endif | #include "internal/benchmark.h"
#include <string>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/rpc/context/attribute_context.pb.h"
#include "google/protobuf/text_format.h"
#include "absl/base/attributes.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/node_hash_set.h"
#include "absl/flags/flag.h"
#include "absl/strings/match.h"
#include "eval/public/activation.h"
#include "eval/public/builtin_func_registrar.h"
#include "eval/public/cel_expr_builder_factory.h"
#include "eval/public/cel_expression.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/tests/request_context.pb.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
#include "parser/parser.h"
#include "google/protobuf/arena.h"
ABSL_FLAG(bool, enable_optimizations, false, "enable const folding opt");
ABSL_FLAG(bool, enable_recursive_planning, false, "enable recursive planning");
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
using ::google::api::expr::v1alpha1::Expr;
using ::google::api::expr::v1alpha1::ParsedExpr;
using ::google::api::expr::v1alpha1::SourceInfo;
using ::google::rpc::context::AttributeContext;
InterpreterOptions GetOptions(google::protobuf::Arena& arena) {
InterpreterOptions options;
if (absl::GetFlag(FLAGS_enable_optimizations)) {
options.constant_arena = &arena;
options.constant_folding = true;
}
if (absl::GetFlag(FLAGS_enable_recursive_planning)) {
options.max_recursion_depth = -1;
}
return options;
}
static void BM_Eval(benchmark::State& state) {
google::protobuf::Arena arena;
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
int len = state.range(0);
Expr root_expr;
Expr* cur_expr = &root_expr;
for (int i = 0; i < len; i++) {
Expr::Call* call = cur_expr->mutable_call_expr();
call->set_function("_+_");
call->add_args()->mutable_const_expr()->set_int64_value(1);
cur_expr = call->add_args();
}
cur_expr->mutable_const_expr()->set_int64_value(1);
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&root_expr, &source_info));
for (auto _ : state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsInt64());
ASSERT_TRUE(result.Int64OrDie() == len + 1);
}
}
BENCHMARK(BM_Eval)->Range(1, 10000);
absl::Status EmptyCallback(int64_t expr_id, const CelValue& value,
google::protobuf::Arena* arena) {
return absl::OkStatus();
}
static void BM_Eval_Trace(benchmark::State& state) {
google::protobuf::Arena arena;
InterpreterOptions options = GetOptions(arena);
options.enable_recursive_tracing = true;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
int len = state.range(0);
Expr root_expr;
Expr* cur_expr = &root_expr;
for (int i = 0; i < len; i++) {
Expr::Call* call = cur_expr->mutable_call_expr();
call->set_function("_+_");
call->add_args()->mutable_const_expr()->set_int64_value(1);
cur_expr = call->add_args();
}
cur_expr->mutable_const_expr()->set_int64_value(1);
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&root_expr, &source_info));
for (auto _ : state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Trace(activation, &arena, EmptyCallback));
ASSERT_TRUE(result.IsInt64());
ASSERT_TRUE(result.Int64OrDie() == len + 1);
}
}
BENCHMARK(BM_Eval_Trace)->Range(1, 10000);
static void BM_EvalString(benchmark::State& state) {
google::protobuf::Arena arena;
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
int len = state.range(0);
Expr root_expr;
Expr* cur_expr = &root_expr;
for (int i = 0; i < len; i++) {
Expr::Call* call = cur_expr->mutable_call_expr();
call->set_function("_+_");
call->add_args()->mutable_const_expr()->set_string_value("a");
cur_expr = call->add_args();
}
cur_expr->mutable_const_expr()->set_string_value("a");
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&root_expr, &source_info));
for (auto _ : state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsString());
ASSERT_TRUE(result.StringOrDie().value().size() == len + 1);
}
}
BENCHMARK(BM_EvalString)->Range(1, 10000);
static void BM_EvalString_Trace(benchmark::State& state) {
google::protobuf::Arena arena;
InterpreterOptions options = GetOptions(arena);
options.enable_recursive_tracing = true;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
int len = state.range(0);
Expr root_expr;
Expr* cur_expr = &root_expr;
for (int i = 0; i < len; i++) {
Expr::Call* call = cur_expr->mutable_call_expr();
call->set_function("_+_");
call->add_args()->mutable_const_expr()->set_string_value("a");
cur_expr = call->add_args();
}
cur_expr->mutable_const_expr()->set_string_value("a");
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&root_expr, &source_info));
for (auto _ : state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Trace(activation, &arena, EmptyCallback));
ASSERT_TRUE(result.IsString());
ASSERT_TRUE(result.StringOrDie().value().size() == len + 1);
}
}
BENCHMARK(BM_EvalString_Trace)->Range(1, 10000);
const char kIP[] = "10.0.1.2";
const char kPath[] = "/admin/edit";
const char kToken[] = "admin";
ABSL_ATTRIBUTE_NOINLINE
bool NativeCheck(absl::btree_map<std::string, std::string>& attributes,
const absl::flat_hash_set<std::string>& denylists,
const absl::flat_hash_set<std::string>& allowlists) {
auto& ip = attributes["ip"];
auto& path = attributes["path"];
auto& token = attributes["token"];
if (denylists.find(ip) != denylists.end()) {
return false;
}
if (absl::StartsWith(path, "v1")) {
if (token == "v1" || token == "v2" || token == "admin") {
return true;
}
} else if (absl::StartsWith(path, "v2")) {
if (token == "v2" || token == "admin") {
return true;
}
} else if (absl::StartsWith(path, "/admin")) {
if (token == "admin") {
if (allowlists.find(ip) != allowlists.end()) {
return true;
}
}
}
return false;
}
void BM_PolicyNative(benchmark::State& state) {
const auto denylists =
absl::flat_hash_set<std::string>{"10.0.1.4", "10.0.1.5", "10.0.1.6"};
const auto allowlists =
absl::flat_hash_set<std::string>{"10.0.1.1", "10.0.1.2", "10.0.1.3"};
auto attributes = absl::btree_map<std::string, std::string>{
{"ip", kIP}, {"token", kToken}, {"path", kPath}};
for (auto _ : state) {
auto result = NativeCheck(attributes, denylists, allowlists);
ASSERT_TRUE(result);
}
}
BENCHMARK(BM_PolicyNative);
void BM_PolicySymbolic(benchmark::State& state) {
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
!(ip in ["10.0.1.4", "10.0.1.5", "10.0.1.6"]) &&
((path.startsWith("v1") && token in ["v1", "v2", "admin"]) ||
(path.startsWith("v2") && token in ["v2", "admin"]) ||
(path.startsWith("/admin") && token == "admin" && ip in [
"10.0.1.1", "10.0.1.2", "10.0.1.3"
])
))cel"));
InterpreterOptions options = GetOptions(arena);
options.constant_folding = true;
options.constant_arena = &arena;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(
&parsed_expr.expr(), &source_info));
Activation activation;
activation.InsertValue("ip", CelValue::CreateStringView(kIP));
activation.InsertValue("path", CelValue::CreateStringView(kPath));
activation.InsertValue("token", CelValue::CreateStringView(kToken));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_PolicySymbolic);
class RequestMap : public CelMap {
public:
absl::optional<CelValue> operator[](CelValue key) const override {
if (!key.IsString()) {
return {};
}
auto value = key.StringOrDie().value();
if (value == "ip") {
return CelValue::CreateStringView(kIP);
} else if (value == "path") {
return CelValue::CreateStringView(kPath);
} else if (value == "token") {
return CelValue::CreateStringView(kToken);
}
return {};
}
int size() const override { return 3; }
absl::StatusOr<const CelList*> ListKeys() const override {
return absl::UnimplementedError("CelMap::ListKeys is not implemented");
}
};
void BM_PolicySymbolicMap(benchmark::State& state) {
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
!(request.ip in ["10.0.1.4", "10.0.1.5", "10.0.1.6"]) &&
((request.path.startsWith("v1") && request.token in ["v1", "v2", "admin"]) ||
(request.path.startsWith("v2") && request.token in ["v2", "admin"]) ||
(request.path.startsWith("/admin") && request.token == "admin" &&
request.ip in ["10.0.1.1", "10.0.1.2", "10.0.1.3"])
))cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(
&parsed_expr.expr(), &source_info));
Activation activation;
RequestMap request;
activation.InsertValue("request", CelValue::CreateMap(&request));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_PolicySymbolicMap);
void BM_PolicySymbolicProto(benchmark::State& state) {
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
!(request.ip in ["10.0.1.4", "10.0.1.5", "10.0.1.6"]) &&
((request.path.startsWith("v1") && request.token in ["v1", "v2", "admin"]) ||
(request.path.startsWith("v2") && request.token in ["v2", "admin"]) ||
(request.path.startsWith("/admin") && request.token == "admin" &&
request.ip in ["10.0.1.1", "10.0.1.2", "10.0.1.3"])
))cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
SourceInfo source_info;
ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(
&parsed_expr.expr(), &source_info));
Activation activation;
RequestContext request;
request.set_ip(kIP);
request.set_path(kPath);
request.set_token(kToken);
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_PolicySymbolicProto);
constexpr char kListSum[] = R"(
id: 1
comprehension_expr: <
accu_var: "__result__"
iter_var: "x"
iter_range: <
id: 2
ident_expr: <
name: "list_var"
>
>
accu_init: <
id: 3
const_expr: <
int64_value: 0
>
>
loop_step: <
id: 4
call_expr: <
function: "_+_"
args: <
id: 5
ident_expr: <
name: "__result__"
>
>
args: <
id: 6
ident_expr: <
name: "x"
>
>
>
>
loop_condition: <
id: 7
const_expr: <
bool_value: true
>
>
result: <
id: 8
ident_expr: <
name: "__result__"
>
>
>)";
void BM_Comprehension(benchmark::State& state) {
google::protobuf::Arena arena;
Expr expr;
Activation activation;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kListSum, &expr));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options = GetOptions(arena);
options.comprehension_max_iterations = 10000000;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&expr, nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsInt64());
ASSERT_EQ(result.Int64OrDie(), len);
}
}
BENCHMARK(BM_Comprehension)->Range(1, 1 << 20);
void BM_Comprehension_Trace(benchmark::State& state) {
google::protobuf::Arena arena;
Expr expr;
Activation activation;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kListSum, &expr));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options = GetOptions(arena);
options.enable_recursive_tracing = true;
options.comprehension_max_iterations = 10000000;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&expr, nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Trace(activation, &arena, EmptyCallback));
ASSERT_TRUE(result.IsInt64());
ASSERT_EQ(result.Int64OrDie(), len);
}
}
BENCHMARK(BM_Comprehension_Trace)->Range(1, 1 << 20);
void BM_HasMap(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("has(request.path) && !has(request.ip)"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
std::vector<std::pair<CelValue, CelValue>> map_pairs{
{CelValue::CreateStringView("path"), CelValue::CreateStringView("path")}};
auto cel_map =
CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>(
map_pairs.data(), map_pairs.size()));
activation.InsertValue("request", CelValue::CreateMap((*cel_map).get()));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_HasMap);
void BM_HasProto(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("has(request.path) && !has(request.ip)"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
auto reg_status = RegisterBuiltinFunctions(builder->GetRegistry(), options);
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
RequestContext request;
request.set_path(kPath);
request.set_token(kToken);
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_HasProto);
void BM_HasProtoMap(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("has(request.headers.create_time) && "
"!has(request.headers.update_time)"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
auto reg_status = RegisterBuiltinFunctions(builder->GetRegistry(), options);
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
RequestContext request;
request.mutable_headers()->insert({"create_time", "2021-01-01"});
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_HasProtoMap);
void BM_ReadProtoMap(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
request.headers.create_time == "2021-01-01"
)cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
auto reg_status = RegisterBuiltinFunctions(builder->GetRegistry(), options);
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
RequestContext request;
request.mutable_headers()->insert({"create_time", "2021-01-01"});
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_ReadProtoMap);
void BM_NestedProtoFieldRead(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
!request.a.b.c.d.e
)cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
auto reg_status = RegisterBuiltinFunctions(builder->GetRegistry(), options);
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
RequestContext request;
request.mutable_a()->mutable_b()->mutable_c()->mutable_d()->set_e(false);
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_NestedProtoFieldRead);
void BM_NestedProtoFieldReadDefaults(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
!request.a.b.c.d.e
)cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
auto reg_status = RegisterBuiltinFunctions(builder->GetRegistry(), options);
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
RequestContext request;
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_NestedProtoFieldReadDefaults);
void BM_ProtoStructAccess(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
has(request.auth.claims.iss) && request.auth.claims.iss == 'accounts.google.com'
)cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
AttributeContext::Request request;
auto* auth = request.mutable_auth();
(*auth->mutable_claims()->mutable_fields())["iss"].set_string_value(
"accounts.google.com");
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_ProtoStructAccess);
void BM_ProtoListAccess(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(R"cel(
"
)cel"));
InterpreterOptions options = GetOptions(arena);
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&parsed_expr.expr(), nullptr));
AttributeContext::Request request;
auto* auth = request.mutable_auth();
auth->add_access_levels("
auth->add_access_levels("
auth->add_access_levels("
auth->add_access_levels("
auth->add_access_levels("
activation.InsertValue("request",
CelProtoWrapper::CreateMessage(&request, &arena));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsBool());
ASSERT_TRUE(result.BoolOrDie());
}
}
BENCHMARK(BM_ProtoListAccess);
constexpr char kNestedListSum[] = R"(
id: 1
comprehension_expr: <
accu_var: "__result__"
iter_var: "x"
iter_range: <
id: 2
ident_expr: <
name: "list_var"
>
>
accu_init: <
id: 3
const_expr: <
int64_value: 0
>
>
loop_step: <
id: 4
call_expr: <
function: "_+_"
args: <
id: 5
ident_expr: <
name: "__result__"
>
>
args: <
id: 6
comprehension_expr: <
accu_var: "__result__"
iter_var: "x"
iter_range: <
id: 9
ident_expr: <
name: "list_var"
>
>
accu_init: <
id: 10
const_expr: <
int64_value: 0
>
>
loop_step: <
id: 11
call_expr: <
function: "_+_"
args: <
id: 12
ident_expr: <
name: "__result__"
>
>
args: <
id: 13
ident_expr: <
name: "x"
>
>
>
>
loop_condition: <
id: 14
const_expr: <
bool_value: true
>
>
result: <
id: 15
ident_expr: <
name: "__result__"
>
>
>
>
>
>
loop_condition: <
id: 7
const_expr: <
bool_value: true
>
>
result: <
id: 8
ident_expr: <
name: "__result__"
>
>
>)";
void BM_NestedComprehension(benchmark::State& state) {
google::protobuf::Arena arena;
Expr expr;
Activation activation;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kNestedListSum, &expr));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options = GetOptions(arena);
options.comprehension_max_iterations = 10000000;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&expr, nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsInt64());
ASSERT_EQ(result.Int64OrDie(), len * len);
}
}
BENCHMARK(BM_NestedComprehension)->Range(1, 1 << 10);
void BM_NestedComprehension_Trace(benchmark::State& state) {
google::protobuf::Arena arena;
Expr expr;
Activation activation;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kNestedListSum, &expr));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options = GetOptions(arena);
options.comprehension_max_iterations = 10000000;
options.enable_comprehension_list_append = true;
options.enable_recursive_tracing = true;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(auto cel_expr,
builder->CreateExpression(&expr, nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Trace(activation, &arena, EmptyCallback));
ASSERT_TRUE(result.IsInt64());
ASSERT_EQ(result.Int64OrDie(), len * len);
}
}
BENCHMARK(BM_NestedComprehension_Trace)->Range(1, 1 << 10);
void BM_ListComprehension(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("list_var.map(x, x * 2)"));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options = GetOptions(arena);
options.comprehension_max_iterations = 10000000;
options.enable_comprehension_list_append = true;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(
auto cel_expr, builder->CreateExpression(&(parsed_expr.expr()), nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsList());
ASSERT_EQ(result.ListOrDie()->size(), len);
}
}
BENCHMARK(BM_ListComprehension)->Range(1, 1 << 16);
void BM_ListComprehension_Trace(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("list_var.map(x, x * 2)"));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options = GetOptions(arena);
options.comprehension_max_iterations = 10000000;
options.enable_comprehension_list_append = true;
options.enable_recursive_tracing = true;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options));
ASSERT_OK_AND_ASSIGN(
auto cel_expr, builder->CreateExpression(&(parsed_expr.expr()), nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Trace(activation, &arena, EmptyCallback));
ASSERT_TRUE(result.IsList());
ASSERT_EQ(result.ListOrDie()->size(), len);
}
}
BENCHMARK(BM_ListComprehension_Trace)->Range(1, 1 << 16);
void BM_ListComprehension_Opt(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr,
parser::Parse("list_var.map(x, x * 2)"));
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
ContainerBackedListImpl cel_list(std::move(list));
activation.InsertValue("list_var", CelValue::CreateList(&cel_list));
InterpreterOptions options;
options.constant_arena = &arena;
options.constant_folding = true;
options.comprehension_max_iterations = 10000000;
options.enable_comprehension_list_append = true;
auto builder = CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry()));
ASSERT_OK_AND_ASSIGN(
auto cel_expr, builder->CreateExpression(&(parsed_expr.expr()), nullptr));
for (auto _ : state) {
ASSERT_OK_AND_ASSIGN(CelValue result,
cel_expr->Evaluate(activation, &arena));
ASSERT_TRUE(result.IsList());
ASSERT_EQ(result.ListOrDie()->size(), len);
}
}
BENCHMARK(BM_ListComprehension_Opt)->Range(1, 1 << 16);
void BM_ComprehensionCpp(benchmark::State& state) {
google::protobuf::Arena arena;
Activation activation;
int len = state.range(0);
std::vector<CelValue> list;
list.reserve(len);
for (int i = 0; i < len; i++) {
list.push_back(CelValue::CreateInt64(1));
}
auto op = [&list]() {
int sum = 0;
for (const auto& value : list) {
sum += value.Int64OrDie();
}
return sum;
};
for (auto _ : state) {
int result = op();
ASSERT_EQ(result, len);
}
}
BENCHMARK(BM_ComprehensionCpp)->Range(1, 1 << 20);
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/benchmark.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/tests/benchmark_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
0038681c-5490-4984-af4b-34301d2f6652 | cpp | google/cel-cpp | arena_string | common/internal/arena_string.h | common/arena_string_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_ARENA_STRING_H_
#define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_ARENA_STRING_H_
#include "absl/strings/string_view.h"
namespace cel::common_internal {
class ArenaString final {
public:
ArenaString() = default;
ArenaString(const ArenaString&) = default;
ArenaString& operator=(const ArenaString&) = default;
explicit ArenaString(absl::string_view content) : content_(content) {}
typename absl::string_view::size_type size() const { return content_.size(); }
typename absl::string_view::const_pointer data() const {
return content_.data();
}
operator absl::string_view() const { return content_; }
private:
absl::string_view content_;
};
}
#endif | #include "common/arena_string.h"
#include "absl/hash/hash.h"
#include "absl/hash/hash_testing.h"
#include "absl/strings/string_view.h"
#include "internal/testing.h"
namespace cel {
namespace {
using ::testing::Eq;
using ::testing::Ge;
using ::testing::Gt;
using ::testing::IsEmpty;
using ::testing::Le;
using ::testing::Lt;
using ::testing::Ne;
using ::testing::SizeIs;
TEST(ArenaString, Default) {
ArenaString string;
EXPECT_THAT(string, IsEmpty());
EXPECT_THAT(string, SizeIs(0));
EXPECT_THAT(string, Eq(ArenaString()));
}
TEST(ArenaString, Iterator) {
ArenaString string = ArenaString::Static("Hello World!");
auto it = string.cbegin();
EXPECT_THAT(*it++, Eq('H'));
EXPECT_THAT(*it++, Eq('e'));
EXPECT_THAT(*it++, Eq('l'));
EXPECT_THAT(*it++, Eq('l'));
EXPECT_THAT(*it++, Eq('o'));
EXPECT_THAT(*it++, Eq(' '));
EXPECT_THAT(*it++, Eq('W'));
EXPECT_THAT(*it++, Eq('o'));
EXPECT_THAT(*it++, Eq('r'));
EXPECT_THAT(*it++, Eq('l'));
EXPECT_THAT(*it++, Eq('d'));
EXPECT_THAT(*it++, Eq('!'));
EXPECT_THAT(it, Eq(string.cend()));
}
TEST(ArenaString, ReverseIterator) {
ArenaString string = ArenaString::Static("Hello World!");
auto it = string.crbegin();
EXPECT_THAT(*it++, Eq('!'));
EXPECT_THAT(*it++, Eq('d'));
EXPECT_THAT(*it++, Eq('l'));
EXPECT_THAT(*it++, Eq('r'));
EXPECT_THAT(*it++, Eq('o'));
EXPECT_THAT(*it++, Eq('W'));
EXPECT_THAT(*it++, Eq(' '));
EXPECT_THAT(*it++, Eq('o'));
EXPECT_THAT(*it++, Eq('l'));
EXPECT_THAT(*it++, Eq('l'));
EXPECT_THAT(*it++, Eq('e'));
EXPECT_THAT(*it++, Eq('H'));
EXPECT_THAT(it, Eq(string.crend()));
}
TEST(ArenaString, RemovePrefix) {
ArenaString string = ArenaString::Static("Hello World!");
string.remove_prefix(6);
EXPECT_EQ(string, "World!");
}
TEST(ArenaString, RemoveSuffix) {
ArenaString string = ArenaString::Static("Hello World!");
string.remove_suffix(7);
EXPECT_EQ(string, "Hello");
}
TEST(ArenaString, Equal) {
EXPECT_THAT(ArenaString::Static("1"), Eq(ArenaString::Static("1")));
}
TEST(ArenaString, NotEqual) {
EXPECT_THAT(ArenaString::Static("1"), Ne(ArenaString::Static("2")));
}
TEST(ArenaString, Less) {
EXPECT_THAT(ArenaString::Static("1"), Lt(ArenaString::Static("2")));
}
TEST(ArenaString, LessEqual) {
EXPECT_THAT(ArenaString::Static("1"), Le(ArenaString::Static("1")));
}
TEST(ArenaString, Greater) {
EXPECT_THAT(ArenaString::Static("2"), Gt(ArenaString::Static("1")));
}
TEST(ArenaString, GreaterEqual) {
EXPECT_THAT(ArenaString::Static("1"), Ge(ArenaString::Static("1")));
}
TEST(ArenaString, ImplementsAbslHashCorrectly) {
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
{ArenaString::Static(""), ArenaString::Static("Hello World!"),
ArenaString::Static("How much wood could a woodchuck chuck if a "
"woodchuck could chuck wood?")}));
}
TEST(ArenaString, Hash) {
EXPECT_EQ(absl::HashOf(ArenaString::Static("Hello World!")),
absl::HashOf(absl::string_view("Hello World!")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/arena_string.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/arena_string_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
ea068d7a-4c02-4749-9466-cbba7ff68004 | cpp | google/cel-cpp | data | common/data.h | common/data_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_DATA_H_
#define THIRD_PARTY_CEL_CPP_COMMON_DATA_H_
#include <cstdint>
#include "absl/base/nullability.h"
#include "absl/log/absl_check.h"
#include "common/internal/metadata.h"
#include "google/protobuf/arena.h"
namespace cel {
class Data;
template <typename T>
struct Ownable;
template <typename T>
struct Borrowable;
namespace common_internal {
class ReferenceCount;
void SetDataReferenceCount(
absl::Nonnull<const Data*> data,
absl::Nonnull<const ReferenceCount*> refcount) noexcept;
absl::Nullable<const ReferenceCount*> GetDataReferenceCount(
absl::Nonnull<const Data*> data) noexcept;
}
class Data {
public:
virtual ~Data() = default;
absl::Nullable<google::protobuf::Arena*> GetArena() const noexcept {
return (owner_ & kOwnerBits) == kOwnerArenaBit
? reinterpret_cast<google::protobuf::Arena*>(owner_ & kOwnerPointerMask)
: nullptr;
}
protected:
Data() noexcept : Data(nullptr) {}
Data(const Data&) = default;
Data(Data&&) = default;
Data& operator=(const Data&) = default;
Data& operator=(Data&&) = default;
explicit Data(absl::Nullable<google::protobuf::Arena*> arena) noexcept
: owner_(reinterpret_cast<uintptr_t>(arena) |
(arena != nullptr ? kOwnerArenaBit : kOwnerNone)) {}
private:
static constexpr uintptr_t kOwnerNone = common_internal::kMetadataOwnerNone;
static constexpr uintptr_t kOwnerReferenceCountBit =
common_internal::kMetadataOwnerReferenceCountBit;
static constexpr uintptr_t kOwnerArenaBit =
common_internal::kMetadataOwnerArenaBit;
static constexpr uintptr_t kOwnerBits = common_internal::kMetadataOwnerBits;
static constexpr uintptr_t kOwnerPointerMask =
common_internal::kMetadataOwnerPointerMask;
friend void common_internal::SetDataReferenceCount(
absl::Nonnull<const Data*> data,
absl::Nonnull<const common_internal::ReferenceCount*> refcount) noexcept;
friend absl::Nullable<const common_internal::ReferenceCount*>
common_internal::GetDataReferenceCount(
absl::Nonnull<const Data*> data) noexcept;
template <typename T>
friend struct Ownable;
template <typename T>
friend struct Borrowable;
mutable uintptr_t owner_ = kOwnerNone;
};
namespace common_internal {
inline void SetDataReferenceCount(
absl::Nonnull<const Data*> data,
absl::Nonnull<const ReferenceCount*> refcount) noexcept {
ABSL_DCHECK_EQ(data->owner_, Data::kOwnerNone);
data->owner_ =
reinterpret_cast<uintptr_t>(refcount) | Data::kOwnerReferenceCountBit;
}
inline absl::Nullable<const ReferenceCount*> GetDataReferenceCount(
absl::Nonnull<const Data*> data) noexcept {
return (data->owner_ & Data::kOwnerBits) == Data::kOwnerReferenceCountBit
? reinterpret_cast<const ReferenceCount*>(data->owner_ &
Data::kOwnerPointerMask)
: nullptr;
}
}
}
#endif | #include "common/data.h"
#include "absl/base/nullability.h"
#include "common/internal/reference_count.h"
#include "internal/testing.h"
#include "google/protobuf/arena.h"
namespace cel {
namespace {
using ::testing::IsNull;
class DataTest final : public Data {
public:
DataTest() noexcept : Data() {}
explicit DataTest(absl::Nullable<google::protobuf::Arena*> arena) noexcept
: Data(arena) {}
};
class DataReferenceCount final : public common_internal::ReferenceCounted {
public:
explicit DataReferenceCount(const Data* data) : data_(data) {}
private:
void Finalize() noexcept override { delete data_; }
const Data* data_;
};
TEST(Data, Arena) {
google::protobuf::Arena arena;
DataTest data(&arena);
EXPECT_EQ(data.GetArena(), &arena);
EXPECT_THAT(common_internal::GetDataReferenceCount(&data), IsNull());
}
TEST(Data, ReferenceCount) {
auto* data = new DataTest();
EXPECT_THAT(data->GetArena(), IsNull());
auto* refcount = new DataReferenceCount(data);
common_internal::SetDataReferenceCount(data, refcount);
EXPECT_EQ(common_internal::GetDataReferenceCount(data), refcount);
common_internal::StrongUnref(refcount);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/data.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/data_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
877c9521-8b29-4b65-b866-ac4f0be049d7 | cpp | google/cel-cpp | allocator | common/allocator.h | common/allocator_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_ALLOCATOR_H_
#define THIRD_PARTY_CEL_CPP_COMMON_ALLOCATOR_H_
#include <cstddef>
#include <new>
#include <type_traits>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/log/absl_check.h"
#include "absl/numeric/bits.h"
#include "common/arena.h"
#include "internal/new.h"
#include "google/protobuf/arena.h"
namespace cel {
enum class AllocatorKind {
kArena = 1,
kNewDelete = 2,
};
template <typename S>
void AbslStringify(S& sink, AllocatorKind kind) {
switch (kind) {
case AllocatorKind::kArena:
sink.Append("ARENA");
return;
case AllocatorKind::kNewDelete:
sink.Append("NEW_DELETE");
return;
default:
sink.Append("ERROR");
return;
}
}
template <typename T = void>
class Allocator;
template <>
class Allocator<void> {
public:
using size_type = size_t;
using difference_type = ptrdiff_t;
using propagate_on_container_copy_assignment = std::true_type;
using propagate_on_container_move_assignment = std::true_type;
using propagate_on_container_swap = std::true_type;
Allocator() = delete;
Allocator(const Allocator&) = default;
Allocator& operator=(const Allocator&) = delete;
Allocator(std::nullptr_t) = delete;
template <typename U, typename = std::enable_if_t<!std::is_void_v<U>>>
constexpr Allocator(const Allocator<U>& other) noexcept
: arena_(other.arena()) {}
constexpr Allocator(absl::Nullable<google::protobuf::Arena*> arena) noexcept
: arena_(arena) {}
absl::Nullable<google::protobuf::Arena*> arena() const noexcept { return arena_; }
ABSL_MUST_USE_RESULT void* allocate_bytes(
size_type nbytes, size_type alignment = alignof(std::max_align_t)) {
ABSL_DCHECK(absl::has_single_bit(alignment));
if (nbytes == 0) {
return nullptr;
}
if (auto* arena = this->arena(); arena != nullptr) {
return arena->AllocateAligned(nbytes, alignment);
}
return internal::AlignedNew(nbytes,
static_cast<std::align_val_t>(alignment));
}
void deallocate_bytes(
void* p, size_type nbytes,
size_type alignment = alignof(std::max_align_t)) noexcept {
ABSL_DCHECK((p == nullptr && nbytes == 0) || (p != nullptr && nbytes != 0));
ABSL_DCHECK(absl::has_single_bit(alignment));
if (arena() == nullptr) {
internal::SizedAlignedDelete(p, nbytes,
static_cast<std::align_val_t>(alignment));
}
}
template <typename T>
ABSL_MUST_USE_RESULT T* allocate_object(size_type n = 1) {
return static_cast<T*>(allocate_bytes(sizeof(T) * n, alignof(T)));
}
template <typename T>
void deallocate_object(T* p, size_type n = 1) {
deallocate_bytes(p, sizeof(T) * n, alignof(T));
}
template <typename T, typename... Args>
ABSL_MUST_USE_RESULT T* new_object(Args&&... args) {
T* object = google::protobuf::Arena::Create<std::remove_const_t<T>>(
arena(), std::forward<Args>(args)...);
if constexpr (IsArenaConstructible<T>::value) {
ABSL_DCHECK_EQ(object->GetArena(), arena());
}
return object;
}
template <typename T>
void delete_object(T* p) noexcept {
ABSL_DCHECK(p != nullptr);
if constexpr (IsArenaConstructible<T>::value) {
ABSL_DCHECK_EQ(p->GetArena(), arena());
}
if (arena() == nullptr) {
delete p;
}
}
void delete_object(std::nullptr_t) = delete;
private:
template <typename U>
friend class Allocator;
absl::Nullable<google::protobuf::Arena*> arena_;
};
template <typename T>
class Allocator : public Allocator<void> {
public:
static_assert(!std::is_const_v<T>, "T must not be const qualified");
static_assert(!std::is_volatile_v<T>, "T must not be volatile qualified");
static_assert(std::is_object_v<T>, "T must be an object type");
using value_type = T;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = value_type&;
using const_reference = const value_type&;
using Allocator<void>::Allocator;
pointer allocate(size_type n, const void* = nullptr) {
return arena() != nullptr
? static_cast<pointer>(
arena()->AllocateAligned(n * sizeof(T), alignof(T)))
: static_cast<pointer>(internal::AlignedNew(
n * sizeof(T), static_cast<std::align_val_t>(alignof(T))));
}
void deallocate(pointer p, size_type n) noexcept {
if (arena() == nullptr) {
internal::SizedAlignedDelete(p, n * sizeof(T),
static_cast<std::align_val_t>(alignof(T)));
}
}
template <typename U, typename... Args>
void construct(U* p, Args&&... args) {
static_assert(std::is_same_v<T*, U*>);
static_assert(!IsArenaConstructible<T>::value);
::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
}
template <typename U>
void destroy(U* p) noexcept {
static_assert(std::is_same_v<T*, U*>);
static_assert(!IsArenaConstructible<T>::value);
p->~T();
}
};
template <typename T, typename U>
inline bool operator==(Allocator<T> lhs, Allocator<U> rhs) noexcept {
return lhs.arena() == rhs.arena();
}
template <typename T, typename U>
inline bool operator!=(Allocator<T> lhs, Allocator<U> rhs) noexcept {
return !operator==(lhs, rhs);
}
inline Allocator<> NewDeleteAllocator() noexcept {
return Allocator<>(static_cast<google::protobuf::Arena*>(nullptr));
}
template <typename T>
inline Allocator<T> NewDeleteAllocatorFor() noexcept {
static_assert(!std::is_void_v<T>);
return Allocator<T>(static_cast<google::protobuf::Arena*>(nullptr));
}
inline Allocator<> ArenaAllocator(
absl::Nonnull<google::protobuf::Arena*> arena) noexcept {
return Allocator<>(arena);
}
template <typename T>
inline Allocator<T> ArenaAllocatorFor(
absl::Nonnull<google::protobuf::Arena*> arena) noexcept {
static_assert(!std::is_void_v<T>);
return Allocator<T>(arena);
}
}
#endif | #include "common/allocator.h"
#include "absl/strings/str_cat.h"
#include "internal/testing.h"
#include "google/protobuf/arena.h"
namespace cel {
namespace {
using ::testing::NotNull;
TEST(AllocatorKind, AbslStringify) {
EXPECT_EQ(absl::StrCat(AllocatorKind::kArena), "ARENA");
EXPECT_EQ(absl::StrCat(AllocatorKind::kNewDelete), "NEW_DELETE");
EXPECT_EQ(absl::StrCat(static_cast<AllocatorKind>(0)), "ERROR");
}
TEST(NewDeleteAllocator, Bytes) {
auto allocator = NewDeleteAllocator();
void* p = allocator.allocate_bytes(17, 8);
EXPECT_THAT(p, NotNull());
allocator.deallocate_bytes(p, 17, 8);
}
TEST(ArenaAllocator, Bytes) {
google::protobuf::Arena arena;
auto allocator = ArenaAllocator(&arena);
void* p = allocator.allocate_bytes(17, 8);
EXPECT_THAT(p, NotNull());
allocator.deallocate_bytes(p, 17, 8);
}
struct TrivialObject {
char data[17];
};
TEST(NewDeleteAllocator, NewDeleteObject) {
auto allocator = NewDeleteAllocator();
auto* p = allocator.new_object<TrivialObject>();
EXPECT_THAT(p, NotNull());
allocator.delete_object(p);
}
TEST(ArenaAllocator, NewDeleteObject) {
google::protobuf::Arena arena;
auto allocator = ArenaAllocator(&arena);
auto* p = allocator.new_object<TrivialObject>();
EXPECT_THAT(p, NotNull());
allocator.delete_object(p);
}
TEST(NewDeleteAllocator, Object) {
auto allocator = NewDeleteAllocator();
auto* p = allocator.allocate_object<TrivialObject>();
EXPECT_THAT(p, NotNull());
allocator.deallocate_object(p);
}
TEST(ArenaAllocator, Object) {
google::protobuf::Arena arena;
auto allocator = ArenaAllocator(&arena);
auto* p = allocator.allocate_object<TrivialObject>();
EXPECT_THAT(p, NotNull());
allocator.deallocate_object(p);
}
TEST(NewDeleteAllocator, ObjectArray) {
auto allocator = NewDeleteAllocator();
auto* p = allocator.allocate_object<TrivialObject>(2);
EXPECT_THAT(p, NotNull());
allocator.deallocate_object(p, 2);
}
TEST(ArenaAllocator, ObjectArray) {
google::protobuf::Arena arena;
auto allocator = ArenaAllocator(&arena);
auto* p = allocator.allocate_object<TrivialObject>(2);
EXPECT_THAT(p, NotNull());
allocator.deallocate_object(p, 2);
}
TEST(NewDeleteAllocator, T) {
auto allocator = NewDeleteAllocatorFor<TrivialObject>();
auto* p = allocator.allocate(1);
EXPECT_THAT(p, NotNull());
allocator.construct(p);
allocator.destroy(p);
allocator.deallocate(p, 1);
}
TEST(ArenaAllocator, T) {
google::protobuf::Arena arena;
auto allocator = ArenaAllocatorFor<TrivialObject>(&arena);
auto* p = allocator.allocate(1);
EXPECT_THAT(p, NotNull());
allocator.construct(p);
allocator.destroy(p);
allocator.deallocate(p, 1);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/allocator.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/allocator_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
df17418c-8f4a-4b2b-acdf-84b34d9ea22d | cpp | google/cel-cpp | arena_string_pool | common/arena_string_pool.h | common/arena_string_pool_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_ARENA_STRING_POOL_H_
#define THIRD_PARTY_CEL_CPP_COMMON_ARENA_STRING_POOL_H_
#include <memory>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/strings/string_view.h"
#include "common/arena_string.h"
#include "internal/string_pool.h"
#include "google/protobuf/arena.h"
namespace cel {
class ArenaStringPool;
absl::Nonnull<std::unique_ptr<ArenaStringPool>> NewArenaStringPool(
absl::Nonnull<google::protobuf::Arena*> arena ABSL_ATTRIBUTE_LIFETIME_BOUND);
class ArenaStringPool final {
public:
ArenaStringPool(const ArenaStringPool&) = delete;
ArenaStringPool(ArenaStringPool&&) = delete;
ArenaStringPool& operator=(const ArenaStringPool&) = delete;
ArenaStringPool& operator=(ArenaStringPool&&) = delete;
ArenaString InternString(absl::string_view string) {
return ArenaString(strings_.InternString(string));
}
ArenaString InternString(ArenaString) = delete;
private:
friend absl::Nonnull<std::unique_ptr<ArenaStringPool>> NewArenaStringPool(
absl::Nonnull<google::protobuf::Arena*>);
explicit ArenaStringPool(absl::Nonnull<google::protobuf::Arena*> arena)
: strings_(arena) {}
internal::StringPool strings_;
};
inline absl::Nonnull<std::unique_ptr<ArenaStringPool>> NewArenaStringPool(
absl::Nonnull<google::protobuf::Arena*> arena ABSL_ATTRIBUTE_LIFETIME_BOUND) {
return std::unique_ptr<ArenaStringPool>(new ArenaStringPool(arena));
}
}
#endif | #include "common/arena_string_pool.h"
#include "internal/testing.h"
#include "google/protobuf/arena.h"
namespace cel {
namespace {
TEST(ArenaStringPool, InternString) {
google::protobuf::Arena arena;
auto string_pool = NewArenaStringPool(&arena);
auto expected = string_pool->InternString("Hello World!");
auto got = string_pool->InternString("Hello World!");
EXPECT_EQ(expected.data(), got.data());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/arena_string_pool.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/arena_string_pool_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
ffee8254-4227-43c8-9032-3f027718dad1 | cpp | google/cel-cpp | duration_type | common/types/duration_type.h | common/types/duration_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_DURATION_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_DURATION_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class DurationType final {
public:
static constexpr TypeKind kKind = TypeKind::kDuration;
static constexpr absl::string_view kName = "google.protobuf.Duration";
DurationType() = default;
DurationType(const DurationType&) = default;
DurationType(DurationType&&) = default;
DurationType& operator=(const DurationType&) = default;
DurationType& operator=(DurationType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(DurationType&) noexcept {}
};
inline constexpr void swap(DurationType& lhs, DurationType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(DurationType, DurationType) { return true; }
inline constexpr bool operator!=(DurationType lhs, DurationType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, DurationType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const DurationType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(DurationType, Kind) {
EXPECT_EQ(DurationType().kind(), DurationType::kKind);
EXPECT_EQ(Type(DurationType()).kind(), DurationType::kKind);
}
TEST(DurationType, Name) {
EXPECT_EQ(DurationType().name(), DurationType::kName);
EXPECT_EQ(Type(DurationType()).name(), DurationType::kName);
}
TEST(DurationType, DebugString) {
{
std::ostringstream out;
out << DurationType();
EXPECT_EQ(out.str(), DurationType::kName);
}
{
std::ostringstream out;
out << Type(DurationType());
EXPECT_EQ(out.str(), DurationType::kName);
}
}
TEST(DurationType, Hash) {
EXPECT_EQ(absl::HashOf(DurationType()), absl::HashOf(DurationType()));
}
TEST(DurationType, Equal) {
EXPECT_EQ(DurationType(), DurationType());
EXPECT_EQ(Type(DurationType()), DurationType());
EXPECT_EQ(DurationType(), Type(DurationType()));
EXPECT_EQ(Type(DurationType()), Type(DurationType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/duration_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/duration_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
6e61aff3-efe6-4cc0-b730-40fab8599639 | cpp | google/cel-cpp | uint_wrapper_type | common/types/uint_wrapper_type.h | common/types/uint_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_UINT_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_UINT_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class UintWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kUintWrapper;
static constexpr absl::string_view kName = "google.protobuf.UInt64Value";
UintWrapperType() = default;
UintWrapperType(const UintWrapperType&) = default;
UintWrapperType(UintWrapperType&&) = default;
UintWrapperType& operator=(const UintWrapperType&) = default;
UintWrapperType& operator=(UintWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(UintWrapperType&) noexcept {}
};
inline constexpr void swap(UintWrapperType& lhs,
UintWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(UintWrapperType, UintWrapperType) {
return true;
}
inline constexpr bool operator!=(UintWrapperType lhs, UintWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, UintWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out,
const UintWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(UintWrapperType, Kind) {
EXPECT_EQ(UintWrapperType().kind(), UintWrapperType::kKind);
EXPECT_EQ(Type(UintWrapperType()).kind(), UintWrapperType::kKind);
}
TEST(UintWrapperType, Name) {
EXPECT_EQ(UintWrapperType().name(), UintWrapperType::kName);
EXPECT_EQ(Type(UintWrapperType()).name(), UintWrapperType::kName);
}
TEST(UintWrapperType, DebugString) {
{
std::ostringstream out;
out << UintWrapperType();
EXPECT_EQ(out.str(), UintWrapperType::kName);
}
{
std::ostringstream out;
out << Type(UintWrapperType());
EXPECT_EQ(out.str(), UintWrapperType::kName);
}
}
TEST(UintWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(UintWrapperType()), absl::HashOf(UintWrapperType()));
}
TEST(UintWrapperType, Equal) {
EXPECT_EQ(UintWrapperType(), UintWrapperType());
EXPECT_EQ(Type(UintWrapperType()), UintWrapperType());
EXPECT_EQ(UintWrapperType(), Type(UintWrapperType()));
EXPECT_EQ(Type(UintWrapperType()), Type(UintWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/uint_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/uint_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
d67fd247-b4ef-42cf-bc1c-4fa0a8cfd35b | cpp | google/cel-cpp | type_param_type | common/types/type_param_type.h | common/types/type_param_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_TYPE_PARAM_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_TYPE_PARAM_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class TypeParamType final {
public:
static constexpr TypeKind kKind = TypeKind::kTypeParam;
explicit TypeParamType(absl::string_view name ABSL_ATTRIBUTE_LIFETIME_BOUND)
: name_(name) {}
TypeParamType() = default;
TypeParamType(const TypeParamType&) = default;
TypeParamType(TypeParamType&&) = default;
TypeParamType& operator=(const TypeParamType&) = default;
TypeParamType& operator=(TypeParamType&&) = default;
static TypeKind kind() { return kKind; }
absl::string_view name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return name_; }
static TypeParameters GetParameters();
std::string DebugString() const { return std::string(name()); }
friend void swap(TypeParamType& lhs, TypeParamType& rhs) noexcept {
using std::swap;
swap(lhs.name_, rhs.name_);
}
private:
absl::string_view name_;
};
inline bool operator==(const TypeParamType& lhs, const TypeParamType& rhs) {
return lhs.name() == rhs.name();
}
inline bool operator!=(const TypeParamType& lhs, const TypeParamType& rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, const TypeParamType& type) {
return H::combine(std::move(state), type.name());
}
inline std::ostream& operator<<(std::ostream& out, const TypeParamType& type) {
return out << type.DebugString();
}
}
#endif | #include "common/type.h"
#include <sstream>
#include "absl/hash/hash.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(TypeParamType, Kind) {
EXPECT_EQ(TypeParamType("T").kind(), TypeParamType::kKind);
EXPECT_EQ(Type(TypeParamType("T")).kind(), TypeParamType::kKind);
}
TEST(TypeParamType, Name) {
EXPECT_EQ(TypeParamType("T").name(), "T");
EXPECT_EQ(Type(TypeParamType("T")).name(), "T");
}
TEST(TypeParamType, DebugString) {
{
std::ostringstream out;
out << TypeParamType("T");
EXPECT_EQ(out.str(), "T");
}
{
std::ostringstream out;
out << Type(TypeParamType("T"));
EXPECT_EQ(out.str(), "T");
}
}
TEST(TypeParamType, Hash) {
EXPECT_EQ(absl::HashOf(TypeParamType("T")), absl::HashOf(TypeParamType("T")));
}
TEST(TypeParamType, Equal) {
EXPECT_EQ(TypeParamType("T"), TypeParamType("T"));
EXPECT_EQ(Type(TypeParamType("T")), TypeParamType("T"));
EXPECT_EQ(TypeParamType("T"), Type(TypeParamType("T")));
EXPECT_EQ(Type(TypeParamType("T")), Type(TypeParamType("T")));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/type_param_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/type_param_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
c15ad434-bb08-4201-adc4-f39173e7f27c | cpp | google/cel-cpp | double_type | common/types/double_type.h | common/types/double_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_DOUBLE_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_DOUBLE_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class DoubleType final {
public:
static constexpr TypeKind kKind = TypeKind::kDouble;
static constexpr absl::string_view kName = "double";
DoubleType() = default;
DoubleType(const DoubleType&) = default;
DoubleType(DoubleType&&) = default;
DoubleType& operator=(const DoubleType&) = default;
DoubleType& operator=(DoubleType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(DoubleType&) noexcept {}
};
inline constexpr void swap(DoubleType& lhs, DoubleType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(DoubleType, DoubleType) { return true; }
inline constexpr bool operator!=(DoubleType lhs, DoubleType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, DoubleType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const DoubleType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(DoubleType, Kind) {
EXPECT_EQ(DoubleType().kind(), DoubleType::kKind);
EXPECT_EQ(Type(DoubleType()).kind(), DoubleType::kKind);
}
TEST(DoubleType, Name) {
EXPECT_EQ(DoubleType().name(), DoubleType::kName);
EXPECT_EQ(Type(DoubleType()).name(), DoubleType::kName);
}
TEST(DoubleType, DebugString) {
{
std::ostringstream out;
out << DoubleType();
EXPECT_EQ(out.str(), DoubleType::kName);
}
{
std::ostringstream out;
out << Type(DoubleType());
EXPECT_EQ(out.str(), DoubleType::kName);
}
}
TEST(DoubleType, Hash) {
EXPECT_EQ(absl::HashOf(DoubleType()), absl::HashOf(DoubleType()));
}
TEST(DoubleType, Equal) {
EXPECT_EQ(DoubleType(), DoubleType());
EXPECT_EQ(Type(DoubleType()), DoubleType());
EXPECT_EQ(DoubleType(), Type(DoubleType()));
EXPECT_EQ(Type(DoubleType()), Type(DoubleType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/double_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/double_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
fb108b70-21f6-4315-9b31-59c2e7d8fca6 | cpp | google/cel-cpp | error_type | common/types/error_type.h | common/types/error_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_ERROR_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_ERROR_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class ErrorType final {
public:
static constexpr TypeKind kKind = TypeKind::kError;
static constexpr absl::string_view kName = "*error*";
ErrorType() = default;
ErrorType(const ErrorType&) = default;
ErrorType(ErrorType&&) = default;
ErrorType& operator=(const ErrorType&) = default;
ErrorType& operator=(ErrorType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(ErrorType&) noexcept {}
};
inline constexpr void swap(ErrorType& lhs, ErrorType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(ErrorType, ErrorType) { return true; }
inline constexpr bool operator!=(ErrorType lhs, ErrorType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, ErrorType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const ErrorType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(ErrorType, Kind) {
EXPECT_EQ(ErrorType().kind(), ErrorType::kKind);
EXPECT_EQ(Type(ErrorType()).kind(), ErrorType::kKind);
}
TEST(ErrorType, Name) {
EXPECT_EQ(ErrorType().name(), ErrorType::kName);
EXPECT_EQ(Type(ErrorType()).name(), ErrorType::kName);
}
TEST(ErrorType, DebugString) {
{
std::ostringstream out;
out << ErrorType();
EXPECT_EQ(out.str(), ErrorType::kName);
}
{
std::ostringstream out;
out << Type(ErrorType());
EXPECT_EQ(out.str(), ErrorType::kName);
}
}
TEST(ErrorType, Hash) {
EXPECT_EQ(absl::HashOf(ErrorType()), absl::HashOf(ErrorType()));
}
TEST(ErrorType, Equal) {
EXPECT_EQ(ErrorType(), ErrorType());
EXPECT_EQ(Type(ErrorType()), ErrorType());
EXPECT_EQ(ErrorType(), Type(ErrorType()));
EXPECT_EQ(Type(ErrorType()), Type(ErrorType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/error_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/error_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
2c0d47c7-2213-4e44-90ad-237902404512 | cpp | google/cel-cpp | timestamp_type | common/types/timestamp_type.h | common/types/timestamp_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_TIMESTAMP_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_TIMESTAMP_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class TimestampType final {
public:
static constexpr TypeKind kKind = TypeKind::kTimestamp;
static constexpr absl::string_view kName = "google.protobuf.Timestamp";
TimestampType() = default;
TimestampType(const TimestampType&) = default;
TimestampType(TimestampType&&) = default;
TimestampType& operator=(const TimestampType&) = default;
TimestampType& operator=(TimestampType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(TimestampType&) noexcept {}
};
inline constexpr void swap(TimestampType& lhs, TimestampType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(TimestampType, TimestampType) { return true; }
inline constexpr bool operator!=(TimestampType lhs, TimestampType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, TimestampType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const TimestampType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(TimestampType, Kind) {
EXPECT_EQ(TimestampType().kind(), TimestampType::kKind);
EXPECT_EQ(Type(TimestampType()).kind(), TimestampType::kKind);
}
TEST(TimestampType, Name) {
EXPECT_EQ(TimestampType().name(), TimestampType::kName);
EXPECT_EQ(Type(TimestampType()).name(), TimestampType::kName);
}
TEST(TimestampType, DebugString) {
{
std::ostringstream out;
out << TimestampType();
EXPECT_EQ(out.str(), TimestampType::kName);
}
{
std::ostringstream out;
out << Type(TimestampType());
EXPECT_EQ(out.str(), TimestampType::kName);
}
}
TEST(TimestampType, Hash) {
EXPECT_EQ(absl::HashOf(TimestampType()), absl::HashOf(TimestampType()));
}
TEST(TimestampType, Equal) {
EXPECT_EQ(TimestampType(), TimestampType());
EXPECT_EQ(Type(TimestampType()), TimestampType());
EXPECT_EQ(TimestampType(), Type(TimestampType()));
EXPECT_EQ(Type(TimestampType()), Type(TimestampType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/timestamp_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/timestamp_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
71a2284b-c8c4-47ae-8f89-1b9d6cb5b1aa | cpp | google/cel-cpp | uint_type | common/types/uint_type.h | common/types/uint_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_UINT_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_UINT_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class UintType final {
public:
static constexpr TypeKind kKind = TypeKind::kUint;
static constexpr absl::string_view kName = "uint";
UintType() = default;
UintType(const UintType&) = default;
UintType(UintType&&) = default;
UintType& operator=(const UintType&) = default;
UintType& operator=(UintType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(UintType&) noexcept {}
};
inline constexpr void swap(UintType& lhs, UintType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(UintType, UintType) { return true; }
inline constexpr bool operator!=(UintType lhs, UintType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, UintType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const UintType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(UintType, Kind) {
EXPECT_EQ(UintType().kind(), UintType::kKind);
EXPECT_EQ(Type(UintType()).kind(), UintType::kKind);
}
TEST(UintType, Name) {
EXPECT_EQ(UintType().name(), UintType::kName);
EXPECT_EQ(Type(UintType()).name(), UintType::kName);
}
TEST(UintType, DebugString) {
{
std::ostringstream out;
out << UintType();
EXPECT_EQ(out.str(), UintType::kName);
}
{
std::ostringstream out;
out << Type(UintType());
EXPECT_EQ(out.str(), UintType::kName);
}
}
TEST(UintType, Hash) {
EXPECT_EQ(absl::HashOf(UintType()), absl::HashOf(UintType()));
}
TEST(UintType, Equal) {
EXPECT_EQ(UintType(), UintType());
EXPECT_EQ(Type(UintType()), UintType());
EXPECT_EQ(UintType(), Type(UintType()));
EXPECT_EQ(Type(UintType()), Type(UintType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/uint_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/uint_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
735cb486-ca91-4254-8dcb-7d65517afcb1 | cpp | google/cel-cpp | int_wrapper_type | common/types/int_wrapper_type.h | common/types/int_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_INT_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_INT_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class IntWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kIntWrapper;
static constexpr absl::string_view kName = "google.protobuf.Int64Value";
IntWrapperType() = default;
IntWrapperType(const IntWrapperType&) = default;
IntWrapperType(IntWrapperType&&) = default;
IntWrapperType& operator=(const IntWrapperType&) = default;
IntWrapperType& operator=(IntWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(IntWrapperType&) noexcept {}
};
inline constexpr void swap(IntWrapperType& lhs, IntWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(IntWrapperType, IntWrapperType) {
return true;
}
inline constexpr bool operator!=(IntWrapperType lhs, IntWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, IntWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const IntWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(IntWrapperType, Kind) {
EXPECT_EQ(IntWrapperType().kind(), IntWrapperType::kKind);
EXPECT_EQ(Type(IntWrapperType()).kind(), IntWrapperType::kKind);
}
TEST(IntWrapperType, Name) {
EXPECT_EQ(IntWrapperType().name(), IntWrapperType::kName);
EXPECT_EQ(Type(IntWrapperType()).name(), IntWrapperType::kName);
}
TEST(IntWrapperType, DebugString) {
{
std::ostringstream out;
out << IntWrapperType();
EXPECT_EQ(out.str(), IntWrapperType::kName);
}
{
std::ostringstream out;
out << Type(IntWrapperType());
EXPECT_EQ(out.str(), IntWrapperType::kName);
}
}
TEST(IntWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(IntWrapperType()), absl::HashOf(IntWrapperType()));
}
TEST(IntWrapperType, Equal) {
EXPECT_EQ(IntWrapperType(), IntWrapperType());
EXPECT_EQ(Type(IntWrapperType()), IntWrapperType());
EXPECT_EQ(IntWrapperType(), Type(IntWrapperType()));
EXPECT_EQ(Type(IntWrapperType()), Type(IntWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/int_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/int_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
76550dac-69ef-42d5-8854-311eb683d6cd | cpp | google/cel-cpp | null_type | common/types/null_type.h | common/types/null_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_NULL_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_NULL_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class NullType final {
public:
static constexpr TypeKind kKind = TypeKind::kNull;
static constexpr absl::string_view kName = "null_type";
NullType() = default;
NullType(const NullType&) = default;
NullType(NullType&&) = default;
NullType& operator=(const NullType&) = default;
NullType& operator=(NullType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(NullType&) noexcept {}
};
inline constexpr void swap(NullType& lhs, NullType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(NullType, NullType) { return true; }
inline constexpr bool operator!=(NullType lhs, NullType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, NullType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const NullType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(NullType, Kind) {
EXPECT_EQ(NullType().kind(), NullType::kKind);
EXPECT_EQ(Type(NullType()).kind(), NullType::kKind);
}
TEST(NullType, Name) {
EXPECT_EQ(NullType().name(), NullType::kName);
EXPECT_EQ(Type(NullType()).name(), NullType::kName);
}
TEST(NullType, DebugString) {
{
std::ostringstream out;
out << NullType();
EXPECT_EQ(out.str(), NullType::kName);
}
{
std::ostringstream out;
out << Type(NullType());
EXPECT_EQ(out.str(), NullType::kName);
}
}
TEST(NullType, Hash) {
EXPECT_EQ(absl::HashOf(NullType()), absl::HashOf(NullType()));
}
TEST(NullType, Equal) {
EXPECT_EQ(NullType(), NullType());
EXPECT_EQ(Type(NullType()), NullType());
EXPECT_EQ(NullType(), Type(NullType()));
EXPECT_EQ(Type(NullType()), Type(NullType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/null_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/null_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
3ebbc352-a229-49cf-9041-6f9176427a0c | cpp | google/cel-cpp | bool_type | common/types/bool_type.h | common/types/bool_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_BOOL_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_BOOL_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class BoolType final {
public:
static constexpr TypeKind kKind = TypeKind::kBool;
static constexpr absl::string_view kName = "bool";
BoolType() = default;
BoolType(const BoolType&) = default;
BoolType(BoolType&&) = default;
BoolType& operator=(const BoolType&) = default;
BoolType& operator=(BoolType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(BoolType&) noexcept {}
};
inline constexpr void swap(BoolType& lhs, BoolType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(BoolType, BoolType) { return true; }
inline constexpr bool operator!=(BoolType lhs, BoolType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, BoolType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const BoolType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(BoolType, Kind) {
EXPECT_EQ(BoolType().kind(), BoolType::kKind);
EXPECT_EQ(Type(BoolType()).kind(), BoolType::kKind);
}
TEST(BoolType, Name) {
EXPECT_EQ(BoolType().name(), BoolType::kName);
EXPECT_EQ(Type(BoolType()).name(), BoolType::kName);
}
TEST(BoolType, DebugString) {
{
std::ostringstream out;
out << BoolType();
EXPECT_EQ(out.str(), BoolType::kName);
}
{
std::ostringstream out;
out << Type(BoolType());
EXPECT_EQ(out.str(), BoolType::kName);
}
}
TEST(BoolType, Hash) {
EXPECT_EQ(absl::HashOf(BoolType()), absl::HashOf(BoolType()));
}
TEST(BoolType, Equal) {
EXPECT_EQ(BoolType(), BoolType());
EXPECT_EQ(Type(BoolType()), BoolType());
EXPECT_EQ(BoolType(), Type(BoolType()));
EXPECT_EQ(Type(BoolType()), Type(BoolType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bool_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bool_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
df77bd3e-397c-4a38-83b1-b0e4b4a814d7 | cpp | google/cel-cpp | bytes_wrapper_type | common/types/bytes_wrapper_type.h | common/types/bytes_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_BYTES_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_BYTES_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class BytesWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kBytesWrapper;
static constexpr absl::string_view kName = "google.protobuf.BytesValue";
BytesWrapperType() = default;
BytesWrapperType(const BytesWrapperType&) = default;
BytesWrapperType(BytesWrapperType&&) = default;
BytesWrapperType& operator=(const BytesWrapperType&) = default;
BytesWrapperType& operator=(BytesWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(BytesWrapperType&) noexcept {}
};
inline constexpr void swap(BytesWrapperType& lhs,
BytesWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(BytesWrapperType, BytesWrapperType) {
return true;
}
inline constexpr bool operator!=(BytesWrapperType lhs, BytesWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, BytesWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out,
const BytesWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(BytesWrapperType, Kind) {
EXPECT_EQ(BytesWrapperType().kind(), BytesWrapperType::kKind);
EXPECT_EQ(Type(BytesWrapperType()).kind(), BytesWrapperType::kKind);
}
TEST(BytesWrapperType, Name) {
EXPECT_EQ(BytesWrapperType().name(), BytesWrapperType::kName);
EXPECT_EQ(Type(BytesWrapperType()).name(), BytesWrapperType::kName);
}
TEST(BytesWrapperType, DebugString) {
{
std::ostringstream out;
out << BytesWrapperType();
EXPECT_EQ(out.str(), BytesWrapperType::kName);
}
{
std::ostringstream out;
out << Type(BytesWrapperType());
EXPECT_EQ(out.str(), BytesWrapperType::kName);
}
}
TEST(BytesWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(BytesWrapperType()), absl::HashOf(BytesWrapperType()));
}
TEST(BytesWrapperType, Equal) {
EXPECT_EQ(BytesWrapperType(), BytesWrapperType());
EXPECT_EQ(Type(BytesWrapperType()), BytesWrapperType());
EXPECT_EQ(BytesWrapperType(), Type(BytesWrapperType()));
EXPECT_EQ(Type(BytesWrapperType()), Type(BytesWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bytes_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bytes_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
e878a070-b00e-42a5-8095-09a09366c7e6 | cpp | google/cel-cpp | string_type | common/types/string_type.h | common/types/string_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_STRING_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_STRING_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class StringType final {
public:
static constexpr TypeKind kKind = TypeKind::kString;
static constexpr absl::string_view kName = "string";
StringType() = default;
StringType(const StringType&) = default;
StringType(StringType&&) = default;
StringType& operator=(const StringType&) = default;
StringType& operator=(StringType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
std::string DebugString() const { return std::string(name()); }
constexpr void swap(StringType&) noexcept {}
};
inline constexpr void swap(StringType& lhs, StringType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(StringType, StringType) { return true; }
inline constexpr bool operator!=(StringType lhs, StringType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, StringType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const StringType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(StringType, Kind) {
EXPECT_EQ(StringType().kind(), StringType::kKind);
EXPECT_EQ(Type(StringType()).kind(), StringType::kKind);
}
TEST(StringType, Name) {
EXPECT_EQ(StringType().name(), StringType::kName);
EXPECT_EQ(Type(StringType()).name(), StringType::kName);
}
TEST(StringType, DebugString) {
{
std::ostringstream out;
out << StringType();
EXPECT_EQ(out.str(), StringType::kName);
}
{
std::ostringstream out;
out << Type(StringType());
EXPECT_EQ(out.str(), StringType::kName);
}
}
TEST(StringType, Hash) {
EXPECT_EQ(absl::HashOf(StringType()), absl::HashOf(StringType()));
}
TEST(StringType, Equal) {
EXPECT_EQ(StringType(), StringType());
EXPECT_EQ(Type(StringType()), StringType());
EXPECT_EQ(StringType(), Type(StringType()));
EXPECT_EQ(Type(StringType()), Type(StringType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/string_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/string_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
13107c29-57b7-48ab-a8cf-a9ea30beefd5 | cpp | google/cel-cpp | unknown_type | common/types/unknown_type.h | common/types/unknown_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_UNKNOWN_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_UNKNOWN_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class UnknownType final {
public:
static constexpr TypeKind kKind = TypeKind::kUnknown;
static constexpr absl::string_view kName = "*unknown*";
UnknownType() = default;
UnknownType(const UnknownType&) = default;
UnknownType(UnknownType&&) = default;
UnknownType& operator=(const UnknownType&) = default;
UnknownType& operator=(UnknownType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(UnknownType&) noexcept {}
};
inline constexpr void swap(UnknownType& lhs, UnknownType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(UnknownType, UnknownType) { return true; }
inline constexpr bool operator!=(UnknownType lhs, UnknownType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, UnknownType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const UnknownType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(UnknownType, Kind) {
EXPECT_EQ(UnknownType().kind(), UnknownType::kKind);
EXPECT_EQ(Type(UnknownType()).kind(), UnknownType::kKind);
}
TEST(UnknownType, Name) {
EXPECT_EQ(UnknownType().name(), UnknownType::kName);
EXPECT_EQ(Type(UnknownType()).name(), UnknownType::kName);
}
TEST(UnknownType, DebugString) {
{
std::ostringstream out;
out << UnknownType();
EXPECT_EQ(out.str(), UnknownType::kName);
}
{
std::ostringstream out;
out << Type(UnknownType());
EXPECT_EQ(out.str(), UnknownType::kName);
}
}
TEST(UnknownType, Hash) {
EXPECT_EQ(absl::HashOf(UnknownType()), absl::HashOf(UnknownType()));
}
TEST(UnknownType, Equal) {
EXPECT_EQ(UnknownType(), UnknownType());
EXPECT_EQ(Type(UnknownType()), UnknownType());
EXPECT_EQ(UnknownType(), Type(UnknownType()));
EXPECT_EQ(Type(UnknownType()), Type(UnknownType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/unknown_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/unknown_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
c0a082eb-4df1-4931-b681-2dda0d5de58d | cpp | google/cel-cpp | bool_wrapper_type | common/types/bool_wrapper_type.h | common/types/bool_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_BOOL_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_BOOL_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class BoolWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kBoolWrapper;
static constexpr absl::string_view kName = "google.protobuf.BoolValue";
BoolWrapperType() = default;
BoolWrapperType(const BoolWrapperType&) = default;
BoolWrapperType(BoolWrapperType&&) = default;
BoolWrapperType& operator=(const BoolWrapperType&) = default;
BoolWrapperType& operator=(BoolWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(BoolWrapperType&) noexcept {}
};
inline constexpr void swap(BoolWrapperType& lhs,
BoolWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(BoolWrapperType, BoolWrapperType) {
return true;
}
inline constexpr bool operator!=(BoolWrapperType lhs, BoolWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, BoolWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out,
const BoolWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(BoolWrapperType, Kind) {
EXPECT_EQ(BoolWrapperType().kind(), BoolWrapperType::kKind);
EXPECT_EQ(Type(BoolWrapperType()).kind(), BoolWrapperType::kKind);
}
TEST(BoolWrapperType, Name) {
EXPECT_EQ(BoolWrapperType().name(), BoolWrapperType::kName);
EXPECT_EQ(Type(BoolWrapperType()).name(), BoolWrapperType::kName);
}
TEST(BoolWrapperType, DebugString) {
{
std::ostringstream out;
out << BoolWrapperType();
EXPECT_EQ(out.str(), BoolWrapperType::kName);
}
{
std::ostringstream out;
out << Type(BoolWrapperType());
EXPECT_EQ(out.str(), BoolWrapperType::kName);
}
}
TEST(BoolWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(BoolWrapperType()), absl::HashOf(BoolWrapperType()));
}
TEST(BoolWrapperType, Equal) {
EXPECT_EQ(BoolWrapperType(), BoolWrapperType());
EXPECT_EQ(Type(BoolWrapperType()), BoolWrapperType());
EXPECT_EQ(BoolWrapperType(), Type(BoolWrapperType()));
EXPECT_EQ(Type(BoolWrapperType()), Type(BoolWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bool_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bool_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
952e58de-4b22-4a59-8c11-cd3e4ecf4b7e | cpp | google/cel-cpp | bytes_type | common/types/bytes_type.h | common/types/bytes_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_BYTES_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_BYTES_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class BytesType final {
public:
static constexpr TypeKind kKind = TypeKind::kBytes;
static constexpr absl::string_view kName = "bytes";
BytesType() = default;
BytesType(const BytesType&) = default;
BytesType(BytesType&&) = default;
BytesType& operator=(const BytesType&) = default;
BytesType& operator=(BytesType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(BytesType&) noexcept {}
};
inline constexpr void swap(BytesType& lhs, BytesType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(BytesType, BytesType) { return true; }
inline constexpr bool operator!=(BytesType lhs, BytesType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, BytesType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const BytesType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(BytesType, Kind) {
EXPECT_EQ(BytesType().kind(), BytesType::kKind);
EXPECT_EQ(Type(BytesType()).kind(), BytesType::kKind);
}
TEST(BytesType, Name) {
EXPECT_EQ(BytesType().name(), BytesType::kName);
EXPECT_EQ(Type(BytesType()).name(), BytesType::kName);
}
TEST(BytesType, DebugString) {
{
std::ostringstream out;
out << BytesType();
EXPECT_EQ(out.str(), BytesType::kName);
}
{
std::ostringstream out;
out << Type(BytesType());
EXPECT_EQ(out.str(), BytesType::kName);
}
}
TEST(BytesType, Hash) {
EXPECT_EQ(absl::HashOf(BytesType()), absl::HashOf(BytesType()));
}
TEST(BytesType, Equal) {
EXPECT_EQ(BytesType(), BytesType());
EXPECT_EQ(Type(BytesType()), BytesType());
EXPECT_EQ(BytesType(), Type(BytesType()));
EXPECT_EQ(Type(BytesType()), Type(BytesType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bytes_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/bytes_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
7d89dd65-9a99-458f-9936-e05ead4d4730 | cpp | google/cel-cpp | string_wrapper_type | common/types/string_wrapper_type.h | common/types/string_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_STRING_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_STRING_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class StringWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kStringWrapper;
static constexpr absl::string_view kName = "google.protobuf.StringValue";
StringWrapperType() = default;
StringWrapperType(const StringWrapperType&) = default;
StringWrapperType(StringWrapperType&&) = default;
StringWrapperType& operator=(const StringWrapperType&) = default;
StringWrapperType& operator=(StringWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(StringWrapperType&) noexcept {}
};
inline constexpr void swap(StringWrapperType& lhs,
StringWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(StringWrapperType, StringWrapperType) {
return true;
}
inline constexpr bool operator!=(StringWrapperType lhs, StringWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, StringWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out,
const StringWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(StringWrapperType, Kind) {
EXPECT_EQ(StringWrapperType().kind(), StringWrapperType::kKind);
EXPECT_EQ(Type(StringWrapperType()).kind(), StringWrapperType::kKind);
}
TEST(StringWrapperType, Name) {
EXPECT_EQ(StringWrapperType().name(), StringWrapperType::kName);
EXPECT_EQ(Type(StringWrapperType()).name(), StringWrapperType::kName);
}
TEST(StringWrapperType, DebugString) {
{
std::ostringstream out;
out << StringWrapperType();
EXPECT_EQ(out.str(), StringWrapperType::kName);
}
{
std::ostringstream out;
out << Type(StringWrapperType());
EXPECT_EQ(out.str(), StringWrapperType::kName);
}
}
TEST(StringWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(StringWrapperType()),
absl::HashOf(StringWrapperType()));
}
TEST(StringWrapperType, Equal) {
EXPECT_EQ(StringWrapperType(), StringWrapperType());
EXPECT_EQ(Type(StringWrapperType()), StringWrapperType());
EXPECT_EQ(StringWrapperType(), Type(StringWrapperType()));
EXPECT_EQ(Type(StringWrapperType()), Type(StringWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/string_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/string_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
965ee7f5-f994-44d4-af96-e70540dd901a | cpp | google/cel-cpp | dyn_type | common/types/dyn_type.h | common/types/dyn_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_DYN_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_DYN_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class DynType final {
public:
static constexpr TypeKind kKind = TypeKind::kDyn;
static constexpr absl::string_view kName = "dyn";
DynType() = default;
DynType(const DynType&) = default;
DynType(DynType&&) = default;
DynType& operator=(const DynType&) = default;
DynType& operator=(DynType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(DynType&) noexcept {}
};
inline constexpr void swap(DynType& lhs, DynType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(DynType, DynType) { return true; }
inline constexpr bool operator!=(DynType lhs, DynType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, DynType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const DynType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(DynType, Kind) {
EXPECT_EQ(DynType().kind(), DynType::kKind);
EXPECT_EQ(Type(DynType()).kind(), DynType::kKind);
}
TEST(DynType, Name) {
EXPECT_EQ(DynType().name(), DynType::kName);
EXPECT_EQ(Type(DynType()).name(), DynType::kName);
}
TEST(DynType, DebugString) {
{
std::ostringstream out;
out << DynType();
EXPECT_EQ(out.str(), DynType::kName);
}
{
std::ostringstream out;
out << Type(DynType());
EXPECT_EQ(out.str(), DynType::kName);
}
}
TEST(DynType, Hash) {
EXPECT_EQ(absl::HashOf(DynType()), absl::HashOf(DynType()));
}
TEST(DynType, Equal) {
EXPECT_EQ(DynType(), DynType());
EXPECT_EQ(Type(DynType()), DynType());
EXPECT_EQ(DynType(), Type(DynType()));
EXPECT_EQ(Type(DynType()), Type(DynType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/dyn_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/dyn_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5d78d715-f803-4538-adf8-a21734a52fc6 | cpp | google/cel-cpp | any_type | common/types/any_type.h | common/types/any_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_ANY_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_ANY_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class AnyType final {
public:
static constexpr TypeKind kKind = TypeKind::kAny;
static constexpr absl::string_view kName = "google.protobuf.Any";
AnyType() = default;
AnyType(const AnyType&) = default;
AnyType(AnyType&&) = default;
AnyType& operator=(const AnyType&) = default;
AnyType& operator=(AnyType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(AnyType&) noexcept {}
};
inline constexpr void swap(AnyType& lhs, AnyType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(AnyType, AnyType) { return true; }
inline constexpr bool operator!=(AnyType lhs, AnyType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, AnyType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const AnyType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(AnyType, Kind) {
EXPECT_EQ(AnyType().kind(), AnyType::kKind);
EXPECT_EQ(Type(AnyType()).kind(), AnyType::kKind);
}
TEST(AnyType, Name) {
EXPECT_EQ(AnyType().name(), AnyType::kName);
EXPECT_EQ(Type(AnyType()).name(), AnyType::kName);
}
TEST(AnyType, DebugString) {
{
std::ostringstream out;
out << AnyType();
EXPECT_EQ(out.str(), AnyType::kName);
}
{
std::ostringstream out;
out << Type(AnyType());
EXPECT_EQ(out.str(), AnyType::kName);
}
}
TEST(AnyType, Hash) {
EXPECT_EQ(absl::HashOf(AnyType()), absl::HashOf(AnyType()));
}
TEST(AnyType, Equal) {
EXPECT_EQ(AnyType(), AnyType());
EXPECT_EQ(Type(AnyType()), AnyType());
EXPECT_EQ(AnyType(), Type(AnyType()));
EXPECT_EQ(Type(AnyType()), Type(AnyType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/any_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/any_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
51c0f3b9-a0e8-42c4-a1a0-6013986f3d2b | cpp | google/cel-cpp | int_type | common/types/int_type.h | common/types/int_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_INT_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_INT_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class IntType final {
public:
static constexpr TypeKind kKind = TypeKind::kInt;
static constexpr absl::string_view kName = "int";
IntType() = default;
IntType(const IntType&) = default;
IntType(IntType&&) = default;
IntType& operator=(const IntType&) = default;
IntType& operator=(IntType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(IntType&) noexcept {}
};
inline constexpr void swap(IntType& lhs, IntType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(IntType, IntType) { return true; }
inline constexpr bool operator!=(IntType lhs, IntType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, IntType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const IntType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(IntType, Kind) {
EXPECT_EQ(IntType().kind(), IntType::kKind);
EXPECT_EQ(Type(IntType()).kind(), IntType::kKind);
}
TEST(IntType, Name) {
EXPECT_EQ(IntType().name(), IntType::kName);
EXPECT_EQ(Type(IntType()).name(), IntType::kName);
}
TEST(IntType, DebugString) {
{
std::ostringstream out;
out << IntType();
EXPECT_EQ(out.str(), IntType::kName);
}
{
std::ostringstream out;
out << Type(IntType());
EXPECT_EQ(out.str(), IntType::kName);
}
}
TEST(IntType, Hash) {
EXPECT_EQ(absl::HashOf(IntType()), absl::HashOf(IntType()));
}
TEST(IntType, Equal) {
EXPECT_EQ(IntType(), IntType());
EXPECT_EQ(Type(IntType()), IntType());
EXPECT_EQ(IntType(), Type(IntType()));
EXPECT_EQ(Type(IntType()), Type(IntType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/int_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/int_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
1036b1df-8b68-4267-bcd2-83a33e692cb7 | cpp | google/cel-cpp | double_wrapper_type | common/types/double_wrapper_type.h | common/types/double_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_DOUBLE_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_DOUBLE_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class DoubleWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kDoubleWrapper;
static constexpr absl::string_view kName = "google.protobuf.DoubleValue";
DoubleWrapperType() = default;
DoubleWrapperType(const DoubleWrapperType&) = default;
DoubleWrapperType(DoubleWrapperType&&) = default;
DoubleWrapperType& operator=(const DoubleWrapperType&) = default;
DoubleWrapperType& operator=(DoubleWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(DoubleWrapperType&) noexcept {}
};
inline constexpr void swap(DoubleWrapperType& lhs,
DoubleWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(DoubleWrapperType, DoubleWrapperType) {
return true;
}
inline constexpr bool operator!=(DoubleWrapperType lhs, DoubleWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, DoubleWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out,
const DoubleWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(DoubleWrapperType, Kind) {
EXPECT_EQ(DoubleWrapperType().kind(), DoubleWrapperType::kKind);
EXPECT_EQ(Type(DoubleWrapperType()).kind(), DoubleWrapperType::kKind);
}
TEST(DoubleWrapperType, Name) {
EXPECT_EQ(DoubleWrapperType().name(), DoubleWrapperType::kName);
EXPECT_EQ(Type(DoubleWrapperType()).name(), DoubleWrapperType::kName);
}
TEST(DoubleWrapperType, DebugString) {
{
std::ostringstream out;
out << DoubleWrapperType();
EXPECT_EQ(out.str(), DoubleWrapperType::kName);
}
{
std::ostringstream out;
out << Type(DoubleWrapperType());
EXPECT_EQ(out.str(), DoubleWrapperType::kName);
}
}
TEST(DoubleWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(DoubleWrapperType()),
absl::HashOf(DoubleWrapperType()));
}
TEST(DoubleWrapperType, Equal) {
EXPECT_EQ(DoubleWrapperType(), DoubleWrapperType());
EXPECT_EQ(Type(DoubleWrapperType()), DoubleWrapperType());
EXPECT_EQ(DoubleWrapperType(), Type(DoubleWrapperType()));
EXPECT_EQ(Type(DoubleWrapperType()), Type(DoubleWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/double_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/double_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
deabf8d9-6a66-4e47-89da-b1da47e70165 | cpp | google/cel-cpp | legacy_type_reflector | common/values/legacy_type_reflector.h | common/legacy_type_reflector_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_LEGACY_TYPE_REFLECTOR_H_
#define THIRD_PARTY_CEL_CPP_COMMON_VALUES_LEGACY_TYPE_REFLECTOR_H_
#include "common/type_reflector.h"
#endif | #include <utility>
#include "absl/status/status.h"
#include "common/legacy_value.h"
#include "common/memory.h"
#include "common/type_reflector.h"
#include "common/value.h"
#include "common/value_testing.h"
#include "common/values/legacy_value_manager.h"
#include "internal/testing.h"
namespace cel {
namespace {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::cel::common_internal::LegacyValueManager;
using ::cel::interop_internal::TestOnly_IsLegacyListBuilder;
using ::cel::interop_internal::TestOnly_IsLegacyMapBuilder;
class TypeReflectorLegacyTest
: public common_internal::ThreadCompatibleValueTest<> {};
TEST_P(TypeReflectorLegacyTest, NewListValueBuilderLegacyOptimized) {
LegacyValueManager manager(memory_manager(), TypeReflector::LegacyBuiltin());
ASSERT_OK_AND_ASSIGN(auto builder,
manager.NewListValueBuilder(manager.GetDynListType()));
switch (memory_management()) {
case MemoryManagement::kPooling:
EXPECT_TRUE(TestOnly_IsLegacyListBuilder(*builder));
break;
case MemoryManagement::kReferenceCounting:
EXPECT_FALSE(TestOnly_IsLegacyListBuilder(*builder));
break;
}
}
TEST_P(TypeReflectorLegacyTest, NewMapValueBuilderLegacyOptimized) {
LegacyValueManager manager(memory_manager(), TypeReflector::LegacyBuiltin());
ASSERT_OK_AND_ASSIGN(auto builder,
manager.NewMapValueBuilder(manager.GetDynDynMapType()));
switch (memory_management()) {
case MemoryManagement::kPooling:
EXPECT_TRUE(TestOnly_IsLegacyMapBuilder(*builder));
break;
case MemoryManagement::kReferenceCounting:
EXPECT_FALSE(TestOnly_IsLegacyMapBuilder(*builder));
break;
}
}
TEST_P(TypeReflectorLegacyTest, ListImplementationNext) {
LegacyValueManager manager(memory_manager(), TypeReflector::LegacyBuiltin());
ASSERT_OK_AND_ASSIGN(auto builder,
manager.NewListValueBuilder(manager.GetDynListType()));
EXPECT_OK(builder->Add(IntValue(1)));
EXPECT_OK(builder->Add(IntValue(2)));
EXPECT_OK(builder->Add(IntValue(3)));
EXPECT_EQ(builder->Size(), 3);
EXPECT_FALSE(builder->IsEmpty());
auto value = std::move(*builder).Build();
EXPECT_THAT(value.Size(), IsOkAndHolds(3));
ASSERT_OK_AND_ASSIGN(auto iterator, value.NewIterator(manager));
while (iterator->HasNext()) {
EXPECT_OK(iterator->Next(manager));
}
EXPECT_FALSE(iterator->HasNext());
EXPECT_THAT(iterator->Next(manager),
StatusIs(absl::StatusCode::kFailedPrecondition));
}
INSTANTIATE_TEST_SUITE_P(Default, TypeReflectorLegacyTest,
testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting));
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/legacy_type_reflector.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/legacy_type_reflector_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5eb69629-495f-4efe-8e13-19cb96a2dada | cpp | google/cel-cpp | data_interface | common/internal/data_interface.h | common/internal/data_interface_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_DATA_INTERFACE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_DATA_INTERFACE_H_
#include <type_traits>
#include "absl/base/attributes.h"
#include "common/native_type.h"
namespace cel {
class TypeInterface;
class ValueInterface;
namespace common_internal {
class DataInterface;
class DataInterface {
public:
DataInterface(const DataInterface&) = delete;
DataInterface(DataInterface&&) = delete;
virtual ~DataInterface() = default;
DataInterface& operator=(const DataInterface&) = delete;
DataInterface& operator=(DataInterface&&) = delete;
protected:
DataInterface() = default;
private:
friend class cel::TypeInterface;
friend class cel::ValueInterface;
friend struct NativeTypeTraits<DataInterface>;
virtual NativeTypeId GetNativeTypeId() const = 0;
};
}
template <>
struct NativeTypeTraits<common_internal::DataInterface> final {
static NativeTypeId Id(const common_internal::DataInterface& data_interface) {
return data_interface.GetNativeTypeId();
}
};
template <typename T>
struct NativeTypeTraits<
T, std::enable_if_t<std::conjunction_v<
std::is_base_of<common_internal::DataInterface, T>,
std::negation<std::is_same<T, common_internal::DataInterface>>>>>
final {
static NativeTypeId Id(const common_internal::DataInterface& data_interface) {
return NativeTypeTraits<common_internal::DataInterface>::Id(data_interface);
}
};
}
#endif | #include "common/internal/data_interface.h"
#include <memory>
#include "common/native_type.h"
#include "internal/testing.h"
namespace cel::common_internal {
namespace {
namespace data_interface_test {
class TestInterface final : public DataInterface {
private:
NativeTypeId GetNativeTypeId() const override {
return NativeTypeId::For<TestInterface>();
}
};
}
TEST(DataInterface, GetNativeTypeId) {
auto data = std::make_unique<data_interface_test::TestInterface>();
EXPECT_EQ(NativeTypeId::Of(*data),
NativeTypeId::For<data_interface_test::TestInterface>());
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/data_interface.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/data_interface_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
5b3f7e47-3d28-4c3f-83c1-0913c8b1626a | cpp | google/cel-cpp | message_wrapper | base/internal/message_wrapper.h | eval/public/message_wrapper_test.cc | #ifndef THIRD_PARTY_CEL_CPP_BASE_INTERNAL_MESSAGE_WRAPPER_H_
#define THIRD_PARTY_CEL_CPP_BASE_INTERNAL_MESSAGE_WRAPPER_H_
#include <cstdint>
namespace cel::base_internal {
inline constexpr uintptr_t kMessageWrapperTagMask = 0b1;
inline constexpr uintptr_t kMessageWrapperPtrMask = ~kMessageWrapperTagMask;
inline constexpr int kMessageWrapperTagSize = 1;
inline constexpr uintptr_t kMessageWrapperTagTypeInfoValue = 0b0;
inline constexpr uintptr_t kMessageWrapperTagMessageValue = 0b1;
}
#endif | #include "eval/public/message_wrapper.h"
#include <type_traits>
#include "google/protobuf/message.h"
#include "google/protobuf/message_lite.h"
#include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/casts.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
TEST(MessageWrapper, Size) {
static_assert(sizeof(MessageWrapper) <= 2 * sizeof(uintptr_t),
"MessageWrapper must not increase CelValue size.");
}
TEST(MessageWrapper, WrapsMessage) {
TestMessage test_message;
test_message.set_int64_value(20);
test_message.set_double_value(12.3);
MessageWrapper wrapped_message(&test_message, TrivialTypeInfo::GetInstance());
constexpr bool is_full_proto_runtime =
std::is_base_of_v<google::protobuf::Message, TestMessage>;
EXPECT_EQ(wrapped_message.message_ptr(),
static_cast<const google::protobuf::MessageLite*>(&test_message));
ASSERT_EQ(wrapped_message.HasFullProto(), is_full_proto_runtime);
}
TEST(MessageWrapperBuilder, Builder) {
TestMessage test_message;
MessageWrapper::Builder builder(&test_message);
constexpr bool is_full_proto_runtime =
std::is_base_of_v<google::protobuf::Message, TestMessage>;
ASSERT_EQ(builder.HasFullProto(), is_full_proto_runtime);
ASSERT_EQ(builder.message_ptr(),
static_cast<google::protobuf::MessageLite*>(&test_message));
auto mutable_message =
cel::internal::down_cast<TestMessage*>(builder.message_ptr());
mutable_message->set_int64_value(20);
mutable_message->set_double_value(12.3);
MessageWrapper wrapped_message =
builder.Build(TrivialTypeInfo::GetInstance());
ASSERT_EQ(wrapped_message.message_ptr(),
static_cast<const google::protobuf::MessageLite*>(&test_message));
ASSERT_EQ(wrapped_message.HasFullProto(), is_full_proto_runtime);
EXPECT_EQ(wrapped_message.message_ptr(),
static_cast<const google::protobuf::MessageLite*>(&test_message));
EXPECT_EQ(test_message.int64_value(), 20);
EXPECT_EQ(test_message.double_value(), 12.3);
}
TEST(MessageWrapper, DefaultNull) {
MessageWrapper wrapper;
EXPECT_EQ(wrapper.message_ptr(), nullptr);
EXPECT_EQ(wrapper.legacy_type_info(), nullptr);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/internal/message_wrapper.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/message_wrapper_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
45587220-e750-404f-9906-bd0f0490ad7b | cpp | google/cel-cpp | unknown_attribute_set | eval/public/unknown_attribute_set.h | eval/public/unknown_attribute_set_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_UNKNOWN_ATTRIBUTE_SET_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_UNKNOWN_ATTRIBUTE_SET_H_
#include "base/attribute_set.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
using UnknownAttributeSet = ::cel::AttributeSet;
}
}
}
}
#endif | #include "eval/public/unknown_attribute_set.h"
#include <memory>
#include <string>
#include <vector>
#include "eval/public/cel_attribute.h"
#include "eval/public/cel_value.h"
#include "internal/testing.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
using ::testing::Eq;
using google::api::expr::v1alpha1::Expr;
TEST(UnknownAttributeSetTest, TestCreate) {
const std::string kAttr1 = "a1";
const std::string kAttr2 = "a2";
const std::string kAttr3 = "a3";
std::shared_ptr<CelAttribute> cel_attr = std::make_shared<CelAttribute>(
"root", std::vector<CelAttributeQualifier>(
{CreateCelAttributeQualifier(CelValue::CreateString(&kAttr1)),
CreateCelAttributeQualifier(CelValue::CreateInt64(1)),
CreateCelAttributeQualifier(CelValue::CreateUint64(2)),
CreateCelAttributeQualifier(CelValue::CreateBool(true))}));
UnknownAttributeSet unknown_set({*cel_attr});
EXPECT_THAT(unknown_set.size(), Eq(1));
EXPECT_THAT(*(unknown_set.begin()), Eq(*cel_attr));
}
TEST(UnknownAttributeSetTest, TestMergeSets) {
const std::string kAttr1 = "a1";
const std::string kAttr2 = "a2";
const std::string kAttr3 = "a3";
CelAttribute cel_attr1(
"root", std::vector<CelAttributeQualifier>(
{CreateCelAttributeQualifier(CelValue::CreateString(&kAttr1)),
CreateCelAttributeQualifier(CelValue::CreateInt64(1)),
CreateCelAttributeQualifier(CelValue::CreateUint64(2)),
CreateCelAttributeQualifier(CelValue::CreateBool(true))}));
CelAttribute cel_attr1_copy(
"root", std::vector<CelAttributeQualifier>(
{CreateCelAttributeQualifier(CelValue::CreateString(&kAttr1)),
CreateCelAttributeQualifier(CelValue::CreateInt64(1)),
CreateCelAttributeQualifier(CelValue::CreateUint64(2)),
CreateCelAttributeQualifier(CelValue::CreateBool(true))}));
CelAttribute cel_attr2(
"root", std::vector<CelAttributeQualifier>(
{CreateCelAttributeQualifier(CelValue::CreateString(&kAttr1)),
CreateCelAttributeQualifier(CelValue::CreateInt64(2)),
CreateCelAttributeQualifier(CelValue::CreateUint64(2)),
CreateCelAttributeQualifier(CelValue::CreateBool(true))}));
CelAttribute cel_attr3(
"root", std::vector<CelAttributeQualifier>(
{CreateCelAttributeQualifier(CelValue::CreateString(&kAttr1)),
CreateCelAttributeQualifier(CelValue::CreateInt64(2)),
CreateCelAttributeQualifier(CelValue::CreateUint64(2)),
CreateCelAttributeQualifier(CelValue::CreateBool(false))}));
UnknownAttributeSet unknown_set1({cel_attr1, cel_attr2});
UnknownAttributeSet unknown_set2({cel_attr1_copy, cel_attr3});
UnknownAttributeSet unknown_set3 =
UnknownAttributeSet::Merge(unknown_set1, unknown_set2);
EXPECT_THAT(unknown_set3.size(), Eq(3));
std::vector<CelAttribute> attrs1;
for (const auto& attr_ptr : unknown_set3) {
attrs1.push_back(attr_ptr);
}
std::vector<CelAttribute> attrs2 = {cel_attr1, cel_attr2, cel_attr3};
EXPECT_THAT(attrs1, testing::UnorderedPointwise(Eq(), attrs2));
}
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/unknown_attribute_set.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/unknown_attribute_set_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
f5697065-59c0-4051-9bd7-069f12d245b5 | cpp | google/cel-cpp | cel_function_adapter | eval/public/cel_function_adapter.h | eval/public/cel_function_adapter_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_FUNCTION_ADAPTER_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_FUNCTION_ADAPTER_H_
#include <cstdint>
#include <functional>
#include <optional>
#include <type_traits>
#include <utility>
#include "google/protobuf/message.h"
#include "absl/status/status.h"
#include "eval/public/cel_function_adapter_impl.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/cel_proto_wrapper.h"
namespace google::api::expr::runtime {
namespace internal {
struct ProtoAdapterTypeCodeMatcher {
template <typename T>
constexpr static std::optional<CelValue::Type> type_code() {
if constexpr (std::is_same_v<T, const google::protobuf::Message*>) {
return CelValue::Type::kMessage;
} else {
return internal::TypeCodeMatcher().type_code<T>();
}
}
};
struct ProtoAdapterValueConverter
: public internal::ValueConverterBase<ProtoAdapterValueConverter> {
using BaseType = internal::ValueConverterBase<ProtoAdapterValueConverter>;
using BaseType::NativeToValue;
using BaseType::ValueToNative;
absl::Status NativeToValue(const ::google::protobuf::Message* value,
::google::protobuf::Arena* arena, CelValue* result) {
if (value == nullptr) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Null Message pointer returned");
}
*result = CelProtoWrapper::CreateMessage(value, arena);
return absl::OkStatus();
}
};
}
template <typename ReturnType, typename... Arguments>
using FunctionAdapter =
internal::FunctionAdapterImpl<internal::ProtoAdapterTypeCodeMatcher,
internal::ProtoAdapterValueConverter>::
FunctionAdapter<ReturnType, Arguments...>;
template <typename ReturnType, typename T>
using UnaryFunctionAdapter = internal::FunctionAdapterImpl<
internal::ProtoAdapterTypeCodeMatcher,
internal::ProtoAdapterValueConverter>::UnaryFunction<ReturnType, T>;
template <typename ReturnType, typename T, typename U>
using BinaryFunctionAdapter = internal::FunctionAdapterImpl<
internal::ProtoAdapterTypeCodeMatcher,
internal::ProtoAdapterValueConverter>::BinaryFunction<ReturnType, T, U>;
}
#endif | #include "eval/public/cel_function_adapter.h"
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include "internal/status_macros.h"
#include "internal/testing.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
TEST(CelFunctionAdapterTest, TestAdapterNoArg) {
auto func = [](google::protobuf::Arena*) -> int64_t { return 100; };
ASSERT_OK_AND_ASSIGN(
auto cel_func, (FunctionAdapter<int64_t>::Create("const", false, func)));
absl::Span<CelValue> args;
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsInt64());
}
TEST(CelFunctionAdapterTest, TestAdapterOneArg) {
std::function<int64_t(google::protobuf::Arena*, int64_t)> func =
[](google::protobuf::Arena* arena, int64_t i) -> int64_t { return i + 1; };
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<int64_t, int64_t>::Create("_++_", false, func)));
std::vector<CelValue> args_vec;
args_vec.push_back(CelValue::CreateInt64(99));
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
absl::Span<CelValue> args(&args_vec[0], args_vec.size());
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 100);
}
TEST(CelFunctionAdapterTest, TestAdapterTwoArgs) {
auto func = [](google::protobuf::Arena* arena, int64_t i, int64_t j) -> int64_t {
return i + j;
};
ASSERT_OK_AND_ASSIGN(auto cel_func,
(FunctionAdapter<int64_t, int64_t, int64_t>::Create(
"_++_", false, func)));
std::vector<CelValue> args_vec;
args_vec.push_back(CelValue::CreateInt64(20));
args_vec.push_back(CelValue::CreateInt64(22));
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
absl::Span<CelValue> args(&args_vec[0], args_vec.size());
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 42);
}
using StringHolder = CelValue::StringHolder;
TEST(CelFunctionAdapterTest, TestAdapterThreeArgs) {
auto func = [](google::protobuf::Arena* arena, StringHolder s1, StringHolder s2,
StringHolder s3) -> StringHolder {
std::string value = absl::StrCat(s1.value(), s2.value(), s3.value());
return StringHolder(
google::protobuf::Arena::Create<std::string>(arena, std::move(value)));
};
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<StringHolder, StringHolder, StringHolder,
StringHolder>::Create("concat", false, func)));
std::string test1 = "1";
std::string test2 = "2";
std::string test3 = "3";
std::vector<CelValue> args_vec;
args_vec.push_back(CelValue::CreateString(&test1));
args_vec.push_back(CelValue::CreateString(&test2));
args_vec.push_back(CelValue::CreateString(&test3));
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
absl::Span<CelValue> args(&args_vec[0], args_vec.size());
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsString());
EXPECT_EQ(result.StringOrDie().value(), "123");
}
TEST(CelFunctionAdapterTest, TestTypeDeductionForCelValueBasicTypes) {
auto func = [](google::protobuf::Arena* arena, bool, int64_t, uint64_t, double,
CelValue::StringHolder, CelValue::BytesHolder,
const google::protobuf::Message*, absl::Duration, absl::Time,
const CelList*, const CelMap*,
const CelError*) -> bool { return false; };
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<bool, bool, int64_t, uint64_t, double,
CelValue::StringHolder, CelValue::BytesHolder,
const google::protobuf::Message*, absl::Duration, absl::Time,
const CelList*, const CelMap*,
const CelError*>::Create("dummy_func", false, func)));
auto descriptor = cel_func->descriptor();
EXPECT_EQ(descriptor.receiver_style(), false);
EXPECT_EQ(descriptor.name(), "dummy_func");
int pos = 0;
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kBool);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kInt64);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kUint64);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kDouble);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kString);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kBytes);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kMessage);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kDuration);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kTimestamp);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kList);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kMap);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kError);
}
TEST(CelFunctionAdapterTest, TestAdapterStatusOrMessage) {
auto func =
[](google::protobuf::Arena* arena) -> absl::StatusOr<const google::protobuf::Message*> {
auto* ret = google::protobuf::Arena::Create<google::protobuf::Timestamp>(arena);
ret->set_seconds(123);
return ret;
};
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<absl::StatusOr<const google::protobuf::Message*>>::Create(
"const", false, func)));
absl::Span<CelValue> args;
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsTimestamp());
EXPECT_EQ(result.TimestampOrDie(), absl::FromUnixSeconds(123));
}
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_function_adapter.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_function_adapter_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
e8d77878-5c89-4f56-bedc-a9c773970949 | cpp | google/cel-cpp | legacy_type_adapter | eval/public/structs/legacy_type_adapter.h | eval/public/structs/legacy_type_adapter_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_LEGACY_TYPE_ADPATER_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_LEGACY_TYPE_ADPATER_H_
#include <cstdint>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "base/attribute.h"
#include "common/memory.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
namespace google::api::expr::runtime {
class LegacyTypeMutationApis {
public:
virtual ~LegacyTypeMutationApis() = default;
virtual bool DefinesField(absl::string_view field_name) const = 0;
virtual absl::StatusOr<CelValue::MessageWrapper::Builder> NewInstance(
cel::MemoryManagerRef memory_manager) const = 0;
virtual absl::StatusOr<CelValue> AdaptFromWellKnownType(
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder instance) const = 0;
virtual absl::Status SetField(
absl::string_view field_name, const CelValue& value,
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder& instance) const = 0;
virtual absl::Status SetFieldByNumber(
int64_t field_number, const CelValue& value,
cel::MemoryManagerRef memory_manager,
CelValue::MessageWrapper::Builder& instance) const {
return absl::UnimplementedError("SetFieldByNumber is not yet implemented");
}
};
class LegacyTypeAccessApis {
public:
struct LegacyQualifyResult {
CelValue value;
int qualifier_count;
};
virtual ~LegacyTypeAccessApis() = default;
virtual absl::StatusOr<bool> HasField(
absl::string_view field_name,
const CelValue::MessageWrapper& value) const = 0;
virtual absl::StatusOr<CelValue> GetField(
absl::string_view field_name, const CelValue::MessageWrapper& instance,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager) const = 0;
virtual absl::StatusOr<LegacyQualifyResult> Qualify(
absl::Span<const cel::SelectQualifier>,
const CelValue::MessageWrapper& instance, bool presence_test,
cel::MemoryManagerRef memory_manager) const {
return absl::UnimplementedError("Qualify unsupported.");
}
virtual bool IsEqualTo(const CelValue::MessageWrapper&,
const CelValue::MessageWrapper&) const {
return false;
}
virtual std::vector<absl::string_view> ListFields(
const CelValue::MessageWrapper& instance) const = 0;
};
class LegacyTypeAdapter {
public:
LegacyTypeAdapter(const LegacyTypeAccessApis* access,
const LegacyTypeMutationApis* mutation)
: access_apis_(access), mutation_apis_(mutation) {}
const LegacyTypeAccessApis* access_apis() { return access_apis_; }
const LegacyTypeMutationApis* mutation_apis() { return mutation_apis_; }
private:
const LegacyTypeAccessApis* access_apis_;
const LegacyTypeMutationApis* mutation_apis_;
};
}
#endif | #include "eval/public/structs/legacy_type_adapter.h"
#include <vector>
#include "google/protobuf/arena.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/public/testing/matchers.h"
#include "eval/testutil/test_message.pb.h"
#include "extensions/protobuf/memory_manager.h"
#include "internal/status_macros.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
class TestAccessApiImpl : public LegacyTypeAccessApis {
public:
TestAccessApiImpl() {}
absl::StatusOr<bool> HasField(
absl::string_view field_name,
const CelValue::MessageWrapper& value) const override {
return absl::UnimplementedError("Not implemented");
}
absl::StatusOr<CelValue> GetField(
absl::string_view field_name, const CelValue::MessageWrapper& instance,
ProtoWrapperTypeOptions unboxing_option,
cel::MemoryManagerRef memory_manager) const override {
return absl::UnimplementedError("Not implemented");
}
std::vector<absl::string_view> ListFields(
const CelValue::MessageWrapper& instance) const override {
return std::vector<absl::string_view>();
}
};
TEST(LegacyTypeAdapterAccessApis, DefaultAlwaysInequal) {
TestMessage message;
MessageWrapper wrapper(&message, nullptr);
MessageWrapper wrapper2(&message, nullptr);
TestAccessApiImpl impl;
EXPECT_FALSE(impl.IsEqualTo(wrapper, wrapper2));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/legacy_type_adapter.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/legacy_type_adapter_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
e400d552-8f2c-4626-b7d9-d0f1ab1d67fe | cpp | google/cel-cpp | trivial_legacy_type_info | eval/public/structs/trivial_legacy_type_info.h | eval/public/structs/trivial_legacy_type_info_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_TRIVIAL_LEGACY_TYPE_INFO_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_TRIVIAL_LEGACY_TYPE_INFO_H_
#include <string>
#include "absl/base/no_destructor.h"
#include "absl/strings/string_view.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/legacy_type_info_apis.h"
namespace google::api::expr::runtime {
class TrivialTypeInfo : public LegacyTypeInfoApis {
public:
absl::string_view GetTypename(const MessageWrapper& wrapper) const override {
return "opaque";
}
std::string DebugString(const MessageWrapper& wrapper) const override {
return "opaque";
}
const LegacyTypeAccessApis* GetAccessApis(
const MessageWrapper& wrapper) const override {
return nullptr;
}
static const TrivialTypeInfo* GetInstance() {
static absl::NoDestructor<TrivialTypeInfo> kInstance;
return &*kInstance;
}
};
}
#endif | #include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/public/message_wrapper.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
TEST(TrivialTypeInfo, GetTypename) {
TrivialTypeInfo info;
MessageWrapper wrapper;
EXPECT_EQ(info.GetTypename(wrapper), "opaque");
EXPECT_EQ(TrivialTypeInfo::GetInstance()->GetTypename(wrapper), "opaque");
}
TEST(TrivialTypeInfo, DebugString) {
TrivialTypeInfo info;
MessageWrapper wrapper;
EXPECT_EQ(info.DebugString(wrapper), "opaque");
EXPECT_EQ(TrivialTypeInfo::GetInstance()->DebugString(wrapper), "opaque");
}
TEST(TrivialTypeInfo, GetAccessApis) {
TrivialTypeInfo info;
MessageWrapper wrapper;
EXPECT_EQ(info.GetAccessApis(wrapper), nullptr);
EXPECT_EQ(TrivialTypeInfo::GetInstance()->GetAccessApis(wrapper), nullptr);
}
TEST(TrivialTypeInfo, GetMutationApis) {
TrivialTypeInfo info;
MessageWrapper wrapper;
EXPECT_EQ(info.GetMutationApis(wrapper), nullptr);
EXPECT_EQ(TrivialTypeInfo::GetInstance()->GetMutationApis(wrapper), nullptr);
}
TEST(TrivialTypeInfo, FindFieldByName) {
TrivialTypeInfo info;
MessageWrapper wrapper;
EXPECT_EQ(info.FindFieldByName("foo"), absl::nullopt);
EXPECT_EQ(TrivialTypeInfo::GetInstance()->FindFieldByName("foo"),
absl::nullopt);
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/trivial_legacy_type_info.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/structs/trivial_legacy_type_info_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
d2483bbb-3d3a-4291-b99e-8aba17f70f7e | cpp | google/cel-cpp | field_backed_list_impl | eval/public/containers/field_backed_list_impl.h | eval/public/containers/field_backed_list_impl_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_FIELD_BACKED_LIST_IMPL_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_FIELD_BACKED_LIST_IMPL_H_
#include "eval/public/cel_value.h"
#include "eval/public/containers/internal_field_backed_list_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
class FieldBackedListImpl : public internal::FieldBackedListImpl {
public:
FieldBackedListImpl(const google::protobuf::Message* message,
const google::protobuf::FieldDescriptor* descriptor,
google::protobuf::Arena* arena)
: internal::FieldBackedListImpl(
message, descriptor, &CelProtoWrapper::InternalWrapMessage, arena) {
}
};
}
}
}
}
#endif | #include "eval/public/containers/field_backed_list_impl.h"
#include <memory>
#include <string>
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
#include "testutil/util.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
using ::testing::Eq;
using ::testing::DoubleEq;
using testutil::EqualsProto;
std::unique_ptr<CelList> CreateList(const TestMessage* message,
const std::string& field,
google::protobuf::Arena* arena) {
const google::protobuf::FieldDescriptor* field_desc =
message->GetDescriptor()->FindFieldByName(field);
return std::make_unique<FieldBackedListImpl>(message, field_desc, arena);
}
TEST(FieldBackedListImplTest, BoolDatatypeTest) {
TestMessage message;
message.add_bool_list(true);
message.add_bool_list(false);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "bool_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].BoolOrDie(), true);
EXPECT_EQ((*cel_list)[1].BoolOrDie(), false);
}
TEST(FieldBackedListImplTest, TestLength0) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), 0);
}
TEST(FieldBackedListImplTest, TestLength1) {
TestMessage message;
message.add_int32_list(1);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), 1);
EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1);
}
TEST(FieldBackedListImplTest, TestLength100000) {
TestMessage message;
const int kLen = 100000;
for (int i = 0; i < kLen; i++) {
message.add_int32_list(i);
}
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), kLen);
for (int i = 0; i < kLen; i++) {
EXPECT_EQ((*cel_list)[i].Int64OrDie(), i);
}
}
TEST(FieldBackedListImplTest, Int32DatatypeTest) {
TestMessage message;
message.add_int32_list(1);
message.add_int32_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int32_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Int64OrDie(), 2);
}
TEST(FieldBackedListImplTest, Int64DatatypeTest) {
TestMessage message;
message.add_int64_list(1);
message.add_int64_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "int64_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Int64OrDie(), 2);
}
TEST(FieldBackedListImplTest, Uint32DatatypeTest) {
TestMessage message;
message.add_uint32_list(1);
message.add_uint32_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "uint32_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Uint64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Uint64OrDie(), 2);
}
TEST(FieldBackedListImplTest, Uint64DatatypeTest) {
TestMessage message;
message.add_uint64_list(1);
message.add_uint64_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "uint64_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].Uint64OrDie(), 1);
EXPECT_EQ((*cel_list)[1].Uint64OrDie(), 2);
}
TEST(FieldBackedListImplTest, FloatDatatypeTest) {
TestMessage message;
message.add_float_list(1);
message.add_float_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "float_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT((*cel_list)[0].DoubleOrDie(), DoubleEq(1));
EXPECT_THAT((*cel_list)[1].DoubleOrDie(), DoubleEq(2));
}
TEST(FieldBackedListImplTest, DoubleDatatypeTest) {
TestMessage message;
message.add_double_list(1);
message.add_double_list(2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "double_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT((*cel_list)[0].DoubleOrDie(), DoubleEq(1));
EXPECT_THAT((*cel_list)[1].DoubleOrDie(), DoubleEq(2));
}
TEST(FieldBackedListImplTest, StringDatatypeTest) {
TestMessage message;
message.add_string_list("1");
message.add_string_list("2");
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "string_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].StringOrDie().value(), "1");
EXPECT_EQ((*cel_list)[1].StringOrDie().value(), "2");
}
TEST(FieldBackedListImplTest, BytesDatatypeTest) {
TestMessage message;
message.add_bytes_list("1");
message.add_bytes_list("2");
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "bytes_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_EQ((*cel_list)[0].BytesOrDie().value(), "1");
EXPECT_EQ((*cel_list)[1].BytesOrDie().value(), "2");
}
TEST(FieldBackedListImplTest, MessageDatatypeTest) {
TestMessage message;
TestMessage* msg1 = message.add_message_list();
TestMessage* msg2 = message.add_message_list();
msg1->set_string_value("1");
msg2->set_string_value("2");
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "message_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT(*msg1, EqualsProto(*((*cel_list)[0].MessageOrDie())));
EXPECT_THAT(*msg2, EqualsProto(*((*cel_list)[1].MessageOrDie())));
}
TEST(FieldBackedListImplTest, EnumDatatypeTest) {
TestMessage message;
message.add_enum_list(TestMessage::TEST_ENUM_1);
message.add_enum_list(TestMessage::TEST_ENUM_2);
google::protobuf::Arena arena;
auto cel_list = CreateList(&message, "enum_list", &arena);
ASSERT_EQ(cel_list->size(), 2);
EXPECT_THAT((*cel_list)[0].Int64OrDie(), Eq(TestMessage::TEST_ENUM_1));
EXPECT_THAT((*cel_list)[1].Int64OrDie(), Eq(TestMessage::TEST_ENUM_2));
}
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/field_backed_list_impl.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/field_backed_list_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
458e0be5-a6e4-4cfb-b5e8-68bac274c1b0 | cpp | google/cel-cpp | field_backed_map_impl | eval/public/containers/field_backed_map_impl.h | eval/public/containers/field_backed_map_impl_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_FIELD_BACKED_MAP_IMPL_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_FIELD_BACKED_MAP_IMPL_H_
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "absl/status/statusor.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/internal_field_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
namespace google::api::expr::runtime {
class FieldBackedMapImpl : public internal::FieldBackedMapImpl {
public:
FieldBackedMapImpl(const google::protobuf::Message* message,
const google::protobuf::FieldDescriptor* descriptor,
google::protobuf::Arena* arena)
: internal::FieldBackedMapImpl(
message, descriptor, &CelProtoWrapper::InternalWrapMessage, arena) {
}
};
}
#endif | #include "eval/public/containers/field_backed_map_impl.h"
#include <array>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::absl_testing::StatusIs;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::UnorderedPointwise;
std::unique_ptr<FieldBackedMapImpl> CreateMap(const TestMessage* message,
const std::string& field,
google::protobuf::Arena* arena) {
const google::protobuf::FieldDescriptor* field_desc =
message->GetDescriptor()->FindFieldByName(field);
return std::make_unique<FieldBackedMapImpl>(message, field_desc, arena);
}
TEST(FieldBackedMapImplTest, BadKeyTypeTest) {
TestMessage message;
google::protobuf::Arena arena;
constexpr std::array<absl::string_view, 6> map_types = {
"int64_int32_map", "uint64_int32_map", "string_int32_map",
"bool_int32_map", "int32_int32_map", "uint32_uint32_map",
};
for (auto map_type : map_types) {
auto cel_map = CreateMap(&message, std::string(map_type), &arena);
auto result = cel_map->Has(CelValue::CreateNull());
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kInvalidArgument));
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kInvalidArgument));
auto lookup = (*cel_map)[CelValue::CreateNull()];
EXPECT_TRUE(lookup.has_value());
EXPECT_TRUE(lookup->IsError());
EXPECT_THAT(lookup->ErrorOrDie()->code(),
Eq(absl::StatusCode::kInvalidArgument));
}
}
TEST(FieldBackedMapImplTest, Int32KeyTest) {
TestMessage message;
auto field_map = message.mutable_int32_int32_map();
(*field_map)[0] = 1;
(*field_map)[1] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "int32_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateInt64(1)).value_or(false));
EXPECT_FALSE((*cel_map)[CelValue::CreateInt64(3)].has_value());
EXPECT_FALSE(cel_map->Has(CelValue::CreateInt64(3)).value_or(true));
}
TEST(FieldBackedMapImplTest, Int32KeyOutOfRangeTest) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "int32_int32_map", &arena);
auto result = cel_map->Has(
CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L));
EXPECT_THAT(result.status(),
StatusIs(absl::StatusCode::kOutOfRange, HasSubstr("overflow")));
result = cel_map->Has(
CelValue::CreateInt64(std::numeric_limits<int32_t>::lowest() - 1L));
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kOutOfRange));
}
TEST(FieldBackedMapImplTest, Int64KeyTest) {
TestMessage message;
auto field_map = message.mutable_int64_int32_map();
(*field_map)[0] = 1;
(*field_map)[1] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "int64_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateInt64(1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateInt64(3)].has_value(), false);
}
TEST(FieldBackedMapImplTest, BoolKeyTest) {
TestMessage message;
auto field_map = message.mutable_bool_int32_map();
(*field_map)[false] = 1;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "bool_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateBool(false)]->Int64OrDie(), 1);
EXPECT_TRUE(cel_map->Has(CelValue::CreateBool(false)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateBool(true)].has_value(), false);
(*field_map)[true] = 2;
EXPECT_EQ((*cel_map)[CelValue::CreateBool(true)]->Int64OrDie(), 2);
}
TEST(FieldBackedMapImplTest, Uint32KeyTest) {
TestMessage message;
auto field_map = message.mutable_uint32_uint32_map();
(*field_map)[0] = 1u;
(*field_map)[1] = 2u;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "uint32_uint32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(0)]->Uint64OrDie(), 1UL);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(1)]->Uint64OrDie(), 2UL);
EXPECT_TRUE(cel_map->Has(CelValue::CreateUint64(1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(3)].has_value(), false);
EXPECT_EQ(cel_map->Has(CelValue::CreateUint64(3)).value_or(true), false);
}
TEST(FieldBackedMapImplTest, Uint32KeyOutOfRangeTest) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "uint32_uint32_map", &arena);
auto result = cel_map->Has(
CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1UL));
EXPECT_FALSE(result.ok());
EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kOutOfRange));
}
TEST(FieldBackedMapImplTest, Uint64KeyTest) {
TestMessage message;
auto field_map = message.mutable_uint64_int32_map();
(*field_map)[0] = 1;
(*field_map)[1] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "uint64_int32_map", &arena);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateUint64(1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateUint64(3)].has_value(), false);
}
TEST(FieldBackedMapImplTest, StringKeyTest) {
TestMessage message;
auto field_map = message.mutable_string_int32_map();
(*field_map)["test0"] = 1;
(*field_map)["test1"] = 2;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
std::string test0 = "test0";
std::string test1 = "test1";
std::string test_notfound = "test_notfound";
EXPECT_EQ((*cel_map)[CelValue::CreateString(&test0)]->Int64OrDie(), 1);
EXPECT_EQ((*cel_map)[CelValue::CreateString(&test1)]->Int64OrDie(), 2);
EXPECT_TRUE(cel_map->Has(CelValue::CreateString(&test1)).value_or(false));
EXPECT_EQ((*cel_map)[CelValue::CreateString(&test_notfound)].has_value(),
false);
}
TEST(FieldBackedMapImplTest, EmptySizeTest) {
TestMessage message;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
EXPECT_EQ(cel_map->size(), 0);
}
TEST(FieldBackedMapImplTest, RepeatedAddTest) {
TestMessage message;
auto field_map = message.mutable_string_int32_map();
(*field_map)["test0"] = 1;
(*field_map)["test1"] = 2;
(*field_map)["test0"] = 3;
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
EXPECT_EQ(cel_map->size(), 2);
}
TEST(FieldBackedMapImplTest, KeyListTest) {
TestMessage message;
auto field_map = message.mutable_string_int32_map();
std::vector<std::string> keys;
std::vector<std::string> keys1;
for (int i = 0; i < 100; i++) {
keys.push_back(absl::StrCat("test", i));
(*field_map)[keys.back()] = i;
}
google::protobuf::Arena arena;
auto cel_map = CreateMap(&message, "string_int32_map", &arena);
const CelList* key_list = cel_map->ListKeys().value();
EXPECT_EQ(key_list->size(), 100);
for (int i = 0; i < key_list->size(); i++) {
keys1.push_back(std::string((*key_list)[i].StringOrDie().value()));
}
EXPECT_THAT(keys, UnorderedPointwise(Eq(), keys1));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/field_backed_map_impl.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/containers/field_backed_map_impl_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
75518bb5-a390-42b6-b985-bea3835768f4 | cpp | google/cel-cpp | comprehension_slots | eval/eval/comprehension_slots.h | eval/eval/comprehension_slots_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_COMPREHENSION_SLOTS_H_
#define THIRD_PARTY_CEL_CPP_EVAL_EVAL_COMPREHENSION_SLOTS_H_
#include <cstddef>
#include <utility>
#include <vector>
#include "absl/base/no_destructor.h"
#include "absl/log/absl_check.h"
#include "absl/types/optional.h"
#include "common/value.h"
#include "eval/eval/attribute_trail.h"
namespace google::api::expr::runtime {
class ComprehensionSlots {
public:
struct Slot {
cel::Value value;
AttributeTrail attribute;
};
static ComprehensionSlots& GetEmptyInstance() {
static absl::NoDestructor<ComprehensionSlots> instance(0);
return *instance;
}
explicit ComprehensionSlots(size_t size) : size_(size), slots_(size) {}
ComprehensionSlots(const ComprehensionSlots&) = delete;
ComprehensionSlots& operator=(const ComprehensionSlots&) = delete;
ComprehensionSlots(ComprehensionSlots&&) = default;
ComprehensionSlots& operator=(ComprehensionSlots&&) = default;
Slot* Get(size_t index) {
ABSL_DCHECK_LT(index, slots_.size());
auto& slot = slots_[index];
if (!slot.has_value()) return nullptr;
return &slot.value();
}
void Reset() {
slots_.clear();
slots_.resize(size_);
}
void ClearSlot(size_t index) {
ABSL_DCHECK_LT(index, slots_.size());
slots_[index] = absl::nullopt;
}
void Set(size_t index) {
ABSL_DCHECK_LT(index, slots_.size());
slots_[index].emplace();
}
void Set(size_t index, cel::Value value) {
Set(index, std::move(value), AttributeTrail());
}
void Set(size_t index, cel::Value value, AttributeTrail attribute) {
ABSL_DCHECK_LT(index, slots_.size());
slots_[index] = Slot{std::move(value), std::move(attribute)};
}
size_t size() const { return slots_.size(); }
private:
size_t size_;
std::vector<absl::optional<Slot>> slots_;
};
}
#endif | #include "eval/eval/comprehension_slots.h"
#include "base/attribute.h"
#include "base/type_provider.h"
#include "common/memory.h"
#include "common/type.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/eval/attribute_trail.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
using ::cel::Attribute;
using ::absl_testing::IsOkAndHolds;
using ::cel::MemoryManagerRef;
using ::cel::StringValue;
using ::cel::TypeFactory;
using ::cel::TypeManager;
using ::cel::TypeProvider;
using ::cel::Value;
using ::cel::ValueManager;
using ::testing::Truly;
TEST(ComprehensionSlots, Basic) {
cel::common_internal::LegacyValueManager factory(
MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin());
ComprehensionSlots slots(4);
ComprehensionSlots::Slot* unset = slots.Get(0);
EXPECT_EQ(unset, nullptr);
slots.Set(0, factory.CreateUncheckedStringValue("abcd"),
AttributeTrail(Attribute("fake_attr")));
auto* slot0 = slots.Get(0);
ASSERT_TRUE(slot0 != nullptr);
EXPECT_THAT(slot0->value, Truly([](const Value& v) {
return v.Is<StringValue>() &&
v.GetString().ToString() == "abcd";
}))
<< "value is 'abcd'";
EXPECT_THAT(slot0->attribute.attribute().AsString(),
IsOkAndHolds("fake_attr"));
slots.ClearSlot(0);
EXPECT_EQ(slots.Get(0), nullptr);
slots.Set(3, factory.CreateUncheckedStringValue("abcd"),
AttributeTrail(Attribute("fake_attr")));
auto* slot3 = slots.Get(3);
ASSERT_TRUE(slot3 != nullptr);
EXPECT_THAT(slot3->value, Truly([](const Value& v) {
return v.Is<StringValue>() &&
v.GetString().ToString() == "abcd";
}))
<< "value is 'abcd'";
slots.Reset();
slot0 = slots.Get(0);
EXPECT_TRUE(slot0 == nullptr);
slot3 = slots.Get(3);
EXPECT_TRUE(slot3 == nullptr);
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/comprehension_slots.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/eval/comprehension_slots_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |