ID
int64
0
2.65k
Language
stringclasses
1 value
Repository Name
stringclasses
14 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
16
116
Code
stringlengths
411
31.4k
Unit Test - (Ground Truth)
stringlengths
40
32.1k
0
cpp
google/cel-cpp
kind
common/kind.cc
common/kind_test.cc
#ifndef THIRD_PARTY_CEL_CPP_BASE_KIND_H_ #define THIRD_PARTY_CEL_CPP_BASE_KIND_H_ #include "common/kind.h" #include "common/type_kind.h" #include "common/value_kind.h" #endif #include "common/kind.h" #include "absl/strings/string_view.h" namespace cel { absl::string_view KindToString(Kind kind) { switch (kind) { case Kind::kNullType: return "null_type"; case Kind::kDyn: return "dyn"; case Kind::kAny: return "any"; case Kind::kType: return "type"; case Kind::kTypeParam: return "type_param"; case Kind::kFunction: return "function"; case Kind::kBool: return "bool"; case Kind::kInt: return "int"; case Kind::kUint: return "uint"; case Kind::kDouble: return "double"; case Kind::kString: return "string"; case Kind::kBytes: return "bytes"; case Kind::kDuration: return "duration"; case Kind::kTimestamp: return "timestamp"; case Kind::kList: return "list"; case Kind::kMap: return "map"; case Kind::kStruct: return "struct"; case Kind::kUnknown: return "*unknown*"; case Kind::kOpaque: return "*opaque*"; case Kind::kBoolWrapper: return "google.protobuf.BoolValue"; case Kind::kIntWrapper: return "google.protobuf.Int64Value"; case Kind::kUintWrapper: return "google.protobuf.UInt64Value"; case Kind::kDoubleWrapper: return "google.protobuf.DoubleValue"; case Kind::kStringWrapper: return "google.protobuf.StringValue"; case Kind::kBytesWrapper: return "google.protobuf.BytesValue"; default: return "*error*"; } } }
#include "common/kind.h" #include <limits> #include <type_traits> #include "common/type_kind.h" #include "common/value_kind.h" #include "internal/testing.h" namespace cel { namespace { static_assert(std::is_same_v<std::underlying_type_t<TypeKind>, std::underlying_type_t<ValueKind>>, "TypeKind and ValueKind must have the same underlying type"); TEST(Kind, ToString) { EXPECT_EQ(KindToString(Kind::kError), "*error*"); EXPECT_EQ(KindToString(Kind::kNullType), "null_type"); EXPECT_EQ(KindToString(Kind::kDyn), "dyn"); EXPECT_EQ(KindToString(Kind::kAny), "any"); EXPECT_EQ(KindToString(Kind::kType), "type"); EXPECT_EQ(KindToString(Kind::kBool), "bool"); EXPECT_EQ(KindToString(Kind::kInt), "int"); EXPECT_EQ(KindToString(Kind::kUint), "uint"); EXPECT_EQ(KindToString(Kind::kDouble), "double"); EXPECT_EQ(KindToString(Kind::kString), "string"); EXPECT_EQ(KindToString(Kind::kBytes), "bytes"); EXPECT_EQ(KindToString(Kind::kDuration), "duration"); EXPECT_EQ(KindToString(Kind::kTimestamp), "timestamp"); EXPECT_EQ(KindToString(Kind::kList), "list"); EXPECT_EQ(KindToString(Kind::kMap), "map"); EXPECT_EQ(KindToString(Kind::kStruct), "struct"); EXPECT_EQ(KindToString(Kind::kUnknown), "*unknown*"); EXPECT_EQ(KindToString(Kind::kOpaque), "*opaque*"); EXPECT_EQ(KindToString(Kind::kBoolWrapper), "google.protobuf.BoolValue"); EXPECT_EQ(KindToString(Kind::kIntWrapper), "google.protobuf.Int64Value"); EXPECT_EQ(KindToString(Kind::kUintWrapper), "google.protobuf.UInt64Value"); EXPECT_EQ(KindToString(Kind::kDoubleWrapper), "google.protobuf.DoubleValue"); EXPECT_EQ(KindToString(Kind::kStringWrapper), "google.protobuf.StringValue"); EXPECT_EQ(KindToString(Kind::kBytesWrapper), "google.protobuf.BytesValue"); EXPECT_EQ(KindToString(static_cast<Kind>(std::numeric_limits<int>::max())), "*error*"); } TEST(Kind, TypeKindRoundtrip) { EXPECT_EQ(TypeKindToKind(KindToTypeKind(Kind::kBool)), Kind::kBool); } TEST(Kind, ValueKindRoundtrip) { EXPECT_EQ(ValueKindToKind(KindToValueKind(Kind::kBool)), Kind::kBool); } TEST(Kind, IsTypeKind) { EXPECT_TRUE(KindIsTypeKind(Kind::kBool)); EXPECT_TRUE(KindIsTypeKind(Kind::kAny)); EXPECT_TRUE(KindIsTypeKind(Kind::kDyn)); } TEST(Kind, IsValueKind) { EXPECT_TRUE(KindIsValueKind(Kind::kBool)); EXPECT_FALSE(KindIsValueKind(Kind::kAny)); EXPECT_FALSE(KindIsValueKind(Kind::kDyn)); } TEST(Kind, Equality) { EXPECT_EQ(Kind::kBool, TypeKind::kBool); EXPECT_EQ(TypeKind::kBool, Kind::kBool); EXPECT_EQ(Kind::kBool, ValueKind::kBool); EXPECT_EQ(ValueKind::kBool, Kind::kBool); EXPECT_NE(Kind::kBool, TypeKind::kInt); EXPECT_NE(TypeKind::kInt, Kind::kBool); EXPECT_NE(Kind::kBool, ValueKind::kInt); EXPECT_NE(ValueKind::kInt, Kind::kBool); } TEST(TypeKind, ToString) { EXPECT_EQ(TypeKindToString(TypeKind::kBool), KindToString(Kind::kBool)); } TEST(ValueKind, ToString) { EXPECT_EQ(ValueKindToString(ValueKind::kBool), KindToString(Kind::kBool)); } } }
1
cpp
google/cel-cpp
value_factory
common/value_factory.cc
common/value_factory_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUE_FACTORY_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUE_FACTORY_H_ #include <cstdint> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "common/json.h" #include "common/type.h" #include "common/type_factory.h" #include "common/unknown.h" #include "common/value.h" namespace cel { namespace common_internal { class PiecewiseValueManager; } class ValueFactory : public virtual TypeFactory { public: Value CreateValueFromJson(Json json); ListValue CreateListValueFromJsonArray(JsonArray json); MapValue CreateMapValueFromJsonObject(JsonObject json); ListValue CreateZeroListValue(ListTypeView type); MapValue CreateZeroMapValue(MapTypeView type); OptionalValue CreateZeroOptionalValue(OptionalTypeView type); ListValueView GetZeroDynListValue(); MapValueView GetZeroDynDynMapValue(); MapValueView GetZeroStringDynMapValue(); OptionalValueView GetZeroDynOptionalValue(); NullValue GetNullValue() { return NullValue{}; } ErrorValue CreateErrorValue(absl::Status status) { return ErrorValue{std::move(status)}; } BoolValue CreateBoolValue(bool value) { return BoolValue{value}; } IntValue CreateIntValue(int64_t value) { return IntValue{value}; } UintValue CreateUintValue(uint64_t value) { return UintValue{value}; } DoubleValue CreateDoubleValue(double value) { return DoubleValue{value}; } BytesValue GetBytesValue() { return BytesValue(); } absl::StatusOr<BytesValue> CreateBytesValue(const char* value) { return CreateBytesValue(absl::string_view(value)); } absl::StatusOr<BytesValue> CreateBytesValue(absl::string_view value) { return CreateBytesValue(std::string(value)); } absl::StatusOr<BytesValue> CreateBytesValue(std::string value); absl::StatusOr<BytesValue> CreateBytesValue(absl::Cord value) { return BytesValue(std::move(value)); } template <typename Releaser> absl::StatusOr<BytesValue> CreateBytesValue(absl::string_view value, Releaser&& releaser) { return BytesValue( absl::MakeCordFromExternal(value, std::forward<Releaser>(releaser))); } StringValue GetStringValue() { return StringValue(); } absl::StatusOr<StringValue> CreateStringValue(const char* value) { return CreateStringValue(absl::string_view(value)); } absl::StatusOr<StringValue> CreateStringValue(absl::string_view value) { return CreateStringValue(std::string(value)); } absl::StatusOr<StringValue> CreateStringValue(std::string value); absl::StatusOr<StringValue> CreateStringValue(absl::Cord value); template <typename Releaser> absl::StatusOr<StringValue> CreateStringValue(absl::string_view value, Releaser&& releaser) { return StringValue( absl::MakeCordFromExternal(value, std::forward<Releaser>(releaser))); } StringValue CreateUncheckedStringValue(const char* value) { return CreateUncheckedStringValue(absl::string_view(value)); } StringValue CreateUncheckedStringValue(absl::string_view value) { return CreateUncheckedStringValue(std::string(value)); } StringValue CreateUncheckedStringValue(std::string value); StringValue CreateUncheckedStringValue(absl::Cord value) { return StringValue(std::move(value)); } template <typename Releaser> StringValue CreateUncheckedStringValue(absl::string_view value, Releaser&& releaser) { return StringValue( absl::MakeCordFromExternal(value, std::forward<Releaser>(releaser))); } absl::StatusOr<DurationValue> CreateDurationValue(absl::Duration value); DurationValue CreateUncheckedDurationValue(absl::Duration value) { return DurationValue{value}; } absl::StatusOr<TimestampValue> CreateTimestampValue(absl::Time value); TimestampValue CreateUncheckedTimestampValue(absl::Time value) { return TimestampValue{value}; } TypeValue CreateTypeValue(TypeView type) { return TypeValue{Type(type)}; } UnknownValue CreateUnknownValue() { return CreateUnknownValue(AttributeSet(), FunctionResultSet()); } UnknownValue CreateUnknownValue(AttributeSet attribute_set) { return CreateUnknownValue(std::move(attribute_set), FunctionResultSet()); } UnknownValue CreateUnknownValue(FunctionResultSet function_result_set) { return CreateUnknownValue(AttributeSet(), std::move(function_result_set)); } UnknownValue CreateUnknownValue(AttributeSet attribute_set, FunctionResultSet function_result_set) { return UnknownValue{ Unknown{std::move(attribute_set), std::move(function_result_set)}}; } protected: friend class common_internal::PiecewiseValueManager; virtual ListValue CreateZeroListValueImpl(ListTypeView type) = 0; virtual MapValue CreateZeroMapValueImpl(MapTypeView type) = 0; virtual OptionalValue CreateZeroOptionalValueImpl(OptionalTypeView type) = 0; }; } #endif #include "common/value_factory.h" #include <algorithm> #include <cstddef> #include <memory> #include <new> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "common/casting.h" #include "common/internal/arena_string.h" #include "common/internal/reference_count.h" #include "common/json.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/value_cache.h" #include "internal/status_macros.h" #include "internal/time.h" #include "internal/utf8.h" namespace cel { namespace { using common_internal::ProcessLocalValueCache; void JsonToValue(const Json& json, ValueFactory& value_factory, Value& result) { absl::visit( absl::Overload( [&result](JsonNull) { result = NullValue(); }, [&result](JsonBool value) { result = BoolValue(value); }, [&result](JsonNumber value) { result = DoubleValue(value); }, [&result](const JsonString& value) { result = StringValue(value); }, [&value_factory, &result](const JsonArray& value) { result = value_factory.CreateListValueFromJsonArray(value); }, [&value_factory, &result](const JsonObject& value) { result = value_factory.CreateMapValueFromJsonObject(value); }), json); } void JsonDebugString(const Json& json, std::string& out); void JsonArrayDebugString(const JsonArray& json, std::string& out) { out.push_back('['); auto element = json.begin(); if (element != json.end()) { JsonDebugString(*element, out); ++element; for (; element != json.end(); ++element) { out.append(", "); JsonDebugString(*element, out); } } out.push_back(']'); } void JsonObjectEntryDebugString(const JsonString& key, const Json& value, std::string& out) { out.append(StringValueView(key).DebugString()); out.append(": "); JsonDebugString(value, out); } void JsonObjectDebugString(const JsonObject& json, std::string& out) { std::vector<JsonString> keys; keys.reserve(json.size()); for (const auto& entry : json) { keys.push_back(entry.first); } std::stable_sort(keys.begin(), keys.end()); out.push_back('{'); auto key = keys.begin(); if (key != keys.end()) { JsonObjectEntryDebugString(*key, json.find(*key)->second, out); ++key; for (; key != keys.end(); ++key) { out.append(", "); JsonObjectEntryDebugString(*key, json.find(*key)->second, out); } } out.push_back('}'); } void JsonDebugString(const Json& json, std::string& out) { absl::visit(absl::Overload( [&out](JsonNull) -> void { out.append(NullValueView().DebugString()); }, [&out](JsonBool value) -> void { out.append(BoolValueView(value).DebugString()); }, [&out](JsonNumber value) -> void { out.append(DoubleValueView(value).DebugString()); }, [&out](const JsonString& value) -> void { out.append(StringValueView(value).DebugString()); }, [&out](const JsonArray& value) -> void { JsonArrayDebugString(value, out); }, [&out](const JsonObject& value) -> void { JsonObjectDebugString(value, out); }), json); } class JsonListValue final : public ParsedListValueInterface { public: explicit JsonListValue(JsonArray array) : array_(std::move(array)) {} std::string DebugString() const override { std::string out; JsonArrayDebugString(array_, out); return out; } bool IsEmpty() const override { return array_.empty(); } size_t Size() const override { return array_.size(); } absl::StatusOr<JsonArray> ConvertToJsonArray( AnyToJsonConverter&) const override { return array_; } private: Type GetTypeImpl(TypeManager& type_manager) const override { return ListType(type_manager.GetDynListType()); } absl::Status GetImpl(ValueManager& value_manager, size_t index, Value& result) const override { JsonToValue(array_[index], value_manager, result); return absl::OkStatus(); } NativeTypeId GetNativeTypeId() const noexcept override { return NativeTypeId::For<JsonListValue>(); } const JsonArray array_; }; class JsonMapValueKeyIterator final : public ValueIterator { public: explicit JsonMapValueKeyIterator( const JsonObject& object ABSL_ATTRIBUTE_LIFETIME_BOUND) : begin_(object.begin()), end_(object.end()) {} bool HasNext() override { return begin_ != end_; } absl::Status Next(ValueManager&, Value& result) override { if (ABSL_PREDICT_FALSE(begin_ == end_)) { return absl::FailedPreconditionError( "ValueIterator::Next() called when " "ValueIterator::HasNext() returns false"); } const auto& key = begin_->first; ++begin_; result = StringValue(key); return absl::OkStatus(); } private: typename JsonObject::const_iterator begin_; typename JsonObject::const_iterator end_; }; class JsonMapValue final : public ParsedMapValueInterface { public: explicit JsonMapValue(JsonObject object) : object_(std::move(object)) {} std::string DebugString() const override { std::string out; JsonObjectDebugString(object_, out); return out; } bool IsEmpty() const override { return object_.empty(); } size_t Size() const override { return object_.size(); } absl::Status ListKeys(ValueManager& value_manager, ListValue& result) const override { JsonArrayBuilder keys; keys.reserve(object_.size()); for (const auto& entry : object_) { keys.push_back(entry.first); } result = ParsedListValue( value_manager.GetMemoryManager().MakeShared<JsonListValue>( std::move(keys).Build())); return absl::OkStatus(); } absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager&) const override { return std::make_unique<JsonMapValueKeyIterator>(object_); } absl::StatusOr<JsonObject> ConvertToJsonObject( AnyToJsonConverter&) const override { return object_; } private: absl::StatusOr<bool> FindImpl(ValueManager& value_manager, ValueView key, Value& result) const override { return Cast<StringValueView>(key).NativeValue(absl::Overload( [this, &value_manager, &result](absl::string_view value) -> bool { if (auto entry = object_.find(value); entry != object_.end()) { JsonToValue(entry->second, value_manager, result); return true; } return false; }, [this, &value_manager, &result](const absl::Cord& value) -> bool { if (auto entry = object_.find(value); entry != object_.end()) { JsonToValue(entry->second, value_manager, result); return true; } return false; })); } absl::StatusOr<bool> HasImpl(ValueManager&, ValueView key) const override { return Cast<StringValueView>(key).NativeValue(absl::Overload( [this](absl::string_view value) -> bool { return object_.contains(value); }, [this](const absl::Cord& value) -> bool { return object_.contains(value); })); } Type GetTypeImpl(TypeManager& type_manager) const override { return MapType(type_manager.GetStringDynMapType()); } NativeTypeId GetNativeTypeId() const noexcept override { return NativeTypeId::For<JsonMapValue>(); } const JsonObject object_; }; } Value ValueFactory::CreateValueFromJson(Json json) { return absl::visit( absl::Overload( [](JsonNull) -> Value { return NullValue(); }, [](JsonBool value) -> Value { return BoolValue(value); }, [](JsonNumber value) -> Value { return DoubleValue(value); }, [](const JsonString& value) -> Value { return StringValue(value); }, [this](JsonArray value) -> Value { return CreateListValueFromJsonArray(std::move(value)); }, [this](JsonObject value) -> Value { return CreateMapValueFromJsonObject(std::move(value)); }), std::move(json)); } ListValue ValueFactory::CreateListValueFromJsonArray(JsonArray json) { if (json.empty()) { return ListValue(GetZeroDynListValue()); } return ParsedListValue( GetMemoryManager().MakeShared<JsonListValue>(std::move(json))); } MapValue ValueFactory::CreateMapValueFromJsonObject(JsonObject json) { if (json.empty()) { return MapValue(GetZeroStringDynMapValue()); } return ParsedMapValue( GetMemoryManager().MakeShared<JsonMapValue>(std::move(json))); } ListValue ValueFactory::CreateZeroListValue(ListTypeView type) { if (auto list_value = ProcessLocalValueCache::Get()->GetEmptyListValue(type); list_value.has_value()) { return ListValue(*list_value); } return CreateZeroListValueImpl(type); } MapValue ValueFactory::CreateZeroMapValue(MapTypeView type) { if (auto map_value = ProcessLocalValueCache::Get()->GetEmptyMapValue(type); map_value.has_value()) { return MapValue(*map_value); } return CreateZeroMapValueImpl(type); } OptionalValue ValueFactory::CreateZeroOptionalValue(OptionalTypeView type) { if (auto optional_value = ProcessLocalValueCache::Get()->GetEmptyOptionalValue(type); optional_value.has_value()) { return OptionalValue(*optional_value); } return CreateZeroOptionalValueImpl(type); } ListValueView ValueFactory::GetZeroDynListValue() { return ProcessLocalValueCache::Get()->GetEmptyDynListValue(); } MapValueView ValueFactory::GetZeroDynDynMapValue() { return ProcessLocalValueCache::Get()->GetEmptyDynDynMapValue(); } MapValueView ValueFactory::GetZeroStringDynMapValue() { return ProcessLocalValueCache::Get()->GetEmptyStringDynMapValue(); } OptionalValueView ValueFactory::GetZeroDynOptionalValue() { return ProcessLocalValueCache::Get()->GetEmptyDynOptionalValue(); } namespace { class ReferenceCountedString final : public common_internal::ReferenceCounted { public: static const ReferenceCountedString* New(std::string&& string) { return new ReferenceCountedString(std::move(string)); } const char* data() const { return std::launder(reinterpret_cast<const std::string*>(&string_[0])) ->data(); } size_t size() const { return std::launder(reinterpret_cast<const std::string*>(&string_[0])) ->size(); } private: explicit ReferenceCountedString(std::string&& robbed) : ReferenceCounted() { ::new (static_cast<void*>(&string_[0])) std::string(std::move(robbed)); } void Finalize() noexcept override { std::launder(reinterpret_cast<const std::string*>(&string_[0])) ->~basic_string(); } alignas(std::string) char string_[sizeof(std::string)]; }; } static void StringDestructor(void* string) { static_cast<std::string*>(string)->~basic_string(); } absl::StatusOr<BytesValue> ValueFactory::CreateBytesValue(std::string value) { auto memory_manager = GetMemoryManager(); switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: { auto* string = ::new ( memory_manager.Allocate(sizeof(std::string), alignof(std::string))) std::string(std::move(value)); memory_manager.OwnCustomDestructor(string, &StringDestructor); return BytesValue{common_internal::ArenaString(*string)}; } case MemoryManagement::kReferenceCounting: { auto* refcount = ReferenceCountedString::New(std::move(value)); auto bytes_value = BytesValue{common_internal::SharedByteString( refcount, absl::string_view(refcount->data(), refcount->size()))}; common_internal::StrongUnref(*refcount); return bytes_value; } } } StringValue ValueFactory::CreateUncheckedStringValue(std::string value) { auto memory_manager = GetMemoryManager(); switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: { auto* string = ::new ( memory_manager.Allocate(sizeof(std::string), alignof(std::string))) std::string(std::move(value)); memory_manager.OwnCustomDestructor(string, &StringDestructor); return StringValue{common_internal::ArenaString(*string)}; } case MemoryManagement::kReferenceCounting: { auto* refcount = ReferenceCountedString::New(std::move(value)); auto string_value = StringValue{common_internal::SharedByteString( refcount, absl::string_view(refcount->data(), refcount->size()))}; common_internal::StrongUnref(*refcount); return string_value; } } } absl::StatusOr<StringValue> ValueFactory::CreateStringValue(std::string value) { auto [count, ok] = internal::Utf8Validate(value); if (ABSL_PREDICT_FALSE(!ok)) { return absl::InvalidArgumentError( "Illegal byte sequence in UTF-8 encoded string"); } return CreateUncheckedStringValue(std::move(value)); } absl::StatusOr<StringValue> ValueFactory::CreateStringValue(absl::Cord value) { auto [count, ok] = internal::Utf8Validate(value); if (ABSL_PREDICT_FALSE(!ok)) { return absl::InvalidArgumentError( "Illegal byte sequence in UTF-8 encoded string"); } return StringValue(std::move(value)); } absl::StatusOr<DurationValue> ValueFactory::CreateDurationValue( absl::Duration value) { CEL_RETURN_IF_ERROR(internal::ValidateDuration(value)); return DurationValue{value}; } absl::StatusOr<TimestampValue> ValueFactory::CreateTimestampValue( absl::Time value) { CEL_RETURN_IF_ERROR(internal::ValidateTimestamp(value)); return TimestampValue{value}; } }
#include "common/value_factory.h" #include <ostream> #include <sstream> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/json.h" #include "common/memory.h" #include "common/memory_testing.h" #include "common/type.h" #include "common/type_factory.h" #include "common/type_reflector.h" #include "common/types/type_cache.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/testing.h" namespace cel { namespace { using common_internal::ProcessLocalTypeCache; using testing::TestParamInfo; using testing::TestWithParam; using testing::UnorderedElementsAreArray; using cel::internal::IsOkAndHolds; enum class ThreadSafety { kCompatible, kSafe, }; std::ostream& operator<<(std::ostream& out, ThreadSafety thread_safety) { switch (thread_safety) { case ThreadSafety::kCompatible: return out << "THREAD_SAFE"; case ThreadSafety::kSafe: return out << "THREAD_COMPATIBLE"; } } class ValueFactoryTest : public common_internal::ThreadCompatibleMemoryTest<ThreadSafety> { public: void SetUp() override { switch (thread_safety()) { case ThreadSafety::kCompatible: value_manager_ = NewThreadCompatibleValueManager( memory_manager(), NewThreadCompatibleTypeReflector(memory_manager())); break; case ThreadSafety::kSafe: value_manager_ = NewThreadSafeValueManager( memory_manager(), NewThreadSafeTypeReflector(memory_manager())); break; } } void TearDown() override { Finish(); } void Finish() { value_manager_.reset(); ThreadCompatibleMemoryTest::Finish(); } TypeFactory& type_factory() const { return value_manager(); } TypeManager& type_manager() const { return value_manager(); } ValueFactory& value_factory() const { return value_manager(); } ValueManager& value_manager() const { return **value_manager_; } ThreadSafety thread_safety() const { return std::get<1>(GetParam()); } static std::string ToString( TestParamInfo<std::tuple<MemoryManagement, ThreadSafety>> param) { std::ostringstream out; out << std::get<0>(param.param) << "_" << std::get<1>(param.param); return out.str(); } private: absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ValueFactoryTest, JsonValueNull) { auto value = value_factory().CreateValueFromJson(kJsonNull); EXPECT_TRUE(InstanceOf<NullValue>(value)); } TEST_P(ValueFactoryTest, JsonValueBool) { auto value = value_factory().CreateValueFromJson(true); ASSERT_TRUE(InstanceOf<BoolValue>(value)); EXPECT_TRUE(Cast<BoolValue>(value).NativeValue()); } TEST_P(ValueFactoryTest, JsonValueNumber) { auto value = value_factory().CreateValueFromJson(1.0); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); EXPECT_EQ(Cast<DoubleValue>(value).NativeValue(), 1.0); } TEST_P(ValueFactoryTest, JsonValueString) { auto value = value_factory().CreateValueFromJson(absl::Cord("foo")); ASSERT_TRUE(InstanceOf<StringValue>(value)); EXPECT_EQ(Cast<StringValue>(value).NativeString(), "foo"); } JsonObject NewJsonObjectForTesting(bool with_array = true, bool with_nested_object = true); JsonArray NewJsonArrayForTesting(bool with_nested_array = true, bool with_object = true) { JsonArrayBuilder builder; builder.push_back(kJsonNull); builder.push_back(true); builder.push_back(1.0); builder.push_back(absl::Cord("foo")); if (with_nested_array) { builder.push_back(NewJsonArrayForTesting(false, false)); } if (with_object) { builder.push_back(NewJsonObjectForTesting(false, false)); } return std::move(builder).Build(); } JsonObject NewJsonObjectForTesting(bool with_array, bool with_nested_object) { JsonObjectBuilder builder; builder.insert_or_assign(absl::Cord("a"), kJsonNull); builder.insert_or_assign(absl::Cord("b"), true); builder.insert_or_assign(absl::Cord("c"), 1.0); builder.insert_or_assign(absl::Cord("d"), absl::Cord("foo")); if (with_array) { builder.insert_or_assign(absl::Cord("e"), NewJsonArrayForTesting(false, false)); } if (with_nested_object) { builder.insert_or_assign(absl::Cord("f"), NewJsonObjectForTesting(false, false)); } return std::move(builder).Build(); } TEST_P(ValueFactoryTest, JsonValueArray) { auto value = value_factory().CreateValueFromJson(NewJsonArrayForTesting()); ASSERT_TRUE(InstanceOf<ListValue>(value)); EXPECT_EQ(TypeView(value.GetType(type_manager())), type_factory().GetDynListType()); auto list_value = Cast<ListValue>(value); EXPECT_THAT(list_value.IsEmpty(), IsOkAndHolds(false)); EXPECT_THAT(list_value.Size(), IsOkAndHolds(6)); EXPECT_EQ(list_value.DebugString(), "[null, true, 1.0, \"foo\", [null, true, 1.0, \"foo\"], {\"a\": " "null, \"b\": true, \"c\": 1.0, \"d\": \"foo\"}]"); ASSERT_OK_AND_ASSIGN(auto element, list_value.Get(value_manager(), 0)); EXPECT_TRUE(InstanceOf<NullValue>(element)); } TEST_P(ValueFactoryTest, JsonValueObject) { auto value = value_factory().CreateValueFromJson(NewJsonObjectForTesting()); ASSERT_TRUE(InstanceOf<MapValue>(value)); EXPECT_EQ(TypeView(value.GetType(type_manager())), type_factory().GetStringDynMapType()); auto map_value = Cast<MapValue>(value); EXPECT_THAT(map_value.IsEmpty(), IsOkAndHolds(false)); EXPECT_THAT(map_value.Size(), IsOkAndHolds(6)); EXPECT_EQ(map_value.DebugString(), "{\"a\": null, \"b\": true, \"c\": 1.0, \"d\": \"foo\", \"e\": " "[null, true, 1.0, \"foo\"], \"f\": {\"a\": null, \"b\": true, " "\"c\": 1.0, \"d\": \"foo\"}}"); ASSERT_OK_AND_ASSIGN(auto keys, map_value.ListKeys(value_manager())); EXPECT_THAT(keys.Size(), IsOkAndHolds(6)); ASSERT_OK_AND_ASSIGN(auto keys_iterator, map_value.NewIterator(value_manager())); std::vector<StringValue> string_keys; while (keys_iterator->HasNext()) { ASSERT_OK_AND_ASSIGN(auto key, keys_iterator->Next(value_manager())); string_keys.push_back(StringValue(Cast<StringValue>(key))); } EXPECT_THAT(string_keys, UnorderedElementsAreArray( {StringValueView("a"), StringValueView("b"), StringValueView("c"), StringValueView("d"), StringValueView("e"), StringValueView("f")})); ASSERT_OK_AND_ASSIGN(auto has, map_value.Has(value_manager(), StringValueView("a"))); ASSERT_TRUE(InstanceOf<BoolValue>(has)); EXPECT_TRUE(Cast<BoolValue>(has).NativeValue()); ASSERT_OK_AND_ASSIGN( has, map_value.Has(value_manager(), StringValueView(absl::Cord("a")))); ASSERT_TRUE(InstanceOf<BoolValue>(has)); EXPECT_TRUE(Cast<BoolValue>(has).NativeValue()); ASSERT_OK_AND_ASSIGN(auto get, map_value.Get(value_manager(), StringValueView("a"))); ASSERT_TRUE(InstanceOf<NullValue>(get)); ASSERT_OK_AND_ASSIGN( get, map_value.Get(value_manager(), StringValueView(absl::Cord("a")))); ASSERT_TRUE(InstanceOf<NullValue>(get)); } TEST_P(ValueFactoryTest, ListValue) { auto list_value1 = value_factory().CreateZeroListValue( type_factory().CreateListType(StringTypeView())); EXPECT_TRUE( Is(list_value1, value_factory().CreateZeroListValue( type_factory().CreateListType(StringTypeView())))); EXPECT_FALSE( Is(list_value1, value_factory().CreateZeroListValue( type_factory().CreateListType(BoolTypeView())))); auto struct_type1 = type_factory().CreateStructType("test.Struct1"); auto struct_type2 = type_factory().CreateStructType("test.Struct2"); auto list_value2 = value_factory().CreateZeroListValue( type_factory().CreateListType(struct_type1)); EXPECT_TRUE( Is(list_value2, value_factory().CreateZeroListValue( type_factory().CreateListType(struct_type1)))); EXPECT_FALSE( Is(list_value2, value_factory().CreateZeroListValue( type_factory().CreateListType(struct_type2)))); auto zero_list_value = value_factory().GetZeroDynListValue(); EXPECT_THAT(zero_list_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(zero_list_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(zero_list_value.GetType(type_manager()), ProcessLocalTypeCache::Get()->GetDynListType()); } TEST_P(ValueFactoryTest, MapValue) { auto map_value1 = value_factory().CreateZeroMapValue( type_factory().CreateMapType(StringTypeView(), IntTypeView())); EXPECT_TRUE(Is(map_value1, value_factory().CreateZeroMapValue( type_factory().CreateMapType(StringTypeView(), IntTypeView())))); EXPECT_FALSE(Is(map_value1, value_factory().CreateZeroMapValue( type_factory().CreateMapType( StringTypeView(), BoolTypeView())))); auto struct_type1 = type_factory().CreateStructType("test.Struct1"); auto struct_type2 = type_factory().CreateStructType("test.Struct2"); auto map_value2 = value_factory().CreateZeroMapValue( type_factory().CreateMapType(StringTypeView(), struct_type1)); EXPECT_TRUE(Is(map_value2, value_factory().CreateZeroMapValue( type_factory().CreateMapType(StringTypeView(), struct_type1)))); EXPECT_FALSE(Is(map_value2, value_factory().CreateZeroMapValue( type_factory().CreateMapType(StringTypeView(), struct_type2)))); auto zero_map_value = value_factory().GetZeroDynDynMapValue(); EXPECT_THAT(zero_map_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(zero_map_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(zero_map_value.GetType(type_manager()), ProcessLocalTypeCache::Get()->GetDynDynMapType()); zero_map_value = value_factory().GetZeroStringDynMapValue(); EXPECT_THAT(zero_map_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(zero_map_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(zero_map_value.GetType(type_manager()), ProcessLocalTypeCache::Get()->GetStringDynMapType()); } TEST_P(ValueFactoryTest, OptionalType) { auto optional_value1 = value_factory().CreateZeroOptionalValue( type_factory().CreateOptionalType(StringTypeView())); EXPECT_TRUE(Is(optional_value1, value_factory().CreateZeroOptionalValue( type_factory().CreateOptionalType(StringTypeView())))); EXPECT_FALSE(Is(optional_value1, value_factory().CreateZeroOptionalValue( type_factory().CreateOptionalType(BoolTypeView())))); auto struct_type1 = type_factory().CreateStructType("test.Struct1"); auto struct_type2 = type_factory().CreateStructType("test.Struct2"); auto optional_value2 = value_factory().CreateZeroOptionalValue( type_factory().CreateOptionalType(struct_type1)); EXPECT_TRUE(Is(optional_value2, value_factory().CreateZeroOptionalValue( type_factory().CreateOptionalType(struct_type1)))); EXPECT_FALSE(Is(optional_value2, value_factory().CreateZeroOptionalValue( type_factory().CreateOptionalType(struct_type2)))); auto zero_optional_value = value_factory().GetZeroDynOptionalValue(); EXPECT_FALSE(zero_optional_value.HasValue()); EXPECT_EQ(zero_optional_value.GetType(type_manager()), ProcessLocalTypeCache::Get()->GetDynOptionalType()); } INSTANTIATE_TEST_SUITE_P( ValueFactoryTest, ValueFactoryTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ::testing::Values(ThreadSafety::kCompatible, ThreadSafety::kSafe)), ValueFactoryTest::ToString); } }
2
cpp
google/cel-cpp
value_testing
common/value_testing.cc
extensions/protobuf/value_testing_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_VALUE_TESTING_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_VALUE_TESTING_H_ #include <ostream> #include "absl/status/status.h" #include "common/value.h" #include "extensions/protobuf/internal/message.h" #include "extensions/protobuf/value.h" #include "internal/testing.h" namespace cel::extensions::test { template <typename MessageType> class StructValueAsProtoMatcher { public: using is_gtest_matcher = void; explicit StructValueAsProtoMatcher(testing::Matcher<MessageType>&& m) : m_(std::move(m)) {} bool MatchAndExplain(cel::Value v, testing::MatchResultListener* result_listener) const { MessageType msg; absl::Status s = ProtoMessageFromValue(v, msg); if (!s.ok()) { *result_listener << "cannot convert to " << MessageType::descriptor()->full_name() << ": " << s; return false; } return m_.MatchAndExplain(msg, result_listener); } void DescribeTo(std::ostream* os) const { *os << "matches proto message " << m_; } void DescribeNegationTo(std::ostream* os) const { *os << "does not match proto message " << m_; } private: testing::Matcher<MessageType> m_; }; template <typename MessageType> inline StructValueAsProtoMatcher<MessageType> StructValueAsProto( testing::Matcher<MessageType>&& m) { static_assert( cel::extensions::protobuf_internal::IsProtoMessage<MessageType>); return StructValueAsProtoMatcher<MessageType>(std::move(m)); } } #endif #include "common/value_testing.h" #include <cstdint> #include <ostream> #include <string> #include <utility> #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/time/time.h" #include "common/casting.h" #include "common/value.h" #include "common/value_kind.h" #include "internal/testing.h" namespace cel { void PrintTo(const Value& value, std::ostream* os) { *os << value << "\n"; } namespace test { namespace { using testing::Matcher; template <typename Type> constexpr ValueKind ToValueKind() { if constexpr (std::is_same_v<Type, BoolValue>) { return ValueKind::kBool; } else if constexpr (std::is_same_v<Type, IntValue>) { return ValueKind::kInt; } else if constexpr (std::is_same_v<Type, UintValue>) { return ValueKind::kUint; } else if constexpr (std::is_same_v<Type, DoubleValue>) { return ValueKind::kDouble; } else if constexpr (std::is_same_v<Type, StringValue>) { return ValueKind::kString; } else if constexpr (std::is_same_v<Type, BytesValue>) { return ValueKind::kBytes; } else if constexpr (std::is_same_v<Type, DurationValue>) { return ValueKind::kDuration; } else if constexpr (std::is_same_v<Type, TimestampValue>) { return ValueKind::kTimestamp; } else if constexpr (std::is_same_v<Type, ErrorValue>) { return ValueKind::kError; } else if constexpr (std::is_same_v<Type, MapValue>) { return ValueKind::kMap; } else if constexpr (std::is_same_v<Type, ListValue>) { return ValueKind::kList; } else if constexpr (std::is_same_v<Type, StructValue>) { return ValueKind::kStruct; } else if constexpr (std::is_same_v<Type, OpaqueValue>) { return ValueKind::kOpaque; } else { return ValueKind::kError; } } template <typename Type, typename NativeType> class SimpleTypeMatcherImpl : public testing::MatcherInterface<const Value&> { public: using MatcherType = Matcher<NativeType>; explicit SimpleTypeMatcherImpl(MatcherType&& matcher) : matcher_(std::forward<MatcherType>(matcher)) {} bool MatchAndExplain(const Value& v, testing::MatchResultListener* listener) const override { return InstanceOf<Type>(v) && matcher_.MatchAndExplain(Cast<Type>(v).NativeValue(), listener); } void DescribeTo(std::ostream* os) const override { *os << absl::StrCat("kind is ", ValueKindToString(ToValueKind<Type>()), " and "); matcher_.DescribeTo(os); } private: MatcherType matcher_; }; template <typename Type> class StringTypeMatcherImpl : public testing::MatcherInterface<const Value&> { public: using MatcherType = Matcher<std::string>; explicit StringTypeMatcherImpl(MatcherType matcher) : matcher_((std::move(matcher))) {} bool MatchAndExplain(const Value& v, testing::MatchResultListener* listener) const override { return InstanceOf<Type>(v) && matcher_.Matches(Cast<Type>(v).ToString()); } void DescribeTo(std::ostream* os) const override { *os << absl::StrCat("kind is ", ValueKindToString(ToValueKind<Type>()), " and "); matcher_.DescribeTo(os); } private: MatcherType matcher_; }; template <typename Type> class AbstractTypeMatcherImpl : public testing::MatcherInterface<const Value&> { public: using MatcherType = Matcher<Type>; explicit AbstractTypeMatcherImpl(MatcherType&& matcher) : matcher_(std::forward<MatcherType>(matcher)) {} bool MatchAndExplain(const Value& v, testing::MatchResultListener* listener) const override { return InstanceOf<Type>(v) && matcher_.Matches(Cast<Type>(v)); } void DescribeTo(std::ostream* os) const override { *os << absl::StrCat("kind is ", ValueKindToString(ToValueKind<Type>()), " and "); matcher_.DescribeTo(os); } private: MatcherType matcher_; }; class OptionalValueMatcherImpl : public testing::MatcherInterface<const Value&> { public: explicit OptionalValueMatcherImpl(ValueMatcher matcher) : matcher_(std::move(matcher)) {} bool MatchAndExplain(const Value& v, testing::MatchResultListener* listener) const override { if (!InstanceOf<OptionalValue>(v)) { *listener << "wanted OptionalValue, got " << ValueKindToString(v.kind()); return false; } const auto& optional_value = Cast<OptionalValue>(v); if (!optional_value->HasValue()) { *listener << "OptionalValue is not engaged"; return false; } return matcher_.MatchAndExplain(optional_value->Value(), listener); } void DescribeTo(std::ostream* os) const override { *os << "is OptionalValue that is engaged with value whose "; matcher_.DescribeTo(os); } private: ValueMatcher matcher_; }; MATCHER(OptionalValueIsEmptyImpl, "is empty OptionalValue") { const Value& v = arg; if (!InstanceOf<OptionalValue>(v)) { *result_listener << "wanted OptionalValue, got " << ValueKindToString(v.kind()); return false; } const auto& optional_value = Cast<OptionalValue>(v); *result_listener << (optional_value.HasValue() ? "is not empty" : "is empty"); return !optional_value->HasValue(); } } ValueMatcher BoolValueIs(Matcher<bool> m) { return ValueMatcher(new SimpleTypeMatcherImpl<BoolValue, bool>(std::move(m))); } ValueMatcher IntValueIs(Matcher<int64_t> m) { return ValueMatcher( new SimpleTypeMatcherImpl<IntValue, int64_t>(std::move(m))); } ValueMatcher UintValueIs(Matcher<uint64_t> m) { return ValueMatcher( new SimpleTypeMatcherImpl<UintValue, uint64_t>(std::move(m))); } ValueMatcher DoubleValueIs(Matcher<double> m) { return ValueMatcher( new SimpleTypeMatcherImpl<DoubleValue, double>(std::move(m))); } ValueMatcher TimestampValueIs(Matcher<absl::Time> m) { return ValueMatcher( new SimpleTypeMatcherImpl<TimestampValue, absl::Time>(std::move(m))); } ValueMatcher DurationValueIs(Matcher<absl::Duration> m) { return ValueMatcher( new SimpleTypeMatcherImpl<DurationValue, absl::Duration>(std::move(m))); } ValueMatcher ErrorValueIs(Matcher<absl::Status> m) { return ValueMatcher( new SimpleTypeMatcherImpl<ErrorValue, absl::Status>(std::move(m))); } ValueMatcher StringValueIs(Matcher<std::string> m) { return ValueMatcher(new StringTypeMatcherImpl<StringValue>(std::move(m))); } ValueMatcher BytesValueIs(Matcher<std::string> m) { return ValueMatcher(new StringTypeMatcherImpl<BytesValue>(std::move(m))); } ValueMatcher MapValueIs(Matcher<MapValue> m) { return ValueMatcher(new AbstractTypeMatcherImpl<MapValue>(std::move(m))); } ValueMatcher ListValueIs(Matcher<ListValue> m) { return ValueMatcher(new AbstractTypeMatcherImpl<ListValue>(std::move(m))); } ValueMatcher StructValueIs(Matcher<StructValue> m) { return ValueMatcher(new AbstractTypeMatcherImpl<StructValue>(std::move(m))); } ValueMatcher OptionalValueIs(ValueMatcher m) { return ValueMatcher(new OptionalValueMatcherImpl(std::move(m))); } ValueMatcher OptionalValueIsEmpty() { return OptionalValueIsEmptyImpl(); } } }
#include "extensions/protobuf/value_testing.h" #include "common/memory.h" #include "common/value.h" #include "common/value_testing.h" #include "extensions/protobuf/memory_manager.h" #include "extensions/protobuf/value.h" #include "internal/proto_matchers.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/arena.h" namespace cel::extensions::test { namespace { using ::cel::extensions::ProtoMessageToValue; using ::cel::internal::test::EqualsProto; using ::google::api::expr::test::v1::proto2::TestAllTypes; class ProtoValueTesting : public common_internal::ThreadCompatibleValueTest<> { protected: MemoryManager NewThreadCompatiblePoolingMemoryManager() override { return cel::extensions::ProtoMemoryManager(&arena_); } private: google::protobuf::Arena arena_; }; class ProtoValueTestingTest : public ProtoValueTesting {}; TEST_P(ProtoValueTestingTest, StructValueAsProtoSimple) { TestAllTypes test_proto; test_proto.set_single_int32(42); test_proto.set_single_string("foo"); ASSERT_OK_AND_ASSIGN(cel::Value v, ProtoMessageToValue(value_manager(), test_proto)); EXPECT_THAT(v, StructValueAsProto<TestAllTypes>(EqualsProto(R"pb( single_int32: 42 single_string: "foo" )pb"))); } INSTANTIATE_TEST_SUITE_P(ProtoValueTesting, ProtoValueTestingTest, testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoValueTestingTest::ToString); } }
3
cpp
google/cel-cpp
type_introspector
extensions/protobuf/type_introspector.cc
extensions/protobuf/type_introspector_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_INTROSPECTOR_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_INTROSPECTOR_H_ #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/type.h" #include "common/type_factory.h" #include "common/type_introspector.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { class ProtoTypeIntrospector : public virtual TypeIntrospector { public: ProtoTypeIntrospector() : ProtoTypeIntrospector(google::protobuf::DescriptorPool::generated_pool()) {} explicit ProtoTypeIntrospector( absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool) : descriptor_pool_(descriptor_pool) {} absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() const { return descriptor_pool_; } protected: absl::StatusOr<absl::optional<TypeView>> FindTypeImpl( TypeFactory& type_factory, absl::string_view name, Type& scratch) const final; absl::StatusOr<absl::optional<StructTypeFieldView>> FindStructTypeFieldByNameImpl(TypeFactory& type_factory, absl::string_view type, absl::string_view name, StructTypeField& scratch) const final; private: absl::Nonnull<const google::protobuf::DescriptorPool*> const descriptor_pool_; }; } #endif #include "extensions/protobuf/type_introspector.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/type.h" #include "common/type_factory.h" #include "common/type_introspector.h" #include "extensions/protobuf/type.h" #include "internal/status_macros.h" namespace cel::extensions { absl::StatusOr<absl::optional<TypeView>> ProtoTypeIntrospector::FindTypeImpl( TypeFactory& type_factory, absl::string_view name, Type& scratch) const { const auto* desc = descriptor_pool()->FindMessageTypeByName(name); if (desc == nullptr) { return absl::nullopt; } scratch = type_factory.CreateStructType(desc->full_name()); return scratch; } absl::StatusOr<absl::optional<StructTypeFieldView>> ProtoTypeIntrospector::FindStructTypeFieldByNameImpl( TypeFactory& type_factory, absl::string_view type, absl::string_view name, StructTypeField& scratch) const { const auto* desc = descriptor_pool()->FindMessageTypeByName(type); if (desc == nullptr) { return absl::nullopt; } const auto* field_desc = desc->FindFieldByName(name); if (field_desc == nullptr) { field_desc = descriptor_pool()->FindExtensionByPrintableName(desc, name); if (field_desc == nullptr) { return absl::nullopt; } } StructTypeFieldView result; CEL_ASSIGN_OR_RETURN( result.type, ProtoFieldTypeToType(type_factory, field_desc, scratch.type)); result.name = field_desc->name(); result.number = field_desc->number(); return result; } }
#include "extensions/protobuf/type_introspector.h" #include "absl/types/optional.h" #include "common/type.h" #include "common/type_testing.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { namespace { using ::google::api::expr::test::v1::proto2::TestAllTypes; using testing::Eq; using testing::Optional; using cel::internal::IsOkAndHolds; class ProtoTypeIntrospectorTest : public common_internal::ThreadCompatibleTypeTest<> { private: Shared<TypeIntrospector> NewTypeIntrospector( MemoryManagerRef memory_manager) override { return memory_manager.MakeShared<ProtoTypeIntrospector>(); } }; TEST_P(ProtoTypeIntrospectorTest, FindType) { EXPECT_THAT( type_manager().FindType(TestAllTypes::descriptor()->full_name()), IsOkAndHolds(Optional(Eq(StructType( memory_manager(), TestAllTypes::GetDescriptor()->full_name()))))); EXPECT_THAT(type_manager().FindType("type.that.does.not.Exist"), IsOkAndHolds(Eq(absl::nullopt))); } TEST_P(ProtoTypeIntrospectorTest, FindStructTypeFieldByName) { ASSERT_OK_AND_ASSIGN( auto field, type_manager().FindStructTypeFieldByName( TestAllTypes::descriptor()->full_name(), "single_int32")); ASSERT_TRUE(field.has_value()); EXPECT_THAT(field->name, Eq("single_int32")); EXPECT_THAT(field->number, Eq(1)); EXPECT_THAT(field->type, Eq(IntType{})); EXPECT_THAT( type_manager().FindStructTypeFieldByName( TestAllTypes::descriptor()->full_name(), "field_that_does_not_exist"), IsOkAndHolds(Eq(absl::nullopt))); EXPECT_THAT(type_manager().FindStructTypeFieldByName( "type.that.does.not.Exist", "does_not_matter"), IsOkAndHolds(Eq(absl::nullopt))); } INSTANTIATE_TEST_SUITE_P( ProtoTypeIntrospectorTest, ProtoTypeIntrospectorTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoTypeIntrospectorTest::ToString); } }
4
cpp
google/cel-cpp
constant
extensions/protobuf/internal/constant.cc
common/constant_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_CONSTANT_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_CONSTANT_H_ #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "common/constant.h" namespace cel::extensions::protobuf_internal { absl::Status ConstantToProto(const Constant& constant, absl::Nonnull<google::api::expr::v1alpha1::Constant*> proto); absl::Status ConstantFromProto(const google::api::expr::v1alpha1::Constant& proto, Constant& constant); } #endif #include "extensions/protobuf/internal/constant.h" #include <cstddef> #include <cstdint> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "absl/types/variant.h" #include "common/constant.h" #include "internal/proto_time_encoding.h" namespace cel::extensions::protobuf_internal { using ConstantProto = google::api::expr::v1alpha1::Constant; absl::Status ConstantToProto(const Constant& constant, absl::Nonnull<ConstantProto*> proto) { return absl::visit(absl::Overload( [proto](absl::monostate) -> absl::Status { proto->clear_constant_kind(); return absl::OkStatus(); }, [proto](std::nullptr_t) -> absl::Status { proto->set_null_value(google::protobuf::NULL_VALUE); return absl::OkStatus(); }, [proto](bool value) -> absl::Status { proto->set_bool_value(value); return absl::OkStatus(); }, [proto](int64_t value) -> absl::Status { proto->set_int64_value(value); return absl::OkStatus(); }, [proto](uint64_t value) -> absl::Status { proto->set_uint64_value(value); return absl::OkStatus(); }, [proto](double value) -> absl::Status { proto->set_double_value(value); return absl::OkStatus(); }, [proto](const BytesConstant& value) -> absl::Status { proto->set_bytes_value(value); return absl::OkStatus(); }, [proto](const StringConstant& value) -> absl::Status { proto->set_string_value(value); return absl::OkStatus(); }, [proto](absl::Duration value) -> absl::Status { return internal::EncodeDuration( value, proto->mutable_duration_value()); }, [proto](absl::Time value) -> absl::Status { return internal::EncodeTime( value, proto->mutable_timestamp_value()); }), constant.kind()); } absl::Status ConstantFromProto(const ConstantProto& proto, Constant& constant) { switch (proto.constant_kind_case()) { case ConstantProto::CONSTANT_KIND_NOT_SET: constant = Constant{}; break; case ConstantProto::kNullValue: constant.set_null_value(); break; case ConstantProto::kBoolValue: constant.set_bool_value(proto.bool_value()); break; case ConstantProto::kInt64Value: constant.set_int_value(proto.int64_value()); break; case ConstantProto::kUint64Value: constant.set_uint_value(proto.uint64_value()); break; case ConstantProto::kDoubleValue: constant.set_double_value(proto.double_value()); break; case ConstantProto::kStringValue: constant.set_string_value(proto.string_value()); break; case ConstantProto::kBytesValue: constant.set_bytes_value(proto.bytes_value()); break; case ConstantProto::kDurationValue: constant.set_duration_value( internal::DecodeDuration(proto.duration_value())); break; case ConstantProto::kTimestampValue: constant.set_timestamp_value( internal::DecodeTime(proto.timestamp_value())); break; default: return absl::InvalidArgumentError( absl::StrCat("unexpected ConstantKindCase: ", static_cast<int>(proto.constant_kind_case()))); } return absl::OkStatus(); } }
#include "common/constant.h" #include <cmath> #include <string> #include "absl/strings/has_absl_stringify.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" #include "internal/testing.h" namespace cel { namespace { using testing::IsEmpty; using testing::IsFalse; using testing::IsTrue; TEST(Constant, NullValue) { Constant const_expr; EXPECT_THAT(const_expr.has_null_value(), IsFalse()); const_expr.set_null_value(); EXPECT_THAT(const_expr.has_null_value(), IsTrue()); } TEST(Constant, BoolValue) { Constant const_expr; EXPECT_THAT(const_expr.has_bool_value(), IsFalse()); EXPECT_EQ(const_expr.bool_value(), false); const_expr.set_bool_value(false); EXPECT_THAT(const_expr.has_bool_value(), IsTrue()); EXPECT_EQ(const_expr.bool_value(), false); } TEST(Constant, IntValue) { Constant const_expr; EXPECT_THAT(const_expr.has_int_value(), IsFalse()); EXPECT_EQ(const_expr.int_value(), 0); const_expr.set_int_value(0); EXPECT_THAT(const_expr.has_int_value(), IsTrue()); EXPECT_EQ(const_expr.int_value(), 0); } TEST(Constant, UintValue) { Constant const_expr; EXPECT_THAT(const_expr.has_uint_value(), IsFalse()); EXPECT_EQ(const_expr.uint_value(), 0); const_expr.set_uint_value(0); EXPECT_THAT(const_expr.has_uint_value(), IsTrue()); EXPECT_EQ(const_expr.uint_value(), 0); } TEST(Constant, DoubleValue) { Constant const_expr; EXPECT_THAT(const_expr.has_double_value(), IsFalse()); EXPECT_EQ(const_expr.double_value(), 0); const_expr.set_double_value(0); EXPECT_THAT(const_expr.has_double_value(), IsTrue()); EXPECT_EQ(const_expr.double_value(), 0); } TEST(Constant, BytesValue) { Constant const_expr; EXPECT_THAT(const_expr.has_bytes_value(), IsFalse()); EXPECT_THAT(const_expr.bytes_value(), IsEmpty()); const_expr.set_bytes_value("foo"); EXPECT_THAT(const_expr.has_bytes_value(), IsTrue()); EXPECT_EQ(const_expr.bytes_value(), "foo"); } TEST(Constant, StringValue) { Constant const_expr; EXPECT_THAT(const_expr.has_string_value(), IsFalse()); EXPECT_THAT(const_expr.string_value(), IsEmpty()); const_expr.set_string_value("foo"); EXPECT_THAT(const_expr.has_string_value(), IsTrue()); EXPECT_EQ(const_expr.string_value(), "foo"); } TEST(Constant, DurationValue) { Constant const_expr; EXPECT_THAT(const_expr.has_duration_value(), IsFalse()); EXPECT_EQ(const_expr.duration_value(), absl::ZeroDuration()); const_expr.set_duration_value(absl::ZeroDuration()); EXPECT_THAT(const_expr.has_duration_value(), IsTrue()); EXPECT_EQ(const_expr.duration_value(), absl::ZeroDuration()); } TEST(Constant, TimestampValue) { Constant const_expr; EXPECT_THAT(const_expr.has_timestamp_value(), IsFalse()); EXPECT_EQ(const_expr.timestamp_value(), absl::UnixEpoch()); const_expr.set_timestamp_value(absl::UnixEpoch()); EXPECT_THAT(const_expr.has_timestamp_value(), IsTrue()); EXPECT_EQ(const_expr.timestamp_value(), absl::UnixEpoch()); } TEST(Constant, Equality) { EXPECT_EQ(Constant{}, Constant{}); Constant lhs_const_expr; Constant rhs_const_expr; lhs_const_expr.set_null_value(); rhs_const_expr.set_null_value(); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_bool_value(false); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_bool_value(false); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_int_value(0); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_int_value(0); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_uint_value(0); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_uint_value(0); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_double_value(0); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_double_value(0); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_bytes_value("foo"); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_bytes_value("foo"); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_string_value("foo"); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_string_value("foo"); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_duration_value(absl::ZeroDuration()); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_duration_value(absl::ZeroDuration()); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); lhs_const_expr.set_timestamp_value(absl::UnixEpoch()); rhs_const_expr.set_null_value(); EXPECT_NE(lhs_const_expr, rhs_const_expr); EXPECT_NE(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); rhs_const_expr.set_timestamp_value(absl::UnixEpoch()); EXPECT_EQ(lhs_const_expr, rhs_const_expr); EXPECT_EQ(rhs_const_expr, lhs_const_expr); EXPECT_NE(lhs_const_expr, Constant{}); EXPECT_NE(Constant{}, rhs_const_expr); } std::string Stringify(const Constant& constant) { return absl::StrFormat("%v", constant); } TEST(Constant, HasAbslStringify) { EXPECT_TRUE(absl::HasAbslStringify<Constant>::value); } TEST(Constant, AbslStringify) { Constant constant; EXPECT_EQ(Stringify(constant), "<unspecified>"); constant.set_null_value(); EXPECT_EQ(Stringify(constant), "null"); constant.set_bool_value(true); EXPECT_EQ(Stringify(constant), "true"); constant.set_int_value(1); EXPECT_EQ(Stringify(constant), "1"); constant.set_uint_value(1); EXPECT_EQ(Stringify(constant), "1u"); constant.set_double_value(1); EXPECT_EQ(Stringify(constant), "1.0"); constant.set_double_value(1.1); EXPECT_EQ(Stringify(constant), "1.1"); constant.set_double_value(NAN); EXPECT_EQ(Stringify(constant), "nan"); constant.set_double_value(INFINITY); EXPECT_EQ(Stringify(constant), "+infinity"); constant.set_double_value(-INFINITY); EXPECT_EQ(Stringify(constant), "-infinity"); constant.set_bytes_value("foo"); EXPECT_EQ(Stringify(constant), "b\"foo\""); constant.set_string_value("foo"); EXPECT_EQ(Stringify(constant), "\"foo\""); constant.set_duration_value(absl::Seconds(1)); EXPECT_EQ(Stringify(constant), "duration(\"1s\")"); constant.set_timestamp_value(absl::UnixEpoch() + absl::Seconds(1)); EXPECT_EQ(Stringify(constant), "timestamp(\"1970-01-01T00:00:01Z\")"); } } }
5
cpp
google/cel-cpp
expr
common/expr.cc
common/expr_test.cc
#ifndef THIRD_PARTY_CEL_CPP_BASE_AST_INTERNAL_EXPR_H_ #define THIRD_PARTY_CEL_CPP_BASE_AST_INTERNAL_EXPR_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "common/ast.h" #include "common/constant.h" #include "common/expr.h" namespace cel::ast_internal { using NullValue = std::nullptr_t; using Bytes = cel::BytesConstant; using Constant = cel::Constant; using ConstantKind = cel::ConstantKind; using Ident = cel::IdentExpr; using Expr = cel::Expr; using ExprKind = cel::ExprKind; using Select = cel::SelectExpr; using Call = cel::CallExpr; using CreateList = cel::ListExpr; using CreateStruct = cel::StructExpr; using Comprehension = cel::ComprehensionExpr; class Extension { public: class Version { public: Version() : major_(0), minor_(0) {} Version(int64_t major, int64_t minor) : major_(major), minor_(minor) {} Version(const Version& other) = default; Version(Version&& other) = default; Version& operator=(const Version& other) = default; Version& operator=(Version&& other) = default; static const Version& DefaultInstance(); int64_t major() const { return major_; } void set_major(int64_t val) { major_ = val; } int64_t minor() const { return minor_; } void set_minor(int64_t val) { minor_ = val; } bool operator==(const Version& other) const { return major_ == other.major_ && minor_ == other.minor_; } bool operator!=(const Version& other) const { return !operator==(other); } private: int64_t major_; int64_t minor_; }; enum class Component { kUnspecified, kParser, kTypeChecker, kRuntime }; static const Extension& DefaultInstance(); Extension() = default; Extension(std::string id, std::unique_ptr<Version> version, std::vector<Component> affected_components) : id_(std::move(id)), affected_components_(std::move(affected_components)), version_(std::move(version)) {} Extension(const Extension& other); Extension(Extension&& other) = default; Extension& operator=(const Extension& other); Extension& operator=(Extension&& other) = default; const std::string& id() const { return id_; } void set_id(std::string id) { id_ = std::move(id); } const std::vector<Component>& affected_components() const { return affected_components_; } std::vector<Component>& mutable_affected_components() { return affected_components_; } const Version& version() const { if (version_ == nullptr) { return Version::DefaultInstance(); } return *version_; } Version& mutable_version() { if (version_ == nullptr) { version_ = std::make_unique<Version>(); } return *version_; } void set_version(std::unique_ptr<Version> version) { version_ = std::move(version); } bool operator==(const Extension& other) const { return id_ == other.id_ && affected_components_ == other.affected_components_ && version() == other.version(); } bool operator!=(const Extension& other) const { return !operator==(other); } private: std::string id_; std::vector<Component> affected_components_; std::unique_ptr<Version> version_; }; class SourceInfo { public: SourceInfo() = default; SourceInfo(std::string syntax_version, std::string location, std::vector<int32_t> line_offsets, absl::flat_hash_map<int64_t, int32_t> positions, absl::flat_hash_map<int64_t, Expr> macro_calls, std::vector<Extension> extensions) : syntax_version_(std::move(syntax_version)), location_(std::move(location)), line_offsets_(std::move(line_offsets)), positions_(std::move(positions)), macro_calls_(std::move(macro_calls)), extensions_(std::move(extensions)) {} void set_syntax_version(std::string syntax_version) { syntax_version_ = std::move(syntax_version); } void set_location(std::string location) { location_ = std::move(location); } void set_line_offsets(std::vector<int32_t> line_offsets) { line_offsets_ = std::move(line_offsets); } void set_positions(absl::flat_hash_map<int64_t, int32_t> positions) { positions_ = std::move(positions); } void set_macro_calls(absl::flat_hash_map<int64_t, Expr> macro_calls) { macro_calls_ = std::move(macro_calls); } const std::string& syntax_version() const { return syntax_version_; } const std::string& location() const { return location_; } const std::vector<int32_t>& line_offsets() const { return line_offsets_; } std::vector<int32_t>& mutable_line_offsets() { return line_offsets_; } const absl::flat_hash_map<int64_t, int32_t>& positions() const { return positions_; } absl::flat_hash_map<int64_t, int32_t>& mutable_positions() { return positions_; } const absl::flat_hash_map<int64_t, Expr>& macro_calls() const { return macro_calls_; } absl::flat_hash_map<int64_t, Expr>& mutable_macro_calls() { return macro_calls_; } bool operator==(const SourceInfo& other) const { return syntax_version_ == other.syntax_version_ && location_ == other.location_ && line_offsets_ == other.line_offsets_ && positions_ == other.positions_ && macro_calls_ == other.macro_calls_ && extensions_ == other.extensions_; } bool operator!=(const SourceInfo& other) const { return !operator==(other); } const std::vector<Extension>& extensions() const { return extensions_; } std::vector<Extension>& mutable_extensions() { return extensions_; } private: std::string syntax_version_; std::string location_; std::vector<int32_t> line_offsets_; absl::flat_hash_map<int64_t, int32_t> positions_; absl::flat_hash_map<int64_t, Expr> macro_calls_; std::vector<Extension> extensions_; }; class ParsedExpr { public: ParsedExpr() = default; ParsedExpr(Expr expr, SourceInfo source_info) : expr_(std::move(expr)), source_info_(std::move(source_info)) {} ParsedExpr(ParsedExpr&& rhs) = default; ParsedExpr& operator=(ParsedExpr&& rhs) = default; void set_expr(Expr expr) { expr_ = std::move(expr); } void set_source_info(SourceInfo source_info) { source_info_ = std::move(source_info); } const Expr& expr() const { return expr_; } Expr& mutable_expr() { return expr_; } const SourceInfo& source_info() const { return source_info_; } SourceInfo& mutable_source_info() { return source_info_; } private: Expr expr_; SourceInfo source_info_; }; enum class PrimitiveType { kPrimitiveTypeUnspecified = 0, kBool = 1, kInt64 = 2, kUint64 = 3, kDouble = 4, kString = 5, kBytes = 6, }; enum class WellKnownType { kWellKnownTypeUnspecified = 0, kAny = 1, kTimestamp = 2, kDuration = 3, }; class Type; class ListType { public: ListType() = default; ListType(const ListType& rhs) : elem_type_(std::make_unique<Type>(rhs.elem_type())) {} ListType& operator=(const ListType& rhs) { elem_type_ = std::make_unique<Type>(rhs.elem_type()); return *this; } ListType(ListType&& rhs) = default; ListType& operator=(ListType&& rhs) = default; explicit ListType(std::unique_ptr<Type> elem_type) : elem_type_(std::move(elem_type)) {} void set_elem_type(std::unique_ptr<Type> elem_type) { elem_type_ = std::move(elem_type); } bool has_elem_type() const { return elem_type_ != nullptr; } const Type& elem_type() const; Type& mutable_elem_type() { if (elem_type_ == nullptr) { elem_type_ = std::make_unique<Type>(); } return *elem_type_; } bool operator==(const ListType& other) const; private: std::unique_ptr<Type> elem_type_; }; class MapType { public: MapType() = default; MapType(std::unique_ptr<Type> key_type, std::unique_ptr<Type> value_type) : key_type_(std::move(key_type)), value_type_(std::move(value_type)) {} MapType(const MapType& rhs) : key_type_(std::make_unique<Type>(rhs.key_type())), value_type_(std::make_unique<Type>(rhs.value_type())) {} MapType& operator=(const MapType& rhs) { key_type_ = std::make_unique<Type>(rhs.key_type()); value_type_ = std::make_unique<Type>(rhs.value_type()); return *this; } MapType(MapType&& rhs) = default; MapType& operator=(MapType&& rhs) = default; void set_key_type(std::unique_ptr<Type> key_type) { key_type_ = std::move(key_type); } void set_value_type(std::unique_ptr<Type> value_type) { value_type_ = std::move(value_type); } bool has_key_type() const { return key_type_ != nullptr; } bool has_value_type() const { return value_type_ != nullptr; } const Type& key_type() const; const Type& value_type() const; bool operator==(const MapType& other) const; Type& mutable_key_type() { if (key_type_ == nullptr) { key_type_ = std::make_unique<Type>(); } return *key_type_; } Type& mutable_value_type() { if (value_type_ == nullptr) { value_type_ = std::make_unique<Type>(); } return *value_type_; } private: std::unique_ptr<Type> key_type_; std::unique_ptr<Type> value_type_; }; class FunctionType { public: FunctionType() = default; FunctionType(std::unique_ptr<Type> result_type, std::vector<Type> arg_types); FunctionType(const FunctionType& other); FunctionType& operator=(const FunctionType& other); FunctionType(FunctionType&&) = default; FunctionType& operator=(FunctionType&&) = default; void set_result_type(std::unique_ptr<Type> result_type) { result_type_ = std::move(result_type); } void set_arg_types(std::vector<Type> arg_types); bool has_result_type() const { return result_type_ != nullptr; } const Type& result_type() const; Type& mutable_result_type() { if (result_type_ == nullptr) { result_type_ = std::make_unique<Type>(); } return *result_type_; } const std::vector<Type>& arg_types() const { return arg_types_; } std::vector<Type>& mutable_arg_types() { return arg_types_; } bool operator==(const FunctionType& other) const; private: std::unique_ptr<Type> result_type_; std::vector<Type> arg_types_; }; class AbstractType { public: AbstractType() = default; AbstractType(std::string name, std::vector<Type> parameter_types); void set_name(std::string name) { name_ = std::move(name); } void set_parameter_types(std::vector<Type> parameter_types); const std::string& name() const { return name_; } const std::vector<Type>& parameter_types() const { return parameter_types_; } std::vector<Type>& mutable_parameter_types() { return parameter_types_; } bool operator==(const AbstractType& other) const; private: std::string name_; std::vector<Type> parameter_types_; }; class PrimitiveTypeWrapper { public: explicit PrimitiveTypeWrapper(PrimitiveType type) : type_(std::move(type)) {} void set_type(PrimitiveType type) { type_ = std::move(type); } const PrimitiveType& type() const { return type_; } PrimitiveType& mutable_type() { return type_; } bool operator==(const PrimitiveTypeWrapper& other) const { return type_ == other.type_; } private: PrimitiveType type_; }; class MessageType { public: MessageType() = default; explicit MessageType(std::string type) : type_(std::move(type)) {} void set_type(std::string type) { type_ = std::move(type); } const std::string& type() const { return type_; } bool operator==(const MessageType& other) const { return type_ == other.type_; } private: std::string type_; }; class ParamType { public: ParamType() = default; explicit ParamType(std::string type) : type_(std::move(type)) {} void set_type(std::string type) { type_ = std::move(type); } const std::string& type() const { return type_; } bool operator==(const ParamType& other) const { return type_ == other.type_; } private: std::string type_; }; enum class ErrorType { kErrorTypeValue = 0 }; using DynamicType = absl::monostate; using TypeKind = absl::variant<DynamicType, NullValue, PrimitiveType, PrimitiveTypeWrapper, WellKnownType, ListType, MapType, FunctionType, MessageType, ParamType, std::unique_ptr<Type>, ErrorType, AbstractType>; class Type { public: Type() = default; explicit Type(TypeKind type_kind) : type_kind_(std::move(type_kind)) {} Type(const Type& other); Type& operator=(const Type& other); Type(Type&&) = default; Type& operator=(Type&&) = default; void set_type_kind(TypeKind type_kind) { type_kind_ = std::move(type_kind); } const TypeKind& type_kind() const { return type_kind_; } TypeKind& mutable_type_kind() { return type_kind_; } bool has_dyn() const { return absl::holds_alternative<DynamicType>(type_kind_); } bool has_null() const { return absl::holds_alternative<NullValue>(type_kind_); } bool has_primitive() const { return absl::holds_alternative<PrimitiveType>(type_kind_); } bool has_wrapper() const { return absl::holds_alternative<PrimitiveTypeWrapper>(type_kind_); } bool has_well_known() const { return absl::holds_alternative<WellKnownType>(type_kind_); } bool has_list_type() const { return absl::holds_alternative<ListType>(type_kind_); } bool has_map_type() const { return absl::holds_alternative<MapType>(type_kind_); } bool has_function() const { return absl::holds_alternative<FunctionType>(type_kind_); } bool has_message_type() const { return absl::holds_alternative<MessageType>(type_kind_); } bool has_type_param() const { return absl::holds_alternative<ParamType>(type_kind_); } bool has_type() const { return absl::holds_alternative<std::unique_ptr<Type>>(type_kind_); } bool has_error() const { return absl::holds_alternative<ErrorType>(type_kind_); } bool has_abstract_type() const { return absl::holds_alternative<AbstractType>(type_kind_); } NullValue null() const { auto* value = absl::get_if<NullValue>(&type_kind_); if (value != nullptr) { return *value; } return nullptr; } PrimitiveType primitive() const { auto* value = absl::get_if<PrimitiveType>(&type_kind_); if (value != nullptr) { return *value; } return PrimitiveType::kPrimitiveTypeUnspecified; } PrimitiveType wrapper() const { auto* value = absl::get_if<PrimitiveTypeWrapper>(&type_kind_); if (value != nullptr) { return value->type(); } return PrimitiveType::kPrimitiveTypeUnspecified; } WellKnownType well_known() const { auto* value = absl::get_if<WellKnownType>(&type_kind_); if (value != nullptr) { return *value; } return WellKnownType::kWellKnownTypeUnspecified; } const ListType& list_type() const { auto* value = absl::get_if<ListType>(&type_kind_); if (value != nullptr) { return *value; } static const ListType* default_list_type = new ListType(); return *default_list_type; } const MapType& map_type() const { auto* value = absl::get_if<MapType>(&type_kind_); if (value != nullptr) { return *value; } static const MapType* default_map_type = new MapType(); return *default_map_type; } const FunctionType& function() const { auto* value = absl::get_if<FunctionType>(&type_kind_); if (value != nullptr) { return *value; } static const FunctionType* default_function_type = new FunctionType(); return *default_function_type; } const MessageType& message_type() const { auto* value = absl::get_if<MessageType>(&type_kind_); if (value != nullptr) { return *value; } static const MessageType* default_message_type = new MessageType(); return *default_message_type; } const ParamType& type_param() const { auto* value = absl::get_if<ParamType>(&type_kind_); if (value != nullptr) { return *value; } static const ParamType* default_param_type = new ParamType(); return *default_param_type; } const Type& type() const; ErrorType error_type() const { auto* value = absl::get_if<ErrorType>(&type_kind_); if (value != nullptr) { return *value; } return ErrorType::kErrorTypeValue; } const AbstractType& abstract_type() const { auto* value = absl::get_if<AbstractType>(&type_kind_); if (value != nullptr) { return *value; } static const AbstractType* default_abstract_type = new AbstractType(); return *default_abstract_type; } bool operator==(const Type& other) const { return type_kind_ == other.type_kind_; } private: TypeKind type_kind_; }; class Reference { public: Reference() = default; Reference(std::string name, std::vector<std::string> overload_id, Constant value) : name_(std::move(name)), overload_id_(std::move(overload_id)), value_(std::move(value)) {} void set_name(std::string name) { name_ = std::move(name); } void set_overload_id(std::vector<std::string> overload_id) { overload_id_ = std::move(overload_id); } void set_value(Constant value) { value_ = std::move(value); } const std::string& name() const { return name_; } const std::vector<std::string>& overload_id() const { return overload_id_; } const Constant& value() const { if (value_.has_value()) { return value_.value(); } static const Constant* default_constant = new Constant; return *default_constant; } std::vector<std::string>& mutable_overload_id() { return overload_id_; } Constant& mutable_value() { if (!value_.has_value()) { value_.emplace(); } return *value_; } bool has_value() const { return value_.has_value(); } bool operator==(const Reference& other) const { return name_ == other.name_ && overload_id_ == other.overload_id_ && value() == other.value(); } private: std::string name_; std::vector<std::string> overload_id_; absl::optional<Constant> value_; }; class CheckedExpr { public: CheckedExpr() = default; CheckedExpr(absl::flat_hash_map<int64_t, Reference> reference_map, absl::flat_hash_map<int64_t, Type> type_map, SourceInfo source_info, std::string expr_version, Expr expr) : reference_map_(std::move(reference_map)), type_map_(std::move(type_map)), source_info_(std::move(source_info)), expr_version_(std::move(expr_version)), expr_(std::move(expr)) {} CheckedExpr(CheckedExpr&& rhs) = default; CheckedExpr& operator=(CheckedExpr&& rhs) = default; void set_reference_map( absl::flat_hash_map<int64_t, Reference> reference_map) { reference_map_ = std::move(reference_map); } void set_type_map(absl::flat_hash_map<int64_t, Type> type_map) { type_map_ = std::move(type_map); } void set_source_info(SourceInfo source_info) { source_info_ = std::move(source_info); } void set_expr_version(std::string expr_version) { expr_version_ = std::move(expr_version); } void set_expr(Expr expr) { expr_ = std::move(expr); } const absl::flat_hash_map<int64_t, Reference>& reference_map() const { return reference_map_; } absl::flat_hash_map<int64_t, Reference>& mutable_reference_map() { return reference_map_; } const absl::flat_hash_map<int64_t, Type>& type_map() const { return type_map_; } absl::flat_hash_map<int64_t, Type>& mutable_type_map() { return type_map_; } const SourceInfo& source_info() const { return source_info_; } SourceInfo& mutable_source_info() { return source_info_; } const std::string& expr_version() const { return expr_version_; } std::string& mutable_expr_version() { return expr_version_; } const Expr& expr() const { return expr_; } Expr& mutable_expr() { return expr_; } private: absl::flat_hash_map<int64_t, Reference> reference_map_; absl::flat_hash_map<int64_t, Type> type_map_; SourceInfo source_info_; std::string expr_version_; Expr expr_; }; inline FunctionType::FunctionType(std::unique_ptr<Type> result_type, std::vector<Type> arg_types) : result_type_(std::move(result_type)), arg_types_(std::move(arg_types)) {} inline void FunctionType::set_arg_types(std::vector<Type> arg_types) { arg_types_ = std::move(arg_types); } inline AbstractType::AbstractType(std::string name, std::vector<Type> parameter_types) : name_(std::move(name)), parameter_types_(std::move(parameter_types)) {} inline void AbstractType::set_parameter_types( std::vector<Type> parameter_types) { parameter_types_ = std::move(parameter_types); } inline bool AbstractType::operator==(const AbstractType& other) const { return name_ == other.name_ && parameter_types_ == other.parameter_types_; } } #endif #include "base/ast_internal/expr.h" #include <memory> #include <vector> #include "absl/base/no_destructor.h" #include "absl/functional/overload.h" #include "absl/types/variant.h" namespace cel::ast_internal { namespace { const Type& default_type() { static absl::NoDestructor<Type> type; return *type; } TypeKind CopyImpl(const TypeKind& other) { return absl::visit(absl::Overload( [](const std::unique_ptr<Type>& other) -> TypeKind { return std::make_unique<Type>(*other); }, [](const auto& other) -> TypeKind { return other; }), other); } } const Extension::Version& Extension::Version::DefaultInstance() { static absl::NoDestructor<Version> instance; return *instance; } const Extension& Extension::DefaultInstance() { static absl::NoDestructor<Extension> instance; return *instance; } Extension::Extension(const Extension& other) : id_(other.id_), affected_components_(other.affected_components_), version_(std::make_unique<Version>(*other.version_)) {} Extension& Extension::operator=(const Extension& other) { id_ = other.id_; affected_components_ = other.affected_components_; version_ = std::make_unique<Version>(*other.version_); return *this; } const Type& ListType::elem_type() const { if (elem_type_ != nullptr) { return *elem_type_; } return default_type(); } bool ListType::operator==(const ListType& other) const { return elem_type() == other.elem_type(); } const Type& MapType::key_type() const { if (key_type_ != nullptr) { return *key_type_; } return default_type(); } const Type& MapType::value_type() const { if (value_type_ != nullptr) { return *value_type_; } return default_type(); } bool MapType::operator==(const MapType& other) const { return key_type() == other.key_type() && value_type() == other.value_type(); } const Type& FunctionType::result_type() const { if (result_type_ != nullptr) { return *result_type_; } return default_type(); } bool FunctionType::operator==(const FunctionType& other) const { return result_type() == other.result_type() && arg_types_ == other.arg_types_; } const Type& Type::type() const { auto* v
#include "base/ast_internal/expr.h" #include <memory> #include <string> #include <utility> #include "absl/types/variant.h" #include "common/ast.h" #include "internal/testing.h" namespace cel { namespace ast_internal { namespace { TEST(AstTest, ParsedExpr) { ParsedExpr parsed_expr; auto& expr = parsed_expr.mutable_expr(); expr.set_id(1); expr.mutable_ident_expr().set_name("name"); auto& source_info = parsed_expr.mutable_source_info(); source_info.set_syntax_version("syntax_version"); source_info.set_location("location"); source_info.set_line_offsets({1, 2, 3}); source_info.set_positions({{1, 1}, {2, 2}}); ASSERT_TRUE(absl::holds_alternative<Ident>(parsed_expr.expr().kind())); ASSERT_EQ(absl::get<Ident>(parsed_expr.expr().kind()).name(), "name"); ASSERT_EQ(parsed_expr.source_info().syntax_version(), "syntax_version"); ASSERT_EQ(parsed_expr.source_info().location(), "location"); EXPECT_THAT(parsed_expr.source_info().line_offsets(), testing::UnorderedElementsAre(1, 2, 3)); EXPECT_THAT( parsed_expr.source_info().positions(), testing::UnorderedElementsAre(testing::Pair(1, 1), testing::Pair(2, 2))); } TEST(AstTest, ListTypeMutableConstruction) { ListType type; type.mutable_elem_type() = Type(PrimitiveType::kBool); EXPECT_EQ(absl::get<PrimitiveType>(type.elem_type().type_kind()), PrimitiveType::kBool); } TEST(AstTest, MapTypeMutableConstruction) { MapType type; type.mutable_key_type() = Type(PrimitiveType::kBool); type.mutable_value_type() = Type(PrimitiveType::kBool); EXPECT_EQ(absl::get<PrimitiveType>(type.key_type().type_kind()), PrimitiveType::kBool); EXPECT_EQ(absl::get<PrimitiveType>(type.value_type().type_kind()), PrimitiveType::kBool); } TEST(AstTest, MapTypeComparatorKeyType) { MapType type; type.mutable_key_type() = Type(PrimitiveType::kBool); EXPECT_FALSE(type == MapType()); } TEST(AstTest, MapTypeComparatorValueType) { MapType type; type.mutable_value_type() = Type(PrimitiveType::kBool); EXPECT_FALSE(type == MapType()); } TEST(AstTest, FunctionTypeMutableConstruction) { FunctionType type; type.mutable_result_type() = Type(PrimitiveType::kBool); EXPECT_EQ(absl::get<PrimitiveType>(type.result_type().type_kind()), PrimitiveType::kBool); } TEST(AstTest, FunctionTypeComparatorArgTypes) { FunctionType type; type.mutable_arg_types().emplace_back(Type()); EXPECT_FALSE(type == FunctionType()); } TEST(AstTest, CheckedExpr) { CheckedExpr checked_expr; auto& expr = checked_expr.mutable_expr(); expr.set_id(1); expr.mutable_ident_expr().set_name("name"); auto& source_info = checked_expr.mutable_source_info(); source_info.set_syntax_version("syntax_version"); source_info.set_location("location"); source_info.set_line_offsets({1, 2, 3}); source_info.set_positions({{1, 1}, {2, 2}}); checked_expr.set_expr_version("expr_version"); checked_expr.mutable_type_map().insert( {1, Type(PrimitiveType(PrimitiveType::kBool))}); ASSERT_TRUE(absl::holds_alternative<Ident>(checked_expr.expr().kind())); ASSERT_EQ(absl::get<Ident>(checked_expr.expr().kind()).name(), "name"); ASSERT_EQ(checked_expr.source_info().syntax_version(), "syntax_version"); ASSERT_EQ(checked_expr.source_info().location(), "location"); EXPECT_THAT(checked_expr.source_info().line_offsets(), testing::UnorderedElementsAre(1, 2, 3)); EXPECT_THAT( checked_expr.source_info().positions(), testing::UnorderedElementsAre(testing::Pair(1, 1), testing::Pair(2, 2))); EXPECT_EQ(checked_expr.expr_version(), "expr_version"); } TEST(AstTest, ListTypeDefaults) { EXPECT_EQ(ListType().elem_type(), Type()); } TEST(AstTest, MapTypeDefaults) { EXPECT_EQ(MapType().key_type(), Type()); EXPECT_EQ(MapType().value_type(), Type()); } TEST(AstTest, FunctionTypeDefaults) { EXPECT_EQ(FunctionType().result_type(), Type()); } TEST(AstTest, TypeDefaults) { EXPECT_EQ(Type().null(), nullptr); EXPECT_EQ(Type().primitive(), PrimitiveType::kPrimitiveTypeUnspecified); EXPECT_EQ(Type().wrapper(), PrimitiveType::kPrimitiveTypeUnspecified); EXPECT_EQ(Type().well_known(), WellKnownType::kWellKnownTypeUnspecified); EXPECT_EQ(Type().list_type(), ListType()); EXPECT_EQ(Type().map_type(), MapType()); EXPECT_EQ(Type().function(), FunctionType()); EXPECT_EQ(Type().message_type(), MessageType()); EXPECT_EQ(Type().type_param(), ParamType()); EXPECT_EQ(Type().type(), Type()); EXPECT_EQ(Type().error_type(), ErrorType()); EXPECT_EQ(Type().abstract_type(), AbstractType()); } TEST(AstTest, TypeComparatorTest) { Type type; type.set_type_kind(std::make_unique<Type>(PrimitiveType::kBool)); EXPECT_FALSE(type.type() == Type()); } TEST(AstTest, ExprMutableConstruction) { Expr expr; expr.mutable_const_expr().set_bool_value(true); ASSERT_TRUE(expr.has_const_expr()); EXPECT_TRUE(expr.const_expr().bool_value()); expr.mutable_ident_expr().set_name("expr"); ASSERT_TRUE(expr.has_ident_expr()); EXPECT_FALSE(expr.has_const_expr()); EXPECT_EQ(expr.ident_expr().name(), "expr"); expr.mutable_select_expr().set_field("field"); ASSERT_TRUE(expr.has_select_expr()); EXPECT_FALSE(expr.has_ident_expr()); EXPECT_EQ(expr.select_expr().field(), "field"); expr.mutable_call_expr().set_function("function"); ASSERT_TRUE(expr.has_call_expr()); EXPECT_FALSE(expr.has_select_expr()); EXPECT_EQ(expr.call_expr().function(), "function"); expr.mutable_list_expr(); EXPECT_TRUE(expr.has_list_expr()); EXPECT_FALSE(expr.has_call_expr()); expr.mutable_struct_expr().set_name("name"); ASSERT_TRUE(expr.has_struct_expr()); EXPECT_EQ(expr.struct_expr().name(), "name"); EXPECT_FALSE(expr.has_list_expr()); expr.mutable_comprehension_expr().set_accu_var("accu_var"); ASSERT_TRUE(expr.has_comprehension_expr()); EXPECT_FALSE(expr.has_list_expr()); EXPECT_EQ(expr.comprehension_expr().accu_var(), "accu_var"); } TEST(AstTest, ReferenceConstantDefaultValue) { Reference reference; EXPECT_EQ(reference.value(), Constant()); } TEST(AstTest, TypeCopyable) { Type type = Type(PrimitiveType::kBool); Type type2 = type; EXPECT_TRUE(type2.has_primitive()); EXPECT_EQ(type2, type); type = Type(ListType(std::make_unique<Type>(PrimitiveType::kBool))); type2 = type; EXPECT_TRUE(type2.has_list_type()); EXPECT_EQ(type2, type); type = Type(MapType(std::make_unique<Type>(PrimitiveType::kBool), std::make_unique<Type>(PrimitiveType::kBool))); type2 = type; EXPECT_TRUE(type2.has_map_type()); EXPECT_EQ(type2, type); type = Type(FunctionType(std::make_unique<Type>(PrimitiveType::kBool), {})); type2 = type; EXPECT_TRUE(type2.has_function()); EXPECT_EQ(type2, type); type = Type(AbstractType("optional", {Type(PrimitiveType::kBool)})); type2 = type; EXPECT_TRUE(type2.has_abstract_type()); EXPECT_EQ(type2, type); } TEST(AstTest, TypeMoveable) { Type type = Type(PrimitiveType::kBool); Type type2 = type; Type type3 = std::move(type); EXPECT_TRUE(type2.has_primitive()); EXPECT_EQ(type2, type3); type = Type(ListType(std::make_unique<Type>(PrimitiveType::kBool))); type2 = type; type3 = std::move(type); EXPECT_TRUE(type2.has_list_type()); EXPECT_EQ(type2, type3); type = Type(MapType(std::make_unique<Type>(PrimitiveType::kBool), std::make_unique<Type>(PrimitiveType::kBool))); type2 = type; type3 = std::move(type); EXPECT_TRUE(type2.has_map_type()); EXPECT_EQ(type2, type3); type = Type(FunctionType(std::make_unique<Type>(PrimitiveType::kBool), {})); type2 = type; type3 = std::move(type); EXPECT_TRUE(type2.has_function()); EXPECT_EQ(type2, type3); type = Type(AbstractType("optional", {Type(PrimitiveType::kBool)})); type2 = type; type3 = std::move(type); EXPECT_TRUE(type2.has_abstract_type()); EXPECT_EQ(type2, type3); } TEST(AstTest, NestedTypeKindCopyAssignable) { ListType list_type(std::make_unique<Type>(PrimitiveType::kBool)); ListType list_type2; list_type2 = list_type; EXPECT_EQ(list_type2, list_type); MapType map_type(std::make_unique<Type>(PrimitiveType::kBool), std::make_unique<Type>(PrimitiveType::kBool)); MapType map_type2; map_type2 = map_type; AbstractType abstract_type( "abstract", {Type(PrimitiveType::kBool), Type(PrimitiveType::kBool)}); AbstractType abstract_type2; abstract_type2 = abstract_type; EXPECT_EQ(abstract_type2, abstract_type); FunctionType function_type( std::make_unique<Type>(PrimitiveType::kBool), {Type(PrimitiveType::kBool), Type(PrimitiveType::kBool)}); FunctionType function_type2; function_type2 = function_type; EXPECT_EQ(function_type2, function_type); } TEST(AstTest, ExtensionSupported) { SourceInfo source_info; source_info.mutable_extensions().push_back( Extension("constant_folding", nullptr, {})); EXPECT_EQ(source_info.extensions()[0], Extension("constant_folding", nullptr, {})); } TEST(AstTest, ExtensionEquality) { Extension extension1("constant_folding", nullptr, {}); EXPECT_EQ(extension1, Extension("constant_folding", nullptr, {})); EXPECT_NE(extension1, Extension("constant_folding", std::make_unique<Extension::Version>(1, 0), {})); EXPECT_NE(extension1, Extension("constant_folding", nullptr, {Extension::Component::kRuntime})); EXPECT_EQ(extension1, Extension("constant_folding", std::make_unique<Extension::Version>(0, 0), {})); } } } }
6
cpp
google/cel-cpp
decl
common/decl.cc
common/decl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_DECL_H_ #define THIRD_PARTY_CEL_CPP_COMMON_DECL_H_ #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/container/flat_hash_set.h" #include "absl/hash/hash.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/constant.h" #include "common/type.h" #include "internal/status_macros.h" namespace cel { class VariableDecl; class OverloadDecl; class FunctionDecl; class VariableDecl final { public: VariableDecl() = default; VariableDecl(const VariableDecl&) = default; VariableDecl(VariableDecl&&) = default; VariableDecl& operator=(const VariableDecl&) = default; VariableDecl& operator=(VariableDecl&&) = default; ABSL_MUST_USE_RESULT const std::string& name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return name_; } void set_name(std::string name) { name_ = std::move(name); } void set_name(absl::string_view name) { name_.assign(name.data(), name.size()); } void set_name(const char* name) { set_name(absl::NullSafeStringView(name)); } ABSL_MUST_USE_RESULT std::string release_name() { std::string released; released.swap(name_); return released; } ABSL_MUST_USE_RESULT const Type& type() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return type_; } ABSL_MUST_USE_RESULT Type& mutable_type() ABSL_ATTRIBUTE_LIFETIME_BOUND { return type_; } void set_type(Type type) { mutable_type() = std::move(type); } ABSL_MUST_USE_RESULT bool has_value() const { return value_.has_value(); } ABSL_MUST_USE_RESULT const Constant& value() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return has_value() ? *value_ : Constant::default_instance(); } Constant& mutable_value() ABSL_ATTRIBUTE_LIFETIME_BOUND { if (!has_value()) { value_.emplace(); } return *value_; } void set_value(absl::optional<Constant> value) { value_ = std::move(value); } void set_value(Constant value) { mutable_value() = std::move(value); } ABSL_MUST_USE_RESULT Constant release_value() { absl::optional<Constant> released; released.swap(value_); return std::move(released).value_or(Constant{}); } private: std::string name_; Type type_ = DynType{}; absl::optional<Constant> value_; }; inline VariableDecl MakeVariableDecl(std::string name, Type type) { VariableDecl variable_decl; variable_decl.set_name(std::move(name)); variable_decl.set_type(std::move(type)); return variable_decl; } inline VariableDecl MakeConstantVariableDecl(std::string name, Type type, Constant value) { VariableDecl variable_decl; variable_decl.set_name(std::move(name)); variable_decl.set_type(std::move(type)); variable_decl.set_value(std::move(value)); return variable_decl; } inline bool operator==(const VariableDecl& lhs, const VariableDecl& rhs) { return lhs.name() == rhs.name() && lhs.type() == rhs.type() && lhs.has_value() == rhs.has_value() && lhs.value() == rhs.value(); } inline bool operator!=(const VariableDecl& lhs, const VariableDecl& rhs) { return !operator==(lhs, rhs); } class OverloadDecl final { public: OverloadDecl() = default; OverloadDecl(const OverloadDecl&) = default; OverloadDecl(OverloadDecl&&) = default; OverloadDecl& operator=(const OverloadDecl&) = default; OverloadDecl& operator=(OverloadDecl&&) = default; ABSL_MUST_USE_RESULT const std::string& id() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return id_; } void set_id(std::string id) { id_ = std::move(id); } void set_id(absl::string_view id) { id_.assign(id.data(), id.size()); } void set_id(const char* id) { set_id(absl::NullSafeStringView(id)); } ABSL_MUST_USE_RESULT std::string release_id() { std::string released; released.swap(id_); return released; } ABSL_MUST_USE_RESULT const std::vector<Type>& args() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return args_; } ABSL_MUST_USE_RESULT std::vector<Type>& mutable_args() ABSL_ATTRIBUTE_LIFETIME_BOUND { return args_; } ABSL_MUST_USE_RESULT std::vector<Type> release_args() { std::vector<Type> released; released.swap(mutable_args()); return released; } ABSL_MUST_USE_RESULT const Type& result() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return result_; } ABSL_MUST_USE_RESULT Type& mutable_result() ABSL_ATTRIBUTE_LIFETIME_BOUND { return result_; } void set_result(Type result) { mutable_result() = std::move(result); } ABSL_MUST_USE_RESULT bool member() const { return member_; } void set_member(bool member) { member_ = member; } absl::flat_hash_set<std::string> GetTypeParams() const; private: std::string id_; std::vector<Type> args_; Type result_ = DynType{}; bool member_ = false; }; inline bool operator==(const OverloadDecl& lhs, const OverloadDecl& rhs) { return lhs.id() == rhs.id() && absl::c_equal(lhs.args(), rhs.args()) && lhs.result() == rhs.result() && lhs.member() == rhs.member(); } inline bool operator!=(const OverloadDecl& lhs, const OverloadDecl& rhs) { return !operator==(lhs, rhs); } template <typename... Args> OverloadDecl MakeOverloadDecl(std::string id, Type result, Args&&... args) { OverloadDecl overload_decl; overload_decl.set_id(std::move(id)); overload_decl.set_result(std::move(result)); overload_decl.set_member(false); auto& mutable_args = overload_decl.mutable_args(); mutable_args.reserve(sizeof...(Args)); (mutable_args.push_back(std::forward<Args>(args)), ...); return overload_decl; } template <typename... Args> OverloadDecl MakeMemberOverloadDecl(std::string id, Type result, Args&&... args) { OverloadDecl overload_decl; overload_decl.set_id(std::move(id)); overload_decl.set_result(std::move(result)); overload_decl.set_member(true); auto& mutable_args = overload_decl.mutable_args(); mutable_args.reserve(sizeof...(Args)); (mutable_args.push_back(std::forward<Args>(args)), ...); return overload_decl; } struct OverloadDeclHash { using is_transparent = void; size_t operator()(const OverloadDecl& overload_decl) const { return (*this)(overload_decl.id()); } size_t operator()(absl::string_view id) const { return absl::HashOf(id); } }; struct OverloadDeclEqualTo { using is_transparent = void; bool operator()(const OverloadDecl& lhs, const OverloadDecl& rhs) const { return (*this)(lhs.id(), rhs.id()); } bool operator()(const OverloadDecl& lhs, absl::string_view rhs) const { return (*this)(lhs.id(), rhs); } bool operator()(absl::string_view lhs, const OverloadDecl& rhs) const { return (*this)(lhs, rhs.id()); } bool operator()(absl::string_view lhs, absl::string_view rhs) const { return lhs == rhs; } }; using OverloadDeclHashSet = absl::flat_hash_set<OverloadDecl, OverloadDeclHash, OverloadDeclEqualTo>; template <typename... Overloads> absl::StatusOr<FunctionDecl> MakeFunctionDecl(std::string name, Overloads&&... overloads); class FunctionDecl final { public: FunctionDecl() = default; FunctionDecl(const FunctionDecl&) = default; FunctionDecl(FunctionDecl&&) = default; FunctionDecl& operator=(const FunctionDecl&) = default; FunctionDecl& operator=(FunctionDecl&&) = default; ABSL_MUST_USE_RESULT const std::string& name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return name_; } void set_name(std::string name) { name_ = std::move(name); } void set_name(absl::string_view name) { name_.assign(name.data(), name.size()); } void set_name(const char* name) { set_name(absl::NullSafeStringView(name)); } ABSL_MUST_USE_RESULT std::string release_name() { std::string released; released.swap(name_); return released; } absl::Status AddOverload(const OverloadDecl& overload) { absl::Status status; AddOverloadImpl(overload, status); return status; } absl::Status AddOverload(OverloadDecl&& overload) { absl::Status status; AddOverloadImpl(std::move(overload), status); return status; } ABSL_MUST_USE_RESULT const OverloadDeclHashSet& overloads() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return overloads_; } ABSL_MUST_USE_RESULT OverloadDeclHashSet release_overloads() { OverloadDeclHashSet released; released.swap(overloads_); return released; } private: template <typename... Overloads> friend absl::StatusOr<FunctionDecl> MakeFunctionDecl( std::string name, Overloads&&... overloads); void AddOverloadImpl(const OverloadDecl& overload, absl::Status& status); void AddOverloadImpl(OverloadDecl&& overload, absl::Status& status); std::string name_; OverloadDeclHashSet overloads_; }; inline bool operator==(const FunctionDecl& lhs, const FunctionDecl& rhs) { return lhs.name() == rhs.name() && absl::c_equal(lhs.overloads(), rhs.overloads()); } inline bool operator!=(const FunctionDecl& lhs, const FunctionDecl& rhs) { return !operator==(lhs, rhs); } template <typename... Overloads> absl::StatusOr<FunctionDecl> MakeFunctionDecl(std::string name, Overloads&&... overloads) { FunctionDecl function_decl; function_decl.set_name(std::move(name)); function_decl.overloads_.reserve(sizeof...(Overloads)); absl::Status status; (function_decl.AddOverloadImpl(std::forward<Overloads>(overloads), status), ...); CEL_RETURN_IF_ERROR(status); return function_decl; } namespace common_internal { bool TypeIsAssignable(TypeView to, TypeView from); } } #endif #include "common/decl.h" #include <cstddef> #include <string> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "common/casting.h" #include "common/type.h" #include "common/type_kind.h" namespace cel { namespace common_internal { bool TypeIsAssignable(TypeView to, TypeView from) { if (to == from) { return true; } const auto to_kind = to.kind(); if (to_kind == TypeKind::kDyn) { return true; } switch (to_kind) { case TypeKind::kBoolWrapper: return TypeIsAssignable(NullTypeView{}, from) || TypeIsAssignable(BoolTypeView{}, from); case TypeKind::kIntWrapper: return TypeIsAssignable(NullTypeView{}, from) || TypeIsAssignable(IntTypeView{}, from); case TypeKind::kUintWrapper: return TypeIsAssignable(NullTypeView{}, from) || TypeIsAssignable(UintTypeView{}, from); case TypeKind::kDoubleWrapper: return TypeIsAssignable(NullTypeView{}, from) || TypeIsAssignable(DoubleTypeView{}, from); case TypeKind::kBytesWrapper: return TypeIsAssignable(NullTypeView{}, from) || TypeIsAssignable(BytesTypeView{}, from); case TypeKind::kStringWrapper: return TypeIsAssignable(NullTypeView{}, from) || TypeIsAssignable(StringTypeView{}, from); default: break; } const auto from_kind = from.kind(); if (to_kind != from_kind || to.name() != from.name()) { return false; } const auto& to_params = to.parameters(); const auto& from_params = from.parameters(); const auto params_size = to_params.size(); if (params_size != from_params.size()) { return false; } for (size_t i = 0; i < params_size; ++i) { if (!TypeIsAssignable(to_params[i], from_params[i])) { return false; } } return true; } } namespace { bool SignaturesOverlap(const OverloadDecl& lhs, const OverloadDecl& rhs) { if (lhs.member() != rhs.member()) { return false; } const auto& lhs_args = lhs.args(); const auto& rhs_args = rhs.args(); const auto args_size = lhs_args.size(); if (args_size != rhs_args.size()) { return false; } bool args_overlap = true; for (size_t i = 0; i < args_size; ++i) { args_overlap = args_overlap && (common_internal::TypeIsAssignable(lhs_args[i], rhs_args[i]) || common_internal::TypeIsAssignable(rhs_args[i], lhs_args[i])); } return args_overlap; } template <typename Overload> void AddOverloadInternal(OverloadDeclHashSet& overloads, Overload&& overload, absl::Status& status) { if (!status.ok()) { return; } if (auto it = overloads.find(overload.id()); it != overloads.end()) { status = absl::AlreadyExistsError( absl::StrCat("overload already exists: ", overload.id())); return; } for (const auto& existing : overloads) { if (SignaturesOverlap(overload, existing)) { status = absl::InvalidArgumentError( absl::StrCat("overload signature collision: ", existing.id(), " collides with ", overload.id())); return; } } const auto inserted = overloads.insert(std::forward<Overload>(overload)).second; ABSL_DCHECK(inserted); } void CollectTypeParams(absl::flat_hash_set<std::string>& type_params, TypeView type) { const auto kind = type.kind(); switch (kind) { case TypeKind::kList: { const auto& list_type = cel::Cast<ListTypeView>(type); CollectTypeParams(type_params, list_type.element()); } break; case TypeKind::kMap: { const auto& map_type = cel::Cast<MapTypeView>(type); CollectTypeParams(type_params, map_type.key()); CollectTypeParams(type_params, map_type.value()); } break; case TypeKind::kOpaque: { const auto& opaque_type = cel::Cast<OpaqueTypeView>(type); for (const auto& param : opaque_type.parameters()) { CollectTypeParams(type_params, param); } } break; case TypeKind::kFunction: { const auto& function_type = cel::Cast<FunctionTypeView>(type); CollectTypeParams(type_params, function_type.result()); for (const auto& arg : function_type.args()) { CollectTypeParams(type_params, arg); } } break; case TypeKind::kTypeParam: type_params.emplace(cel::Cast<TypeParamTypeView>(type).name()); break; default: break; } } } absl::flat_hash_set<std::string> OverloadDecl::GetTypeParams() const { absl::flat_hash_set<std::string> type_params; CollectTypeParams(type_params, result()); for (const auto& arg : args()) { CollectTypeParams(type_params, arg); } return type_params; } void FunctionDecl::AddOverloadImpl(const OverloadDecl& overload, absl::Status& status) { AddOverloadInternal(overloads_, overload, status); } void FunctionDecl::AddOverloadImpl(OverloadDecl&& overload, absl::Status& status) { AddOverloadInternal(overloads_, std::move(overload), status); } }
#include "common/decl.h" #include "absl/status/status.h" #include "common/constant.h" #include "common/memory.h" #include "common/type.h" #include "internal/testing.h" namespace cel { namespace { using testing::ElementsAre; using testing::IsEmpty; using testing::UnorderedElementsAre; using cel::internal::StatusIs; TEST(VariableDecl, Name) { VariableDecl variable_decl; EXPECT_THAT(variable_decl.name(), IsEmpty()); variable_decl.set_name("foo"); EXPECT_EQ(variable_decl.name(), "foo"); EXPECT_EQ(variable_decl.release_name(), "foo"); EXPECT_THAT(variable_decl.name(), IsEmpty()); } TEST(VariableDecl, Type) { VariableDecl variable_decl; EXPECT_EQ(variable_decl.type(), DynType{}); variable_decl.set_type(StringType{}); EXPECT_EQ(variable_decl.type(), StringType{}); } TEST(VariableDecl, Value) { VariableDecl variable_decl; EXPECT_FALSE(variable_decl.has_value()); EXPECT_EQ(variable_decl.value(), Constant{}); Constant value; value.set_bool_value(true); variable_decl.set_value(value); EXPECT_TRUE(variable_decl.has_value()); EXPECT_EQ(variable_decl.value(), value); EXPECT_EQ(variable_decl.release_value(), value); EXPECT_EQ(variable_decl.value(), Constant{}); } Constant MakeBoolConstant(bool value) { Constant constant; constant.set_bool_value(value); return constant; } TEST(VariableDecl, Equality) { VariableDecl variable_decl; EXPECT_EQ(variable_decl, VariableDecl{}); variable_decl.mutable_value().set_bool_value(true); EXPECT_NE(variable_decl, VariableDecl{}); EXPECT_EQ(MakeVariableDecl("foo", StringType{}), MakeVariableDecl("foo", StringType{})); EXPECT_EQ(MakeVariableDecl("foo", StringType{}), MakeVariableDecl("foo", StringType{})); EXPECT_EQ( MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true)), MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true))); EXPECT_EQ( MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true)), MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true))); } TEST(OverloadDecl, Id) { OverloadDecl overload_decl; EXPECT_THAT(overload_decl.id(), IsEmpty()); overload_decl.set_id("foo"); EXPECT_EQ(overload_decl.id(), "foo"); EXPECT_EQ(overload_decl.release_id(), "foo"); EXPECT_THAT(overload_decl.id(), IsEmpty()); } TEST(OverloadDecl, Result) { OverloadDecl overload_decl; EXPECT_EQ(overload_decl.result(), DynType{}); overload_decl.set_result(StringType{}); EXPECT_EQ(overload_decl.result(), StringType{}); } TEST(OverloadDecl, Args) { OverloadDecl overload_decl; EXPECT_THAT(overload_decl.args(), IsEmpty()); overload_decl.mutable_args().push_back(StringType{}); EXPECT_THAT(overload_decl.args(), ElementsAre(StringType{})); EXPECT_THAT(overload_decl.release_args(), ElementsAre(StringType{})); EXPECT_THAT(overload_decl.args(), IsEmpty()); } TEST(OverloadDecl, Member) { OverloadDecl overload_decl; EXPECT_FALSE(overload_decl.member()); overload_decl.set_member(true); EXPECT_TRUE(overload_decl.member()); } TEST(OverloadDecl, Equality) { OverloadDecl overload_decl; EXPECT_EQ(overload_decl, OverloadDecl{}); overload_decl.set_member(true); EXPECT_NE(overload_decl, OverloadDecl{}); } TEST(OverloadDecl, GetTypeParams) { auto memory_manager = MemoryManagerRef::ReferenceCounting(); auto overload_decl = MakeOverloadDecl( "foo", ListType(memory_manager, TypeParamType(memory_manager, "A")), MapType(memory_manager, TypeParamType(memory_manager, "B"), TypeParamType(memory_manager, "C")), OpaqueType(memory_manager, "bar", {FunctionType(memory_manager, TypeParamType(memory_manager, "D"), {})})); EXPECT_THAT(overload_decl.GetTypeParams(), UnorderedElementsAre("A", "B", "C", "D")); } TEST(FunctionDecl, Name) { FunctionDecl function_decl; EXPECT_THAT(function_decl.name(), IsEmpty()); function_decl.set_name("foo"); EXPECT_EQ(function_decl.name(), "foo"); EXPECT_EQ(function_decl.release_name(), "foo"); EXPECT_THAT(function_decl.name(), IsEmpty()); } TEST(FunctionDecl, Overloads) { ASSERT_OK_AND_ASSIGN( auto function_decl, MakeFunctionDecl( "hello", MakeOverloadDecl("foo", StringType{}, StringType{}), MakeMemberOverloadDecl("bar", StringType{}, StringType{}))); EXPECT_THAT(function_decl.AddOverload( MakeOverloadDecl("baz", DynType{}, StringType{})), StatusIs(absl::StatusCode::kInvalidArgument)); } using common_internal::TypeIsAssignable; TEST(TypeIsAssignable, BoolWrapper) { EXPECT_TRUE(TypeIsAssignable(BoolWrapperTypeView{}, BoolWrapperTypeView{})); EXPECT_TRUE(TypeIsAssignable(BoolWrapperTypeView{}, NullTypeView{})); EXPECT_TRUE(TypeIsAssignable(BoolWrapperTypeView{}, BoolTypeView{})); EXPECT_FALSE(TypeIsAssignable(BoolWrapperTypeView{}, DurationTypeView{})); } TEST(TypeIsAssignable, IntWrapper) { EXPECT_TRUE(TypeIsAssignable(IntWrapperTypeView{}, IntWrapperTypeView{})); EXPECT_TRUE(TypeIsAssignable(IntWrapperTypeView{}, NullTypeView{})); EXPECT_TRUE(TypeIsAssignable(IntWrapperTypeView{}, IntTypeView{})); EXPECT_FALSE(TypeIsAssignable(IntWrapperTypeView{}, DurationTypeView{})); } TEST(TypeIsAssignable, UintWrapper) { EXPECT_TRUE(TypeIsAssignable(UintWrapperTypeView{}, UintWrapperTypeView{})); EXPECT_TRUE(TypeIsAssignable(UintWrapperTypeView{}, NullTypeView{})); EXPECT_TRUE(TypeIsAssignable(UintWrapperTypeView{}, UintTypeView{})); EXPECT_FALSE(TypeIsAssignable(UintWrapperTypeView{}, DurationTypeView{})); } TEST(TypeIsAssignable, DoubleWrapper) { EXPECT_TRUE( TypeIsAssignable(DoubleWrapperTypeView{}, DoubleWrapperTypeView{})); EXPECT_TRUE(TypeIsAssignable(DoubleWrapperTypeView{}, NullTypeView{})); EXPECT_TRUE(TypeIsAssignable(DoubleWrapperTypeView{}, DoubleTypeView{})); EXPECT_FALSE(TypeIsAssignable(DoubleWrapperTypeView{}, DurationTypeView{})); } TEST(TypeIsAssignable, BytesWrapper) { EXPECT_TRUE(TypeIsAssignable(BytesWrapperTypeView{}, BytesWrapperTypeView{})); EXPECT_TRUE(TypeIsAssignable(BytesWrapperTypeView{}, NullTypeView{})); EXPECT_TRUE(TypeIsAssignable(BytesWrapperTypeView{}, BytesTypeView{})); EXPECT_FALSE(TypeIsAssignable(BytesWrapperTypeView{}, DurationTypeView{})); } TEST(TypeIsAssignable, StringWrapper) { EXPECT_TRUE( TypeIsAssignable(StringWrapperTypeView{}, StringWrapperTypeView{})); EXPECT_TRUE(TypeIsAssignable(StringWrapperTypeView{}, NullTypeView{})); EXPECT_TRUE(TypeIsAssignable(StringWrapperTypeView{}, StringTypeView{})); EXPECT_FALSE(TypeIsAssignable(StringWrapperTypeView{}, DurationTypeView{})); } TEST(TypeIsAssignable, Complex) { auto memory_manager = MemoryManagerRef::ReferenceCounting(); EXPECT_TRUE(TypeIsAssignable(OptionalType(memory_manager, DynTypeView{}), OptionalType(memory_manager, StringTypeView{}))); EXPECT_FALSE( TypeIsAssignable(OptionalType(memory_manager, BoolTypeView{}), OptionalType(memory_manager, StringTypeView{}))); } } }
7
cpp
google/cel-cpp
type_factory
null
null
#ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPE_FACTORY_H_ #define THIRD_PARTY_CEL_CPP_COMMON_TYPE_FACTORY_H_ #include "absl/strings/string_view.h" #include "common/memory.h" #include "common/sized_input_view.h" #include "common/type.h" namespace cel { namespace common_internal { class PiecewiseValueManager; } class TypeFactory { public: virtual ~TypeFactory() = default; virtual MemoryManagerRef GetMemoryManager() const = 0; ListType CreateListType(TypeView element); MapType CreateMapType(TypeView key, TypeView value); StructType CreateStructType(absl::string_view name); OpaqueType CreateOpaqueType(absl::string_view name, const SizedInputView<TypeView>& parameters); OptionalType CreateOptionalType(TypeView parameter); ListTypeView GetDynListType(); MapTypeView GetDynDynMapType(); MapTypeView GetStringDynMapType(); OptionalTypeView GetDynOptionalType(); NullType GetNullType() { return NullType{}; } ErrorType GetErrorType() { return ErrorType{}; } DynType GetDynType() { return DynType{}; } AnyType GetAnyType() { return AnyType{}; } BoolType GetBoolType() { return BoolType{}; } IntType GetIntType() { return IntType{}; } UintType GetUintType() { return UintType{}; } DoubleType GetDoubleType() { return DoubleType{}; } StringType GetStringType() { return StringType{}; } BytesType GetBytesType() { return BytesType{}; } DurationType GetDurationType() { return DurationType{}; } TimestampType GetTimestampType() { return TimestampType{}; } TypeType GetTypeType() { return TypeType{}; } UnknownType GetUnknownType() { return UnknownType{}; } BoolWrapperType GetBoolWrapperType() { return BoolWrapperType{}; } BytesWrapperType GetBytesWrapperType() { return BytesWrapperType{}; } DoubleWrapperType GetDoubleWrapperType() { return DoubleWrapperType{}; } IntWrapperType GetIntWrapperType() { return IntWrapperType{}; } StringWrapperType GetStringWrapperType() { return StringWrapperType{}; } UintWrapperType GetUintWrapperType() { return UintWrapperType{}; } Type GetJsonValueType() { return DynType{}; } ListType GetJsonListType() { return ListType(GetDynListType()); } MapType GetJsonMapType() { return MapType(GetStringDynMapType()); } protected: friend class common_internal::PiecewiseValueManager; virtual ListType CreateListTypeImpl(TypeView element) = 0; virtual MapType CreateMapTypeImpl(TypeView key, TypeView value) = 0; virtual StructType CreateStructTypeImpl(absl::string_view name) = 0; virtual OpaqueType CreateOpaqueTypeImpl( absl::string_view name, const SizedInputView<TypeView>& parameters) = 0; }; } #endif #include "common/type_factory.h" #include "absl/base/attributes.h" #include "absl/log/absl_check.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/sized_input_view.h" #include "common/type.h" #include "common/type_kind.h" #include "common/types/type_cache.h" #include "internal/names.h" namespace cel { namespace { using common_internal::ListTypeCacheMap; using common_internal::MapTypeCacheMap; using common_internal::OpaqueTypeCacheMap; using common_internal::ProcessLocalTypeCache; using common_internal::StructTypeCacheMap; bool IsValidMapKeyType(TypeView type) { switch (type.kind()) { case TypeKind::kDyn: ABSL_FALLTHROUGH_INTENDED; case TypeKind::kError: ABSL_FALLTHROUGH_INTENDED; case TypeKind::kBool: ABSL_FALLTHROUGH_INTENDED; case TypeKind::kInt: ABSL_FALLTHROUGH_INTENDED; case TypeKind::kUint: ABSL_FALLTHROUGH_INTENDED; case TypeKind::kString: return true; default: return false; } } } ListType TypeFactory::CreateListType(TypeView element) { if (auto list_type = ProcessLocalTypeCache::Get()->FindListType(element); list_type.has_value()) { return ListType(*list_type); } return CreateListTypeImpl(element); } MapType TypeFactory::CreateMapType(TypeView key, TypeView value) { ABSL_DCHECK(IsValidMapKeyType(key)) << key; if (auto map_type = ProcessLocalTypeCache::Get()->FindMapType(key, value); map_type.has_value()) { return MapType(*map_type); } return CreateMapTypeImpl(key, value); } StructType TypeFactory::CreateStructType(absl::string_view name) { ABSL_DCHECK(internal::IsValidRelativeName(name)) << name; return CreateStructTypeImpl(name); } OpaqueType TypeFactory::CreateOpaqueType( absl::string_view name, const SizedInputView<TypeView>& parameters) { ABSL_DCHECK(internal::IsValidRelativeName(name)) << name; if (auto opaque_type = ProcessLocalTypeCache::Get()->FindOpaqueType(name, parameters); opaque_type.has_value()) { return OpaqueType(*opaque_type); } return CreateOpaqueTypeImpl(name, parameters); } OptionalType TypeFactory::CreateOptionalType(TypeView parameter) { return Cast<OptionalType>(CreateOpaqueType(OptionalType::kName, {parameter})); } ListTypeView TypeFactory::GetDynListType() { return ProcessLocalTypeCache::Get()->GetDynListType(); } MapTypeView TypeFactory::GetDynDynMapType() { return ProcessLocalTypeCache::Get()->GetDynDynMapType(); } MapTypeView TypeFactory::GetStringDynMapType() { return ProcessLocalTypeCache::Get()->GetStringDynMapType(); } OptionalTypeView TypeFactory::GetDynOptionalType() { return ProcessLocalTypeCache::Get()->GetDynOptionalType(); } }
#include "common/type_factory.h" #include <ostream> #include <sstream> #include <string> #include <tuple> #include "absl/types/optional.h" #include "common/memory.h" #include "common/memory_testing.h" #include "common/type.h" #include "common/type_introspector.h" #include "common/type_manager.h" #include "common/types/type_cache.h" #include "internal/testing.h" namespace cel { namespace { using common_internal::ProcessLocalTypeCache; using testing::_; using testing::Eq; using testing::Ne; using testing::TestParamInfo; using testing::TestWithParam; enum class ThreadSafety { kCompatible, kSafe, }; std::ostream& operator<<(std::ostream& out, ThreadSafety thread_safety) { switch (thread_safety) { case ThreadSafety::kCompatible: return out << "THREAD_SAFE"; case ThreadSafety::kSafe: return out << "THREAD_COMPATIBLE"; } } class TypeFactoryTest : public common_internal::ThreadCompatibleMemoryTest<ThreadSafety> { public: void SetUp() override { ThreadCompatibleMemoryTest::SetUp(); switch (thread_safety()) { case ThreadSafety::kCompatible: type_manager_ = NewThreadCompatibleTypeManager( memory_manager(), NewThreadCompatibleTypeIntrospector(memory_manager())); break; case ThreadSafety::kSafe: type_manager_ = NewThreadSafeTypeManager( memory_manager(), NewThreadSafeTypeIntrospector(memory_manager())); break; } } void TearDown() override { Finish(); } void Finish() { type_manager_.reset(); ThreadCompatibleMemoryTest::Finish(); } TypeFactory& type_factory() const { return **type_manager_; } ThreadSafety thread_safety() const { return std::get<1>(GetParam()); } static std::string ToString( TestParamInfo<std::tuple<MemoryManagement, ThreadSafety>> param) { std::ostringstream out; out << std::get<0>(param.param) << "_" << std::get<1>(param.param); return out.str(); } private: absl::optional<Shared<TypeManager>> type_manager_; }; TEST_P(TypeFactoryTest, ListType) { auto list_type1 = type_factory().CreateListType(StringType()); EXPECT_THAT(type_factory().CreateListType(StringType()), Eq(list_type1)); EXPECT_THAT(type_factory().CreateListType(BytesType()), Ne(list_type1)); auto struct_type1 = type_factory().CreateStructType("test.Struct1"); auto struct_type2 = type_factory().CreateStructType("test.Struct2"); auto list_type2 = type_factory().CreateListType(struct_type1); EXPECT_THAT(type_factory().CreateListType(struct_type1), Eq(list_type2)); EXPECT_THAT(type_factory().CreateListType(struct_type2), Ne(list_type2)); EXPECT_EQ(type_factory().GetDynListType(), ProcessLocalTypeCache::Get()->GetDynListType()); } TEST_P(TypeFactoryTest, MapType) { auto map_type1 = type_factory().CreateMapType(StringType(), BytesType()); EXPECT_THAT(type_factory().CreateMapType(StringType(), BytesType()), Eq(map_type1)); EXPECT_THAT(type_factory().CreateMapType(StringType(), StringType()), Ne(map_type1)); auto struct_type1 = type_factory().CreateStructType("test.Struct1"); auto struct_type2 = type_factory().CreateStructType("test.Struct2"); auto map_type2 = type_factory().CreateMapType(StringType(), struct_type1); EXPECT_THAT(type_factory().CreateMapType(StringType(), struct_type1), Eq(map_type2)); EXPECT_THAT(type_factory().CreateMapType(StringType(), struct_type2), Ne(map_type2)); EXPECT_EQ(type_factory().GetDynDynMapType(), ProcessLocalTypeCache::Get()->GetDynDynMapType()); EXPECT_EQ(type_factory().GetStringDynMapType(), ProcessLocalTypeCache::Get()->GetStringDynMapType()); } TEST_P(TypeFactoryTest, MapTypeInvalidKeyType) { EXPECT_DEBUG_DEATH(type_factory().CreateMapType(DoubleType(), BytesType()), _); } TEST_P(TypeFactoryTest, StructType) { auto struct_type1 = type_factory().CreateStructType("test.Struct1"); EXPECT_THAT(type_factory().CreateStructType("test.Struct1"), Eq(struct_type1)); EXPECT_THAT(type_factory().CreateStructType("test.Struct2"), Ne(struct_type1)); } TEST_P(TypeFactoryTest, StructTypeBadName) { EXPECT_DEBUG_DEATH(type_factory().CreateStructType("test.~"), _); } TEST_P(TypeFactoryTest, OpaqueType) { auto opaque_type1 = type_factory().CreateOpaqueType("test.Struct1", {BytesType()}); EXPECT_THAT(type_factory().CreateOpaqueType("test.Struct1", {BytesType()}), Eq(opaque_type1)); EXPECT_THAT(type_factory().CreateOpaqueType("test.Struct2", {}), Ne(opaque_type1)); } TEST_P(TypeFactoryTest, OpaqueTypeBadName) { EXPECT_DEBUG_DEATH(type_factory().CreateOpaqueType("test.~", {}), _); } TEST_P(TypeFactoryTest, OptionalType) { auto optional_type1 = type_factory().CreateOptionalType(StringType()); EXPECT_THAT(type_factory().CreateOptionalType(StringType()), Eq(optional_type1)); EXPECT_THAT(type_factory().CreateOptionalType(BytesType()), Ne(optional_type1)); auto struct_type1 = type_factory().CreateStructType("test.Struct1"); auto struct_type2 = type_factory().CreateStructType("test.Struct2"); auto optional_type2 = type_factory().CreateOptionalType(struct_type1); EXPECT_THAT(type_factory().CreateOptionalType(struct_type1), Eq(optional_type2)); EXPECT_THAT(type_factory().CreateOptionalType(struct_type2), Ne(optional_type2)); EXPECT_EQ(type_factory().GetDynOptionalType(), ProcessLocalTypeCache::Get()->GetDynOptionalType()); } INSTANTIATE_TEST_SUITE_P( TypeFactoryTest, TypeFactoryTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ::testing::Values(ThreadSafety::kCompatible, ThreadSafety::kSafe)), TypeFactoryTest::ToString); } }
8
cpp
google/cel-cpp
ast_traverse
eval/public/ast_traverse.cc
eval/public/ast_traverse_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_AST_TRAVERSE_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_AST_TRAVERSE_H_ #include "google/api/expr/v1alpha1/syntax.pb.h" #include "eval/public/ast_visitor.h" namespace google::api::expr::runtime { struct TraversalOptions { bool use_comprehension_callbacks; TraversalOptions() : use_comprehension_callbacks(false) {} }; void AstTraverse(const google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info, AstVisitor* visitor, TraversalOptions options = TraversalOptions()); } #endif #include "eval/public/ast_traverse.h" #include <stack> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/log/absl_log.h" #include "absl/types/variant.h" #include "eval/public/ast_visitor.h" #include "eval/public/source_position.h" namespace google::api::expr::runtime { using google::api::expr::v1alpha1::Expr; using google::api::expr::v1alpha1::SourceInfo; using Ident = google::api::expr::v1alpha1::Expr::Ident; using Select = google::api::expr::v1alpha1::Expr::Select; using Call = google::api::expr::v1alpha1::Expr::Call; using CreateList = google::api::expr::v1alpha1::Expr::CreateList; using CreateStruct = google::api::expr::v1alpha1::Expr::CreateStruct; using Comprehension = google::api::expr::v1alpha1::Expr::Comprehension; namespace { struct ArgRecord { const Expr* expr; const SourceInfo* source_info; const Expr* calling_expr; int call_arg; }; struct ComprehensionRecord { const Expr* expr; const SourceInfo* source_info; const Comprehension* comprehension; const Expr* comprehension_expr; ComprehensionArg comprehension_arg; bool use_comprehension_callbacks; }; struct ExprRecord { const Expr* expr; const SourceInfo* source_info; }; using StackRecordKind = absl::variant<ExprRecord, ArgRecord, ComprehensionRecord>; struct StackRecord { public: ABSL_ATTRIBUTE_UNUSED static constexpr int kNotCallArg = -1; static constexpr int kTarget = -2; StackRecord(const Expr* e, const SourceInfo* info) { ExprRecord record; record.expr = e; record.source_info = info; record_variant = record; } StackRecord(const Expr* e, const SourceInfo* info, const Comprehension* comprehension, const Expr* comprehension_expr, ComprehensionArg comprehension_arg, bool use_comprehension_callbacks) { if (use_comprehension_callbacks) { ComprehensionRecord record; record.expr = e; record.source_info = info; record.comprehension = comprehension; record.comprehension_expr = comprehension_expr; record.comprehension_arg = comprehension_arg; record.use_comprehension_callbacks = use_comprehension_callbacks; record_variant = record; return; } ArgRecord record; record.expr = e; record.source_info = info; record.calling_expr = comprehension_expr; record.call_arg = comprehension_arg; record_variant = record; } StackRecord(const Expr* e, const SourceInfo* info, const Expr* call, int argnum) { ArgRecord record; record.expr = e; record.source_info = info; record.calling_expr = call; record.call_arg = argnum; record_variant = record; } StackRecordKind record_variant; bool visited = false; }; struct PreVisitor { void operator()(const ExprRecord& record) { const Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); visitor->PreVisitExpr(expr, &position); switch (expr->expr_kind_case()) { case Expr::kConstExpr: visitor->PreVisitConst(&expr->const_expr(), expr, &position); break; case Expr::kIdentExpr: visitor->PreVisitIdent(&expr->ident_expr(), expr, &position); break; case Expr::kSelectExpr: visitor->PreVisitSelect(&expr->select_expr(), expr, &position); break; case Expr::kCallExpr: visitor->PreVisitCall(&expr->call_expr(), expr, &position); break; case Expr::kListExpr: visitor->PreVisitCreateList(&expr->list_expr(), expr, &position); break; case Expr::kStructExpr: visitor->PreVisitCreateStruct(&expr->struct_expr(), expr, &position); break; case Expr::kComprehensionExpr: visitor->PreVisitComprehension(&expr->comprehension_expr(), expr, &position); break; default: break; } } void operator()(const ArgRecord&) {} void operator()(const ComprehensionRecord& record) { const Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); visitor->PreVisitComprehensionSubexpression( expr, record.comprehension, record.comprehension_arg, &position); } AstVisitor* visitor; }; void PreVisit(const StackRecord& record, AstVisitor* visitor) { absl::visit(PreVisitor{visitor}, record.record_variant); } struct PostVisitor { void operator()(const ExprRecord& record) { const Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); switch (expr->expr_kind_case()) { case Expr::kConstExpr: visitor->PostVisitConst(&expr->const_expr(), expr, &position); break; case Expr::kIdentExpr: visitor->PostVisitIdent(&expr->ident_expr(), expr, &position); break; case Expr::kSelectExpr: visitor->PostVisitSelect(&expr->select_expr(), expr, &position); break; case Expr::kCallExpr: visitor->PostVisitCall(&expr->call_expr(), expr, &position); break; case Expr::kListExpr: visitor->PostVisitCreateList(&expr->list_expr(), expr, &position); break; case Expr::kStructExpr: visitor->PostVisitCreateStruct(&expr->struct_expr(), expr, &position); break; case Expr::kComprehensionExpr: visitor->PostVisitComprehension(&expr->comprehension_expr(), expr, &position); break; default: ABSL_LOG(ERROR) << "Unsupported Expr kind: " << expr->expr_kind_case(); } visitor->PostVisitExpr(expr, &position); } void operator()(const ArgRecord& record) { const Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); if (record.call_arg == StackRecord::kTarget) { visitor->PostVisitTarget(record.calling_expr, &position); } else { visitor->PostVisitArg(record.call_arg, record.calling_expr, &position); } } void operator()(const ComprehensionRecord& record) { const Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); visitor->PostVisitComprehensionSubexpression( expr, record.comprehension, record.comprehension_arg, &position); } AstVisitor* visitor; }; void PostVisit(const StackRecord& record, AstVisitor* visitor) { absl::visit(PostVisitor{visitor}, record.record_variant); } void PushSelectDeps(const Select* select_expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { if (select_expr->has_operand()) { stack->push(StackRecord(&select_expr->operand(), source_info)); } } void PushCallDeps(const Call* call_expr, const Expr* expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { const int arg_size = call_expr->args_size(); for (int i = arg_size - 1; i >= 0; --i) { stack->push(StackRecord(&call_expr->args(i), source_info, expr, i)); } if (call_expr->has_target()) { stack->push(StackRecord(&call_expr->target(), source_info, expr, StackRecord::kTarget)); } } void PushListDeps(const CreateList* list_expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { const auto& elements = list_expr->elements(); for (auto it = elements.rbegin(); it != elements.rend(); ++it) { const auto& element = *it; stack->push(StackRecord(&element, source_info)); } } void PushStructDeps(const CreateStruct* struct_expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { const auto& entries = struct_expr->entries(); for (auto it = entries.rbegin(); it != entries.rend(); ++it) { const auto& entry = *it; if (entry.has_value()) { stack->push(StackRecord(&entry.value(), source_info)); } if (entry.has_map_key()) { stack->push(StackRecord(&entry.map_key(), source_info)); } } } void PushComprehensionDeps(const Comprehension* c, const Expr* expr, const SourceInfo* source_info, std::stack<StackRecord>* stack, bool use_comprehension_callbacks) { StackRecord iter_range(&c->iter_range(), source_info, c, expr, ITER_RANGE, use_comprehension_callbacks); StackRecord accu_init(&c->accu_init(), source_info, c, expr, ACCU_INIT, use_comprehension_callbacks); StackRecord loop_condition(&c->loop_condition(), source_info, c, expr, LOOP_CONDITION, use_comprehension_callbacks); StackRecord loop_step(&c->loop_step(), source_info, c, expr, LOOP_STEP, use_comprehension_callbacks); StackRecord result(&c->result(), source_info, c, expr, RESULT, use_comprehension_callbacks); stack->push(result); stack->push(loop_step); stack->push(loop_condition); stack->push(accu_init); stack->push(iter_range); } struct PushDepsVisitor { void operator()(const ExprRecord& record) { const Expr* expr = record.expr; switch (expr->expr_kind_case()) { case Expr::kSelectExpr: PushSelectDeps(&expr->select_expr(), record.source_info, &stack); break; case Expr::kCallExpr: PushCallDeps(&expr->call_expr(), expr, record.source_info, &stack); break; case Expr::kListExpr: PushListDeps(&expr->list_expr(), record.source_info, &stack); break; case Expr::kStructExpr: PushStructDeps(&expr->struct_expr(), record.source_info, &stack); break; case Expr::kComprehensionExpr: PushComprehensionDeps(&expr->comprehension_expr(), expr, record.source_info, &stack, options.use_comprehension_callbacks); break; default: break; } } void operator()(const ArgRecord& record) { stack.push(StackRecord(record.expr, record.source_info)); } void operator()(const ComprehensionRecord& record) { stack.push(StackRecord(record.expr, record.source_info)); } std::stack<StackRecord>& stack; const TraversalOptions& options; }; void PushDependencies(const StackRecord& record, std::stack<StackRecord>& stack, const TraversalOptions& options) { absl::visit(PushDepsVisitor{stack, options}, record.record_variant); } } void AstTraverse(const Expr* expr, const SourceInfo* source_info, AstVisitor* visitor, TraversalOptions options) { std::stack<StackRecord> stack; stack.push(StackRecord(expr, source_info)); while (!stack.empty()) { StackRecord& record = stack.top(); if (!record.visited) { PreVisit(record, visitor); PushDependencies(record, stack, options); record.visited = true; } else { PostVisit(record, visitor); stack.pop(); } } } }
#include "eval/public/ast_traverse.h" #include "eval/public/ast_visitor.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using google::api::expr::v1alpha1::Constant; using google::api::expr::v1alpha1::Expr; using google::api::expr::v1alpha1::SourceInfo; using testing::_; using Ident = google::api::expr::v1alpha1::Expr::Ident; using Select = google::api::expr::v1alpha1::Expr::Select; using Call = google::api::expr::v1alpha1::Expr::Call; using CreateList = google::api::expr::v1alpha1::Expr::CreateList; using CreateStruct = google::api::expr::v1alpha1::Expr::CreateStruct; using Comprehension = google::api::expr::v1alpha1::Expr::Comprehension; class MockAstVisitor : public AstVisitor { public: MOCK_METHOD(void, PreVisitExpr, (const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitExpr, (const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitConst, (const Constant* const_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitConst, (const Constant* const_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitIdent, (const Ident* ident_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitIdent, (const Ident* ident_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitSelect, (const Select* select_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitSelect, (const Select* select_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitCall, (const Call* call_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitCall, (const Call* call_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitComprehension, (const Comprehension* comprehension_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitComprehension, (const Comprehension* comprehension_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitComprehensionSubexpression, (const Expr* expr, const Comprehension* comprehension_expr, ComprehensionArg comprehension_arg, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitComprehensionSubexpression, (const Expr* expr, const Comprehension* comprehension_expr, ComprehensionArg comprehension_arg, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitTarget, (const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitArg, (int arg_num, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitCreateList, (const CreateList* list_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitCreateList, (const CreateList* list_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitCreateStruct, (const CreateStruct* struct_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitCreateStruct, (const CreateStruct* struct_expr, const Expr* expr, const SourcePosition* position), (override)); }; TEST(AstCrawlerTest, CheckCrawlConstant) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto const_expr = expr.mutable_const_expr(); EXPECT_CALL(handler, PreVisitConst(const_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(const_expr, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlIdent) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto ident_expr = expr.mutable_ident_expr(); EXPECT_CALL(handler, PreVisitIdent(ident_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlSelectNotCrashingPostVisitAbsentOperand) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto select_expr = expr.mutable_select_expr(); EXPECT_CALL(handler, PostVisitSelect(select_expr, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlSelect) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto select_expr = expr.mutable_select_expr(); auto operand = select_expr->mutable_operand(); auto ident_expr = operand->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PostVisitIdent(ident_expr, operand, _)).Times(1); EXPECT_CALL(handler, PostVisitSelect(select_expr, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlCallNoReceiver) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto* call_expr = expr.mutable_call_expr(); Expr* arg0 = call_expr->add_args(); auto* const_expr = arg0->mutable_const_expr(); Expr* arg1 = call_expr->add_args(); auto* ident_expr = arg1->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitTarget(_, _)).Times(0); EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(0, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(1, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(&expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlCallReceiver) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto* call_expr = expr.mutable_call_expr(); Expr* target = call_expr->mutable_target(); auto* target_ident = target->mutable_ident_expr(); Expr* arg0 = call_expr->add_args(); auto* const_expr = arg0->mutable_const_expr(); Expr* arg1 = call_expr->add_args(); auto* ident_expr = arg1->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(target_ident, target, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(target, _)).Times(1); EXPECT_CALL(handler, PostVisitTarget(&expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(0, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(1, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(&expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlComprehension) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto c = expr.mutable_comprehension_expr(); auto iter_range = c->mutable_iter_range(); auto iter_range_expr = iter_range->mutable_const_expr(); auto accu_init = c->mutable_accu_init(); auto accu_init_expr = accu_init->mutable_ident_expr(); auto loop_condition = c->mutable_loop_condition(); auto loop_condition_expr = loop_condition->mutable_const_expr(); auto loop_step = c->mutable_loop_step(); auto loop_step_expr = loop_step->mutable_ident_expr(); auto result = c->mutable_result(); auto result_expr = result->mutable_const_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitComprehension(c, &expr, _)).Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(iter_range, c, ITER_RANGE, _)) .Times(1); EXPECT_CALL(handler, PostVisitConst(iter_range_expr, iter_range, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(iter_range, c, ITER_RANGE, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(accu_init, c, ACCU_INIT, _)) .Times(1); EXPECT_CALL(handler, PostVisitIdent(accu_init_expr, accu_init, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(accu_init, c, ACCU_INIT, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(loop_condition, c, LOOP_CONDITION, _)) .Times(1); EXPECT_CALL(handler, PostVisitConst(loop_condition_expr, loop_condition, _)) .Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(loop_condition, c, LOOP_CONDITION, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(loop_step, c, LOOP_STEP, _)) .Times(1); EXPECT_CALL(handler, PostVisitIdent(loop_step_expr, loop_step, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(loop_step, c, LOOP_STEP, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(result, c, RESULT, _)) .Times(1); EXPECT_CALL(handler, PostVisitConst(result_expr, result, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(result, c, RESULT, _)) .Times(1); EXPECT_CALL(handler, PostVisitComprehension(c, &expr, _)).Times(1); TraversalOptions opts; opts.use_comprehension_callbacks = true; AstTraverse(&expr, &source_info, &handler, opts); } TEST(AstCrawlerTest, CheckCrawlComprehensionLegacyCallbacks) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto c = expr.mutable_comprehension_expr(); auto iter_range = c->mutable_iter_range(); auto iter_range_expr = iter_range->mutable_const_expr(); auto accu_init = c->mutable_accu_init(); auto accu_init_expr = accu_init->mutable_ident_expr(); auto loop_condition = c->mutable_loop_condition(); auto loop_condition_expr = loop_condition->mutable_const_expr(); auto loop_step = c->mutable_loop_step(); auto loop_step_expr = loop_step->mutable_ident_expr(); auto result = c->mutable_result(); auto result_expr = result->mutable_const_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitComprehension(c, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(iter_range_expr, iter_range, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(ITER_RANGE, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(accu_init_expr, accu_init, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(ACCU_INIT, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(loop_condition_expr, loop_condition, _)) .Times(1); EXPECT_CALL(handler, PostVisitArg(LOOP_CONDITION, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(loop_step_expr, loop_step, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(LOOP_STEP, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(result_expr, result, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(RESULT, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehension(c, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCreateList) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto list_expr = expr.mutable_list_expr(); auto arg0 = list_expr->add_elements(); auto const_expr = arg0->mutable_const_expr(); auto arg1 = list_expr->add_elements(); auto ident_expr = arg1->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitCreateList(list_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitCreateList(list_expr, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCreateStruct) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto struct_expr = expr.mutable_struct_expr(); auto entry0 = struct_expr->add_entries(); auto key = entry0->mutable_map_key()->mutable_const_expr(); auto value = entry0->mutable_value()->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitCreateStruct(struct_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(key, &entry0->map_key(), _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(value, &entry0->value(), _)).Times(1); EXPECT_CALL(handler, PostVisitCreateStruct(struct_expr, &expr, _)).Times(1); AstTraverse(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckExprHandlers) { SourceInfo source_info; MockAstVisitor handler; Expr expr; auto struct_expr = expr.mutable_struct_expr(); auto entry0 = struct_expr->add_entries(); entry0->mutable_map_key()->mutable_const_expr(); entry0->mutable_value()->mutable_ident_expr(); EXPECT_CALL(handler, PreVisitExpr(_, _)).Times(3); EXPECT_CALL(handler, PostVisitExpr(_, _)).Times(3); AstTraverse(&expr, &source_info, &handler); } } }
9
cpp
google/cel-cpp
source
common/source.cc
common/source_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_SOURCE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_SOURCE_H_ #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" namespace cel { namespace common_internal { class SourceImpl; } class Source; using SourcePosition = int32_t; struct SourceRange final { SourcePosition begin = -1; SourcePosition end = -1; }; inline bool operator==(const SourceRange& lhs, const SourceRange& rhs) { return lhs.begin == rhs.begin && lhs.end == rhs.end; } inline bool operator!=(const SourceRange& lhs, const SourceRange& rhs) { return !operator==(lhs, rhs); } struct SourceLocation final { int32_t line = -1; int32_t column = -1; }; inline bool operator==(const SourceLocation& lhs, const SourceLocation& rhs) { return lhs.line == rhs.line && lhs.column == rhs.column; } inline bool operator!=(const SourceLocation& lhs, const SourceLocation& rhs) { return !operator==(lhs, rhs); } class SourceContentView final { public: SourceContentView(const SourceContentView&) = default; SourceContentView(SourceContentView&&) = default; SourceContentView& operator=(const SourceContentView&) = default; SourceContentView& operator=(SourceContentView&&) = default; SourcePosition size() const; bool empty() const; char32_t at(SourcePosition position) const; std::string ToString(SourcePosition begin, SourcePosition end) const; std::string ToString(SourcePosition begin) const { return ToString(begin, size()); } std::string ToString() const { return ToString(0); } void AppendToString(std::string& dest) const; private: friend class Source; constexpr SourceContentView() = default; constexpr explicit SourceContentView(absl::Span<const char> view) : view_(view) {} constexpr explicit SourceContentView(absl::Span<const uint8_t> view) : view_(view) {} constexpr explicit SourceContentView(absl::Span<const char16_t> view) : view_(view) {} constexpr explicit SourceContentView(absl::Span<const char32_t> view) : view_(view) {} absl::variant<absl::Span<const char>, absl::Span<const uint8_t>, absl::Span<const char16_t>, absl::Span<const char32_t>> view_; }; class Source { public: using ContentView = SourceContentView; Source(const Source&) = delete; Source(Source&&) = delete; virtual ~Source() = default; Source& operator=(const Source&) = delete; Source& operator=(Source&&) = delete; virtual absl::string_view description() const ABSL_ATTRIBUTE_LIFETIME_BOUND = 0; absl::optional<SourceLocation> GetLocation(SourcePosition position) const; absl::optional<SourcePosition> GetPosition( const SourceLocation& location) const; absl::optional<std::string> Snippet(int32_t line) const; std::string DisplayErrorLocation(SourceLocation location) const; virtual ContentView content() const ABSL_ATTRIBUTE_LIFETIME_BOUND = 0; virtual absl::Span<const SourcePosition> line_offsets() const ABSL_ATTRIBUTE_LIFETIME_BOUND = 0; protected: static constexpr ContentView EmptyContentView() { return ContentView(); } static constexpr ContentView MakeContentView(absl::Span<const char> view) { return ContentView(view); } static constexpr ContentView MakeContentView(absl::Span<const uint8_t> view) { return ContentView(view); } static constexpr ContentView MakeContentView( absl::Span<const char16_t> view) { return ContentView(view); } static constexpr ContentView MakeContentView( absl::Span<const char32_t> view) { return ContentView(view); } private: friend class common_internal::SourceImpl; Source() = default; absl::optional<SourcePosition> FindLinePosition(int32_t line) const; absl::optional<std::pair<int32_t, SourcePosition>> FindLine( SourcePosition position) const; }; using SourcePtr = std::unique_ptr<Source>; absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource( absl::string_view content, std::string description = "<input>"); absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource( const absl::Cord& content, std::string description = "<input>"); } #endif #include "common/source.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/container/inlined_vector.h" #include "absl/functional/overload.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "internal/unicode.h" #include "internal/utf8.h" namespace cel { SourcePosition SourceContentView::size() const { return static_cast<SourcePosition>(absl::visit( absl::Overload( [](absl::Span<const char> view) { return view.size(); }, [](absl::Span<const uint8_t> view) { return view.size(); }, [](absl::Span<const char16_t> view) { return view.size(); }, [](absl::Span<const char32_t> view) { return view.size(); }), view_)); } bool SourceContentView::empty() const { return absl::visit( absl::Overload( [](absl::Span<const char> view) { return view.empty(); }, [](absl::Span<const uint8_t> view) { return view.empty(); }, [](absl::Span<const char16_t> view) { return view.empty(); }, [](absl::Span<const char32_t> view) { return view.empty(); }), view_); } char32_t SourceContentView::at(SourcePosition position) const { ABSL_DCHECK_GE(position, 0); ABSL_DCHECK_LT(position, size()); return absl::visit( absl::Overload( [position = static_cast<size_t>(position)](absl::Span<const char> view) { return static_cast<char32_t>(static_cast<uint8_t>(view[position])); }, [position = static_cast<size_t>(position)](absl::Span<const uint8_t> view) { return static_cast<char32_t>(view[position]); }, [position = static_cast<size_t>(position)](absl::Span<const char16_t> view) { return static_cast<char32_t>(view[position]); }, [position = static_cast<size_t>(position)](absl::Span<const char32_t> view) { return static_cast<char32_t>(view[position]); }), view_); } std::string SourceContentView::ToString(SourcePosition begin, SourcePosition end) const { ABSL_DCHECK_GE(begin, 0); ABSL_DCHECK_LE(end, size()); ABSL_DCHECK_LE(begin, end); return absl::visit( absl::Overload( [begin = static_cast<size_t>(begin), end = static_cast<size_t>(end)](absl::Span<const char> view) { view = view.subspan(begin, end - begin); return std::string(view.data(), view.size()); }, [begin = static_cast<size_t>(begin), end = static_cast<size_t>(end)](absl::Span<const uint8_t> view) { view = view.subspan(begin, end - begin); std::string result; result.reserve(view.size() * 2); for (const auto& code_point : view) { internal::Utf8Encode(result, code_point); } result.shrink_to_fit(); return result; }, [begin = static_cast<size_t>(begin), end = static_cast<size_t>(end)](absl::Span<const char16_t> view) { view = view.subspan(begin, end - begin); std::string result; result.reserve(view.size() * 3); for (const auto& code_point : view) { internal::Utf8Encode(result, code_point); } result.shrink_to_fit(); return result; }, [begin = static_cast<size_t>(begin), end = static_cast<size_t>(end)](absl::Span<const char32_t> view) { view = view.subspan(begin, end - begin); std::string result; result.reserve(view.size() * 4); for (const auto& code_point : view) { internal::Utf8Encode(result, code_point); } result.shrink_to_fit(); return result; }), view_); } void SourceContentView::AppendToString(std::string& dest) const { absl::visit(absl::Overload( [&dest](absl::Span<const char> view) { dest.append(view.data(), view.size()); }, [&dest](absl::Span<const uint8_t> view) { for (const auto& code_point : view) { internal::Utf8Encode(dest, code_point); } }, [&dest](absl::Span<const char16_t> view) { for (const auto& code_point : view) { internal::Utf8Encode(dest, code_point); } }, [&dest](absl::Span<const char32_t> view) { for (const auto& code_point : view) { internal::Utf8Encode(dest, code_point); } }), view_); } namespace common_internal { class SourceImpl : public Source { public: SourceImpl(std::string description, absl::InlinedVector<SourcePosition, 1> line_offsets) : description_(std::move(description)), line_offsets_(std::move(line_offsets)) {} absl::string_view description() const final { return description_; } absl::Span<const SourcePosition> line_offsets() const final { return absl::MakeConstSpan(line_offsets_); } private: const std::string description_; const absl::InlinedVector<SourcePosition, 1> line_offsets_; }; namespace { class AsciiSource final : public SourceImpl { public: AsciiSource(std::string description, absl::InlinedVector<SourcePosition, 1> line_offsets, std::vector<char> text) : SourceImpl(std::move(description), std::move(line_offsets)), text_(std::move(text)) {} ContentView content() const override { return MakeContentView(absl::MakeConstSpan(text_)); } private: const std::vector<char> text_; }; class Latin1Source final : public SourceImpl { public: Latin1Source(std::string description, absl::InlinedVector<SourcePosition, 1> line_offsets, std::vector<uint8_t> text) : SourceImpl(std::move(description), std::move(line_offsets)), text_(std::move(text)) {} ContentView content() const override { return MakeContentView(absl::MakeConstSpan(text_)); } private: const std::vector<uint8_t> text_; }; class BasicPlaneSource final : public SourceImpl { public: BasicPlaneSource(std::string description, absl::InlinedVector<SourcePosition, 1> line_offsets, std::vector<char16_t> text) : SourceImpl(std::move(description), std::move(line_offsets)), text_(std::move(text)) {} ContentView content() const override { return MakeContentView(absl::MakeConstSpan(text_)); } private: const std::vector<char16_t> text_; }; class SupplementalPlaneSource final : public SourceImpl { public: SupplementalPlaneSource(std::string description, absl::InlinedVector<SourcePosition, 1> line_offsets, std::vector<char32_t> text) : SourceImpl(std::move(description), std::move(line_offsets)), text_(std::move(text)) {} ContentView content() const override { return MakeContentView(absl::MakeConstSpan(text_)); } private: const std::vector<char32_t> text_; }; template <typename T> struct SourceTextTraits; template <> struct SourceTextTraits<absl::string_view> { using iterator_type = absl::string_view; static iterator_type Begin(absl::string_view text) { return text; } static void Advance(iterator_type& it, size_t n) { it.remove_prefix(n); } static void AppendTo(std::vector<uint8_t>& out, absl::string_view text, size_t n) { const auto* in = reinterpret_cast<const uint8_t*>(text.data()); out.insert(out.end(), in, in + n); } static std::vector<char> ToVector(absl::string_view in) { std::vector<char> out; out.reserve(in.size()); out.insert(out.end(), in.begin(), in.end()); return out; } }; template <> struct SourceTextTraits<absl::Cord> { using iterator_type = absl::Cord::CharIterator; static iterator_type Begin(const absl::Cord& text) { return text.char_begin(); } static void Advance(iterator_type& it, size_t n) { absl::Cord::Advance(&it, n); } static void AppendTo(std::vector<uint8_t>& out, const absl::Cord& text, size_t n) { auto it = text.char_begin(); while (n > 0) { auto str = absl::Cord::ChunkRemaining(it); size_t to_append = std::min(n, str.size()); const auto* in = reinterpret_cast<const uint8_t*>(str.data()); out.insert(out.end(), in, in + to_append); n -= to_append; absl::Cord::Advance(&it, to_append); } } static std::vector<char> ToVector(const absl::Cord& in) { std::vector<char> out; out.reserve(in.size()); for (const auto& chunk : in.Chunks()) { out.insert(out.end(), chunk.begin(), chunk.end()); } return out; } }; template <typename T> absl::StatusOr<SourcePtr> NewSourceImpl(std::string description, const T& text, const size_t text_size) { if (ABSL_PREDICT_FALSE( text_size > static_cast<size_t>(std::numeric_limits<int32_t>::max()))) { return absl::InvalidArgumentError("expression larger than 2GiB limit"); } using Traits = SourceTextTraits<T>; size_t index = 0; typename Traits::iterator_type it = Traits::Begin(text); SourcePosition offset = 0; char32_t code_point; size_t code_units; std::vector<uint8_t> data8; std::vector<char16_t> data16; std::vector<char32_t> data32; absl::InlinedVector<SourcePosition, 1> line_offsets; while (index < text_size) { std::tie(code_point, code_units) = cel::internal::Utf8Decode(it); if (ABSL_PREDICT_FALSE(code_point == cel::internal::kUnicodeReplacementCharacter && code_units == 1)) { return absl::InvalidArgumentError("cannot parse malformed UTF-8 input"); } if (code_point == '\n') { line_offsets.push_back(offset + 1); } if (code_point <= 0x7f) { Traits::Advance(it, code_units); index += code_units; ++offset; continue; } if (code_point <= 0xff) { data8.reserve(text_size); Traits::AppendTo(data8, text, index); data8.push_back(static_cast<uint8_t>(code_point)); Traits::Advance(it, code_units); index += code_units; ++offset; goto latin1; } if (code_point <= 0xffff) { data16.reserve(text_size); for (size_t offset = 0; offset < index; offset++) { data16.push_back(static_cast<uint8_t>(text[offset])); } data16.push_back(static_cast<char16_t>(code_point)); Traits::Advance(it, code_units); index += code_units; ++offset; goto basic; } data32.reserve(text_size); for (size_t offset = 0; offset < index; offset++) { data32.push_back(static_cast<char32_t>(text[offset])); } data32.push_back(code_point); Traits::Advance(it, code_units); index += code_units; ++offset; goto supplemental; } line_offsets.push_back(offset + 1); return std::make_unique<AsciiSource>( std::move(description), std::move(line_offsets), Traits::ToVector(text)); latin1: while (index < text_size) { std::tie(code_point, code_units) = internal::Utf8Decode(it); if (ABSL_PREDICT_FALSE(code_point == internal::kUnicodeReplacementCharacter && code_units == 1)) { return absl::InvalidArgumentError("cannot parse malformed UTF-8 input"); } if (code_point == '\n') { line_offsets.push_back(offset + 1); } if (code_point <= 0xff) { data8.push_back(static_cast<uint8_t>(code_point)); Traits::Advance(it, code_units); index += code_units; ++offset; continue; } if (code_point <= 0xffff) { data16.reserve(text_size); for (const auto& value : data8) { data16.push_back(value); } std::vector<uint8_t>().swap(data8); data16.push_back(static_cast<char16_t>(code_point)); Traits::Advance(it, code_units); index += code_units; ++offset; goto basic; } data32.reserve(text_size); for (const auto& value : data8) { data32.push_back(value); } std::vector<uint8_t>().swap(data8); data32.push_back(code_point); Traits::Advance(it, code_units); index += code_units; ++offset; goto supplemental; } line_offsets.push_back(offset + 1); return std::make_unique<Latin1Source>( std::move(description), std::move(line_offsets), std::move(data8)); basic: while (index < text_size) { std::tie(code_point, code_units) = internal::Utf8Decode(it); if (ABSL_PREDICT_FALSE(code_point == internal::kUnicodeReplacementCharacter && code_units == 1)) { return absl::InvalidArgumentError("cannot parse malformed UTF-8 input"); } if (code_point == '\n') { line_offsets.push_back(offset + 1); } if (code_point <= 0xffff) { data16.push_back(static_cast<char16_t>(code_point)); Traits::Advance(it, code_units); index += code_units; ++offset; continue; } data32.reserve(text_size); for (const auto& value : data16) { data32.push_back(static_cast<char32_t>(value)); } std::vector<char16_t>().swap(data16); data32.push_back(code_point); Traits::Advance(it, code_units); index += code_units; ++offset; goto supplemental; } line_offsets.push_back(offset + 1); return std::make_unique<BasicPlaneSource>( std::move(description), std::move(line_offsets), std::move(data16)); supplemental: while (index < text_size) { std::tie(code_point, code_units) = internal::Utf8Decode(it); if (ABSL_PREDICT_FALSE(code_point == internal::kUnicodeReplacementCharacter && code_units == 1)) { return absl::InvalidArgumentError("cannot parse malformed UTF-8 input"); } if (code_point == '\n') { line_offsets.push_back(offset + 1); } data32.push_back(code_point); Traits::Advance(it, code_units); index += code_units; ++offset; } line_offsets.push_back(offset + 1); return std::make_unique<SupplementalPlaneSource>( std::move(description), std::move(line_offsets), std::move(data32)); } } } absl::optional<SourceLocation> Source::GetLocation( SourcePosition position) const { if (auto line_and_offset = FindLine(position); ABSL_PREDICT_TRUE(line_and_offset.has_value())) { return SourceLocation{line_and_offset->first, position - line_and_offset->second}; } return absl::nullopt; } absl::optional<SourcePosition> Source::GetPosition( const SourceLocation& location) const { if (ABSL_PREDICT_FALSE(location.line < 1 || location.column < 0)) { return absl::nullopt; } if (auto position = FindLinePosition(location.line); ABSL_PREDICT_TRUE(position.has_value())) { return *position + location.column; } return absl::nullopt; } absl::optional<std::string> Source::Snippet(int32_t line) const { auto content = this->content(); auto start = FindLinePosition(line); if (ABSL_PREDICT_FALSE(!start.has_value() || content.empty())) { return absl::nullopt; } auto end = FindLinePosition(line + 1); if (end.has_value()) { return content.ToString(*start, *end - 1); } return content.ToString(*start); } std::string Source::DisplayErrorLocation(SourceLocation location) const { constexpr char32_t kDot = '.'; constexpr char32_t kHat = '^'; constexpr char32_t kWideDot = 0xff0e; constexpr char32_t kWideHat = 0xff3e; absl::optional<std::string> snippet = Snippet(location.line); if (!snippet || snippet->empty()) { return ""; } *snippet = absl::StrReplaceAll(*snippet, {{"\t", " "}}); absl::string_view snippet_view(*snippet); std::string result; absl::StrAppend(&result, "\n | ", *snippet); absl::StrAppend(&result, "\n | "); std::string index_line; for (int32_t i = 0; i < location.column && !snippet_view.empty(); ++i) { size_t count; std::tie(std::ignore, count) = internal::Utf8Decode(snippet_view); snippet_view.remove_prefix(count); if (count > 1) { internal::Utf8Encode(index_line, kWideDot); } else { internal::Utf8Encode(index_line, kDot); } } size_t count = 0; if (!snippet_view.empty()) { std::tie(std::ignore, count) = internal::Utf8Decode(snippet_view); } if (count > 1) { internal::Utf8Encode(index_line, kWideHat); } else { internal::Utf8Encode(index_line, kHat); } absl::StrAppend(&result, index_line); return result; } absl::optional<SourcePosition> Source::FindLinePosition(int32_t line) const { if (ABSL_PREDICT_FALSE(line < 1)) { return absl::nullopt; } if (line == 1) { return SourcePosition{0}; } const auto line_offsets = this->line_offsets(); if (ABSL_PREDICT_TRUE(line <= static_cast<int32_t>(line_offsets.size()))) { return line_offsets[static_cast<size_t>(line - 2)]; } return absl::nullopt; } absl::optional<std::pair<int32_t, SourcePosition>> Source::FindLine( SourcePosition position) const { if (ABSL_PREDICT_FALSE(position < 0)) { return absl::nullopt; } int32_t line = 1; const auto line_offsets = this->line_offsets(); for (const auto& line_offset : line_offsets) { if (line_offset > position) { break; } ++line; } if (line == 1) { return std::make_pair(line, SourcePosition{0}); } return std::make_pair(line, line_offsets[static_cast<size_t>(line) - 2]); } absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource(absl::string_view content, std::string description) { return common_internal::NewSourceImpl(std::move(description), content, content.size()); } absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource(const absl::Cord& content, std::string description) { return common_internal::NewSourceImpl(std::move(description), content, content.size()); } }
#include "common/source.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "internal/testing.h" namespace cel { namespace { using testing::ElementsAre; using testing::Eq; using testing::Ne; using testing::Optional; TEST(SourceRange, Default) { SourceRange range; EXPECT_EQ(range.begin, -1); EXPECT_EQ(range.end, -1); } TEST(SourceRange, Equality) { EXPECT_THAT((SourceRange{}), (Eq(SourceRange{}))); EXPECT_THAT((SourceRange{0, 1}), (Ne(SourceRange{0, 0}))); } TEST(SourceLocation, Default) { SourceLocation location; EXPECT_EQ(location.line, -1); EXPECT_EQ(location.column, -1); } TEST(SourceLocation, Equality) { EXPECT_THAT((SourceLocation{}), (Eq(SourceLocation{}))); EXPECT_THAT((SourceLocation{1, 1}), (Ne(SourceLocation{1, 0}))); } TEST(StringSource, Description) { ASSERT_OK_AND_ASSIGN( auto source, NewSource("c.d &&\n\t b.c.arg(10) &&\n\t test(10)", "offset-test")); EXPECT_THAT(source->description(), Eq("offset-test")); } TEST(StringSource, Content) { ASSERT_OK_AND_ASSIGN( auto source, NewSource("c.d &&\n\t b.c.arg(10) &&\n\t test(10)", "offset-test")); EXPECT_THAT(source->content().ToString(), Eq("c.d &&\n\t b.c.arg(10) &&\n\t test(10)")); } TEST(StringSource, PositionAndLocation) { ASSERT_OK_AND_ASSIGN( auto source, NewSource("c.d &&\n\t b.c.arg(10) &&\n\t test(10)", "offset-test")); EXPECT_THAT(source->line_offsets(), ElementsAre(7, 24, 35)); auto start = source->GetPosition(SourceLocation{int32_t{1}, int32_t{2}}); auto end = source->GetPosition(SourceLocation{int32_t{3}, int32_t{2}}); ASSERT_TRUE(start.has_value()); ASSERT_TRUE(end.has_value()); EXPECT_THAT(source->GetLocation(*start), Optional(Eq(SourceLocation{int32_t{1}, int32_t{2}}))); EXPECT_THAT(source->GetLocation(*end), Optional(Eq(SourceLocation{int32_t{3}, int32_t{2}}))); EXPECT_THAT(source->GetLocation(-1), Eq(absl::nullopt)); EXPECT_THAT(source->content().ToString(*start, *end), Eq("d &&\n\t b.c.arg(10) &&\n\t ")); EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{0}, int32_t{0}}), Eq(absl::nullopt)); EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{1}, int32_t{-1}}), Eq(absl::nullopt)); EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{4}, int32_t{0}}), Eq(absl::nullopt)); } TEST(StringSource, SnippetSingle) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("hello, world", "one-line-test")); EXPECT_THAT(source->Snippet(1), Optional(Eq("hello, world"))); EXPECT_THAT(source->Snippet(2), Eq(absl::nullopt)); } TEST(StringSource, SnippetMulti) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("hello\nworld\nmy\nbub\n", "four-line-test")); EXPECT_THAT(source->Snippet(0), Eq(absl::nullopt)); EXPECT_THAT(source->Snippet(1), Optional(Eq("hello"))); EXPECT_THAT(source->Snippet(2), Optional(Eq("world"))); EXPECT_THAT(source->Snippet(3), Optional(Eq("my"))); EXPECT_THAT(source->Snippet(4), Optional(Eq("bub"))); EXPECT_THAT(source->Snippet(5), Optional(Eq(""))); EXPECT_THAT(source->Snippet(6), Eq(absl::nullopt)); } TEST(CordSource, Description) { ASSERT_OK_AND_ASSIGN( auto source, NewSource(absl::Cord("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"), "offset-test")); EXPECT_THAT(source->description(), Eq("offset-test")); } TEST(CordSource, Content) { ASSERT_OK_AND_ASSIGN( auto source, NewSource(absl::Cord("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"), "offset-test")); EXPECT_THAT(source->content().ToString(), Eq("c.d &&\n\t b.c.arg(10) &&\n\t test(10)")); } TEST(CordSource, PositionAndLocation) { ASSERT_OK_AND_ASSIGN( auto source, NewSource(absl::Cord("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"), "offset-test")); EXPECT_THAT(source->line_offsets(), ElementsAre(7, 24, 35)); auto start = source->GetPosition(SourceLocation{int32_t{1}, int32_t{2}}); auto end = source->GetPosition(SourceLocation{int32_t{3}, int32_t{2}}); ASSERT_TRUE(start.has_value()); ASSERT_TRUE(end.has_value()); EXPECT_THAT(source->GetLocation(*start), Optional(Eq(SourceLocation{int32_t{1}, int32_t{2}}))); EXPECT_THAT(source->GetLocation(*end), Optional(Eq(SourceLocation{int32_t{3}, int32_t{2}}))); EXPECT_THAT(source->GetLocation(-1), Eq(absl::nullopt)); EXPECT_THAT(source->content().ToString(*start, *end), Eq("d &&\n\t b.c.arg(10) &&\n\t ")); EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{0}, int32_t{0}}), Eq(absl::nullopt)); EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{1}, int32_t{-1}}), Eq(absl::nullopt)); EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{4}, int32_t{0}}), Eq(absl::nullopt)); } TEST(CordSource, SnippetSingle) { ASSERT_OK_AND_ASSIGN(auto source, NewSource(absl::Cord("hello, world"), "one-line-test")); EXPECT_THAT(source->Snippet(1), Optional(Eq("hello, world"))); EXPECT_THAT(source->Snippet(2), Eq(absl::nullopt)); } TEST(CordSource, SnippetMulti) { ASSERT_OK_AND_ASSIGN( auto source, NewSource(absl::Cord("hello\nworld\nmy\nbub\n"), "four-line-test")); EXPECT_THAT(source->Snippet(0), Eq(absl::nullopt)); EXPECT_THAT(source->Snippet(1), Optional(Eq("hello"))); EXPECT_THAT(source->Snippet(2), Optional(Eq("world"))); EXPECT_THAT(source->Snippet(3), Optional(Eq("my"))); EXPECT_THAT(source->Snippet(4), Optional(Eq("bub"))); EXPECT_THAT(source->Snippet(5), Optional(Eq(""))); EXPECT_THAT(source->Snippet(6), Eq(absl::nullopt)); } TEST(Source, DisplayErrorLocationBasic) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello' +\n 'world'")); SourceLocation location{2, 3}; EXPECT_EQ(source->DisplayErrorLocation(location), "\n | 'world'" "\n | ...^"); } TEST(Source, DisplayErrorLocationOutOfRange) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello world!'")); SourceLocation location{3, 3}; EXPECT_EQ(source->DisplayErrorLocation(location), ""); } TEST(Source, DisplayErrorLocationTabsShortened) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello' +\n\t\t'world!'")); SourceLocation location{2, 4}; EXPECT_EQ(source->DisplayErrorLocation(location), "\n | 'world!'" "\n | ....^"); } TEST(Source, DisplayErrorLocationFullWidth) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello'")); SourceLocation location{1, 2}; EXPECT_EQ(source->DisplayErrorLocation(location), "\n | 'Hello'" "\n | ..^"); } } }
10
cpp
google/cel-cpp
memory
common/memory.cc
common/memory_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_MEMORY_H_ #define THIRD_PARTY_CEL_CPP_COMMON_MEMORY_H_ #include <cstddef> #include <cstdint> #include <memory> #include <ostream> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/numeric/bits.h" #include "common/allocator.h" #include "common/arena.h" #include "common/data.h" #include "common/internal/metadata.h" #include "common/internal/reference_count.h" #include "common/native_type.h" #include "common/reference_count.h" #include "internal/exceptions.h" #include "internal/to_address.h" #include "google/protobuf/arena.h" namespace cel { using internal::to_address; enum class MemoryManagement { kPooling = 1, kReferenceCounting, }; std::ostream& operator<<(std::ostream& out, MemoryManagement memory_management); class Data; class ABSL_ATTRIBUTE_TRIVIAL_ABI [[nodiscard]] Owner; class Borrower; template <typename T> class ABSL_ATTRIBUTE_TRIVIAL_ABI Shared; template <typename T> class ABSL_ATTRIBUTE_TRIVIAL_ABI SharedView; template <typename T> class ABSL_ATTRIBUTE_TRIVIAL_ABI [[nodiscard]] Unique; template <typename T> struct EnableSharedFromThis; class MemoryManager; class ReferenceCountingMemoryManager; class PoolingMemoryManager; namespace common_internal { absl::Nullable<const ReferenceCount*> OwnerRelease(Owner& owner) noexcept; template <typename T> T* GetPointer(const Shared<T>& shared); template <typename T> const ReferenceCount* GetReferenceCount(const Shared<T>& shared); template <typename T> Shared<T> MakeShared(AdoptRef, T* value, const ReferenceCount* refcount); template <typename T> Shared<T> MakeShared(T* value, const ReferenceCount* refcount); template <typename T> T* GetPointer(SharedView<T> shared); template <typename T> const ReferenceCount* GetReferenceCount(SharedView<T> shared); template <typename T> SharedView<T> MakeSharedView(T* value, const ReferenceCount* refcount); } template <typename To, typename From> Shared<To> StaticCast(const Shared<From>& from); template <typename To, typename From> Shared<To> StaticCast(Shared<From>&& from); template <typename To, typename From> SharedView<To> StaticCast(SharedView<From> from); class ABSL_ATTRIBUTE_TRIVIAL_ABI [[nodiscard]] Owner final { private: static constexpr uintptr_t kNone = common_internal::kMetadataOwnerNone; static constexpr uintptr_t kReferenceCountBit = common_internal::kMetadataOwnerReferenceCountBit; static constexpr uintptr_t kArenaBit = common_internal::kMetadataOwnerArenaBit; static constexpr uintptr_t kBits = common_internal::kMetadataOwnerBits; static constexpr uintptr_t kPointerMask = common_internal::kMetadataOwnerPointerMask; public: static Owner None() noexcept { return Owner(); } static Owner Allocator(Allocator<> allocator) noexcept { auto* arena = allocator.arena(); return arena != nullptr ? Arena(arena) : None(); } static Owner Arena(absl::Nonnull<google::protobuf::Arena*> arena ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ABSL_DCHECK(arena != nullptr); return Owner(reinterpret_cast<uintptr_t>(arena) | kArenaBit); } static Owner Arena(std::nullptr_t) = delete; static Owner ReferenceCount( absl::Nonnull<const ReferenceCount*> reference_count ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ABSL_DCHECK(reference_count != nullptr); common_internal::StrongRef(*reference_count); return Owner(reinterpret_cast<uintptr_t>(reference_count) | kReferenceCountBit); } static Owner ReferenceCount(std::nullptr_t) = delete; Owner() = default; Owner(const Owner& other) noexcept : Owner(CopyFrom(other.ptr_)) {} Owner(Owner&& other) noexcept : Owner(MoveFrom(other.ptr_)) {} explicit Owner(Borrower borrower) noexcept; ~Owner() { Destroy(ptr_); } Owner& operator=(const Owner& other) noexcept { if (ptr_ != other.ptr_) { Destroy(ptr_); ptr_ = CopyFrom(other.ptr_); } return *this; } Owner& operator=(Owner&& other) noexcept { if (ABSL_PREDICT_TRUE(this != &other)) { Destroy(ptr_); ptr_ = MoveFrom(other.ptr_); } return *this; } explicit operator bool() const noexcept { return !IsNone(ptr_); } absl::Nullable<google::protobuf::Arena*> arena() const noexcept { return (ptr_ & Owner::kBits) == Owner::kArenaBit ? reinterpret_cast<google::protobuf::Arena*>(ptr_ & Owner::kPointerMask) : nullptr; } friend bool operator==(const Owner& lhs, const Owner& rhs) noexcept { return lhs.ptr_ == rhs.ptr_; } private: friend class Borrower; friend absl::Nullable<const common_internal::ReferenceCount*> common_internal::OwnerRelease(Owner& owner) noexcept; constexpr explicit Owner(uintptr_t ptr) noexcept : ptr_(ptr) {} static constexpr bool IsNone(uintptr_t ptr) noexcept { return ptr == kNone; } static constexpr bool IsArena(uintptr_t ptr) noexcept { return (ptr & kArenaBit) != kNone; } static constexpr bool IsReferenceCount(uintptr_t ptr) noexcept { return (ptr & kReferenceCountBit) != kNone; } ABSL_ATTRIBUTE_RETURNS_NONNULL static absl::Nonnull<google::protobuf::Arena*> AsArena(uintptr_t ptr) noexcept { ABSL_ASSERT(IsArena(ptr)); return reinterpret_cast<google::protobuf::Arena*>(ptr & kPointerMask); } ABSL_ATTRIBUTE_RETURNS_NONNULL static absl::Nonnull<const common_internal::ReferenceCount*> AsReferenceCount( uintptr_t ptr) noexcept { ABSL_ASSERT(IsReferenceCount(ptr)); return reinterpret_cast<const common_internal::ReferenceCount*>( ptr & kPointerMask); } static uintptr_t CopyFrom(uintptr_t other) noexcept { return Own(other); } static uintptr_t MoveFrom(uintptr_t& other) noexcept { return std::exchange(other, kNone); } static void Destroy(uintptr_t ptr) noexcept { Unown(ptr); } static uintptr_t Own(uintptr_t ptr) noexcept { if (IsReferenceCount(ptr)) { const auto* refcount = Owner::AsReferenceCount(ptr); ABSL_ASSUME(refcount != nullptr); common_internal::StrongRef(refcount); } return ptr; } static void Unown(uintptr_t ptr) noexcept { if (IsReferenceCount(ptr)) { const auto* reference_count = AsReferenceCount(ptr); ABSL_ASSUME(reference_count != nullptr); common_internal::StrongUnref(reference_count); } } uintptr_t ptr_ = kNone; }; inline bool operator!=(const Owner& lhs, const Owner& rhs) noexcept { return !operator==(lhs, rhs); } namespace common_internal { inline absl::Nullable<const ReferenceCount*> OwnerRelease( Owner& owner) noexcept { uintptr_t ptr = std::exchange(owner.ptr_, uintptr_t{0}); if (Owner::IsReferenceCount(ptr)) { return Owner::AsReferenceCount(ptr); } return nullptr; } } class Borrower final { public: static Borrower None() noexcept { return Borrower(); } static Borrower Allocator(Allocator<> allocator) noexcept { auto* arena = allocator.arena(); return arena != nullptr ? Arena(arena) : None(); } static Borrower Arena(absl::Nonnull<google::protobuf::Arena*> arena ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ABSL_DCHECK(arena != nullptr); return Borrower(reinterpret_cast<uintptr_t>(arena) | Owner::kArenaBit); } static Borrower Arena(std::nullptr_t) = delete; static Borrower ReferenceCount( absl::Nonnull<const ReferenceCount*> reference_count ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ABSL_DCHECK(reference_count != nullptr); return Borrower(reinterpret_cast<uintptr_t>(reference_count) | Owner::kReferenceCountBit); } static Borrower ReferenceCount(std::nullptr_t) = delete; Borrower() = default; Borrower(const Borrower&) = default; Borrower(Borrower&&) = default; Borrower& operator=(const Borrower&) = default; Borrower& operator=(Borrower&&) = default; Borrower(const Owner& owner ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : ptr_(owner.ptr_) {} Borrower& operator=( const Owner& owner ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ptr_ = owner.ptr_; return *this; } Borrower& operator=(Owner&&) = delete; explicit operator bool() const noexcept { return !Owner::IsNone(ptr_); } absl::Nullable<google::protobuf::Arena*> arena() const noexcept { return (ptr_ & Owner::kBits) == Owner::kArenaBit ? reinterpret_cast<google::protobuf::Arena*>(ptr_ & Owner::kPointerMask) : nullptr; } friend bool operator==(Borrower lhs, Borrower rhs) noexcept { return lhs.ptr_ == rhs.ptr_; } private: friend class Owner; constexpr explicit Borrower(uintptr_t ptr) noexcept : ptr_(ptr) {} uintptr_t ptr_ = Owner::kNone; }; inline bool operator!=(Borrower lhs, Borrower rhs) noexcept { return !operator==(lhs, rhs); } inline bool operator==(Borrower lhs, const Owner& rhs) noexcept { return operator==(lhs, Borrower(rhs)); } inline bool operator==(const Owner& lhs, Borrower rhs) noexcept { return operator==(Borrower(lhs), rhs); } inline bool operator!=(Borrower lhs, const Owner& rhs) noexcept { return !operator==(lhs, rhs); } inline bool operator!=(const Owner& lhs, Borrower rhs) noexcept { return !operator==(lhs, rhs); } inline Owner::Owner(Borrower borrower) noexcept : ptr_(Owner::Own(borrower.ptr_)) {} template <typename T, typename... Args> Unique<T> AllocateUnique(Allocator<> allocator, Args&&... args); template <typename T> Unique<T> WrapUnique(T* object); template <typename T> class ABSL_ATTRIBUTE_TRIVIAL_ABI [[nodiscard]] Unique final { public: using element_type = T; static_assert(!std::is_array_v<T>, "T must not be an array"); static_assert(!std::is_reference_v<T>, "T must not be a reference"); static_assert(!std::is_volatile_v<T>, "T must not be volatile qualified"); Unique() = default; Unique(const Unique&) = delete; Unique& operator=(const Unique&) = delete; explicit Unique(T* ptr) noexcept : Unique(ptr, nullptr) {} Unique(std::nullptr_t) noexcept : Unique() {} Unique(Unique&& other) noexcept : Unique(other.ptr_, other.arena_) { other.ptr_ = nullptr; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Unique(Unique<U>&& other) noexcept : Unique(other.ptr_, other.arena_) { other.ptr_ = nullptr; } ~Unique() { Delete(); } Unique& operator=(Unique&& other) noexcept { if (ABSL_PREDICT_TRUE(this != &other)) { Delete(); ptr_ = other.ptr_; arena_ = other.arena_; other.ptr_ = nullptr; } return *this; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Unique& operator=(U* other) noexcept { reset(other); return *this; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Unique& operator=(Unique<U>&& other) noexcept { Delete(); ptr_ = other.ptr_; arena_ = other.arena_; other.ptr_ = nullptr; return *this; } Unique& operator=(std::nullptr_t) noexcept { reset(); return *this; } T& operator*() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK(static_cast<bool>(*this)); return *get(); } absl::Nonnull<T*> operator->() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK(static_cast<bool>(*this)); return get(); } ABSL_MUST_USE_RESULT T* release() noexcept { if constexpr (!IsArenaDestructorSkippable<T>::value) { if (static_cast<bool>(*this) && arena_ != nullptr) { arena_->OwnDestructor(ptr_); } } return std::exchange(ptr_, nullptr); } void reset() noexcept { reset(nullptr); } void reset(T* ptr) noexcept { Delete(); ptr_ = ptr; arena_ = nullptr; } void reset(std::nullptr_t) noexcept { Delete(); ptr_ = nullptr; } explicit operator bool() const noexcept { return get() != nullptr; } friend void swap(Unique& lhs, Unique& rhs) noexcept { using std::swap; swap(lhs.ptr_, rhs.ptr_); swap(lhs.arena_, rhs.arena_); } private: template <typename U> friend class Unique; template <typename U, typename... Args> friend Unique<U> AllocateUnique(Allocator<> allocator, Args&&... args); friend class ReferenceCountingMemoryManager; friend class PoolingMemoryManager; friend struct std::pointer_traits<Unique<T>>; constexpr Unique(T* ptr, google::protobuf::Arena* arena) noexcept : ptr_(ptr), arena_(arena) {} T* get() const noexcept { return ptr_; } void Delete() const noexcept { if (static_cast<bool>(*this)) { if (arena_ != nullptr) { if constexpr (!IsArenaDestructorSkippable<T>::value) { ptr_->~T(); } } else { google::protobuf::Arena::Destroy(ptr_); } } } T* ptr_ = nullptr; google::protobuf::Arena* arena_ = nullptr; }; template <typename T> Unique(T*) -> Unique<T>; template <typename T, typename... Args> Unique<T> AllocateUnique(Allocator<> allocator, Args&&... args) { T* object; auto* arena = allocator.arena(); if constexpr (IsArenaConstructible<T>::value) { object = google::protobuf::Arena::Create<T>(arena, std::forward<Args>(args)...); arena = nullptr; } else { void* p = allocator.allocate_bytes(sizeof(T), alignof(T)); CEL_INTERNAL_TRY { object = ::new (p) T(std::forward<Args>(args)...); } CEL_INTERNAL_CATCH_ANY { allocator.deallocate_bytes(p, sizeof(T), alignof(T)); CEL_INTERNAL_RETHROW; } } return Unique<T>(object, arena); } template <typename T> Unique<T> WrapUnique(T* object) { return Unique<T>(object); } } namespace std { template <typename T> struct pointer_traits<cel::Unique<T>> { using pointer = cel::Unique<T>; using element_type = typename cel::Unique<T>::element_type; using difference_type = ptrdiff_t; template <typename U> using rebind = cel::Unique<U>; static element_type* to_address(const pointer& p) noexcept { return p.ptr_; } }; } namespace cel { template <typename T> class ABSL_ATTRIBUTE_TRIVIAL_ABI Shared final { public: Shared() = default; Shared(const Shared& other) : value_(other.value_), refcount_(other.refcount_) { common_internal::StrongRef(refcount_); } Shared(Shared&& other) noexcept : value_(other.value_), refcount_(other.refcount_) { other.value_ = nullptr; other.refcount_ = nullptr; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Shared(const Shared<U>& other) : value_(other.value_), refcount_(other.refcount_) { common_internal::StrongRef(refcount_); } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Shared(Shared<U>&& other) noexcept : value_(other.value_), refcount_(other.refcount_) { other.value_ = nullptr; other.refcount_ = nullptr; } template <typename U, typename = std::enable_if_t<std::is_convertible_v<U*, T*>>> explicit Shared(SharedView<U> other); template <typename U> Shared(const Shared<U>& alias, T* ptr) : value_(ptr), refcount_(alias.refcount_) { common_internal::StrongRef(refcount_); } template <typename U> Shared(Shared<U>&& alias, T* ptr) noexcept : value_(ptr), refcount_(alias.refcount_) { alias.value_ = nullptr; alias.refcount_ = nullptr; } ~Shared() { common_internal::StrongUnref(refcount_); } Shared& operator=(const Shared& other) { common_internal::StrongRef(other.refcount_); common_internal::StrongUnref(refcount_); value_ = other.value_; refcount_ = other.refcount_; return *this; } Shared& operator=(Shared&& other) noexcept { common_internal::StrongUnref(refcount_); value_ = other.value_; refcount_ = other.refcount_; other.value_ = nullptr; other.refcount_ = nullptr; return *this; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Shared& operator=(const Shared<U>& other) { common_internal::StrongRef(other.refcount_); common_internal::StrongUnref(refcount_); value_ = other.value_; refcount_ = other.refcount_; return *this; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> Shared& operator=(Shared<U>&& other) noexcept { common_internal::StrongUnref(refcount_); value_ = other.value_; refcount_ = other.refcount_; other.value_ = nullptr; other.refcount_ = nullptr; return *this; } template <typename U = T, typename = std::enable_if_t<!std::is_void_v<U>>> U& operator*() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK(!IsEmpty()); return *value_; } absl::Nonnull<T*> operator->() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK(!IsEmpty()); return value_; } explicit operator bool() const { return !IsEmpty(); } friend constexpr void swap(Shared& lhs, Shared& rhs) noexcept { using std::swap; swap(lhs.value_, rhs.value_); swap(lhs.refcount_, rhs.refcount_); } private: template <typename U> friend class Shared; template <typename U> friend class SharedView; template <typename To, typename From> friend Shared<To> StaticCast(Shared<From>&& from); template <typename U> friend U* common_internal::GetPointer(const Shared<U>& shared); template <typename U> friend const common_internal::ReferenceCount* common_internal::GetReferenceCount(const Shared<U>& shared); template <typename U> friend Shared<U> common_internal::MakeShared( common_internal::AdoptRef, U* value, const common_internal::ReferenceCount* refcount); Shared(common_internal::AdoptRef, T* value, const common_internal::ReferenceCount* refcount) noexcept : value_(value), refcount_(refcount) {} Shared(T* value, const common_internal::ReferenceCount* refcount) noexcept : value_(value), refcount_(refcount) { common_internal::StrongRef(refcount_); } bool IsEmpty() const noexcept { return value_ == nullptr; } T* value_ = nullptr; const common_internal::ReferenceCount* refcount_ = nullptr; }; template <typename To, typename From> inline Shared<To> StaticCast(const Shared<From>& from) { return common_internal::MakeShared( static_cast<To*>(common_internal::GetPointer(from)), common_internal::GetReferenceCount(from)); } template <typename To, typename From> inline Shared<To> StaticCast(Shared<From>&& from) { To* value = static_cast<To*>(from.value_); const auto* refcount = from.refcount_; from.value_ = nullptr; from.refcount_ = nullptr; return Shared<To>(common_internal::kAdoptRef, value, refcount); } template <typename T> struct NativeTypeTraits<Shared<T>> final { static bool SkipDestructor(const Shared<T>& shared) { return common_internal::GetReferenceCount(shared) == nullptr; } }; template <typename T> class ABSL_ATTRIBUTE_TRIVIAL_ABI SharedView final { public: SharedView() = default; SharedView(const SharedView&) = default; SharedView& operator=(const SharedView&) = default; template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> SharedView(const SharedView<U>& other) : value_(other.value_), refcount_(other.refcount_) {} template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> SharedView(SharedView<U>&& other) noexcept : value_(other.value_), refcount_(other.refcount_) {} template <typename U, typename = std::enable_if_t<std::is_convertible_v<U*, T*>>> SharedView(const Shared<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(other.value_), refcount_(other.refcount_) {} template <typename U> SharedView(SharedView<U> alias, T* ptr) : value_(ptr), refcount_(alias.refcount_) {} template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> SharedView& operator=(const SharedView<U>& other) { value_ = other.value_; refcount_ = other.refcount_; return *this; } template < typename U, typename = std::enable_if_t<std::conjunction_v< std::negation<std::is_same<U, T>>, std::is_convertible<U*, T*>>>> SharedView& operator=(SharedView<U>&& other) noexcept { value_ = other.value_; refcount_ = other.refcount_; return *this; } template <typename U, typename = std::enable_if_t<std::is_convertible_v<U*, T*>>> SharedView& operator=( const Shared<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { value_ = other.value_; refcount_ = other.refcount_; return *this; } template <typename U, typename = std::enable_if_t<std::is_convertible_v<U*, T*>>> SharedView& operator=(Shared<U>&&) = delete; template <typename U = T, typename = std::enable_if_t<!std::is_void_v<U>>> U& operator*() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK(!IsEmpty()); return *value_; } absl::Nonnull<T*> operator->() const noexcept { ABSL_DCHECK(!IsEmpty()); return value_; } explicit operator bool() const { return !IsEmpty(); } friend constexpr void swap(SharedView& lhs, SharedView& rhs) noexcept { using std::swap; swap(lhs.value_, rhs.value_); swap(lhs.refcount_, rhs.refcount_); } private: template <typename U> friend class Shared; template <typename U> friend class SharedView; template <typename U> friend U* common_internal::GetPointer(SharedView<U> shared); template <typename U> friend const common_internal::ReferenceCount* common_internal::GetReferenceCount(SharedView<U> shared); template <typename U> friend SharedView<U> common_internal::MakeSharedView( U* value, const common_internal::ReferenceCount* refcount); SharedView(T* value, const common_internal::ReferenceCount* refcount) : value_(value), refcount_(refcount) {} bool IsEmpty() const noexcept { return value_ == nullptr; } T* value_ = nullptr; const common_internal::ReferenceCount* refcount_ = nullptr; }; template <typename T> template <typename U, typename> Shared<T>::Shared(SharedView<U> other) : value_(other.value_), refcount_(other.refcount_) { StrongRef(refcount_); } template <typename To, typename From> SharedView<To> StaticCast(SharedView<From> from) { return common_internal::MakeSharedView( static_cast<To*>(common_internal::GetPointer(from)), common_internal::GetReferenceCount(from)); } template <typename T> struct EnableSharedFromThis : public virtual common_internal::ReferenceCountFromThis { protected: Shared<T> shared_from_this() noexcept { auto* const derived = static_cast<T*>(this); auto* const refcount = common_internal::GetReferenceCountForThat(*this); return common_internal::MakeShared(derived, refcount); } Shared<const T> shared_from_this() const noexcept { auto* const derived = static_cast<const T*>(this); auto* const refcount = common_internal::GetReferenceCountForThat(*this); return common_internal::MakeShared(derived, refcount); } }; class ReferenceCountingMemoryManager final { public: ReferenceCountingMemoryManager(const ReferenceCountingMemoryManager&) = delete; ReferenceCountingMemoryManager(ReferenceCountingMemoryManager&&) = delete; ReferenceCountingMemoryManager& operator=( const ReferenceCountingMemoryManager&) = delete; ReferenceCountingMemoryManager& operator=(ReferenceCountingMemoryManager&&) = delete; private: template <typename T, typename... Args> static ABSL_MUST_USE_RESULT Shared<T> MakeShared(Args&&... args) { using U = std::remove_const_t<T>; U* ptr; common_internal::ReferenceCount* refcount; std::tie(ptr, refcount) = common_internal::MakeReferenceCount<U>(std::forward<Args>(args)...); return common_internal::MakeShared(common_internal::kAdoptRef, static_cast<T*>(ptr), refcount); } template <typename T, typename... Args> static ABSL_MUST_USE_RESULT Unique<T> MakeUnique(Args&&... args) { using U = std::remove_const_t<T>; return Unique<T>(static_cast<T*>(new U(std::forward<Args>(args)...)), nullptr); } static void* Allocate(size_t size, size_t alignment); static bool Deallocate(void* ptr, size_t size, size_t alignment) noexcept; explicit ReferenceCountingMemoryManager() = default; friend class MemoryManager; }; class PoolingMemoryManager final { public: PoolingMemoryManager(const PoolingMemoryManager&) = delete; PoolingMemoryManager(PoolingMemoryManager&&) = delete; PoolingMemoryManager& operator=(const PoolingMemoryManager&) = delete; PoolingMemoryManager& operator=(PoolingMemoryManager&&) = delete; private: template <typename T, typename... Args> ABSL_MUST_USE_RESULT static Shared<T> MakeShared(google::protobuf::Arena* arena, Args&&... args) { using U = std::remove_const_t<T>; U* ptr = nullptr; void* addr = Allocate(arena, sizeof(U), alignof(U)); CEL_INTERNAL_TRY { ptr = ::new (addr) U(std::forward<Args>(args)...); if constexpr (!std::is_trivially_destructible_v<U>) { if (!NativeType::SkipDestructor(*ptr)) { CEL_INTERNAL_TRY { OwnCustomDestructor(arena, ptr, &DefaultDestructor<U>); } CEL_INTERNAL_CATCH_ANY { ptr->~U(); CEL_INTERNAL_RETHROW; } } } if constexpr (std::is_base_of_v<common_internal::ReferenceC
#include "common/memory.h" #include <cstddef> #include <memory> #include <sstream> #include <string> #include <utility> #include "absl/base/config.h" #include "absl/debugging/leak_check.h" #include "absl/log/absl_check.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/internal/reference_count.h" #include "common/native_type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" #ifdef ABSL_HAVE_EXCEPTIONS #include <stdexcept> #endif namespace cel { namespace { using testing::_; using testing::IsFalse; using testing::IsNull; using testing::IsTrue; using testing::NotNull; using testing::TestParamInfo; using testing::TestWithParam; TEST(MemoryManagement, ostream) { { std::ostringstream out; out << MemoryManagement::kPooling; EXPECT_EQ(out.str(), "POOLING"); } { std::ostringstream out; out << MemoryManagement::kReferenceCounting; EXPECT_EQ(out.str(), "REFERENCE_COUNTING"); } } struct TrivialSmallObject { uintptr_t ptr; char padding[32 - sizeof(uintptr_t)]; }; TEST(RegionalMemoryManager, TrivialSmallSizes) { google::protobuf::Arena arena; MemoryManager memory_manager = MemoryManager::Pooling(&arena); for (size_t i = 0; i < 1024; ++i) { static_cast<void>(memory_manager.MakeUnique<TrivialSmallObject>()); } } struct TrivialMediumObject { uintptr_t ptr; char padding[256 - sizeof(uintptr_t)]; }; TEST(RegionalMemoryManager, TrivialMediumSizes) { google::protobuf::Arena arena; MemoryManager memory_manager = MemoryManager::Pooling(&arena); for (size_t i = 0; i < 1024; ++i) { static_cast<void>(memory_manager.MakeUnique<TrivialMediumObject>()); } } struct TrivialLargeObject { uintptr_t ptr; char padding[4096 - sizeof(uintptr_t)]; }; TEST(RegionalMemoryManager, TrivialLargeSizes) { google::protobuf::Arena arena; MemoryManager memory_manager = MemoryManager::Pooling(&arena); for (size_t i = 0; i < 1024; ++i) { static_cast<void>(memory_manager.MakeUnique<TrivialLargeObject>()); } } TEST(RegionalMemoryManager, TrivialMixedSizes) { google::protobuf::Arena arena; MemoryManager memory_manager = MemoryManager::Pooling(&arena); for (size_t i = 0; i < 1024; ++i) { switch (i % 3) { case 0: static_cast<void>(memory_manager.MakeUnique<TrivialSmallObject>()); break; case 1: static_cast<void>(memory_manager.MakeUnique<TrivialMediumObject>()); break; case 2: static_cast<void>(memory_manager.MakeUnique<TrivialLargeObject>()); break; } } } struct TrivialHugeObject { uintptr_t ptr; char padding[32768 - sizeof(uintptr_t)]; }; TEST(RegionalMemoryManager, TrivialHugeSizes) { google::protobuf::Arena arena; MemoryManager memory_manager = MemoryManager::Pooling(&arena); for (size_t i = 0; i < 1024; ++i) { static_cast<void>(memory_manager.MakeUnique<TrivialHugeObject>()); } } class SkippableDestructor { public: explicit SkippableDestructor(bool& deleted) : deleted_(deleted) {} ~SkippableDestructor() { deleted_ = true; } private: bool& deleted_; }; } template <> struct NativeTypeTraits<SkippableDestructor> final { static bool SkipDestructor(const SkippableDestructor&) { return true; } }; namespace { TEST(RegionalMemoryManager, SkippableDestructor) { bool deleted = false; { google::protobuf::Arena arena; MemoryManager memory_manager = MemoryManager::Pooling(&arena); auto shared = memory_manager.MakeShared<SkippableDestructor>(deleted); static_cast<void>(shared); } EXPECT_FALSE(deleted); } class MemoryManagerTest : public TestWithParam<MemoryManagement> { public: void SetUp() override {} void TearDown() override { Finish(); } void Finish() { arena_.reset(); } MemoryManagerRef memory_manager() { switch (memory_management()) { case MemoryManagement::kReferenceCounting: return MemoryManager::ReferenceCounting(); case MemoryManagement::kPooling: if (!arena_) { arena_.emplace(); } return MemoryManager::Pooling(&*arena_); } } MemoryManagement memory_management() const { return GetParam(); } static std::string ToString(TestParamInfo<MemoryManagement> param) { std::ostringstream out; out << param.param; return out.str(); } private: absl::optional<google::protobuf::Arena> arena_; }; TEST_P(MemoryManagerTest, AllocateAndDeallocateZeroSize) { EXPECT_THAT(memory_manager().Allocate(0, 1), IsNull()); EXPECT_THAT(memory_manager().Deallocate(nullptr, 0, 1), IsFalse()); } TEST_P(MemoryManagerTest, AllocateAndDeallocateBadAlignment) { EXPECT_DEBUG_DEATH(absl::IgnoreLeak(memory_manager().Allocate(1, 0)), _); EXPECT_DEBUG_DEATH(memory_manager().Deallocate(nullptr, 0, 0), _); } TEST_P(MemoryManagerTest, AllocateAndDeallocate) { constexpr size_t kSize = 1024; constexpr size_t kAlignment = __STDCPP_DEFAULT_NEW_ALIGNMENT__; void* ptr = memory_manager().Allocate(kSize, kAlignment); ASSERT_THAT(ptr, NotNull()); if (memory_management() == MemoryManagement::kReferenceCounting) { EXPECT_THAT(memory_manager().Deallocate(ptr, kSize, kAlignment), IsTrue()); } } TEST_P(MemoryManagerTest, AllocateAndDeallocateOveraligned) { constexpr size_t kSize = 1024; constexpr size_t kAlignment = __STDCPP_DEFAULT_NEW_ALIGNMENT__ * 4; void* ptr = memory_manager().Allocate(kSize, kAlignment); ASSERT_THAT(ptr, NotNull()); if (memory_management() == MemoryManagement::kReferenceCounting) { EXPECT_THAT(memory_manager().Deallocate(ptr, kSize, kAlignment), IsTrue()); } } class Object { public: Object() : deleted_(nullptr) {} explicit Object(bool& deleted) : deleted_(&deleted) {} ~Object() { if (deleted_ != nullptr) { ABSL_CHECK(!*deleted_); *deleted_ = true; } } int member = 0; private: bool* deleted_; }; class Subobject : public Object { public: using Object::Object; }; TEST_P(MemoryManagerTest, Shared) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedAliasCopy) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); EXPECT_FALSE(deleted); { auto member = Shared<int>(object, &object->member); EXPECT_TRUE(object); EXPECT_FALSE(deleted); EXPECT_TRUE(member); } EXPECT_TRUE(object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedAliasMove) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); EXPECT_FALSE(deleted); { auto member = Shared<int>(std::move(object), &object->member); EXPECT_FALSE(object); EXPECT_FALSE(deleted); EXPECT_TRUE(member); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } } Finish(); } TEST_P(MemoryManagerTest, SharedStaticCastCopy) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); EXPECT_FALSE(deleted); { auto member = StaticCast<void>(object); EXPECT_TRUE(object); EXPECT_FALSE(deleted); EXPECT_TRUE(member); } EXPECT_TRUE(object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedStaticCastMove) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); EXPECT_FALSE(deleted); { auto member = StaticCast<void>(std::move(object)); EXPECT_FALSE(object); EXPECT_FALSE(deleted); EXPECT_TRUE(member); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } } Finish(); } TEST_P(MemoryManagerTest, SharedCopyConstruct) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); Shared<Object> copied_object(object); EXPECT_TRUE(copied_object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedMoveConstruct) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); Shared<Object> moved_object(std::move(object)); EXPECT_FALSE(object); EXPECT_TRUE(moved_object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedCopyAssign) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); Shared<Object> moved_object(std::move(object)); EXPECT_FALSE(object); EXPECT_TRUE(moved_object); object = moved_object; EXPECT_TRUE(object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedMoveAssign) { bool deleted = false; { auto object = memory_manager().MakeShared<Object>(deleted); EXPECT_TRUE(object); Shared<Object> moved_object(std::move(object)); EXPECT_FALSE(object); EXPECT_TRUE(moved_object); object = std::move(moved_object); EXPECT_FALSE(moved_object); EXPECT_TRUE(object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedCopyConstructConvertible) { bool deleted = false; { auto object = memory_manager().MakeShared<Subobject>(deleted); EXPECT_TRUE(object); Shared<Object> copied_object(object); EXPECT_TRUE(copied_object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedMoveConstructConvertible) { bool deleted = false; { auto object = memory_manager().MakeShared<Subobject>(deleted); EXPECT_TRUE(object); Shared<Object> moved_object(std::move(object)); EXPECT_FALSE(object); EXPECT_TRUE(moved_object); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedCopyAssignConvertible) { bool deleted = false; { auto subobject = memory_manager().MakeShared<Subobject>(deleted); EXPECT_TRUE(subobject); auto object = memory_manager().MakeShared<Object>(); EXPECT_TRUE(object); object = subobject; EXPECT_TRUE(object); EXPECT_TRUE(subobject); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedMoveAssignConvertible) { bool deleted = false; { auto subobject = memory_manager().MakeShared<Subobject>(deleted); EXPECT_TRUE(subobject); auto object = memory_manager().MakeShared<Object>(); EXPECT_TRUE(object); object = std::move(subobject); EXPECT_TRUE(object); EXPECT_FALSE(subobject); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedSwap) { using std::swap; auto object1 = memory_manager().MakeShared<Object>(); auto object2 = memory_manager().MakeShared<Object>(); auto* const object1_ptr = object1.operator->(); auto* const object2_ptr = object2.operator->(); swap(object1, object2); EXPECT_EQ(object1.operator->(), object2_ptr); EXPECT_EQ(object2.operator->(), object1_ptr); } TEST_P(MemoryManagerTest, SharedPointee) { using std::swap; auto object = memory_manager().MakeShared<Object>(); EXPECT_EQ(std::addressof(*object), object.operator->()); } TEST_P(MemoryManagerTest, SharedViewConstruct) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto object = memory_manager().MakeShared<Object>(deleted); dangling_object_view.emplace(object); EXPECT_TRUE(*dangling_object_view); { auto copied_object = Shared<Object>(*dangling_object_view); EXPECT_FALSE(deleted); } EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewCopyConstruct) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto object = memory_manager().MakeShared<Object>(deleted); auto object_view = SharedView<Object>(object); SharedView<Object> copied_object_view(object_view); dangling_object_view.emplace(copied_object_view); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewMoveConstruct) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto object = memory_manager().MakeShared<Object>(deleted); auto object_view = SharedView<Object>(object); SharedView<Object> moved_object_view(std::move(object_view)); dangling_object_view.emplace(moved_object_view); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewCopyAssign) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto object = memory_manager().MakeShared<Object>(deleted); auto object_view1 = SharedView<Object>(object); SharedView<Object> object_view2(object); object_view1 = object_view2; dangling_object_view.emplace(object_view1); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewMoveAssign) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto object = memory_manager().MakeShared<Object>(deleted); auto object_view1 = SharedView<Object>(object); SharedView<Object> object_view2(object); object_view1 = std::move(object_view2); dangling_object_view.emplace(object_view1); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewCopyConstructConvertible) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto subobject = memory_manager().MakeShared<Subobject>(deleted); auto subobject_view = SharedView<Subobject>(subobject); SharedView<Object> object_view(subobject_view); dangling_object_view.emplace(object_view); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewMoveConstructConvertible) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto subobject = memory_manager().MakeShared<Subobject>(deleted); auto subobject_view = SharedView<Subobject>(subobject); SharedView<Object> object_view(std::move(subobject_view)); dangling_object_view.emplace(object_view); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewCopyAssignConvertible) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto subobject = memory_manager().MakeShared<Subobject>(deleted); auto object_view1 = SharedView<Object>(subobject); SharedView<Subobject> subobject_view2(subobject); object_view1 = subobject_view2; dangling_object_view.emplace(object_view1); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewMoveAssignConvertible) { bool deleted = false; absl::optional<SharedView<Object>> dangling_object_view; { auto subobject = memory_manager().MakeShared<Subobject>(deleted); auto object_view1 = SharedView<Object>(subobject); SharedView<Subobject> subobject_view2(subobject); object_view1 = std::move(subobject_view2); dangling_object_view.emplace(object_view1); EXPECT_FALSE(deleted); } switch (memory_management()) { case MemoryManagement::kPooling: EXPECT_FALSE(deleted); break; case MemoryManagement::kReferenceCounting: EXPECT_TRUE(deleted); break; } Finish(); } TEST_P(MemoryManagerTest, SharedViewSwap) { using std::swap; auto object1 = memory_manager().MakeShared<Object>(); auto object2 = memory_manager().MakeShared<Object>(); auto object1_view = SharedView<Object>(object1); auto object2_view = SharedView<Object>(object2); swap(object1_view, object2_view); EXPECT_EQ(object1_view.operator->(), object2.operator->()); EXPECT_EQ(object2_view.operator->(), object1.operator->()); } TEST_P(MemoryManagerTest, SharedViewPointee) { using std::swap; auto object = memory_manager().MakeShared<Object>(); auto object_view = SharedView<Object>(object); EXPECT_EQ(std::addressof(*object_view), object_view.operator->()); } TEST_P(MemoryManagerTest, Unique) { bool deleted = false; { auto object = memory_manager().MakeUnique<Object>(deleted); EXPECT_TRUE(object); EXPECT_FALSE(deleted); } EXPECT_TRUE(deleted); Finish(); } TEST_P(MemoryManagerTest, UniquePointee) { using std::swap; auto object = memory_manager().MakeUnique<Object>(); EXPECT_EQ(std::addressof(*object), object.operator->()); } TEST_P(MemoryManagerTest, UniqueSwap) { using std::swap; auto object1 = memory_manager().MakeUnique<Object>(); auto object2 = memory_manager().MakeUnique<Object>(); auto* const object1_ptr = object1.operator->(); auto* const object2_ptr = object2.operator->(); swap(object1, object2); EXPECT_EQ(object1.operator->(), object2_ptr); EXPECT_EQ(object2.operator->(), object1_ptr); } struct EnabledObject : EnableSharedFromThis<EnabledObject> { Shared<EnabledObject> This() { return shared_from_this(); } Shared<const EnabledObject> This() const { return shared_from_this(); } }; TEST_P(MemoryManagerTest, EnableSharedFromThis) { { auto object = memory_manager().MakeShared<EnabledObject>(); auto this_object = object->This(); EXPECT_EQ(this_object.operator->(), object.operator->()); } { auto object = memory_manager().MakeShared<const EnabledObject>(); auto this_object = object->This(); EXPECT_EQ(this_object.operator->(), object.operator->()); } Finish(); } struct ThrowingConstructorObject { ThrowingConstructorObject() { #ifdef ABSL_HAVE_EXCEPTIONS throw std::invalid_argument("ThrowingConstructorObject"); #endif } char padding[64]; }; TEST_P(MemoryManagerTest, SharedThrowingConstructor) { #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(static_cast<void>( memory_manager().MakeShared<ThrowingConstructorObject>()), std::invalid_argument); #else GTEST_SKIP(); #endif } TEST_P(MemoryManagerTest, UniqueThrowingConstructor) { #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(static_cast<void>( memory_manager().MakeUnique<ThrowingConstructorObject>()), std::invalid_argument); #else GTEST_SKIP(); #endif } INSTANTIATE_TEST_SUITE_P( MemoryManagerTest, MemoryManagerTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), MemoryManagerTest::ToString); TEST(Owner, None) { EXPECT_THAT(Owner::None(), IsFalse()); EXPECT_THAT(Owner::None().arena(), IsNull()); } TEST(Owner, Allocator) { google::protobuf::Arena arena; EXPECT_THAT(Owner::Allocator(NewDeleteAllocator()), IsFalse()); EXPECT_THAT(Owner::Allocator(ArenaAllocator(&arena)), IsTrue()); } TEST(Owner, Arena) { google::protobuf::Arena arena; EXPECT_THAT(Owner::Arena(&arena), IsTrue()); EXPECT_EQ(Owner::Arena(&arena).arena(), &arena); } TEST(Owner, ReferenceCount) { auto* refcount = new common_internal::ReferenceCounted(); EXPECT_THAT(Owner::ReferenceCount(refcount), IsTrue()); EXPECT_THAT(Owner::ReferenceCount(refcount).arena(), IsNull()); common_internal::StrongUnref(refcount); } TEST(Owner, Equality) { google::protobuf::Arena arena1; google::protobuf::Arena arena2; EXPECT_EQ(Owner::None(), Owner::None()); EXPECT_EQ(Owner::Allocator(NewDeleteAllocator()), Owner::None()); EXPECT_EQ(Owner::Arena(&arena1), Owner::Arena(&arena1)); EXPECT_NE(Owner::Arena(&arena1), Owner::None()); EXPECT_NE(Owner::None(), Owner::Arena(&arena1)); EXPECT_NE(Owner::Arena(&arena1), Owner::Arena(&arena2)); EXPECT_EQ(Owner::Allocator(ArenaAllocator(&arena1)), Owner::Arena(&arena1)); } TEST(Borrower, None) { EXPECT_THAT(Borrower::None(), IsFalse()); EXPECT_THAT(Borrower::None().arena(), IsNull()); } TEST(Borrower, Allocator) { google::protobuf::Arena arena; EXPECT_THAT(Borrower::Allocator(NewDeleteAllocator()), IsFalse()); EXPECT_THAT(Borrower::Allocator(ArenaAllocator(&arena)), IsTrue()); } TEST(Borrower, Arena) { google::protobuf::Arena arena; EXPECT_THAT(Borrower::Arena(&arena), IsTrue()); EXPECT_EQ(Borrower::Arena(&arena).arena(), &arena); } TEST(Borrower, ReferenceCount) { auto* refcount = new common_internal::ReferenceCounted(); EXPECT_THAT(Borrower::ReferenceCount(refcount), IsTrue()); EXPECT_THAT(Borrower::ReferenceCount(refcount).arena(), IsNull()); common_internal::StrongUnref(refcount); } TEST(Borrower, Equality) { google::protobuf::Arena arena1; google::protobuf::Arena arena2; EXPECT_EQ(Borrower::None(), Borrower::None()); EXPECT_EQ(Borrower::Allocator(NewDeleteAllocator()), Borrower::None()); EXPECT_EQ(Borrower::Arena(&arena1), Borrower::Arena(&arena1)); EXPECT_NE(Borrower::Arena(&arena1), Borrower::None()); EXPECT_NE(Borrower::None(), Borrower::Arena(&arena1)); EXPECT_NE(Borrower::Arena(&arena1), Borrower::Arena(&arena2)); EXPECT_EQ(Borrower::Allocator(ArenaAllocator(&arena1)), Borrower::Arena(&arena1)); } TEST(OwnerBorrower, CopyConstruct) { auto* refcount = new common_internal::ReferenceCounted(); Owner owner1 = Owner::ReferenceCount(refcount); common_internal::StrongUnref(refcount); Owner owner2(owner1); Borrower borrower(owner1); EXPECT_EQ(owner1, owner2); EXPECT_EQ(owner1, borrower); EXPECT_EQ(borrower, owner1); } TEST(OwnerBorrower, MoveConstruct) { auto* refcount = new common_internal::ReferenceCounted(); Owner owner1 = Owner::ReferenceCount(refcount); common_internal::StrongUnref(refcount); Owner owner2(std::move(owner1)); Borrower borrower(owner2); EXPECT_EQ(owner2, borrower); EXPECT_EQ(borrower, owner2); } TEST(OwnerBorrower, CopyAssign) { auto* refcount = new common_internal::ReferenceCounted(); Owner owner1 = Owner::ReferenceCount(refcount); common_internal::StrongUnref(refcount); Owner owner2; owner2 = owner1; Borrower borrower(owner1); EXPECT_EQ(owner1, owner2); EXPECT_EQ(owner1, borrower); EXPECT_EQ(borrower, owner1); } TEST(OwnerBorrower, MoveAssign) { auto* refcount = new common_internal::ReferenceCounted(); Owner owner1 = Owner::ReferenceCount(refcount); common_internal::StrongUnref(refcount); Owner owner2; owner2 = std::move(owner1); Borrower borrower(owner2); EXPECT_EQ(owner2, borrower); EXPECT_EQ(borrower, owner2); } TEST(Unique, ToAddress) { Unique<bool> unique; EXPECT_EQ(cel::to_address(unique), nullptr); unique = AllocateUnique<bool>(NewDeleteAllocator()); EXPECT_EQ(cel::to_address(unique), unique.operator->()); } } }
11
cpp
google/cel-cpp
any
extensions/protobuf/internal/any.cc
extensions/protobuf/internal/any_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_ANY_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_ANY_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<Any> UnwrapDynamicAnyProto(const google::protobuf::Message& message); absl::Status WrapDynamicAnyProto(absl::string_view type_url, const absl::Cord& value, google::protobuf::Message& message); inline absl::Status WrapDynamicAnyProto(const Any& any, google::protobuf::Message& message) { return WrapDynamicAnyProto(any.type_url(), any.value(), message); } } #endif #include "extensions/protobuf/internal/any.h" #include <string> #include "google/protobuf/any.pb.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #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 "common/any.h" #include "extensions/protobuf/internal/any_lite.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<Any> UnwrapDynamicAnyProto(const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Any"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (desc == google::protobuf::Any::descriptor()) { return UnwrapGeneratedAnyProto( google::protobuf::DownCastToGenerated<google::protobuf::Any>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* type_url_field = desc->FindFieldByNumber(google::protobuf::Any::kTypeUrlFieldNumber); if (ABSL_PREDICT_FALSE(type_url_field == nullptr)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " missing type_url field descriptor")); } if (ABSL_PREDICT_FALSE(type_url_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_STRING)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected type_url field type: ", type_url_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(type_url_field->is_map() || type_url_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", type_url_field->name(), " field cardinality: REPEATED")); } const auto* value_field = desc->FindFieldByNumber(google::protobuf::Any::kValueFieldNumber); if (ABSL_PREDICT_FALSE(value_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing value field descriptor")); } if (ABSL_PREDICT_FALSE(value_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_STRING)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected value field type: ", value_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(value_field->is_map() || value_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", value_field->name(), " field cardinality: REPEATED")); } return MakeAny(reflect->GetString(message, type_url_field), reflect->GetCord(message, value_field)); } absl::Status WrapDynamicAnyProto(absl::string_view type_url, const absl::Cord& value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Any"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (desc == google::protobuf::Any::descriptor()) { return WrapGeneratedAnyProto( type_url, value, google::protobuf::DownCastToGenerated<google::protobuf::Any>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* type_url_field = desc->FindFieldByNumber(google::protobuf::Any::kTypeUrlFieldNumber); if (ABSL_PREDICT_FALSE(type_url_field == nullptr)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " missing type_url field descriptor")); } if (ABSL_PREDICT_FALSE(type_url_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_STRING)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected type_url field type: ", type_url_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(type_url_field->is_map() || type_url_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", type_url_field->name(), " field cardinality: REPEATED")); } const auto* value_field = desc->FindFieldByNumber(google::protobuf::Any::kValueFieldNumber); if (ABSL_PREDICT_FALSE(value_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing value field descriptor")); } if (ABSL_PREDICT_FALSE(value_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_STRING)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected value field type: ", value_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(value_field->is_map() || value_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", value_field->name(), " field cardinality: REPEATED")); } reflect->SetString(&message, type_url_field, std::string(type_url)); reflect->SetString(&message, value_field, value); return absl::OkStatus(); } }
#include "extensions/protobuf/internal/any.h" #include <memory> #include "google/protobuf/any.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/memory/memory.h" #include "absl/strings/cord.h" #include "common/any.h" #include "extensions/protobuf/internal/any_lite.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor_database.h" #include "google/protobuf/dynamic_message.h" namespace cel::extensions::protobuf_internal { namespace { using testing::Eq; using cel::internal::IsOkAndHolds; TEST(Any, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedAnyProto(google::protobuf::Any()), IsOkAndHolds(Eq(Any()))); } TEST(Any, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Any::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicAnyProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.Any"))), IsOkAndHolds(Eq(Any()))); } TEST(Any, GeneratedToProto) { google::protobuf::Any proto; ASSERT_OK(WrapGeneratedAnyProto("type.googleapis.com/foo.Bar", absl::Cord("blah"), proto)); EXPECT_EQ(proto.type_url(), "type.googleapis.com/foo.Bar"); EXPECT_EQ(proto.value(), "blah"); } TEST(Any, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Any::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique( factory.GetPrototype(pool.FindMessageTypeByName("google.protobuf.Any")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* type_url_field = descriptor->FindFieldByName("type_url"); ASSERT_NE(type_url_field, nullptr); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicAnyProto("type.googleapis.com/foo.Bar", absl::Cord("blah"), *proto)); EXPECT_EQ(reflection->GetString(*proto, type_url_field), "type.googleapis.com/foo.Bar"); EXPECT_EQ(reflection->GetString(*proto, value_field), "blah"); } } }
12
cpp
google/cel-cpp
native_type
common/native_type.cc
common/native_type_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_NATIVE_TYPE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_NATIVE_TYPE_H_ #include <cstddef> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/meta/type_traits.h" #if ABSL_HAVE_FEATURE(cxx_rtti) #define CEL_INTERNAL_HAVE_RTTI 1 #elif defined(__GNUC__) && defined(__GXX_RTTI) #define CEL_INTERNAL_HAVE_RTTI 1 #elif defined(_MSC_VER) && defined(_CPPRTTI) #define CEL_INTERNAL_HAVE_RTTI 1 #elif !defined(__GNUC__) && !defined(_MSC_VER) #define CEL_INTERNAL_HAVE_RTTI 1 #endif #ifdef CEL_INTERNAL_HAVE_RTTI #include <typeinfo> #endif namespace cel { template <typename T, typename = void> struct NativeTypeTraits; class ABSL_ATTRIBUTE_TRIVIAL_ABI NativeTypeId final { private: template <typename, typename = void> struct HasNativeTypeTraitsId : std::false_type {}; template <typename T> struct HasNativeTypeTraitsId<T, std::void_t<decltype(NativeTypeTraits<T>::Id( std::declval<const T&>()))>> : std::true_type {}; template <typename T> static constexpr bool HasNativeTypeTraitsIdV = HasNativeTypeTraitsId<T>::value; public: template <typename T> static NativeTypeId For() { static_assert(!std::is_pointer_v<T>); static_assert(std::is_same_v<T, std::decay_t<T>>); static_assert(!std::is_same_v<NativeTypeId, std::decay_t<T>>); #ifdef CEL_INTERNAL_HAVE_RTTI return NativeTypeId(&typeid(T)); #else static char rep; return NativeTypeId(&rep); #endif } template <typename T> static std::enable_if_t<HasNativeTypeTraitsIdV<absl::remove_cvref_t<T>>, NativeTypeId> Of(const T& type) noexcept { static_assert(!std::is_pointer_v<T>); static_assert(std::is_same_v<T, std::decay_t<T>>); static_assert(!std::is_same_v<NativeTypeId, std::decay_t<T>>); return NativeTypeTraits<absl::remove_cvref_t<T>>::Id(type); } template <typename T> static std::enable_if_t< std::conjunction_v< std::negation<HasNativeTypeTraitsId<absl::remove_cvref_t<T>>>, std::is_final<absl::remove_cvref_t<T>>>, NativeTypeId> Of(const T&) noexcept { static_assert(!std::is_pointer_v<T>); static_assert(std::is_same_v<T, std::decay_t<T>>); static_assert(!std::is_same_v<NativeTypeId, std::decay_t<T>>); return NativeTypeId::For<absl::remove_cvref_t<T>>(); } NativeTypeId() = default; NativeTypeId(const NativeTypeId&) = default; NativeTypeId(NativeTypeId&&) noexcept = default; NativeTypeId& operator=(const NativeTypeId&) = default; NativeTypeId& operator=(NativeTypeId&&) noexcept = default; std::string DebugString() const; friend bool operator==(NativeTypeId lhs, NativeTypeId rhs) { #ifdef CEL_INTERNAL_HAVE_RTTI return lhs.rep_ == rhs.rep_ || (lhs.rep_ != nullptr && rhs.rep_ != nullptr && *lhs.rep_ == *rhs.rep_); #else return lhs.rep_ == rhs.rep_; #endif } template <typename H> friend H AbslHashValue(H state, NativeTypeId id) { #ifdef CEL_INTERNAL_HAVE_RTTI return H::combine(std::move(state), id.rep_ != nullptr ? id.rep_->hash_code() : size_t{0}); #else return H::combine(std::move(state), absl::bit_cast<uintptr_t>(id.rep_)); #endif } private: #ifdef CEL_INTERNAL_HAVE_RTTI constexpr explicit NativeTypeId(const std::type_info* rep) : rep_(rep) {} const std::type_info* rep_ = nullptr; #else constexpr explicit NativeTypeId(const void* rep) : rep_(rep) {} const void* rep_ = nullptr; #endif }; inline bool operator!=(NativeTypeId lhs, NativeTypeId rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, NativeTypeId id) { return out << id.DebugString(); } class NativeType final { public: template <typename T> ABSL_MUST_USE_RESULT static bool SkipDestructor(const T& type) { if constexpr (std::is_trivially_destructible_v<T>) { return true; } else if constexpr (HasNativeTypeTraitsSkipDestructorV<T>) { return NativeTypeTraits<T>::SkipDestructor(type); } else { return false; } } private: template <typename, typename = void> struct HasNativeTypeTraitsSkipDestructor : std::false_type {}; template <typename T> struct HasNativeTypeTraitsSkipDestructor< T, std::void_t<decltype(NativeTypeTraits<T>::SkipDestructor( std::declval<const T&>()))>> : std::true_type {}; template <typename T> static inline constexpr bool HasNativeTypeTraitsSkipDestructorV = HasNativeTypeTraitsSkipDestructor<T>::value; NativeType() = delete; NativeType(const NativeType&) = delete; NativeType(NativeType&&) = delete; ~NativeType() = delete; NativeType& operator=(const NativeType&) = delete; NativeType& operator=(NativeType&&) = delete; }; } #endif #include "common/native_type.h" #include <cstddef> #include <cstdint> #include <cstdlib> #include <memory> #include <string> #include "absl/base/casts.h" #include "absl/strings/str_cat.h" #ifdef CEL_INTERNAL_HAVE_RTTI #ifdef _WIN32 extern "C" char* __unDName(char*, const char*, int, void* (*)(size_t), void (*)(void*), int); #else #include <cxxabi.h> #endif #endif namespace cel { namespace { #ifdef CEL_INTERNAL_HAVE_RTTI struct FreeDeleter { void operator()(char* ptr) const { std::free(ptr); } }; #endif } std::string NativeTypeId::DebugString() const { if (rep_ == nullptr) { return std::string(); } #ifdef CEL_INTERNAL_HAVE_RTTI #ifdef _WIN32 std::unique_ptr<char, FreeDeleter> demangled( __unDName(nullptr, rep_->raw_name(), 0, std::malloc, std::free, 0x2800)); if (demangled == nullptr) { return std::string(rep_->name()); } return std::string(demangled.get()); #else size_t length = 0; int status = 0; std::unique_ptr<char, FreeDeleter> demangled( abi::__cxa_demangle(rep_->name(), nullptr, &length, &status)); if (status != 0 || demangled == nullptr) { return std::string(rep_->name()); } while (length != 0 && demangled.get()[length - 1] == '\0') { --length; } return std::string(demangled.get(), length); #endif #else return absl::StrCat("0x", absl::Hex(absl::bit_cast<uintptr_t>(rep_))); #endif } }
#include "common/native_type.h" #include <cstring> #include <sstream> #include "absl/hash/hash_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::IsEmpty; using testing::Not; using testing::SizeIs; struct Type1 {}; struct Type2 {}; struct Type3 {}; TEST(NativeTypeId, ImplementsAbslHashCorrectly) { EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {NativeTypeId(), NativeTypeId::For<Type1>(), NativeTypeId::For<Type2>(), NativeTypeId::For<Type3>()})); } TEST(NativeTypeId, DebugString) { std::ostringstream out; out << NativeTypeId(); EXPECT_THAT(out.str(), IsEmpty()); out << NativeTypeId::For<Type1>(); auto string = out.str(); EXPECT_THAT(string, Not(IsEmpty())); EXPECT_THAT(string, SizeIs(std::strlen(string.c_str()))); } struct TestType {}; } template <> struct NativeTypeTraits<TestType> final { static NativeTypeId Id(const TestType&) { return NativeTypeId::For<TestType>(); } }; namespace { TEST(NativeTypeId, Of) { EXPECT_EQ(NativeTypeId::Of(TestType()), NativeTypeId::For<TestType>()); } struct TrivialObject {}; TEST(NativeType, SkipDestructorTrivial) { EXPECT_TRUE(NativeType::SkipDestructor(TrivialObject{})); } struct NonTrivialObject { ~NonTrivialObject() {} }; TEST(NativeType, SkipDestructorNonTrivial) { EXPECT_FALSE(NativeType::SkipDestructor(NonTrivialObject{})); } struct SkippableDestructObject { ~SkippableDestructObject() {} }; } template <> struct NativeTypeTraits<SkippableDestructObject> final { static bool SkipDestructor(const SkippableDestructObject&) { return true; } }; namespace { TEST(NativeType, SkipDestructorTraits) { EXPECT_TRUE(NativeType::SkipDestructor(SkippableDestructObject{})); } } }
13
cpp
google/cel-cpp
operators
common/operators.cc
base/operators_test.cc
#ifndef THIRD_PARTY_CEL_CPP_BASE_INTERNAL_OPERATORS_H_ #define THIRD_PARTY_CEL_CPP_BASE_INTERNAL_OPERATORS_H_ #include "absl/strings/string_view.h" namespace cel { enum class OperatorId; namespace base_internal { struct OperatorData final { OperatorData() = delete; OperatorData(const OperatorData&) = delete; OperatorData(OperatorData&&) = delete; OperatorData& operator=(const OperatorData&) = delete; OperatorData& operator=(OperatorData&&) = delete; constexpr OperatorData(cel::OperatorId id, absl::string_view name, absl::string_view display_name, int precedence, int arity) : id(id), name(name), display_name(display_name), precedence(precedence), arity(arity) {} const cel::OperatorId id; const absl::string_view name; const absl::string_view display_name; const int precedence; const int arity; }; #define CEL_INTERNAL_UNARY_OPERATORS_ENUM(XX) \ XX(LogicalNot, "!", "!_", 2, 1) \ XX(Negate, "-", "-_", 2, 1) \ XX(NotStrictlyFalse, "", "@not_strictly_false", 0, 1) \ XX(OldNotStrictlyFalse, "", "__not_strictly_false__", 0, 1) #define CEL_INTERNAL_BINARY_OPERATORS_ENUM(XX) \ XX(Equals, "==", "_==_", 5, 2) \ XX(NotEquals, "!=", "_!=_", 5, 2) \ XX(Less, "<", "_<_", 5, 2) \ XX(LessEquals, "<=", "_<=_", 5, 2) \ XX(Greater, ">", "_>_", 5, 2) \ XX(GreaterEquals, ">=", "_>=_", 5, 2) \ XX(In, "in", "@in", 5, 2) \ XX(OldIn, "in", "_in_", 5, 2) \ XX(Index, "", "_[_]", 1, 2) \ XX(LogicalOr, "||", "_||_", 7, 2) \ XX(LogicalAnd, "&&", "_&&_", 6, 2) \ XX(Add, "+", "_+_", 4, 2) \ XX(Subtract, "-", "_-_", 4, 2) \ XX(Multiply, "*", "_*_", 3, 2) \ XX(Divide, "/", "_/_", 3, 2) \ XX(Modulo, "%", "_%_", 3, 2) #define CEL_INTERNAL_TERNARY_OPERATORS_ENUM(XX) \ XX(Conditional, "", "_?_:_", 8, 3) #define CEL_INTERNAL_OPERATORS_ENUM(XX) \ CEL_INTERNAL_TERNARY_OPERATORS_ENUM(XX) \ CEL_INTERNAL_BINARY_OPERATORS_ENUM(XX) \ CEL_INTERNAL_UNARY_OPERATORS_ENUM(XX) } } #endif #include "base/operators.h" #include <algorithm> #include <array> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/log/absl_check.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/internal/operators.h" namespace cel { namespace { using base_internal::OperatorData; struct OperatorDataNameComparer { using is_transparent = void; bool operator()(const OperatorData* lhs, const OperatorData* rhs) const { return lhs->name < rhs->name; } bool operator()(const OperatorData* lhs, absl::string_view rhs) const { return lhs->name < rhs; } bool operator()(absl::string_view lhs, const OperatorData* rhs) const { return lhs < rhs->name; } }; struct OperatorDataDisplayNameComparer { using is_transparent = void; bool operator()(const OperatorData* lhs, const OperatorData* rhs) const { return lhs->display_name < rhs->display_name; } bool operator()(const OperatorData* lhs, absl::string_view rhs) const { return lhs->display_name < rhs; } bool operator()(absl::string_view lhs, const OperatorData* rhs) const { return lhs < rhs->display_name; } }; #define CEL_OPERATORS_DATA(id, symbol, name, precedence, arity) \ ABSL_CONST_INIT const OperatorData id##_storage = { \ OperatorId::k##id, name, symbol, precedence, arity}; CEL_INTERNAL_OPERATORS_ENUM(CEL_OPERATORS_DATA) #undef CEL_OPERATORS_DATA #define CEL_OPERATORS_COUNT(id, symbol, name, precedence, arity) +1 using OperatorsArray = std::array<const OperatorData*, 0 + CEL_INTERNAL_OPERATORS_ENUM(CEL_OPERATORS_COUNT)>; using UnaryOperatorsArray = std::array<const OperatorData*, 0 + CEL_INTERNAL_UNARY_OPERATORS_ENUM(CEL_OPERATORS_COUNT)>; using BinaryOperatorsArray = std::array<const OperatorData*, 0 + CEL_INTERNAL_BINARY_OPERATORS_ENUM(CEL_OPERATORS_COUNT)>; using TernaryOperatorsArray = std::array<const OperatorData*, 0 + CEL_INTERNAL_TERNARY_OPERATORS_ENUM(CEL_OPERATORS_COUNT)>; #undef CEL_OPERATORS_COUNT ABSL_CONST_INIT absl::once_flag operators_once_flag; #define CEL_OPERATORS_DO(id, symbol, name, precedence, arity) &id##_storage, OperatorsArray operators_by_name = { CEL_INTERNAL_OPERATORS_ENUM(CEL_OPERATORS_DO)}; OperatorsArray operators_by_display_name = { CEL_INTERNAL_OPERATORS_ENUM(CEL_OPERATORS_DO)}; UnaryOperatorsArray unary_operators_by_name = { CEL_INTERNAL_UNARY_OPERATORS_ENUM(CEL_OPERATORS_DO)}; UnaryOperatorsArray unary_operators_by_display_name = { CEL_INTERNAL_UNARY_OPERATORS_ENUM(CEL_OPERATORS_DO)}; BinaryOperatorsArray binary_operators_by_name = { CEL_INTERNAL_BINARY_OPERATORS_ENUM(CEL_OPERATORS_DO)}; BinaryOperatorsArray binary_operators_by_display_name = { CEL_INTERNAL_BINARY_OPERATORS_ENUM(CEL_OPERATORS_DO)}; TernaryOperatorsArray ternary_operators_by_name = { CEL_INTERNAL_TERNARY_OPERATORS_ENUM(CEL_OPERATORS_DO)}; TernaryOperatorsArray ternary_operators_by_display_name = { CEL_INTERNAL_TERNARY_OPERATORS_ENUM(CEL_OPERATORS_DO)}; #undef CEL_OPERATORS_DO void InitializeOperators() { std::stable_sort(operators_by_name.begin(), operators_by_name.end(), OperatorDataNameComparer{}); std::stable_sort(operators_by_display_name.begin(), operators_by_display_name.end(), OperatorDataDisplayNameComparer{}); std::stable_sort(unary_operators_by_name.begin(), unary_operators_by_name.end(), OperatorDataNameComparer{}); std::stable_sort(unary_operators_by_display_name.begin(), unary_operators_by_display_name.end(), OperatorDataDisplayNameComparer{}); std::stable_sort(binary_operators_by_name.begin(), binary_operators_by_name.end(), OperatorDataNameComparer{}); std::stable_sort(binary_operators_by_display_name.begin(), binary_operators_by_display_name.end(), OperatorDataDisplayNameComparer{}); std::stable_sort(ternary_operators_by_name.begin(), ternary_operators_by_name.end(), OperatorDataNameComparer{}); std::stable_sort(ternary_operators_by_display_name.begin(), ternary_operators_by_display_name.end(), OperatorDataDisplayNameComparer{}); } } UnaryOperator::UnaryOperator(Operator op) : data_(op.data_) { ABSL_CHECK(op.arity() == Arity::kUnary); } BinaryOperator::BinaryOperator(Operator op) : data_(op.data_) { ABSL_CHECK(op.arity() == Arity::kBinary); } TernaryOperator::TernaryOperator(Operator op) : data_(op.data_) { ABSL_CHECK(op.arity() == Arity::kTernary); } #define CEL_UNARY_OPERATOR(id, symbol, name, precedence, arity) \ UnaryOperator Operator::id() { return UnaryOperator(&id##_storage); } CEL_INTERNAL_UNARY_OPERATORS_ENUM(CEL_UNARY_OPERATOR) #undef CEL_UNARY_OPERATOR #define CEL_BINARY_OPERATOR(id, symbol, name, precedence, arity) \ BinaryOperator Operator::id() { return BinaryOperator(&id##_storage); } CEL_INTERNAL_BINARY_OPERATORS_ENUM(CEL_BINARY_OPERATOR) #undef CEL_BINARY_OPERATOR #define CEL_TERNARY_OPERATOR(id, symbol, name, precedence, arity) \ TernaryOperator Operator::id() { return TernaryOperator(&id##_storage); } CEL_INTERNAL_TERNARY_OPERATORS_ENUM(CEL_TERNARY_OPERATOR) #undef CEL_TERNARY_OPERATOR absl::optional<Operator> Operator::FindByName(absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(operators_by_name.cbegin(), operators_by_name.cend(), input, OperatorDataNameComparer{}); if (it == operators_by_name.cend() || (*it)->name != input) { return absl::nullopt; } return Operator(*it); } absl::optional<Operator> Operator::FindByDisplayName(absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(operators_by_display_name.cbegin(), operators_by_display_name.cend(), input, OperatorDataDisplayNameComparer{}); if (it == operators_by_name.cend() || (*it)->display_name != input) { return absl::nullopt; } return Operator(*it); } absl::optional<UnaryOperator> UnaryOperator::FindByName( absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(unary_operators_by_name.cbegin(), unary_operators_by_name.cend(), input, OperatorDataNameComparer{}); if (it == unary_operators_by_name.cend() || (*it)->name != input) { return absl::nullopt; } return UnaryOperator(*it); } absl::optional<UnaryOperator> UnaryOperator::FindByDisplayName( absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(unary_operators_by_display_name.cbegin(), unary_operators_by_display_name.cend(), input, OperatorDataDisplayNameComparer{}); if (it == unary_operators_by_display_name.cend() || (*it)->display_name != input) { return absl::nullopt; } return UnaryOperator(*it); } absl::optional<BinaryOperator> BinaryOperator::FindByName( absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(binary_operators_by_name.cbegin(), binary_operators_by_name.cend(), input, OperatorDataNameComparer{}); if (it == binary_operators_by_name.cend() || (*it)->name != input) { return absl::nullopt; } return BinaryOperator(*it); } absl::optional<BinaryOperator> BinaryOperator::FindByDisplayName( absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(binary_operators_by_display_name.cbegin(), binary_operators_by_display_name.cend(), input, OperatorDataDisplayNameComparer{}); if (it == binary_operators_by_display_name.cend() || (*it)->display_name != input) { return absl::nullopt; } return BinaryOperator(*it); } absl::optional<TernaryOperator> TernaryOperator::FindByName( absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(ternary_operators_by_name.cbegin(), ternary_operators_by_name.cend(), input, OperatorDataNameComparer{}); if (it == ternary_operators_by_name.cend() || (*it)->name != input) { return absl::nullopt; } return TernaryOperator(*it); } absl::optional<TernaryOperator> TernaryOperator::FindByDisplayName( absl::string_view input) { absl::call_once(operators_once_flag, InitializeOperators); if (input.empty()) { return absl::nullopt; } auto it = std::lower_bound(ternary_operators_by_display_name.cbegin(), ternary_operators_by_display_name.cend(), input, OperatorDataDisplayNameComparer{}); if (it == ternary_operators_by_display_name.cend() || (*it)->display_name != input) { return absl::nullopt; } return TernaryOperator(*it); } }
#include "base/operators.h" #include <type_traits> #include "absl/hash/hash_testing.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/internal/operators.h" #include "internal/testing.h" namespace cel { namespace { using testing::Eq; using testing::Optional; template <typename Op, typename OpId> void TestOperator(Op op, OpId id, absl::string_view name, absl::string_view display_name, int precedence, Arity arity) { EXPECT_EQ(op.id(), id); EXPECT_EQ(Operator(op).id(), static_cast<OperatorId>(id)); EXPECT_EQ(op.name(), name); EXPECT_EQ(op.display_name(), display_name); EXPECT_EQ(op.precedence(), precedence); EXPECT_EQ(op.arity(), arity); EXPECT_EQ(Operator(op).arity(), arity); EXPECT_EQ(Op(Operator(op)), op); } void TestUnaryOperator(UnaryOperator op, UnaryOperatorId id, absl::string_view name, absl::string_view display_name, int precedence) { TestOperator(op, id, name, display_name, precedence, Arity::kUnary); } void TestBinaryOperator(BinaryOperator op, BinaryOperatorId id, absl::string_view name, absl::string_view display_name, int precedence) { TestOperator(op, id, name, display_name, precedence, Arity::kBinary); } void TestTernaryOperator(TernaryOperator op, TernaryOperatorId id, absl::string_view name, absl::string_view display_name, int precedence) { TestOperator(op, id, name, display_name, precedence, Arity::kTernary); } TEST(Operator, TypeTraits) { EXPECT_FALSE(std::is_default_constructible_v<Operator>); EXPECT_TRUE(std::is_copy_constructible_v<Operator>); EXPECT_TRUE(std::is_move_constructible_v<Operator>); EXPECT_TRUE(std::is_copy_assignable_v<Operator>); EXPECT_TRUE(std::is_move_assignable_v<Operator>); EXPECT_FALSE((std::is_convertible_v<Operator, UnaryOperator>)); EXPECT_FALSE((std::is_convertible_v<Operator, BinaryOperator>)); EXPECT_FALSE((std::is_convertible_v<Operator, TernaryOperator>)); } TEST(UnaryOperator, TypeTraits) { EXPECT_FALSE(std::is_default_constructible_v<UnaryOperator>); EXPECT_TRUE(std::is_copy_constructible_v<UnaryOperator>); EXPECT_TRUE(std::is_move_constructible_v<UnaryOperator>); EXPECT_TRUE(std::is_copy_assignable_v<UnaryOperator>); EXPECT_TRUE(std::is_move_assignable_v<UnaryOperator>); EXPECT_TRUE((std::is_convertible_v<UnaryOperator, Operator>)); } TEST(BinaryOperator, TypeTraits) { EXPECT_FALSE(std::is_default_constructible_v<BinaryOperator>); EXPECT_TRUE(std::is_copy_constructible_v<BinaryOperator>); EXPECT_TRUE(std::is_move_constructible_v<BinaryOperator>); EXPECT_TRUE(std::is_copy_assignable_v<BinaryOperator>); EXPECT_TRUE(std::is_move_assignable_v<BinaryOperator>); EXPECT_TRUE((std::is_convertible_v<BinaryOperator, Operator>)); } TEST(TernaryOperator, TypeTraits) { EXPECT_FALSE(std::is_default_constructible_v<TernaryOperator>); EXPECT_TRUE(std::is_copy_constructible_v<TernaryOperator>); EXPECT_TRUE(std::is_move_constructible_v<TernaryOperator>); EXPECT_TRUE(std::is_copy_assignable_v<TernaryOperator>); EXPECT_TRUE(std::is_move_assignable_v<TernaryOperator>); EXPECT_TRUE((std::is_convertible_v<TernaryOperator, Operator>)); } #define CEL_UNARY_OPERATOR(id, symbol, name, precedence, arity) \ TEST(UnaryOperator, id) { \ TestUnaryOperator(UnaryOperator::id(), UnaryOperatorId::k##id, name, \ symbol, precedence); \ } CEL_INTERNAL_UNARY_OPERATORS_ENUM(CEL_UNARY_OPERATOR) #undef CEL_UNARY_OPERATOR #define CEL_BINARY_OPERATOR(id, symbol, name, precedence, arity) \ TEST(BinaryOperator, id) { \ TestBinaryOperator(BinaryOperator::id(), BinaryOperatorId::k##id, name, \ symbol, precedence); \ } CEL_INTERNAL_BINARY_OPERATORS_ENUM(CEL_BINARY_OPERATOR) #undef CEL_BINARY_OPERATOR #define CEL_TERNARY_OPERATOR(id, symbol, name, precedence, arity) \ TEST(TernaryOperator, id) { \ TestTernaryOperator(TernaryOperator::id(), TernaryOperatorId::k##id, name, \ symbol, precedence); \ } CEL_INTERNAL_TERNARY_OPERATORS_ENUM(CEL_TERNARY_OPERATOR) #undef CEL_TERNARY_OPERATOR TEST(Operator, FindByName) { EXPECT_THAT(Operator::FindByName("@in"), Optional(Eq(Operator::In()))); EXPECT_THAT(Operator::FindByName("_in_"), Optional(Eq(Operator::OldIn()))); EXPECT_THAT(Operator::FindByName("in"), Eq(absl::nullopt)); EXPECT_THAT(Operator::FindByName(""), Eq(absl::nullopt)); } TEST(Operator, FindByDisplayName) { EXPECT_THAT(Operator::FindByDisplayName("-"), Optional(Eq(Operator::Subtract()))); EXPECT_THAT(Operator::FindByDisplayName("@in"), Eq(absl::nullopt)); EXPECT_THAT(Operator::FindByDisplayName(""), Eq(absl::nullopt)); } TEST(UnaryOperator, FindByName) { EXPECT_THAT(UnaryOperator::FindByName("-_"), Optional(Eq(Operator::Negate()))); EXPECT_THAT(UnaryOperator::FindByName("_-_"), Eq(absl::nullopt)); EXPECT_THAT(UnaryOperator::FindByName(""), Eq(absl::nullopt)); } TEST(UnaryOperator, FindByDisplayName) { EXPECT_THAT(UnaryOperator::FindByDisplayName("-"), Optional(Eq(Operator::Negate()))); EXPECT_THAT(UnaryOperator::FindByDisplayName("&&"), Eq(absl::nullopt)); EXPECT_THAT(UnaryOperator::FindByDisplayName(""), Eq(absl::nullopt)); } TEST(BinaryOperator, FindByName) { EXPECT_THAT(BinaryOperator::FindByName("_-_"), Optional(Eq(Operator::Subtract()))); EXPECT_THAT(BinaryOperator::FindByName("-_"), Eq(absl::nullopt)); EXPECT_THAT(BinaryOperator::FindByName(""), Eq(absl::nullopt)); } TEST(BinaryOperator, FindByDisplayName) { EXPECT_THAT(BinaryOperator::FindByDisplayName("-"), Optional(Eq(Operator::Subtract()))); EXPECT_THAT(BinaryOperator::FindByDisplayName("!"), Eq(absl::nullopt)); EXPECT_THAT(BinaryOperator::FindByDisplayName(""), Eq(absl::nullopt)); } TEST(TernaryOperator, FindByName) { EXPECT_THAT(TernaryOperator::FindByName("_?_:_"), Optional(Eq(TernaryOperator::Conditional()))); EXPECT_THAT(TernaryOperator::FindByName("-_"), Eq(absl::nullopt)); EXPECT_THAT(TernaryOperator::FindByName(""), Eq(absl::nullopt)); } TEST(TernaryOperator, FindByDisplayName) { EXPECT_THAT(TernaryOperator::FindByDisplayName(""), Eq(absl::nullopt)); EXPECT_THAT(TernaryOperator::FindByDisplayName("!"), Eq(absl::nullopt)); } TEST(Operator, SupportsAbslHash) { #define CEL_OPERATOR(id, symbol, name, precedence, arity) \ Operator(Operator::id()), EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {CEL_INTERNAL_OPERATORS_ENUM(CEL_OPERATOR)})); #undef CEL_OPERATOR } TEST(UnaryOperator, SupportsAbslHash) { #define CEL_UNARY_OPERATOR(id, symbol, name, precedence, arity) \ UnaryOperator::id(), EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {CEL_INTERNAL_UNARY_OPERATORS_ENUM(CEL_UNARY_OPERATOR)})); #undef CEL_UNARY_OPERATOR } TEST(BinaryOperator, SupportsAbslHash) { #define CEL_BINARY_OPERATOR(id, symbol, name, precedence, arity) \ BinaryOperator::id(), EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {CEL_INTERNAL_BINARY_OPERATORS_ENUM(CEL_BINARY_OPERATOR)})); #undef CEL_BINARY_OPERATOR } } }
14
cpp
google/cel-cpp
json
extensions/protobuf/internal/json.cc
extensions/protobuf/internal/json_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_JSON_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_JSON_H_ #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "common/json.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<Json> ProtoMessageToJson(AnyToJsonConverter& converter, const google::protobuf::Message& message); absl::StatusOr<Json> ProtoFieldToJson( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field); absl::StatusOr<JsonArray> ProtoRepeatedFieldToJsonArray( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field); absl::StatusOr<JsonObject> ProtoMapFieldToJsonObject( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field); Json ProtoEnumToJson(absl::Nonnull<const google::protobuf::EnumDescriptor*> descriptor, int value); Json ProtoEnumToJson( absl::Nonnull<const google::protobuf::EnumValueDescriptor*> descriptor); } #endif #include "extensions/protobuf/internal/json.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "google/protobuf/duration.pb.h" #include "google/protobuf/empty.pb.h" #include "google/protobuf/field_mask.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/wrappers.pb.h" #include "absl/base/nullability.h" #include "absl/base/optimization.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/time/time.h" #include "absl/types/variant.h" #include "common/any.h" #include "common/json.h" #include "common/value.h" #include "extensions/protobuf/internal/any.h" #include "extensions/protobuf/internal/duration.h" #include "extensions/protobuf/internal/field_mask.h" #include "extensions/protobuf/internal/field_mask_lite.h" #include "extensions/protobuf/internal/map_reflection.h" #include "extensions/protobuf/internal/struct.h" #include "extensions/protobuf/internal/struct_lite.h" #include "extensions/protobuf/internal/timestamp.h" #include "extensions/protobuf/internal/wrappers.h" #include "internal/status_macros.h" #include "internal/time.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/map_field.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { namespace { absl::StatusOr<Json> ProtoSingularFieldToJson( AnyToJsonConverter& converter, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { switch (field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return JsonInt(reflection->GetInt32(message, field)); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return JsonInt(reflection->GetInt64(message, field)); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return JsonUint(reflection->GetUInt32(message, field)); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return JsonUint(reflection->GetUInt64(message, field)); case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return reflection->GetDouble(message, field); case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return static_cast<double>(reflection->GetFloat(message, field)); case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return reflection->GetBool(message, field); case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: return ProtoEnumToJson(field->enum_type(), reflection->GetEnumValue(message, field)); case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { std::string scratch; const auto& value = reflection->GetStringReference(message, field, &scratch); return JsonBytes(value); } return reflection->GetCord(message, field); } case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageToJson(converter, reflection->GetMessage(message, field)); default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer field type: ", google::protobuf::FieldDescriptor::CppTypeName(field->cpp_type()))); } } absl::StatusOr<JsonString> ProtoMapKeyToJsonString(const google::protobuf::MapKey& key) { switch (key.type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return key.GetBoolValue() ? JsonString("true") : JsonString("false"); case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return JsonString(absl::StrCat(key.GetInt32Value())); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return JsonString(absl::StrCat(key.GetInt64Value())); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return JsonString(absl::StrCat(key.GetUInt32Value())); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return JsonString(absl::StrCat(key.GetUInt64Value())); case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return JsonString(key.GetStringValue()); default: return TypeConversionError( google::protobuf::FieldDescriptor::CppTypeName(key.type()), "STRING") .NativeValue(); } } absl::StatusOr<Json> ProtoMapValueToJson( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueRef& value) { switch (field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return JsonInt(value.GetInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return JsonInt(value.GetInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return JsonUint(value.GetUInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return JsonUint(value.GetUInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return value.GetDoubleValue(); case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return static_cast<double>(value.GetFloatValue()); case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return value.GetBoolValue(); case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: return ProtoEnumToJson(field->enum_type(), value.GetEnumValue()); case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { return JsonBytes(value.GetStringValue()); } return JsonString(value.GetStringValue()); } case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageToJson(converter, value.GetMessageValue()); default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer field type: ", google::protobuf::FieldDescriptor::CppTypeName(field->cpp_type()))); } } absl::StatusOr<Json> ProtoAnyToJson(AnyToJsonConverter& converter, const google::protobuf::Message& message) { CEL_ASSIGN_OR_RETURN(auto any, UnwrapDynamicAnyProto(message)); absl::string_view type_name; if (!ParseTypeUrl(any.type_url(), &type_name)) { return absl::InvalidArgumentError( "invalid `google.protobuf.Any` field `type_url`"); } JsonObjectBuilder builder; builder.reserve(2); builder.insert_or_assign(JsonString("@type"), JsonString(any.type_url())); if (type_name == "google.protobuf.BoolValue") { google::protobuf::BoolValue value_message; if (!value_message.ParseFromCord(any.value())) { return absl::InvalidArgumentError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), value_message.value()); return std::move(builder).Build(); } if (type_name == "google.protobuf.Int32Value") { google::protobuf::Int32Value value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonInt(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.Int64Value") { google::protobuf::Int64Value value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonInt(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.UInt32Value") { google::protobuf::UInt32Value value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonUint(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.UInt64Value") { google::protobuf::UInt64Value value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonUint(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.FloatValue") { google::protobuf::FloatValue value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), static_cast<double>(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.DoubleValue") { google::protobuf::DoubleValue value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), value_message.value()); return std::move(builder).Build(); } if (type_name == "google.protobuf.BytesValue") { google::protobuf::BytesValue value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonBytes(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.StringValue") { google::protobuf::StringValue value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonString(value_message.value())); return std::move(builder).Build(); } if (type_name == "google.protobuf.FieldMask") { google::protobuf::FieldMask value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } CEL_ASSIGN_OR_RETURN(auto json_value, GeneratedFieldMaskProtoToJsonString(value_message)); builder.insert_or_assign(JsonString("value"), std::move(json_value)); return std::move(builder).Build(); } if (type_name == "google.protobuf.ListValue") { google::protobuf::ListValue value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } CEL_ASSIGN_OR_RETURN(auto json_value, GeneratedListValueProtoToJson(value_message)); builder.insert_or_assign(JsonString("value"), std::move(json_value)); return std::move(builder).Build(); } if (type_name == "google.protobuf.Struct") { google::protobuf::Struct value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } CEL_ASSIGN_OR_RETURN(auto json_value, GeneratedStructProtoToJson(value_message)); builder.insert_or_assign(JsonString("value"), std::move(json_value)); return std::move(builder).Build(); } if (type_name == "google.protobuf.Value") { google::protobuf::Value value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } CEL_ASSIGN_OR_RETURN(auto json_value, GeneratedValueProtoToJson(value_message)); builder.insert_or_assign(JsonString("value"), std::move(json_value)); return std::move(builder).Build(); } if (type_name == "google.protobuf.Duration") { google::protobuf::Duration value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } CEL_ASSIGN_OR_RETURN(auto json_value, internal::EncodeDurationToJson( absl::Seconds(value_message.seconds()) + absl::Nanoseconds(value_message.nanos()))); builder.insert_or_assign(JsonString("value"), JsonString(json_value)); return std::move(builder).Build(); } if (type_name == "google.protobuf.Timestamp") { google::protobuf::Timestamp value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } CEL_ASSIGN_OR_RETURN( auto json_value, internal::EncodeTimestampToJson( absl::UnixEpoch() + absl::Seconds(value_message.seconds()) + absl::Nanoseconds(value_message.nanos()))); builder.insert_or_assign(JsonString("value"), JsonString(json_value)); return std::move(builder).Build(); } if (type_name == "google.protobuf.Empty") { google::protobuf::Empty value_message; if (!value_message.ParseFromCord(any.value())) { return absl::UnknownError( absl::StrCat("failed to parse `", value_message.GetTypeName(), "`")); } builder.insert_or_assign(JsonString("value"), JsonObject()); return std::move(builder).Build(); } if (type_name == "google.protobuf.Any") { return absl::InvalidArgumentError( "refusing to convert recursive `google.protobuf.Any` to JSON"); } CEL_ASSIGN_OR_RETURN(auto json_value, converter.ConvertToJson(any.type_url(), any.value())); if (!absl::holds_alternative<JsonObject>(json_value)) { return absl::InternalError("expected JSON object"); } const auto& json_object = absl::get<JsonObject>(json_value); builder.reserve(json_object.size() + 1); for (const auto& json_entry : json_object) { builder.insert_or_assign(json_entry.first, json_entry.second); } return std::move(builder).Build(); } } absl::StatusOr<Json> ProtoMessageToJson(AnyToJsonConverter& converter, const google::protobuf::Message& message) { const auto* descriptor = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InvalidArgumentError( absl::StrCat("`", message.GetTypeName(), "` is missing descriptor")); } const auto* reflection = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflection == nullptr)) { return absl::InvalidArgumentError( absl::StrCat("`", message.GetTypeName(), "` is missing reflection")); } switch (descriptor->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicDoubleValueProto(message)); return value; } case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicFloatValueProto(message)); return value; } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicInt64ValueProto(message)); return JsonInt(value); } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicUInt64ValueProto(message)); return JsonUint(value); } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicInt32ValueProto(message)); return JsonInt(value); } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicUInt32ValueProto(message)); return JsonUint(value); } case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicStringValueProto(message)); return value; } case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicBytesValueProto(message)); return JsonBytes(value); } case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicBoolValueProto(message)); return value; } case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY: return ProtoAnyToJson(converter, message); case google::protobuf::Descriptor::WELLKNOWNTYPE_FIELDMASK: { CEL_ASSIGN_OR_RETURN(auto value, DynamicFieldMaskProtoToJsonString(message)); return value; } case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicDurationProto(message)); CEL_ASSIGN_OR_RETURN(auto json, internal::EncodeDurationToJson(value)); return JsonString(std::move(json)); } case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicTimestampProto(message)); CEL_ASSIGN_OR_RETURN(auto json, internal::EncodeTimestampToJson(value)); return JsonString(std::move(json)); } case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE: return DynamicValueProtoToJson(message); case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE: return DynamicListValueProtoToJson(message); case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT: return DynamicStructProtoToJson(message); default: break; } if (descriptor->full_name() == "google.protobuf.Empty") { return JsonObject(); } JsonObjectBuilder builder; std::vector<const google::protobuf::FieldDescriptor*> fields; reflection->ListFields(message, &fields); builder.reserve(fields.size()); for (const auto* field : fields) { CEL_ASSIGN_OR_RETURN( auto field_value, ProtoFieldToJson(converter, reflection, message, field)); builder.insert_or_assign(JsonString(field->json_name()), std::move(field_value)); } return std::move(builder).Build(); } absl::StatusOr<Json> ProtoFieldToJson( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { if (field->is_map()) { return ProtoMapFieldToJsonObject(converter, reflection, message, field); } if (field->is_repeated()) { return ProtoRepeatedFieldToJsonArray(converter, reflection, message, field); } return ProtoSingularFieldToJson(converter, message, reflection, field); } absl::StatusOr<JsonObject> ProtoMapFieldToJsonObject( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { ABSL_DCHECK(field->is_map()); JsonObjectBuilder builder; const auto field_size = reflection->FieldSize(message, field); builder.reserve(static_cast<size_t>(field_size)); auto begin = MapBegin(*reflection, message, *field); auto end = MapEnd(*reflection, message, *field); while (begin != end) { CEL_ASSIGN_OR_RETURN(auto key, ProtoMapKeyToJsonString(begin.GetKey())); CEL_ASSIGN_OR_RETURN( auto value, ProtoMapValueToJson(converter, field->message_type()->map_value(), begin.GetValueRef())); builder.insert_or_assign(std::move(key), std::move(value)); ++begin; } return std::move(builder).Build(); } absl::StatusOr<JsonArray> ProtoRepeatedFieldToJsonArray( AnyToJsonConverter& converter, absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { ABSL_DCHECK(field->is_repeated() && !field->is_map()); JsonArrayBuilder builder; const auto field_size = reflection->FieldSize(message, field); builder.reserve(static_cast<size_t>(field_size)); switch (field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_INT32: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back( JsonInt(reflection->GetRepeatedInt32(message, field, field_index))); } break; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back( JsonInt(reflection->GetRepeatedInt64(message, field, field_index))); } break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back(JsonUint( reflection->GetRepeatedUInt32(message, field, field_index))); } break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back(JsonUint( reflection->GetRepeatedUInt64(message, field, field_index))); } break; case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back( reflection->GetRepeatedDouble(message, field, field_index)); } break; case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back(static_cast<double>( reflection->GetRepeatedFloat(message, field, field_index))); } break; case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back( reflection->GetRepeatedBool(message, field, field_index)); } break; case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back(ProtoEnumToJson( field->enum_type(), reflection->GetRepeatedEnumValue(message, field, field_index))); } break; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { std::string scratch; for (int field_index = 0; field_index < field_size; ++field_index) { builder.push_back(JsonBytes(reflection->GetRepeatedStringReference( message, field, field_index, &scratch))); } } else { std::string scratch; for (int field_index = 0; field_index < field_size; ++field_index) { const auto& field_value = reflection->GetRepeatedStringReference( message, field, field_index, &scratch); if (&field_value == &scratch) { builder.push_back(JsonString(std::move(scratch))); } else { builder.push_back(JsonString(field_value)); } } } break; case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: for (int field_index = 0; field_index < field_size; ++field_index) { CEL_ASSIGN_OR_RETURN( auto json, ProtoMessageToJson(converter, reflection->GetRepeatedMessage( message, field, field_index))); builder.push_back(std::move(json)); } break; default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer field type: ", google::protobuf::FieldDescriptor::CppTypeName(field->cpp_type()))); } return std::move(builder).Build(); } Json ProtoEnumToJson(absl::Nonnull<const google::protobuf::EnumDescriptor*> descriptor, int value) { if (descriptor->full_name() == "google.protobuf.NullValue") { return kJsonNull; } if (const auto* value_descriptor = descriptor->FindValueByNumber(value); value_descriptor != nullptr) { return ProtoEnumToJson(value_descriptor); } return JsonInt(value); } Json ProtoEnumToJson( absl::Nonnull<const google::protobuf::EnumValueDescriptor*> descriptor) { if (descriptor->type()->full_name() == "google.protobuf.NullValue") { return kJsonNull; } if (!descriptor->name().empty()) { return JsonString(descriptor->name()); } return JsonInt(descriptor->number()); } }
#include "extensions/protobuf/internal/json.h" #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/log/absl_check.h" #include "absl/strings/string_view.h" #include "common/json.h" #include "common/value_testing.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/text_format.h" namespace cel::extensions::protobuf_internal { namespace { using ::google::api::expr::test::v1::proto2::TestAllTypes; using testing::_; using testing::Eq; using testing::VariantWith; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; template <typename T> T ParseTextOrDie(absl::string_view text) { T proto; ABSL_CHECK(google::protobuf::TextFormat::ParseFromString(text, &proto)); return proto; } class ProtoJsonTest : public common_internal::ThreadCompatibleValueTest<> {}; TEST_P(ProtoJsonTest, Bool) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_bool: true )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleBool"), true}})))); } TEST_P(ProtoJsonTest, Int32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_int32: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleInt32"), 1.0}})))); } TEST_P(ProtoJsonTest, Int64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_int64: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleInt64"), 1.0}})))); } TEST_P(ProtoJsonTest, UInt32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_uint32: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleUint32"), 1.0}})))); } TEST_P(ProtoJsonTest, UInt64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_uint64: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleUint64"), 1.0}})))); } TEST_P(ProtoJsonTest, Float) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_float: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleFloat"), 1.0}})))); } TEST_P(ProtoJsonTest, Double) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_double: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleDouble"), 1.0}})))); } TEST_P(ProtoJsonTest, Bytes) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_bytes: "foo" )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleBytes"), JsonBytes("foo")}})))); } TEST_P(ProtoJsonTest, String) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_string: "foo" )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleString"), JsonString("foo")}})))); } TEST_P(ProtoJsonTest, Null) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( null_value: NULL_VALUE )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("nullValue"), kJsonNull}})))); } TEST_P(ProtoJsonTest, Enum) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_nested_enum: BAR )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("singleNestedEnum"), JsonString("BAR")}})))); } TEST_P(ProtoJsonTest, Message) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( single_nested_message { bb: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleNestedMessage"), MakeJsonObject({{JsonString("bb"), 1.0}})}})))); } TEST_P(ProtoJsonTest, BoolValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::BoolValue::default_instance()), IsOkAndHolds(VariantWith<JsonBool>(false))); } TEST_P(ProtoJsonTest, Int32Value) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::Int32Value::default_instance()), IsOkAndHolds(VariantWith<JsonNumber>(0))); } TEST_P(ProtoJsonTest, Int64Value) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::Int64Value::default_instance()), IsOkAndHolds(VariantWith<JsonNumber>(0))); } TEST_P(ProtoJsonTest, UInt32Value) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::UInt32Value::default_instance()), IsOkAndHolds(VariantWith<JsonNumber>(0))); } TEST_P(ProtoJsonTest, UInt64Value) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::UInt64Value::default_instance()), IsOkAndHolds(VariantWith<JsonNumber>(0))); } TEST_P(ProtoJsonTest, FloatValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::FloatValue::default_instance()), IsOkAndHolds(VariantWith<JsonNumber>(0))); } TEST_P(ProtoJsonTest, DoubleValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::DoubleValue::default_instance()), IsOkAndHolds(VariantWith<JsonNumber>(0))); } TEST_P(ProtoJsonTest, BytesValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::BytesValue::default_instance()), IsOkAndHolds(VariantWith<JsonString>(JsonString("")))); } TEST_P(ProtoJsonTest, StringValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::StringValue::default_instance()), IsOkAndHolds(VariantWith<JsonString>(JsonString("")))); } TEST_P(ProtoJsonTest, Duration) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::Duration::default_instance()), IsOkAndHolds(VariantWith<JsonString>(JsonString("0s")))); } TEST_P(ProtoJsonTest, Timestamp) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::Timestamp::default_instance()), IsOkAndHolds( VariantWith<JsonString>(JsonString("1970-01-01T00:00:00Z")))); } TEST_P(ProtoJsonTest, FieldMask) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::FieldMask::default_instance()), IsOkAndHolds(VariantWith<JsonString>(JsonString("")))); } TEST_P(ProtoJsonTest, Value) { EXPECT_THAT(ProtoMessageToJson(value_manager(), google::protobuf::Value::default_instance()), IsOkAndHolds(VariantWith<JsonNull>(kJsonNull))); } TEST_P(ProtoJsonTest, Struct) { EXPECT_THAT(ProtoMessageToJson(value_manager(), google::protobuf::Struct::default_instance()), IsOkAndHolds(VariantWith<JsonObject>(JsonObject()))); } TEST_P(ProtoJsonTest, Empty) { EXPECT_THAT(ProtoMessageToJson(value_manager(), google::protobuf::Empty::default_instance()), IsOkAndHolds(VariantWith<JsonObject>(JsonObject()))); } TEST_P(ProtoJsonTest, TestAllTypes) { TestAllTypes message; message.set_single_int64(1); EXPECT_THAT(ProtoMessageToJson(value_manager(), message), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("singleInt64"), Json(1.0)}})))); } TEST_P(ProtoJsonTest, ListValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), google::protobuf::ListValue::default_instance()), IsOkAndHolds(VariantWith<JsonArray>(JsonArray()))); } TEST_P(ProtoJsonTest, RepeatedBool) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_bool: true )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedBool"), MakeJsonArray({true})}})))); } TEST_P(ProtoJsonTest, RepeatedInt32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_int32: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedInt32"), MakeJsonArray({1.0})}})))); } TEST_P(ProtoJsonTest, RepeatedInt64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_int64: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedInt64"), MakeJsonArray({1.0})}})))); } TEST_P(ProtoJsonTest, RepeatedUInt32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_uint32: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedUint32"), MakeJsonArray({1.0})}})))); } TEST_P(ProtoJsonTest, RepeatedUInt64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_uint64: 1 )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedUint64"), MakeJsonArray({1.0})}})))); } TEST_P(ProtoJsonTest, RepeatedFloat) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_float: 1.0 )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedFloat"), MakeJsonArray({1.0})}})))); } TEST_P(ProtoJsonTest, RepeatedDouble) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_double: 1.0 )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedDouble"), MakeJsonArray({1.0})}})))); } TEST_P(ProtoJsonTest, RepeatedBytes) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_bytes: "foo" )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("repeatedBytes"), MakeJsonArray({JsonBytes("foo")})}})))); } TEST_P(ProtoJsonTest, RepeatedString) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_string: "foo" )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("repeatedString"), MakeJsonArray({JsonString("foo")})}})))); } TEST_P(ProtoJsonTest, RepeatedNull) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_null_value: NULL_VALUE )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedNullValue"), MakeJsonArray({kJsonNull})}})))); } TEST_P(ProtoJsonTest, RepeatedEnum) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_nested_enum: FOO )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("repeatedNestedEnum"), MakeJsonArray({JsonString("FOO")})}})))); } TEST_P(ProtoJsonTest, RepeatedMessage) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( repeated_nested_message { bb: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("repeatedNestedMessage"), MakeJsonArray({MakeJsonObject({{JsonString("bb"), 1.0}})})}})))); } TEST_P(ProtoJsonTest, MapBoolBool) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_bool_bool { key: true value: true } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapBoolBool"), MakeJsonObject({{JsonString("true"), true}})}})))); } TEST_P(ProtoJsonTest, MapInt32Int32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_int32_int32 { key: 1 value: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapInt32Int32"), MakeJsonObject({{JsonString("1"), 1.0}})}})))); } TEST_P(ProtoJsonTest, MapInt64Int64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_int64_int64 { key: 1 value: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapInt64Int64"), MakeJsonObject({{JsonString("1"), 1.0}})}})))); } TEST_P(ProtoJsonTest, MapUint32Uint32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_uint32_uint32 { key: 1 value: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapUint32Uint32"), MakeJsonObject({{JsonString("1"), 1.0}})}})))); } TEST_P(ProtoJsonTest, MapUint64Uint64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_uint64_uint64 { key: 1 value: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapUint64Uint64"), MakeJsonObject({{JsonString("1"), 1.0}})}})))); } TEST_P(ProtoJsonTest, MapStringString) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_string_string { key: "foo" value: "foo" } )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("mapStringString"), MakeJsonObject({{JsonString("foo"), JsonString("foo")}})}})))); } TEST_P(ProtoJsonTest, MapStringFloat) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_string_float { key: "foo" value: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapStringFloat"), MakeJsonObject({{JsonString("foo"), 1.0}})}})))); } TEST_P(ProtoJsonTest, MapStringDouble) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_string_double { key: "foo" value: 1 } )pb")), IsOkAndHolds(VariantWith<JsonObject>( MakeJsonObject({{JsonString("mapStringDouble"), MakeJsonObject({{JsonString("foo"), 1.0}})}})))); } TEST_P(ProtoJsonTest, MapStringNull) { EXPECT_THAT(ProtoMessageToJson( value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_string_null_value { key: "foo" value: NULL_VALUE } )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("mapStringNullValue"), MakeJsonObject({{JsonString("foo"), kJsonNull}})}})))); } TEST_P(ProtoJsonTest, MapStringEnum) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_string_enum { key: "foo" value: BAR } )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("mapStringEnum"), MakeJsonObject({{JsonString("foo"), JsonString("BAR")}})}})))); } TEST_P(ProtoJsonTest, MapStringMessage) { EXPECT_THAT( ProtoMessageToJson(value_manager(), ParseTextOrDie<TestAllTypes>(R"pb( map_string_message { key: "foo" value: { bb: 1 } } )pb")), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("mapStringMessage"), MakeJsonObject({{JsonString("foo"), MakeJsonObject({{JsonString("bb"), 1.0}})}})}})))); } template <typename T> google::protobuf::Any MakeAnyProto() { google::protobuf::Any any; ABSL_CHECK(any.PackFrom(T::default_instance())); return any; } TEST_P(ProtoJsonTest, AnyBool) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::BoolValue>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.BoolValue")}, {JsonString("value"), false}})))); } TEST_P(ProtoJsonTest, AnyInt32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Int32Value>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Int32Value")}, {JsonString("value"), 0.0}})))); } TEST_P(ProtoJsonTest, AnyInt64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Int64Value>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Int64Value")}, {JsonString("value"), 0.0}})))); } TEST_P(ProtoJsonTest, AnyUInt32) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::UInt32Value>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.UInt32Value")}, {JsonString("value"), 0.0}})))); } TEST_P(ProtoJsonTest, AnyUInt64) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::UInt64Value>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.UInt64Value")}, {JsonString("value"), 0.0}})))); } TEST_P(ProtoJsonTest, AnyFloat) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::FloatValue>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.FloatValue")}, {JsonString("value"), 0.0}})))); } TEST_P(ProtoJsonTest, AnyDouble) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::DoubleValue>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.DoubleValue")}, {JsonString("value"), 0.0}})))); } TEST_P(ProtoJsonTest, AnyBytes) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::BytesValue>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.BytesValue")}, {JsonString("value"), JsonString("")}})))); } TEST_P(ProtoJsonTest, AnyString) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::StringValue>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.StringValue")}, {JsonString("value"), JsonString("")}})))); } TEST_P(ProtoJsonTest, AnyDuration) { EXPECT_THAT(ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Duration>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Duration")}, {JsonString("value"), JsonString("0s")}})))); } TEST_P(ProtoJsonTest, AnyTimestamp) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Timestamp>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Timestamp")}, {JsonString("value"), JsonString("1970-01-01T00:00:00Z")}})))); } TEST_P(ProtoJsonTest, AnyFieldMask) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::FieldMask>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.FieldMask")}, {JsonString("value"), JsonString("")}})))); } TEST_P(ProtoJsonTest, AnyValue) { EXPECT_THAT(ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Value>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Value")}, {JsonString("value"), kJsonNull}})))); } TEST_P(ProtoJsonTest, AnyListValue) { EXPECT_THAT( ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::ListValue>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.ListValue")}, {JsonString("value"), JsonArray()}})))); } TEST_P(ProtoJsonTest, AnyStruct) { EXPECT_THAT(ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Struct>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Struct")}, {JsonString("value"), JsonObject()}})))); } TEST_P(ProtoJsonTest, AnyEmpty) { EXPECT_THAT(ProtoMessageToJson(value_manager(), MakeAnyProto<google::protobuf::Empty>()), IsOkAndHolds(VariantWith<JsonObject>(MakeJsonObject( {{JsonString("@type"), JsonString("type.googleapis.com/google.protobuf.Empty")}, {JsonString("value"), JsonObject()}})))); } TEST_P(ProtoJsonTest, EnumBehavior) { EXPECT_THAT( ProtoEnumToJson(google::protobuf::GetEnumDescriptor<TestAllTypes::NestedEnum>(), 1), VariantWith<JsonString>(Eq(JsonString("BAR")))); EXPECT_THAT(ProtoEnumToJson( google::protobuf::GetEnumDescriptor<TestAllTypes::NestedEnum>(), 99), VariantWith<JsonNumber>(Eq(99.0))); } TEST_P(ProtoJsonTest, NullBehavior) { EXPECT_THAT(ProtoEnumToJson( google::protobuf::GetEnumDescriptor<google::protobuf::NullValue>(), 0), VariantWith<JsonNull>(_)); EXPECT_THAT(ProtoEnumToJson( google::protobuf::GetEnumDescriptor<google::protobuf::NullValue>(), 99), VariantWith<JsonNull>(_)); } INSTANTIATE_TEST_SUITE_P( ProtoJsonTest, ProtoJsonTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoJsonTest::ToString); } }
15
cpp
google/cel-cpp
reference
common/reference.cc
common/reference_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_REFERENCE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_REFERENCE_H_ #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "common/constant.h" namespace cel { class Reference; class VariableReference; class FunctionReference; using ReferenceKind = absl::variant<VariableReference, FunctionReference>; class VariableReference final { public: bool has_value() const { return value_.has_value(); } void set_value(Constant value) { value_ = std::move(value); } const Constant& value() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return value_; } Constant& mutable_value() ABSL_ATTRIBUTE_LIFETIME_BOUND { return value_; } ABSL_MUST_USE_RESULT Constant release_value() { using std::swap; Constant value; swap(mutable_value(), value); return value; } friend void swap(VariableReference& lhs, VariableReference& rhs) noexcept { using std::swap; swap(lhs.value_, rhs.value_); } private: friend class Reference; static const VariableReference& default_instance(); Constant value_; }; inline bool operator==(const VariableReference& lhs, const VariableReference& rhs) { return lhs.value() == rhs.value(); } inline bool operator!=(const VariableReference& lhs, const VariableReference& rhs) { return !operator==(lhs, rhs); } class FunctionReference final { public: const std::vector<std::string>& overloads() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return overloads_; } void set_overloads(std::vector<std::string> overloads) { mutable_overloads() = std::move(overloads); } std::vector<std::string>& mutable_overloads() ABSL_ATTRIBUTE_LIFETIME_BOUND { return overloads_; } ABSL_MUST_USE_RESULT std::vector<std::string> release_overloads() { std::vector<std::string> overloads; overloads.swap(mutable_overloads()); return overloads; } friend void swap(FunctionReference& lhs, FunctionReference& rhs) noexcept { using std::swap; swap(lhs.overloads_, rhs.overloads_); } private: friend class Reference; static const FunctionReference& default_instance(); std::vector<std::string> overloads_; }; inline bool operator==(const FunctionReference& lhs, const FunctionReference& rhs) { return absl::c_equal(lhs.overloads(), rhs.overloads()); } inline bool operator!=(const FunctionReference& lhs, const FunctionReference& rhs) { return !operator==(lhs, rhs); } class Reference final { public: const std::string& name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return name_; } void set_name(std::string name) { name_ = std::move(name); } void set_name(absl::string_view name) { name_.assign(name.data(), name.size()); } void set_name(const char* name) { set_name(absl::NullSafeStringView(name)); } ABSL_MUST_USE_RESULT std::string release_name() { std::string name; name.swap(name_); return name; } void set_kind(ReferenceKind kind) { kind_ = std::move(kind); } const ReferenceKind& kind() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return kind_; } ReferenceKind& mutable_kind() ABSL_ATTRIBUTE_LIFETIME_BOUND { return kind_; } ABSL_MUST_USE_RESULT ReferenceKind release_kind() { using std::swap; ReferenceKind kind; swap(kind, kind_); return kind; } ABSL_MUST_USE_RESULT bool has_variable() const { return absl::holds_alternative<VariableReference>(kind()); } ABSL_MUST_USE_RESULT const VariableReference& variable() const ABSL_ATTRIBUTE_LIFETIME_BOUND { if (const auto* alt = absl::get_if<VariableReference>(&kind()); alt) { return *alt; } return VariableReference::default_instance(); } void set_variable(VariableReference variable) { mutable_variable() = std::move(variable); } VariableReference& mutable_variable() ABSL_ATTRIBUTE_LIFETIME_BOUND { if (!has_variable()) { mutable_kind().emplace<VariableReference>(); } return absl::get<VariableReference>(mutable_kind()); } ABSL_MUST_USE_RESULT VariableReference release_variable() { VariableReference variable_reference; if (auto* alt = absl::get_if<VariableReference>(&mutable_kind()); alt) { variable_reference = std::move(*alt); } mutable_kind().emplace<VariableReference>(); return variable_reference; } ABSL_MUST_USE_RESULT bool has_function() const { return absl::holds_alternative<FunctionReference>(kind()); } ABSL_MUST_USE_RESULT const FunctionReference& function() const ABSL_ATTRIBUTE_LIFETIME_BOUND { if (const auto* alt = absl::get_if<FunctionReference>(&kind()); alt) { return *alt; } return FunctionReference::default_instance(); } void set_function(FunctionReference function) { mutable_function() = std::move(function); } FunctionReference& mutable_function() ABSL_ATTRIBUTE_LIFETIME_BOUND { if (!has_function()) { mutable_kind().emplace<FunctionReference>(); } return absl::get<FunctionReference>(mutable_kind()); } ABSL_MUST_USE_RESULT FunctionReference release_function() { FunctionReference function_reference; if (auto* alt = absl::get_if<FunctionReference>(&mutable_kind()); alt) { function_reference = std::move(*alt); } mutable_kind().emplace<VariableReference>(); return function_reference; } friend void swap(Reference& lhs, Reference& rhs) noexcept { using std::swap; swap(lhs.name_, rhs.name_); swap(lhs.kind_, rhs.kind_); } private: std::string name_; ReferenceKind kind_; }; inline bool operator==(const Reference& lhs, const Reference& rhs) { return lhs.name() == rhs.name() && lhs.kind() == rhs.kind(); } inline bool operator!=(const Reference& lhs, const Reference& rhs) { return !operator==(lhs, rhs); } inline Reference MakeVariableReference(std::string name) { Reference reference; reference.set_name(std::move(name)); reference.mutable_kind().emplace<VariableReference>(); return reference; } inline Reference MakeConstantVariableReference(std::string name, Constant constant) { Reference reference; reference.set_name(std::move(name)); reference.mutable_kind().emplace<VariableReference>().set_value( std::move(constant)); return reference; } inline Reference MakeFunctionReference(std::string name, std::vector<std::string> overloads) { Reference reference; reference.set_name(std::move(name)); reference.mutable_kind().emplace<FunctionReference>().set_overloads( std::move(overloads)); return reference; } } #endif #include "common/reference.h" #include "absl/base/no_destructor.h" namespace cel { const VariableReference& VariableReference::default_instance() { static const absl::NoDestructor<VariableReference> instance; return *instance; } const FunctionReference& FunctionReference::default_instance() { static const absl::NoDestructor<FunctionReference> instance; return *instance; } }
#include "common/reference.h" #include <cstdint> #include <string> #include <vector> #include "common/constant.h" #include "internal/testing.h" namespace cel { namespace { using testing::_; using testing::ElementsAre; using testing::Eq; using testing::IsEmpty; using testing::VariantWith; TEST(VariableReference, Value) { VariableReference variable_reference; EXPECT_FALSE(variable_reference.has_value()); EXPECT_EQ(variable_reference.value(), Constant{}); Constant value; value.set_bool_value(true); variable_reference.set_value(value); EXPECT_TRUE(variable_reference.has_value()); EXPECT_EQ(variable_reference.value(), value); EXPECT_EQ(variable_reference.release_value(), value); EXPECT_EQ(variable_reference.value(), Constant{}); } TEST(VariableReference, Equality) { VariableReference variable_reference; EXPECT_EQ(variable_reference, VariableReference{}); variable_reference.mutable_value().set_bool_value(true); EXPECT_NE(variable_reference, VariableReference{}); } TEST(FunctionReference, Overloads) { FunctionReference function_reference; EXPECT_THAT(function_reference.overloads(), IsEmpty()); function_reference.mutable_overloads().reserve(2); function_reference.mutable_overloads().push_back("foo"); function_reference.mutable_overloads().push_back("bar"); EXPECT_THAT(function_reference.release_overloads(), ElementsAre("foo", "bar")); EXPECT_THAT(function_reference.overloads(), IsEmpty()); } TEST(FunctionReference, Equality) { FunctionReference function_reference; EXPECT_EQ(function_reference, FunctionReference{}); function_reference.mutable_overloads().push_back("foo"); EXPECT_NE(function_reference, FunctionReference{}); } TEST(Reference, Name) { Reference reference; EXPECT_THAT(reference.name(), IsEmpty()); reference.set_name("foo"); EXPECT_EQ(reference.name(), "foo"); EXPECT_EQ(reference.release_name(), "foo"); EXPECT_THAT(reference.name(), IsEmpty()); } TEST(Reference, Variable) { Reference reference; EXPECT_THAT(reference.kind(), VariantWith<VariableReference>(_)); EXPECT_TRUE(reference.has_variable()); EXPECT_THAT(reference.release_variable(), Eq(VariableReference{})); EXPECT_TRUE(reference.has_variable()); } TEST(Reference, Function) { Reference reference; EXPECT_FALSE(reference.has_function()); EXPECT_THAT(reference.function(), Eq(FunctionReference{})); reference.mutable_function(); EXPECT_TRUE(reference.has_function()); EXPECT_THAT(reference.variable(), Eq(VariableReference{})); EXPECT_THAT(reference.kind(), VariantWith<FunctionReference>(_)); EXPECT_THAT(reference.release_function(), Eq(FunctionReference{})); EXPECT_FALSE(reference.has_function()); } TEST(Reference, Equality) { EXPECT_EQ(MakeVariableReference("foo"), MakeVariableReference("foo")); EXPECT_NE(MakeVariableReference("foo"), MakeConstantVariableReference("foo", Constant(int64_t{1}))); EXPECT_EQ( MakeFunctionReference("foo", std::vector<std::string>{"bar", "baz"}), MakeFunctionReference("foo", std::vector<std::string>{"bar", "baz"})); EXPECT_NE( MakeFunctionReference("foo", std::vector<std::string>{"bar", "baz"}), MakeFunctionReference("foo", std::vector<std::string>{"bar"})); } } }
16
cpp
google/cel-cpp
type_reflector
extensions/protobuf/type_reflector.cc
extensions/protobuf/type_reflector_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_REFLECTOR_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_REFLECTOR_H_ #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_factory.h" #include "extensions/protobuf/type_introspector.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions { class ProtoTypeReflector : public TypeReflector, public ProtoTypeIntrospector { public: ProtoTypeReflector() : ProtoTypeReflector(google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory()) {} ProtoTypeReflector( absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool, absl::Nonnull<google::protobuf::MessageFactory*> message_factory) : ProtoTypeIntrospector(descriptor_pool), message_factory_(message_factory) {} absl::StatusOr<absl::optional<Unique<StructValueBuilder>>> NewStructValueBuilder(ValueFactory& value_factory, StructTypeView type) const final; absl::Nonnull<google::protobuf::MessageFactory*> message_factory() const { return message_factory_; } private: absl::StatusOr<absl::optional<Value>> DeserializeValueImpl( ValueFactory& value_factory, absl::string_view type_url, const absl::Cord& value) const final; absl::Nonnull<google::protobuf::MessageFactory*> const message_factory_; }; } #endif #include "extensions/protobuf/type_reflector.h" #include <cstdint> #include <limits> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/functional/overload.h" #include "absl/log/absl_check.h" #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/types/optional.h" #include "absl/types/variant.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/memory.h" #include "common/type.h" #include "common/type_factory.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_factory.h" #include "common/values/piecewise_value_manager.h" #include "extensions/protobuf/internal/any.h" #include "extensions/protobuf/internal/duration.h" #include "extensions/protobuf/internal/map_reflection.h" #include "extensions/protobuf/internal/message.h" #include "extensions/protobuf/internal/struct.h" #include "extensions/protobuf/internal/timestamp.h" #include "extensions/protobuf/internal/wrappers.h" #include "extensions/protobuf/json.h" #include "extensions/protobuf/memory_manager.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 cel::extensions { namespace { using ProtoRepeatedFieldFromValueMutator = absl::Status (*)( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*>, absl::Nonnull<google::protobuf::Message*>, absl::Nonnull<const google::protobuf::FieldDescriptor*>, ValueView); absl::Status ProtoBoolRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto bool_value = As<BoolValueView>(value); bool_value) { reflection->AddBool(message, field, bool_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } absl::Status ProtoInt32RepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto int_value = As<IntValueView>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int32_t>::min() || int_value->NativeValue() > std::numeric_limits<int32_t>::max()) { return absl::OutOfRangeError("int64 to int32_t overflow"); } reflection->AddInt32(message, field, static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoInt64RepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto int_value = As<IntValueView>(value); int_value) { reflection->AddInt64(message, field, int_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoUInt32RepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto uint_value = As<UintValueView>(value); uint_value) { if (uint_value->NativeValue() > std::numeric_limits<uint32_t>::max()) { return absl::OutOfRangeError("uint64 to uint32_t overflow"); } reflection->AddUInt32(message, field, static_cast<uint32_t>(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoUInt64RepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto uint_value = As<UintValueView>(value); uint_value) { reflection->AddUInt64(message, field, uint_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoFloatRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto double_value = As<DoubleValueView>(value); double_value) { reflection->AddFloat(message, field, static_cast<float>(double_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status ProtoDoubleRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto double_value = As<DoubleValueView>(value); double_value) { reflection->AddDouble(message, field, double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status ProtoBytesRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto bytes_value = As<BytesValueView>(value); bytes_value) { reflection->AddString(message, field, bytes_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bytes").NativeValue(); } absl::Status ProtoStringRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (auto string_value = As<StringValueView>(value); string_value) { reflection->AddString(message, field, string_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } absl::Status ProtoNullRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { if (InstanceOf<NullValueView>(value) || InstanceOf<IntValueView>(value)) { reflection->AddEnumValue(message, field, 0); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "null_type").NativeValue(); } absl::Status ProtoEnumRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*>, absl::Nonnull<google::protobuf::MessageFactory*>, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { const auto* enum_descriptor = field->enum_type(); if (auto int_value = As<IntValueView>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int>::min() || int_value->NativeValue() > std::numeric_limits<int>::max()) { return TypeConversionError(value.GetTypeName(), enum_descriptor->full_name()) .NativeValue(); } reflection->AddEnumValue(message, field, static_cast<int>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), enum_descriptor->full_name()) .NativeValue(); } absl::Status ProtoMessageRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueView value) { auto* element = reflection->AddMessage(message, field, factory); auto status = protobuf_internal::ProtoMessageFromValueImpl(value, pool, factory, element); if (!status.ok()) { reflection->RemoveLast(message, field); } return status; } absl::StatusOr<ProtoRepeatedFieldFromValueMutator> GetProtoRepeatedFieldFromValueMutator( absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { ABSL_DCHECK(!field->is_map()); ABSL_DCHECK(field->is_repeated()); switch (field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return ProtoBoolRepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32RepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64RepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32RepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64RepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return ProtoFloatRepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return ProtoDoubleRepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { return ProtoBytesRepeatedFieldFromValueMutator; } return ProtoStringRepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: if (field->enum_type()->full_name() == "google.protobuf.NullValue") { return ProtoNullRepeatedFieldFromValueMutator; } return ProtoEnumRepeatedFieldFromValueMutator; case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageRepeatedFieldFromValueMutator; default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer repeated field type: ", google::protobuf::FieldDescriptor::CppTypeName(field->cpp_type()))); } } class ProtoStructValueBuilder final : public StructValueBuilder { public: ProtoStructValueBuilder( const ProtoTypeReflector& type_reflector, ValueFactory& value_factory, absl::Nullable<google::protobuf::Arena*> arena, absl::Nonnull<google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> const reflection, absl::Nonnull<const google::protobuf::Descriptor*> const descriptor) : type_reflector_(type_reflector), value_factory_(value_factory), arena_(arena), message_(message), reflection_(reflection), descriptor_(descriptor) {} ~ProtoStructValueBuilder() override { if (message_ != nullptr && arena_ == nullptr) { delete message_; } } absl::Status SetFieldByName(absl::string_view name, Value value) override { const auto* field = descriptor_->FindFieldByName(name); if (field == nullptr) { field = reflection_->FindKnownExtensionByName(name); if (field == nullptr) { return NoSuchFieldError(name).NativeValue(); } } return SetField(field, std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number < std::numeric_limits<int>::min() || number > std::numeric_limits<int>::max()) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } const auto* field = descriptor_->FindFieldByNumber(number); if (field == nullptr) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetField(field, std::move(value)); } absl::StatusOr<StructValue> Build() && override { ABSL_ASSERT(message_ != nullptr); auto* message = message_; message_ = nullptr; return protobuf_internal::ProtoMessageAsStructValueImpl(value_factory_, message); } private: absl::Status SetField(absl::Nonnull<const google::protobuf::FieldDescriptor*> field, Value value) { if (field->is_map()) { return SetMapField(field, std::move(value)); } if (field->is_repeated()) { return SetRepeatedField(field, std::move(value)); } return SetSingularField(field, std::move(value)); } absl::Status SetMapField(absl::Nonnull<const google::protobuf::FieldDescriptor*> field, Value value) { auto map_value = As<MapValue>(value); if (!map_value) { return TypeConversionError(value.GetTypeName(), "map").NativeValue(); } CEL_ASSIGN_OR_RETURN(auto key_converter, protobuf_internal::GetProtoMapKeyFromValueConverter( field->message_type()->map_key()->cpp_type())); CEL_ASSIGN_OR_RETURN( auto value_converter, protobuf_internal::GetProtoMapValueFromValueConverter(field)); reflection_->ClearField(message_, field); common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); const auto* map_value_field = field->message_type()->map_value(); CEL_RETURN_IF_ERROR(map_value->ForEach( value_manager, [this, field, key_converter, map_value_field, value_converter]( ValueView entry_key, ValueView entry_value) -> absl::StatusOr<bool> { google::protobuf::MapKey proto_key; CEL_RETURN_IF_ERROR((*key_converter)(entry_key, proto_key)); google::protobuf::MapValueRef proto_value; protobuf_internal::InsertOrLookupMapValue( *reflection_, message_, *field, proto_key, &proto_value); CEL_RETURN_IF_ERROR( (*value_converter)(entry_value, map_value_field, proto_value)); return true; })); return absl::OkStatus(); } absl::Status SetRepeatedField( absl::Nonnull<const google::protobuf::FieldDescriptor*> field, Value value) { auto list_value = As<ListValue>(value); if (!list_value) { return TypeConversionError(value.GetTypeName(), "list").NativeValue(); } CEL_ASSIGN_OR_RETURN(auto accessor, GetProtoRepeatedFieldFromValueMutator(field)); reflection_->ClearField(message_, field); common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_RETURN_IF_ERROR(list_value->ForEach( value_manager, [this, field, accessor, &value_manager](ValueView element) -> absl::StatusOr<bool> { CEL_RETURN_IF_ERROR((*accessor)(type_reflector_.descriptor_pool(), type_reflector_.message_factory(), reflection_, message_, field, element)); return true; })); return absl::OkStatus(); } absl::Status SetSingularField( absl::Nonnull<const google::protobuf::FieldDescriptor*> field, Value value) { switch (field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { if (auto bool_value = As<BoolValue>(value); bool_value) { reflection_->SetBool(message_, field, bool_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { if (auto int_value = As<IntValue>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int32_t>::min() || int_value->NativeValue() > std::numeric_limits<int32_t>::max()) { return absl::OutOfRangeError("int64 to int32_t overflow"); } reflection_->SetInt32(message_, field, static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { if (auto int_value = As<IntValue>(value); int_value) { reflection_->SetInt64(message_, field, int_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { if (auto uint_value = As<UintValue>(value); uint_value) { if (uint_value->NativeValue() > std::numeric_limits<uint32_t>::max()) { return absl::OutOfRangeError("uint64 to uint32_t overflow"); } reflection_->SetUInt32( message_, field, static_cast<uint32_t>(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { if (auto uint_value = As<UintValue>(value); uint_value) { reflection_->SetUInt64(message_, field, uint_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: { if (auto double_value = As<DoubleValue>(value); double_value) { reflection_->SetFloat(message_, field, double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: { if (auto double_value = As<DoubleValue>(value); double_value) { reflection_->SetDouble(message_, field, double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { if (auto bytes_value = As<BytesValue>(value); bytes_value) { bytes_value->NativeValue(absl::Overload( [this, field](absl::string_view string) { reflection_->SetString(message_, field, std::string(string)); }, [this, field](const absl::Cord& cord) { reflection_->SetString(message_, field, cord); })); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bytes") .NativeValue(); } if (auto string_value = As<StringValue>(value); string_value) { string_value->NativeValue(absl::Overload( [this, field](absl::string_view string) { reflection_->SetString(message_, field, std::string(string)); }, [this, field](const absl::Cord& cord) { reflection_->SetString(message_, field, cord); })); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: { if (field->enum_type()->full_name() == "google.protobuf.NullValue") { if (InstanceOf<NullValue>(value) || InstanceOf<IntValue>(value)) { reflection_->SetEnumValue(message_, field, 0); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "null_type") .NativeValue(); } if (auto int_value = As<IntValue>(value); int_value) { if (int_value->NativeValue() >= std::numeric_limits<int32_t>::min() && int_value->NativeValue() <= std::numeric_limits<int32_t>::max()) { reflection_->SetEnumValue( message_, field, static_cast<int>(int_value->NativeValue())); return absl::OkStatus(); } } return TypeConversionError(value.GetTypeName(), field->enum_type()->full_name()) .NativeValue(); } case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { switch (field->message_type()->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: { if (auto bool_value = As<BoolValue>(value); bool_value) { return protobuf_internal::WrapDynamicBoolValueProto( bool_value->NativeValue(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: { if (auto int_value = As<IntValue>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int32_t>::min() || int_value->NativeValue() > std::numeric_limits<int32_t>::max()) { return absl::OutOfRangeError("int64 to int32_t overflow"); } return protobuf_internal::WrapDynamicInt32ValueProto( static_cast<int32_t>(int_value->NativeValue()), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: { if (auto int_value = As<IntValue>(value); int_value) { return protobuf_internal::WrapDynamicInt64ValueProto( int_value->NativeValue(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: { if (auto uint_value = As<UintValue>(value); uint_value) { if (uint_value->NativeValue() > std::numeric_limits<uint32_t>::max()) { return absl::OutOfRangeError("uint64 to uint32_t overflow"); } return protobuf_internal::WrapDynamicUInt32ValueProto( static_cast<uint32_t>(uint_value->NativeValue()), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: { if (auto uint_value = As<UintValue>(value); uint_value) { return protobuf_internal::WrapDynamicUInt64ValueProto( uint_value->NativeValue(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: { if (auto double_value = As<DoubleValue>(value); double_value) { return protobuf_internal::WrapDynamicFloatValueProto( static_cast<float>(double_value->NativeValue()), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: { if (auto double_value = As<DoubleValue>(value); double_value) { return protobuf_internal::WrapDynamicDoubleValueProto( double_value->NativeValue(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: { if (auto bytes_value = As<BytesValue>(value); bytes_value) { return protobuf_internal::WrapDynamicBytesValueProto( bytes_value->NativeCord(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: { if (auto string_value = As<StringValue>(value); string_value) { return protobuf_internal::WrapDynamicStringValueProto( string_value->NativeCord(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION: { if (auto duration_value = As<DurationValue>(value); duration_value) { return protobuf_internal::WrapDynamicDurationProto( duration_value->NativeValue(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP: { if (auto timestamp_value = As<TimestampValue>(value); timestamp_value) { return protobuf_internal::WrapDynamicTimestampProto( timestamp_value->NativeValue(), *reflection_->MutableMessage( message_, field, type_reflector_.message_factory())); } return TypeConversionError(value.GetTypeName(), field->message_type()->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE: { ProtoAnyToJsonConverter converter( type_reflector_.descriptor_pool(),
#include "extensions/protobuf/type_reflector.h" #include "google/protobuf/wrappers.pb.h" #include "absl/status/status.h" #include "absl/types/optional.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { namespace { using ::google::api::expr::test::v1::proto2::TestAllTypes; using cel::internal::StatusIs; class ProtoTypeReflectorTest : public common_internal::ThreadCompatibleValueTest<> { private: Shared<TypeReflector> NewTypeReflector( MemoryManagerRef memory_manager) override { return memory_manager.MakeShared<ProtoTypeReflector>(); } }; TEST_P(ProtoTypeReflectorTest, NewStructValueBuilder_WellKnownType) { ASSERT_OK_AND_ASSIGN( auto builder, value_manager().NewStructValueBuilder(value_manager().CreateStructType( google::protobuf::BoolValue::descriptor()->full_name()))); ASSERT_FALSE(builder.has_value()); } TEST_P(ProtoTypeReflectorTest, NewStructValueBuilder_NoSuchType) { ASSERT_OK_AND_ASSIGN( auto builder, value_manager().NewStructValueBuilder( value_manager().CreateStructType("message.that.does.not.Exist"))); ASSERT_FALSE(builder.has_value()); } TEST_P(ProtoTypeReflectorTest, NewStructValueBuilder_SetFieldByNumber) { ASSERT_OK_AND_ASSIGN( auto builder, value_manager().NewStructValueBuilder(value_manager().CreateStructType( TestAllTypes::descriptor()->full_name()))); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByNumber(13, UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_P(ProtoTypeReflectorTest, NewStructValueBuilder_TypeConversionError) { ASSERT_OK_AND_ASSIGN( auto builder, value_manager().NewStructValueBuilder(value_manager().CreateStructType( TestAllTypes::descriptor()->full_name()))); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("single_bool", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_int32", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_int64", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_uint32", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_uint64", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_float", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_double", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_string", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_bytes", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("single_bool_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_int32_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_int64_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_uint32_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_uint64_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_float_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_double_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_string_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByName("single_bytes_wrapper", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("null_value", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("repeated_bool", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("map_bool_bool", UnknownValue{}), StatusIs(absl::StatusCode::kInvalidArgument)); } INSTANTIATE_TEST_SUITE_P( ProtoTypeReflectorTest, ProtoTypeReflectorTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoTypeReflectorTest::ToString); } }
17
cpp
google/cel-cpp
ast_rewrite
eval/public/ast_rewrite.cc
eval/public/ast_rewrite_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_AST_REWRITE_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_AST_REWRITE_H_ #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/types/span.h" #include "eval/public/ast_visitor.h" namespace google::api::expr::runtime { struct RewriteTraversalOptions { bool use_comprehension_callbacks; RewriteTraversalOptions() : use_comprehension_callbacks(false) {} }; class AstRewriter : public AstVisitor { public: ~AstRewriter() override {} virtual bool PreVisitRewrite(google::api::expr::v1alpha1::Expr* expr, const SourcePosition* position) = 0; virtual bool PostVisitRewrite(google::api::expr::v1alpha1::Expr* expr, const SourcePosition* position) = 0; virtual void TraversalStackUpdate( absl::Span<const google::api::expr::v1alpha1::Expr*> path) = 0; }; class AstRewriterBase : public AstRewriter { public: ~AstRewriterBase() override {} void PreVisitExpr(const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitExpr(const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitConst(const google::api::expr::v1alpha1::Constant*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitIdent(const google::api::expr::v1alpha1::Expr::Ident*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitSelect(const google::api::expr::v1alpha1::Expr::Select*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PreVisitCall(const google::api::expr::v1alpha1::Expr::Call*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitCall(const google::api::expr::v1alpha1::Expr::Call*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PreVisitComprehension(const google::api::expr::v1alpha1::Expr::Comprehension*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitComprehension(const google::api::expr::v1alpha1::Expr::Comprehension*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitArg(int, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitTarget(const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitCreateList(const google::api::expr::v1alpha1::Expr::CreateList*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} void PostVisitCreateStruct(const google::api::expr::v1alpha1::Expr::CreateStruct*, const google::api::expr::v1alpha1::Expr*, const SourcePosition*) override {} bool PreVisitRewrite(google::api::expr::v1alpha1::Expr* expr, const SourcePosition* position) override { return false; } bool PostVisitRewrite(google::api::expr::v1alpha1::Expr* expr, const SourcePosition* position) override { return false; } void TraversalStackUpdate( absl::Span<const google::api::expr::v1alpha1::Expr*> path) override {} }; bool AstRewrite(google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info, AstRewriter* visitor); bool AstRewrite(google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info, AstRewriter* visitor, RewriteTraversalOptions options); } #endif #include "eval/public/ast_rewrite.h" #include <stack> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/log/absl_log.h" #include "absl/types/variant.h" #include "eval/public/ast_visitor.h" #include "eval/public/source_position.h" namespace google::api::expr::runtime { using google::api::expr::v1alpha1::Expr; using google::api::expr::v1alpha1::SourceInfo; using Ident = google::api::expr::v1alpha1::Expr::Ident; using Select = google::api::expr::v1alpha1::Expr::Select; using Call = google::api::expr::v1alpha1::Expr::Call; using CreateList = google::api::expr::v1alpha1::Expr::CreateList; using CreateStruct = google::api::expr::v1alpha1::Expr::CreateStruct; using Comprehension = google::api::expr::v1alpha1::Expr::Comprehension; namespace { struct ArgRecord { Expr* expr; const SourceInfo* source_info; const Expr* calling_expr; int call_arg; }; struct ComprehensionRecord { Expr* expr; const SourceInfo* source_info; const Comprehension* comprehension; const Expr* comprehension_expr; ComprehensionArg comprehension_arg; bool use_comprehension_callbacks; }; struct ExprRecord { Expr* expr; const SourceInfo* source_info; }; using StackRecordKind = absl::variant<ExprRecord, ArgRecord, ComprehensionRecord>; struct StackRecord { public: ABSL_ATTRIBUTE_UNUSED static constexpr int kNotCallArg = -1; static constexpr int kTarget = -2; StackRecord(Expr* e, const SourceInfo* info) { ExprRecord record; record.expr = e; record.source_info = info; record_variant = record; } StackRecord(Expr* e, const SourceInfo* info, Comprehension* comprehension, Expr* comprehension_expr, ComprehensionArg comprehension_arg, bool use_comprehension_callbacks) { if (use_comprehension_callbacks) { ComprehensionRecord record; record.expr = e; record.source_info = info; record.comprehension = comprehension; record.comprehension_expr = comprehension_expr; record.comprehension_arg = comprehension_arg; record.use_comprehension_callbacks = use_comprehension_callbacks; record_variant = record; return; } ArgRecord record; record.expr = e; record.source_info = info; record.calling_expr = comprehension_expr; record.call_arg = comprehension_arg; record_variant = record; } StackRecord(Expr* e, const SourceInfo* info, const Expr* call, int argnum) { ArgRecord record; record.expr = e; record.source_info = info; record.calling_expr = call; record.call_arg = argnum; record_variant = record; } Expr* expr() const { return absl::get<ExprRecord>(record_variant).expr; } const SourceInfo* source_info() const { return absl::get<ExprRecord>(record_variant).source_info; } bool IsExprRecord() const { return absl::holds_alternative<ExprRecord>(record_variant); } StackRecordKind record_variant; bool visited = false; }; struct PreVisitor { void operator()(const ExprRecord& record) { Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); visitor->PreVisitExpr(expr, &position); switch (expr->expr_kind_case()) { case Expr::kSelectExpr: visitor->PreVisitSelect(&expr->select_expr(), expr, &position); break; case Expr::kCallExpr: visitor->PreVisitCall(&expr->call_expr(), expr, &position); break; case Expr::kComprehensionExpr: visitor->PreVisitComprehension(&expr->comprehension_expr(), expr, &position); break; default: break; } } void operator()(const ArgRecord&) {} void operator()(const ComprehensionRecord& record) { Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); visitor->PreVisitComprehensionSubexpression( expr, record.comprehension, record.comprehension_arg, &position); } AstVisitor* visitor; }; void PreVisit(const StackRecord& record, AstVisitor* visitor) { absl::visit(PreVisitor{visitor}, record.record_variant); } struct PostVisitor { void operator()(const ExprRecord& record) { Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); switch (expr->expr_kind_case()) { case Expr::kConstExpr: visitor->PostVisitConst(&expr->const_expr(), expr, &position); break; case Expr::kIdentExpr: visitor->PostVisitIdent(&expr->ident_expr(), expr, &position); break; case Expr::kSelectExpr: visitor->PostVisitSelect(&expr->select_expr(), expr, &position); break; case Expr::kCallExpr: visitor->PostVisitCall(&expr->call_expr(), expr, &position); break; case Expr::kListExpr: visitor->PostVisitCreateList(&expr->list_expr(), expr, &position); break; case Expr::kStructExpr: visitor->PostVisitCreateStruct(&expr->struct_expr(), expr, &position); break; case Expr::kComprehensionExpr: visitor->PostVisitComprehension(&expr->comprehension_expr(), expr, &position); break; case Expr::EXPR_KIND_NOT_SET: break; default: ABSL_LOG(ERROR) << "Unsupported Expr kind: " << expr->expr_kind_case(); } visitor->PostVisitExpr(expr, &position); } void operator()(const ArgRecord& record) { Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); if (record.call_arg == StackRecord::kTarget) { visitor->PostVisitTarget(record.calling_expr, &position); } else { visitor->PostVisitArg(record.call_arg, record.calling_expr, &position); } } void operator()(const ComprehensionRecord& record) { Expr* expr = record.expr; const SourcePosition position(expr->id(), record.source_info); visitor->PostVisitComprehensionSubexpression( expr, record.comprehension, record.comprehension_arg, &position); } AstVisitor* visitor; }; void PostVisit(const StackRecord& record, AstVisitor* visitor) { absl::visit(PostVisitor{visitor}, record.record_variant); } void PushSelectDeps(Select* select_expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { if (select_expr->has_operand()) { stack->push(StackRecord(select_expr->mutable_operand(), source_info)); } } void PushCallDeps(Call* call_expr, Expr* expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { const int arg_size = call_expr->args_size(); for (int i = arg_size - 1; i >= 0; --i) { stack->push(StackRecord(call_expr->mutable_args(i), source_info, expr, i)); } if (call_expr->has_target()) { stack->push(StackRecord(call_expr->mutable_target(), source_info, expr, StackRecord::kTarget)); } } void PushListDeps(CreateList* list_expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { auto& elements = *list_expr->mutable_elements(); for (auto it = elements.rbegin(); it != elements.rend(); ++it) { auto& element = *it; stack->push(StackRecord(&element, source_info)); } } void PushStructDeps(CreateStruct* struct_expr, const SourceInfo* source_info, std::stack<StackRecord>* stack) { auto& entries = *struct_expr->mutable_entries(); for (auto it = entries.rbegin(); it != entries.rend(); ++it) { auto& entry = *it; if (entry.has_value()) { stack->push(StackRecord(entry.mutable_value(), source_info)); } if (entry.has_map_key()) { stack->push(StackRecord(entry.mutable_map_key(), source_info)); } } } void PushComprehensionDeps(Comprehension* c, Expr* expr, const SourceInfo* source_info, std::stack<StackRecord>* stack, bool use_comprehension_callbacks) { StackRecord iter_range(c->mutable_iter_range(), source_info, c, expr, ITER_RANGE, use_comprehension_callbacks); StackRecord accu_init(c->mutable_accu_init(), source_info, c, expr, ACCU_INIT, use_comprehension_callbacks); StackRecord loop_condition(c->mutable_loop_condition(), source_info, c, expr, LOOP_CONDITION, use_comprehension_callbacks); StackRecord loop_step(c->mutable_loop_step(), source_info, c, expr, LOOP_STEP, use_comprehension_callbacks); StackRecord result(c->mutable_result(), source_info, c, expr, RESULT, use_comprehension_callbacks); stack->push(result); stack->push(loop_step); stack->push(loop_condition); stack->push(accu_init); stack->push(iter_range); } struct PushDepsVisitor { void operator()(const ExprRecord& record) { Expr* expr = record.expr; switch (expr->expr_kind_case()) { case Expr::kSelectExpr: PushSelectDeps(expr->mutable_select_expr(), record.source_info, &stack); break; case Expr::kCallExpr: PushCallDeps(expr->mutable_call_expr(), expr, record.source_info, &stack); break; case Expr::kListExpr: PushListDeps(expr->mutable_list_expr(), record.source_info, &stack); break; case Expr::kStructExpr: PushStructDeps(expr->mutable_struct_expr(), record.source_info, &stack); break; case Expr::kComprehensionExpr: PushComprehensionDeps(expr->mutable_comprehension_expr(), expr, record.source_info, &stack, options.use_comprehension_callbacks); break; default: break; } } void operator()(const ArgRecord& record) { stack.push(StackRecord(record.expr, record.source_info)); } void operator()(const ComprehensionRecord& record) { stack.push(StackRecord(record.expr, record.source_info)); } std::stack<StackRecord>& stack; const RewriteTraversalOptions& options; }; void PushDependencies(const StackRecord& record, std::stack<StackRecord>& stack, const RewriteTraversalOptions& options) { absl::visit(PushDepsVisitor{stack, options}, record.record_variant); } } bool AstRewrite(Expr* expr, const SourceInfo* source_info, AstRewriter* visitor) { return AstRewrite(expr, source_info, visitor, RewriteTraversalOptions{}); } bool AstRewrite(Expr* expr, const SourceInfo* source_info, AstRewriter* visitor, RewriteTraversalOptions options) { std::stack<StackRecord> stack; std::vector<const Expr*> traversal_path; stack.push(StackRecord(expr, source_info)); bool rewritten = false; while (!stack.empty()) { StackRecord& record = stack.top(); if (!record.visited) { if (record.IsExprRecord()) { traversal_path.push_back(record.expr()); visitor->TraversalStackUpdate(absl::MakeSpan(traversal_path)); SourcePosition pos(record.expr()->id(), record.source_info()); if (visitor->PreVisitRewrite(record.expr(), &pos)) { rewritten = true; } } PreVisit(record, visitor); PushDependencies(record, stack, options); record.visited = true; } else { PostVisit(record, visitor); if (record.IsExprRecord()) { SourcePosition pos(record.expr()->id(), record.source_info()); if (visitor->PostVisitRewrite(record.expr(), &pos)) { rewritten = true; } traversal_path.pop_back(); visitor->TraversalStackUpdate(absl::MakeSpan(traversal_path)); } stack.pop(); } } return rewritten; } }
#include "eval/public/ast_rewrite.h" #include <string> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "eval/public/ast_visitor.h" #include "eval/public/source_position.h" #include "internal/testing.h" #include "parser/parser.h" #include "testutil/util.h" namespace google::api::expr::runtime { namespace { using ::google::api::expr::v1alpha1::Constant; using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::v1alpha1::SourceInfo; using testing::_; using testing::ElementsAre; using testing::InSequence; using Ident = google::api::expr::v1alpha1::Expr::Ident; using Select = google::api::expr::v1alpha1::Expr::Select; using Call = google::api::expr::v1alpha1::Expr::Call; using CreateList = google::api::expr::v1alpha1::Expr::CreateList; using CreateStruct = google::api::expr::v1alpha1::Expr::CreateStruct; using Comprehension = google::api::expr::v1alpha1::Expr::Comprehension; class MockAstRewriter : public AstRewriter { public: MOCK_METHOD(void, PreVisitExpr, (const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitExpr, (const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitConst, (const Constant* const_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitIdent, (const Ident* ident_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitSelect, (const Select* select_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitSelect, (const Select* select_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitCall, (const Call* call_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitCall, (const Call* call_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitComprehension, (const Comprehension* comprehension_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitComprehension, (const Comprehension* comprehension_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PreVisitComprehensionSubexpression, (const Expr* expr, const Comprehension* comprehension_expr, ComprehensionArg comprehension_arg, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitComprehensionSubexpression, (const Expr* expr, const Comprehension* comprehension_expr, ComprehensionArg comprehension_arg, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitTarget, (const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitArg, (int arg_num, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitCreateList, (const CreateList* list_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(void, PostVisitCreateStruct, (const CreateStruct* struct_expr, const Expr* expr, const SourcePosition* position), (override)); MOCK_METHOD(bool, PreVisitRewrite, (Expr * expr, const SourcePosition* position), (override)); MOCK_METHOD(bool, PostVisitRewrite, (Expr * expr, const SourcePosition* position), (override)); MOCK_METHOD(void, TraversalStackUpdate, (absl::Span<const Expr*> path), (override)); }; TEST(AstCrawlerTest, CheckCrawlConstant) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto const_expr = expr.mutable_const_expr(); EXPECT_CALL(handler, PostVisitConst(const_expr, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlIdent) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto ident_expr = expr.mutable_ident_expr(); EXPECT_CALL(handler, PostVisitIdent(ident_expr, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlSelectNotCrashingPostVisitAbsentOperand) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto select_expr = expr.mutable_select_expr(); EXPECT_CALL(handler, PostVisitSelect(select_expr, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlSelect) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto select_expr = expr.mutable_select_expr(); auto operand = select_expr->mutable_operand(); auto ident_expr = operand->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PostVisitIdent(ident_expr, operand, _)).Times(1); EXPECT_CALL(handler, PostVisitSelect(select_expr, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlCallNoReceiver) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto* call_expr = expr.mutable_call_expr(); Expr* arg0 = call_expr->add_args(); auto* const_expr = arg0->mutable_const_expr(); Expr* arg1 = call_expr->add_args(); auto* ident_expr = arg1->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitTarget(_, _)).Times(0); EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(0, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(1, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(&expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlCallReceiver) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto* call_expr = expr.mutable_call_expr(); Expr* target = call_expr->mutable_target(); auto* target_ident = target->mutable_ident_expr(); Expr* arg0 = call_expr->add_args(); auto* const_expr = arg0->mutable_const_expr(); Expr* arg1 = call_expr->add_args(); auto* ident_expr = arg1->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(target_ident, target, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(target, _)).Times(1); EXPECT_CALL(handler, PostVisitTarget(&expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(0, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(1, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitCall(call_expr, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitExpr(&expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCrawlComprehension) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto c = expr.mutable_comprehension_expr(); auto iter_range = c->mutable_iter_range(); auto iter_range_expr = iter_range->mutable_const_expr(); auto accu_init = c->mutable_accu_init(); auto accu_init_expr = accu_init->mutable_ident_expr(); auto loop_condition = c->mutable_loop_condition(); auto loop_condition_expr = loop_condition->mutable_const_expr(); auto loop_step = c->mutable_loop_step(); auto loop_step_expr = loop_step->mutable_ident_expr(); auto result = c->mutable_result(); auto result_expr = result->mutable_const_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitComprehension(c, &expr, _)).Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(iter_range, c, ITER_RANGE, _)) .Times(1); EXPECT_CALL(handler, PostVisitConst(iter_range_expr, iter_range, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(iter_range, c, ITER_RANGE, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(accu_init, c, ACCU_INIT, _)) .Times(1); EXPECT_CALL(handler, PostVisitIdent(accu_init_expr, accu_init, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(accu_init, c, ACCU_INIT, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(loop_condition, c, LOOP_CONDITION, _)) .Times(1); EXPECT_CALL(handler, PostVisitConst(loop_condition_expr, loop_condition, _)) .Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(loop_condition, c, LOOP_CONDITION, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(loop_step, c, LOOP_STEP, _)) .Times(1); EXPECT_CALL(handler, PostVisitIdent(loop_step_expr, loop_step, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(loop_step, c, LOOP_STEP, _)) .Times(1); EXPECT_CALL(handler, PreVisitComprehensionSubexpression(result, c, RESULT, _)) .Times(1); EXPECT_CALL(handler, PostVisitConst(result_expr, result, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehensionSubexpression(result, c, RESULT, _)) .Times(1); EXPECT_CALL(handler, PostVisitComprehension(c, &expr, _)).Times(1); RewriteTraversalOptions opts; opts.use_comprehension_callbacks = true; AstRewrite(&expr, &source_info, &handler, opts); } TEST(AstCrawlerTest, CheckCrawlComprehensionLegacyCallbacks) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto c = expr.mutable_comprehension_expr(); auto iter_range = c->mutable_iter_range(); auto iter_range_expr = iter_range->mutable_const_expr(); auto accu_init = c->mutable_accu_init(); auto accu_init_expr = accu_init->mutable_ident_expr(); auto loop_condition = c->mutable_loop_condition(); auto loop_condition_expr = loop_condition->mutable_const_expr(); auto loop_step = c->mutable_loop_step(); auto loop_step_expr = loop_step->mutable_ident_expr(); auto result = c->mutable_result(); auto result_expr = result->mutable_const_expr(); testing::InSequence seq; EXPECT_CALL(handler, PreVisitComprehension(c, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(iter_range_expr, iter_range, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(ITER_RANGE, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(accu_init_expr, accu_init, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(ACCU_INIT, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(loop_condition_expr, loop_condition, _)) .Times(1); EXPECT_CALL(handler, PostVisitArg(LOOP_CONDITION, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(loop_step_expr, loop_step, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(LOOP_STEP, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitConst(result_expr, result, _)).Times(1); EXPECT_CALL(handler, PostVisitArg(RESULT, &expr, _)).Times(1); EXPECT_CALL(handler, PostVisitComprehension(c, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCreateList) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto list_expr = expr.mutable_list_expr(); auto arg0 = list_expr->add_elements(); auto const_expr = arg0->mutable_const_expr(); auto arg1 = list_expr->add_elements(); auto ident_expr = arg1->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1); EXPECT_CALL(handler, PostVisitCreateList(list_expr, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckCreateStruct) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto struct_expr = expr.mutable_struct_expr(); auto entry0 = struct_expr->add_entries(); auto key = entry0->mutable_map_key()->mutable_const_expr(); auto value = entry0->mutable_value()->mutable_ident_expr(); testing::InSequence seq; EXPECT_CALL(handler, PostVisitConst(key, &entry0->map_key(), _)).Times(1); EXPECT_CALL(handler, PostVisitIdent(value, &entry0->value(), _)).Times(1); EXPECT_CALL(handler, PostVisitCreateStruct(struct_expr, &expr, _)).Times(1); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckExprHandlers) { SourceInfo source_info; MockAstRewriter handler; Expr expr; auto struct_expr = expr.mutable_struct_expr(); auto entry0 = struct_expr->add_entries(); entry0->mutable_map_key()->mutable_const_expr(); entry0->mutable_value()->mutable_ident_expr(); EXPECT_CALL(handler, PreVisitExpr(_, _)).Times(3); EXPECT_CALL(handler, PostVisitExpr(_, _)).Times(3); AstRewrite(&expr, &source_info, &handler); } TEST(AstCrawlerTest, CheckExprRewriteHandlers) { SourceInfo source_info; MockAstRewriter handler; Expr select_expr; select_expr.mutable_select_expr()->set_field("var"); auto* inner_select_expr = select_expr.mutable_select_expr()->mutable_operand(); inner_select_expr->mutable_select_expr()->set_field("mid"); auto* ident = inner_select_expr->mutable_select_expr()->mutable_operand(); ident->mutable_ident_expr()->set_name("top"); { InSequence sequence; EXPECT_CALL(handler, TraversalStackUpdate(testing::ElementsAre(&select_expr))); EXPECT_CALL(handler, PreVisitRewrite(&select_expr, _)); EXPECT_CALL(handler, TraversalStackUpdate(testing::ElementsAre( &select_expr, inner_select_expr))); EXPECT_CALL(handler, PreVisitRewrite(inner_select_expr, _)); EXPECT_CALL(handler, TraversalStackUpdate(testing::ElementsAre( &select_expr, inner_select_expr, ident))); EXPECT_CALL(handler, PreVisitRewrite(ident, _)); EXPECT_CALL(handler, PostVisitRewrite(ident, _)); EXPECT_CALL(handler, TraversalStackUpdate(testing::ElementsAre( &select_expr, inner_select_expr))); EXPECT_CALL(handler, PostVisitRewrite(inner_select_expr, _)); EXPECT_CALL(handler, TraversalStackUpdate(testing::ElementsAre(&select_expr))); EXPECT_CALL(handler, PostVisitRewrite(&select_expr, _)); EXPECT_CALL(handler, TraversalStackUpdate(testing::IsEmpty())); } EXPECT_FALSE(AstRewrite(&select_expr, &source_info, &handler)); } class RewriterExample : public AstRewriterBase { public: RewriterExample() {} bool PostVisitRewrite(Expr* expr, const SourcePosition* info) override { if (target_.has_value() && expr->id() == *target_) { expr->mutable_ident_expr()->set_name("com.google.Identifier"); return true; } return false; } void PostVisitIdent(const Ident* ident, const Expr* expr, const SourcePosition* pos) override { if (path_.size() >= 3) { if (ident->name() == "com") { const Expr* p1 = path_.at(path_.size() - 2); const Expr* p2 = path_.at(path_.size() - 3); if (p1->has_select_expr() && p1->select_expr().field() == "google" && p2->has_select_expr() && p2->select_expr().field() == "Identifier") { target_ = p2->id(); } } } } void TraversalStackUpdate(absl::Span<const Expr*> path) override { path_ = path; } private: absl::Span<const Expr*> path_; absl::optional<int64_t> target_; }; TEST(AstRewrite, SelectRewriteExample) { ASSERT_OK_AND_ASSIGN(ParsedExpr parsed, parser::Parse("com.google.Identifier")); RewriterExample example; ASSERT_TRUE( AstRewrite(parsed.mutable_expr(), &parsed.source_info(), &example)); EXPECT_THAT(parsed.expr(), testutil::EqualsProto(R"pb( id: 3 ident_expr { name: "com.google.Identifier" } )pb")); } class PreRewriterExample : public AstRewriterBase { public: PreRewriterExample() {} bool PreVisitRewrite(Expr* expr, const SourcePosition* info) override { if (expr->ident_expr().name() == "x") { expr->mutable_ident_expr()->set_name("y"); return true; } return false; } bool PostVisitRewrite(Expr* expr, const SourcePosition* info) override { if (expr->ident_expr().name() == "y") { expr->mutable_ident_expr()->set_name("z"); return true; } return false; } void PostVisitIdent(const Ident* ident, const Expr* expr, const SourcePosition* pos) override { visited_idents_.push_back(ident->name()); } const std::vector<std::string>& visited_idents() const { return visited_idents_; } private: std::vector<std::string> visited_idents_; }; TEST(AstRewrite, PreAndPostVisitExpample) { ASSERT_OK_AND_ASSIGN(ParsedExpr parsed, parser::Parse("x")); PreRewriterExample visitor; ASSERT_TRUE( AstRewrite(parsed.mutable_expr(), &parsed.source_info(), &visitor)); EXPECT_THAT(parsed.expr(), testutil::EqualsProto(R"pb( id: 1 ident_expr { name: "z" } )pb")); EXPECT_THAT(visitor.visited_idents(), ElementsAre("y")); } } }
18
cpp
google/cel-cpp
value
extensions/protobuf/value.cc
extensions/protobuf/value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_VALUE_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_VALUE_H_ #include <type_traits> #include <utility> #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 "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/functional/overload.h" #include "absl/status/statusor.h" #include "common/value.h" #include "common/value_factory.h" #include "common/value_manager.h" #include "extensions/protobuf/internal/duration_lite.h" #include "extensions/protobuf/internal/enum.h" #include "extensions/protobuf/internal/message.h" #include "extensions/protobuf/internal/struct_lite.h" #include "extensions/protobuf/internal/timestamp_lite.h" #include "extensions/protobuf/internal/wrappers_lite.h" #include "internal/status_macros.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/generated_enum_reflection.h" namespace cel::extensions { template <typename T> std::enable_if_t<protobuf_internal::IsProtoEnum<T>, absl::StatusOr<ValueView>> ProtoEnumToValue(ValueFactory&, T value, Value& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND ABSL_ATTRIBUTE_UNUSED) { if constexpr (std::is_same_v<T, google::protobuf::NullValue>) { return NullValueView{}; } return IntValueView{static_cast<int>(value)}; } template <typename T> std::enable_if_t<protobuf_internal::IsProtoEnum<T>, absl::StatusOr<Value>> ProtoEnumToValue(ValueFactory&, T value) { if constexpr (std::is_same_v<T, google::protobuf::NullValue>) { return NullValue{}; } return IntValue{static_cast<int>(value)}; } absl::StatusOr<int> ProtoEnumFromValue( ValueView value, absl::Nonnull<const google::protobuf::EnumDescriptor*> desc); template <typename T> std::enable_if_t<protobuf_internal::IsProtoEnum<T>, absl::StatusOr<T>> ProtoEnumFromValue(ValueView value) { CEL_ASSIGN_OR_RETURN( auto enum_value, ProtoEnumFromValue(value, google::protobuf::GetEnumDescriptor<T>())); return static_cast<T>(enum_value); } template <typename T> std::enable_if_t<protobuf_internal::IsProtoMessage<T>, absl::StatusOr<Value>> ProtoMessageToValue(ValueManager& value_manager, T&& value) { using Tp = std::decay_t<T>; if constexpr (std::is_same_v<Tp, google::protobuf::BoolValue>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedBoolValueProto( std::forward<T>(value))); return BoolValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::Int32Value>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedInt32ValueProto( std::forward<T>(value))); return IntValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::Int64Value>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedInt64ValueProto( std::forward<T>(value))); return IntValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::UInt32Value>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedUInt32ValueProto( std::forward<T>(value))); return UintValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::UInt64Value>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedUInt64ValueProto( std::forward<T>(value))); return UintValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::FloatValue>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedFloatValueProto( std::forward<T>(value))); return DoubleValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::DoubleValue>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedDoubleValueProto( std::forward<T>(value))); return DoubleValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::BytesValue>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedBytesValueProto( std::forward<T>(value))); return BytesValue{std::move(result)}; } else if constexpr (std::is_same_v<Tp, google::protobuf::StringValue>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedStringValueProto( std::forward<T>(value))); return StringValue{std::move(result)}; } else if constexpr (std::is_same_v<Tp, google::protobuf::Duration>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedDurationProto( std::forward<T>(value))); return DurationValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::Timestamp>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::UnwrapGeneratedTimestampProto( std::forward<T>(value))); return TimestampValue{result}; } else if constexpr (std::is_same_v<Tp, google::protobuf::Value>) { CEL_ASSIGN_OR_RETURN( auto result, protobuf_internal::GeneratedValueProtoToJson(std::forward<T>(value))); return value_manager.CreateValueFromJson(std::move(result)); } else if constexpr (std::is_same_v<Tp, google::protobuf::ListValue>) { CEL_ASSIGN_OR_RETURN(auto result, protobuf_internal::GeneratedListValueProtoToJson( std::forward<T>(value))); return value_manager.CreateListValueFromJsonArray(std::move(result)); } else if constexpr (std::is_same_v<Tp, google::protobuf::Struct>) { CEL_ASSIGN_OR_RETURN( auto result, protobuf_internal::GeneratedStructProtoToJson(std::forward<T>(value))); return value_manager.CreateMapValueFromJsonObject(std::move(result)); } else { auto dispatcher = absl::Overload( [&](Tp&& m) { return protobuf_internal::ProtoMessageToValueImpl( value_manager, &m, sizeof(T), alignof(T), &protobuf_internal::ProtoMessageTraits<Tp>::ArenaMoveConstruct, &protobuf_internal::ProtoMessageTraits<Tp>::MoveConstruct); }, [&](const Tp& m) { return protobuf_internal::ProtoMessageToValueImpl( value_manager, &m, sizeof(T), alignof(T), &protobuf_internal::ProtoMessageTraits<Tp>::ArenaCopyConstruct, &protobuf_internal::ProtoMessageTraits<Tp>::CopyConstruct); }); return dispatcher(std::forward<T>(value)); } } template <typename T> std::enable_if_t<protobuf_internal::IsProtoMessage<T>, absl::StatusOr<ValueView>> ProtoMessageToValue(ValueManager& value_manager, T&& value, Value& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { CEL_ASSIGN_OR_RETURN( scratch, ProtoMessageToValue(value_manager, std::forward<T>(value))); return scratch; } template <typename T> std::enable_if_t<protobuf_internal::IsProtoMessage<T>, absl::Status> ProtoMessageFromValue(ValueView value, T& message, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory) { return protobuf_internal::ProtoMessageFromValueImpl(value, pool, factory, &message); } template <typename T> std::enable_if_t<protobuf_internal::IsProtoMessage<T>, absl::Status> ProtoMessageFromValue(ValueView value, T& message) { return protobuf_internal::ProtoMessageFromValueImpl(value, &message); } inline absl::StatusOr<absl::Nonnull<google::protobuf::Message*>> ProtoMessageFromValue( ValueView value, absl::Nullable<google::protobuf::Arena*> arena) { return protobuf_internal::ProtoMessageFromValueImpl(value, arena); } inline absl::StatusOr<absl::Nonnull<google::protobuf::Message*>> ProtoMessageFromValue( ValueView value, absl::Nullable<google::protobuf::Arena*> arena, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory) { return protobuf_internal::ProtoMessageFromValueImpl(value, pool, factory, arena); } } #endif #include "extensions/protobuf/value.h" #include <limits> #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common/casting.h" #include "common/value.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { absl::StatusOr<int> ProtoEnumFromValue( ValueView value, absl::Nonnull<const google::protobuf::EnumDescriptor*> desc) { if (desc->full_name() == "google.protobuf.NullValue") { if (InstanceOf<NullValueView>(value) || InstanceOf<IntValueView>(value)) { return 0; } return TypeConversionError(value.GetTypeName(), desc->full_name()) .NativeValue(); } if (auto int_value = As<IntValueView>(value); int_value) { if (int_value->NativeValue() >= 0 && int_value->NativeValue() <= std::numeric_limits<int>::max()) { const auto* value_desc = desc->FindValueByNumber(static_cast<int>(int_value->NativeValue())); if (value_desc != nullptr) { return value_desc->number(); } } return absl::NotFoundError(absl::StrCat("enum `", desc->full_name(), "` has no value with number ", int_value->NativeValue())); } return TypeConversionError(value.GetTypeName(), desc->full_name()) .NativeValue(); } }
#include "extensions/protobuf/value.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #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 "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "base/attribute.h" #include "base/internal/message_wrapper.h" #include "common/casting.h" #include "common/memory.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_testing.h" #include "eval/public/structs/proto_message_type_adapter.h" #include "extensions/protobuf/memory_manager.h" #include "internal/proto_matchers.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/text_format.h" namespace cel::extensions { namespace { using ::cel::internal::test::EqualsProto; using ::cel::test::BoolValueIs; using ::cel::test::BytesValueIs; using ::cel::test::DoubleValueIs; using ::cel::test::DurationValueIs; using ::cel::test::ErrorValueIs; using ::cel::test::IntValueIs; using ::cel::test::ListValueIs; using ::cel::test::MapValueIs; using ::cel::test::StringValueIs; using ::cel::test::StructValueFieldHas; using ::cel::test::StructValueFieldIs; using ::cel::test::StructValueIs; using ::cel::test::TimestampValueIs; using ::cel::test::UintValueIs; using ::cel::test::ValueKindIs; using ::google::api::expr::test::v1::proto2::TestAllTypes; using testing::_; using testing::AllOf; using testing::ElementsAre; using testing::Eq; using testing::HasSubstr; using testing::IsTrue; using testing::Pair; using testing::UnorderedElementsAre; using cel::internal::IsOk; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; template <typename T> T ParseTextOrDie(absl::string_view text) { T proto; ABSL_CHECK(google::protobuf::TextFormat::ParseFromString(text, &proto)); return proto; } class ProtoValueTest : public common_internal::ThreadCompatibleValueTest<> { protected: MemoryManager NewThreadCompatiblePoolingMemoryManager() override { return ProtoMemoryManager(&arena_); } private: google::protobuf::Arena arena_; }; class ProtoValueWrapTest : public ProtoValueTest {}; TEST_P(ProtoValueWrapTest, ProtoEnumToValue) { ASSERT_OK_AND_ASSIGN( auto enum_value, ProtoEnumToValue(value_factory(), google::protobuf::NullValue::NULL_VALUE)); ASSERT_TRUE(InstanceOf<NullValue>(enum_value)); ASSERT_OK_AND_ASSIGN(enum_value, ProtoEnumToValue(value_factory(), TestAllTypes::BAR)); ASSERT_TRUE(InstanceOf<IntValue>(enum_value)); ASSERT_THAT(Cast<IntValue>(enum_value).NativeValue(), Eq(1)); } TEST_P(ProtoValueWrapTest, ProtoBoolValueToValue) { google::protobuf::BoolValue message; message.set_value(true); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(BoolValueIs(Eq(true)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(BoolValueIs(Eq(true)))); } TEST_P(ProtoValueWrapTest, ProtoInt32ValueToValue) { google::protobuf::Int32Value message; message.set_value(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(IntValueIs(Eq(1)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(IntValueIs(Eq(1)))); } TEST_P(ProtoValueWrapTest, ProtoInt64ValueToValue) { google::protobuf::Int64Value message; message.set_value(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(IntValueIs(Eq(1)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(IntValueIs(Eq(1)))); } TEST_P(ProtoValueWrapTest, ProtoUInt32ValueToValue) { google::protobuf::UInt32Value message; message.set_value(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(UintValueIs(Eq(1)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(UintValueIs(Eq(1)))); } TEST_P(ProtoValueWrapTest, ProtoUInt64ValueToValue) { google::protobuf::UInt64Value message; message.set_value(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(UintValueIs(Eq(1)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(UintValueIs(Eq(1)))); } TEST_P(ProtoValueWrapTest, ProtoFloatValueToValue) { google::protobuf::FloatValue message; message.set_value(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(DoubleValueIs(Eq(1)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(DoubleValueIs(Eq(1)))); } TEST_P(ProtoValueWrapTest, ProtoDoubleValueToValue) { google::protobuf::DoubleValue message; message.set_value(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(DoubleValueIs(Eq(1)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(DoubleValueIs(Eq(1)))); } TEST_P(ProtoValueWrapTest, ProtoBytesValueToValue) { google::protobuf::BytesValue message; message.set_value("foo"); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(BytesValueIs(Eq("foo")))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(BytesValueIs(Eq("foo")))); } TEST_P(ProtoValueWrapTest, ProtoStringValueToValue) { google::protobuf::StringValue message; message.set_value("foo"); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(StringValueIs(Eq("foo")))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(StringValueIs(Eq("foo")))); } TEST_P(ProtoValueWrapTest, ProtoDurationToValue) { google::protobuf::Duration message; message.set_seconds(1); message.set_nanos(1); EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(DurationValueIs( Eq(absl::Seconds(1) + absl::Nanoseconds(1))))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(DurationValueIs( Eq(absl::Seconds(1) + absl::Nanoseconds(1))))); } TEST_P(ProtoValueWrapTest, ProtoTimestampToValue) { google::protobuf::Timestamp message; message.set_seconds(1); message.set_nanos(1); EXPECT_THAT( ProtoMessageToValue(value_manager(), message), IsOkAndHolds(TimestampValueIs( Eq(absl::UnixEpoch() + absl::Seconds(1) + absl::Nanoseconds(1))))); EXPECT_THAT( ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(TimestampValueIs( Eq(absl::UnixEpoch() + absl::Seconds(1) + absl::Nanoseconds(1))))); } TEST_P(ProtoValueWrapTest, ProtoMessageToValue) { TestAllTypes message; EXPECT_THAT(ProtoMessageToValue(value_manager(), message), IsOkAndHolds(ValueKindIs(Eq(ValueKind::kStruct)))); EXPECT_THAT(ProtoMessageToValue(value_manager(), std::move(message)), IsOkAndHolds(ValueKindIs(Eq(ValueKind::kStruct)))); } TEST_P(ProtoValueWrapTest, GetFieldByName) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 1 single_uint32: 1 single_uint64: 1 single_float: 1 single_double: 1 single_bool: true single_string: "foo" single_bytes: "foo")pb"))); EXPECT_THAT(value, StructValueIs(StructValueFieldIs( &value_manager(), "single_int32", IntValueIs(Eq(1))))); EXPECT_THAT(value, StructValueIs(StructValueFieldHas("single_int32", IsTrue()))); EXPECT_THAT(value, StructValueIs(StructValueFieldIs( &value_manager(), "single_int64", IntValueIs(Eq(1))))); EXPECT_THAT(value, StructValueIs(StructValueFieldHas("single_int64", IsTrue()))); EXPECT_THAT( value, StructValueIs(StructValueFieldIs(&value_manager(), "single_uint32", UintValueIs(Eq(1))))); EXPECT_THAT(value, StructValueIs(StructValueFieldHas("single_uint32", IsTrue()))); EXPECT_THAT( value, StructValueIs(StructValueFieldIs(&value_manager(), "single_uint64", UintValueIs(Eq(1))))); EXPECT_THAT(value, StructValueIs(StructValueFieldHas("single_uint64", IsTrue()))); } TEST_P(ProtoValueWrapTest, GetFieldNoSuchField) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue( value_manager(), ParseTextOrDie<TestAllTypes>(R"pb(single_int32: 1)pb"))); ASSERT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); EXPECT_THAT(struct_value.GetFieldByName(value_manager(), "does_not_exist"), IsOkAndHolds(ErrorValueIs(StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field"))))); } TEST_P(ProtoValueWrapTest, GetFieldByNumber) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 single_uint32: 3 single_uint64: 4 single_float: 1.25 single_double: 1.5 single_bool: true single_string: "foo" single_bytes: "foo")pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleInt32FieldNumber), IsOkAndHolds(IntValueIs(1))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleInt64FieldNumber), IsOkAndHolds(IntValueIs(2))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleUint32FieldNumber), IsOkAndHolds(UintValueIs(3))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleUint64FieldNumber), IsOkAndHolds(UintValueIs(4))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleFloatFieldNumber), IsOkAndHolds(DoubleValueIs(1.25))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleDoubleFieldNumber), IsOkAndHolds(DoubleValueIs(1.5))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleBoolFieldNumber), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleStringFieldNumber), IsOkAndHolds(StringValueIs("foo"))); EXPECT_THAT(struct_value.GetFieldByNumber( value_manager(), TestAllTypes::kSingleBytesFieldNumber), IsOkAndHolds(BytesValueIs("foo"))); } TEST_P(ProtoValueWrapTest, GetFieldByNumberNoSuchField) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 single_uint32: 3 single_uint64: 4 single_float: 1.25 single_double: 1.5 single_bool: true single_string: "foo" single_bytes: "foo")pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); EXPECT_THAT(struct_value.GetFieldByNumber(value_manager(), 999), IsOkAndHolds(ErrorValueIs(StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field"))))); EXPECT_THAT(struct_value.GetFieldByNumber(value_manager(), 0x1ffffffff), IsOkAndHolds(ErrorValueIs(StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field"))))); } TEST_P(ProtoValueWrapTest, HasFieldByNumber) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2)pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); EXPECT_THAT( struct_value.HasFieldByNumber(TestAllTypes::kSingleInt32FieldNumber), IsOkAndHolds(BoolValue(true))); EXPECT_THAT( struct_value.HasFieldByNumber(TestAllTypes::kSingleInt64FieldNumber), IsOkAndHolds(BoolValue(true))); EXPECT_THAT( struct_value.HasFieldByNumber(TestAllTypes::kSingleStringFieldNumber), IsOkAndHolds(BoolValue(false))); EXPECT_THAT( struct_value.HasFieldByNumber(TestAllTypes::kSingleBytesFieldNumber), IsOkAndHolds(BoolValue(false))); } TEST_P(ProtoValueWrapTest, HasFieldByNumberNoSuchField) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2)pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); EXPECT_THAT( struct_value.HasFieldByNumber(999), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field"))); EXPECT_THAT( struct_value.HasFieldByNumber(0x1ffffffff), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field"))); } TEST_P(ProtoValueWrapTest, ProtoMessageDebugString) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 )pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); EXPECT_THAT(struct_value.DebugString(), AllOf(HasSubstr("single_int32:"), HasSubstr("1"), HasSubstr("single_int64:"), HasSubstr("2"))); } TEST_P(ProtoValueWrapTest, ProtoMessageEqual) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 )pb"))); ASSERT_OK_AND_ASSIGN( auto value2, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 )pb"))); EXPECT_THAT(value.Equal(value_manager(), value), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(value2.Equal(value_manager(), value), IsOkAndHolds(BoolValueIs(true))); } TEST_P(ProtoValueWrapTest, ProtoMessageEqualFalse) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 )pb"))); ASSERT_OK_AND_ASSIGN( auto value2, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 2, single_int64: 1 )pb"))); EXPECT_THAT(value2.Equal(value_manager(), value), IsOkAndHolds(BoolValueIs(false))); } TEST_P(ProtoValueWrapTest, ProtoMessageForEachField) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb(single_int32: 1, single_int64: 2 )pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); std::vector<std::string> fields; auto cb = [&fields](absl::string_view field, ValueView) -> absl::StatusOr<bool> { fields.push_back(std::string(field)); return true; }; ASSERT_OK(struct_value.ForEachField(value_manager(), cb)); EXPECT_THAT(fields, UnorderedElementsAre("single_int32", "single_int64")); } TEST_P(ProtoValueWrapTest, ProtoMessageQualify) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( standalone_message { bb: 42 } )pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); std::vector<SelectQualifier> qualifiers{ FieldSpecifier{TestAllTypes::kStandaloneMessageFieldNumber, "standalone_message"}, FieldSpecifier{TestAllTypes::NestedMessage::kBbFieldNumber, "bb"}}; Value scratch; ASSERT_OK_AND_ASSIGN(auto qualify_value, struct_value.Qualify(value_manager(), qualifiers, false, scratch)); static_cast<void>(qualify_value); EXPECT_THAT(scratch, IntValueIs(42)); } TEST_P(ProtoValueWrapTest, ProtoMessageQualifyHas) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( standalone_message { bb: 42 } )pb"))); EXPECT_THAT(value, StructValueIs(_)); StructValue struct_value = Cast<StructValue>(value); std::vector<SelectQualifier> qualifiers{ FieldSpecifier{TestAllTypes::kStandaloneMessageFieldNumber, "standalone_message"}, FieldSpecifier{TestAllTypes::NestedMessage::kBbFieldNumber, "bb"}}; Value scratch; ASSERT_OK_AND_ASSIGN(auto qualify_value, struct_value.Qualify(value_manager(), qualifiers, true, scratch)); static_cast<void>(qualify_value); EXPECT_THAT(scratch, BoolValueIs(true)); } TEST_P(ProtoValueWrapTest, ProtoInt64MapListKeys) { if (memory_management() == MemoryManagement::kReferenceCounting) { GTEST_SKIP() << "TODO(uncreated-issue/66): use after free"; } ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_int64_int64 { key: 10 value: 20 })pb"))); ASSERT_OK_AND_ASSIGN(auto map_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_int64_int64")); ASSERT_THAT(map_value, MapValueIs(_)); ASSERT_OK_AND_ASSIGN(ListValue key_set, Cast<MapValue>(map_value).ListKeys(value_manager())); EXPECT_THAT(key_set.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(Value key0, key_set.Get(value_manager(), 0)); EXPECT_THAT(key0, IntValueIs(10)); } TEST_P(ProtoValueWrapTest, ProtoInt32MapListKeys) { if (memory_management() == MemoryManagement::kReferenceCounting) { GTEST_SKIP() << "TODO(uncreated-issue/66): use after free"; } ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_int32_int64 { key: 10 value: 20 })pb"))); ASSERT_OK_AND_ASSIGN(auto map_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_int32_int64")); ASSERT_THAT(map_value, MapValueIs(_)); ASSERT_OK_AND_ASSIGN(ListValue key_set, Cast<MapValue>(map_value).ListKeys(value_manager())); EXPECT_THAT(key_set.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(Value key0, key_set.Get(value_manager(), 0)); EXPECT_THAT(key0, IntValueIs(10)); } TEST_P(ProtoValueWrapTest, ProtoBoolMapListKeys) { if (memory_management() == MemoryManagement::kReferenceCounting) { GTEST_SKIP() << "TODO(uncreated-issue/66): use after free"; } ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_bool_int64 { key: false value: 20 })pb"))); ASSERT_OK_AND_ASSIGN(auto map_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_bool_int64")); ASSERT_THAT(map_value, MapValueIs(_)); ASSERT_OK_AND_ASSIGN(ListValue key_set, Cast<MapValue>(map_value).ListKeys(value_manager())); EXPECT_THAT(key_set.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(Value key0, key_set.Get(value_manager(), 0)); EXPECT_THAT(key0, BoolValueIs(false)); } TEST_P(ProtoValueWrapTest, ProtoUint32MapListKeys) { if (memory_management() == MemoryManagement::kReferenceCounting) { GTEST_SKIP() << "TODO(uncreated-issue/66): use after free"; } ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_uint32_int64 { key: 11 value: 20 })pb"))); ASSERT_OK_AND_ASSIGN(auto map_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_uint32_int64")); ASSERT_THAT(map_value, MapValueIs(_)); ASSERT_OK_AND_ASSIGN(ListValue key_set, Cast<MapValue>(map_value).ListKeys(value_manager())); EXPECT_THAT(key_set.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(Value key0, key_set.Get(value_manager(), 0)); EXPECT_THAT(key0, UintValueIs(11)); } TEST_P(ProtoValueWrapTest, ProtoUint64MapListKeys) { if (memory_management() == MemoryManagement::kReferenceCounting) { GTEST_SKIP() << "TODO(uncreated-issue/66): use after free"; } ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_uint64_int64 { key: 11 value: 20 })pb"))); ASSERT_OK_AND_ASSIGN(auto map_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_uint64_int64")); ASSERT_THAT(map_value, MapValueIs(_)); ASSERT_OK_AND_ASSIGN(ListValue key_set, Cast<MapValue>(map_value).ListKeys(value_manager())); EXPECT_THAT(key_set.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(Value key0, key_set.Get(value_manager(), 0)); EXPECT_THAT(key0, UintValueIs(11)); } TEST_P(ProtoValueWrapTest, ProtoStringMapListKeys) { if (memory_management() == MemoryManagement::kReferenceCounting) { GTEST_SKIP() << "TODO(uncreated-issue/66): use after free"; } ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue( value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_string_int64 { key: "key1" value: 20 })pb"))); ASSERT_OK_AND_ASSIGN(auto map_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_string_int64")); ASSERT_THAT(map_value, MapValueIs(_)); ASSERT_OK_AND_ASSIGN(ListValue key_set, Cast<MapValue>(map_value).ListKeys(value_manager())); EXPECT_THAT(key_set.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(Value key0, key_set.Get(value_manager(), 0)); EXPECT_THAT(key0, StringValueIs("key1")); } TEST_P(ProtoValueWrapTest, ProtoMapDebugString) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_int64_int64 { key: 10 value: 20 } map_int64_int64 { key: 12 value: 24 } )pb"))); ASSERT_OK_AND_ASSIGN(auto field_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_int64_int64")); ASSERT_THAT(field_value, MapValueIs(_)); MapValue map_value = Cast<MapValue>(field_value); EXPECT_THAT(map_value.DebugString(), AllOf(HasSubstr("10:"), HasSubstr("20"), HasSubstr("12:"), HasSubstr("24"))); } TEST_P(ProtoValueWrapTest, ProtoMapIterator) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_int64_int64 { key: 10 value: 20 } map_int64_int64 { key: 12 value: 24 } )pb"))); ASSERT_OK_AND_ASSIGN(auto field_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_int64_int64")); ASSERT_THAT(field_value, MapValueIs(_)); MapValue map_value = Cast<MapValue>(field_value); std::vector<Value> keys; ASSERT_OK_AND_ASSIGN(auto iter, map_value.NewIterator(value_manager())); while (iter->HasNext()) { ASSERT_OK_AND_ASSIGN(keys.emplace_back(), iter->Next(value_manager())); } EXPECT_THAT(keys, UnorderedElementsAre(IntValueIs(10), IntValueIs(12))); } TEST_P(ProtoValueWrapTest, ProtoMapForEach) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( map_int64_int64 { key: 10 value: 20 } map_int64_int64 { key: 12 value: 24 } )pb"))); ASSERT_OK_AND_ASSIGN(auto field_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "map_int64_int64")); ASSERT_THAT(field_value, MapValueIs(_)); MapValue map_value = Cast<MapValue>(field_value); std::vector<std::pair<Value, Value>> pairs; auto cb = [&pairs](ValueView key, ValueView value) -> absl::StatusOr<bool> { pairs.push_back(std::pair<Value, Value>(key, value)); return true; }; ASSERT_OK(map_value.ForEach(value_manager(), cb)); EXPECT_THAT(pairs, UnorderedElementsAre(Pair(IntValueIs(10), IntValueIs(20)), Pair(IntValueIs(12), IntValueIs(24)))); } TEST_P(ProtoValueWrapTest, ProtoListIterator) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( repeated_int64: 1 repeated_int64: 2 )pb"))); ASSERT_OK_AND_ASSIGN(auto field_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "repeated_int64")); ASSERT_THAT(field_value, ListValueIs(_)); ListValue list_value = Cast<ListValue>(field_value); std::vector<Value> elements; ASSERT_OK_AND_ASSIGN(auto iter, list_value.NewIterator(value_manager())); while (iter->HasNext()) { ASSERT_OK_AND_ASSIGN(elements.emplace_back(), iter->Next(value_manager())); } EXPECT_THAT(elements, ElementsAre(IntValueIs(1), IntValueIs(2))); } TEST_P(ProtoValueWrapTest, ProtoListForEachWithIndex) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( repeated_int64: 1 repeated_int64: 2 )pb"))); ASSERT_OK_AND_ASSIGN(auto field_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "repeated_int64")); ASSERT_THAT(field_value, ListValueIs(_)); ListValue list_value = Cast<ListValue>(field_value); std::vector<std::pair<size_t, Value>> elements; auto cb = [&elements](size_t index, ValueView value) -> absl::StatusOr<bool> { elements.push_back(std::pair<size_t, Value>(index, value)); return true; }; ASSERT_OK(list_value.ForEach(value_manager(), cb)); EXPECT_THAT(elements, ElementsAre(Pair(0, IntValueIs(1)), Pair(1, IntValueIs(2)))); } TEST_P(ProtoValueWrapTest, ProtoListDebugString) { ASSERT_OK_AND_ASSIGN( auto value, ProtoMessageToValue(value_manager(), ParseTextOrDie<TestAllTypes>( R"pb( repeated_int64: 1 repeated_int64: 2 )pb"))); ASSERT_OK_AND_ASSIGN(auto field_value, Cast<StructValue>(value).GetFieldByName( value_manager(), "repeated_int64")); ASSERT_THAT(field_value, ListValueIs(_)); ListValue list_value = Cast<ListValue>(field_value); EXPECT_THAT(list_value.DebugString(), AllOf(HasSubstr("1"), HasSubstr("2"))); } INSTANTIATE_TEST_SUITE_P(ProtoValueTest, ProtoValueWrapTest, testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoValueTest::ToString); struct DefaultArenaDeleter { template <typename T> void operator()(T* message) const { if (arena == nullptr) { delete message; } } google::protobuf::Arena* arena = nullptr; }; template <typename T> using ArenaUniquePtr = std::unique_ptr<T, DefaultArenaDeleter>; template <typename T> ArenaUniquePtr<T> WrapArenaUnique(T* message) { return ArenaUniquePtr<T>(message, DefaultArenaDeleter{mess
19
cpp
google/cel-cpp
byte_string
common/internal/byte_string.cc
common/internal/byte_string_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_BYTE_STRING_H_ #define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_BYTE_STRING_H_ #include <cstddef> #include <cstdint> #include <functional> #include <new> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/hash/hash.h" #include "absl/log/absl_check.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/internal/metadata.h" #include "common/internal/reference_count.h" #include "common/memory.h" #include "google/protobuf/arena.h" namespace cel::common_internal { #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || defined(ABSL_HAVE_MEMORY_SANITIZER) #define CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI #else #define CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI ABSL_ATTRIBUTE_TRIVIAL_ABI #endif class CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI [[nodiscard]] ByteString; class ByteStringView; struct ByteStringTestFriend; struct ByteStringViewTestFriend; enum class ByteStringKind : unsigned int { kSmall = 0, kMedium, kLarge, }; inline std::ostream& operator<<(std::ostream& out, ByteStringKind kind) { switch (kind) { case ByteStringKind::kSmall: return out << "SMALL"; case ByteStringKind::kMedium: return out << "MEDIUM"; case ByteStringKind::kLarge: return out << "LARGE"; } } struct CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI SmallByteStringRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI { ByteStringKind kind : 2; size_t size : 6; }; #ifdef _MSC_VER #pragma pop(pack) #endif char data[23 - sizeof(google::protobuf::Arena*)]; google::protobuf::Arena* arena; }; inline constexpr size_t kSmallByteStringCapacity = sizeof(SmallByteStringRep::data); inline constexpr size_t kMediumByteStringSizeBits = sizeof(size_t) * 8 - 2; inline constexpr size_t kMediumByteStringMaxSize = (size_t{1} << kMediumByteStringSizeBits) - 1; inline constexpr size_t kByteStringViewSizeBits = sizeof(size_t) * 8 - 1; inline constexpr size_t kByteStringViewMaxSize = (size_t{1} << kByteStringViewSizeBits) - 1; struct CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI MediumByteStringRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI { ByteStringKind kind : 2; size_t size : kMediumByteStringSizeBits; }; #ifdef _MSC_VER #pragma pop(pack) #endif const char* data; uintptr_t owner; }; struct CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI LargeByteStringRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI { ByteStringKind kind : 2; size_t padding : kMediumByteStringSizeBits; }; #ifdef _MSC_VER #pragma pop(pack) #endif alignas(absl::Cord) char data[sizeof(absl::Cord)]; }; union CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI ByteStringRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI { ByteStringKind kind : 2; } header; #ifdef _MSC_VER #pragma pop(pack) #endif SmallByteStringRep small; MediumByteStringRep medium; LargeByteStringRep large; }; class CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI [[nodiscard]] ByteString final { public: static ByteString Owned(Allocator<> allocator, const char* string) { return ByteString(allocator, string); } static ByteString Owned(Allocator<> allocator, absl::string_view string) { return ByteString(allocator, string); } static ByteString Owned(Allocator<> allocator, const std::string& string) { return ByteString(allocator, string); } static ByteString Owned(Allocator<> allocator, std::string&& string) { return ByteString(allocator, std::move(string)); } static ByteString Owned(Allocator<> allocator, const absl::Cord& cord) { return ByteString(allocator, cord); } static ByteString Owned(Allocator<> allocator, ByteStringView other); static ByteString Borrowed( Owner owner, absl::string_view string ABSL_ATTRIBUTE_LIFETIME_BOUND); static ByteString Borrowed( const Owner& owner, const absl::Cord& cord ABSL_ATTRIBUTE_LIFETIME_BOUND); ByteString() noexcept : ByteString(NewDeleteAllocator()) {} explicit ByteString(const char* string) : ByteString(NewDeleteAllocator(), string) {} explicit ByteString(absl::string_view string) : ByteString(NewDeleteAllocator(), string) {} explicit ByteString(const std::string& string) : ByteString(NewDeleteAllocator(), string) {} explicit ByteString(std::string&& string) : ByteString(NewDeleteAllocator(), std::move(string)) {} explicit ByteString(const absl::Cord& cord) : ByteString(NewDeleteAllocator(), cord) {} explicit ByteString(ByteStringView other); ByteString(const ByteString& other) : ByteString(other.GetArena(), other) {} ByteString(ByteString&& other) : ByteString(other.GetArena(), std::move(other)) {} explicit ByteString(Allocator<> allocator) noexcept { SetSmallEmpty(allocator.arena()); } ByteString(Allocator<> allocator, const char* string) : ByteString(allocator, absl::NullSafeStringView(string)) {} ByteString(Allocator<> allocator, absl::string_view string); ByteString(Allocator<> allocator, const std::string& string); ByteString(Allocator<> allocator, std::string&& string); ByteString(Allocator<> allocator, const absl::Cord& cord); ByteString(Allocator<> allocator, ByteStringView other); ByteString(Allocator<> allocator, const ByteString& other) : ByteString(allocator) { CopyFrom(other); } ByteString(Allocator<> allocator, ByteString&& other) : ByteString(allocator) { MoveFrom(other); } ~ByteString() { Destroy(); } ByteString& operator=(const ByteString& other) { if (ABSL_PREDICT_TRUE(this != &other)) { CopyFrom(other); } return *this; } ByteString& operator=(ByteString&& other) { if (ABSL_PREDICT_TRUE(this != &other)) { MoveFrom(other); } return *this; } ByteString& operator=(ByteStringView other); bool empty() const noexcept; size_t size() const noexcept; size_t max_size() const noexcept { return kByteStringViewMaxSize; } absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::optional<absl::string_view> TryFlat() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::string_view GetFlat(std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND; bool Equals(ByteStringView rhs) const noexcept; int Compare(ByteStringView rhs) const noexcept; bool StartsWith(ByteStringView rhs) const noexcept; bool EndsWith(ByteStringView rhs) const noexcept; void RemovePrefix(size_t n); void RemoveSuffix(size_t n); std::string ToString() const; absl::Cord ToCord() const&; absl::Cord ToCord() &&; absl::Nullable<google::protobuf::Arena*> GetArena() const noexcept; void HashValue(absl::HashState state) const; void swap(ByteString& other) { if (ABSL_PREDICT_TRUE(this != &other)) { Swap(other); } } template <typename Visitor> std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>, std::invoke_result_t<Visitor, const absl::Cord&>> Visit(Visitor&& visitor) const { switch (GetKind()) { case ByteStringKind::kSmall: return std::invoke(std::forward<Visitor>(visitor), GetSmall()); case ByteStringKind::kMedium: return std::invoke(std::forward<Visitor>(visitor), GetMedium()); case ByteStringKind::kLarge: return std::invoke(std::forward<Visitor>(visitor), GetLarge()); } } friend void swap(ByteString& lhs, ByteString& rhs) { lhs.swap(rhs); } private: friend class ByteStringView; friend struct ByteStringTestFriend; ByteString(absl::Nonnull<const ReferenceCount*> refcount, absl::string_view string); constexpr ByteStringKind GetKind() const noexcept { return rep_.header.kind; } absl::string_view GetSmall() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); return GetSmall(rep_.small); } static absl::string_view GetSmall(const SmallByteStringRep& rep) noexcept { return absl::string_view(rep.data, rep.size); } absl::string_view GetMedium() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); return GetMedium(rep_.medium); } static absl::string_view GetMedium(const MediumByteStringRep& rep) noexcept { return absl::string_view(rep.data, rep.size); } absl::Nullable<google::protobuf::Arena*> GetSmallArena() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); return GetSmallArena(rep_.small); } static absl::Nullable<google::protobuf::Arena*> GetSmallArena( const SmallByteStringRep& rep) noexcept { return rep.arena; } absl::Nullable<google::protobuf::Arena*> GetMediumArena() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); return GetMediumArena(rep_.medium); } static absl::Nullable<google::protobuf::Arena*> GetMediumArena( const MediumByteStringRep& rep) noexcept; absl::Nullable<const ReferenceCount*> GetMediumReferenceCount() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); return GetMediumReferenceCount(rep_.medium); } static absl::Nullable<const ReferenceCount*> GetMediumReferenceCount( const MediumByteStringRep& rep) noexcept; uintptr_t GetMediumOwner() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); return rep_.medium.owner; } absl::Cord& GetLarge() noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); return GetLarge(rep_.large); } static absl::Cord& GetLarge( LargeByteStringRep& rep ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *std::launder(reinterpret_cast<absl::Cord*>(&rep.data[0])); } const absl::Cord& GetLarge() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); return GetLarge(rep_.large); } static const absl::Cord& GetLarge( const LargeByteStringRep& rep ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *std::launder(reinterpret_cast<const absl::Cord*>(&rep.data[0])); } void SetSmallEmpty(absl::Nullable<google::protobuf::Arena*> arena); void SetSmall(absl::Nullable<google::protobuf::Arena*> arena, absl::string_view string); void SetSmall(absl::Nullable<google::protobuf::Arena*> arena, const absl::Cord& cord); void SetMedium(absl::Nullable<google::protobuf::Arena*> arena, absl::string_view string); void SetMedium(absl::Nullable<google::protobuf::Arena*> arena, std::string&& string); void SetMedium(absl::Nonnull<google::protobuf::Arena*> arena, const absl::Cord& cord); void SetMedium(absl::string_view string, uintptr_t owner); void SetMediumOrLarge(absl::Nullable<google::protobuf::Arena*> arena, const absl::Cord& cord); void SetMediumOrLarge(absl::Nullable<google::protobuf::Arena*> arena, absl::Cord&& cord); void SetLarge(const absl::Cord& cord); void SetLarge(absl::Cord&& cord); void Swap(ByteString& other); static void SwapSmallSmall(ByteString& lhs, ByteString& rhs); static void SwapSmallMedium(ByteString& lhs, ByteString& rhs); static void SwapSmallLarge(ByteString& lhs, ByteString& rhs); static void SwapMediumMedium(ByteString& lhs, ByteString& rhs); static void SwapMediumLarge(ByteString& lhs, ByteString& rhs); static void SwapLargeLarge(ByteString& lhs, ByteString& rhs); void CopyFrom(const ByteString& other); void CopyFromSmallSmall(const ByteString& other); void CopyFromSmallMedium(const ByteString& other); void CopyFromSmallLarge(const ByteString& other); void CopyFromMediumSmall(const ByteString& other); void CopyFromMediumMedium(const ByteString& other); void CopyFromMediumLarge(const ByteString& other); void CopyFromLargeSmall(const ByteString& other); void CopyFromLargeMedium(const ByteString& other); void CopyFromLargeLarge(const ByteString& other); void CopyFrom(ByteStringView other); void CopyFromSmallString(ByteStringView other); void CopyFromSmallCord(ByteStringView other); void CopyFromMediumString(ByteStringView other); void CopyFromMediumCord(ByteStringView other); void CopyFromLargeString(ByteStringView other); void CopyFromLargeCord(ByteStringView other); void MoveFrom(ByteString& other); void MoveFromSmallSmall(ByteString& other); void MoveFromSmallMedium(ByteString& other); void MoveFromSmallLarge(ByteString& other); void MoveFromMediumSmall(ByteString& other); void MoveFromMediumMedium(ByteString& other); void MoveFromMediumLarge(ByteString& other); void MoveFromLargeSmall(ByteString& other); void MoveFromLargeMedium(ByteString& other); void MoveFromLargeLarge(ByteString& other); void Destroy() noexcept; void DestroyMedium() noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); DestroyMedium(rep_.medium); } static void DestroyMedium(const MediumByteStringRep& rep) noexcept { StrongUnref(GetMediumReferenceCount(rep)); } void DestroyLarge() noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); DestroyLarge(rep_.large); } static void DestroyLarge(LargeByteStringRep& rep) noexcept { GetLarge(rep).~Cord(); } ByteStringRep rep_; }; template <typename H> H AbslHashValue(H state, const ByteString& byte_string) { byte_string.HashValue(absl::HashState::Create(&state)); return state; } enum class ByteStringViewKind : unsigned int { kString = 0, kCord, }; inline std::ostream& operator<<(std::ostream& out, ByteStringViewKind kind) { switch (kind) { case ByteStringViewKind::kString: return out << "STRING"; case ByteStringViewKind::kCord: return out << "CORD"; } } struct StringByteStringViewRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED { ByteStringViewKind kind : 1; size_t size : kByteStringViewSizeBits; }; #ifdef _MSC_VER #pragma pop(pack) #endif const char* data; uintptr_t owner; }; struct CordByteStringViewRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED { ByteStringViewKind kind : 1; size_t size : kByteStringViewSizeBits; }; #ifdef _MSC_VER #pragma pop(pack) #endif const absl::Cord* data; size_t pos; }; union ByteStringViewRep final { #ifdef _MSC_VER #pragma push(pack, 1) #endif struct ABSL_ATTRIBUTE_PACKED { ByteStringViewKind kind : 1; size_t size : kByteStringViewSizeBits; } header; #ifdef _MSC_VER #pragma pop(pack) #endif StringByteStringViewRep string; CordByteStringViewRep cord; }; class ByteStringView final { public: ByteStringView() noexcept { rep_.header.kind = ByteStringViewKind::kString; rep_.string.size = 0; rep_.string.data = ""; rep_.string.owner = 0; } ByteStringView(const ByteStringView&) = default; ByteStringView(ByteStringView&&) = default; ByteStringView& operator=(const ByteStringView&) = default; ByteStringView& operator=(ByteStringView&&) = default; ByteStringView(const char* string ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : ByteStringView(absl::NullSafeStringView(string)) {} ByteStringView( absl::string_view string ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ABSL_DCHECK_LE(string.size(), max_size()); rep_.header.kind = ByteStringViewKind::kString; rep_.string.size = string.size(); rep_.string.data = string.data(); rep_.string.owner = 0; } ByteStringView( const std::string& string ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : ByteStringView(absl::string_view(string)) {} ByteStringView( const absl::Cord& cord ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { ABSL_DCHECK_LE(cord.size(), max_size()); rep_.header.kind = ByteStringViewKind::kCord; rep_.cord.size = cord.size(); rep_.cord.data = &cord; rep_.cord.pos = 0; } ByteStringView( const ByteString& other ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept; ByteStringView& operator=( const char* string ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *this = ByteStringView(string); } ByteStringView& operator=( absl::string_view string ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *this = ByteStringView(string); } ByteStringView& operator=( const std::string& string ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *this = ByteStringView(string); } ByteStringView& operator=(std::string&&) = delete; ByteStringView& operator=( const absl::Cord& cord ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *this = ByteStringView(cord); } ByteStringView& operator=(absl::Cord&&) = delete; ByteStringView& operator=( const ByteString& other ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { return *this = ByteStringView(other); } ByteStringView& operator=(ByteString&&) = delete; bool empty() const noexcept; size_t size() const noexcept; size_t max_size() const noexcept { return kByteStringViewMaxSize; } absl::optional<absl::string_view> TryFlat() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::string_view GetFlat(std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND; bool Equals(ByteStringView rhs) const noexcept; int Compare(ByteStringView rhs) const noexcept; bool StartsWith(ByteStringView rhs) const noexcept; bool EndsWith(ByteStringView rhs) const noexcept; void RemovePrefix(size_t n); void RemoveSuffix(size_t n); std::string ToString() const; absl::Cord ToCord() const; absl::Nullable<google::protobuf::Arena*> GetArena() const noexcept; void HashValue(absl::HashState state) const; template <typename Visitor> std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>, std::invoke_result_t<Visitor, const absl::Cord&>> Visit(Visitor&& visitor) const { switch (GetKind()) { case ByteStringViewKind::kString: return std::invoke(std::forward<Visitor>(visitor), GetString()); case ByteStringViewKind::kCord: return std::invoke(std::forward<Visitor>(visitor), static_cast<const absl::Cord&>(GetSubcord())); } } private: friend class ByteString; friend struct ByteStringViewTestFriend; constexpr ByteStringViewKind GetKind() const noexcept { return rep_.header.kind; } absl::string_view GetString() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringViewKind::kString); return absl::string_view(rep_.string.data, rep_.string.size); } absl::Nullable<google::protobuf::Arena*> GetStringArena() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringViewKind::kString); if ((rep_.string.owner & kMetadataOwnerBits) == kMetadataOwnerArenaBit) { return reinterpret_cast<google::protobuf::Arena*>(rep_.string.owner & kMetadataOwnerPointerMask); } return nullptr; } absl::Nullable<const ReferenceCount*> GetStringReferenceCount() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringViewKind::kString); return GetStringReferenceCount(rep_.string); } static absl::Nullable<const ReferenceCount*> GetStringReferenceCount( const StringByteStringViewRep& rep) noexcept { if ((rep.owner & kMetadataOwnerBits) == kMetadataOwnerReferenceCountBit) { return reinterpret_cast<const ReferenceCount*>(rep.owner & kMetadataOwnerPointerMask); } return nullptr; } uintptr_t GetStringOwner() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringViewKind::kString); return rep_.string.owner; } const absl::Cord& GetCord() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringViewKind::kCord); return *rep_.cord.data; } absl::Cord GetSubcord() const noexcept { ABSL_DCHECK_EQ(GetKind(), ByteStringViewKind::kCord); return GetCord().Subcord(rep_.cord.pos, rep_.cord.size); } ByteStringViewRep rep_; }; inline bool operator==(const ByteString& lhs, const ByteString& rhs) noexcept { return lhs.Equals(rhs); } inline bool operator!=(const ByteString& lhs, const ByteString& rhs) noexcept { return !operator==(lhs, rhs); } inline bool operator<(const ByteString& lhs, const ByteString& rhs) noexcept { return lhs.Compare(rhs) < 0; } inline bool operator<=(const ByteString& lhs, const ByteString& rhs) noexcept { return lhs.Compare(rhs) <= 0; } inline bool operator>(const ByteString& lhs, const ByteString& rhs) noexcept { return lhs.Compare(rhs) > 0; } inline bool operator>=(const ByteString& lhs, const ByteString& rhs) noexcept { return lhs.Compare(rhs) >= 0; } inline bool ByteString::Equals(ByteStringView rhs) const noexcept { return ByteStringView(*this).Equals(rhs); } inline int ByteString::Compare(ByteStringView rhs) const noexcept { return ByteStringView(*this).Compare(rhs); } inline bool ByteString::StartsWith(ByteStringView rhs) const noexcept { return ByteStringView(*this).StartsWith(rhs); } inline bool ByteString::EndsWith(ByteStringView rhs) const noexcept { return ByteStringView(*this).EndsWith(rhs); } inline bool operator==(ByteStringView lhs, ByteStringView rhs) noexcept { return lhs.Equals(rhs); } inline bool operator!=(ByteStringView lhs, ByteStringView rhs) noexcept { return !operator==(lhs, rhs); } inline bool operator<(ByteStringView lhs, ByteStringView rhs) noexcept { return lhs.Compare(rhs) < 0; } inline bool operator<=(ByteStringView lhs, ByteStringView rhs) noexcept { return lhs.Compare(rhs) <= 0; } inline bool operator>(ByteStringView lhs, ByteStringView rhs) noexcept { return lhs.Compare(rhs) > 0; } inline bool operator>=(ByteStringView lhs, ByteStringView rhs) noexcept { return lhs.Compare(rhs) >= 0; } template <typename H> H AbslHashValue(H state, ByteStringView byte_string_view) { byte_string_view.HashValue(absl::HashState::Create(&state)); return state; } inline ByteString ByteString::Owned(Allocator<> allocator, ByteStringView other) { return ByteString(allocator, other); } inline ByteString::ByteString(ByteStringView other) : ByteString(NewDeleteAllocator(), other) {} inline ByteString::ByteString(Allocator<> allocator, ByteStringView other) : ByteString(allocator) { CopyFrom(other); } inline ByteString& ByteString::operator=(ByteStringView other) { CopyFrom(other); return *this; } #undef CEL_COMMON_INTERNAL_BYTE_STRING_TRIVIAL_ABI } #endif #include "common/internal/byte_string.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <new> #include <string> #include <utility> #include "absl/base/nullability.h" #include "absl/functional/overload.h" #include "absl/hash/hash.h" #include "absl/log/absl_check.h" #include "absl/strings/cord.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/internal/metadata.h" #include "common/internal/reference_count.h" #include "common/memory.h" #include "internal/new.h" #include "google/protobuf/arena.h" namespace cel::common_internal { namespace { char* CopyCordToArray(const absl::Cord& cord, char* data) { for (auto chunk : cord.Chunks()) { std::memcpy(data, chunk.data(), chunk.size()); data += chunk.size(); } return data; } class ReferenceCountedStdString final : public ReferenceCounted { public: template <typename String> explicit ReferenceCountedStdString(String&& string) { ::new (static_cast<void*>(&string_[0])) std::string(std::forward<String>(string)); } const char* data() const noexcept { return std::launder(reinterpret_cast<const std::string*>(&string_[0])) ->data(); } size_t size() const noexcept { return std::launder(reinterpret_cast<const std::string*>(&string_[0])) ->size(); } private: void Finalize() noexcept override { std::destroy_at(std::launder(reinterpret_cast<std::string*>(&string_[0]))); } alignas(std::string) char string_[sizeof(std::string)]; }; class ReferenceCountedString final : public ReferenceCounted { public: static const ReferenceCountedString* New(const char* data, size_t size) { size_t offset = offsetof(ReferenceCountedString, data_); return ::new (internal::New(offset + size)) ReferenceCountedString(size, data); } const char* data() const noexcept { return reinterpret_cast<const char*>(&data_); } size_t size() const noexcept { return size_; } private: ReferenceCountedString(size_t size, const char* data) noexcept : size_(size) { std::memcpy(&data_, data, size); } void Delete() noexcept override { void* const that = this; const auto size = size_; std::destroy_at(this); internal::SizedDelete(that, offsetof(ReferenceCountedString, data_) + size); } const size_t size_; char data_[]; }; template <typename T> T ConsumeAndDestroy(T& object) { T consumed = std::move(object); object.~T(); return consumed; } } ByteString::ByteString(Allocator<> allocator, absl::string_view string) { ABSL_DCHECK_LE(string.size(), max_size()); auto* arena = allocator.arena(); if (string.size() <= kSmallByteStringCapacity) { SetSmall(arena, string); } else { SetMedium(arena, string); } } ByteString::ByteString(Allocator<> allocator, const std::string& string) { ABSL_DCHECK_LE(string.size(), max_size()); auto* arena = allocator.arena(); if (string.size() <= kSmallByteStringCapacity) { SetSmall(arena, string); } else { SetMedium(arena, string); } } ByteString::ByteString(Allocator<> allocator, std::string&& string) { ABSL_DCHECK_LE(string.size(), max_size()); auto* arena = allocator.arena(); if (string.size() <= kSmallByteStringCapacity) { SetSmall(arena, string); } else { SetMedium(arena, std::move(string)); } } ByteString::ByteString(Allocator<> allocator, const absl::Cord& cord) { ABSL_DCHECK_LE(cord.size(), max_size()); auto* arena = allocator.arena(); if (cord.size() <= kSmallByteStringCapacity) { SetSmall(arena, cord); } else if (arena != nullptr) { SetMedium(arena, cord); } else { SetLarge(cord); } } ByteString ByteString::Borrowed(Owner owner, absl::string_view string) { ABSL_DCHECK(owner != Owner::None()) << "Borrowing from Owner::None()"; auto* arena = owner.arena(); if (string.size() <= kSmallByteStringCapacity || arena != nullptr) { return ByteString(arena, string); } const auto* refcount = OwnerRelease(owner); if (refcount == nullptr) { auto* refcount_string = ReferenceCountedString::New(string.data(), string.size()); string = absl::string_view(refcount_string->data(), string.size()); refcount = refcount_string; } return ByteString(refcount, string); } ByteString ByteString::Borrowed(const Owner& owner, const absl::Cord& cord) { ABSL_DCHECK(owner != Owner::None()) << "Borrowing from Owner::None()"; return ByteString(owner.arena(), cord); } ByteString::ByteString(absl::Nonnull<const ReferenceCount*> refcount, absl::string_view string) { ABSL_DCHECK_LE(string.size(), max_size()); SetMedium(string, reinterpret_cast<uintptr_t>(refcount) | kMetadataOwnerReferenceCountBit); } absl::Nullable<google::protobuf::Arena*> ByteString::GetArena() const noexcept { switch (GetKind()) { case ByteStringKind::kSmall: return GetSmallArena(); case ByteStringKind::kMedium: return GetMediumArena(); case ByteStringKind::kLarge: return nullptr; } } bool ByteString::empty() const noexcept { switch (GetKind()) { case ByteStringKind::kSmall: return rep_.small.size == 0; case ByteStringKind::kMedium: return rep_.medium.size == 0; case ByteStringKind::kLarge: return GetLarge().empty(); } } size_t ByteString::size() const noexcept { switch (GetKind()) { case ByteStringKind::kSmall: return rep_.small.size; case ByteStringKind::kMedium: return rep_.medium.size; case ByteStringKind::kLarge: return GetLarge().size(); } } absl::string_view ByteString::Flatten() { switch (GetKind()) { case ByteStringKind::kSmall: return GetSmall(); case ByteStringKind::kMedium: return GetMedium(); case ByteStringKind::kLarge: return GetLarge().Flatten(); } } absl::optional<absl::string_view> ByteString::TryFlat() const noexcept { switch (GetKind()) { case ByteStringKind::kSmall: return GetSmall(); case ByteStringKind::kMedium: return GetMedium(); case ByteStringKind::kLarge: return GetLarge().TryFlat(); } } absl::string_view ByteString::GetFlat(std::string& scratch) const { switch (GetKind()) { case ByteStringKind::kSmall: return GetSmal
#include "common/internal/byte_string.h" #include <algorithm> #include <sstream> #include <string> #include <utility> #include "absl/base/no_destructor.h" #include "absl/hash/hash.h" #include "absl/strings/cord.h" #include "absl/strings/cord_test_helpers.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/internal/reference_count.h" #include "common/memory.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel::common_internal { struct ByteStringTestFriend { static ByteStringKind GetKind(const ByteString& byte_string) { return byte_string.GetKind(); } }; struct ByteStringViewTestFriend { static ByteStringViewKind GetKind(ByteStringView byte_string_view) { return byte_string_view.GetKind(); } }; namespace { using testing::Eq; using testing::IsEmpty; using testing::Not; using testing::Optional; using testing::SizeIs; using testing::TestWithParam; TEST(ByteStringKind, Ostream) { { std::ostringstream out; out << ByteStringKind::kSmall; EXPECT_EQ(out.str(), "SMALL"); } { std::ostringstream out; out << ByteStringKind::kMedium; EXPECT_EQ(out.str(), "MEDIUM"); } { std::ostringstream out; out << ByteStringKind::kLarge; EXPECT_EQ(out.str(), "LARGE"); } } TEST(ByteStringViewKind, Ostream) { { std::ostringstream out; out << ByteStringViewKind::kString; EXPECT_EQ(out.str(), "STRING"); } { std::ostringstream out; out << ByteStringViewKind::kCord; EXPECT_EQ(out.str(), "CORD"); } } class ByteStringTest : public TestWithParam<MemoryManagement>, public ByteStringTestFriend { public: Allocator<> GetAllocator() { switch (GetParam()) { case MemoryManagement::kPooling: return ArenaAllocator(&arena_); case MemoryManagement::kReferenceCounting: return NewDeleteAllocator(); } } private: google::protobuf::Arena arena_; }; absl::string_view GetSmallStringView() { static constexpr absl::string_view small = "A small string!"; return small.substr(0, std::min(kSmallByteStringCapacity, small.size())); } std::string GetSmallString() { return std::string(GetSmallStringView()); } absl::Cord GetSmallCord() { static const absl::NoDestructor<absl::Cord> small(GetSmallStringView()); return *small; } absl::string_view GetMediumStringView() { static constexpr absl::string_view medium = "A string that is too large for the small string optimization!"; return medium; } std::string GetMediumString() { return std::string(GetMediumStringView()); } const absl::Cord& GetMediumOrLargeCord() { static const absl::NoDestructor<absl::Cord> medium_or_large( GetMediumStringView()); return *medium_or_large; } const absl::Cord& GetMediumOrLargeFragmentedCord() { static const absl::NoDestructor<absl::Cord> medium_or_large( absl::MakeFragmentedCord( {GetMediumStringView().substr(0, kSmallByteStringCapacity), GetMediumStringView().substr(kSmallByteStringCapacity)})); return *medium_or_large; } TEST_P(ByteStringTest, Default) { ByteString byte_string = ByteString::Owned(GetAllocator(), ""); EXPECT_THAT(byte_string, SizeIs(0)); EXPECT_THAT(byte_string, IsEmpty()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); } TEST_P(ByteStringTest, ConstructSmallCString) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallString().c_str()); EXPECT_THAT(byte_string, SizeIs(GetSmallStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructMediumCString) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumString().c_str()); EXPECT_THAT(byte_string, SizeIs(GetMediumStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructSmallRValueString) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallString()); EXPECT_THAT(byte_string, SizeIs(GetSmallStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructSmallLValueString) { ByteString byte_string = ByteString::Owned( GetAllocator(), static_cast<const std::string&>(GetSmallString())); EXPECT_THAT(byte_string, SizeIs(GetSmallStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructMediumRValueString) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumString()); EXPECT_THAT(byte_string, SizeIs(GetMediumStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructMediumLValueString) { ByteString byte_string = ByteString::Owned( GetAllocator(), static_cast<const std::string&>(GetMediumString())); EXPECT_THAT(byte_string, SizeIs(GetMediumStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructSmallCord) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallCord()); EXPECT_THAT(byte_string, SizeIs(GetSmallStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringTest, ConstructMediumOrLargeCord) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_THAT(byte_string, SizeIs(GetMediumStringView().size())); EXPECT_THAT(byte_string, Not(IsEmpty())); EXPECT_EQ(byte_string, GetMediumStringView()); if (GetAllocator().arena() == nullptr) { EXPECT_EQ(GetKind(byte_string), ByteStringKind::kLarge); } else { EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); } EXPECT_EQ(byte_string.GetArena(), GetAllocator().arena()); } TEST(ByteStringTest, BorrowedUnownedString) { #ifdef NDEBUG ByteString byte_string = ByteString::Borrowed(Owner::None(), GetMediumStringView()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), nullptr); EXPECT_EQ(byte_string, GetMediumStringView()); #else EXPECT_DEBUG_DEATH(static_cast<void>(ByteString::Borrowed( Owner::None(), GetMediumStringView())), ::testing::_); #endif } TEST(ByteStringTest, BorrowedUnownedCord) { #ifdef NDEBUG ByteString byte_string = ByteString::Borrowed(Owner::None(), GetMediumOrLargeCord()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kLarge); EXPECT_EQ(byte_string.GetArena(), nullptr); EXPECT_EQ(byte_string, GetMediumOrLargeCord()); #else EXPECT_DEBUG_DEATH(static_cast<void>(ByteString::Borrowed( Owner::None(), GetMediumOrLargeCord())), ::testing::_); #endif } TEST(ByteStringTest, BorrowedReferenceCountSmallString) { auto* refcount = new ReferenceCounted(); Owner owner = Owner::ReferenceCount(refcount); StrongUnref(refcount); ByteString byte_string = ByteString::Borrowed(owner, GetSmallStringView()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetArena(), nullptr); EXPECT_EQ(byte_string, GetSmallStringView()); } TEST(ByteStringTest, BorrowedReferenceCountMediumString) { auto* refcount = new ReferenceCounted(); Owner owner = Owner::ReferenceCount(refcount); StrongUnref(refcount); ByteString byte_string = ByteString::Borrowed(owner, GetMediumStringView()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), nullptr); EXPECT_EQ(byte_string, GetMediumStringView()); } TEST(ByteStringTest, BorrowedArenaSmallString) { google::protobuf::Arena arena; ByteString byte_string = ByteString::Borrowed(Owner::Arena(&arena), GetSmallStringView()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetArena(), &arena); EXPECT_EQ(byte_string, GetSmallStringView()); } TEST(ByteStringTest, BorrowedArenaMediumString) { google::protobuf::Arena arena; ByteString byte_string = ByteString::Borrowed(Owner::Arena(&arena), GetMediumStringView()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), &arena); EXPECT_EQ(byte_string, GetMediumStringView()); } TEST(ByteStringTest, BorrowedReferenceCountCord) { auto* refcount = new ReferenceCounted(); Owner owner = Owner::ReferenceCount(refcount); StrongUnref(refcount); ByteString byte_string = ByteString::Borrowed(owner, GetMediumOrLargeCord()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kLarge); EXPECT_EQ(byte_string.GetArena(), nullptr); EXPECT_EQ(byte_string, GetMediumOrLargeCord()); } TEST(ByteStringTest, BorrowedArenaCord) { google::protobuf::Arena arena; Owner owner = Owner::Arena(&arena); ByteString byte_string = ByteString::Borrowed(owner, GetMediumOrLargeCord()); EXPECT_EQ(ByteStringTestFriend::GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetArena(), &arena); EXPECT_EQ(byte_string, GetMediumOrLargeCord()); } TEST_P(ByteStringTest, CopyFromByteStringView) { ByteString small_byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); ByteString medium_byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); ByteString large_byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); ByteString new_delete_byte_string(NewDeleteAllocator()); new_delete_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(small_byte_string)); new_delete_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(medium_byte_string)); new_delete_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(medium_byte_string)); new_delete_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(large_byte_string)); new_delete_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(large_byte_string)); new_delete_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(small_byte_string)); new_delete_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(large_byte_string)); new_delete_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(medium_byte_string)); new_delete_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(new_delete_byte_string, ByteStringView(small_byte_string)); google::protobuf::Arena arena; ByteString arena_byte_string(ArenaAllocator(&arena)); arena_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(small_byte_string)); arena_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(medium_byte_string)); arena_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(medium_byte_string)); arena_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(large_byte_string)); arena_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(large_byte_string)); arena_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(small_byte_string)); arena_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(large_byte_string)); arena_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(medium_byte_string)); arena_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(arena_byte_string, ByteStringView(small_byte_string)); ByteString allocator_byte_string(GetAllocator()); allocator_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(small_byte_string)); allocator_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(medium_byte_string)); allocator_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(medium_byte_string)); allocator_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(large_byte_string)); allocator_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(large_byte_string)); allocator_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(small_byte_string)); allocator_byte_string = ByteStringView(large_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(large_byte_string)); allocator_byte_string = ByteStringView(medium_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(medium_byte_string)); allocator_byte_string = ByteStringView(small_byte_string); EXPECT_EQ(allocator_byte_string, ByteStringView(small_byte_string)); allocator_byte_string = ByteStringView(absl::Cord(GetSmallStringView())); EXPECT_EQ(allocator_byte_string, GetSmallStringView()); allocator_byte_string = ByteStringView(medium_byte_string); allocator_byte_string = ByteStringView(absl::Cord(GetSmallStringView())); EXPECT_EQ(allocator_byte_string, GetSmallStringView()); allocator_byte_string = ByteStringView(large_byte_string); allocator_byte_string = ByteStringView(absl::Cord(GetSmallStringView())); EXPECT_EQ(allocator_byte_string, GetSmallStringView()); ByteString large_new_delete_byte_string(NewDeleteAllocator(), GetMediumOrLargeCord()); ByteString medium_arena_byte_string(ArenaAllocator(&arena), GetMediumStringView()); large_new_delete_byte_string = ByteStringView(medium_arena_byte_string); EXPECT_EQ(large_new_delete_byte_string, medium_arena_byte_string); } TEST_P(ByteStringTest, CopyFromByteString) { ByteString small_byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); ByteString medium_byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); ByteString large_byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); ByteString new_delete_byte_string(NewDeleteAllocator()); new_delete_byte_string = small_byte_string; EXPECT_EQ(new_delete_byte_string, small_byte_string); new_delete_byte_string = medium_byte_string; EXPECT_EQ(new_delete_byte_string, medium_byte_string); new_delete_byte_string = medium_byte_string; EXPECT_EQ(new_delete_byte_string, medium_byte_string); new_delete_byte_string = large_byte_string; EXPECT_EQ(new_delete_byte_string, large_byte_string); new_delete_byte_string = large_byte_string; EXPECT_EQ(new_delete_byte_string, large_byte_string); new_delete_byte_string = small_byte_string; EXPECT_EQ(new_delete_byte_string, small_byte_string); new_delete_byte_string = large_byte_string; EXPECT_EQ(new_delete_byte_string, large_byte_string); new_delete_byte_string = medium_byte_string; EXPECT_EQ(new_delete_byte_string, medium_byte_string); new_delete_byte_string = small_byte_string; EXPECT_EQ(new_delete_byte_string, small_byte_string); google::protobuf::Arena arena; ByteString arena_byte_string(ArenaAllocator(&arena)); arena_byte_string = small_byte_string; EXPECT_EQ(arena_byte_string, small_byte_string); arena_byte_string = medium_byte_string; EXPECT_EQ(arena_byte_string, medium_byte_string); arena_byte_string = medium_byte_string; EXPECT_EQ(arena_byte_string, medium_byte_string); arena_byte_string = large_byte_string; EXPECT_EQ(arena_byte_string, large_byte_string); arena_byte_string = large_byte_string; EXPECT_EQ(arena_byte_string, large_byte_string); arena_byte_string = small_byte_string; EXPECT_EQ(arena_byte_string, small_byte_string); arena_byte_string = large_byte_string; EXPECT_EQ(arena_byte_string, large_byte_string); arena_byte_string = medium_byte_string; EXPECT_EQ(arena_byte_string, medium_byte_string); arena_byte_string = small_byte_string; EXPECT_EQ(arena_byte_string, small_byte_string); ByteString allocator_byte_string(GetAllocator()); allocator_byte_string = small_byte_string; EXPECT_EQ(allocator_byte_string, small_byte_string); allocator_byte_string = medium_byte_string; EXPECT_EQ(allocator_byte_string, medium_byte_string); allocator_byte_string = medium_byte_string; EXPECT_EQ(allocator_byte_string, medium_byte_string); allocator_byte_string = large_byte_string; EXPECT_EQ(allocator_byte_string, large_byte_string); allocator_byte_string = large_byte_string; EXPECT_EQ(allocator_byte_string, large_byte_string); allocator_byte_string = small_byte_string; EXPECT_EQ(allocator_byte_string, small_byte_string); allocator_byte_string = large_byte_string; EXPECT_EQ(allocator_byte_string, large_byte_string); allocator_byte_string = medium_byte_string; EXPECT_EQ(allocator_byte_string, medium_byte_string); allocator_byte_string = small_byte_string; EXPECT_EQ(allocator_byte_string, small_byte_string); ByteString large_new_delete_byte_string(NewDeleteAllocator(), GetMediumOrLargeCord()); ByteString medium_arena_byte_string(ArenaAllocator(&arena), GetMediumStringView()); large_new_delete_byte_string = medium_arena_byte_string; EXPECT_EQ(large_new_delete_byte_string, medium_arena_byte_string); } TEST_P(ByteStringTest, MoveFrom) { const auto& small_byte_string = [this]() { return ByteString::Owned(GetAllocator(), GetSmallStringView()); }; const auto& medium_byte_string = [this]() { return ByteString::Owned(GetAllocator(), GetMediumStringView()); }; const auto& large_byte_string = [this]() { return ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); }; ByteString new_delete_byte_string(NewDeleteAllocator()); new_delete_byte_string = small_byte_string(); EXPECT_EQ(new_delete_byte_string, small_byte_string()); new_delete_byte_string = medium_byte_string(); EXPECT_EQ(new_delete_byte_string, medium_byte_string()); new_delete_byte_string = medium_byte_string(); EXPECT_EQ(new_delete_byte_string, medium_byte_string()); new_delete_byte_string = large_byte_string(); EXPECT_EQ(new_delete_byte_string, large_byte_string()); new_delete_byte_string = large_byte_string(); EXPECT_EQ(new_delete_byte_string, large_byte_string()); new_delete_byte_string = small_byte_string(); EXPECT_EQ(new_delete_byte_string, small_byte_string()); new_delete_byte_string = large_byte_string(); EXPECT_EQ(new_delete_byte_string, large_byte_string()); new_delete_byte_string = medium_byte_string(); EXPECT_EQ(new_delete_byte_string, medium_byte_string()); new_delete_byte_string = small_byte_string(); EXPECT_EQ(new_delete_byte_string, small_byte_string()); google::protobuf::Arena arena; ByteString arena_byte_string(ArenaAllocator(&arena)); arena_byte_string = small_byte_string(); EXPECT_EQ(arena_byte_string, small_byte_string()); arena_byte_string = medium_byte_string(); EXPECT_EQ(arena_byte_string, medium_byte_string()); arena_byte_string = medium_byte_string(); EXPECT_EQ(arena_byte_string, medium_byte_string()); arena_byte_string = large_byte_string(); EXPECT_EQ(arena_byte_string, large_byte_string()); arena_byte_string = large_byte_string(); EXPECT_EQ(arena_byte_string, large_byte_string()); arena_byte_string = small_byte_string(); EXPECT_EQ(arena_byte_string, small_byte_string()); arena_byte_string = large_byte_string(); EXPECT_EQ(arena_byte_string, large_byte_string()); arena_byte_string = medium_byte_string(); EXPECT_EQ(arena_byte_string, medium_byte_string()); arena_byte_string = small_byte_string(); EXPECT_EQ(arena_byte_string, small_byte_string()); ByteString allocator_byte_string(GetAllocator()); allocator_byte_string = small_byte_string(); EXPECT_EQ(allocator_byte_string, small_byte_string()); allocator_byte_string = medium_byte_string(); EXPECT_EQ(allocator_byte_string, medium_byte_string()); allocator_byte_string = medium_byte_string(); EXPECT_EQ(allocator_byte_string, medium_byte_string()); allocator_byte_string = large_byte_string(); EXPECT_EQ(allocator_byte_string, large_byte_string()); allocator_byte_string = large_byte_string(); EXPECT_EQ(allocator_byte_string, large_byte_string()); allocator_byte_string = small_byte_string(); EXPECT_EQ(allocator_byte_string, small_byte_string()); allocator_byte_string = large_byte_string(); EXPECT_EQ(allocator_byte_string, large_byte_string()); allocator_byte_string = medium_byte_string(); EXPECT_EQ(allocator_byte_string, medium_byte_string()); allocator_byte_string = small_byte_string(); EXPECT_EQ(allocator_byte_string, small_byte_string()); ByteString large_new_delete_byte_string(NewDeleteAllocator(), GetMediumOrLargeCord()); ByteString medium_arena_byte_string(ArenaAllocator(&arena), GetMediumStringView()); large_new_delete_byte_string = std::move(medium_arena_byte_string); EXPECT_EQ(large_new_delete_byte_string, GetMediumStringView()); } TEST_P(ByteStringTest, Swap) { using std::swap; ByteString empty_byte_string(GetAllocator()); ByteString small_byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); ByteString medium_byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); ByteString large_byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); swap(empty_byte_string, small_byte_string); EXPECT_EQ(empty_byte_string, GetSmallStringView()); EXPECT_EQ(small_byte_string, ""); swap(empty_byte_string, small_byte_string); EXPECT_EQ(empty_byte_string, ""); EXPECT_EQ(small_byte_string, GetSmallStringView()); swap(small_byte_string, medium_byte_string); EXPECT_EQ(small_byte_string, GetMediumStringView()); EXPECT_EQ(medium_byte_string, GetSmallStringView()); swap(small_byte_string, medium_byte_string); EXPECT_EQ(small_byte_string, GetSmallStringView()); EXPECT_EQ(medium_byte_string, GetMediumStringView()); swap(small_byte_string, large_byte_string); EXPECT_EQ(small_byte_string, GetMediumOrLargeCord()); EXPECT_EQ(large_byte_string, GetSmallStringView()); swap(small_byte_string, large_byte_string); EXPECT_EQ(small_byte_string, GetSmallStringView()); EXPECT_EQ(large_byte_string, GetMediumOrLargeCord()); static constexpr absl::string_view kDifferentMediumStringView = "A different string that is too large for the small string optimization!"; ByteString other_medium_byte_string = ByteString::Owned(GetAllocator(), kDifferentMediumStringView); swap(medium_byte_string, other_medium_byte_string); EXPECT_EQ(medium_byte_string, kDifferentMediumStringView); EXPECT_EQ(other_medium_byte_string, GetMediumStringView()); swap(medium_byte_string, other_medium_byte_string); EXPECT_EQ(medium_byte_string, GetMediumStringView()); EXPECT_EQ(other_medium_byte_string, kDifferentMediumStringView); swap(medium_byte_string, large_byte_string); EXPECT_EQ(medium_byte_string, GetMediumOrLargeCord()); EXPECT_EQ(large_byte_string, GetMediumStringView()); swap(medium_byte_string, large_byte_string); EXPECT_EQ(medium_byte_string, GetMediumStringView()); EXPECT_EQ(large_byte_string, GetMediumOrLargeCord()); const absl::Cord different_medium_or_large_cord = absl::Cord(kDifferentMediumStringView); ByteString other_large_byte_string = ByteString::Owned(GetAllocator(), different_medium_or_large_cord); swap(large_byte_string, other_large_byte_string); EXPECT_EQ(large_byte_string, different_medium_or_large_cord); EXPECT_EQ(other_large_byte_string, GetMediumStringView()); swap(large_byte_string, other_large_byte_string); EXPECT_EQ(large_byte_string, GetMediumStringView()); EXPECT_EQ(other_large_byte_string, different_medium_or_large_cord); ByteString medium_new_delete_byte_string = ByteString::Owned(NewDeleteAllocator(), kDifferentMediumStringView); swap(empty_byte_string, medium_new_delete_byte_string); EXPECT_EQ(empty_byte_string, kDifferentMediumStringView); EXPECT_EQ(medium_new_delete_byte_string, ""); ByteString large_new_delete_byte_string = ByteString::Owned(NewDeleteAllocator(), GetMediumOrLargeCord()); swap(small_byte_string, large_new_delete_byte_string); EXPECT_EQ(small_byte_string, GetMediumOrLargeCord()); EXPECT_EQ(large_new_delete_byte_string, GetSmallStringView()); large_new_delete_byte_string = ByteString::Owned(NewDeleteAllocator(), different_medium_or_large_cord); swap(medium_byte_string, large_new_delete_byte_string); EXPECT_EQ(medium_byte_string, different_medium_or_large_cord); EXPECT_EQ(large_new_delete_byte_string, GetMediumStringView()); medium_byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); medium_new_delete_byte_string = ByteString::Owned(NewDeleteAllocator(), kDifferentMediumStringView); swap(medium_byte_string, medium_new_delete_byte_string); EXPECT_EQ(medium_byte_string, kDifferentMediumStringView); EXPECT_EQ(medium_new_delete_byte_string, GetMediumStringView()); } TEST_P(ByteStringTest, FlattenSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.Flatten(), GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); } TEST_P(ByteStringTest, FlattenMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.Flatten(), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); } TEST_P(ByteStringTest, FlattenLarge) { if (GetAllocator().arena() != nullptr) { GTEST_SKIP(); } ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kLarge); EXPECT_EQ(byte_string.Flatten(), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kLarge); } TEST_P(ByteStringTest, TryFlatSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_THAT(byte_string.TryFlat(), Optional(GetSmallStringView())); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); } TEST_P(ByteStringTest, TryFlatMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); EXPECT_THAT(byte_string.TryFlat(), Optional(GetMediumStringView())); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); } TEST_P(ByteStringTest, TryFlatLarge) { if (GetAllocator().arena() != nullptr) { GTEST_SKIP(); } ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeFragmentedCord()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kLarge); EXPECT_THAT(byte_string.TryFlat(), Eq(absl::nullopt)); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kLarge); } TEST_P(ByteStringTest, GetFlatSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); std::string scratch; EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string.GetFlat(scratch), GetSmallStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); } TEST_P(ByteStringTest, GetFlatMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); std::string scratch; EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); EXPECT_EQ(byte_string.GetFlat(scratch), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); } TEST_P(ByteStringTest, GetFlatLarge) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); std::string scratch; EXPECT_EQ(byte_string.GetFlat(scratch), GetMediumStringView()); } TEST_P(ByteStringTest, GetFlatLargeFragmented) { ByteString byte_string = Byte
20
cpp
google/cel-cpp
reference_count
common/internal/reference_count.cc
common/internal/reference_count_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_REFERENCE_COUNT_H_ #define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_REFERENCE_COUNT_H_ #include <atomic> #include <cstdint> #include <new> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "common/arena.h" #include "common/data.h" #include "google/protobuf/arena.h" #include "google/protobuf/message_lite.h" namespace cel::common_internal { struct AdoptRef final { explicit AdoptRef() = default; }; inline constexpr AdoptRef kAdoptRef{}; class ReferenceCount; struct ReferenceCountFromThis; void SetReferenceCountForThat(ReferenceCountFromThis& that, absl::Nullable<ReferenceCount*> refcount); ABSL_ATTRIBUTE_PURE_FUNCTION absl::Nullable<ReferenceCount*> GetReferenceCountForThat( const ReferenceCountFromThis& that); struct ReferenceCountFromThis { private: friend void SetReferenceCountForThat( ReferenceCountFromThis& that, absl::Nullable<ReferenceCount*> refcount); friend absl::Nullable<ReferenceCount*> GetReferenceCountForThat( const ReferenceCountFromThis& that); static constexpr uintptr_t kNullPtr = uintptr_t{0}; static constexpr uintptr_t kSentinelPtr = ~kNullPtr; absl::Nullable<void*> refcount = reinterpret_cast<void*>(kSentinelPtr); }; inline void SetReferenceCountForThat(ReferenceCountFromThis& that, absl::Nullable<ReferenceCount*> refcount) { ABSL_DCHECK_EQ(that.refcount, reinterpret_cast<void*>(ReferenceCountFromThis::kSentinelPtr)); that.refcount = static_cast<void*>(refcount); } inline absl::Nullable<ReferenceCount*> GetReferenceCountForThat( const ReferenceCountFromThis& that) { ABSL_DCHECK_NE(that.refcount, reinterpret_cast<void*>(ReferenceCountFromThis::kSentinelPtr)); return static_cast<ReferenceCount*>(that.refcount); } void StrongRef(const ReferenceCount& refcount) noexcept; void StrongRef(absl::Nullable<const ReferenceCount*> refcount) noexcept; void StrongUnref(const ReferenceCount& refcount) noexcept; void StrongUnref(absl::Nullable<const ReferenceCount*> refcount) noexcept; ABSL_MUST_USE_RESULT bool StrengthenRef(const ReferenceCount& refcount) noexcept; ABSL_MUST_USE_RESULT bool StrengthenRef(absl::Nullable<const ReferenceCount*> refcount) noexcept; void WeakRef(const ReferenceCount& refcount) noexcept; void WeakRef(absl::Nullable<const ReferenceCount*> refcount) noexcept; void WeakUnref(const ReferenceCount& refcount) noexcept; void WeakUnref(absl::Nullable<const ReferenceCount*> refcount) noexcept; ABSL_MUST_USE_RESULT bool IsUniqueRef(const ReferenceCount& refcount) noexcept; ABSL_MUST_USE_RESULT bool IsUniqueRef(absl::Nullable<const ReferenceCount*> refcount) noexcept; ABSL_MUST_USE_RESULT bool IsExpiredRef(const ReferenceCount& refcount) noexcept; ABSL_MUST_USE_RESULT bool IsExpiredRef(absl::Nullable<const ReferenceCount*> refcount) noexcept; class alignas(8) ReferenceCount { public: ReferenceCount() = default; ReferenceCount(const ReferenceCount&) = delete; ReferenceCount(ReferenceCount&&) = delete; ReferenceCount& operator=(const ReferenceCount&) = delete; ReferenceCount& operator=(ReferenceCount&&) = delete; virtual ~ReferenceCount() = default; private: friend void StrongRef(const ReferenceCount& refcount) noexcept; friend void StrongUnref(const ReferenceCount& refcount) noexcept; friend bool StrengthenRef(const ReferenceCount& refcount) noexcept; friend void WeakRef(const ReferenceCount& refcount) noexcept; friend void WeakUnref(const ReferenceCount& refcount) noexcept; friend bool IsUniqueRef(const ReferenceCount& refcount) noexcept; friend bool IsExpiredRef(const ReferenceCount& refcount) noexcept; virtual void Finalize() noexcept = 0; virtual void Delete() noexcept = 0; mutable std::atomic<int32_t> strong_refcount_ = 1; mutable std::atomic<int32_t> weak_refcount_ = 1; }; static_assert(alignof(ReferenceCount) >= alignof(google::protobuf::Arena)); class ReferenceCounted : public ReferenceCount { private: void Finalize() noexcept override {} void Delete() noexcept override { delete this; } }; template <typename T> class EmplacedReferenceCount final : public ReferenceCounted { public: static_assert(std::is_destructible_v<T>, "T must be destructible"); static_assert(!std::is_reference_v<T>, "T must not be a reference"); static_assert(!std::is_volatile_v<T>, "T must not be volatile qualified"); static_assert(!std::is_const_v<T>, "T must not be const qualified"); template <typename... Args> explicit EmplacedReferenceCount(T*& value, Args&&... args) noexcept( std::is_nothrow_constructible_v<T, Args...>) { value = ::new (static_cast<void*>(&value_[0])) T(std::forward<Args>(args)...); } private: void Finalize() noexcept override { std::launder(reinterpret_cast<T*>(&value_[0]))->~T(); } alignas(T) char value_[sizeof(T)]; }; template <typename T> class DeletingReferenceCount final : public ReferenceCounted { public: explicit DeletingReferenceCount(absl::Nonnull<const T*> to_delete) noexcept : to_delete_(to_delete) {} private: void Finalize() noexcept override { delete std::exchange(to_delete_, nullptr); } const T* to_delete_; }; extern template class DeletingReferenceCount<google::protobuf::MessageLite>; extern template class DeletingReferenceCount<Data>; template <typename T> absl::Nonnull<const ReferenceCount*> MakeDeletingReferenceCount( absl::Nonnull<const T*> to_delete) { if constexpr (IsArenaConstructible<T>::value) { ABSL_DCHECK_EQ(to_delete->GetArena(), nullptr); } if constexpr (std::is_base_of_v<google::protobuf::MessageLite, T>) { return new DeletingReferenceCount<google::protobuf::MessageLite>(to_delete); } else if constexpr (std::is_base_of_v<Data, T>) { auto* refcount = new DeletingReferenceCount<Data>(to_delete); common_internal::SetDataReferenceCount(to_delete, refcount); return refcount; } else { return new DeletingReferenceCount<T>(to_delete); } } template <typename T, typename... Args> std::pair<absl::Nonnull<T*>, absl::Nonnull<const ReferenceCount*>> MakeEmplacedReferenceCount(Args&&... args) { using U = std::remove_const_t<T>; U* pointer; auto* const refcount = new EmplacedReferenceCount<U>(pointer, std::forward<Args>(args)...); if constexpr (IsArenaConstructible<U>::value) { ABSL_DCHECK_EQ(pointer->GetArena(), nullptr); } if constexpr (std::is_base_of_v<Data, T>) { common_internal::SetDataReferenceCount(pointer, refcount); } return std::pair{static_cast<absl::Nonnull<T*>>(pointer), static_cast<absl::Nonnull<const ReferenceCount*>>(refcount)}; } template <typename T> class InlinedReferenceCount final : public ReferenceCounted { public: template <typename... Args> explicit InlinedReferenceCount(std::in_place_t, Args&&... args) : ReferenceCounted() { ::new (static_cast<void*>(value())) T(std::forward<Args>(args)...); } ABSL_ATTRIBUTE_ALWAYS_INLINE absl::Nonnull<T*> value() { return reinterpret_cast<T*>(&value_[0]); } ABSL_ATTRIBUTE_ALWAYS_INLINE absl::Nonnull<const T*> value() const { return reinterpret_cast<const T*>(&value_[0]); } private: void Finalize() noexcept override { value()->~T(); } alignas(T) char value_[sizeof(T)]; }; template <typename T, typename... Args> std::pair<absl::Nonnull<T*>, absl::Nonnull<ReferenceCount*>> MakeReferenceCount( Args&&... args) { using U = std::remove_const_t<T>; auto* const refcount = new InlinedReferenceCount<U>(std::in_place, std::forward<Args>(args)...); auto* const pointer = refcount->value(); if constexpr (std::is_base_of_v<ReferenceCountFromThis, U>) { SetReferenceCountForThat(*pointer, refcount); } return std::make_pair(static_cast<T*>(pointer), static_cast<ReferenceCount*>(refcount)); } inline void StrongRef(const ReferenceCount& refcount) noexcept { const auto count = refcount.strong_refcount_.fetch_add(1, std::memory_order_relaxed); ABSL_DCHECK_GT(count, 0); } inline void StrongRef(absl::Nullable<const ReferenceCount*> refcount) noexcept { if (refcount != nullptr) { StrongRef(*refcount); } } inline void StrongUnref(const ReferenceCount& refcount) noexcept { const auto count = refcount.strong_refcount_.fetch_sub(1, std::memory_order_acq_rel); ABSL_DCHECK_GT(count, 0); ABSL_ASSUME(count > 0); if (ABSL_PREDICT_FALSE(count == 1)) { const_cast<ReferenceCount&>(refcount).Finalize(); WeakUnref(refcount); } } inline void StrongUnref( absl::Nullable<const ReferenceCount*> refcount) noexcept { if (refcount != nullptr) { StrongUnref(*refcount); } } ABSL_MUST_USE_RESULT inline bool StrengthenRef(const ReferenceCount& refcount) noexcept { auto count = refcount.strong_refcount_.load(std::memory_order_relaxed); while (true) { ABSL_DCHECK_GE(count, 0); ABSL_ASSUME(count >= 0); if (count == 0) { return false; } if (refcount.strong_refcount_.compare_exchange_weak( count, count + 1, std::memory_order_release, std::memory_order_relaxed)) { return true; } } } ABSL_MUST_USE_RESULT inline bool StrengthenRef( absl::Nullable<const ReferenceCount*> refcount) noexcept { return refcount != nullptr ? StrengthenRef(*refcount) : false; } inline void WeakRef(const ReferenceCount& refcount) noexcept { const auto count = refcount.weak_refcount_.fetch_add(1, std::memory_order_relaxed); ABSL_DCHECK_GT(count, 0); } inline void WeakRef(absl::Nullable<const ReferenceCount*> refcount) noexcept { if (refcount != nullptr) { WeakRef(*refcount); } } inline void WeakUnref(const ReferenceCount& refcount) noexcept { const auto count = refcount.weak_refcount_.fetch_sub(1, std::memory_order_acq_rel); ABSL_DCHECK_GT(count, 0); ABSL_ASSUME(count > 0); if (ABSL_PREDICT_FALSE(count == 1)) { const_cast<ReferenceCount&>(refcount).Delete(); } } inline void WeakUnref(absl::Nullable<const ReferenceCount*> refcount) noexcept { if (refcount != nullptr) { WeakUnref(*refcount); } } ABSL_MUST_USE_RESULT inline bool IsUniqueRef(const ReferenceCount& refcount) noexcept { const auto count = refcount.strong_refcount_.load(std::memory_order_acquire); ABSL_DCHECK_GT(count, 0); ABSL_ASSUME(count > 0); return count == 1; } ABSL_MUST_USE_RESULT inline bool IsUniqueRef( absl::Nullable<const ReferenceCount*> refcount) noexcept { return refcount != nullptr ? IsUniqueRef(*refcount) : false; } ABSL_MUST_USE_RESULT inline bool IsExpiredRef(const ReferenceCount& refcount) noexcept { const auto count = refcount.strong_refcount_.load(std::memory_order_acquire); ABSL_DCHECK_GE(count, 0); ABSL_ASSUME(count >= 0); return count == 0; } ABSL_MUST_USE_RESULT inline bool IsExpiredRef( absl::Nullable<const ReferenceCount*> refcount) noexcept { return refcount != nullptr ? IsExpiredRef(*refcount) : false; } } #endif #include "common/internal/reference_count.h" #include "common/data.h" #include "google/protobuf/message_lite.h" namespace cel::common_internal { template class DeletingReferenceCount<google::protobuf::MessageLite>; template class DeletingReferenceCount<Data>; }
#include "common/internal/reference_count.h" #include <tuple> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "common/data.h" #include "internal/testing.h" #include "google/protobuf/arena.h" #include "google/protobuf/message_lite.h" namespace cel::common_internal { namespace { using testing::NotNull; using testing::WhenDynamicCastTo; class Object : public virtual ReferenceCountFromThis { public: explicit Object(bool& destructed) : destructed_(destructed) {} ~Object() { destructed_ = true; } private: bool& destructed_; }; class Subobject : public Object, public virtual ReferenceCountFromThis { public: using Object::Object; }; TEST(ReferenceCount, Strong) { bool destructed = false; Object* object; ReferenceCount* refcount; std::tie(object, refcount) = MakeReferenceCount<Subobject>(destructed); EXPECT_EQ(GetReferenceCountForThat(*object), refcount); EXPECT_EQ(GetReferenceCountForThat(*static_cast<Subobject*>(object)), refcount); StrongRef(refcount); StrongUnref(refcount); EXPECT_TRUE(IsUniqueRef(refcount)); EXPECT_FALSE(IsExpiredRef(refcount)); EXPECT_FALSE(destructed); StrongUnref(refcount); EXPECT_TRUE(destructed); } TEST(ReferenceCount, Weak) { bool destructed = false; Object* object; ReferenceCount* refcount; std::tie(object, refcount) = MakeReferenceCount<Subobject>(destructed); EXPECT_EQ(GetReferenceCountForThat(*object), refcount); EXPECT_EQ(GetReferenceCountForThat(*static_cast<Subobject*>(object)), refcount); WeakRef(refcount); ASSERT_TRUE(StrengthenRef(refcount)); StrongUnref(refcount); EXPECT_TRUE(IsUniqueRef(refcount)); EXPECT_FALSE(IsExpiredRef(refcount)); EXPECT_FALSE(destructed); StrongUnref(refcount); EXPECT_TRUE(destructed); EXPECT_TRUE(IsExpiredRef(refcount)); ASSERT_FALSE(StrengthenRef(refcount)); WeakUnref(refcount); } class DataObject final : public Data { public: DataObject() noexcept : Data() {} explicit DataObject(absl::Nullable<google::protobuf::Arena*> arena) noexcept : Data(arena) {} char member_[17]; }; struct OtherObject final { char data[17]; }; TEST(DeletingReferenceCount, Data) { auto* data = new DataObject(); const auto* refcount = MakeDeletingReferenceCount(data); EXPECT_THAT(refcount, WhenDynamicCastTo<const DeletingReferenceCount<Data>*>( NotNull())); EXPECT_EQ(common_internal::GetDataReferenceCount(data), refcount); StrongUnref(refcount); } TEST(DeletingReferenceCount, MessageLite) { auto* message_lite = new google::protobuf::Value(); const auto* refcount = MakeDeletingReferenceCount(message_lite); EXPECT_THAT( refcount, WhenDynamicCastTo<const DeletingReferenceCount<google::protobuf::MessageLite>*>( NotNull())); StrongUnref(refcount); } TEST(DeletingReferenceCount, Other) { auto* other = new OtherObject(); const auto* refcount = MakeDeletingReferenceCount(other); EXPECT_THAT( refcount, WhenDynamicCastTo<const DeletingReferenceCount<OtherObject>*>(NotNull())); StrongUnref(refcount); } TEST(EmplacedReferenceCount, Data) { Data* data; const ReferenceCount* refcount; std::tie(data, refcount) = MakeEmplacedReferenceCount<DataObject>(); EXPECT_THAT( refcount, WhenDynamicCastTo<const EmplacedReferenceCount<DataObject>*>(NotNull())); EXPECT_EQ(common_internal::GetDataReferenceCount(data), refcount); StrongUnref(refcount); } TEST(EmplacedReferenceCount, MessageLite) { google::protobuf::Value* message_lite; const ReferenceCount* refcount; std::tie(message_lite, refcount) = MakeEmplacedReferenceCount<google::protobuf::Value>(); EXPECT_THAT( refcount, WhenDynamicCastTo<const EmplacedReferenceCount<google::protobuf::Value>*>( NotNull())); StrongUnref(refcount); } TEST(EmplacedReferenceCount, Other) { OtherObject* other; const ReferenceCount* refcount; std::tie(other, refcount) = MakeEmplacedReferenceCount<OtherObject>(); EXPECT_THAT( refcount, WhenDynamicCastTo<const EmplacedReferenceCount<OtherObject>*>(NotNull())); StrongUnref(refcount); } } }
21
cpp
google/cel-cpp
function_type
common/types/function_type.cc
common/types/function_type_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_FUNCTION_TYPE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_TYPES_FUNCTION_TYPE_H_ #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/memory.h" #include "common/native_type.h" #include "common/sized_input_view.h" #include "common/type_kind.h" namespace cel { class Type; class TypeView; class FunctionType; class FunctionTypeView; namespace common_internal { struct FunctionTypeData; } class FunctionType final { public: using view_alternative_type = FunctionTypeView; static constexpr TypeKind kKind = TypeKind::kFunction; explicit FunctionType(FunctionTypeView other); FunctionType(MemoryManagerRef memory_manager, TypeView result, const SizedInputView<TypeView>& args); FunctionType() = delete; FunctionType(const FunctionType&) = default; FunctionType(FunctionType&&) = default; FunctionType& operator=(const FunctionType&) = default; FunctionType& operator=(FunctionType&&) = default; constexpr TypeKind kind() const { return kKind; } absl::string_view name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return "function"; } absl::Span<const Type> parameters() const ABSL_ATTRIBUTE_LIFETIME_BOUND; std::string DebugString() const; const Type& result() const ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::Span<const Type> args() const ABSL_ATTRIBUTE_LIFETIME_BOUND; void swap(FunctionType& other) noexcept { using std::swap; swap(data_, other.data_); } private: friend class FunctionTypeView; friend struct NativeTypeTraits<FunctionType>; Shared<const common_internal::FunctionTypeData> data_; }; inline void swap(FunctionType& lhs, FunctionType& rhs) noexcept { lhs.swap(rhs); } bool operator==(const FunctionType& lhs, const FunctionType& rhs); inline bool operator!=(const FunctionType& lhs, const FunctionType& rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, const FunctionType& type); inline std::ostream& operator<<(std::ostream& out, const FunctionType& type) { return out << type.DebugString(); } template <> struct NativeTypeTraits<FunctionType> final { static bool SkipDestructor(const FunctionType& type) { return NativeType::SkipDestructor(type.data_); } }; class FunctionTypeView final { public: using alternative_type = FunctionType; static constexpr TypeKind kKind = FunctionType::kKind; FunctionTypeView( const FunctionType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept; FunctionTypeView& operator=( const FunctionType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) { data_ = type.data_; return *this; } FunctionTypeView& operator=(FunctionType&&) = delete; FunctionTypeView() = delete; FunctionTypeView(const FunctionTypeView&) = default; FunctionTypeView(FunctionTypeView&&) = default; FunctionTypeView& operator=(const FunctionTypeView&) = default; FunctionTypeView& operator=(FunctionTypeView&&) = default; constexpr TypeKind kind() const { return kKind; } absl::string_view name() const { return "function"; } std::string DebugString() const; absl::Span<const Type> parameters() const; const Type& result() const; absl::Span<const Type> args() const; void swap(FunctionTypeView& other) noexcept { using std::swap; swap(data_, other.data_); } private: friend class FunctionType; SharedView<const common_internal::FunctionTypeData> data_; }; inline void swap(FunctionTypeView& lhs, FunctionTypeView& rhs) noexcept { lhs.swap(rhs); } bool operator==(FunctionTypeView lhs, FunctionTypeView rhs); inline bool operator!=(FunctionTypeView lhs, FunctionTypeView rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, FunctionTypeView type); inline std::ostream& operator<<(std::ostream& out, FunctionTypeView type) { return out << type.DebugString(); } } #endif #include <cstddef> #include <string> #include "absl/container/fixed_array.h" #include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/memory.h" #include "common/sized_input_view.h" #include "common/type.h" namespace cel { namespace { struct TypeFormatter { void operator()(std::string* out, const Type& type) const { out->append(type.DebugString()); } }; std::string FunctionDebugString(const Type& result, absl::Span<const Type> args) { return absl::StrCat("(", absl::StrJoin(args, ", ", TypeFormatter{}), ") -> ", result.DebugString()); } absl::FixedArray<Type, 3> SizedInputViewToFixedArray( TypeView result, const SizedInputView<TypeView>& args) { absl::FixedArray<Type, 3> fixed_args(1 + args.size()); size_t index = 0; fixed_args[index++] = Type(result); for (const auto& arg : args) { fixed_args[index++] = Type(arg); } ABSL_DCHECK_EQ(index, 1 + args.size()); return fixed_args; } } FunctionType::FunctionType(MemoryManagerRef memory_manager, TypeView result, const SizedInputView<TypeView>& args) : data_(memory_manager.MakeShared<common_internal::FunctionTypeData>( SizedInputViewToFixedArray(result, args))) {} std::string FunctionType::DebugString() const { return FunctionDebugString(result(), args()); } std::string FunctionTypeView::DebugString() const { return FunctionDebugString(result(), args()); } }
#include <sstream> #include <string> #include "absl/hash/hash.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/memory_testing.h" #include "common/native_type.h" #include "common/type.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using testing::TestParamInfo; using testing::TestWithParam; class FunctionTypeTest : public common_internal::ThreadCompatibleMemoryTest<> { }; TEST_P(FunctionTypeTest, Kind) { EXPECT_EQ(FunctionType(memory_manager(), DynType{}, {BytesType()}).kind(), FunctionType::kKind); EXPECT_EQ( Type(FunctionType(memory_manager(), DynType{}, {BytesType()})).kind(), FunctionType::kKind); } TEST_P(FunctionTypeTest, Name) { EXPECT_EQ(FunctionType(memory_manager(), DynType{}, {BytesType()}).name(), "function"); EXPECT_EQ( Type(FunctionType(memory_manager(), DynType{}, {BytesType()})).name(), "function"); } TEST_P(FunctionTypeTest, DebugString) { { std::ostringstream out; out << FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_EQ(out.str(), "(bytes) -> dyn"); } { std::ostringstream out; out << Type(FunctionType(memory_manager(), DynType{}, {BytesType()})); EXPECT_EQ(out.str(), "(bytes) -> dyn"); } } TEST_P(FunctionTypeTest, Hash) { EXPECT_EQ( absl::HashOf(FunctionType(memory_manager(), DynType{}, {BytesType()})), absl::HashOf(FunctionType(memory_manager(), DynType{}, {BytesType()}))); } TEST_P(FunctionTypeTest, Equal) { EXPECT_EQ(FunctionType(memory_manager(), DynType{}, {BytesType()}), FunctionType(memory_manager(), DynType{}, {BytesType()})); EXPECT_EQ(Type(FunctionType(memory_manager(), DynType{}, {BytesType()})), FunctionType(memory_manager(), DynType{}, {BytesType()})); EXPECT_EQ(FunctionType(memory_manager(), DynType{}, {BytesType()}), Type(FunctionType(memory_manager(), DynType{}, {BytesType()}))); EXPECT_EQ(Type(FunctionType(memory_manager(), DynType{}, {BytesType()})), Type(FunctionType(memory_manager(), DynType{}, {BytesType()}))); } TEST_P(FunctionTypeTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of( FunctionType(memory_manager(), DynType{}, {BytesType()})), NativeTypeId::For<FunctionType>()); EXPECT_EQ(NativeTypeId::Of( Type(FunctionType(memory_manager(), DynType{}, {BytesType()}))), NativeTypeId::For<FunctionType>()); } TEST_P(FunctionTypeTest, InstanceOf) { EXPECT_TRUE(InstanceOf<FunctionType>( FunctionType(memory_manager(), DynType{}, {BytesType()}))); EXPECT_TRUE(InstanceOf<FunctionType>( Type(FunctionType(memory_manager(), DynType{}, {BytesType()})))); } TEST_P(FunctionTypeTest, Cast) { EXPECT_THAT(Cast<FunctionType>( FunctionType(memory_manager(), DynType{}, {BytesType()})), An<FunctionType>()); EXPECT_THAT(Cast<FunctionType>(Type( FunctionType(memory_manager(), DynType{}, {BytesType()}))), An<FunctionType>()); } TEST_P(FunctionTypeTest, As) { EXPECT_THAT(As<FunctionType>( FunctionType(memory_manager(), DynType{}, {BytesType()})), Ne(absl::nullopt)); EXPECT_THAT(As<FunctionType>(Type( FunctionType(memory_manager(), DynType{}, {BytesType()}))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( FunctionTypeTest, FunctionTypeTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), FunctionTypeTest::ToString); class FunctionTypeViewTest : public common_internal::ThreadCompatibleMemoryTest<> {}; TEST_P(FunctionTypeViewTest, Kind) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_EQ(FunctionTypeView(type).kind(), FunctionTypeView::kKind); EXPECT_EQ(TypeView(FunctionTypeView(type)).kind(), FunctionTypeView::kKind); } TEST_P(FunctionTypeViewTest, Name) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_EQ(FunctionTypeView(type).name(), "function"); EXPECT_EQ(TypeView(FunctionTypeView(type)).name(), "function"); } TEST_P(FunctionTypeViewTest, DebugString) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); { std::ostringstream out; out << FunctionTypeView(type); EXPECT_EQ(out.str(), "(bytes) -> dyn"); } { std::ostringstream out; out << TypeView(FunctionTypeView(type)); EXPECT_EQ(out.str(), "(bytes) -> dyn"); } } TEST_P(FunctionTypeViewTest, Hash) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_EQ(absl::HashOf(FunctionTypeView(type)), absl::HashOf(FunctionTypeView(type))); EXPECT_EQ(absl::HashOf(FunctionTypeView(type)), absl::HashOf(FunctionType(type))); } TEST_P(FunctionTypeViewTest, Equal) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_EQ(FunctionTypeView(type), FunctionTypeView(type)); EXPECT_EQ(TypeView(FunctionTypeView(type)), FunctionTypeView(type)); EXPECT_EQ(FunctionTypeView(type), TypeView(FunctionTypeView(type))); EXPECT_EQ(TypeView(FunctionTypeView(type)), TypeView(FunctionTypeView(type))); EXPECT_EQ(FunctionTypeView(type), FunctionType(type)); EXPECT_EQ(TypeView(FunctionTypeView(type)), FunctionType(type)); EXPECT_EQ(TypeView(FunctionTypeView(type)), Type(FunctionType(type))); EXPECT_EQ(FunctionType(type), FunctionTypeView(type)); EXPECT_EQ(FunctionType(type), FunctionTypeView(type)); EXPECT_EQ(FunctionType(type), TypeView(FunctionTypeView(type))); EXPECT_EQ(Type(FunctionType(type)), TypeView(FunctionTypeView(type))); EXPECT_EQ(FunctionTypeView(type), FunctionType(type)); } TEST_P(FunctionTypeViewTest, NativeTypeId) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_EQ(NativeTypeId::Of(FunctionTypeView(type)), NativeTypeId::For<FunctionTypeView>()); EXPECT_EQ(NativeTypeId::Of(TypeView(FunctionTypeView(type))), NativeTypeId::For<FunctionTypeView>()); } TEST_P(FunctionTypeViewTest, InstanceOf) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_TRUE(InstanceOf<FunctionTypeView>(FunctionTypeView(type))); EXPECT_TRUE(InstanceOf<FunctionTypeView>(TypeView(FunctionTypeView(type)))); } TEST_P(FunctionTypeViewTest, Cast) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_THAT(Cast<FunctionTypeView>(FunctionTypeView(type)), An<FunctionTypeView>()); EXPECT_THAT(Cast<FunctionTypeView>(TypeView(FunctionTypeView(type))), An<FunctionTypeView>()); } TEST_P(FunctionTypeViewTest, As) { auto type = FunctionType(memory_manager(), DynType{}, {BytesType()}); EXPECT_THAT(As<FunctionTypeView>(FunctionTypeView(type)), Ne(absl::nullopt)); EXPECT_THAT(As<FunctionTypeView>(TypeView(FunctionTypeView(type))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( FunctionTypeViewTest, FunctionTypeViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), FunctionTypeViewTest::ToString); } }
22
cpp
google/cel-cpp
opaque_type
common/types/opaque_type.cc
common/types/opaque_type_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_OPAQUE_TYPE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_TYPES_OPAQUE_TYPE_H_ #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/casting.h" #include "common/memory.h" #include "common/native_type.h" #include "common/sized_input_view.h" #include "common/type_kind.h" namespace cel { class Type; class TypeView; class OpaqueType; class OpaqueTypeView; namespace common_internal { struct OpaqueTypeData; } class OpaqueType { public: using view_alternative_type = OpaqueTypeView; static constexpr TypeKind kKind = TypeKind::kOpaque; explicit OpaqueType(OpaqueTypeView other); OpaqueType(MemoryManagerRef memory_manager, absl::string_view name, const SizedInputView<TypeView>& parameters); OpaqueType() = delete; OpaqueType(const OpaqueType&) = default; OpaqueType(OpaqueType&&) = default; OpaqueType& operator=(const OpaqueType&) = default; OpaqueType& operator=(OpaqueType&&) = default; constexpr TypeKind kind() const { return kKind; } absl::string_view name() const ABSL_ATTRIBUTE_LIFETIME_BOUND; std::string DebugString() const; void swap(OpaqueType& other) noexcept { using std::swap; swap(data_, other.data_); } absl::Span<const Type> parameters() const ABSL_ATTRIBUTE_LIFETIME_BOUND; private: friend class OpaqueTypeView; friend struct NativeTypeTraits<OpaqueType>; Shared<const common_internal::OpaqueTypeData> data_; }; inline void swap(OpaqueType& lhs, OpaqueType& rhs) noexcept { lhs.swap(rhs); } bool operator==(const OpaqueType& lhs, const OpaqueType& rhs); inline bool operator!=(const OpaqueType& lhs, const OpaqueType& rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, const OpaqueType& type); inline std::ostream& operator<<(std::ostream& out, const OpaqueType& type) { return out << type.DebugString(); } template <> struct NativeTypeTraits<OpaqueType> final { static NativeTypeId Id(const OpaqueType&) { return NativeTypeId::For<OpaqueType>(); } static bool SkipDestructor(const OpaqueType& type) { return NativeType::SkipDestructor(type.data_); } }; template <typename T> struct NativeTypeTraits<T, std::enable_if_t<std::conjunction_v< std::negation<std::is_same<OpaqueType, T>>, std::is_base_of<OpaqueType, T>>>> final { static NativeTypeId Id(const T& type) { return NativeTypeTraits<OpaqueType>::Id(type); } static bool SkipDestructor(const T& type) { return NativeTypeTraits<OpaqueType>::SkipDestructor(type); } }; template <typename To, typename From> struct CastTraits< To, From, std::enable_if_t<std::conjunction_v< std::bool_constant<sizeof(To) == sizeof(absl::remove_cvref_t<From>)>, std::bool_constant<alignof(To) == alignof(absl::remove_cvref_t<From>)>, std::is_same<OpaqueType, absl::remove_cvref_t<From>>, std::negation<std::is_same<OpaqueType, To>>, std::is_base_of<OpaqueType, To>>>> final { static bool Compatible(const absl::remove_cvref_t<From>& from) { return SubsumptionTraits<To>::IsA(from); } static decltype(auto) Convert(From from) { return SubsumptionTraits<To>::DownCast(std::move(from)); } }; class OpaqueTypeView { public: using alternative_type = OpaqueType; static constexpr TypeKind kKind = OpaqueType::kKind; OpaqueTypeView(const OpaqueType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept; OpaqueTypeView& operator=( const OpaqueType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) { data_ = type.data_; return *this; } OpaqueTypeView& operator=(OpaqueType&&) = delete; OpaqueTypeView() = delete; OpaqueTypeView(const OpaqueTypeView&) = default; OpaqueTypeView(OpaqueTypeView&&) = default; OpaqueTypeView& operator=(const OpaqueTypeView&) = default; OpaqueTypeView& operator=(OpaqueTypeView&&) = default; constexpr TypeKind kind() const { return kKind; } absl::string_view name() const; std::string DebugString() const; void swap(OpaqueTypeView& other) noexcept { using std::swap; swap(data_, other.data_); } absl::Span<const Type> parameters() const; private: friend class OpaqueType; friend struct NativeTypeTraits<OpaqueTypeView>; SharedView<const common_internal::OpaqueTypeData> data_; }; inline void swap(OpaqueTypeView& lhs, OpaqueTypeView& rhs) noexcept { lhs.swap(rhs); } bool operator==(OpaqueTypeView lhs, OpaqueTypeView rhs); inline bool operator!=(OpaqueTypeView lhs, OpaqueTypeView rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, OpaqueTypeView type); inline std::ostream& operator<<(std::ostream& out, OpaqueTypeView type) { return out << type.DebugString(); } template <> struct NativeTypeTraits<OpaqueTypeView> final { static NativeTypeId Id(OpaqueTypeView type) { return NativeTypeId::For<OpaqueTypeView>(); } }; template <typename T> struct NativeTypeTraits<T, std::enable_if_t<std::conjunction_v< std::negation<std::is_same<OpaqueTypeView, T>>, std::is_base_of<OpaqueTypeView, T>>>> final { static NativeTypeId Id(const T& type) { return NativeTypeTraits<OpaqueTypeView>::Id(type); } }; template <typename To, typename From> struct CastTraits< To, From, std::enable_if_t<std::conjunction_v< std::bool_constant<sizeof(To) == sizeof(absl::remove_cvref_t<From>)>, std::bool_constant<alignof(To) == alignof(absl::remove_cvref_t<From>)>, std::is_same<OpaqueTypeView, absl::remove_cvref_t<From>>, std::negation<std::is_same<OpaqueTypeView, To>>, std::is_base_of<OpaqueTypeView, To>>>> final { static bool Compatible(const absl::remove_cvref_t<From>& from) { return SubsumptionTraits<To>::IsA(from); } static decltype(auto) Convert(From from) { return SubsumptionTraits<To>::DownCast(std::move(from)); } }; } #endif #include <cstddef> #include <string> #include <utility> #include "absl/container/fixed_array.h" #include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/memory.h" #include "common/native_type.h" #include "common/sized_input_view.h" #include "common/type.h" namespace cel { namespace { std::string OpaqueDebugString(absl::string_view name, absl::Span<const Type> parameters) { if (parameters.empty()) { return std::string(name); } return absl::StrCat( name, "<", absl::StrJoin(parameters, ", ", absl::StreamFormatter()), ">"); } absl::FixedArray<Type, 1> SizedInputViewToFixedArray( const SizedInputView<TypeView>& parameters) { absl::FixedArray<Type, 1> fixed_parameters(parameters.size()); size_t index = 0; for (const auto& parameter : parameters) { fixed_parameters[index++] = Type(parameter); } ABSL_DCHECK_EQ(index, parameters.size()); return fixed_parameters; } } OpaqueType::OpaqueType(MemoryManagerRef memory_manager, absl::string_view name, const SizedInputView<TypeView>& parameters) : data_(memory_manager.MakeShared<common_internal::OpaqueTypeData>( std::string(name), SizedInputViewToFixedArray(std::move(parameters)))) {} std::string OpaqueType::DebugString() const { return OpaqueDebugString(name(), parameters()); } std::string OpaqueTypeView::DebugString() const { return OpaqueDebugString(name(), parameters()); } }
#include <sstream> #include <string> #include "absl/hash/hash.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/memory_testing.h" #include "common/native_type.h" #include "common/type.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using testing::TestParamInfo; using testing::TestWithParam; class OpaqueTypeTest : public common_internal::ThreadCompatibleMemoryTest<> {}; TEST_P(OpaqueTypeTest, Kind) { EXPECT_EQ(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}).kind(), OpaqueType::kKind); EXPECT_EQ( Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})).kind(), OpaqueType::kKind); } TEST_P(OpaqueTypeTest, Name) { EXPECT_EQ(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}).name(), "test.Opaque"); EXPECT_EQ( Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})).name(), "test.Opaque"); } TEST_P(OpaqueTypeTest, DebugString) { { std::ostringstream out; out << OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_EQ(out.str(), "test.Opaque<bytes>"); } { std::ostringstream out; out << Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})); EXPECT_EQ(out.str(), "test.Opaque<bytes>"); } { std::ostringstream out; out << OpaqueType(memory_manager(), "test.Opaque", {}); EXPECT_EQ(out.str(), "test.Opaque"); } } TEST_P(OpaqueTypeTest, Hash) { EXPECT_EQ( absl::HashOf(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})), absl::HashOf(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))); } TEST_P(OpaqueTypeTest, Equal) { EXPECT_EQ(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}), OpaqueType(memory_manager(), "test.Opaque", {BytesType()})); EXPECT_EQ(Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})), OpaqueType(memory_manager(), "test.Opaque", {BytesType()})); EXPECT_EQ(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}), Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))); EXPECT_EQ(Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})), Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))); } TEST_P(OpaqueTypeTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of( OpaqueType(memory_manager(), "test.Opaque", {BytesType()})), NativeTypeId::For<OpaqueType>()); EXPECT_EQ(NativeTypeId::Of(Type( OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))), NativeTypeId::For<OpaqueType>()); } TEST_P(OpaqueTypeTest, InstanceOf) { EXPECT_TRUE(InstanceOf<OpaqueType>( OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))); EXPECT_TRUE(InstanceOf<OpaqueType>( Type(OpaqueType(memory_manager(), "test.Opaque", {BytesType()})))); } TEST_P(OpaqueTypeTest, Cast) { EXPECT_THAT(Cast<OpaqueType>( OpaqueType(memory_manager(), "test.Opaque", {BytesType()})), An<OpaqueType>()); EXPECT_THAT(Cast<OpaqueType>(Type( OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))), An<OpaqueType>()); } TEST_P(OpaqueTypeTest, As) { EXPECT_THAT(As<OpaqueType>( OpaqueType(memory_manager(), "test.Opaque", {BytesType()})), Ne(absl::nullopt)); EXPECT_THAT(As<OpaqueType>(Type( OpaqueType(memory_manager(), "test.Opaque", {BytesType()}))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( OpaqueTypeTest, OpaqueTypeTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), OpaqueTypeTest::ToString); class OpaqueTypeViewTest : public common_internal::ThreadCompatibleMemoryTest<> {}; TEST_P(OpaqueTypeViewTest, Kind) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_EQ(OpaqueTypeView(type).kind(), OpaqueTypeView::kKind); EXPECT_EQ(TypeView(OpaqueTypeView(type)).kind(), OpaqueTypeView::kKind); } TEST_P(OpaqueTypeViewTest, Name) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_EQ(OpaqueTypeView(type).name(), "test.Opaque"); EXPECT_EQ(TypeView(OpaqueTypeView(type)).name(), "test.Opaque"); } TEST_P(OpaqueTypeViewTest, DebugString) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); { std::ostringstream out; out << OpaqueTypeView(type); EXPECT_EQ(out.str(), "test.Opaque<bytes>"); } { std::ostringstream out; out << TypeView(OpaqueTypeView(type)); EXPECT_EQ(out.str(), "test.Opaque<bytes>"); } } TEST_P(OpaqueTypeViewTest, Hash) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_EQ(absl::HashOf(OpaqueTypeView(type)), absl::HashOf(OpaqueTypeView(type))); EXPECT_EQ(absl::HashOf(OpaqueTypeView(type)), absl::HashOf(OpaqueType(type))); } TEST_P(OpaqueTypeViewTest, Equal) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_EQ(OpaqueTypeView(type), OpaqueTypeView(type)); EXPECT_EQ(TypeView(OpaqueTypeView(type)), OpaqueTypeView(type)); EXPECT_EQ(OpaqueTypeView(type), TypeView(OpaqueTypeView(type))); EXPECT_EQ(TypeView(OpaqueTypeView(type)), TypeView(OpaqueTypeView(type))); EXPECT_EQ(OpaqueTypeView(type), OpaqueType(type)); EXPECT_EQ(TypeView(OpaqueTypeView(type)), OpaqueType(type)); EXPECT_EQ(TypeView(OpaqueTypeView(type)), Type(OpaqueType(type))); EXPECT_EQ(OpaqueType(type), OpaqueTypeView(type)); EXPECT_EQ(OpaqueType(type), OpaqueTypeView(type)); EXPECT_EQ(OpaqueType(type), TypeView(OpaqueTypeView(type))); EXPECT_EQ(Type(OpaqueType(type)), TypeView(OpaqueTypeView(type))); EXPECT_EQ(OpaqueTypeView(type), OpaqueType(type)); } TEST_P(OpaqueTypeViewTest, NativeTypeId) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_EQ(NativeTypeId::Of(OpaqueTypeView(type)), NativeTypeId::For<OpaqueTypeView>()); EXPECT_EQ(NativeTypeId::Of(TypeView(OpaqueTypeView(type))), NativeTypeId::For<OpaqueTypeView>()); } TEST_P(OpaqueTypeViewTest, InstanceOf) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_TRUE(InstanceOf<OpaqueTypeView>(OpaqueTypeView(type))); EXPECT_TRUE(InstanceOf<OpaqueTypeView>(TypeView(OpaqueTypeView(type)))); } TEST_P(OpaqueTypeViewTest, Cast) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_THAT(Cast<OpaqueTypeView>(OpaqueTypeView(type)), An<OpaqueTypeView>()); EXPECT_THAT(Cast<OpaqueTypeView>(TypeView(OpaqueTypeView(type))), An<OpaqueTypeView>()); } TEST_P(OpaqueTypeViewTest, As) { auto type = OpaqueType(memory_manager(), "test.Opaque", {BytesType()}); EXPECT_THAT(As<OpaqueTypeView>(OpaqueTypeView(type)), Ne(absl::nullopt)); EXPECT_THAT(As<OpaqueTypeView>(TypeView(OpaqueTypeView(type))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( OpaqueTypeViewTest, OpaqueTypeViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), OpaqueTypeViewTest::ToString); } }
23
cpp
google/cel-cpp
list_type
common/types/list_type.cc
common/types/list_type_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_LIST_TYPE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_TYPES_LIST_TYPE_H_ #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type_kind.h" namespace cel { class Type; class TypeView; class ListType; class ListTypeView; namespace common_internal { struct ListTypeData; } class ListType final { public: using view_alternative_type = ListTypeView; static constexpr TypeKind kKind = TypeKind::kList; static constexpr absl::string_view kName = "list"; explicit ListType(ListTypeView other); ListType(MemoryManagerRef memory_manager, Type element); ListType(); ListType(const ListType&) = default; ListType(ListType&&) = default; ListType& operator=(const ListType&) = default; ListType& operator=(ListType&&) = default; constexpr TypeKind kind() const { return kKind; } constexpr absl::string_view name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return kName; } std::string DebugString() const; absl::Span<const Type> parameters() const ABSL_ATTRIBUTE_LIFETIME_BOUND; void swap(ListType& other) noexcept { using std::swap; swap(data_, other.data_); } const Type& element() const ABSL_ATTRIBUTE_LIFETIME_BOUND; private: friend class ListTypeView; friend struct NativeTypeTraits<ListType>; Shared<const common_internal::ListTypeData> data_; }; inline void swap(ListType& lhs, ListType& rhs) noexcept { lhs.swap(rhs); } bool operator==(const ListType& lhs, const ListType& rhs); inline bool operator!=(const ListType& lhs, const ListType& rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, const ListType& type); inline std::ostream& operator<<(std::ostream& out, const ListType& type) { return out << type.DebugString(); } template <> struct NativeTypeTraits<ListType> final { static bool SkipDestructor(const ListType& type) { return NativeType::SkipDestructor(type.data_); } }; class ListTypeView final { public: using alternative_type = ListType; static constexpr TypeKind kKind = ListType::kKind; static constexpr absl::string_view kName = ListType::kName; ListTypeView(const ListType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept; ListTypeView& operator=(const ListType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) { data_ = type.data_; return *this; } ListTypeView& operator=(ListType&&) = delete; ListTypeView(); ListTypeView(const ListTypeView&) = default; ListTypeView(ListTypeView&&) = default; ListTypeView& operator=(const ListTypeView&) = default; ListTypeView& operator=(ListTypeView&&) = default; constexpr TypeKind kind() const { return kKind; } constexpr absl::string_view name() const { return kName; } std::string DebugString() const; absl::Span<const Type> parameters() const; void swap(ListTypeView& other) noexcept { using std::swap; swap(data_, other.data_); } const Type& element() const; private: friend class ListType; SharedView<const common_internal::ListTypeData> data_; }; inline void swap(ListTypeView& lhs, ListTypeView& rhs) noexcept { lhs.swap(rhs); } bool operator==(ListTypeView lhs, ListTypeView rhs); inline bool operator!=(ListTypeView lhs, ListTypeView rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, ListTypeView type); inline std::ostream& operator<<(std::ostream& out, ListTypeView type) { return out << type.DebugString(); } } #endif #include <string> #include "absl/strings/str_cat.h" #include "common/type.h" namespace cel { std::string ListType::DebugString() const { return absl::StrCat("list<", element().DebugString(), ">"); } std::string ListTypeView::DebugString() const { return absl::StrCat("list<", element().DebugString(), ">"); } }
#include <sstream> #include <string> #include "absl/hash/hash.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/memory_testing.h" #include "common/native_type.h" #include "common/type.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using testing::TestParamInfo; using testing::TestWithParam; TEST(ListType, Default) { ListType list_type; EXPECT_EQ(list_type.element(), DynType()); } TEST(ListTypeView, Default) { ListTypeView list_type; EXPECT_EQ(list_type.element(), DynType()); } class ListTypeTest : public common_internal::ThreadCompatibleMemoryTest<> {}; TEST_P(ListTypeTest, Kind) { EXPECT_EQ(ListType(memory_manager(), BoolType()).kind(), ListType::kKind); EXPECT_EQ(Type(ListType(memory_manager(), BoolType())).kind(), ListType::kKind); } TEST_P(ListTypeTest, Name) { EXPECT_EQ(ListType(memory_manager(), BoolType()).name(), ListType::kName); EXPECT_EQ(Type(ListType(memory_manager(), BoolType())).name(), ListType::kName); } TEST_P(ListTypeTest, DebugString) { { std::ostringstream out; out << ListType(memory_manager(), BoolType()); EXPECT_EQ(out.str(), "list<bool>"); } { std::ostringstream out; out << Type(ListType(memory_manager(), BoolType())); EXPECT_EQ(out.str(), "list<bool>"); } } TEST_P(ListTypeTest, Hash) { EXPECT_EQ(absl::HashOf(ListType(memory_manager(), BoolType())), absl::HashOf(ListType(memory_manager(), BoolType()))); } TEST_P(ListTypeTest, Equal) { EXPECT_EQ(ListType(memory_manager(), BoolType()), ListType(memory_manager(), BoolType())); EXPECT_EQ(Type(ListType(memory_manager(), BoolType())), ListType(memory_manager(), BoolType())); EXPECT_EQ(ListType(memory_manager(), BoolType()), Type(ListType(memory_manager(), BoolType()))); EXPECT_EQ(Type(ListType(memory_manager(), BoolType())), Type(ListType(memory_manager(), BoolType()))); } TEST_P(ListTypeTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(ListType(memory_manager(), BoolType())), NativeTypeId::For<ListType>()); EXPECT_EQ(NativeTypeId::Of(Type(ListType(memory_manager(), BoolType()))), NativeTypeId::For<ListType>()); } TEST_P(ListTypeTest, InstanceOf) { EXPECT_TRUE(InstanceOf<ListType>(ListType(memory_manager(), BoolType()))); EXPECT_TRUE( InstanceOf<ListType>(Type(ListType(memory_manager(), BoolType())))); } TEST_P(ListTypeTest, Cast) { EXPECT_THAT(Cast<ListType>(ListType(memory_manager(), BoolType())), An<ListType>()); EXPECT_THAT(Cast<ListType>(Type(ListType(memory_manager(), BoolType()))), An<ListType>()); } TEST_P(ListTypeTest, As) { EXPECT_THAT(As<ListType>(ListType(memory_manager(), BoolType())), Ne(absl::nullopt)); EXPECT_THAT(As<ListType>(Type(ListType(memory_manager(), BoolType()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( ListTypeTest, ListTypeTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ListTypeTest::ToString); class ListTypeViewTest : public common_internal::ThreadCompatibleMemoryTest<> { }; TEST_P(ListTypeViewTest, Kind) { auto type = ListType(memory_manager(), BoolType()); EXPECT_EQ(ListTypeView(type).kind(), ListTypeView::kKind); EXPECT_EQ(TypeView(ListTypeView(type)).kind(), ListTypeView::kKind); } TEST_P(ListTypeViewTest, Name) { auto type = ListType(memory_manager(), BoolType()); EXPECT_EQ(ListTypeView(type).name(), ListTypeView::kName); EXPECT_EQ(TypeView(ListTypeView(type)).name(), ListTypeView::kName); } TEST_P(ListTypeViewTest, DebugString) { auto type = ListType(memory_manager(), BoolType()); { std::ostringstream out; out << ListTypeView(type); EXPECT_EQ(out.str(), "list<bool>"); } { std::ostringstream out; out << TypeView(ListTypeView(type)); EXPECT_EQ(out.str(), "list<bool>"); } } TEST_P(ListTypeViewTest, Hash) { auto type = ListType(memory_manager(), BoolType()); EXPECT_EQ(absl::HashOf(ListTypeView(type)), absl::HashOf(ListTypeView(type))); EXPECT_EQ(absl::HashOf(ListTypeView(type)), absl::HashOf(ListType(type))); } TEST_P(ListTypeViewTest, Equal) { auto type = ListType(memory_manager(), BoolType()); EXPECT_EQ(ListTypeView(type), ListTypeView(type)); EXPECT_EQ(TypeView(ListTypeView(type)), ListTypeView(type)); EXPECT_EQ(ListTypeView(type), TypeView(ListTypeView(type))); EXPECT_EQ(TypeView(ListTypeView(type)), TypeView(ListTypeView(type))); EXPECT_EQ(ListTypeView(type), ListType(type)); EXPECT_EQ(TypeView(ListTypeView(type)), ListType(type)); EXPECT_EQ(TypeView(ListTypeView(type)), Type(ListType(type))); EXPECT_EQ(ListType(type), ListTypeView(type)); EXPECT_EQ(ListType(type), ListTypeView(type)); EXPECT_EQ(ListType(type), TypeView(ListTypeView(type))); EXPECT_EQ(Type(ListType(type)), TypeView(ListTypeView(type))); EXPECT_EQ(ListTypeView(type), ListType(type)); } TEST_P(ListTypeViewTest, NativeTypeId) { auto type = ListType(memory_manager(), BoolType()); EXPECT_EQ(NativeTypeId::Of(ListTypeView(type)), NativeTypeId::For<ListTypeView>()); EXPECT_EQ(NativeTypeId::Of(TypeView(ListTypeView(type))), NativeTypeId::For<ListTypeView>()); } TEST_P(ListTypeViewTest, InstanceOf) { auto type = ListType(memory_manager(), BoolType()); EXPECT_TRUE(InstanceOf<ListTypeView>(ListTypeView(type))); EXPECT_TRUE(InstanceOf<ListTypeView>(TypeView(ListTypeView(type)))); } TEST_P(ListTypeViewTest, Cast) { auto type = ListType(memory_manager(), BoolType()); EXPECT_THAT(Cast<ListTypeView>(ListTypeView(type)), An<ListTypeView>()); EXPECT_THAT(Cast<ListTypeView>(TypeView(ListTypeView(type))), An<ListTypeView>()); } TEST_P(ListTypeViewTest, As) { auto type = ListType(memory_manager(), BoolType()); EXPECT_THAT(As<ListTypeView>(ListTypeView(type)), Ne(absl::nullopt)); EXPECT_THAT(As<ListTypeView>(TypeView(ListTypeView(type))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( ListTypeViewTest, ListTypeViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ListTypeViewTest::ToString); } }
24
cpp
google/cel-cpp
map_type
common/types/map_type.cc
common/types/map_type_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_MAP_TYPE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_TYPES_MAP_TYPE_H_ #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type_kind.h" namespace cel { class Type; class TypeView; class MapType; class MapTypeView; namespace common_internal { struct MapTypeData; } class MapType final { public: using view_alternative_type = MapTypeView; static constexpr TypeKind kKind = TypeKind::kMap; static constexpr absl::string_view kName = "map"; explicit MapType(MapTypeView other); MapType(MemoryManagerRef memory_manager, Type key, Type value); MapType(); MapType(const MapType&) = default; MapType(MapType&&) = default; MapType& operator=(const MapType&) = default; MapType& operator=(MapType&&) = default; constexpr TypeKind kind() const { return kKind; } constexpr absl::string_view name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return kName; } std::string DebugString() const; absl::Span<const Type> parameters() const ABSL_ATTRIBUTE_LIFETIME_BOUND; void swap(MapType& other) noexcept { using std::swap; swap(data_, other.data_); } const Type& key() const ABSL_ATTRIBUTE_LIFETIME_BOUND; const Type& value() const ABSL_ATTRIBUTE_LIFETIME_BOUND; private: friend class MapTypeView; friend struct NativeTypeTraits<MapType>; Shared<const common_internal::MapTypeData> data_; }; inline void swap(MapType& lhs, MapType& rhs) noexcept { lhs.swap(rhs); } bool operator==(const MapType& lhs, const MapType& rhs); inline bool operator!=(const MapType& lhs, const MapType& rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, const MapType& type); inline std::ostream& operator<<(std::ostream& out, const MapType& type) { return out << type.DebugString(); } template <> struct NativeTypeTraits<MapType> final { static bool SkipDestructor(const MapType& type) { return NativeType::SkipDestructor(type.data_); } }; class MapTypeView final { public: using alternative_type = MapType; static constexpr TypeKind kKind = MapType::kKind; static constexpr absl::string_view kName = MapType::kName; MapTypeView(const MapType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept; MapTypeView& operator=(const MapType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) { data_ = type.data_; return *this; } MapTypeView& operator=(MapType&&) = delete; MapTypeView(); MapTypeView(const MapTypeView&) = default; MapTypeView(MapTypeView&&) = default; MapTypeView& operator=(const MapTypeView&) = default; MapTypeView& operator=(MapTypeView&&) = default; constexpr TypeKind kind() const { return kKind; } constexpr absl::string_view name() const { return kName; } std::string DebugString() const; absl::Span<const Type> parameters() const; void swap(MapTypeView& other) noexcept { using std::swap; swap(data_, other.data_); } const Type& key() const; const Type& value() const; private: friend class MapType; SharedView<const common_internal::MapTypeData> data_; }; inline void swap(MapTypeView& lhs, MapTypeView& rhs) noexcept { lhs.swap(rhs); } bool operator==(MapTypeView lhs, MapTypeView rhs); inline bool operator!=(MapTypeView lhs, MapTypeView rhs) { return !operator==(lhs, rhs); } template <typename H> H AbslHashValue(H state, MapTypeView type); inline std::ostream& operator<<(std::ostream& out, MapTypeView type) { return out << type.DebugString(); } } #endif #include <string> #include "absl/strings/str_cat.h" #include "common/type.h" namespace cel { std::string MapType::DebugString() const { return absl::StrCat("map<", key().DebugString(), ", ", value().DebugString(), ">"); } std::string MapTypeView::DebugString() const { return absl::StrCat("map<", key().DebugString(), ", ", value().DebugString(), ">"); } }
#include <sstream> #include <string> #include "absl/hash/hash.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/memory_testing.h" #include "common/native_type.h" #include "common/type.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using testing::TestParamInfo; using testing::TestWithParam; TEST(MapType, Default) { MapType map_type; EXPECT_EQ(map_type.key(), DynType()); EXPECT_EQ(map_type.value(), DynType()); } TEST(MapTypeView, Default) { MapTypeView map_type; EXPECT_EQ(map_type.key(), DynType()); EXPECT_EQ(map_type.value(), DynType()); } class MapTypeTest : public common_internal::ThreadCompatibleMemoryTest<> {}; TEST_P(MapTypeTest, Kind) { EXPECT_EQ(MapType(memory_manager(), StringType(), BytesType()).kind(), MapType::kKind); EXPECT_EQ(Type(MapType(memory_manager(), StringType(), BytesType())).kind(), MapType::kKind); } TEST_P(MapTypeTest, Name) { EXPECT_EQ(MapType(memory_manager(), StringType(), BytesType()).name(), MapType::kName); EXPECT_EQ(Type(MapType(memory_manager(), StringType(), BytesType())).name(), MapType::kName); } TEST_P(MapTypeTest, DebugString) { { std::ostringstream out; out << MapType(memory_manager(), StringType(), BytesType()); EXPECT_EQ(out.str(), "map<string, bytes>"); } { std::ostringstream out; out << Type(MapType(memory_manager(), StringType(), BytesType())); EXPECT_EQ(out.str(), "map<string, bytes>"); } } TEST_P(MapTypeTest, Hash) { EXPECT_EQ(absl::HashOf(MapType(memory_manager(), StringType(), BytesType())), absl::HashOf(MapType(memory_manager(), StringType(), BytesType()))); } TEST_P(MapTypeTest, Equal) { EXPECT_EQ(MapType(memory_manager(), StringType(), BytesType()), MapType(memory_manager(), StringType(), BytesType())); EXPECT_EQ(Type(MapType(memory_manager(), StringType(), BytesType())), MapType(memory_manager(), StringType(), BytesType())); EXPECT_EQ(MapType(memory_manager(), StringType(), BytesType()), Type(MapType(memory_manager(), StringType(), BytesType()))); EXPECT_EQ(Type(MapType(memory_manager(), StringType(), BytesType())), Type(MapType(memory_manager(), StringType(), BytesType()))); } TEST_P(MapTypeTest, NativeTypeId) { EXPECT_EQ( NativeTypeId::Of(MapType(memory_manager(), StringType(), BytesType())), NativeTypeId::For<MapType>()); EXPECT_EQ(NativeTypeId::Of( Type(MapType(memory_manager(), StringType(), BytesType()))), NativeTypeId::For<MapType>()); } TEST_P(MapTypeTest, InstanceOf) { EXPECT_TRUE(InstanceOf<MapType>( MapType(memory_manager(), StringType(), BytesType()))); EXPECT_TRUE(InstanceOf<MapType>( Type(MapType(memory_manager(), StringType(), BytesType())))); } TEST_P(MapTypeTest, Cast) { EXPECT_THAT( Cast<MapType>(MapType(memory_manager(), StringType(), BytesType())), An<MapType>()); EXPECT_THAT( Cast<MapType>(Type(MapType(memory_manager(), StringType(), BytesType()))), An<MapType>()); } TEST_P(MapTypeTest, As) { EXPECT_THAT(As<MapType>(MapType(memory_manager(), StringType(), BytesType())), Ne(absl::nullopt)); EXPECT_THAT( As<MapType>(Type(MapType(memory_manager(), StringType(), BytesType()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( MapTypeTest, MapTypeTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), MapTypeTest::ToString); class MapTypeViewTest : public common_internal::ThreadCompatibleMemoryTest<> {}; TEST_P(MapTypeViewTest, Kind) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_EQ(MapTypeView(type).kind(), MapTypeView::kKind); EXPECT_EQ(TypeView(MapTypeView(type)).kind(), MapTypeView::kKind); } TEST_P(MapTypeViewTest, Name) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_EQ(MapTypeView(type).name(), MapTypeView::kName); EXPECT_EQ(TypeView(MapTypeView(type)).name(), MapTypeView::kName); } TEST_P(MapTypeViewTest, DebugString) { auto type = MapType(memory_manager(), StringType(), BytesType()); { std::ostringstream out; out << MapTypeView(type); EXPECT_EQ(out.str(), "map<string, bytes>"); } { std::ostringstream out; out << TypeView(MapTypeView(type)); EXPECT_EQ(out.str(), "map<string, bytes>"); } } TEST_P(MapTypeViewTest, Hash) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_EQ(absl::HashOf(MapTypeView(type)), absl::HashOf(MapTypeView(type))); EXPECT_EQ(absl::HashOf(MapTypeView(type)), absl::HashOf(MapType(type))); } TEST_P(MapTypeViewTest, Equal) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_EQ(MapTypeView(type), MapTypeView(type)); EXPECT_EQ(TypeView(MapTypeView(type)), MapTypeView(type)); EXPECT_EQ(MapTypeView(type), TypeView(MapTypeView(type))); EXPECT_EQ(TypeView(MapTypeView(type)), TypeView(MapTypeView(type))); EXPECT_EQ(MapTypeView(type), MapType(type)); EXPECT_EQ(TypeView(MapTypeView(type)), MapType(type)); EXPECT_EQ(TypeView(MapTypeView(type)), Type(MapType(type))); EXPECT_EQ(MapType(type), MapTypeView(type)); EXPECT_EQ(MapType(type), MapTypeView(type)); EXPECT_EQ(MapType(type), TypeView(MapTypeView(type))); EXPECT_EQ(Type(MapType(type)), TypeView(MapTypeView(type))); EXPECT_EQ(MapTypeView(type), MapType(type)); } TEST_P(MapTypeViewTest, NativeTypeId) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_EQ(NativeTypeId::Of(MapTypeView(type)), NativeTypeId::For<MapTypeView>()); EXPECT_EQ(NativeTypeId::Of(TypeView(MapTypeView(type))), NativeTypeId::For<MapTypeView>()); } TEST_P(MapTypeViewTest, InstanceOf) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_TRUE(InstanceOf<MapTypeView>(MapTypeView(type))); EXPECT_TRUE(InstanceOf<MapTypeView>(TypeView(MapTypeView(type)))); } TEST_P(MapTypeViewTest, Cast) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_THAT(Cast<MapTypeView>(MapTypeView(type)), An<MapTypeView>()); EXPECT_THAT(Cast<MapTypeView>(TypeView(MapTypeView(type))), An<MapTypeView>()); } TEST_P(MapTypeViewTest, As) { auto type = MapType(memory_manager(), StringType(), BytesType()); EXPECT_THAT(As<MapTypeView>(MapTypeView(type)), Ne(absl::nullopt)); EXPECT_THAT(As<MapTypeView>(TypeView(MapTypeView(type))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( MapTypeViewTest, MapTypeViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), MapTypeViewTest::ToString); } }
25
cpp
google/cel-cpp
bool_value
common/values/bool_value.cc
common/values/bool_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_BOOL_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_BOOL_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class BoolValue; class BoolValueView; class TypeManager; namespace common_internal { struct BoolValueBase { static constexpr ValueKind kKind = ValueKind::kBool; BoolValueBase() = default; BoolValueBase(const BoolValueBase&) = default; BoolValueBase(BoolValueBase&&) = default; BoolValueBase& operator=(const BoolValueBase&) = default; BoolValueBase& operator=(BoolValueBase&&) = default; constexpr explicit BoolValueBase(bool value) noexcept : value(value) {} constexpr operator bool() const noexcept { return value; } constexpr ValueKind kind() const { return kKind; } BoolType GetType(TypeManager&) const { return BoolType(); } absl::string_view GetTypeName() const { return BoolType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue() == false; } constexpr bool NativeValue() const { return value; } bool value = false; }; } class BoolValue final : private common_internal::BoolValueBase { private: using Base = BoolValueBase; public: using view_alternative_type = BoolValueView; using Base::kKind; BoolValue() = default; BoolValue(const BoolValue&) = default; BoolValue(BoolValue&&) = default; BoolValue& operator=(const BoolValue&) = default; BoolValue& operator=(BoolValue&&) = default; constexpr explicit BoolValue(bool value) noexcept : Base(value) {} constexpr explicit BoolValue(BoolValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator bool; friend void swap(BoolValue& lhs, BoolValue& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class BoolValueView; }; template <typename H> H AbslHashValue(H state, BoolValue value) { return H::combine(std::move(state), value.NativeValue()); } inline std::ostream& operator<<(std::ostream& out, BoolValue value) { return out << value.DebugString(); } class BoolValueView final : private common_internal::BoolValueBase { private: using Base = BoolValueBase; public: using alternative_type = BoolValue; using Base::kKind; BoolValueView() = default; BoolValueView(const BoolValueView&) = default; BoolValueView(BoolValueView&&) = default; BoolValueView& operator=(const BoolValueView&) = default; BoolValueView& operator=(BoolValueView&&) = default; constexpr explicit BoolValueView(bool value) noexcept : Base(value) {} constexpr BoolValueView(BoolValue other) noexcept : BoolValueView(static_cast<bool>(other)) {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator bool; friend void swap(BoolValueView& lhs, BoolValueView& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class BoolValue; }; template <typename H> H AbslHashValue(H state, BoolValueView value) { return H::combine(std::move(state), value.NativeValue()); } inline std::ostream& operator<<(std::ostream& out, BoolValueView value) { return out << value.DebugString(); } inline constexpr BoolValue::BoolValue(BoolValueView other) noexcept : BoolValue(static_cast<bool>(other)) {} } #endif #include <cstddef> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/serialize.h" #include "internal/status_macros.h" namespace cel::common_internal { namespace { std::string BoolDebugString(bool value) { return value ? "true" : "false"; } } std::string BoolValueBase::DebugString() const { return BoolDebugString(NativeValue()); } absl::StatusOr<Json> BoolValueBase::ConvertToJson(AnyToJsonConverter&) const { return NativeValue(); } absl::StatusOr<size_t> BoolValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedBoolValueSize(NativeValue()); } absl::Status BoolValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeBoolValue(NativeValue(), value); } absl::StatusOr<absl::Cord> BoolValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> BoolValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.BoolValue"); } absl::StatusOr<Any> BoolValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::Status BoolValueBase::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<BoolValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<Value> BoolValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <sstream> #include "absl/hash/hash.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using BoolValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(BoolValueTest, Kind) { EXPECT_EQ(BoolValue(true).kind(), BoolValue::kKind); EXPECT_EQ(Value(BoolValue(true)).kind(), BoolValue::kKind); } TEST_P(BoolValueTest, DebugString) { { std::ostringstream out; out << BoolValue(true); EXPECT_EQ(out.str(), "true"); } { std::ostringstream out; out << Value(BoolValue(true)); EXPECT_EQ(out.str(), "true"); } } TEST_P(BoolValueTest, GetSerializedSize) { EXPECT_THAT(BoolValue(false).GetSerializedSize(value_manager()), IsOkAndHolds(0)); EXPECT_THAT(BoolValue(true).GetSerializedSize(value_manager()), IsOkAndHolds(2)); } TEST_P(BoolValueTest, ConvertToAny) { EXPECT_THAT(BoolValue(false).ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.BoolValue"), absl::Cord()))); } TEST_P(BoolValueTest, ConvertToJson) { EXPECT_THAT(BoolValue(false).ConvertToJson(value_manager()), IsOkAndHolds(Json(false))); } TEST_P(BoolValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(BoolValue(true)), NativeTypeId::For<BoolValue>()); EXPECT_EQ(NativeTypeId::Of(Value(BoolValue(true))), NativeTypeId::For<BoolValue>()); } TEST_P(BoolValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<BoolValue>(BoolValue(true))); EXPECT_TRUE(InstanceOf<BoolValue>(Value(BoolValue(true)))); } TEST_P(BoolValueTest, Cast) { EXPECT_THAT(Cast<BoolValue>(BoolValue(true)), An<BoolValue>()); EXPECT_THAT(Cast<BoolValue>(Value(BoolValue(true))), An<BoolValue>()); } TEST_P(BoolValueTest, As) { EXPECT_THAT(As<BoolValue>(BoolValue(true)), Ne(absl::nullopt)); EXPECT_THAT(As<BoolValue>(Value(BoolValue(true))), Ne(absl::nullopt)); } TEST_P(BoolValueTest, HashValue) { EXPECT_EQ(absl::HashOf(BoolValue(true)), absl::HashOf(true)); } TEST_P(BoolValueTest, Equality) { EXPECT_NE(BoolValue(false), true); EXPECT_NE(true, BoolValue(false)); EXPECT_NE(BoolValue(false), BoolValue(true)); } TEST_P(BoolValueTest, LessThan) { EXPECT_LT(BoolValue(false), true); EXPECT_LT(false, BoolValue(true)); EXPECT_LT(BoolValue(false), BoolValue(true)); } INSTANTIATE_TEST_SUITE_P( BoolValueTest, BoolValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), BoolValueTest::ToString); using BoolValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(BoolValueViewTest, Kind) { EXPECT_EQ(BoolValueView(true).kind(), BoolValueView::kKind); EXPECT_EQ(ValueView(BoolValueView(true)).kind(), BoolValueView::kKind); } TEST_P(BoolValueViewTest, DebugString) { { std::ostringstream out; out << BoolValueView(true); EXPECT_EQ(out.str(), "true"); } { std::ostringstream out; out << ValueView(BoolValueView(true)); EXPECT_EQ(out.str(), "true"); } } TEST_P(BoolValueViewTest, GetSerializedSize) { EXPECT_THAT(BoolValueView(false).GetSerializedSize(value_manager()), IsOkAndHolds(0)); EXPECT_THAT(BoolValueView(true).GetSerializedSize(value_manager()), IsOkAndHolds(2)); } TEST_P(BoolValueViewTest, ConvertToAny) { EXPECT_THAT(BoolValueView(false).ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.BoolValue"), absl::Cord()))); } TEST_P(BoolValueViewTest, ConvertToJson) { EXPECT_THAT(BoolValueView(false).ConvertToJson(value_manager()), IsOkAndHolds(Json(false))); } TEST_P(BoolValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(BoolValueView(true)), NativeTypeId::For<BoolValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(BoolValueView(true))), NativeTypeId::For<BoolValueView>()); } TEST_P(BoolValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<BoolValueView>(BoolValueView(true))); EXPECT_TRUE(InstanceOf<BoolValueView>(ValueView(BoolValueView(true)))); } TEST_P(BoolValueViewTest, Cast) { EXPECT_THAT(Cast<BoolValueView>(BoolValueView(true)), An<BoolValueView>()); EXPECT_THAT(Cast<BoolValueView>(ValueView(BoolValueView(true))), An<BoolValueView>()); } TEST_P(BoolValueViewTest, As) { EXPECT_THAT(As<BoolValueView>(BoolValueView(true)), Ne(absl::nullopt)); EXPECT_THAT(As<BoolValueView>(ValueView(BoolValueView(true))), Ne(absl::nullopt)); } TEST_P(BoolValueViewTest, HashValue) { EXPECT_EQ(absl::HashOf(BoolValueView(true)), absl::HashOf(true)); } TEST_P(BoolValueViewTest, Equality) { EXPECT_NE(BoolValueView(BoolValue(false)), true); EXPECT_NE(true, BoolValueView(false)); EXPECT_NE(BoolValueView(false), BoolValueView(true)); EXPECT_NE(BoolValueView(false), BoolValue(true)); EXPECT_NE(BoolValue(true), BoolValueView(false)); } TEST_P(BoolValueViewTest, LessThan) { EXPECT_LT(BoolValueView(false), true); EXPECT_LT(false, BoolValueView(true)); EXPECT_LT(BoolValueView(false), BoolValueView(true)); EXPECT_LT(BoolValueView(false), BoolValue(true)); EXPECT_LT(BoolValue(false), BoolValueView(true)); } INSTANTIATE_TEST_SUITE_P( BoolValueViewTest, BoolValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), BoolValueViewTest::ToString); } }
26
cpp
google/cel-cpp
null_value
common/values/null_value.cc
common/values/null_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_NULL_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_NULL_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class NullValue; class NullValueView; class TypeManager; namespace common_internal { struct NullValueBase { static constexpr ValueKind kKind = ValueKind::kNull; NullValueBase() = default; NullValueBase(const NullValueBase&) = default; NullValueBase(NullValueBase&&) = default; NullValueBase& operator=(const NullValueBase&) = default; NullValueBase& operator=(NullValueBase&&) = default; constexpr ValueKind kind() const { return kKind; } NullType GetType(TypeManager&) const { return NullType(); } absl::string_view GetTypeName() const { return NullType::kName; } std::string DebugString() const { return "null"; } absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const { return kJsonNull; } absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return true; } }; } class NullValue final : private common_internal::NullValueBase { private: using Base = NullValueBase; public: using view_alternative_type = NullValueView; using Base::kKind; NullValue() = default; NullValue(const NullValue&) = default; NullValue(NullValue&&) = default; NullValue& operator=(const NullValue&) = default; NullValue& operator=(NullValue&&) = default; constexpr explicit NullValue(NullValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; friend void swap(NullValue&, NullValue&) noexcept {} private: friend class NullValueView; }; inline bool operator==(NullValue, NullValue) { return true; } inline bool operator!=(NullValue lhs, NullValue rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, const NullValue& value) { return out << value.DebugString(); } class NullValueView final : private common_internal::NullValueBase { private: using Base = NullValueBase; public: using alternative_type = NullValue; using Base::kKind; NullValueView() = default; NullValueView(const NullValueView&) = default; NullValueView(NullValueView&&) = default; NullValueView& operator=(const NullValueView&) = default; NullValueView& operator=(NullValueView&&) = default; constexpr NullValueView(NullValue) noexcept {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; friend void swap(NullValueView&, NullValueView&) noexcept {} private: friend class NullValue; }; inline bool operator==(NullValueView, NullValueView) { return true; } inline bool operator!=(NullValueView lhs, NullValueView rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, NullValueView value) { return out << value.DebugString(); } inline constexpr NullValue::NullValue(NullValueView) noexcept {} } #endif #include <cstddef> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/serialize.h" #include "internal/status_macros.h" namespace cel::common_internal { absl::StatusOr<size_t> NullValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedValueSize(kJsonNull); } absl::Status NullValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeValue(kJsonNull, value); } absl::StatusOr<absl::Cord> NullValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> NullValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.Value"); } absl::StatusOr<Any> NullValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::Status NullValueBase::Equal(ValueManager&, ValueView other, Value& result) const { result = BoolValueView{InstanceOf<NullValueView>(other)}; return absl::OkStatus(); } absl::StatusOr<Value> NullValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <sstream> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using NullValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(NullValueTest, Kind) { EXPECT_EQ(NullValue().kind(), NullValue::kKind); EXPECT_EQ(Value(NullValue()).kind(), NullValue::kKind); } TEST_P(NullValueTest, DebugString) { { std::ostringstream out; out << NullValue(); EXPECT_EQ(out.str(), "null"); } { std::ostringstream out; out << Value(NullValue()); EXPECT_EQ(out.str(), "null"); } } TEST_P(NullValueTest, GetSerializedSize) { EXPECT_THAT(NullValue().GetSerializedSize(value_manager()), IsOkAndHolds(2)); } TEST_P(NullValueTest, ConvertToAny) { EXPECT_THAT( NullValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Value"), absl::Cord(absl::string_view("\010\000", 2))))); } TEST_P(NullValueTest, ConvertToJson) { EXPECT_THAT(NullValue().ConvertToJson(value_manager()), IsOkAndHolds(Json(kJsonNull))); } TEST_P(NullValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(NullValue()), NativeTypeId::For<NullValue>()); EXPECT_EQ(NativeTypeId::Of(Value(NullValue())), NativeTypeId::For<NullValue>()); } TEST_P(NullValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<NullValue>(NullValue())); EXPECT_TRUE(InstanceOf<NullValue>(Value(NullValue()))); } TEST_P(NullValueTest, Cast) { EXPECT_THAT(Cast<NullValue>(NullValue()), An<NullValue>()); EXPECT_THAT(Cast<NullValue>(Value(NullValue())), An<NullValue>()); } TEST_P(NullValueTest, As) { EXPECT_THAT(As<NullValue>(NullValue()), Ne(absl::nullopt)); EXPECT_THAT(As<NullValue>(Value(NullValue())), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( NullValueTest, NullValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), NullValueTest::ToString); using NullValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(NullValueViewTest, Kind) { EXPECT_EQ(NullValueView().kind(), NullValueView::kKind); EXPECT_EQ(ValueView(NullValueView()).kind(), NullValueView::kKind); } TEST_P(NullValueViewTest, DebugString) { { std::ostringstream out; out << NullValueView(); EXPECT_EQ(out.str(), "null"); } { std::ostringstream out; out << ValueView(NullValueView()); EXPECT_EQ(out.str(), "null"); } } TEST_P(NullValueViewTest, GetSerializedSize) { EXPECT_THAT(NullValueView().GetSerializedSize(value_manager()), IsOkAndHolds(2)); } TEST_P(NullValueViewTest, ConvertToAny) { EXPECT_THAT( NullValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Value"), absl::Cord(absl::string_view("\010\000", 2))))); } TEST_P(NullValueViewTest, ConvertToJson) { EXPECT_THAT(NullValueView().ConvertToJson(value_manager()), IsOkAndHolds(Json(kJsonNull))); } TEST_P(NullValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(NullValueView()), NativeTypeId::For<NullValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(NullValueView())), NativeTypeId::For<NullValueView>()); } TEST_P(NullValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<NullValueView>(NullValueView())); EXPECT_TRUE(InstanceOf<NullValueView>(ValueView(NullValueView()))); } TEST_P(NullValueViewTest, Cast) { EXPECT_THAT(Cast<NullValueView>(NullValueView()), An<NullValueView>()); EXPECT_THAT(Cast<NullValueView>(ValueView(NullValueView())), An<NullValueView>()); } TEST_P(NullValueViewTest, As) { EXPECT_THAT(As<NullValueView>(NullValueView()), Ne(absl::nullopt)); EXPECT_THAT(As<NullValueView>(ValueView(NullValueView())), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( NullValueViewTest, NullValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), NullValueViewTest::ToString); } }
27
cpp
google/cel-cpp
timestamp_value
common/values/timestamp_value.cc
common/values/timestamp_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_TIMESTAMP_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_TIMESTAMP_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class TimestampValue; class TimestampValueView; class TypeManager; namespace common_internal { struct TimestampValueBase { static constexpr ValueKind kKind = ValueKind::kTimestamp; constexpr explicit TimestampValueBase(absl::Time value) noexcept : value(value) {} TimestampValueBase() = default; TimestampValueBase(const TimestampValueBase&) = default; TimestampValueBase(TimestampValueBase&&) = default; TimestampValueBase& operator=(const TimestampValueBase&) = default; TimestampValueBase& operator=(TimestampValueBase&&) = default; constexpr ValueKind kind() const { return kKind; } TimestampType GetType(TypeManager&) const { return TimestampType(); } absl::string_view GetTypeName() const { return TimestampType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue() == absl::UnixEpoch(); } constexpr absl::Time NativeValue() const { return value; } constexpr operator absl::Time() const noexcept { return value; } absl::Time value = absl::UnixEpoch(); }; } class TimestampValue final : private common_internal::TimestampValueBase { private: using Base = TimestampValueBase; public: using view_alternative_type = TimestampValueView; using Base::kKind; TimestampValue() = default; TimestampValue(const TimestampValue&) = default; TimestampValue(TimestampValue&&) = default; TimestampValue& operator=(const TimestampValue&) = default; TimestampValue& operator=(TimestampValue&&) = default; constexpr explicit TimestampValue(absl::Time value) noexcept : Base(value) {} constexpr explicit TimestampValue(TimestampValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator absl::Time; friend void swap(TimestampValue& lhs, TimestampValue& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class DurationValueView; }; constexpr bool operator==(TimestampValue lhs, TimestampValue rhs) { return lhs.NativeValue() == rhs.NativeValue(); } constexpr bool operator!=(TimestampValue lhs, TimestampValue rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, TimestampValue value) { return out << value.DebugString(); } class TimestampValueView final : private common_internal::TimestampValueBase { private: using Base = TimestampValueBase; public: using alternative_type = TimestampValue; using Base::kKind; TimestampValueView() = default; TimestampValueView(const TimestampValueView&) = default; TimestampValueView(TimestampValueView&&) = default; TimestampValueView& operator=(const TimestampValueView&) = default; TimestampValueView& operator=(TimestampValueView&&) = default; constexpr explicit TimestampValueView(absl::Time value) noexcept : Base(value) {} constexpr TimestampValueView(TimestampValue other) noexcept : TimestampValueView(static_cast<absl::Time>(other)) {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator absl::Time; friend void swap(TimestampValueView& lhs, TimestampValueView& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class DurationValue; }; constexpr bool operator==(TimestampValueView lhs, TimestampValueView rhs) { return lhs.NativeValue() == rhs.NativeValue(); } constexpr bool operator!=(TimestampValueView lhs, TimestampValueView rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, TimestampValueView value) { return out << value.DebugString(); } inline constexpr TimestampValue::TimestampValue( TimestampValueView other) noexcept : TimestampValue(static_cast<absl::Time>(other)) {} } #endif #include <cstddef> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/serialize.h" #include "internal/status_macros.h" #include "internal/time.h" namespace cel::common_internal { namespace { std::string TimestampDebugString(absl::Time value) { return internal::DebugStringTimestamp(value); } } std::string TimestampValueBase::DebugString() const { return TimestampDebugString(NativeValue()); } absl::StatusOr<size_t> TimestampValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedTimestampSize(NativeValue()); } absl::Status TimestampValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeTimestamp(NativeValue(), value); } absl::StatusOr<absl::Cord> TimestampValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> TimestampValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.Timestamp"); } absl::StatusOr<Any> TimestampValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> TimestampValueBase::ConvertToJson( AnyToJsonConverter&) const { CEL_ASSIGN_OR_RETURN(auto json, internal::EncodeTimestampToJson(NativeValue())); return JsonString(std::move(json)); } absl::Status TimestampValueBase::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<TimestampValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<Value> TimestampValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <sstream> #include "absl/strings/cord.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using TimestampValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(TimestampValueTest, Kind) { EXPECT_EQ(TimestampValue().kind(), TimestampValue::kKind); EXPECT_EQ(Value(TimestampValue(absl::UnixEpoch() + absl::Seconds(1))).kind(), TimestampValue::kKind); } TEST_P(TimestampValueTest, DebugString) { { std::ostringstream out; out << TimestampValue(absl::UnixEpoch() + absl::Seconds(1)); EXPECT_EQ(out.str(), "1970-01-01T00:00:01Z"); } { std::ostringstream out; out << Value(TimestampValue(absl::UnixEpoch() + absl::Seconds(1))); EXPECT_EQ(out.str(), "1970-01-01T00:00:01Z"); } } TEST_P(TimestampValueTest, GetSerializedSize) { EXPECT_THAT(TimestampValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(TimestampValueTest, ConvertToAny) { EXPECT_THAT(TimestampValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Timestamp"), absl::Cord()))); } TEST_P(TimestampValueTest, ConvertToJson) { EXPECT_THAT(TimestampValue().ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonString("1970-01-01T00:00:00Z")))); } TEST_P(TimestampValueTest, NativeTypeId) { EXPECT_EQ( NativeTypeId::Of(TimestampValue(absl::UnixEpoch() + absl::Seconds(1))), NativeTypeId::For<TimestampValue>()); EXPECT_EQ(NativeTypeId::Of( Value(TimestampValue(absl::UnixEpoch() + absl::Seconds(1)))), NativeTypeId::For<TimestampValue>()); } TEST_P(TimestampValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<TimestampValue>( TimestampValue(absl::UnixEpoch() + absl::Seconds(1)))); EXPECT_TRUE(InstanceOf<TimestampValue>( Value(TimestampValue(absl::UnixEpoch() + absl::Seconds(1))))); } TEST_P(TimestampValueTest, Cast) { EXPECT_THAT(Cast<TimestampValue>( TimestampValue(absl::UnixEpoch() + absl::Seconds(1))), An<TimestampValue>()); EXPECT_THAT(Cast<TimestampValue>( Value(TimestampValue(absl::UnixEpoch() + absl::Seconds(1)))), An<TimestampValue>()); } TEST_P(TimestampValueTest, As) { EXPECT_THAT( As<TimestampValue>(TimestampValue(absl::UnixEpoch() + absl::Seconds(1))), Ne(absl::nullopt)); EXPECT_THAT(As<TimestampValue>( Value(TimestampValue(absl::UnixEpoch() + absl::Seconds(1)))), Ne(absl::nullopt)); } TEST_P(TimestampValueTest, Equality) { EXPECT_NE(TimestampValue(absl::UnixEpoch()), absl::UnixEpoch() + absl::Seconds(1)); EXPECT_NE(absl::UnixEpoch() + absl::Seconds(1), TimestampValue(absl::UnixEpoch())); EXPECT_NE(TimestampValue(absl::UnixEpoch()), TimestampValue(absl::UnixEpoch() + absl::Seconds(1))); } INSTANTIATE_TEST_SUITE_P( TimestampValueTest, TimestampValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), TimestampValueTest::ToString); using TimestampValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(TimestampValueViewTest, Kind) { EXPECT_EQ(TimestampValueView(absl::UnixEpoch() + absl::Seconds(1)).kind(), TimestampValueView::kKind); EXPECT_EQ(ValueView(TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))) .kind(), TimestampValueView::kKind); } TEST_P(TimestampValueViewTest, DebugString) { { std::ostringstream out; out << TimestampValueView(absl::UnixEpoch() + absl::Seconds(1)); EXPECT_EQ(out.str(), "1970-01-01T00:00:01Z"); } { std::ostringstream out; out << ValueView(TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))); EXPECT_EQ(out.str(), "1970-01-01T00:00:01Z"); } } TEST_P(TimestampValueViewTest, GetSerializedSize) { EXPECT_THAT(TimestampValueView().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(TimestampValueViewTest, ConvertToAny) { EXPECT_THAT(TimestampValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Timestamp"), absl::Cord()))); } TEST_P(TimestampValueViewTest, ConvertToJson) { EXPECT_THAT(TimestampValueView().ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonString("1970-01-01T00:00:00Z")))); } TEST_P(TimestampValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))), NativeTypeId::For<TimestampValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1)))), NativeTypeId::For<TimestampValueView>()); } TEST_P(TimestampValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<TimestampValueView>( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1)))); EXPECT_TRUE(InstanceOf<TimestampValueView>( ValueView(TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))))); } TEST_P(TimestampValueViewTest, Cast) { EXPECT_THAT(Cast<TimestampValueView>( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))), An<TimestampValueView>()); EXPECT_THAT(Cast<TimestampValueView>(ValueView( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1)))), An<TimestampValueView>()); } TEST_P(TimestampValueViewTest, As) { EXPECT_THAT(As<TimestampValueView>( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))), Ne(absl::nullopt)); EXPECT_THAT(As<TimestampValueView>(ValueView( TimestampValueView(absl::UnixEpoch() + absl::Seconds(1)))), Ne(absl::nullopt)); } TEST_P(TimestampValueViewTest, Equality) { EXPECT_NE(TimestampValueView(TimestampValue(absl::UnixEpoch())), absl::UnixEpoch() + absl::Seconds(1)); EXPECT_NE(absl::UnixEpoch() + absl::Seconds(1), TimestampValueView(absl::UnixEpoch())); EXPECT_NE(TimestampValueView(absl::UnixEpoch()), TimestampValueView(absl::UnixEpoch() + absl::Seconds(1))); EXPECT_NE(TimestampValueView(absl::UnixEpoch()), TimestampValue(absl::UnixEpoch() + absl::Seconds(1))); EXPECT_NE(TimestampValue(absl::UnixEpoch() + absl::Seconds(1)), TimestampValueView(absl::UnixEpoch())); } INSTANTIATE_TEST_SUITE_P( TimestampValueViewTest, TimestampValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), TimestampValueViewTest::ToString); } }
28
cpp
google/cel-cpp
duration_value
common/values/duration_value.cc
common/values/duration_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_DURATION_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_DURATION_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class DurationValue; class DurationValueView; class TypeManager; namespace common_internal { struct DurationValueBase { static constexpr ValueKind kKind = ValueKind::kDuration; constexpr explicit DurationValueBase(absl::Duration value) noexcept : value(value) {} DurationValueBase() = default; DurationValueBase(const DurationValueBase&) = default; DurationValueBase(DurationValueBase&&) = default; DurationValueBase& operator=(const DurationValueBase&) = default; DurationValueBase& operator=(DurationValueBase&&) = default; constexpr ValueKind kind() const { return kKind; } DurationType GetType(TypeManager&) const { return DurationType(); } absl::string_view GetTypeName() const { return DurationType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue() == absl::ZeroDuration(); } constexpr absl::Duration NativeValue() const { return value; } constexpr operator absl::Duration() const noexcept { return value; } absl::Duration value = absl::ZeroDuration(); }; } class DurationValue final : private common_internal::DurationValueBase { private: using Base = DurationValueBase; public: using view_alternative_type = DurationValueView; using Base::kKind; DurationValue() = default; DurationValue(const DurationValue&) = default; DurationValue(DurationValue&&) = default; DurationValue& operator=(const DurationValue&) = default; DurationValue& operator=(DurationValue&&) = default; constexpr explicit DurationValue(absl::Duration value) noexcept : Base(value) {} constexpr explicit DurationValue(DurationValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator absl::Duration; friend void swap(DurationValue& lhs, DurationValue& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class DurationValueView; }; inline bool operator==(DurationValue lhs, DurationValue rhs) { return static_cast<absl::Duration>(lhs) == static_cast<absl::Duration>(rhs); } inline bool operator!=(DurationValue lhs, DurationValue rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, DurationValue value) { return out << value.DebugString(); } class DurationValueView final : private common_internal::DurationValueBase { private: using Base = DurationValueBase; public: using alternative_type = DurationValue; using Base::kKind; DurationValueView() = default; DurationValueView(const DurationValueView&) = default; DurationValueView(DurationValueView&&) = default; DurationValueView& operator=(const DurationValueView&) = default; DurationValueView& operator=(DurationValueView&&) = default; constexpr explicit DurationValueView(absl::Duration value) noexcept : Base(value) {} constexpr DurationValueView(DurationValue other) noexcept : DurationValueView(static_cast<absl::Duration>(other)) {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator absl::Duration; friend void swap(DurationValueView& lhs, DurationValueView& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class DurationValue; }; inline bool operator==(DurationValueView lhs, DurationValueView rhs) { return static_cast<absl::Duration>(lhs) == static_cast<absl::Duration>(rhs); } inline bool operator!=(DurationValueView lhs, DurationValueView rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, DurationValueView value) { return out << value.DebugString(); } inline constexpr DurationValue::DurationValue(DurationValueView other) noexcept : DurationValue(static_cast<absl::Duration>(other)) {} } #endif #include <cstddef> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/serialize.h" #include "internal/status_macros.h" #include "internal/time.h" namespace cel::common_internal { namespace { std::string DurationDebugString(absl::Duration value) { return internal::DebugStringDuration(value); } } std::string DurationValueBase::DebugString() const { return DurationDebugString(NativeValue()); } absl::StatusOr<size_t> DurationValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedDurationSize(NativeValue()); } absl::Status DurationValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeDuration(NativeValue(), value); } absl::StatusOr<absl::Cord> DurationValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> DurationValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.Duration"); } absl::StatusOr<Any> DurationValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> DurationValueBase::ConvertToJson( AnyToJsonConverter&) const { CEL_ASSIGN_OR_RETURN(auto json, internal::EncodeDurationToJson(NativeValue())); return JsonString(std::move(json)); } absl::Status DurationValueBase::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<DurationValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<Value> DurationValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <sstream> #include "absl/strings/cord.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using DurationValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(DurationValueTest, Kind) { EXPECT_EQ(DurationValue().kind(), DurationValue::kKind); EXPECT_EQ(Value(DurationValue(absl::Seconds(1))).kind(), DurationValue::kKind); } TEST_P(DurationValueTest, DebugString) { { std::ostringstream out; out << DurationValue(absl::Seconds(1)); EXPECT_EQ(out.str(), "1s"); } { std::ostringstream out; out << Value(DurationValue(absl::Seconds(1))); EXPECT_EQ(out.str(), "1s"); } } TEST_P(DurationValueTest, GetSerializedSize) { EXPECT_THAT(DurationValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(DurationValueTest, ConvertToAny) { EXPECT_THAT(DurationValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Duration"), absl::Cord()))); } TEST_P(DurationValueTest, ConvertToJson) { EXPECT_THAT(DurationValue().ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonString("0s")))); } TEST_P(DurationValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(DurationValue(absl::Seconds(1))), NativeTypeId::For<DurationValue>()); EXPECT_EQ(NativeTypeId::Of(Value(DurationValue(absl::Seconds(1)))), NativeTypeId::For<DurationValue>()); } TEST_P(DurationValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<DurationValue>(DurationValue(absl::Seconds(1)))); EXPECT_TRUE( InstanceOf<DurationValue>(Value(DurationValue(absl::Seconds(1))))); } TEST_P(DurationValueTest, Cast) { EXPECT_THAT(Cast<DurationValue>(DurationValue(absl::Seconds(1))), An<DurationValue>()); EXPECT_THAT(Cast<DurationValue>(Value(DurationValue(absl::Seconds(1)))), An<DurationValue>()); } TEST_P(DurationValueTest, As) { EXPECT_THAT(As<DurationValue>(DurationValue(absl::Seconds(1))), Ne(absl::nullopt)); EXPECT_THAT(As<DurationValue>(Value(DurationValue(absl::Seconds(1)))), Ne(absl::nullopt)); } TEST_P(DurationValueTest, Equality) { EXPECT_NE(DurationValue(absl::ZeroDuration()), absl::Seconds(1)); EXPECT_NE(absl::Seconds(1), DurationValue(absl::ZeroDuration())); EXPECT_NE(DurationValue(absl::ZeroDuration()), DurationValue(absl::Seconds(1))); } INSTANTIATE_TEST_SUITE_P( DurationValueTest, DurationValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), DurationValueTest::ToString); using DurationValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(DurationValueViewTest, Kind) { EXPECT_EQ(DurationValueView(absl::Seconds(1)).kind(), DurationValueView::kKind); EXPECT_EQ(ValueView(DurationValueView(absl::Seconds(1))).kind(), DurationValueView::kKind); } TEST_P(DurationValueViewTest, DebugString) { { std::ostringstream out; out << DurationValueView(absl::Seconds(1)); EXPECT_EQ(out.str(), "1s"); } { std::ostringstream out; out << ValueView(DurationValueView(absl::Seconds(1))); EXPECT_EQ(out.str(), "1s"); } } TEST_P(DurationValueViewTest, GetSerializedSize) { EXPECT_THAT(DurationValueView().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(DurationValueViewTest, ConvertToAny) { EXPECT_THAT(DurationValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Duration"), absl::Cord()))); } TEST_P(DurationValueViewTest, ConvertToJson) { EXPECT_THAT(DurationValueView().ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonString("0s")))); } TEST_P(DurationValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(DurationValueView(absl::Seconds(1))), NativeTypeId::For<DurationValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(DurationValueView(absl::Seconds(1)))), NativeTypeId::For<DurationValueView>()); } TEST_P(DurationValueViewTest, InstanceOf) { EXPECT_TRUE( InstanceOf<DurationValueView>(DurationValueView(absl::Seconds(1)))); EXPECT_TRUE(InstanceOf<DurationValueView>( ValueView(DurationValueView(absl::Seconds(1))))); } TEST_P(DurationValueViewTest, Cast) { EXPECT_THAT(Cast<DurationValueView>(DurationValueView(absl::Seconds(1))), An<DurationValueView>()); EXPECT_THAT( Cast<DurationValueView>(ValueView(DurationValueView(absl::Seconds(1)))), An<DurationValueView>()); } TEST_P(DurationValueViewTest, As) { EXPECT_THAT(As<DurationValueView>(DurationValueView(absl::Seconds(1))), Ne(absl::nullopt)); EXPECT_THAT( As<DurationValueView>(ValueView(DurationValueView(absl::Seconds(1)))), Ne(absl::nullopt)); } TEST_P(DurationValueViewTest, Equality) { EXPECT_NE(DurationValueView(DurationValue(absl::ZeroDuration())), absl::Seconds(1)); EXPECT_NE(absl::Seconds(1), DurationValueView(absl::ZeroDuration())); EXPECT_NE(DurationValueView(absl::ZeroDuration()), DurationValueView(absl::Seconds(1))); EXPECT_NE(DurationValueView(absl::ZeroDuration()), DurationValue(absl::Seconds(1))); EXPECT_NE(DurationValue(absl::Seconds(1)), DurationValueView(absl::ZeroDuration())); } INSTANTIATE_TEST_SUITE_P( DurationValueViewTest, DurationValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), DurationValueViewTest::ToString); } }
29
cpp
google/cel-cpp
error_value
common/values/error_value.cc
common/values/error_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_ERROR_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_ERROR_VALUE_H_ #include <cstddef> #include <memory> #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class ErrorValue; class ErrorValueView; class TypeManager; class ABSL_ATTRIBUTE_TRIVIAL_ABI ErrorValue final { public: using view_alternative_type = ErrorValueView; static constexpr ValueKind kKind = ValueKind::kError; ErrorValue(absl::Status value) noexcept : value_(std::move(value)) { ABSL_DCHECK(!value_.ok()) << "ErrorValue requires a non-OK absl::Status"; } explicit ErrorValue(ErrorValueView value) noexcept; ErrorValue(); ErrorValue(const ErrorValue&) = default; ErrorValue& operator=(const ErrorValue&) = default; ErrorValue(ErrorValue&& other) noexcept : value_(std::move(other.value_)) {} ErrorValue& operator=(ErrorValue&& other) noexcept { value_ = std::move(other.value_); return *this; } constexpr ValueKind kind() const { return kKind; } ErrorType GetType(TypeManager&) const { return ErrorType(); } absl::string_view GetTypeName() const { return ErrorType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& value_manager) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return false; } absl::Status NativeValue() const& { ABSL_DCHECK(!value_.ok()) << "use of moved-from ErrorValue"; return value_; } absl::Status NativeValue() && { ABSL_DCHECK(!value_.ok()) << "use of moved-from ErrorValue"; return std::move(value_); } void swap(ErrorValue& other) noexcept { using std::swap; swap(value_, other.value_); } private: friend class ErrorValueView; absl::Status value_; }; ErrorValue NoSuchFieldError(absl::string_view field); ErrorValue NoSuchKeyError(absl::string_view key); ErrorValue NoSuchTypeError(absl::string_view type); ErrorValue DuplicateKeyError(); ErrorValue TypeConversionError(absl::string_view from, absl::string_view to); ErrorValue TypeConversionError(TypeView from, TypeView to); inline void swap(ErrorValue& lhs, ErrorValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const ErrorValue& value) { return out << value.DebugString(); } class ErrorValueView final { public: using alternative_type = ErrorValue; static constexpr ValueKind kKind = ErrorValue::kKind; ErrorValueView( const absl::Status& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(std::addressof(value)) { ABSL_DCHECK(!value.ok()) << "ErrorValueView requires a non-OK absl::Status"; } ErrorValueView(const ErrorValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(std::addressof(value.value_)) { ABSL_DCHECK(!value_->ok()) << "use of moved-from ErrorValue"; } ErrorValueView(); ErrorValueView(const ErrorValueView&) = default; ErrorValueView(ErrorValueView&&) = default; ErrorValueView& operator=(const ErrorValueView&) = default; ErrorValueView& operator=(ErrorValueView&&) = default; constexpr ValueKind kind() const { return kKind; } ErrorType GetType(TypeManager&) const { return ErrorType(); } absl::string_view GetTypeName() const { return ErrorType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& value_manager) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return false; } const absl::Status& NativeValue() const ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_DCHECK(!value_->ok()) << "use of moved-from ErrorValue"; return *value_; } void swap(ErrorValueView& other) noexcept { using std::swap; swap(value_, other.value_); } private: friend class ErrorValue; absl::Nonnull<const absl::Status*> value_; }; inline void swap(ErrorValueView& lhs, ErrorValueView& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, ErrorValueView value) { return out << value.DebugString(); } bool IsNoSuchField(ErrorValueView value); bool IsNoSuchKey(ErrorValueView value); inline ErrorValue::ErrorValue(ErrorValueView value) noexcept : value_(value.NativeValue()) {} } #endif #include <cstddef> #include <string> #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value.h" namespace cel { namespace { std::string ErrorDebugString(const absl::Status& value) { ABSL_DCHECK(!value.ok()) << "use of moved-from ErrorValue"; return value.ToString(absl::StatusToStringMode::kWithEverything); } } ErrorValue NoSuchFieldError(absl::string_view field) { return ErrorValue(absl::NotFoundError( absl::StrCat("no_such_field", field.empty() ? "" : " : ", field))); } ErrorValue NoSuchKeyError(absl::string_view key) { return ErrorValue( absl::NotFoundError(absl::StrCat("Key not found in map : ", key))); } ErrorValue NoSuchTypeError(absl::string_view type) { return ErrorValue( absl::NotFoundError(absl::StrCat("type not found: ", type))); } ErrorValue DuplicateKeyError() { return ErrorValue(absl::AlreadyExistsError("duplicate key in map")); } ErrorValue TypeConversionError(absl::string_view from, absl::string_view to) { return ErrorValue(absl::InvalidArgumentError( absl::StrCat("type conversion error from '", from, "' to '", to, "'"))); } ErrorValue TypeConversionError(TypeView from, TypeView to) { return TypeConversionError(from.DebugString(), to.DebugString()); } bool IsNoSuchField(ErrorValueView value) { return absl::IsNotFound(value.NativeValue()) && absl::StartsWith(value.NativeValue().message(), "no_such_field"); } bool IsNoSuchKey(ErrorValueView value) { return absl::IsNotFound(value.NativeValue()) && absl::StartsWith(value.NativeValue().message(), "Key not found in map"); } std::string ErrorValue::DebugString() const { return ErrorDebugString(value_); } absl::StatusOr<size_t> ErrorValue::GetSerializedSize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::Status ErrorValue::SerializeTo(AnyToJsonConverter&, absl::Cord&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<absl::Cord> ErrorValue::Serialize(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<std::string> ErrorValue::GetTypeUrl(absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Any> ErrorValue::ConvertToAny(AnyToJsonConverter&, absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Json> ErrorValue::ConvertToJson(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is not convertable to JSON")); } absl::Status ErrorValue::Equal(ValueManager&, ValueView, Value& result) const { result = BoolValueView{false}; return absl::OkStatus(); } std::string ErrorValueView::DebugString() const { return ErrorDebugString(*value_); } absl::StatusOr<size_t> ErrorValueView::GetSerializedSize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::Status ErrorValueView::SerializeTo(AnyToJsonConverter&, absl::Cord&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<absl::Cord> ErrorValueView::Serialize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<std::string> ErrorValueView::GetTypeUrl( absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Any> ErrorValueView::ConvertToAny(AnyToJsonConverter&, absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Json> ErrorValueView::ConvertToJson(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is not convertable to JSON")); } absl::Status ErrorValueView::Equal(ValueManager&, ValueView, Value& result) const { result = BoolValueView{false}; return absl::OkStatus(); } }
#include <sstream> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::_; using testing::An; using testing::IsEmpty; using testing::Ne; using testing::Not; using cel::internal::StatusIs; using ErrorValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(ErrorValueTest, Default) { ErrorValue value; EXPECT_THAT(value.NativeValue(), StatusIs(absl::StatusCode::kUnknown)); } TEST_P(ErrorValueTest, OkStatus) { EXPECT_DEBUG_DEATH(static_cast<void>(ErrorValue(absl::OkStatus())), _); } TEST_P(ErrorValueTest, Kind) { EXPECT_EQ(ErrorValue(absl::CancelledError()).kind(), ErrorValue::kKind); EXPECT_EQ(Value(ErrorValue(absl::CancelledError())).kind(), ErrorValue::kKind); } TEST_P(ErrorValueTest, DebugString) { { std::ostringstream out; out << ErrorValue(absl::CancelledError()); EXPECT_THAT(out.str(), Not(IsEmpty())); } { std::ostringstream out; out << Value(ErrorValue(absl::CancelledError())); EXPECT_THAT(out.str(), Not(IsEmpty())); } } TEST_P(ErrorValueTest, GetSerializedSize) { EXPECT_THAT(ErrorValue().GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueTest, SerializeTo) { absl::Cord value; EXPECT_THAT(ErrorValue().SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueTest, Serialize) { EXPECT_THAT(ErrorValue().Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueTest, GetTypeUrl) { EXPECT_THAT(ErrorValue().GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueTest, ConvertToAny) { EXPECT_THAT(ErrorValue().ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueTest, ConvertToJson) { EXPECT_THAT(ErrorValue().ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(ErrorValue(absl::CancelledError())), NativeTypeId::For<ErrorValue>()); EXPECT_EQ(NativeTypeId::Of(Value(ErrorValue(absl::CancelledError()))), NativeTypeId::For<ErrorValue>()); } TEST_P(ErrorValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<ErrorValue>(ErrorValue(absl::CancelledError()))); EXPECT_TRUE( InstanceOf<ErrorValue>(Value(ErrorValue(absl::CancelledError())))); } TEST_P(ErrorValueTest, Cast) { EXPECT_THAT(Cast<ErrorValue>(ErrorValue(absl::CancelledError())), An<ErrorValue>()); EXPECT_THAT(Cast<ErrorValue>(Value(ErrorValue(absl::CancelledError()))), An<ErrorValue>()); } TEST_P(ErrorValueTest, As) { EXPECT_THAT(As<ErrorValue>(ErrorValue(absl::CancelledError())), Ne(absl::nullopt)); EXPECT_THAT(As<ErrorValue>(Value(ErrorValue(absl::CancelledError()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( ErrorValueTest, ErrorValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), ErrorValueTest::ToString); using ErrorValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(ErrorValueViewTest, Default) { ErrorValueView value; EXPECT_THAT(value.NativeValue(), StatusIs(absl::StatusCode::kUnknown)); } TEST_P(ErrorValueViewTest, OkStatus) { EXPECT_DEBUG_DEATH(static_cast<void>(ErrorValueView(absl::OkStatus())), _); } TEST_P(ErrorValueViewTest, Kind) { EXPECT_EQ(ErrorValueView(absl::CancelledError()).kind(), ErrorValueView::kKind); EXPECT_EQ(ValueView(ErrorValueView(absl::CancelledError())).kind(), ErrorValueView::kKind); } TEST_P(ErrorValueViewTest, DebugString) { { std::ostringstream out; out << ErrorValueView(absl::CancelledError()); EXPECT_THAT(out.str(), Not(IsEmpty())); } { std::ostringstream out; out << ValueView(ErrorValueView(absl::CancelledError())); EXPECT_THAT(out.str(), Not(IsEmpty())); } } TEST_P(ErrorValueViewTest, GetSerializedSize) { EXPECT_THAT(ErrorValueView().GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueViewTest, SerializeTo) { absl::Cord value; EXPECT_THAT(ErrorValueView().SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueViewTest, Serialize) { EXPECT_THAT(ErrorValueView().Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueViewTest, GetTypeUrl) { EXPECT_THAT(ErrorValueView().GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueViewTest, ConvertToAny) { EXPECT_THAT(ErrorValueView().ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueViewTest, ConvertToJson) { EXPECT_THAT(ErrorValueView().ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ErrorValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(ErrorValueView(absl::CancelledError())), NativeTypeId::For<ErrorValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(ErrorValueView(absl::CancelledError()))), NativeTypeId::For<ErrorValueView>()); } TEST_P(ErrorValueViewTest, InstanceOf) { EXPECT_TRUE( InstanceOf<ErrorValueView>(ErrorValueView(absl::CancelledError()))); EXPECT_TRUE(InstanceOf<ErrorValueView>( ValueView(ErrorValueView(absl::CancelledError())))); } TEST_P(ErrorValueViewTest, Cast) { EXPECT_THAT(Cast<ErrorValueView>(ErrorValueView(absl::CancelledError())), An<ErrorValueView>()); EXPECT_THAT( Cast<ErrorValueView>(ValueView(ErrorValueView(absl::CancelledError()))), An<ErrorValueView>()); } TEST_P(ErrorValueViewTest, As) { EXPECT_THAT(As<ErrorValueView>(ErrorValueView(absl::CancelledError())), Ne(absl::nullopt)); EXPECT_THAT( As<ErrorValueView>(ValueView(ErrorValueView(absl::CancelledError()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( ErrorValueViewTest, ErrorValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), ErrorValueViewTest::ToString); } }
30
cpp
google/cel-cpp
int_value
common/values/int_value.cc
common/values/int_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_INT_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_INT_VALUE_H_ #include <cstddef> #include <cstdint> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class IntValue; class IntValueView; class TypeManager; namespace common_internal { struct IntValueBase { static constexpr ValueKind kKind = ValueKind::kInt; constexpr explicit IntValueBase(int64_t value) noexcept : value(value) {} IntValueBase() = default; IntValueBase(const IntValueBase&) = default; IntValueBase(IntValueBase&&) = default; IntValueBase& operator=(const IntValueBase&) = default; IntValueBase& operator=(IntValueBase&&) = default; constexpr ValueKind kind() const { return kKind; } IntType GetType(TypeManager&) const { return IntType(); } absl::string_view GetTypeName() const { return IntType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue() == 0; } constexpr int64_t NativeValue() const { return value; } constexpr operator int64_t() const noexcept { return value; } int64_t value = 0; }; } class IntValue final : private common_internal::IntValueBase { private: using Base = IntValueBase; public: using view_alternative_type = IntValueView; using Base::kKind; IntValue() = default; IntValue(const IntValue&) = default; IntValue(IntValue&&) = default; IntValue& operator=(const IntValue&) = default; IntValue& operator=(IntValue&&) = default; constexpr explicit IntValue(int64_t value) noexcept : Base(value) {} constexpr explicit IntValue(IntValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator int64_t; friend void swap(IntValue& lhs, IntValue& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class IntValueView; }; template <typename H> H AbslHashValue(H state, IntValue value) { return H::combine(std::move(state), value.NativeValue()); } constexpr bool operator==(IntValue lhs, IntValue rhs) { return lhs.NativeValue() == rhs.NativeValue(); } constexpr bool operator!=(IntValue lhs, IntValue rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, IntValue value) { return out << value.DebugString(); } class IntValueView final : private common_internal::IntValueBase { private: using Base = IntValueBase; public: using alternative_type = IntValue; using Base::kKind; IntValueView() = default; IntValueView(const IntValueView&) = default; IntValueView(IntValueView&&) = default; IntValueView& operator=(const IntValueView&) = default; IntValueView& operator=(IntValueView&&) = default; constexpr explicit IntValueView(int64_t value) noexcept : Base(value) {} constexpr IntValueView(IntValue other) noexcept : IntValueView(static_cast<int64_t>(other)) {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator int64_t; friend void swap(IntValueView& lhs, IntValueView& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class IntValue; }; template <typename H> H AbslHashValue(H state, IntValueView value) { return H::combine(std::move(state), value.NativeValue()); } constexpr bool operator==(IntValueView lhs, IntValueView rhs) { return lhs.NativeValue() == rhs.NativeValue(); } constexpr bool operator!=(IntValueView lhs, IntValueView rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, IntValueView value) { return out << value.DebugString(); } inline constexpr IntValue::IntValue(IntValueView other) noexcept : IntValue(static_cast<int64_t>(other)) {} } #endif #include <cstddef> #include <cstdint> #include <string> #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 "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/number.h" #include "internal/serialize.h" #include "internal/status_macros.h" namespace cel::common_internal { namespace { std::string IntDebugString(int64_t value) { return absl::StrCat(value); } } std::string IntValueBase::DebugString() const { return IntDebugString(NativeValue()); } absl::StatusOr<size_t> IntValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedInt64ValueSize(NativeValue()); } absl::Status IntValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeInt64Value(NativeValue(), value); } absl::StatusOr<absl::Cord> IntValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> IntValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.Int64Value"); } absl::StatusOr<Any> IntValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> IntValueBase::ConvertToJson(AnyToJsonConverter&) const { return JsonInt(NativeValue()); } absl::Status IntValueBase::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<IntValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } if (auto other_value = As<DoubleValueView>(other); other_value.has_value()) { result = BoolValueView{internal::Number::FromInt64(NativeValue()) == internal::Number::FromDouble(other_value->NativeValue())}; return absl::OkStatus(); } if (auto other_value = As<UintValueView>(other); other_value.has_value()) { result = BoolValueView{internal::Number::FromInt64(NativeValue()) == internal::Number::FromUint64(other_value->NativeValue())}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<Value> IntValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <cstdint> #include <sstream> #include "absl/hash/hash.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using IntValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(IntValueTest, Kind) { EXPECT_EQ(IntValue(1).kind(), IntValue::kKind); EXPECT_EQ(Value(IntValue(1)).kind(), IntValue::kKind); } TEST_P(IntValueTest, DebugString) { { std::ostringstream out; out << IntValue(1); EXPECT_EQ(out.str(), "1"); } { std::ostringstream out; out << Value(IntValue(1)); EXPECT_EQ(out.str(), "1"); } } TEST_P(IntValueTest, GetSerializedSize) { EXPECT_THAT(IntValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(IntValueTest, ConvertToAny) { EXPECT_THAT(IntValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Int64Value"), absl::Cord()))); } TEST_P(IntValueTest, ConvertToJson) { EXPECT_THAT(IntValue(1).ConvertToJson(value_manager()), IsOkAndHolds(Json(1.0))); } TEST_P(IntValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(IntValue(1)), NativeTypeId::For<IntValue>()); EXPECT_EQ(NativeTypeId::Of(Value(IntValue(1))), NativeTypeId::For<IntValue>()); } TEST_P(IntValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<IntValue>(IntValue(1))); EXPECT_TRUE(InstanceOf<IntValue>(Value(IntValue(1)))); } TEST_P(IntValueTest, Cast) { EXPECT_THAT(Cast<IntValue>(IntValue(1)), An<IntValue>()); EXPECT_THAT(Cast<IntValue>(Value(IntValue(1))), An<IntValue>()); } TEST_P(IntValueTest, As) { EXPECT_THAT(As<IntValue>(IntValue(1)), Ne(absl::nullopt)); EXPECT_THAT(As<IntValue>(Value(IntValue(1))), Ne(absl::nullopt)); } TEST_P(IntValueTest, HashValue) { EXPECT_EQ(absl::HashOf(IntValue(1)), absl::HashOf(int64_t{1})); } TEST_P(IntValueTest, Equality) { EXPECT_NE(IntValue(0), 1); EXPECT_NE(1, IntValue(0)); EXPECT_NE(IntValue(0), IntValue(1)); } TEST_P(IntValueTest, LessThan) { EXPECT_LT(IntValue(0), 1); EXPECT_LT(0, IntValue(1)); EXPECT_LT(IntValue(0), IntValue(1)); } INSTANTIATE_TEST_SUITE_P( IntValueTest, IntValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), IntValueTest::ToString); using IntValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(IntValueViewTest, Kind) { EXPECT_EQ(IntValueView(1).kind(), IntValueView::kKind); EXPECT_EQ(ValueView(IntValueView(1)).kind(), IntValueView::kKind); } TEST_P(IntValueViewTest, DebugString) { { std::ostringstream out; out << IntValueView(1); EXPECT_EQ(out.str(), "1"); } { std::ostringstream out; out << ValueView(IntValueView(1)); EXPECT_EQ(out.str(), "1"); } } TEST_P(IntValueViewTest, GetSerializedSize) { EXPECT_THAT(IntValueView().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(IntValueViewTest, ConvertToAny) { EXPECT_THAT(IntValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Int64Value"), absl::Cord()))); } TEST_P(IntValueViewTest, ConvertToJson) { EXPECT_THAT(IntValueView(1).ConvertToJson(value_manager()), IsOkAndHolds(Json(1.0))); } TEST_P(IntValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(IntValueView(1)), NativeTypeId::For<IntValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(IntValueView(1))), NativeTypeId::For<IntValueView>()); } TEST_P(IntValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<IntValueView>(IntValueView(1))); EXPECT_TRUE(InstanceOf<IntValueView>(ValueView(IntValueView(1)))); } TEST_P(IntValueViewTest, Cast) { EXPECT_THAT(Cast<IntValueView>(IntValueView(1)), An<IntValueView>()); EXPECT_THAT(Cast<IntValueView>(ValueView(IntValueView(1))), An<IntValueView>()); } TEST_P(IntValueViewTest, As) { EXPECT_THAT(As<IntValueView>(IntValueView(1)), Ne(absl::nullopt)); EXPECT_THAT(As<IntValueView>(ValueView(IntValueView(1))), Ne(absl::nullopt)); } TEST_P(IntValueViewTest, HashValue) { EXPECT_EQ(absl::HashOf(IntValueView(1)), absl::HashOf(int64_t{1})); } TEST_P(IntValueViewTest, Equality) { EXPECT_NE(IntValueView(IntValue(0)), 1); EXPECT_NE(1, IntValueView(0)); EXPECT_NE(IntValueView(0), IntValueView(1)); EXPECT_NE(IntValueView(0), IntValue(1)); EXPECT_NE(IntValue(1), IntValueView(0)); } TEST_P(IntValueViewTest, LessThan) { EXPECT_LT(IntValueView(0), 1); EXPECT_LT(0, IntValueView(1)); EXPECT_LT(IntValueView(0), IntValueView(1)); EXPECT_LT(IntValueView(0), IntValue(1)); EXPECT_LT(IntValue(0), IntValueView(1)); } INSTANTIATE_TEST_SUITE_P( IntValueViewTest, IntValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), IntValueViewTest::ToString); } }
31
cpp
google/cel-cpp
double_value
common/values/double_value.cc
common/values/double_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_DOUBLE_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_DOUBLE_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class DoubleValue; class DoubleValueView; class TypeManager; namespace common_internal { struct DoubleValueBase { static constexpr ValueKind kKind = ValueKind::kDouble; constexpr explicit DoubleValueBase(double value) noexcept : value(value) {} DoubleValueBase() = default; DoubleValueBase(const DoubleValueBase&) = default; DoubleValueBase(DoubleValueBase&&) = default; DoubleValueBase& operator=(const DoubleValueBase&) = default; DoubleValueBase& operator=(DoubleValueBase&&) = default; constexpr ValueKind kind() const { return kKind; } DoubleType GetType(TypeManager&) const { return DoubleType(); } absl::string_view GetTypeName() const { return DoubleType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& value_manager) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue() == 0.0; } constexpr double NativeValue() const { return value; } constexpr operator double() const noexcept { return value; } double value = 0.0; }; } class DoubleValue final : private common_internal::DoubleValueBase { private: using Base = DoubleValueBase; public: using view_alternative_type = DoubleValueView; using Base::kKind; DoubleValue() = default; DoubleValue(const DoubleValue&) = default; DoubleValue(DoubleValue&&) = default; DoubleValue& operator=(const DoubleValue&) = default; DoubleValue& operator=(DoubleValue&&) = default; constexpr explicit DoubleValue(double value) noexcept : Base(value) {} constexpr explicit DoubleValue(DoubleValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator double; friend void swap(DoubleValue& lhs, DoubleValue& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class DoubleValueView; }; inline std::ostream& operator<<(std::ostream& out, DoubleValue value) { return out << value.DebugString(); } class DoubleValueView final : private common_internal::DoubleValueBase { private: using Base = DoubleValueBase; public: using alternative_type = DoubleValue; using Base::kKind; DoubleValueView() = default; DoubleValueView(const DoubleValueView&) = default; DoubleValueView(DoubleValueView&&) = default; DoubleValueView& operator=(const DoubleValueView&) = default; DoubleValueView& operator=(DoubleValueView&&) = default; constexpr explicit DoubleValueView(double value) noexcept : Base(value) {} constexpr DoubleValueView(DoubleValue other) noexcept : DoubleValueView(static_cast<double>(other)) {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator double; friend void swap(DoubleValueView& lhs, DoubleValueView& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class BoolValue; }; inline std::ostream& operator<<(std::ostream& out, DoubleValueView value) { return out << value.DebugString(); } inline constexpr DoubleValue::DoubleValue(DoubleValueView other) noexcept : DoubleValue(static_cast<double>(other)) {} } #endif #include <cmath> #include <cstddef> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/number.h" #include "internal/serialize.h" #include "internal/status_macros.h" namespace cel::common_internal { namespace { std::string DoubleDebugString(double value) { if (std::isfinite(value)) { if (std::floor(value) != value) { return absl::StrCat(value); } std::string stringified = absl::StrCat(value); if (!absl::StrContains(stringified, '.')) { absl::StrAppend(&stringified, ".0"); } else { } return stringified; } if (std::isnan(value)) { return "nan"; } if (std::signbit(value)) { return "-infinity"; } return "+infinity"; } } std::string DoubleValueBase::DebugString() const { return DoubleDebugString(NativeValue()); } absl::StatusOr<size_t> DoubleValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedDoubleValueSize(NativeValue()); } absl::Status DoubleValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeDoubleValue(NativeValue(), value); } absl::StatusOr<absl::Cord> DoubleValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> DoubleValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.DoubleValue"); } absl::StatusOr<Any> DoubleValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> DoubleValueBase::ConvertToJson(AnyToJsonConverter&) const { return NativeValue(); } absl::Status DoubleValueBase::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<DoubleValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } if (auto other_value = As<IntValueView>(other); other_value.has_value()) { result = BoolValueView{internal::Number::FromDouble(NativeValue()) == internal::Number::FromInt64(other_value->NativeValue())}; return absl::OkStatus(); } if (auto other_value = As<UintValueView>(other); other_value.has_value()) { result = BoolValueView{internal::Number::FromDouble(NativeValue()) == internal::Number::FromUint64(other_value->NativeValue())}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<Value> DoubleValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <cmath> #include <sstream> #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using DoubleValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(DoubleValueTest, Kind) { EXPECT_EQ(DoubleValue(1.0).kind(), DoubleValue::kKind); EXPECT_EQ(Value(DoubleValue(1.0)).kind(), DoubleValue::kKind); } TEST_P(DoubleValueTest, DebugString) { { std::ostringstream out; out << DoubleValue(0.0); EXPECT_EQ(out.str(), "0.0"); } { std::ostringstream out; out << DoubleValue(1.0); EXPECT_EQ(out.str(), "1.0"); } { std::ostringstream out; out << DoubleValue(1.1); EXPECT_EQ(out.str(), "1.1"); } { std::ostringstream out; out << DoubleValue(NAN); EXPECT_EQ(out.str(), "nan"); } { std::ostringstream out; out << DoubleValue(INFINITY); EXPECT_EQ(out.str(), "+infinity"); } { std::ostringstream out; out << DoubleValue(-INFINITY); EXPECT_EQ(out.str(), "-infinity"); } { std::ostringstream out; out << Value(DoubleValue(0.0)); EXPECT_EQ(out.str(), "0.0"); } } TEST_P(DoubleValueTest, GetSerializedSize) { EXPECT_THAT(DoubleValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(DoubleValueTest, ConvertToAny) { EXPECT_THAT(DoubleValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.DoubleValue"), absl::Cord()))); } TEST_P(DoubleValueTest, ConvertToJson) { EXPECT_THAT(DoubleValue(1.0).ConvertToJson(value_manager()), IsOkAndHolds(Json(1.0))); } TEST_P(DoubleValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(DoubleValue(1.0)), NativeTypeId::For<DoubleValue>()); EXPECT_EQ(NativeTypeId::Of(Value(DoubleValue(1.0))), NativeTypeId::For<DoubleValue>()); } TEST_P(DoubleValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<DoubleValue>(DoubleValue(1.0))); EXPECT_TRUE(InstanceOf<DoubleValue>(Value(DoubleValue(1.0)))); } TEST_P(DoubleValueTest, Cast) { EXPECT_THAT(Cast<DoubleValue>(DoubleValue(1.0)), An<DoubleValue>()); EXPECT_THAT(Cast<DoubleValue>(Value(DoubleValue(1.0))), An<DoubleValue>()); } TEST_P(DoubleValueTest, As) { EXPECT_THAT(As<DoubleValue>(DoubleValue(1.0)), Ne(absl::nullopt)); EXPECT_THAT(As<DoubleValue>(Value(DoubleValue(1.0))), Ne(absl::nullopt)); } TEST_P(DoubleValueTest, Equality) { EXPECT_NE(DoubleValue(0.0), 1.0); EXPECT_NE(1.0, DoubleValue(0.0)); EXPECT_NE(DoubleValue(0.0), DoubleValue(1.0)); } INSTANTIATE_TEST_SUITE_P( DoubleValueTest, DoubleValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), DoubleValueTest::ToString); using DoubleValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(DoubleValueViewTest, Kind) { EXPECT_EQ(DoubleValueView(1.0).kind(), DoubleValueView::kKind); EXPECT_EQ(ValueView(DoubleValueView(1.0)).kind(), DoubleValueView::kKind); } TEST_P(DoubleValueViewTest, DebugString) { { std::ostringstream out; out << DoubleValueView(0.0); EXPECT_EQ(out.str(), "0.0"); } { std::ostringstream out; out << DoubleValueView(1.0); EXPECT_EQ(out.str(), "1.0"); } { std::ostringstream out; out << DoubleValueView(1.1); EXPECT_EQ(out.str(), "1.1"); } { std::ostringstream out; out << DoubleValueView(NAN); EXPECT_EQ(out.str(), "nan"); } { std::ostringstream out; out << DoubleValueView(INFINITY); EXPECT_EQ(out.str(), "+infinity"); } { std::ostringstream out; out << DoubleValueView(-INFINITY); EXPECT_EQ(out.str(), "-infinity"); } { std::ostringstream out; out << ValueView(DoubleValueView(0.0)); EXPECT_EQ(out.str(), "0.0"); } } TEST_P(DoubleValueViewTest, GetSerializedSize) { EXPECT_THAT(DoubleValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(DoubleValueViewTest, ConvertToAny) { EXPECT_THAT(DoubleValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.DoubleValue"), absl::Cord()))); } TEST_P(DoubleValueViewTest, ConvertToJson) { EXPECT_THAT(DoubleValueView(1.0).ConvertToJson(value_manager()), IsOkAndHolds(Json(1.0))); } TEST_P(DoubleValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(DoubleValueView(1.0)), NativeTypeId::For<DoubleValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(DoubleValueView(1.0))), NativeTypeId::For<DoubleValueView>()); } TEST_P(DoubleValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<DoubleValueView>(DoubleValueView(1.0))); EXPECT_TRUE(InstanceOf<DoubleValueView>(ValueView(DoubleValueView(1.0)))); } TEST_P(DoubleValueViewTest, Cast) { EXPECT_THAT(Cast<DoubleValueView>(DoubleValueView(1.0)), An<DoubleValueView>()); EXPECT_THAT(Cast<DoubleValueView>(ValueView(DoubleValueView(1.0))), An<DoubleValueView>()); } TEST_P(DoubleValueViewTest, As) { EXPECT_THAT(As<DoubleValueView>(DoubleValueView(1.0)), Ne(absl::nullopt)); EXPECT_THAT(As<DoubleValueView>(ValueView(DoubleValueView(1.0))), Ne(absl::nullopt)); } TEST_P(DoubleValueViewTest, Equality) { EXPECT_NE(DoubleValueView(DoubleValue(0.0)), 1.0); EXPECT_NE(1.0, DoubleValueView(0.0)); EXPECT_NE(DoubleValueView(0.0), DoubleValueView(1.0)); EXPECT_NE(DoubleValueView(0.0), DoubleValue(1.0)); EXPECT_NE(DoubleValue(1.0), DoubleValueView(0.0)); } INSTANTIATE_TEST_SUITE_P( DoubleValueViewTest, DoubleValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), DoubleValueViewTest::ToString); } }
32
cpp
google/cel-cpp
unknown_value
common/values/unknown_value.cc
common/values/unknown_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_UNKNOWN_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_UNKNOWN_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/unknown.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class UnknownValue; class UnknownValueView; class TypeManager; class UnknownValue final { public: using view_alternative_type = UnknownValueView; static constexpr ValueKind kKind = ValueKind::kUnknown; explicit UnknownValue(UnknownValueView) noexcept; explicit UnknownValue(Unknown unknown) : unknown_(std::move(unknown)) {} UnknownValue() = default; UnknownValue(const UnknownValue&) = default; UnknownValue(UnknownValue&&) = default; UnknownValue& operator=(const UnknownValue&) = default; UnknownValue& operator=(UnknownValue&&) = default; constexpr ValueKind kind() const { return kKind; } UnknownType GetType(TypeManager&) const { return UnknownType(); } absl::string_view GetTypeName() const { return UnknownType::kName; } std::string DebugString() const { return ""; } absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return false; } void swap(UnknownValue& other) noexcept { using std::swap; swap(unknown_, other.unknown_); } const Unknown& NativeValue() const& ABSL_ATTRIBUTE_LIFETIME_BOUND { return unknown_; } Unknown NativeValue() && { Unknown unknown = std::move(unknown_); return unknown; } const AttributeSet& attribute_set() const { return unknown_.unknown_attributes(); } const FunctionResultSet& function_result_set() const { return unknown_.unknown_function_results(); } private: friend class UnknownValueView; Unknown unknown_; }; inline void swap(UnknownValue& lhs, UnknownValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const UnknownValue& value) { return out << value.DebugString(); } class UnknownValueView final { private: ABSL_ATTRIBUTE_PURE_FUNCTION static const Unknown& Empty(); public: using alternative_type = UnknownValue; static constexpr ValueKind kKind = UnknownValue::kKind; UnknownValueView( const UnknownValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : unknown_(&value.unknown_) {} UnknownValueView( const Unknown& unknown ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : unknown_(&unknown) {} UnknownValueView(UnknownValue&&) = delete; UnknownValueView(Unknown&&) = delete; UnknownValueView& operator=( const UnknownValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { unknown_ = &value.unknown_; return *this; } UnknownValueView& operator=( const Unknown& unknown ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept { unknown_ = &unknown; return *this; } UnknownValueView& operator=(UnknownValue&&) = delete; UnknownValueView& operator=(Unknown&&) = delete; UnknownValueView() = default; UnknownValueView(const UnknownValueView&) = default; UnknownValueView& operator=(const UnknownValueView&) = default; constexpr ValueKind kind() const { return kKind; } UnknownType GetType(TypeManager&) const { return UnknownType(); } absl::string_view GetTypeName() const { return UnknownType::kName; } std::string DebugString() const { return ""; } absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return false; } const Unknown& NativeValue() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return *unknown_; } void swap(UnknownValueView& other) noexcept { using std::swap; swap(unknown_, other.unknown_); } const AttributeSet& attribute_set() const { return unknown_->unknown_attributes(); } const FunctionResultSet& function_result_set() const { return unknown_->unknown_function_results(); } private: friend class UnknownValue; const Unknown* unknown_ = &Empty(); }; inline void swap(UnknownValueView& lhs, UnknownValueView& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, UnknownValueView value) { return out << value.DebugString(); } inline UnknownValue::UnknownValue(UnknownValueView value) noexcept : unknown_(*value.unknown_) {} } #endif #include <cstddef> #include <string> #include "absl/base/no_destructor.h" #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 "common/any.h" #include "common/json.h" #include "common/unknown.h" #include "common/value.h" namespace cel { absl::StatusOr<size_t> UnknownValue::GetSerializedSize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::Status UnknownValue::SerializeTo(AnyToJsonConverter&, absl::Cord&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<absl::Cord> UnknownValue::Serialize(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<std::string> UnknownValue::GetTypeUrl(absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Any> UnknownValue::ConvertToAny(AnyToJsonConverter&, absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Json> UnknownValue::ConvertToJson(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is not convertable to JSON")); } absl::Status UnknownValue::Equal(ValueManager&, ValueView, Value& result) const { result = BoolValueView{false}; return absl::OkStatus(); } const Unknown& UnknownValueView::Empty() { static const absl::NoDestructor<Unknown> empty; return *empty; } absl::StatusOr<size_t> UnknownValueView::GetSerializedSize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::Status UnknownValueView::SerializeTo(AnyToJsonConverter&, absl::Cord&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<absl::Cord> UnknownValueView::Serialize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<std::string> UnknownValueView::GetTypeUrl( absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Any> UnknownValueView::ConvertToAny(AnyToJsonConverter&, absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Json> UnknownValueView::ConvertToJson( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is not convertable to JSON")); } absl::Status UnknownValueView::Equal(ValueManager&, ValueView, Value& result) const { result = BoolValueView{false}; return absl::OkStatus(); } }
#include <sstream> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::StatusIs; using UnknownValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(UnknownValueTest, Kind) { EXPECT_EQ(UnknownValue().kind(), UnknownValue::kKind); EXPECT_EQ(Value(UnknownValue()).kind(), UnknownValue::kKind); } TEST_P(UnknownValueTest, DebugString) { { std::ostringstream out; out << UnknownValue(); EXPECT_EQ(out.str(), ""); } { std::ostringstream out; out << Value(UnknownValue()); EXPECT_EQ(out.str(), ""); } } TEST_P(UnknownValueTest, GetSerializedSize) { EXPECT_THAT(UnknownValue().GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueTest, SerializeTo) { absl::Cord value; EXPECT_THAT(UnknownValue().SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueTest, Serialize) { EXPECT_THAT(UnknownValue().Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueTest, GetTypeUrl) { EXPECT_THAT(UnknownValue().GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueTest, ConvertToAny) { EXPECT_THAT(UnknownValue().ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueTest, ConvertToJson) { EXPECT_THAT(UnknownValue().ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(UnknownValue()), NativeTypeId::For<UnknownValue>()); EXPECT_EQ(NativeTypeId::Of(Value(UnknownValue())), NativeTypeId::For<UnknownValue>()); } TEST_P(UnknownValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<UnknownValue>(UnknownValue())); EXPECT_TRUE(InstanceOf<UnknownValue>(Value(UnknownValue()))); } TEST_P(UnknownValueTest, Cast) { EXPECT_THAT(Cast<UnknownValue>(UnknownValue()), An<UnknownValue>()); EXPECT_THAT(Cast<UnknownValue>(Value(UnknownValue())), An<UnknownValue>()); } TEST_P(UnknownValueTest, As) { EXPECT_THAT(As<UnknownValue>(UnknownValue()), Ne(absl::nullopt)); EXPECT_THAT(As<UnknownValue>(Value(UnknownValue())), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( UnknownValueTest, UnknownValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), UnknownValueTest::ToString); using UnknownValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(UnknownValueViewTest, Kind) { EXPECT_EQ(UnknownValueView().kind(), UnknownValueView::kKind); EXPECT_EQ(ValueView(UnknownValueView()).kind(), UnknownValueView::kKind); } TEST_P(UnknownValueViewTest, DebugString) { { std::ostringstream out; out << UnknownValueView(); EXPECT_EQ(out.str(), ""); } { std::ostringstream out; out << ValueView(UnknownValueView()); EXPECT_EQ(out.str(), ""); } } TEST_P(UnknownValueViewTest, GetSerializedSize) { EXPECT_THAT(UnknownValueView().GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueViewTest, SerializeTo) { absl::Cord value; EXPECT_THAT(UnknownValueView().SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueViewTest, Serialize) { EXPECT_THAT(UnknownValueView().Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueViewTest, GetTypeUrl) { EXPECT_THAT(UnknownValueView().GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueViewTest, ConvertToAny) { EXPECT_THAT(UnknownValueView().ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueViewTest, ConvertToJson) { EXPECT_THAT(UnknownValueView().ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(UnknownValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(UnknownValueView()), NativeTypeId::For<UnknownValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(UnknownValueView())), NativeTypeId::For<UnknownValueView>()); } TEST_P(UnknownValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<UnknownValueView>(UnknownValueView())); EXPECT_TRUE(InstanceOf<UnknownValueView>(ValueView(UnknownValueView()))); } TEST_P(UnknownValueViewTest, Cast) { EXPECT_THAT(Cast<UnknownValueView>(UnknownValueView()), An<UnknownValueView>()); EXPECT_THAT(Cast<UnknownValueView>(ValueView(UnknownValueView())), An<UnknownValueView>()); } TEST_P(UnknownValueViewTest, As) { EXPECT_THAT(As<UnknownValueView>(UnknownValueView()), Ne(absl::nullopt)); EXPECT_THAT(As<UnknownValueView>(ValueView(UnknownValueView())), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( UnknownValueViewTest, UnknownValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), UnknownValueViewTest::ToString); } }
33
cpp
google/cel-cpp
uint_value
common/values/uint_value.cc
common/values/uint_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_UINT_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_UINT_VALUE_H_ #include <cstddef> #include <cstdint> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class UintValue; class UintValueView; class TypeManager; namespace common_internal { struct UintValueBase { static constexpr ValueKind kKind = ValueKind::kUint; constexpr explicit UintValueBase(uint64_t value) noexcept : value(value) {} UintValueBase() = default; UintValueBase(const UintValueBase&) = default; UintValueBase(UintValueBase&&) = default; UintValueBase& operator=(const UintValueBase&) = default; UintValueBase& operator=(UintValueBase&&) = default; constexpr ValueKind kind() const { return kKind; } UintType GetType(TypeManager&) const { return UintType(); } absl::string_view GetTypeName() const { return UintType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue() == 0; } constexpr uint64_t NativeValue() const { return value; } constexpr operator uint64_t() const noexcept { return value; } uint64_t value = 0; }; } class UintValue final : private common_internal::UintValueBase { private: using Base = UintValueBase; public: using view_alternative_type = UintValueView; using Base::kKind; UintValue() = default; UintValue(const UintValue&) = default; UintValue(UintValue&&) = default; UintValue& operator=(const UintValue&) = default; UintValue& operator=(UintValue&&) = default; constexpr explicit UintValue(uint64_t value) noexcept : Base(value) {} constexpr explicit UintValue(UintValueView other) noexcept; using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator uint64_t; friend void swap(UintValue& lhs, UintValue& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class UintValueView; }; template <typename H> H AbslHashValue(H state, UintValue value) { return H::combine(std::move(state), value.NativeValue()); } constexpr bool operator==(UintValue lhs, UintValue rhs) { return lhs.NativeValue() == rhs.NativeValue(); } constexpr bool operator!=(UintValue lhs, UintValue rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, UintValue value) { return out << value.DebugString(); } class UintValueView final : private common_internal::UintValueBase { private: using Base = UintValueBase; public: using alternative_type = UintValue; using Base::kKind; UintValueView() = default; UintValueView(const UintValueView&) = default; UintValueView(UintValueView&&) = default; UintValueView& operator=(const UintValueView&) = default; UintValueView& operator=(UintValueView&&) = default; constexpr explicit UintValueView(uint64_t value) noexcept : Base(value) {} constexpr UintValueView(UintValue other) noexcept : UintValueView(static_cast<uint64_t>(other)) {} using Base::kind; using Base::GetType; using Base::GetTypeName; using Base::DebugString; using Base::GetSerializedSize; using Base::SerializeTo; using Base::Serialize; using Base::GetTypeUrl; using Base::ConvertToAny; using Base::ConvertToJson; using Base::Equal; using Base::IsZeroValue; using Base::NativeValue; using Base::operator uint64_t; friend void swap(UintValueView& lhs, UintValueView& rhs) noexcept { using std::swap; swap(lhs.value, rhs.value); } private: friend class IntValue; }; template <typename H> H AbslHashValue(H state, UintValueView value) { return H::combine(std::move(state), value.NativeValue()); } constexpr bool operator==(UintValueView lhs, UintValueView rhs) { return lhs.NativeValue() == rhs.NativeValue(); } constexpr bool operator!=(UintValueView lhs, UintValueView rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, UintValueView value) { return out << value.DebugString(); } inline constexpr UintValue::UintValue(UintValueView other) noexcept : UintValue(static_cast<uint64_t>(other)) {} } #endif #include <cstddef> #include <cstdint> #include <string> #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 "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/number.h" #include "internal/serialize.h" #include "internal/status_macros.h" namespace cel::common_internal { namespace { std::string UintDebugString(int64_t value) { return absl::StrCat(value, "u"); } } std::string UintValueBase::DebugString() const { return UintDebugString(NativeValue()); } absl::StatusOr<size_t> UintValueBase::GetSerializedSize( AnyToJsonConverter&) const { return internal::SerializedUInt64ValueSize(NativeValue()); } absl::Status UintValueBase::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeUInt64Value(NativeValue(), value); } absl::StatusOr<absl::Cord> UintValueBase::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> UintValueBase::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.UInt64Value"); } absl::StatusOr<Any> UintValueBase::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> UintValueBase::ConvertToJson(AnyToJsonConverter&) const { return JsonUint(NativeValue()); } absl::Status UintValueBase::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<UintValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } if (auto other_value = As<DoubleValueView>(other); other_value.has_value()) { result = BoolValueView{internal::Number::FromUint64(NativeValue()) == internal::Number::FromDouble(other_value->NativeValue())}; return absl::OkStatus(); } if (auto other_value = As<IntValueView>(other); other_value.has_value()) { result = BoolValueView{internal::Number::FromUint64(NativeValue()) == internal::Number::FromInt64(other_value->NativeValue())}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<Value> UintValueBase::Equal(ValueManager& value_manager, ValueView other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } }
#include <cstdint> #include <sstream> #include "absl/hash/hash.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using UintValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(UintValueTest, Kind) { EXPECT_EQ(UintValue(1).kind(), UintValue::kKind); EXPECT_EQ(Value(UintValue(1)).kind(), UintValue::kKind); } TEST_P(UintValueTest, DebugString) { { std::ostringstream out; out << UintValue(1); EXPECT_EQ(out.str(), "1u"); } { std::ostringstream out; out << Value(UintValue(1)); EXPECT_EQ(out.str(), "1u"); } } TEST_P(UintValueTest, GetSerializedSize) { EXPECT_THAT(UintValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(UintValueTest, ConvertToAny) { EXPECT_THAT(UintValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.UInt64Value"), absl::Cord()))); } TEST_P(UintValueTest, ConvertToJson) { EXPECT_THAT(UintValue(1).ConvertToJson(value_manager()), IsOkAndHolds(Json(1.0))); } TEST_P(UintValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(UintValue(1)), NativeTypeId::For<UintValue>()); EXPECT_EQ(NativeTypeId::Of(Value(UintValue(1))), NativeTypeId::For<UintValue>()); } TEST_P(UintValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<UintValue>(UintValue(1))); EXPECT_TRUE(InstanceOf<UintValue>(Value(UintValue(1)))); } TEST_P(UintValueTest, Cast) { EXPECT_THAT(Cast<UintValue>(UintValue(1)), An<UintValue>()); EXPECT_THAT(Cast<UintValue>(Value(UintValue(1))), An<UintValue>()); } TEST_P(UintValueTest, As) { EXPECT_THAT(As<UintValue>(UintValue(1)), Ne(absl::nullopt)); EXPECT_THAT(As<UintValue>(Value(UintValue(1))), Ne(absl::nullopt)); } TEST_P(UintValueTest, HashValue) { EXPECT_EQ(absl::HashOf(UintValue(1)), absl::HashOf(uint64_t{1})); } TEST_P(UintValueTest, Equality) { EXPECT_NE(UintValue(0u), 1u); EXPECT_NE(1u, UintValue(0u)); EXPECT_NE(UintValue(0u), UintValue(1u)); } TEST_P(UintValueTest, LessThan) { EXPECT_LT(UintValue(0), 1); EXPECT_LT(0, UintValue(1)); EXPECT_LT(UintValue(0), UintValue(1)); } INSTANTIATE_TEST_SUITE_P( UintValueTest, UintValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), UintValueTest::ToString); using UintValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(UintValueViewTest, Kind) { EXPECT_EQ(UintValueView(1).kind(), UintValueView::kKind); EXPECT_EQ(ValueView(UintValueView(1)).kind(), UintValueView::kKind); } TEST_P(UintValueViewTest, DebugString) { { std::ostringstream out; out << UintValueView(1); EXPECT_EQ(out.str(), "1u"); } { std::ostringstream out; out << ValueView(UintValueView(1)); EXPECT_EQ(out.str(), "1u"); } } TEST_P(UintValueViewTest, GetSerializedSize) { EXPECT_THAT(UintValueView().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(UintValueViewTest, ConvertToAny) { EXPECT_THAT(UintValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.UInt64Value"), absl::Cord()))); } TEST_P(UintValueViewTest, ConvertToJson) { EXPECT_THAT(UintValueView(1).ConvertToJson(value_manager()), IsOkAndHolds(Json(1.0))); } TEST_P(UintValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(UintValueView(1)), NativeTypeId::For<UintValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(UintValueView(1))), NativeTypeId::For<UintValueView>()); } TEST_P(UintValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<UintValueView>(UintValueView(1))); EXPECT_TRUE(InstanceOf<UintValueView>(ValueView(UintValueView(1)))); } TEST_P(UintValueViewTest, Cast) { EXPECT_THAT(Cast<UintValueView>(UintValueView(1)), An<UintValueView>()); EXPECT_THAT(Cast<UintValueView>(ValueView(UintValueView(1))), An<UintValueView>()); } TEST_P(UintValueViewTest, As) { EXPECT_THAT(As<UintValueView>(UintValueView(1)), Ne(absl::nullopt)); EXPECT_THAT(As<UintValueView>(ValueView(UintValueView(1))), Ne(absl::nullopt)); } TEST_P(UintValueViewTest, HashValue) { EXPECT_EQ(absl::HashOf(UintValueView(1)), absl::HashOf(uint64_t{1})); } TEST_P(UintValueViewTest, Equality) { EXPECT_NE(UintValueView(UintValue(0u)), 1u); EXPECT_NE(1u, UintValueView(0u)); EXPECT_NE(UintValueView(0u), UintValueView(1u)); EXPECT_NE(UintValueView(0u), UintValue(1u)); EXPECT_NE(UintValue(1u), UintValueView(0u)); } TEST_P(UintValueViewTest, LessThan) { EXPECT_LT(UintValueView(0), 1); EXPECT_LT(0, UintValueView(1)); EXPECT_LT(UintValueView(0), UintValueView(1)); EXPECT_LT(UintValueView(0), UintValue(1)); EXPECT_LT(UintValue(0), UintValueView(1)); } INSTANTIATE_TEST_SUITE_P( UintValueViewTest, UintValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), UintValueViewTest::ToString); } }
34
cpp
google/cel-cpp
type_value
common/values/type_value.cc
common/values/type_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_TYPE_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_TYPE_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/json.h" #include "common/native_type.h" #include "common/type.h" #include "common/value_kind.h" namespace cel { class Value; class ValueView; class ValueManager; class TypeValue; class TypeValueView; class TypeManager; class TypeValue final { public: using view_alternative_type = TypeValueView; static constexpr ValueKind kKind = ValueKind::kType; TypeValue(Type value) noexcept : value_(std::move(value)) {} explicit TypeValue(TypeValueView value) noexcept; TypeValue() = default; TypeValue(const TypeValue&) = default; TypeValue(TypeValue&&) = default; TypeValue& operator=(const TypeValue&) = default; TypeValue& operator=(TypeValue&&) = default; constexpr ValueKind kind() const { return kKind; } TypeType GetType(TypeManager&) const { return TypeType(); } absl::string_view GetTypeName() const { return TypeType::kName; } std::string DebugString() const { return value_.DebugString(); } absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return false; } TypeView NativeValue() const { return value_; } void swap(TypeValue& other) noexcept { using std::swap; swap(value_, other.value_); } absl::string_view name() const { return NativeValue().name(); } private: friend class TypeValueView; friend struct NativeTypeTraits<TypeValue>; Type value_; }; inline void swap(TypeValue& lhs, TypeValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const TypeValue& value) { return out << value.DebugString(); } template <> struct NativeTypeTraits<TypeValue> final { static bool SkipDestructor(const TypeValue& value) { return NativeTypeTraits<Type>::SkipDestructor(value.value_); } }; class TypeValueView final { public: using alternative_type = TypeValue; static constexpr ValueKind kKind = TypeValue::kKind; TypeValueView(TypeView value) noexcept : value_(value) {} TypeValueView(const TypeValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : TypeValueView(TypeView(value.value_)) {} TypeValueView() = delete; TypeValueView(const TypeValueView&) = default; TypeValueView(TypeValueView&&) = default; TypeValueView& operator=(const TypeValueView&) = default; TypeValueView& operator=(TypeValueView&&) = default; constexpr ValueKind kind() const { return kKind; } TypeType GetType(TypeManager&) const { return TypeType(); } absl::string_view GetTypeName() const { return TypeType::kName; } std::string DebugString() const { return value_.DebugString(); } absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return false; } TypeView NativeValue() const { return value_; } void swap(TypeValueView& other) noexcept { using std::swap; swap(value_, other.value_); } absl::string_view name() const { return NativeValue().name(); } private: friend class TypeValue; TypeView value_; }; inline void swap(TypeValueView& lhs, TypeValueView& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, TypeValueView value) { return out << value.DebugString(); } inline TypeValue::TypeValue(TypeValueView value) noexcept : value_(value.value_) {} } #endif #include <cstddef> #include <string> #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 "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/type.h" #include "common/value.h" namespace cel { absl::StatusOr<size_t> TypeValue::GetSerializedSize(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::Status TypeValue::SerializeTo(AnyToJsonConverter&, absl::Cord&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<absl::Cord> TypeValue::Serialize(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<std::string> TypeValue::GetTypeUrl(absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Any> TypeValue::ConvertToAny(AnyToJsonConverter&, absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Json> TypeValue::ConvertToJson(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is not convertable to JSON")); } absl::Status TypeValue::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<TypeValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } absl::StatusOr<size_t> TypeValueView::GetSerializedSize( AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::Status TypeValueView::SerializeTo(AnyToJsonConverter&, absl::Cord&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<absl::Cord> TypeValueView::Serialize(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<std::string> TypeValueView::GetTypeUrl(absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Any> TypeValueView::ConvertToAny(AnyToJsonConverter&, absl::string_view) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is unserializable")); } absl::StatusOr<Json> TypeValueView::ConvertToJson(AnyToJsonConverter&) const { return absl::FailedPreconditionError( absl::StrCat(GetTypeName(), " is not convertable to JSON")); } absl::Status TypeValueView::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<TypeValueView>(other); other_value.has_value()) { result = BoolValueView{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } }
#include <sstream> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::StatusIs; using TypeValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(TypeValueTest, Kind) { EXPECT_EQ(TypeValue(AnyType()).kind(), TypeValue::kKind); EXPECT_EQ(Value(TypeValue(AnyType())).kind(), TypeValue::kKind); } TEST_P(TypeValueTest, DebugString) { { std::ostringstream out; out << TypeValue(AnyType()); EXPECT_EQ(out.str(), "google.protobuf.Any"); } { std::ostringstream out; out << Value(TypeValue(AnyType())); EXPECT_EQ(out.str(), "google.protobuf.Any"); } } TEST_P(TypeValueTest, GetSerializedSize) { EXPECT_THAT(TypeValue(AnyType()).GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueTest, SerializeTo) { absl::Cord value; EXPECT_THAT(TypeValue(AnyType()).SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueTest, Serialize) { EXPECT_THAT(TypeValue(AnyType()).Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueTest, GetTypeUrl) { EXPECT_THAT(TypeValue(AnyType()).GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueTest, ConvertToAny) { EXPECT_THAT(TypeValue(AnyType()).ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueTest, ConvertToJson) { EXPECT_THAT(TypeValue(AnyType()).ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(TypeValue(AnyType())), NativeTypeId::For<TypeValue>()); EXPECT_EQ(NativeTypeId::Of(Value(TypeValue(AnyType()))), NativeTypeId::For<TypeValue>()); } TEST_P(TypeValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<TypeValue>(TypeValue(AnyType()))); EXPECT_TRUE(InstanceOf<TypeValue>(Value(TypeValue(AnyType())))); } TEST_P(TypeValueTest, Cast) { EXPECT_THAT(Cast<TypeValue>(TypeValue(AnyType())), An<TypeValue>()); EXPECT_THAT(Cast<TypeValue>(Value(TypeValue(AnyType()))), An<TypeValue>()); } TEST_P(TypeValueTest, As) { EXPECT_THAT(As<TypeValue>(TypeValue(AnyType())), Ne(absl::nullopt)); EXPECT_THAT(As<TypeValue>(Value(TypeValue(AnyType()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( TypeValueTest, TypeValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), TypeValueTest::ToString); using TypeValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(TypeValueViewTest, Kind) { EXPECT_EQ(TypeValueView(AnyTypeView()).kind(), TypeValueView::kKind); EXPECT_EQ(ValueView(TypeValueView(AnyTypeView())).kind(), TypeValueView::kKind); } TEST_P(TypeValueViewTest, DebugString) { { std::ostringstream out; out << TypeValueView(AnyTypeView()); EXPECT_EQ(out.str(), "google.protobuf.Any"); } { std::ostringstream out; out << ValueView(TypeValueView(AnyTypeView())); EXPECT_EQ(out.str(), "google.protobuf.Any"); } } TEST_P(TypeValueViewTest, GetSerializedSize) { EXPECT_THAT(TypeValueView(AnyTypeView()).GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueViewTest, SerializeTo) { absl::Cord value; EXPECT_THAT(TypeValueView(AnyTypeView()).SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueViewTest, Serialize) { EXPECT_THAT(TypeValueView(AnyTypeView()).Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueViewTest, GetTypeUrl) { EXPECT_THAT(TypeValueView(AnyTypeView()).GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueViewTest, ConvertToAny) { EXPECT_THAT(TypeValueView(AnyTypeView()).ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueViewTest, ConvertToJson) { EXPECT_THAT(TypeValueView(AnyTypeView()).ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(TypeValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(TypeValueView(AnyTypeView())), NativeTypeId::For<TypeValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(TypeValueView(AnyTypeView()))), NativeTypeId::For<TypeValueView>()); } TEST_P(TypeValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<TypeValueView>(TypeValueView(AnyTypeView()))); EXPECT_TRUE( InstanceOf<TypeValueView>(ValueView(TypeValueView(AnyTypeView())))); } TEST_P(TypeValueViewTest, Cast) { EXPECT_THAT(Cast<TypeValueView>(TypeValueView(AnyTypeView())), An<TypeValueView>()); EXPECT_THAT(Cast<TypeValueView>(ValueView(TypeValueView(AnyTypeView()))), An<TypeValueView>()); } TEST_P(TypeValueViewTest, As) { EXPECT_THAT(As<TypeValueView>(TypeValueView(AnyTypeView())), Ne(absl::nullopt)); EXPECT_THAT(As<TypeValueView>(ValueView(TypeValueView(AnyTypeView()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( TypeValueViewTest, TypeValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), TypeValueViewTest::ToString); } }
35
cpp
google/cel-cpp
bytes_value
common/values/bytes_value.cc
common/values/bytes_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_BYTES_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_BYTES_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/internal/arena_string.h" #include "common/internal/shared_byte_string.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" #include "common/values/values.h" namespace cel { class Value; class ValueView; class ValueManager; class BytesValue; class BytesValueView; class TypeManager; class BytesValue final { public: using view_alternative_type = BytesValueView; static constexpr ValueKind kKind = ValueKind::kBytes; explicit BytesValue(absl::Cord value) noexcept : value_(std::move(value)) {} explicit BytesValue(absl::string_view value) noexcept : value_(absl::Cord(value)) {} explicit BytesValue(common_internal::ArenaString value) noexcept : value_(value) {} explicit BytesValue(common_internal::SharedByteString value) noexcept : value_(std::move(value)) {} template <typename T, typename = std::enable_if_t<std::is_same_v< absl::remove_cvref_t<T>, std::string>>> explicit BytesValue(T&& data) : value_(absl::Cord(std::forward<T>(data))) {} #if ABSL_HAVE_ATTRIBUTE(enable_if) template <size_t N> explicit BytesValue(const char (&data)[N]) __attribute__((enable_if(::cel::common_internal::IsStringLiteral(data), "chosen when 'data' is a string literal"))) : value_(absl::string_view(data)) {} #endif explicit BytesValue(BytesValueView value) noexcept; BytesValue() = default; BytesValue(const BytesValue&) = default; BytesValue(BytesValue&&) = default; BytesValue& operator=(const BytesValue&) = default; BytesValue& operator=(BytesValue&&) = default; constexpr ValueKind kind() const { return kKind; } BytesType GetType(TypeManager&) const { return BytesType(); } absl::string_view GetTypeName() const { return BytesType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize( AnyToJsonConverter& value_manager) const; absl::Status SerializeTo(AnyToJsonConverter& value_manager, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& value_manager) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue([](const auto& value) -> bool { return value.empty(); }); } std::string NativeString() const { return value_.ToString(); } absl::string_view NativeString( std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return value_.ToString(scratch); } absl::Cord NativeCord() const { return value_.ToCord(); } template <typename Visitor> std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>, std::invoke_result_t<Visitor, const absl::Cord&>> NativeValue(Visitor&& visitor) const { return value_.Visit(std::forward<Visitor>(visitor)); } void swap(BytesValue& other) noexcept { using std::swap; swap(value_, other.value_); } size_t Size() const; bool IsEmpty() const; bool Equals(absl::string_view bytes) const; bool Equals(const absl::Cord& bytes) const; bool Equals(BytesValueView bytes) const; int Compare(absl::string_view bytes) const; int Compare(const absl::Cord& bytes) const; int Compare(BytesValueView bytes) const; std::string ToString() const { return NativeString(); } absl::Cord ToCord() const { return NativeCord(); } private: friend class BytesValueView; friend const common_internal::SharedByteString& common_internal::AsSharedByteString(const BytesValue& value); common_internal::SharedByteString value_; }; inline void swap(BytesValue& lhs, BytesValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const BytesValue& value) { return out << value.DebugString(); } inline bool operator==(const BytesValue& lhs, absl::string_view rhs) { return lhs.Equals(rhs); } inline bool operator==(absl::string_view lhs, const BytesValue& rhs) { return rhs == lhs; } inline bool operator!=(const BytesValue& lhs, absl::string_view rhs) { return !lhs.Equals(rhs); } inline bool operator!=(absl::string_view lhs, const BytesValue& rhs) { return rhs != lhs; } class BytesValueView final { public: using alternative_type = BytesValue; static constexpr ValueKind kKind = BytesValue::kKind; explicit BytesValueView( const absl::Cord& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(value) {} explicit BytesValueView(absl::string_view value) noexcept : value_(value) {} explicit BytesValueView(common_internal::ArenaString value) noexcept : value_(value) {} explicit BytesValueView(common_internal::SharedByteStringView value) noexcept : value_(value) {} BytesValueView(const BytesValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(value.value_) {} BytesValueView& operator=( const BytesValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) { value_ = value.value_; return *this; } BytesValueView& operator=(BytesValue&&) = delete; BytesValueView() = default; BytesValueView(const BytesValueView&) = default; BytesValueView(BytesValueView&&) = default; BytesValueView& operator=(const BytesValueView&) = default; BytesValueView& operator=(BytesValueView&&) = default; constexpr ValueKind kind() const { return kKind; } BytesType GetType(TypeManager&) const { return BytesType(); } absl::string_view GetTypeName() const { return BytesType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue([](const auto& value) -> bool { return value.empty(); }); } std::string NativeString() const { return value_.ToString(); } absl::string_view NativeString( std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return value_.ToString(scratch); } absl::Cord NativeCord() const { return value_.ToCord(); } template <typename Visitor> std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>, std::invoke_result_t<Visitor, const absl::Cord&>> NativeValue(Visitor&& visitor) const { return value_.Visit(std::forward<Visitor>(visitor)); } void swap(BytesValueView& other) noexcept { using std::swap; swap(value_, other.value_); } size_t Size() const; bool IsEmpty() const; bool Equals(absl::string_view bytes) const; bool Equals(const absl::Cord& bytes) const; bool Equals(BytesValueView bytes) const; int Compare(absl::string_view bytes) const; int Compare(const absl::Cord& bytes) const; int Compare(BytesValueView bytes) const; std::string ToString() const { return NativeString(); } absl::Cord ToCord() const { return NativeCord(); } private: friend class BytesValue; friend common_internal::SharedByteStringView common_internal::AsSharedByteStringView(BytesValueView value); common_internal::SharedByteStringView value_; }; inline void swap(BytesValueView& lhs, BytesValueView& rhs) noexcept { lhs.swap(rhs); } inline bool operator==(BytesValueView lhs, absl::string_view rhs) { return lhs.Equals(rhs); } inline bool operator==(absl::string_view lhs, BytesValueView rhs) { return rhs == lhs; } inline bool operator!=(BytesValueView lhs, absl::string_view rhs) { return !lhs.Equals(rhs); } inline bool operator!=(absl::string_view lhs, BytesValueView rhs) { return rhs != lhs; } inline std::ostream& operator<<(std::ostream& out, BytesValueView value) { return out << value.DebugString(); } inline BytesValue::BytesValue(BytesValueView value) noexcept : value_(value.value_) {} namespace common_internal { inline const SharedByteString& AsSharedByteString(const BytesValue& value) { return value.value_; } inline SharedByteStringView AsSharedByteStringView(BytesValueView value) { return value.value_; } } } #endif #include <cstddef> #include <string> #include <utility> #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/serialize.h" #include "internal/status_macros.h" #include "internal/strings.h" namespace cel { namespace { template <typename Bytes> std::string BytesDebugString(const Bytes& value) { return value.NativeValue(absl::Overload( [](absl::string_view string) -> std::string { return internal::FormatBytesLiteral(string); }, [](const absl::Cord& cord) -> std::string { if (auto flat = cord.TryFlat(); flat.has_value()) { return internal::FormatBytesLiteral(*flat); } return internal::FormatBytesLiteral(static_cast<std::string>(cord)); })); } } std::string BytesValue::DebugString() const { return BytesDebugString(*this); } absl::StatusOr<size_t> BytesValue::GetSerializedSize( AnyToJsonConverter&) const { return NativeValue([](const auto& bytes) -> size_t { return internal::SerializedBytesValueSize(bytes); }); } absl::Status BytesValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return NativeValue([&value](const auto& bytes) -> absl::Status { return internal::SerializeBytesValue(bytes, value); }); } absl::StatusOr<absl::Cord> BytesValue::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> BytesValue::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.BytesValue"); } absl::StatusOr<Any> BytesValue::ConvertToAny(AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> BytesValue::ConvertToJson(AnyToJsonConverter&) const { return NativeValue( [](const auto& value) -> Json { return JsonBytes(value); }); } absl::Status BytesValue::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<BytesValueView>(other); other_value.has_value()) { result = NativeValue([other_value](const auto& value) -> BoolValue { return other_value->NativeValue( [&value](const auto& other_value) -> BoolValue { return BoolValue{value == other_value}; }); }); return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } size_t BytesValue::Size() const { return NativeValue( [](const auto& alternative) -> size_t { return alternative.size(); }); } bool BytesValue::IsEmpty() const { return NativeValue( [](const auto& alternative) -> bool { return alternative.empty(); }); } bool BytesValue::Equals(absl::string_view bytes) const { return NativeValue([bytes](const auto& alternative) -> bool { return alternative == bytes; }); } bool BytesValue::Equals(const absl::Cord& bytes) const { return NativeValue([&bytes](const auto& alternative) -> bool { return alternative == bytes; }); } bool BytesValue::Equals(BytesValueView bytes) const { return bytes.NativeValue( [this](const auto& alternative) -> bool { return Equals(alternative); }); } namespace { int CompareImpl(absl::string_view lhs, absl::string_view rhs) { return lhs.compare(rhs); } int CompareImpl(absl::string_view lhs, const absl::Cord& rhs) { return -rhs.Compare(lhs); } int CompareImpl(const absl::Cord& lhs, absl::string_view rhs) { return lhs.Compare(rhs); } int CompareImpl(const absl::Cord& lhs, const absl::Cord& rhs) { return lhs.Compare(rhs); } } int BytesValue::Compare(absl::string_view bytes) const { return NativeValue([bytes](const auto& alternative) -> int { return CompareImpl(alternative, bytes); }); } int BytesValue::Compare(const absl::Cord& bytes) const { return NativeValue([&bytes](const auto& alternative) -> int { return CompareImpl(alternative, bytes); }); } int BytesValue::Compare(BytesValueView bytes) const { return bytes.NativeValue( [this](const auto& alternative) -> int { return Compare(alternative); }); } std::string BytesValueView::DebugString() const { return BytesDebugString(*this); } absl::StatusOr<size_t> BytesValueView::GetSerializedSize( AnyToJsonConverter&) const { return NativeValue([](const auto& bytes) -> size_t { return internal::SerializedBytesValueSize(bytes); }); } absl::Status BytesValueView::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return NativeValue([&value](const auto& bytes) -> absl::Status { return internal::SerializeBytesValue(bytes, value); }); } absl::StatusOr<absl::Cord> BytesValueView::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> BytesValueView::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.BytesValue"); } absl::StatusOr<Any> BytesValueView::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> BytesValueView::ConvertToJson(AnyToJsonConverter&) const { return NativeValue( [](const auto& value) -> Json { return JsonBytes(value); }); } absl::Status BytesValueView::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<BytesValueView>(other); other_value.has_value()) { result = NativeValue([other_value](const auto& value) -> BoolValue { return other_value->NativeValue( [&value](const auto& other_value) -> BoolValue { return BoolValue{value == other_value}; }); }); return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } size_t BytesValueView::Size() const { return NativeValue( [](const auto& alternative) -> size_t { return alternative.size(); }); } bool BytesValueView::IsEmpty() const { return NativeValue( [](const auto& alternative) -> bool { return alternative.empty(); }); } bool BytesValueView::Equals(absl::string_view bytes) const { return NativeValue([bytes](const auto& alternative) -> bool { return alternative == bytes; }); } bool BytesValueView::Equals(const absl::Cord& bytes) const { return NativeValue([&bytes](const auto& alternative) -> bool { return alternative == bytes; }); } bool BytesValueView::Equals(BytesValueView bytes) const { return bytes.NativeValue( [this](const auto& alternative) -> bool { return Equals(alternative); }); } int BytesValueView::Compare(absl::string_view bytes) const { return NativeValue([bytes](const auto& alternative) -> int { return CompareImpl(alternative, bytes); }); } int BytesValueView::Compare(const absl::Cord& bytes) const { return NativeValue([&bytes](const auto& alternative) -> int { return CompareImpl(alternative, bytes); }); } int BytesValueView::Compare(BytesValueView bytes) const { return bytes.NativeValue( [this](const auto& alternative) -> int { return Compare(alternative); }); } }
#include <sstream> #include <string> #include "absl/strings/cord.h" #include "absl/strings/cord_test_helpers.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using BytesValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(BytesValueTest, Kind) { EXPECT_EQ(BytesValue("foo").kind(), BytesValue::kKind); EXPECT_EQ(Value(BytesValue(absl::Cord("foo"))).kind(), BytesValue::kKind); } TEST_P(BytesValueTest, DebugString) { { std::ostringstream out; out << BytesValue("foo"); EXPECT_EQ(out.str(), "b\"foo\""); } { std::ostringstream out; out << BytesValue(absl::MakeFragmentedCord({"f", "o", "o"})); EXPECT_EQ(out.str(), "b\"foo\""); } { std::ostringstream out; out << Value(BytesValue(absl::Cord("foo"))); EXPECT_EQ(out.str(), "b\"foo\""); } } TEST_P(BytesValueTest, GetSerializedSize) { EXPECT_THAT(BytesValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(BytesValueTest, ConvertToAny) { EXPECT_THAT(BytesValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.BytesValue"), absl::Cord()))); } TEST_P(BytesValueTest, ConvertToJson) { EXPECT_THAT(BytesValue("foo").ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonBytes("foo")))); } TEST_P(BytesValueTest, NativeValue) { std::string scratch; EXPECT_EQ(BytesValue("foo").NativeString(), "foo"); EXPECT_EQ(BytesValue("foo").NativeString(scratch), "foo"); EXPECT_EQ(BytesValue("foo").NativeCord(), "foo"); } TEST_P(BytesValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(BytesValue("foo")), NativeTypeId::For<BytesValue>()); EXPECT_EQ(NativeTypeId::Of(Value(BytesValue(absl::Cord("foo")))), NativeTypeId::For<BytesValue>()); } TEST_P(BytesValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<BytesValue>(BytesValue("foo"))); EXPECT_TRUE(InstanceOf<BytesValue>(Value(BytesValue(absl::Cord("foo"))))); } TEST_P(BytesValueTest, Cast) { EXPECT_THAT(Cast<BytesValue>(BytesValue("foo")), An<BytesValue>()); EXPECT_THAT(Cast<BytesValue>(Value(BytesValue(absl::Cord("foo")))), An<BytesValue>()); } TEST_P(BytesValueTest, As) { EXPECT_THAT(As<BytesValue>(BytesValue("foo")), Ne(absl::nullopt)); EXPECT_THAT(As<BytesValue>(Value(BytesValue(absl::Cord("foo")))), Ne(absl::nullopt)); } TEST_P(BytesValueTest, StringViewEquality) { EXPECT_TRUE(BytesValue("foo") == "foo"); EXPECT_FALSE(BytesValue("foo") == "bar"); EXPECT_TRUE("foo" == BytesValue("foo")); EXPECT_FALSE("bar" == BytesValue("foo")); } TEST_P(BytesValueTest, StringViewInequality) { EXPECT_FALSE(BytesValue("foo") != "foo"); EXPECT_TRUE(BytesValue("foo") != "bar"); EXPECT_FALSE("foo" != BytesValue("foo")); EXPECT_TRUE("bar" != BytesValue("foo")); } INSTANTIATE_TEST_SUITE_P( BytesValueTest, BytesValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), BytesValueTest::ToString); using BytesValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(BytesValueViewTest, Kind) { EXPECT_EQ(BytesValueView("foo").kind(), BytesValueView::kKind); EXPECT_EQ(ValueView(BytesValueView("foo")).kind(), BytesValueView::kKind); } TEST_P(BytesValueViewTest, DebugString) { { std::ostringstream out; out << BytesValueView("foo"); EXPECT_EQ(out.str(), "b\"foo\""); } { std::ostringstream out; out << ValueView(BytesValueView("foo")); EXPECT_EQ(out.str(), "b\"foo\""); } } TEST_P(BytesValueViewTest, GetSerializedSize) { EXPECT_THAT(BytesValueView().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(BytesValueViewTest, ConvertToAny) { EXPECT_THAT(BytesValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.BytesValue"), absl::Cord()))); } TEST_P(BytesValueViewTest, ConvertToJson) { EXPECT_THAT(BytesValueView("foo").ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonBytes("foo")))); } TEST_P(BytesValueViewTest, StringViewEquality) { EXPECT_TRUE(BytesValueView("foo") == "foo"); EXPECT_FALSE(BytesValueView("foo") == "bar"); EXPECT_TRUE("foo" == BytesValueView("foo")); EXPECT_FALSE("bar" == BytesValueView("foo")); } TEST_P(BytesValueViewTest, StringViewInequality) { EXPECT_FALSE(BytesValueView("foo") != "foo"); EXPECT_TRUE(BytesValueView("foo") != "bar"); EXPECT_FALSE("foo" != BytesValueView("foo")); EXPECT_TRUE("bar" != BytesValueView("foo")); } TEST_P(BytesValueViewTest, NativeValue) { std::string scratch; EXPECT_EQ(BytesValueView(BytesValue("foo")).NativeString(), "foo"); EXPECT_EQ(BytesValueView(BytesValue("foo")).NativeString(scratch), "foo"); EXPECT_EQ(BytesValueView(BytesValue("foo")).NativeCord(), "foo"); } TEST_P(BytesValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(BytesValueView("foo")), NativeTypeId::For<BytesValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(BytesValueView("foo"))), NativeTypeId::For<BytesValueView>()); } TEST_P(BytesValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<BytesValueView>(BytesValueView("foo"))); EXPECT_TRUE(InstanceOf<BytesValueView>(ValueView(BytesValueView("foo")))); } TEST_P(BytesValueViewTest, Cast) { EXPECT_THAT(Cast<BytesValueView>(BytesValueView("foo")), An<BytesValueView>()); EXPECT_THAT(Cast<BytesValueView>(ValueView(BytesValueView("foo"))), An<BytesValueView>()); } TEST_P(BytesValueViewTest, As) { EXPECT_THAT(As<BytesValueView>(BytesValueView("foo")), Ne(absl::nullopt)); EXPECT_THAT(As<BytesValueView>(ValueView(BytesValueView("foo"))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( BytesValueViewTest, BytesValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), BytesValueViewTest::ToString); } }
36
cpp
google/cel-cpp
map_value
common/values/map_value.cc
common/values/map_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_MAP_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_MAP_VALUE_H_ #include <cstddef> #include <memory> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/log/absl_check.h" #include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/type.h" #include "common/value_kind.h" #include "common/values/legacy_map_value.h" #include "common/values/map_value_interface.h" #include "common/values/parsed_map_value.h" #include "common/values/values.h" namespace cel { class MapValueInterface; class MapValue; class MapValueView; class Value; class ValueView; class ValueManager; class TypeManager; absl::Status CheckMapKey(ValueView key); bool Is(MapValueView lhs, MapValueView rhs); class MapValue final { public: using interface_type = MapValueInterface; using view_alternative_type = MapValueView; static constexpr ValueKind kKind = MapValueInterface::kKind; template <typename T, typename = std::enable_if_t<common_internal::IsMapValueAlternativeV< absl::remove_cvref_t<T>>>> MapValue(const T& value) : variant_( absl::in_place_type<common_internal::BaseMapValueAlternativeForT< absl::remove_cvref_t<T>>>, value) {} template <typename T, typename = std::enable_if_t<common_internal::IsMapValueAlternativeV< absl::remove_cvref_t<T>>>> MapValue(T&& value) : variant_( absl::in_place_type<common_internal::BaseMapValueAlternativeForT< absl::remove_cvref_t<T>>>, std::forward<T>(value)) {} explicit MapValue(MapValueView value); template < typename T, typename = std::enable_if_t< common_internal::IsMapValueViewAlternativeV<absl::remove_cvref_t<T>>>> explicit MapValue(T value) : variant_( absl::in_place_type<common_internal::BaseMapValueAlternativeForT< absl::remove_cvref_t<T>>>, value) {} MapValue() = default; MapValue(const MapValue& other) : variant_(other.variant_) {} MapValue(MapValue&& other) noexcept : variant_(std::move(other.variant_)) {} MapValue& operator=(const MapValue& other) { ABSL_DCHECK(this != std::addressof(other)) << "MapValue should not be copied to itself"; variant_ = other.variant_; return *this; } MapValue& operator=(MapValue&& other) noexcept { ABSL_DCHECK(this != std::addressof(other)) << "MapValue should not be moved to itself"; variant_ = std::move(other.variant_); other.variant_.emplace<ParsedMapValue>(); return *this; } constexpr ValueKind kind() const { return kKind; } MapType GetType(TypeManager& type_manager) const; absl::string_view GetTypeName() const; std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter& converter) const; absl::Status SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& converter) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& converter, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& converter) const; absl::StatusOr<JsonObject> ConvertToJsonObject( AnyToJsonConverter& converter) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const; void swap(MapValue& other) noexcept { variant_.swap(other.variant_); } absl::StatusOr<bool> IsEmpty() const; absl::StatusOr<size_t> Size() const; absl::Status Get(ValueManager& value_manager, ValueView key, Value& result) const; absl::StatusOr<Value> Get(ValueManager& value_manager, ValueView key) const; absl::StatusOr<bool> Find(ValueManager& value_manager, ValueView key, Value& result) const; absl::StatusOr<std::pair<Value, bool>> Find(ValueManager& value_manager, ValueView key) const; absl::Status Has(ValueManager& value_manager, ValueView key, Value& result) const; absl::StatusOr<Value> Has(ValueManager& value_manager, ValueView key) const; absl::Status ListKeys(ValueManager& value_manager, ListValue& result) const; absl::StatusOr<ListValue> ListKeys(ValueManager& value_manager) const; using ForEachCallback = typename MapValueInterface::ForEachCallback; absl::Status ForEach(ValueManager& value_manager, ForEachCallback callback) const; absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager& value_manager) const; private: friend class MapValueView; friend struct NativeTypeTraits<MapValue>; friend struct CompositionTraits<MapValue>; common_internal::MapValueViewVariant ToViewVariant() const; common_internal::MapValueVariant variant_; }; inline void swap(MapValue& lhs, MapValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const MapValue& value) { return out << value.DebugString(); } template <> struct NativeTypeTraits<MapValue> final { static NativeTypeId Id(const MapValue& value) { return absl::visit( [](const auto& alternative) -> NativeTypeId { return NativeTypeId::Of(alternative); }, value.variant_); } static bool SkipDestructor(const MapValue& value) { return absl::visit( [](const auto& alternative) -> bool { return NativeType::SkipDestructor(alternative); }, value.variant_); } }; template <> struct CompositionTraits<MapValue> final { template <typename U> static std::enable_if_t<common_internal::IsMapValueAlternativeV<U>, bool> HasA(const MapValue& value) { using Base = common_internal::BaseMapValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::holds_alternative<U>(value.variant_); } else { return absl::holds_alternative<Base>(value.variant_) && InstanceOf<U>(Get<U>(value)); } } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, bool> HasA( const MapValue& value) { return true; } template <typename U> static std::enable_if_t<common_internal::IsMapValueAlternativeV<U>, const U&> Get(const MapValue& value) { using Base = common_internal::BaseMapValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(value.variant_); } else { return Cast<U>(absl::get<Base>(value.variant_)); } } template <typename U> static std::enable_if_t<common_internal::IsMapValueAlternativeV<U>, U&> Get( MapValue& value) { using Base = common_internal::BaseMapValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(value.variant_); } else { return Cast<U>(absl::get<Base>(value.variant_)); } } template <typename U> static std::enable_if_t<common_internal::IsMapValueAlternativeV<U>, U> Get( const MapValue&& value) { using Base = common_internal::BaseMapValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(std::move(value.variant_)); } else { return Cast<U>(absl::get<Base>(std::move(value.variant_))); } } template <typename U> static std::enable_if_t<common_internal::IsMapValueAlternativeV<U>, U> Get( MapValue&& value) { using Base = common_internal::BaseMapValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(std::move(value.variant_)); } else { return Cast<U>(absl::get<Base>(std::move(value.variant_))); } } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get( const MapValue& value) { return absl::visit( [](const auto& alternative) -> U { return U{alternative}; }, value.variant_); } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get(MapValue& value) { return absl::visit( [](const auto& alternative) -> U { return U{alternative}; }, value.variant_); } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get( const MapValue&& value) { return absl::visit( [](const auto& alternative) -> U { return U{alternative}; }, value.variant_); } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get(MapValue&& value) { return absl::visit( [](auto&& alternative) -> U { return U{std::move(alternative)}; }, std::move(value.variant_)); } }; template <typename To, typename From> struct CastTraits< To, From, std::enable_if_t<std::is_same_v<MapValue, absl::remove_cvref_t<From>>>> : CompositionCastTraits<To, From> {}; class MapValueView final { public: using interface_type = MapValueInterface; using alternative_type = MapValue; static constexpr ValueKind kKind = MapValue::kKind; template <typename T, typename = std::enable_if_t< common_internal::IsMapValueViewAlternativeV<T>>> MapValueView(T value) : variant_(absl::in_place_type< common_internal::BaseMapValueViewAlternativeForT<T>>, value) {} MapValueView(const MapValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) : variant_(value.ToViewVariant()) {} template <typename T, typename = std::enable_if_t< common_internal::IsMapValueAlternativeV<T>>> MapValueView(const T& value ABSL_ATTRIBUTE_LIFETIME_BOUND) : variant_(absl::in_place_type< common_internal::BaseMapValueViewAlternativeForT<T>>, value) {} MapValueView& operator=(MapValue&&) = delete; template <typename T, typename = std::enable_if_t<common_internal::IsMapValueAlternativeV< absl::remove_cvref_t<T>>>> MapValueView& operator=(T&&) = delete; MapValueView() = default; MapValueView(const MapValueView&) = default; MapValueView& operator=(const MapValueView&) = default; constexpr ValueKind kind() const { return kKind; } MapType GetType(TypeManager& type_manager) const; absl::string_view GetTypeName() const; std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter& converter) const; absl::Status SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& converter) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& converter, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& converter) const; absl::StatusOr<JsonObject> ConvertToJsonObject( AnyToJsonConverter& converter) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const; void swap(MapValueView& other) noexcept { variant_.swap(other.variant_); } absl::StatusOr<bool> IsEmpty() const; absl::StatusOr<size_t> Size() const; absl::Status Get(ValueManager& value_manager, ValueView key, Value& result) const; absl::StatusOr<Value> Get(ValueManager& value_manager, ValueView key) const; absl::StatusOr<bool> Find(ValueManager& value_manager, ValueView key, Value& result) const; absl::StatusOr<std::pair<Value, bool>> Find(ValueManager& value_manager, ValueView key) const; absl::Status Has(ValueManager& value_manager, ValueView key, Value& result) const; absl::StatusOr<Value> Has(ValueManager& value_manager, ValueView key) const; absl::Status ListKeys(ValueManager& value_manager, ListValue& result) const; absl::StatusOr<ListValue> ListKeys(ValueManager& value_manager) const; using ForEachCallback = typename MapValueInterface::ForEachCallback; absl::Status ForEach(ValueManager& value_manager, ForEachCallback callback) const; absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager& value_manager) const; private: friend class MapValue; friend struct NativeTypeTraits<MapValueView>; friend struct CompositionTraits<MapValueView>; friend bool Is(MapValueView lhs, MapValueView rhs); common_internal::MapValueVariant ToVariant() const; common_internal::MapValueViewVariant variant_; }; inline void swap(MapValueView& lhs, MapValueView& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, MapValueView value) { return out << value.DebugString(); } template <> struct NativeTypeTraits<MapValueView> final { static NativeTypeId Id(MapValueView value) { return absl::visit( [](const auto& alternative) -> NativeTypeId { return NativeTypeId::Of(alternative); }, value.variant_); } }; template <> struct CompositionTraits<MapValueView> final { template <typename U> static std::enable_if_t<common_internal::IsMapValueViewAlternativeV<U>, bool> HasA(MapValueView value) { using Base = common_internal::BaseMapValueViewAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::holds_alternative<U>(value.variant_); } else { return InstanceOf<U>(Get<Base>(value)); } } template <typename U> static std::enable_if_t<std::is_same_v<ValueView, U>, bool> HasA( MapValueView value) { return true; } template <typename U> static std::enable_if_t<common_internal::IsMapValueViewAlternativeV<U>, U> Get(MapValueView value) { using Base = common_internal::BaseMapValueViewAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(value.variant_); } else { return Cast<U>(absl::get<Base>(value.variant_)); } } template <typename U> static std::enable_if_t<std::is_same_v<ValueView, U>, U> Get( MapValueView value) { return absl::visit([](auto alternative) -> U { return U{alternative}; }, value.variant_); } }; template <typename To, typename From> struct CastTraits< To, From, std::enable_if_t<std::is_same_v<MapValueView, absl::remove_cvref_t<From>>>> : CompositionCastTraits<To, From> {}; inline MapValue::MapValue(MapValueView value) : variant_(value.ToVariant()) {} inline bool Is(MapValueView lhs, MapValueView rhs) { return absl::visit( [](auto alternative_lhs, auto alternative_rhs) -> bool { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative_lhs)>, absl::remove_cvref_t<decltype(alternative_rhs)>>) { return cel::Is(alternative_lhs, alternative_rhs); } else { return false; } }, lhs.variant_, rhs.variant_); } class MapValueBuilder { public: virtual ~MapValueBuilder() = default; virtual absl::Status Put(Value key, Value value) = 0; virtual bool IsEmpty() const { return Size() == 0; } virtual size_t Size() const = 0; virtual void Reserve(size_t capacity) {} virtual MapValue Build() && = 0; }; } #endif #include <cstddef> #include <tuple> #include "absl/base/attributes.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common/casting.h" #include "common/type.h" #include "common/value.h" #include "common/value_kind.h" #include "internal/status_macros.h" namespace cel { namespace { absl::Status InvalidMapKeyTypeError(ValueKind kind) { return absl::InvalidArgumentError( absl::StrCat("Invalid map key type: '", ValueKindToString(kind), "'")); } } MapType MapValue::GetType(TypeManager& type_manager) const { return absl::visit( [&type_manager](const auto& alternative) -> MapType { return alternative.GetType(type_manager); }, variant_); } absl::string_view MapValue::GetTypeName() const { return absl::visit( [](const auto& alternative) -> absl::string_view { return alternative.GetTypeName(); }, variant_); } std::string MapValue::DebugString() const { return absl::visit( [](const auto& alternative) -> std::string { return alternative.DebugString(); }, variant_); } absl::StatusOr<size_t> MapValue::GetSerializedSize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<size_t> { return alternative.GetSerializedSize(converter); }, variant_); } absl::Status MapValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::visit( [&converter, &value](const auto& alternative) -> absl::Status { return alternative.SerializeTo(converter, value); }, variant_); } absl::StatusOr<absl::Cord> MapValue::Serialize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<absl::Cord> { return alternative.Serialize(converter); }, variant_); } absl::StatusOr<std::string> MapValue::GetTypeUrl( absl::string_view prefix) const { return absl::visit( [prefix](const auto& alternative) -> absl::StatusOr<std::string> { return alternative.GetTypeUrl(prefix); }, variant_); } absl::StatusOr<Any> MapValue::ConvertToAny(AnyToJsonConverter& converter, absl::string_view prefix) const { return absl::visit( [&converter, prefix](const auto& alternative) -> absl::StatusOr<Any> { return alternative.ConvertToAny(converter, prefix); }, variant_); } absl::StatusOr<Json> MapValue::ConvertToJson( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<Json> { return alternative.ConvertToJson(converter); }, variant_); } absl::StatusOr<JsonObject> MapValue::ConvertToJsonObject( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<JsonObject> { return alternative.ConvertToJsonObject(converter); }, variant_); } bool MapValue::IsZeroValue() const { return absl::visit( [](const auto& alternative) -> bool { return alternative.IsZeroValue(); }, variant_); } absl::StatusOr<bool> MapValue::IsEmpty() const { return absl::visit( [](const auto& alternative) -> bool { return alternative.IsEmpty(); }, variant_); } absl::StatusOr<size_t> MapValue::Size() const { return absl::visit( [](const auto& alternative) -> size_t { return alternative.Size(); }, variant_); } common_internal::MapValueViewVariant MapValue::ToViewVariant() const { return absl::visit( [](const auto& alternative) -> common_internal::MapValueViewVariant { return common_internal::MapValueViewVariant{ absl::in_place_type<typename absl::remove_cvref_t< decltype(alternative)>::view_alternative_type>, alternative}; }, variant_); } MapType MapValueView::GetType(TypeManager& type_manager) const { return absl::visit( [&type_manager](auto alternative) -> MapType { return alternative.GetType(type_manager); }, variant_); } absl::string_view MapValueView::GetTypeName() const { return absl::visit( [](auto alternative) -> absl::string_view { return alternative.GetTypeName(); }, variant_); } std::string MapValueView::DebugString() const { return absl::visit( [](auto alternative) -> std::string { return alternative.DebugString(); }, variant_); } absl::StatusOr<size_t> MapValueView::GetSerializedSize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<size_t> { return alternative.GetSerializedSize(converter); }, variant_); } absl::Status MapValueView::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::visit( [&converter, &value](auto alternative) -> absl::Status { return alternative.SerializeTo(converter, value); }, variant_); } absl::StatusOr<absl::Cord> MapValueView::Serialize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<absl::Cord> { return alternative.Serialize(converter); }, variant_); } absl::StatusOr<std::string> MapValueView::GetTypeUrl( absl::string_view prefix) const { return absl::visit( [prefix](auto alternative) -> absl::StatusOr<std::string> { return alternative.GetTypeUrl(prefix); }, variant_); } absl::StatusOr<Any> MapValueView::ConvertToAny(AnyToJsonConverter& converter, absl::string_view prefix) const { return absl::visit( [&converter, prefix](auto alternative) -> absl::StatusOr<Any> { return alternative.ConvertToAny(converter, prefix); }, variant_); } absl::StatusOr<Json> MapValueView::ConvertToJson( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<Json> { return alternative.ConvertToJson(converter); }, variant_); } absl::StatusOr<JsonObject> MapValueView::ConvertToJsonObject( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<JsonObject> { return alternative.ConvertToJsonObject(converter); }, variant_); } bool MapValueView::IsZeroValue() const { return absl::visit( [](auto alternative) -> bool { return alternative.IsZeroValue(); }, variant_); } absl::StatusOr<bool> MapValueView::IsEmpty() const { return absl::visit( [](auto alternative) -> bool { return alternative.IsEmpty(); }, variant_); } absl::StatusOr<size_t> MapValueView::Size() const { return absl::visit( [](auto alternative) -> size_t { return alternative.Size(); }, variant_); } common_internal::MapValueVariant MapValueView::ToVariant() const { return absl::visit( [](auto alternative) -> common_internal::MapValueVariant { return common_internal::MapValueVariant{ absl::in_place_type<typename absl::remove_cvref_t< decltype(alternative)>::alternative_type>, alternative}; }, variant_); } namespace common_internal { absl::Status MapValueEqual(ValueManager& value_manager, MapValueView lhs, MapValueView rhs, Value& result) { if (Is(lhs, rhs)) { result = BoolValueView{true}; return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(auto lhs_size, lhs.Size()); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { result = BoolValueView{false}; return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(auto lhs_iterator, lhs.NewIterator(value_manager)); Value lhs_key; Value lhs_value; Value rhs_value; for (size_t index = 0; index < lhs_size; ++index) { ABSL_CHECK(lhs_iterator->HasNext()); CEL_RETURN_IF_ERROR(lhs_iterator->Next(value_manager, lhs_key)); bool rhs_value_found; CEL_ASSIGN_OR_RETURN(rhs_value_found, rhs.Find(value_manager, lhs_key, rhs_value)); if (!rhs_value_found) { result = BoolValueView{false}; return absl::OkStatus(); } CEL_RETURN_IF_ERROR(lhs.Get(value_manager, lhs_key, lhs_value)); CEL_RETURN_IF_ERROR(lhs_value.Equal(value_manager, rhs_value, result)); if (auto bool_value = As<BoolValue>(result); bool_value.has_value() && !bool_value->NativeValue()) { return absl::OkStatus(); } } ABSL_DCHECK(!lhs_iterator->HasNext()); result = BoolValueView{true}; return absl::OkStatus(); } absl::Status MapValueEqual(ValueManager& value_manager, const ParsedMapValueInterface& lhs, MapValueView rhs, Value& result) { auto lhs_size = lhs.Size(); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { result = BoolValueView{false}; return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(auto lhs_iterator, lhs.NewIterator(value_manager)); Value lhs_key; Value lhs_value; Value rhs_value; for (size_t index = 0; index < lhs_size; ++index) { ABSL_CHECK(lhs_iterator->HasNext()); CEL_RETURN_IF_ERROR(lhs_iterator->Next(value_manager, lhs_key)); bool rhs_value_found; CEL_ASSIGN_OR_RETURN(rhs_value_found, rhs.Find(value_manager, lhs_key, rhs_value)); if (!rhs_value_found) { result = BoolValueView{false}; return absl::OkStatus(); } CEL_RETURN_IF_ERROR(lhs.Get(value_manager, lhs_key, lhs_value)); CEL_RETURN_IF_ERROR(lhs_value.Equal(value_manager, rhs_value, result)); if (auto bool_value = As<BoolValue>(result); bool_value.has_value() && !bool_value->NativeValue()) { return absl::OkStatus(); } } ABSL_DCHECK(!lhs_iterator->HasNext()); result = BoolValueView{true}; return absl::OkStatus(); } } absl::Status CheckMapKey(ValueView key) { switch (key.kind()) { case ValueKind::kBool: ABSL_FALLTHROUGH_INTENDED; case ValueKind::kInt: ABSL_FALLTHROUGH_INTENDED; case ValueKind::kUint: ABSL_FALLTHROUGH_INTENDED; case ValueKind::kString: return absl::OkStatus(); default: return InvalidMapKeyTypeError(key.kind()); } } }
#include <cstdint> #include <memory> #include <sstream> #include <tuple> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/memory.h" #include "common/type.h" #include "common/type_factory.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/status_macros.h" #include "internal/testing.h" namespace cel { namespace { using testing::TestParamInfo; using testing::UnorderedElementsAreArray; using cel::internal::IsOk; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; TEST(MapValue, CheckKey) { EXPECT_THAT(CheckMapKey(BoolValueView()), IsOk()); EXPECT_THAT(CheckMapKey(IntValueView()), IsOk()); EXPECT_THAT(CheckMapKey(UintValueView()), IsOk()); EXPECT_THAT(CheckMapKey(StringValueView()), IsOk()); EXPECT_THAT(CheckMapKey(BytesValueView()), StatusIs(absl::StatusCode::kInvalidArgument)); } class MapValueTest : public common_internal::ThreadCompatibleValueTest<> { public: template <typename... Args> absl::StatusOr<MapValue> NewIntDoubleMapValue(Args&&... args) { CEL_ASSIGN_OR_RETURN(auto builder, value_manager().NewMapValueBuilder( GetIntDoubleMapType())); (static_cast<void>(builder->Put(std::forward<Args>(args).first, std::forward<Args>(args).second)), ...); return std::move(*builder).Build(); } template <typename... Args> absl::StatusOr<MapValue> NewJsonMapValue(Args&&... args) { CEL_ASSIGN_OR_RETURN(auto builder, value_manager().NewMapValueBuilder( type_factory().GetJsonMapType())); (static_cast<void>(builder->Put(std::forward<Args>(args).first, std::forward<Args>(args).second)), ...); return std::move(*builder).Build(); } ListType GetIntListType() { return type_factory().CreateListType(IntTypeView()); } MapType GetIntDoubleMapType() { return type_factory().CreateMapType(IntTypeView(), DoubleTypeView()); } }; TEST_P(MapValueTest, Default) { MapValue map_value; EXPECT_THAT(map_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(map_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(map_value.DebugString(), "{}"); EXPECT_EQ(map_value.GetType(type_manager()).key(), DynType()); EXPECT_EQ(map_value.GetType(type_manager()).value(), DynType()); ASSERT_OK_AND_ASSIGN(auto list_value, map_value.ListKeys(value_manager())); EXPECT_THAT(list_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(list_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(list_value.DebugString(), "[]"); EXPECT_EQ(list_value.GetType(type_manager()).element(), DynType()); ASSERT_OK_AND_ASSIGN(auto iterator, map_value.NewIterator(value_manager())); EXPECT_FALSE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(MapValueTest, Kind) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_EQ(value.kind(), MapValue::kKind); EXPECT_EQ(Value(value).kind(), MapValue::kKind); } TEST_P(MapValueTest, Type) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_EQ(value.GetType(type_manager()), GetIntDoubleMapType()); EXPECT_EQ(Value(value).GetType(type_manager()), GetIntDoubleMapType()); } TEST_P(MapValueTest, DebugString) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); { std::ostringstream out; out << value; EXPECT_EQ(out.str(), "{0: 3.0, 1: 4.0, 2: 5.0}"); } { std::ostringstream out; out << Value(value); EXPECT_EQ(out.str(), "{0: 3.0, 1: 4.0, 2: 5.0}"); } } TEST_P(MapValueTest, IsEmpty) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_THAT(value.IsEmpty(), IsOkAndHolds(false)); } TEST_P(MapValueTest, Size) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_THAT(value.Size(), IsOkAndHolds(3)); } TEST_P(MapValueTest, Get) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto value, map_value.Get(value_manager(), IntValueView(0))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 3.0); ASSERT_OK_AND_ASSIGN(value, map_value.Get(value_manager(), IntValueView(1))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 4.0); ASSERT_OK_AND_ASSIGN(value, map_value.Get(value_manager(), IntValueView(2))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 5.0); EXPECT_THAT(map_value.Get(value_manager(), IntValueView(3)), StatusIs(absl::StatusCode::kNotFound)); } TEST_P(MapValueTest, Find) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); Value value; bool ok; ASSERT_OK_AND_ASSIGN(std::tie(value, ok), map_value.Find(value_manager(), IntValueView(0))); ASSERT_TRUE(ok); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 3.0); ASSERT_OK_AND_ASSIGN(std::tie(value, ok), map_value.Find(value_manager(), IntValueView(1))); ASSERT_TRUE(ok); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 4.0); ASSERT_OK_AND_ASSIGN(std::tie(value, ok), map_value.Find(value_manager(), IntValueView(2))); ASSERT_TRUE(ok); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 5.0); ASSERT_OK_AND_ASSIGN(std::tie(value, ok), map_value.Find(value_manager(), IntValueView(3))); ASSERT_FALSE(ok); } TEST_P(MapValueTest, Has) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto value, map_value.Has(value_manager(), IntValueView(0))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN(value, map_value.Has(value_manager(), IntValueView(1))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN(value, map_value.Has(value_manager(), IntValueView(2))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN(value, map_value.Has(value_manager(), IntValueView(3))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_FALSE(Cast<BoolValue>(value).NativeValue()); } TEST_P(MapValueTest, ListKeys) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto list_keys, map_value.ListKeys(value_manager())); std::vector<int64_t> keys; ASSERT_OK( list_keys.ForEach(value_manager(), [&keys](ValueView element) -> bool { keys.push_back(Cast<IntValueView>(element).NativeValue()); return true; })); EXPECT_THAT(keys, UnorderedElementsAreArray({0, 1, 2})); } TEST_P(MapValueTest, ForEach) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); std::vector<std::pair<int64_t, double>> entries; EXPECT_OK(value.ForEach(value_manager(), [&entries](ValueView key, ValueView value) { entries.push_back(std::pair{Cast<IntValueView>(key).NativeValue(), Cast<DoubleValueView>(value).NativeValue()}); return true; })); EXPECT_THAT(entries, UnorderedElementsAreArray( {std::pair{0, 3.0}, std::pair{1, 4.0}, std::pair{2, 5.0}})); } TEST_P(MapValueTest, NewIterator) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto iterator, value.NewIterator(value_manager())); std::vector<int64_t> keys; while (iterator->HasNext()) { ASSERT_OK_AND_ASSIGN(auto element, iterator->Next(value_manager())); ASSERT_TRUE(InstanceOf<IntValue>(element)); keys.push_back(Cast<IntValue>(element).NativeValue()); } EXPECT_EQ(iterator->HasNext(), false); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(keys, UnorderedElementsAreArray({0, 1, 2})); } TEST_P(MapValueTest, GetSerializedSize) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_THAT(value.GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(MapValueTest, ConvertToAny) { ASSERT_OK_AND_ASSIGN(auto value, NewIntDoubleMapValue()); EXPECT_THAT(value.ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Struct"), absl::Cord()))); } TEST_P(MapValueTest, ConvertToJson) { ASSERT_OK_AND_ASSIGN( auto value, NewJsonMapValue(std::pair{StringValue("0"), DoubleValue(3.0)}, std::pair{StringValue("1"), DoubleValue(4.0)}, std::pair{StringValue("2"), DoubleValue(5.0)})); EXPECT_THAT(value.ConvertToJson(value_manager()), IsOkAndHolds(Json(MakeJsonObject({{JsonString("0"), 3.0}, {JsonString("1"), 4.0}, {JsonString("2"), 5.0}})))); } INSTANTIATE_TEST_SUITE_P( MapValueTest, MapValueTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), MapValueTest::ToString); class MapValueViewTest : public common_internal::ThreadCompatibleValueTest<> { public: template <typename... Args> absl::StatusOr<MapValue> NewIntDoubleMapValue(Args&&... args) { CEL_ASSIGN_OR_RETURN(auto builder, value_manager().NewMapValueBuilder( GetIntDoubleMapType())); (static_cast<void>(builder->Put(std::forward<Args>(args).first, std::forward<Args>(args).second)), ...); return std::move(*builder).Build(); } template <typename... Args> absl::StatusOr<MapValue> NewJsonMapValue(Args&&... args) { CEL_ASSIGN_OR_RETURN(auto builder, value_manager().NewMapValueBuilder( type_factory().GetJsonMapType())); (static_cast<void>(builder->Put(std::forward<Args>(args).first, std::forward<Args>(args).second)), ...); return std::move(*builder).Build(); } ListType GetIntListType() { return type_factory().CreateListType(IntTypeView()); } MapType GetIntDoubleMapType() { return type_factory().CreateMapType(IntTypeView(), DoubleTypeView()); } }; TEST_P(MapValueViewTest, Default) { MapValueView map_value; EXPECT_THAT(map_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(map_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(map_value.DebugString(), "{}"); EXPECT_EQ(map_value.GetType(type_manager()).key(), DynType()); EXPECT_EQ(map_value.GetType(type_manager()).value(), DynType()); ASSERT_OK_AND_ASSIGN(auto list_value, map_value.ListKeys(value_manager())); EXPECT_THAT(list_value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(list_value.Size(), IsOkAndHolds(0)); EXPECT_EQ(list_value.DebugString(), "[]"); EXPECT_EQ(list_value.GetType(type_manager()).element(), DynType()); ASSERT_OK_AND_ASSIGN(auto iterator, map_value.NewIterator(value_manager())); EXPECT_FALSE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(MapValueViewTest, Kind) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_EQ(MapValueView(value).kind(), MapValue::kKind); EXPECT_EQ(ValueView(MapValueView(value)).kind(), MapValue::kKind); } TEST_P(MapValueViewTest, Type) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_EQ(MapValueView(value).GetType(type_manager()), GetIntDoubleMapType()); EXPECT_EQ(ValueView(MapValueView(value)).GetType(type_manager()), GetIntDoubleMapType()); } TEST_P(MapValueViewTest, DebugString) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); { std::ostringstream out; out << MapValueView(value); EXPECT_EQ(out.str(), "{0: 3.0, 1: 4.0, 2: 5.0}"); } { std::ostringstream out; out << ValueView(MapValueView(value)); EXPECT_EQ(out.str(), "{0: 3.0, 1: 4.0, 2: 5.0}"); } } TEST_P(MapValueViewTest, IsEmpty) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_THAT(MapValueView(value).IsEmpty(), IsOkAndHolds(false)); } TEST_P(MapValueViewTest, Size) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_THAT(MapValueView(value).Size(), IsOkAndHolds(3)); } TEST_P(MapValueViewTest, Get) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto value, MapValueView(map_value).Get( value_manager(), IntValueView(0))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 3.0); ASSERT_OK_AND_ASSIGN( value, MapValueView(map_value).Get(value_manager(), IntValueView(1))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 4.0); ASSERT_OK_AND_ASSIGN( value, MapValueView(map_value).Get(value_manager(), IntValueView(2))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 5.0); EXPECT_THAT(MapValueView(map_value).Get(value_manager(), IntValueView(3)), StatusIs(absl::StatusCode::kNotFound)); } TEST_P(MapValueViewTest, Find) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); Value value; bool ok; ASSERT_OK_AND_ASSIGN( std::tie(value, ok), MapValueView(map_value).Find(value_manager(), IntValueView(0))); ASSERT_TRUE(ok); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 3.0); ASSERT_OK_AND_ASSIGN( std::tie(value, ok), MapValueView(map_value).Find(value_manager(), IntValueView(1))); ASSERT_TRUE(ok); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 4.0); ASSERT_OK_AND_ASSIGN( std::tie(value, ok), MapValueView(map_value).Find(value_manager(), IntValueView(2))); ASSERT_TRUE(ok); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 5.0); ASSERT_OK_AND_ASSIGN( std::tie(value, ok), MapValueView(map_value).Find(value_manager(), IntValueView(3))); ASSERT_FALSE(ok); } TEST_P(MapValueViewTest, Has) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto value, MapValueView(map_value).Has( value_manager(), IntValueView(0))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN( value, MapValueView(map_value).Has(value_manager(), IntValueView(1))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN( value, MapValueView(map_value).Has(value_manager(), IntValueView(2))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN( value, MapValueView(map_value).Has(value_manager(), IntValueView(3))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_FALSE(Cast<BoolValue>(value).NativeValue()); } TEST_P(MapValueViewTest, ListKeys) { ASSERT_OK_AND_ASSIGN( auto map_value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto list_keys, MapValueView(map_value).ListKeys(value_manager())); std::vector<int64_t> keys; ASSERT_OK( list_keys.ForEach(value_manager(), [&keys](ValueView element) -> bool { keys.push_back(Cast<IntValueView>(element).NativeValue()); return true; })); EXPECT_THAT(keys, UnorderedElementsAreArray({0, 1, 2})); } TEST_P(MapValueViewTest, ForEach) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); std::vector<std::pair<int64_t, double>> entries; EXPECT_OK(MapValueView(value).ForEach( value_manager(), [&entries](ValueView key, ValueView value) { entries.push_back( std::pair{Cast<IntValueView>(key).NativeValue(), Cast<DoubleValueView>(value).NativeValue()}); return true; })); EXPECT_THAT(entries, UnorderedElementsAreArray( {std::pair{0, 3.0}, std::pair{1, 4.0}, std::pair{2, 5.0}})); } TEST_P(MapValueViewTest, NewIterator) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); ASSERT_OK_AND_ASSIGN(auto iterator, MapValueView(value).NewIterator(value_manager())); std::vector<int64_t> keys; while (iterator->HasNext()) { ASSERT_OK_AND_ASSIGN(auto element, iterator->Next(value_manager())); ASSERT_TRUE(InstanceOf<IntValue>(element)); keys.push_back(Cast<IntValue>(element).NativeValue()); } EXPECT_EQ(iterator->HasNext(), false); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(keys, UnorderedElementsAreArray({0, 1, 2})); } TEST_P(MapValueViewTest, GetSerializedSize) { ASSERT_OK_AND_ASSIGN( auto value, NewIntDoubleMapValue(std::pair{IntValue(0), DoubleValue(3.0)}, std::pair{IntValue(1), DoubleValue(4.0)}, std::pair{IntValue(2), DoubleValue(5.0)})); EXPECT_THAT(MapValueView(value).GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(MapValueViewTest, ConvertToAny) { ASSERT_OK_AND_ASSIGN(auto value, NewIntDoubleMapValue()); EXPECT_THAT(MapValueView(value).ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.Struct"), absl::Cord()))); } TEST_P(MapValueViewTest, ConvertToJson) { ASSERT_OK_AND_ASSIGN( auto value, NewJsonMapValue(std::pair{StringValue("0"), DoubleValue(3.0)}, std::pair{StringValue("1"), DoubleValue(4.0)}, std::pair{StringValue("2"), DoubleValue(5.0)})); EXPECT_THAT(MapValueView(value).ConvertToJson(value_manager()), IsOkAndHolds(Json(MakeJsonObject({{JsonString("0"), 3.0}, {JsonString("1"), 4.0}, {JsonString("2"), 5.0}})))); } INSTANTIATE_TEST_SUITE_P( MapValueViewTest, MapValueViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), MapValueViewTest::ToString); } }
37
cpp
google/cel-cpp
list_value
common/values/list_value.cc
common/values/list_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_LIST_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_LIST_VALUE_H_ #include <cstddef> #include <memory> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/log/absl_check.h" #include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/type.h" #include "common/value_kind.h" #include "common/values/legacy_list_value.h" #include "common/values/list_value_interface.h" #include "common/values/parsed_list_value.h" #include "common/values/values.h" namespace cel { class ListValueInterface; class ListValue; class ListValueView; class Value; class ValueView; class ValueManager; class TypeManager; bool Is(ListValueView lhs, ListValueView rhs); class ListValue final { public: using interface_type = ListValueInterface; using view_alternative_type = ListValueView; static constexpr ValueKind kKind = ListValueInterface::kKind; template < typename T, typename = std::enable_if_t< common_internal::IsListValueAlternativeV<absl::remove_cvref_t<T>>>> ListValue(const T& value) : variant_( absl::in_place_type<common_internal::BaseListValueAlternativeForT< absl::remove_cvref_t<T>>>, value) {} template < typename T, typename = std::enable_if_t< common_internal::IsListValueAlternativeV<absl::remove_cvref_t<T>>>> ListValue(T&& value) : variant_( absl::in_place_type<common_internal::BaseListValueAlternativeForT< absl::remove_cvref_t<T>>>, std::forward<T>(value)) {} explicit ListValue(ListValueView value); template <typename T, typename = std::enable_if_t< common_internal::IsListValueViewAlternativeV< absl::remove_cvref_t<T>>>> explicit ListValue(T value) : variant_( absl::in_place_type<common_internal::BaseListValueAlternativeForT< absl::remove_cvref_t<T>>>, value) {} ListValue() = default; ListValue(const ListValue& other) : variant_(other.variant_) {} ListValue(ListValue&& other) noexcept : variant_(std::move(other.variant_)) {} ListValue& operator=(const ListValue& other) { ABSL_DCHECK(this != std::addressof(other)) << "ListValue should not be copied to itself"; variant_ = other.variant_; return *this; } ListValue& operator=(ListValue&& other) noexcept { ABSL_DCHECK(this != std::addressof(other)) << "ListValue should not be moved to itself"; variant_ = std::move(other.variant_); other.variant_.emplace<ParsedListValue>(); return *this; } constexpr ValueKind kind() const { return kKind; } ListType GetType(TypeManager& type_manager) const; absl::string_view GetTypeName() const; std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter& converter) const; absl::Status SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& converter) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& converter, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& converter) const; absl::StatusOr<JsonArray> ConvertToJsonArray( AnyToJsonConverter& converter) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const; void swap(ListValue& other) noexcept { variant_.swap(other.variant_); } absl::StatusOr<bool> IsEmpty() const; absl::StatusOr<size_t> Size() const; absl::Status Get(ValueManager& value_manager, size_t index, Value& result) const; absl::StatusOr<Value> Get(ValueManager& value_manager, size_t index) const; using ForEachCallback = typename ListValueInterface::ForEachCallback; using ForEachWithIndexCallback = typename ListValueInterface::ForEachWithIndexCallback; absl::Status ForEach(ValueManager& value_manager, ForEachCallback callback) const; absl::Status ForEach(ValueManager& value_manager, ForEachWithIndexCallback callback) const; absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager& value_manager) const; absl::Status Contains(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Contains(ValueManager& value_manager, ValueView other) const; private: friend class ListValueView; friend struct NativeTypeTraits<ListValue>; friend struct CompositionTraits<ListValue>; common_internal::ListValueViewVariant ToViewVariant() const; common_internal::ListValueVariant variant_; }; inline void swap(ListValue& lhs, ListValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const ListValue& value) { return out << value.DebugString(); } template <> struct NativeTypeTraits<ListValue> final { static NativeTypeId Id(const ListValue& value) { return absl::visit( [](const auto& alternative) -> NativeTypeId { return NativeTypeId::Of(alternative); }, value.variant_); } static bool SkipDestructor(const ListValue& value) { return absl::visit( [](const auto& alternative) -> bool { return NativeType::SkipDestructor(alternative); }, value.variant_); } }; template <> struct CompositionTraits<ListValue> final { template <typename U> static std::enable_if_t<common_internal::IsListValueAlternativeV<U>, bool> HasA(const ListValue& value) { using Base = common_internal::BaseListValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::holds_alternative<U>(value.variant_); } else { return absl::holds_alternative<Base>(value.variant_) && InstanceOf<U>(Get<U>(value)); } } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, bool> HasA( const ListValue& value) { return true; } template <typename U> static std::enable_if_t<common_internal::IsListValueAlternativeV<U>, const U&> Get(const ListValue& value) { using Base = common_internal::BaseListValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(value.variant_); } else { return Cast<U>(absl::get<Base>(value.variant_)); } } template <typename U> static std::enable_if_t<common_internal::IsListValueAlternativeV<U>, U&> Get( ListValue& value) { using Base = common_internal::BaseListValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(value.variant_); } else { return Cast<U>(absl::get<Base>(value.variant_)); } } template <typename U> static std::enable_if_t<common_internal::IsListValueAlternativeV<U>, U> Get( const ListValue&& value) { using Base = common_internal::BaseListValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(std::move(value.variant_)); } else { return Cast<U>(absl::get<Base>(std::move(value.variant_))); } } template <typename U> static std::enable_if_t<common_internal::IsListValueAlternativeV<U>, U> Get( ListValue&& value) { using Base = common_internal::BaseListValueAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(std::move(value.variant_)); } else { return Cast<U>(absl::get<Base>(std::move(value.variant_))); } } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get( const ListValue& value) { return absl::visit( [](const auto& alternative) -> U { return U{alternative}; }, value.variant_); } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get(ListValue& value) { return absl::visit( [](const auto& alternative) -> U { return U{alternative}; }, value.variant_); } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get( const ListValue&& value) { return absl::visit( [](const auto& alternative) -> U { return U{alternative}; }, value.variant_); } template <typename U> static std::enable_if_t<std::is_same_v<Value, U>, U> Get(ListValue&& value) { return absl::visit( [](auto&& alternative) -> U { return U{std::move(alternative)}; }, std::move(value.variant_)); } }; template <typename To, typename From> struct CastTraits< To, From, std::enable_if_t<std::is_same_v<ListValue, absl::remove_cvref_t<From>>>> : CompositionCastTraits<To, From> {}; class ListValueView final { public: using interface_type = ListValueInterface; using alternative_type = ListValue; static constexpr ValueKind kKind = ListValue::kKind; template <typename T, typename = std::enable_if_t< common_internal::IsListValueViewAlternativeV<T>>> ListValueView(T value) : variant_(absl::in_place_type< common_internal::BaseListValueViewAlternativeForT<T>>, value) {} ListValueView(const ListValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) : variant_(value.ToViewVariant()) {} template <typename T, typename = std::enable_if_t< common_internal::IsListValueAlternativeV<T>>> ListValueView(const T& value ABSL_ATTRIBUTE_LIFETIME_BOUND) : variant_(absl::in_place_type< common_internal::BaseListValueViewAlternativeForT<T>>, value) {} ListValueView& operator=(ListValue&&) = delete; template < typename T, typename = std::enable_if_t< common_internal::IsListValueAlternativeV<absl::remove_cvref_t<T>>>> ListValueView& operator=(T&&) = delete; ListValueView() = default; ListValueView(const ListValueView&) = default; ListValueView& operator=(const ListValueView&) = default; constexpr ValueKind kind() const { return kKind; } ListType GetType(TypeManager& type_manager) const; absl::string_view GetTypeName() const; std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter& converter) const; absl::Status SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& converter) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& converter, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& converter) const; absl::StatusOr<JsonArray> ConvertToJsonArray( AnyToJsonConverter& converter) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const; void swap(ListValueView& other) noexcept { variant_.swap(other.variant_); } absl::StatusOr<bool> IsEmpty() const; absl::StatusOr<size_t> Size() const; absl::Status Get(ValueManager& value_manager, size_t index, Value& result) const; absl::StatusOr<Value> Get(ValueManager& value_manager, size_t index) const; using ForEachCallback = typename ListValueInterface::ForEachCallback; using ForEachWithIndexCallback = typename ListValueInterface::ForEachWithIndexCallback; absl::Status ForEach(ValueManager& value_manager, ForEachCallback callback) const; absl::Status ForEach(ValueManager& value_manager, ForEachWithIndexCallback callback) const; absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager& value_manager) const; absl::Status Contains(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Contains(ValueManager& value_manager, ValueView other) const; private: friend class ListValue; friend struct NativeTypeTraits<ListValueView>; friend struct CompositionTraits<ListValueView>; friend bool Is(ListValueView lhs, ListValueView rhs); common_internal::ListValueVariant ToVariant() const; common_internal::ListValueViewVariant variant_; }; inline void swap(ListValueView& lhs, ListValueView& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, ListValueView value) { return out << value.DebugString(); } template <> struct NativeTypeTraits<ListValueView> final { static NativeTypeId Id(ListValueView value) { return absl::visit( [](const auto& alternative) -> NativeTypeId { return NativeTypeId::Of(alternative); }, value.variant_); } }; template <> struct CompositionTraits<ListValueView> final { template <typename U> static std::enable_if_t<common_internal::IsListValueViewAlternativeV<U>, bool> HasA(ListValueView value) { using Base = common_internal::BaseListValueViewAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::holds_alternative<U>(value.variant_); } else { return InstanceOf<U>(Get<Base>(value)); } } template <typename U> static std::enable_if_t<std::is_same_v<ValueView, U>, bool> HasA( ListValueView value) { return true; } template <typename U> static std::enable_if_t<common_internal::IsListValueViewAlternativeV<U>, U> Get(ListValueView value) { using Base = common_internal::BaseListValueViewAlternativeForT<U>; if constexpr (std::is_same_v<Base, U>) { return absl::get<U>(value.variant_); } else { return Cast<U>(absl::get<Base>(value.variant_)); } } template <typename U> static std::enable_if_t<std::is_same_v<ValueView, U>, U> Get( ListValueView value) { return absl::visit([](auto alternative) -> U { return U{alternative}; }, value.variant_); } }; template <typename To, typename From> struct CastTraits< To, From, std::enable_if_t<std::is_same_v<ListValueView, absl::remove_cvref_t<From>>>> : CompositionCastTraits<To, From> {}; inline ListValue::ListValue(ListValueView value) : variant_(value.ToVariant()) {} inline bool Is(ListValueView lhs, ListValueView rhs) { return absl::visit( [](auto alternative_lhs, auto alternative_rhs) -> bool { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative_lhs)>, absl::remove_cvref_t<decltype(alternative_rhs)>>) { return cel::Is(alternative_lhs, alternative_rhs); } else { return false; } }, lhs.variant_, rhs.variant_); } class ListValueBuilder { public: virtual ~ListValueBuilder() = default; virtual absl::Status Add(Value value) = 0; virtual bool IsEmpty() const { return Size() == 0; } virtual size_t Size() const = 0; virtual void Reserve(size_t capacity) {} virtual ListValue Build() && = 0; }; } #endif #include <cstddef> #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/casting.h" #include "common/type.h" #include "common/value.h" #include "internal/status_macros.h" namespace cel { ListType ListValue::GetType(TypeManager& type_manager) const { return absl::visit( [&type_manager](const auto& alternative) -> ListType { return alternative.GetType(type_manager); }, variant_); } absl::string_view ListValue::GetTypeName() const { return absl::visit( [](const auto& alternative) -> absl::string_view { return alternative.GetTypeName(); }, variant_); } std::string ListValue::DebugString() const { return absl::visit( [](const auto& alternative) -> std::string { return alternative.DebugString(); }, variant_); } absl::StatusOr<size_t> ListValue::GetSerializedSize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<size_t> { return alternative.GetSerializedSize(converter); }, variant_); } absl::Status ListValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::visit( [&converter, &value](const auto& alternative) -> absl::Status { return alternative.SerializeTo(converter, value); }, variant_); } absl::StatusOr<absl::Cord> ListValue::Serialize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<absl::Cord> { return alternative.Serialize(converter); }, variant_); } absl::StatusOr<std::string> ListValue::GetTypeUrl( absl::string_view prefix) const { return absl::visit( [prefix](const auto& alternative) -> absl::StatusOr<std::string> { return alternative.GetTypeUrl(prefix); }, variant_); } absl::StatusOr<Any> ListValue::ConvertToAny(AnyToJsonConverter& converter, absl::string_view prefix) const { return absl::visit( [&converter, prefix](const auto& alternative) -> absl::StatusOr<Any> { return alternative.ConvertToAny(converter, prefix); }, variant_); } absl::StatusOr<Json> ListValue::ConvertToJson( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<Json> { return alternative.ConvertToJson(converter); }, variant_); } absl::StatusOr<JsonArray> ListValue::ConvertToJsonArray( AnyToJsonConverter& converter) const { return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<JsonArray> { return alternative.ConvertToJsonArray(converter); }, variant_); } bool ListValue::IsZeroValue() const { return absl::visit( [](const auto& alternative) -> bool { return alternative.IsZeroValue(); }, variant_); } absl::StatusOr<bool> ListValue::IsEmpty() const { return absl::visit( [](const auto& alternative) -> bool { return alternative.IsEmpty(); }, variant_); } absl::StatusOr<size_t> ListValue::Size() const { return absl::visit( [](const auto& alternative) -> size_t { return alternative.Size(); }, variant_); } common_internal::ListValueViewVariant ListValue::ToViewVariant() const { return absl::visit( [](const auto& alternative) -> common_internal::ListValueViewVariant { return common_internal::ListValueViewVariant{ absl::in_place_type<typename absl::remove_cvref_t< decltype(alternative)>::view_alternative_type>, alternative}; }, variant_); } ListType ListValueView::GetType(TypeManager& type_manager) const { return absl::visit( [&type_manager](auto alternative) -> ListType { return alternative.GetType(type_manager); }, variant_); } absl::string_view ListValueView::GetTypeName() const { return absl::visit( [](auto alternative) -> absl::string_view { return alternative.GetTypeName(); }, variant_); } std::string ListValueView::DebugString() const { return absl::visit( [](auto alternative) -> std::string { return alternative.DebugString(); }, variant_); } absl::StatusOr<size_t> ListValueView::GetSerializedSize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<size_t> { return alternative.GetSerializedSize(converter); }, variant_); } absl::Status ListValueView::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::visit( [&converter, &value](auto alternative) -> absl::Status { return alternative.SerializeTo(converter, value); }, variant_); } absl::StatusOr<absl::Cord> ListValueView::Serialize( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<absl::Cord> { return alternative.Serialize(converter); }, variant_); } absl::StatusOr<std::string> ListValueView::GetTypeUrl( absl::string_view prefix) const { return absl::visit( [prefix](auto alternative) -> absl::StatusOr<std::string> { return alternative.GetTypeUrl(prefix); }, variant_); } absl::StatusOr<Any> ListValueView::ConvertToAny( AnyToJsonConverter& converter, absl::string_view prefix) const { return absl::visit( [&converter, prefix](auto alternative) -> absl::StatusOr<Any> { return alternative.ConvertToAny(converter, prefix); }, variant_); } absl::StatusOr<Json> ListValueView::ConvertToJson( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<Json> { return alternative.ConvertToJson(converter); }, variant_); } absl::StatusOr<JsonArray> ListValueView::ConvertToJsonArray( AnyToJsonConverter& converter) const { return absl::visit( [&converter](auto alternative) -> absl::StatusOr<JsonArray> { return alternative.ConvertToJsonArray(converter); }, variant_); } bool ListValueView::IsZeroValue() const { return absl::visit( [](auto alternative) -> bool { return alternative.IsZeroValue(); }, variant_); } absl::StatusOr<bool> ListValueView::IsEmpty() const { return absl::visit( [](auto alternative) -> bool { return alternative.IsEmpty(); }, variant_); } absl::StatusOr<size_t> ListValueView::Size() const { return absl::visit( [](auto alternative) -> size_t { return alternative.Size(); }, variant_); } common_internal::ListValueVariant ListValueView::ToVariant() const { return absl::visit( [](auto alternative) -> common_internal::ListValueVariant { return common_internal::ListValueVariant{ absl::in_place_type<typename absl::remove_cvref_t< decltype(alternative)>::alternative_type>, alternative}; }, variant_); } namespace common_internal { absl::Status ListValueEqual(ValueManager& value_manager, ListValueView lhs, ListValueView rhs, Value& result) { if (Is(lhs, rhs)) { result = BoolValueView{true}; return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(auto lhs_size, lhs.Size()); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { result = BoolValueView{false}; return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(auto lhs_iterator, lhs.NewIterator(value_manager)); CEL_ASSIGN_OR_RETURN(auto rhs_iterator, rhs.NewIterator(value_manager)); Value lhs_element; Value rhs_element; for (size_t index = 0; index < lhs_size; ++index) { ABSL_CHECK(lhs_iterator->HasNext()); ABSL_CHECK(rhs_iterator->HasNext()); CEL_RETURN_IF_ERROR(lhs_iterator->Next(value_manager, lhs_element)); CEL_RETURN_IF_ERROR(rhs_iterator->Next(value_manager, rhs_element)); CEL_RETURN_IF_ERROR(lhs_element.Equal(value_manager, rhs_element, result)); if (auto bool_value = As<BoolValue>(result); bool_value.has_value() && !bool_value->NativeValue()) { return absl::OkStatus(); } } ABSL_DCHECK(!lhs_iterator->HasNext()); ABSL_DCHECK(!rhs_iterator->HasNext()); result = BoolValueView{true}; return absl::OkStatus(); } absl::Status ListValueEqual(ValueManager& value_manager, const ParsedListValueInterface& lhs, ListValueView rhs, Value& result) { auto lhs_size = lhs.Size(); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { result = BoolValueView{false}; return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(auto lhs_iterator, lhs.NewIterator(value_manager)); CEL_ASSIGN_OR_RETURN(auto rhs_iterator, rhs.NewIterator(value_manager)); Value lhs_element; Value rhs_element; for (size_t index = 0; index < lhs_size; ++index) { ABSL_CHECK(lhs_iterator->HasNext()); ABSL_CHECK(rhs_iterator->HasNext()); CEL_RETURN_IF_ERROR(lhs_iterator->Next(value_manager, lhs_element)); CEL_RETURN_IF_ERROR(rhs_iterator->Next(value_manager, rhs_element)); CEL_RETURN_IF_ERROR(lhs_element.Equal(value_manager, rhs_element, result)); if (auto bool_value = As<BoolValue>(result); bool_value.has_value() && !bool_value->NativeValue()) { return absl::OkStatus(); } } ABSL_DCHECK(!lhs_iterator->HasNext()); ABSL_DCHECK(!rhs_iterator->HasNext()); result = BoolValueView{true}; return absl::OkStatus(); } } }
#include <cstdint> #include <memory> #include <sstream> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/memory.h" #include "common/type.h" #include "common/type_factory.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/status_macros.h" #include "internal/testing.h" namespace cel { namespace { using testing::ElementsAreArray; using testing::TestParamInfo; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; class ListValueTest : public common_internal::ThreadCompatibleValueTest<> { public: template <typename... Args> absl::StatusOr<ListValue> NewIntListValue(Args&&... args) { CEL_ASSIGN_OR_RETURN(auto builder, value_manager().NewListValueBuilder(GetIntListType())); (static_cast<void>(builder->Add(std::forward<Args>(args))), ...); return std::move(*builder).Build(); } ListType GetIntListType() { return type_factory().CreateListType(IntTypeView()); } }; TEST_P(ListValueTest, Default) { ListValue value; EXPECT_THAT(value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(value.Size(), IsOkAndHolds(0)); EXPECT_EQ(value.DebugString(), "[]"); EXPECT_EQ(value.GetType(type_manager()).element(), DynType()); } TEST_P(ListValueTest, Kind) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_EQ(value.kind(), ListValue::kKind); EXPECT_EQ(Value(value).kind(), ListValue::kKind); } TEST_P(ListValueTest, Type) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_EQ(value.GetType(type_manager()), GetIntListType()); EXPECT_EQ(Value(value).GetType(type_manager()), GetIntListType()); } TEST_P(ListValueTest, DebugString) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); { std::ostringstream out; out << value; EXPECT_EQ(out.str(), "[0, 1, 2]"); } { std::ostringstream out; out << Value(value); EXPECT_EQ(out.str(), "[0, 1, 2]"); } } TEST_P(ListValueTest, IsEmpty) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_THAT(value.IsEmpty(), IsOkAndHolds(false)); } TEST_P(ListValueTest, Size) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_THAT(value.Size(), IsOkAndHolds(3)); } TEST_P(ListValueTest, Get) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); ASSERT_OK_AND_ASSIGN(auto element, value.Get(value_manager(), 0)); ASSERT_TRUE(InstanceOf<IntValue>(element)); ASSERT_EQ(Cast<IntValue>(element).NativeValue(), 0); ASSERT_OK_AND_ASSIGN(element, value.Get(value_manager(), 1)); ASSERT_TRUE(InstanceOf<IntValue>(element)); ASSERT_EQ(Cast<IntValue>(element).NativeValue(), 1); ASSERT_OK_AND_ASSIGN(element, value.Get(value_manager(), 2)); ASSERT_TRUE(InstanceOf<IntValue>(element)); ASSERT_EQ(Cast<IntValue>(element).NativeValue(), 2); EXPECT_THAT(value.Get(value_manager(), 3), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_P(ListValueTest, ForEach) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); std::vector<int64_t> elements; EXPECT_OK(value.ForEach(value_manager(), [&elements](ValueView element) { elements.push_back(Cast<IntValueView>(element).NativeValue()); return true; })); EXPECT_THAT(elements, ElementsAreArray({0, 1, 2})); } TEST_P(ListValueTest, Contains) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); ASSERT_OK_AND_ASSIGN(auto contained, value.Contains(value_manager(), IntValueView(2))); ASSERT_TRUE(InstanceOf<BoolValue>(contained)); EXPECT_TRUE(Cast<BoolValue>(contained).NativeValue()); ASSERT_OK_AND_ASSIGN(contained, value.Contains(value_manager(), IntValueView(3))); ASSERT_TRUE(InstanceOf<BoolValue>(contained)); EXPECT_FALSE(Cast<BoolValue>(contained).NativeValue()); } TEST_P(ListValueTest, NewIterator) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); ASSERT_OK_AND_ASSIGN(auto iterator, value.NewIterator(value_manager())); std::vector<int64_t> elements; while (iterator->HasNext()) { ASSERT_OK_AND_ASSIGN(auto element, iterator->Next(value_manager())); ASSERT_TRUE(InstanceOf<IntValue>(element)); elements.push_back(Cast<IntValue>(element).NativeValue()); } EXPECT_EQ(iterator->HasNext(), false); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(elements, ElementsAreArray({0, 1, 2})); } TEST_P(ListValueTest, GetSerializedSize) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue()); EXPECT_THAT(value.GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ListValueTest, ConvertToAny) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue()); EXPECT_THAT(value.ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.ListValue"), absl::Cord()))); } TEST_P(ListValueTest, ConvertToJson) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_THAT(value.ConvertToJson(value_manager()), IsOkAndHolds(Json(MakeJsonArray({0.0, 1.0, 2.0})))); } INSTANTIATE_TEST_SUITE_P( ListValueTest, ListValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), ListValueTest::ToString); class ListValueViewTest : public common_internal::ThreadCompatibleValueTest<> { public: template <typename... Args> absl::StatusOr<ListValue> NewIntListValue(Args&&... args) { CEL_ASSIGN_OR_RETURN(auto builder, value_manager().NewListValueBuilder(GetIntListType())); (static_cast<void>(builder->Add(std::forward<Args>(args))), ...); return std::move(*builder).Build(); } ListType GetIntListType() { return type_factory().CreateListType(IntTypeView()); } }; TEST_P(ListValueViewTest, Default) { ListValueView value; EXPECT_THAT(value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(value.Size(), IsOkAndHolds(0)); EXPECT_EQ(value.DebugString(), "[]"); EXPECT_EQ(value.GetType(type_manager()).element(), DynType()); } TEST_P(ListValueViewTest, Kind) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_EQ(ListValueView(value).kind(), ListValueView::kKind); EXPECT_EQ(ValueView(ListValueView(value)).kind(), ListValueView::kKind); } TEST_P(ListValueViewTest, Type) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_EQ(ListValueView(value).GetType(type_manager()), GetIntListType()); EXPECT_EQ(ListValue(ListValueView(value)).GetType(type_manager()), GetIntListType()); } TEST_P(ListValueViewTest, DebugString) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); { std::ostringstream out; out << ListValueView(value); EXPECT_EQ(out.str(), "[0, 1, 2]"); } { std::ostringstream out; out << ValueView(ListValueView(value)); EXPECT_EQ(out.str(), "[0, 1, 2]"); } } TEST_P(ListValueViewTest, IsEmpty) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_THAT(ListValueView(value).IsEmpty(), IsOkAndHolds(false)); } TEST_P(ListValueViewTest, Size) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_THAT(ListValueView(value).Size(), IsOkAndHolds(3)); } TEST_P(ListValueViewTest, Get) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); ASSERT_OK_AND_ASSIGN(auto element, ListValueView(value).Get(value_manager(), 0)); ASSERT_TRUE(InstanceOf<IntValue>(element)); ASSERT_EQ(Cast<IntValue>(element).NativeValue(), 0); ASSERT_OK_AND_ASSIGN(element, ListValueView(value).Get(value_manager(), 1)); ASSERT_TRUE(InstanceOf<IntValue>(element)); ASSERT_EQ(Cast<IntValue>(element).NativeValue(), 1); ASSERT_OK_AND_ASSIGN(element, ListValueView(value).Get(value_manager(), 2)); ASSERT_TRUE(InstanceOf<IntValue>(element)); ASSERT_EQ(Cast<IntValue>(element).NativeValue(), 2); EXPECT_THAT(ListValueView(value).Get(value_manager(), 3), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_P(ListValueViewTest, ForEach) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); std::vector<int64_t> elements; EXPECT_OK(ListValueView(value).ForEach( value_manager(), [&elements](ValueView element) { elements.push_back(Cast<IntValueView>(element).NativeValue()); return true; })); EXPECT_THAT(elements, ElementsAreArray({0, 1, 2})); } TEST_P(ListValueViewTest, Contains) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); ASSERT_OK_AND_ASSIGN(auto contained, ListValueView(value).Contains( value_manager(), IntValueView(2))); ASSERT_TRUE(InstanceOf<BoolValue>(contained)); EXPECT_TRUE(Cast<BoolValue>(contained).NativeValue()); ASSERT_OK_AND_ASSIGN(contained, ListValueView(value).Contains( value_manager(), IntValueView(3))); ASSERT_TRUE(InstanceOf<BoolValue>(contained)); EXPECT_FALSE(Cast<BoolValue>(contained).NativeValue()); } TEST_P(ListValueViewTest, NewIterator) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); ASSERT_OK_AND_ASSIGN(auto iterator, ListValueView(value).NewIterator(value_manager())); std::vector<int64_t> elements; while (iterator->HasNext()) { ASSERT_OK_AND_ASSIGN(auto element, iterator->Next(value_manager())); ASSERT_TRUE(InstanceOf<IntValue>(element)); elements.push_back(Cast<IntValue>(element).NativeValue()); } EXPECT_EQ(iterator->HasNext(), false); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(elements, ElementsAreArray({0, 1, 2})); } TEST_P(ListValueViewTest, GetSerializedSize) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue()); EXPECT_THAT(ListValueView(value).GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ListValueViewTest, ConvertToAny) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue()); EXPECT_THAT(ListValueView(value).ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.ListValue"), absl::Cord()))); } TEST_P(ListValueViewTest, ConvertToJson) { ASSERT_OK_AND_ASSIGN(auto value, NewIntListValue(IntValue(0), IntValue(1), IntValue(2))); EXPECT_THAT(ListValueView(value).ConvertToJson(value_manager()), IsOkAndHolds(Json(MakeJsonArray({0.0, 1.0, 2.0})))); } INSTANTIATE_TEST_SUITE_P( ListValueViewTest, ListValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), ListValueViewTest::ToString); } }
38
cpp
google/cel-cpp
legacy_struct_value
common/values/legacy_struct_value.cc
common/values/legacy_struct_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_LEGACY_STRUCT_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_LEGACY_STRUCT_VALUE_H_ #include <cstddef> #include <cstdint> #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/type.h" #include "common/value_kind.h" #include "common/values/struct_value_interface.h" #include "runtime/runtime_options.h" namespace cel { class Value; class ValueView; class ValueManager; class TypeManager; namespace common_internal { class LegacyStructValue; class LegacyStructValueView; class LegacyStructValue final { public: using view_alternative_type = LegacyStructValueView; static constexpr ValueKind kKind = ValueKind::kStruct; explicit LegacyStructValue(LegacyStructValueView value); LegacyStructValue(uintptr_t message_ptr, uintptr_t type_info) : message_ptr_(message_ptr), type_info_(type_info) {} LegacyStructValue(const LegacyStructValue&) = default; LegacyStructValue& operator=(const LegacyStructValue&) = default; constexpr ValueKind kind() const { return kKind; } StructType GetType(TypeManager& type_manager) const; absl::string_view GetTypeName() const; std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize( AnyToJsonConverter& value_manager) const; absl::Status SerializeTo(AnyToJsonConverter& value_manager, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& value_manager) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& value_manager) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; bool IsZeroValue() const; void swap(LegacyStructValue& other) noexcept { using std::swap; swap(message_ptr_, other.message_ptr_); swap(type_info_, other.type_info_); } absl::Status GetFieldByName(ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options = ProtoWrapperTypeOptions::kUnsetNull) const; absl::Status GetFieldByNumber(ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options = ProtoWrapperTypeOptions::kUnsetNull) const; absl::StatusOr<bool> HasFieldByName(absl::string_view name) const; absl::StatusOr<bool> HasFieldByNumber(int64_t number) const; using ForEachFieldCallback = StructValueInterface::ForEachFieldCallback; absl::Status ForEachField(ValueManager& value_manager, ForEachFieldCallback callback) const; absl::StatusOr<int> Qualify(ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const; uintptr_t message_ptr() const { return message_ptr_; } uintptr_t legacy_type_info() const { return type_info_; } private: friend class LegacyStructValueView; uintptr_t message_ptr_; uintptr_t type_info_; }; inline void swap(LegacyStructValue& lhs, LegacyStructValue& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, const LegacyStructValue& value) { return out << value.DebugString(); } class LegacyStructValueView final { public: using alternative_type = LegacyStructValue; static constexpr ValueKind kKind = LegacyStructValue::kKind; LegacyStructValueView(uintptr_t message_ptr, uintptr_t type_info) : message_ptr_(message_ptr), type_info_(type_info) {} LegacyStructValueView( const LegacyStructValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) : LegacyStructValueView(value.message_ptr_, value.type_info_) {} LegacyStructValueView(LegacyStructValue&&) = delete; LegacyStructValueView(const LegacyStructValueView&) = default; LegacyStructValueView& operator=(const LegacyStructValueView&) = default; LegacyStructValueView& operator=( const LegacyStructValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) { message_ptr_ = value.message_ptr_; type_info_ = value.type_info_; return *this; } LegacyStructValueView& operator=(LegacyStructValue&&) = delete; constexpr ValueKind kind() const { return kKind; } StructType GetType(TypeManager& type_manager) const; absl::string_view GetTypeName() const; std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize( AnyToJsonConverter& value_manager) const; absl::Status SerializeTo(AnyToJsonConverter& value_manager, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter& value_manager) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter& value_manager) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; bool IsZeroValue() const; void swap(LegacyStructValueView& other) noexcept { using std::swap; swap(message_ptr_, other.message_ptr_); swap(type_info_, other.type_info_); } absl::Status GetFieldByName(ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options = ProtoWrapperTypeOptions::kUnsetNull) const; absl::Status GetFieldByNumber(ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options = ProtoWrapperTypeOptions::kUnsetNull) const; absl::StatusOr<bool> HasFieldByName(absl::string_view name) const; absl::StatusOr<bool> HasFieldByNumber(int64_t number) const; using ForEachFieldCallback = StructValueInterface::ForEachFieldCallback; absl::Status ForEachField(ValueManager& value_manager, ForEachFieldCallback callback) const; absl::StatusOr<int> Qualify(ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const; uintptr_t message_ptr() const { return message_ptr_; } uintptr_t legacy_type_info() const { return type_info_; } private: friend class LegacyStructValue; uintptr_t message_ptr_; uintptr_t type_info_; }; inline void swap(LegacyStructValueView& lhs, LegacyStructValueView& rhs) noexcept { lhs.swap(rhs); } inline std::ostream& operator<<(std::ostream& out, LegacyStructValueView value) { return out << value.DebugString(); } inline LegacyStructValue::LegacyStructValue(LegacyStructValueView value) : message_ptr_(value.message_ptr_), type_info_(value.type_info_) {} } } #endif #include <cstddef> #include <cstdint> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/any.h" #include "common/json.h" #include "common/type.h" #include "common/value.h" #include "internal/dynamic_loader.h" #include "internal/status_macros.h" #include "runtime/runtime_options.h" namespace cel::common_internal { namespace { using LegacyStructValue_DebugString = std::string (*)(uintptr_t, uintptr_t); using LegacyStructValue_GetSerializedSize = absl::StatusOr<size_t> (*)(uintptr_t, uintptr_t); using LegacyStructValue_SerializeTo = absl::Status (*)(uintptr_t, uintptr_t, absl::Cord&); using LegacyStructValue_GetType = std::string (*)(uintptr_t, uintptr_t); using LegacyStructValue_GetTypeName = absl::string_view (*)(uintptr_t, uintptr_t); using LegacyStructValue_ConvertToJsonObject = absl::StatusOr<JsonObject> (*)(uintptr_t, uintptr_t); using LegacyStructValue_GetFieldByName = absl::Status (*)(uintptr_t, uintptr_t, ValueManager&, absl::string_view, Value&, ProtoWrapperTypeOptions); using LegacyStructValue_GetFieldByNumber = absl::Status (*)(uintptr_t, uintptr_t, ValueManager&, int64_t, Value&, ProtoWrapperTypeOptions); using LegacyStructValue_HasFieldByName = absl::StatusOr<bool> (*)(uintptr_t, uintptr_t, absl::string_view); using LegacyStructValue_HasFieldByNumber = absl::StatusOr<bool> (*)(uintptr_t, uintptr_t, int64_t); using LegacyStructValue_Equal = absl::Status (*)(uintptr_t, uintptr_t, ValueManager&, ValueView, Value&); using LegacyStructValue_IsZeroValue = bool (*)(uintptr_t, uintptr_t); using LegacyStructValue_ForEachField = absl::Status (*)(uintptr_t, uintptr_t, ValueManager&, LegacyStructValue::ForEachFieldCallback); using LegacyStructValue_Qualify = absl::StatusOr<int> (*)(uintptr_t, uintptr_t, ValueManager&, absl::Span<const SelectQualifier>, bool, Value&); ABSL_CONST_INIT struct { absl::once_flag init_once; LegacyStructValue_DebugString debug_string = nullptr; LegacyStructValue_GetSerializedSize get_serialized_size = nullptr; LegacyStructValue_SerializeTo serialize_to = nullptr; LegacyStructValue_GetType get_type = nullptr; LegacyStructValue_GetTypeName get_type_name = nullptr; LegacyStructValue_ConvertToJsonObject convert_to_json_object = nullptr; LegacyStructValue_GetFieldByName get_field_by_name = nullptr; LegacyStructValue_GetFieldByNumber get_field_by_number = nullptr; LegacyStructValue_HasFieldByName has_field_by_name = nullptr; LegacyStructValue_HasFieldByNumber has_field_by_number = nullptr; LegacyStructValue_Equal equal = nullptr; LegacyStructValue_IsZeroValue is_zero_value = nullptr; LegacyStructValue_ForEachField for_each_field = nullptr; LegacyStructValue_Qualify qualify = nullptr; } legacy_struct_value_vtable; #if ABSL_HAVE_ATTRIBUTE_WEAK extern "C" ABSL_ATTRIBUTE_WEAK std::string cel_common_internal_LegacyStructValue_DebugString(uintptr_t message_ptr, uintptr_t type_info); extern "C" ABSL_ATTRIBUTE_WEAK absl::StatusOr<size_t> cel_common_internal_LegacyStructValue_GetSerializedSize(uintptr_t message_ptr, uintptr_t type_info); extern "C" ABSL_ATTRIBUTE_WEAK absl::Status cel_common_internal_LegacyStructValue_SerializeTo(uintptr_t message_ptr, uintptr_t type_info, absl::Cord& value); extern "C" ABSL_ATTRIBUTE_WEAK std::string cel_common_internal_LegacyStructValue_GetType(uintptr_t message_ptr, uintptr_t type_info); extern "C" ABSL_ATTRIBUTE_WEAK absl::string_view cel_common_internal_LegacyStructValue_GetTypeName(uintptr_t message_ptr, uintptr_t type_info); extern "C" ABSL_ATTRIBUTE_WEAK absl::StatusOr<JsonObject> cel_common_internal_LegacyStructValue_ConvertToJsonObject(uintptr_t message_ptr, uintptr_t type_info); extern "C" ABSL_ATTRIBUTE_WEAK absl::Status cel_common_internal_LegacyStructValue_GetFieldByName( uintptr_t message_ptr, uintptr_t type_info, ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options); extern "C" ABSL_ATTRIBUTE_WEAK absl::Status cel_common_internal_LegacyStructValue_GetFieldByNumber(uintptr_t, uintptr_t, ValueManager&, int64_t, Value&, ProtoWrapperTypeOptions); extern "C" ABSL_ATTRIBUTE_WEAK absl::StatusOr<bool> cel_common_internal_LegacyStructValue_HasFieldByName(uintptr_t message_ptr, uintptr_t type_info, absl::string_view name); extern "C" ABSL_ATTRIBUTE_WEAK absl::StatusOr<bool> cel_common_internal_LegacyStructValue_HasFieldByNumber(uintptr_t, uintptr_t, int64_t); extern "C" ABSL_ATTRIBUTE_WEAK absl::Status cel_common_internal_LegacyStructValue_Equal(uintptr_t message_ptr, uintptr_t type_info, ValueManager& value_manager, ValueView other, Value& result); extern "C" ABSL_ATTRIBUTE_WEAK bool cel_common_internal_LegacyStructValue_IsZeroValue(uintptr_t message_ptr, uintptr_t type_info); extern "C" ABSL_ATTRIBUTE_WEAK absl::Status cel_common_internal_LegacyStructValue_ForEachField( uintptr_t message_ptr, uintptr_t type_info, ValueManager& value_manager, StructValue::ForEachFieldCallback callback); extern "C" ABSL_ATTRIBUTE_WEAK absl::StatusOr<int> cel_common_internal_LegacyStructValue_Qualify( uintptr_t message_ptr, uintptr_t type_info, ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result); #endif void InitializeLegacyStructValue() { absl::call_once(legacy_struct_value_vtable.init_once, []() -> void { #if ABSL_HAVE_ATTRIBUTE_WEAK legacy_struct_value_vtable.debug_string = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_DebugString); legacy_struct_value_vtable.get_serialized_size = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_GetSerializedSize); legacy_struct_value_vtable.serialize_to = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_SerializeTo); legacy_struct_value_vtable.get_type = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_GetType); legacy_struct_value_vtable.get_type_name = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_GetTypeName); legacy_struct_value_vtable.convert_to_json_object = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_ConvertToJsonObject); legacy_struct_value_vtable.get_field_by_name = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_GetFieldByName); legacy_struct_value_vtable.get_field_by_number = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_GetFieldByNumber); legacy_struct_value_vtable.has_field_by_name = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_HasFieldByName); legacy_struct_value_vtable.has_field_by_number = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_HasFieldByNumber); legacy_struct_value_vtable.equal = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_Equal); legacy_struct_value_vtable.is_zero_value = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_IsZeroValue); legacy_struct_value_vtable.for_each_field = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_ForEachField); legacy_struct_value_vtable.qualify = ABSL_DIE_IF_NULL( cel_common_internal_LegacyStructValue_Qualify); #else internal::DynamicLoader symbol_finder; legacy_struct_value_vtable.debug_string = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_DebugString"); legacy_struct_value_vtable.get_serialized_size = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_GetSerializedSize"); legacy_struct_value_vtable.serialize_to = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_SerializeTo"); legacy_struct_value_vtable.get_type = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_GetType"); legacy_struct_value_vtable.get_type_name = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_GetTypeName"); legacy_struct_value_vtable.convert_to_json_object = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_ConvertToJsonObject"); legacy_struct_value_vtable.get_field_by_name = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_GetFieldByName"); legacy_struct_value_vtable.get_field_by_number = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_GetFieldByNumber"); legacy_struct_value_vtable.has_field_by_name = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_HasFieldByName"); legacy_struct_value_vtable.has_field_by_number = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_HasFieldByNumber"); legacy_struct_value_vtable.equal = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_Equal"); legacy_struct_value_vtable.is_zero_value = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_IsZeroValue"); legacy_struct_value_vtable.for_each_field = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_ForEachField"); legacy_struct_value_vtable.qualify = symbol_finder.FindSymbolOrDie( "cel_common_internal_LegacyStructValue_Qualify"); #endif }); } } StructType LegacyStructValue::GetType(TypeManager& type_manager) const { InitializeLegacyStructValue(); return type_manager.CreateStructType( (*legacy_struct_value_vtable.get_type)(message_ptr_, type_info_)); } absl::string_view LegacyStructValue::GetTypeName() const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_type_name)(message_ptr_, type_info_); } std::string LegacyStructValue::DebugString() const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.debug_string)(message_ptr_, type_info_); } absl::StatusOr<size_t> LegacyStructValue::GetSerializedSize( AnyToJsonConverter&) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_serialized_size)(message_ptr_, type_info_); } absl::Status LegacyStructValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.serialize_to)(message_ptr_, type_info_, value); } absl::StatusOr<absl::Cord> LegacyStructValue::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord serialized_value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, serialized_value)); return serialized_value; } absl::StatusOr<std::string> LegacyStructValue::GetTypeUrl( absl::string_view prefix) const { InitializeLegacyStructValue(); return MakeTypeUrlWithPrefix( prefix, (*legacy_struct_value_vtable.get_type_name)(message_ptr_, type_info_)); } absl::StatusOr<Any> LegacyStructValue::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto serialized_value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(serialized_value)); } absl::StatusOr<Json> LegacyStructValue::ConvertToJson( AnyToJsonConverter& value_manager) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.convert_to_json_object)(message_ptr_, type_info_); } absl::Status LegacyStructValue::Equal(ValueManager& value_manager, ValueView other, Value& result) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.equal)(message_ptr_, type_info_, value_manager, other, result); } bool LegacyStructValue::IsZeroValue() const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.is_zero_value)(message_ptr_, type_info_); } absl::Status LegacyStructValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_field_by_name)( message_ptr_, type_info_, value_manager, name, result, unboxing_options); } absl::Status LegacyStructValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_field_by_number)( message_ptr_, type_info_, value_manager, number, result, unboxing_options); } absl::StatusOr<bool> LegacyStructValue::HasFieldByName( absl::string_view name) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.has_field_by_name)(message_ptr_, type_info_, name); } absl::StatusOr<bool> LegacyStructValue::HasFieldByNumber(int64_t number) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.has_field_by_number)(message_ptr_, type_info_, number); } absl::Status LegacyStructValue::ForEachField( ValueManager& value_manager, ForEachFieldCallback callback) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.for_each_field)(message_ptr_, type_info_, value_manager, callback); } absl::StatusOr<int> LegacyStructValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.qualify)(message_ptr_, type_info_, value_manager, qualifiers, presence_test, result); } StructType LegacyStructValueView::GetType(TypeManager& type_manager) const { InitializeLegacyStructValue(); return type_manager.CreateStructType( (*legacy_struct_value_vtable.get_type)(message_ptr_, type_info_)); } absl::string_view LegacyStructValueView::GetTypeName() const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_type_name)(message_ptr_, type_info_); } std::string LegacyStructValueView::DebugString() const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.debug_string)(message_ptr_, type_info_); } absl::StatusOr<size_t> LegacyStructValueView::GetSerializedSize( AnyToJsonConverter&) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_serialized_size)(message_ptr_, type_info_); } absl::Status LegacyStructValueView::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.serialize_to)(message_ptr_, type_info_, value); } absl::StatusOr<absl::Cord> LegacyStructValueView::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord serialized_value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, serialized_value)); return serialized_value; } absl::StatusOr<std::string> LegacyStructValueView::GetTypeUrl( absl::string_view prefix) const { InitializeLegacyStructValue(); return MakeTypeUrlWithPrefix( prefix, (*legacy_struct_value_vtable.get_type_name)(message_ptr_, type_info_)); } absl::StatusOr<Any> LegacyStructValueView::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto serialized_value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(serialized_value)); } absl::StatusOr<Json> LegacyStructValueView::ConvertToJson( AnyToJsonConverter& value_manager) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.convert_to_json_object)(message_ptr_, type_info_); } absl::Status LegacyStructValueView::Equal(ValueManager& value_manager, ValueView other, Value& result) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.equal)(message_ptr_, type_info_, value_manager, other, result); } bool LegacyStructValueView::IsZeroValue() const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.is_zero_value)(message_ptr_, type_info_); } absl::Status LegacyStructValueView::GetFieldByName( ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_field_by_name)( message_ptr_, type_info_, value_manager, name, result, unboxing_options); } absl::Status LegacyStructValueView::GetFieldByNumber( ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.get_field_by_number)( message_ptr_, type_info_, value_manager, number, result, unboxing_options); } absl::StatusOr<bool> LegacyStructValueView::HasFieldByName( absl::string_view name) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.has_field_by_name)(message_ptr_, type_info_, name); } absl::StatusOr<bool> LegacyStructValueView::HasFieldByNumber( int64_t number) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.has_field_by_number)(message_ptr_, type_info_, number); } absl::Status LegacyStructValueView::ForEachField( ValueManager& value_manager, ForEachFieldCallback callback) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.for_each_field)(message_ptr_, type_info_, value_manager, callback); } absl::StatusOr<int> LegacyStructValueView::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.qualify)(message_ptr_, type_info_, value_manager, qualifiers, presence_test, result); } }
#include "common/values/legacy_struct_value.h" #include "common/memory.h" #include "common/value_kind.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel::common_internal { namespace { using testing::_; class LegacyStructValueTest : public ThreadCompatibleValueTest<> {}; TEST_P(LegacyStructValueTest, Kind) { EXPECT_EQ(LegacyStructValue(0, 0).kind(), ValueKind::kStruct); } TEST_P(LegacyStructValueTest, GetType) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).GetType(type_manager())), _); } TEST_P(LegacyStructValueTest, GetTypeName) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetTypeName()), _); } TEST_P(LegacyStructValueTest, DebugString) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).DebugString()), _); } TEST_P(LegacyStructValueTest, GetSerializedSize) { EXPECT_DEATH(static_cast<void>( LegacyStructValue(0, 0).GetSerializedSize(value_manager())), _); } TEST_P(LegacyStructValueTest, Serialize) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).Serialize(value_manager())), _); } TEST_P(LegacyStructValueTest, SerializeTo) { absl::Cord serialize_value; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).SerializeTo( value_manager(), serialize_value)), _); } TEST_P(LegacyStructValueTest, GetTypeUrl) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetTypeUrl()), _); } TEST_P(LegacyStructValueTest, ConvertToAny) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).ConvertToAny(value_manager())), _); } TEST_P(LegacyStructValueTest, ConvertToJson) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).ConvertToJson(value_manager())), _); } TEST_P(LegacyStructValueTest, GetFieldByName) { Value scratch; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetFieldByName( value_manager(), "", scratch)), _); } TEST_P(LegacyStructValueTest, GetFieldByNumber) { Value scratch; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetFieldByNumber( value_manager(), 0, scratch)), _); } TEST_P(LegacyStructValueTest, HasFieldByName) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).HasFieldByName("")), _); } TEST_P(LegacyStructValueTest, HasFieldByNumber) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).HasFieldByNumber(0)), _); } INSTANTIATE_TEST_SUITE_P( LegacyStructValueTest, LegacyStructValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), LegacyStructValueTest::ToString); class LegacyStructValueViewTest : public ThreadCompatibleValueTest<> {}; TEST_P(LegacyStructValueViewTest, Kind) { EXPECT_EQ(LegacyStructValue(0, 0).kind(), ValueKind::kStruct); } TEST_P(LegacyStructValueViewTest, GetType) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).GetType(type_manager())), _); } TEST_P(LegacyStructValueViewTest, GetTypeName) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetTypeName()), _); } TEST_P(LegacyStructValueViewTest, DebugString) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).DebugString()), _); } TEST_P(LegacyStructValueViewTest, GetSerializedSize) { EXPECT_DEATH(static_cast<void>( LegacyStructValue(0, 0).GetSerializedSize(value_manager())), _); } TEST_P(LegacyStructValueViewTest, Serialize) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).Serialize(value_manager())), _); } TEST_P(LegacyStructValueViewTest, SerializeTo) { absl::Cord serialize_value; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).SerializeTo( value_manager(), serialize_value)), _); } TEST_P(LegacyStructValueViewTest, GetTypeUrl) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetTypeUrl()), _); } TEST_P(LegacyStructValueViewTest, ConvertToAny) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).ConvertToAny(value_manager())), _); } TEST_P(LegacyStructValueViewTest, ConvertToJson) { EXPECT_DEATH( static_cast<void>(LegacyStructValue(0, 0).ConvertToJson(value_manager())), _); } TEST_P(LegacyStructValueViewTest, GetFieldByName) { Value scratch; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetFieldByName( value_manager(), "", scratch)), _); } TEST_P(LegacyStructValueViewTest, GetFieldByNumber) { Value scratch; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).GetFieldByNumber( value_manager(), 0, scratch)), _); } TEST_P(LegacyStructValueViewTest, HasFieldByName) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).HasFieldByName("")), _); } TEST_P(LegacyStructValueViewTest, HasFieldByNumber) { EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).HasFieldByNumber(0)), _); } INSTANTIATE_TEST_SUITE_P( LegacyStructValueViewTest, LegacyStructValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), LegacyStructValueViewTest::ToString); } }
39
cpp
google/cel-cpp
string_value
common/values/string_value.cc
common/values/string_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_STRING_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_STRING_VALUE_H_ #include <cstddef> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/internal/arena_string.h" #include "common/internal/shared_byte_string.h" #include "common/json.h" #include "common/type.h" #include "common/type_manager.h" #include "common/value_kind.h" #include "common/values/values.h" namespace cel { class Value; class ValueView; class ValueManager; class StringValue; class StringValueView; class TypeManager; class StringValue final { public: using view_alternative_type = StringValueView; static constexpr ValueKind kKind = ValueKind::kString; static StringValue Concat(ValueManager&, StringValueView lhs, StringValueView rhs); explicit StringValue(absl::Cord value) noexcept : value_(std::move(value)) {} explicit StringValue(absl::string_view value) noexcept : value_(absl::Cord(value)) {} explicit StringValue(common_internal::ArenaString value) noexcept : value_(value) {} explicit StringValue(common_internal::SharedByteString value) noexcept : value_(std::move(value)) {} template <typename T, typename = std::enable_if_t<std::is_same_v< absl::remove_cvref_t<T>, std::string>>> explicit StringValue(T&& data) : value_(absl::Cord(std::forward<T>(data))) {} #if ABSL_HAVE_ATTRIBUTE(enable_if) template <size_t N> explicit StringValue(const char (&data)[N]) __attribute__((enable_if(::cel::common_internal::IsStringLiteral(data), "chosen when 'data' is a string literal"))) : value_(absl::string_view(data)) {} #endif explicit StringValue(StringValueView value) noexcept; StringValue() = default; StringValue(const StringValue&) = default; StringValue(StringValue&&) = default; StringValue& operator=(const StringValue&) = default; StringValue& operator=(StringValue&&) = default; constexpr ValueKind kind() const { return kKind; } StringType GetType(TypeManager&) const { return StringType(); } absl::string_view GetTypeName() const { return StringType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue([](const auto& value) -> bool { return value.empty(); }); } std::string NativeString() const { return value_.ToString(); } absl::string_view NativeString( std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return value_.ToString(scratch); } absl::Cord NativeCord() const { return value_.ToCord(); } template <typename Visitor> std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>, std::invoke_result_t<Visitor, const absl::Cord&>> NativeValue(Visitor&& visitor) const { return value_.Visit(std::forward<Visitor>(visitor)); } void swap(StringValue& other) noexcept { using std::swap; swap(value_, other.value_); } size_t Size() const; bool IsEmpty() const; bool Equals(absl::string_view string) const; bool Equals(const absl::Cord& string) const; bool Equals(StringValueView string) const; int Compare(absl::string_view string) const; int Compare(const absl::Cord& string) const; int Compare(StringValueView string) const; std::string ToString() const { return NativeString(); } absl::Cord ToCord() const { return NativeCord(); } template <typename H> friend H AbslHashValue(H state, const StringValue& string) { return H::combine(std::move(state), string.value_); } friend bool operator==(const StringValue& lhs, const StringValue& rhs) { return lhs.value_ == rhs.value_; } friend bool operator<(const StringValue& lhs, const StringValue& rhs) { return lhs.value_ < rhs.value_; } private: friend class StringValueView; friend const common_internal::SharedByteString& common_internal::AsSharedByteString(const StringValue& value); common_internal::SharedByteString value_; }; inline void swap(StringValue& lhs, StringValue& rhs) noexcept { lhs.swap(rhs); } inline bool operator==(const StringValue& lhs, absl::string_view rhs) { return lhs.Equals(rhs); } inline bool operator==(absl::string_view lhs, const StringValue& rhs) { return rhs == lhs; } inline bool operator!=(const StringValue& lhs, absl::string_view rhs) { return !operator==(lhs, rhs); } inline bool operator!=(absl::string_view lhs, const StringValue& rhs) { return !operator==(lhs, rhs); } inline bool operator!=(const StringValue& lhs, const StringValue& rhs) { return !operator==(lhs, rhs); } inline std::ostream& operator<<(std::ostream& out, const StringValue& value) { return out << value.DebugString(); } class StringValueView final { public: using alternative_type = StringValue; static constexpr ValueKind kKind = StringValue::kKind; explicit StringValueView( const absl::Cord& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(value) {} explicit StringValueView(absl::string_view value) noexcept : value_(value) {} explicit StringValueView(common_internal::ArenaString value) noexcept : value_(value) {} explicit StringValueView(common_internal::SharedByteStringView value) noexcept : value_(value) {} StringValueView( const StringValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : value_(value.value_) {} StringValueView& operator=( const StringValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) { value_ = value.value_; return *this; } StringValueView& operator=(StringValue&&) = delete; StringValueView() = default; StringValueView(const StringValueView&) = default; StringValueView(StringValueView&&) = default; StringValueView& operator=(const StringValueView&) = default; StringValueView& operator=(StringValueView&&) = default; constexpr ValueKind kind() const { return kKind; } StringType GetType(TypeManager&) const { return StringType(); } absl::string_view GetTypeName() const { return StringType::kName; } std::string DebugString() const; absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const; absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const; absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const; absl::StatusOr<std::string> GetTypeUrl( absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Any> ConvertToAny( AnyToJsonConverter&, absl::string_view prefix = kTypeGoogleApisComPrefix) const; absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const; absl::Status Equal(ValueManager& value_manager, ValueView other, Value& result) const; absl::StatusOr<Value> Equal(ValueManager& value_manager, ValueView other) const; bool IsZeroValue() const { return NativeValue([](const auto& value) -> bool { return value.empty(); }); } std::string NativeString() const { return value_.ToString(); } absl::string_view NativeString( std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return value_.ToString(scratch); } absl::Cord NativeCord() const { return value_.ToCord(); } template <typename Visitor> std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>, std::invoke_result_t<Visitor, const absl::Cord&>> NativeValue(Visitor&& visitor) const { return value_.Visit(std::forward<Visitor>(visitor)); } void swap(StringValueView& other) noexcept { using std::swap; swap(value_, other.value_); } size_t Size() const; bool IsEmpty() const; bool Equals(absl::string_view string) const; bool Equals(const absl::Cord& string) const; bool Equals(StringValueView string) const; int Compare(absl::string_view string) const; int Compare(const absl::Cord& string) const; int Compare(StringValueView string) const; std::string ToString() const { return NativeString(); } absl::Cord ToCord() const { return NativeCord(); } template <typename H> friend H AbslHashValue(H state, StringValueView string) { return H::combine(std::move(state), string.value_); } friend bool operator==(StringValueView lhs, StringValueView rhs) { return lhs.value_ == rhs.value_; } friend bool operator<(StringValueView lhs, StringValueView rhs) { return lhs.value_ < rhs.value_; } private: friend class StringValue; friend common_internal::SharedByteStringView common_internal::AsSharedByteStringView(StringValueView value); common_internal::SharedByteStringView value_; }; inline void swap(StringValueView& lhs, StringValueView& rhs) noexcept { lhs.swap(rhs); } inline bool operator==(StringValueView lhs, absl::string_view rhs) { return lhs == StringValueView(rhs); } inline bool operator==(absl::string_view lhs, StringValueView rhs) { return StringValueView(lhs) == rhs; } inline bool operator==(StringValueView lhs, const absl::Cord& rhs) { return lhs == StringValueView(rhs); } inline bool operator==(const absl::Cord& lhs, StringValueView rhs) { return StringValueView(lhs) == rhs; } inline bool operator!=(StringValueView lhs, StringValueView rhs) { return !operator==(lhs, rhs); } inline bool operator!=(StringValueView lhs, absl::string_view rhs) { return !operator==(lhs, rhs); } inline bool operator!=(absl::string_view lhs, StringValueView rhs) { return !operator==(lhs, rhs); } inline bool operator!=(StringValueView lhs, const absl::Cord& rhs) { return !operator==(lhs, rhs); } inline bool operator!=(const absl::Cord& lhs, StringValueView rhs) { return !operator==(lhs, rhs); } inline bool operator<(StringValueView lhs, absl::string_view rhs) { return lhs < StringValueView(rhs); } inline bool operator<(absl::string_view lhs, StringValueView rhs) { return StringValueView(lhs) < rhs; } inline bool operator<(StringValueView lhs, const absl::Cord& rhs) { return lhs < StringValueView(rhs); } inline bool operator<(const absl::Cord& lhs, StringValueView rhs) { return StringValueView(lhs) < rhs; } inline std::ostream& operator<<(std::ostream& out, StringValueView value) { return out << value.DebugString(); } inline StringValue::StringValue(StringValueView value) noexcept : value_(value.value_) {} inline StringValue StringValue::Concat(ValueManager&, StringValueView lhs, StringValueView rhs) { absl::Cord result; result.Append(lhs.ToCord()); result.Append(rhs.ToCord()); return StringValue(std::move(result)); } namespace common_internal { inline const SharedByteString& AsSharedByteString(const StringValue& value) { return value.value_; } inline SharedByteStringView AsSharedByteStringView(StringValueView value) { return value.value_; } } } #endif #include <cstddef> #include <string> #include <utility> #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/value.h" #include "internal/serialize.h" #include "internal/status_macros.h" #include "internal/strings.h" #include "internal/utf8.h" namespace cel { namespace { template <typename Bytes> std::string StringDebugString(const Bytes& value) { return value.NativeValue(absl::Overload( [](absl::string_view string) -> std::string { return internal::FormatStringLiteral(string); }, [](const absl::Cord& cord) -> std::string { if (auto flat = cord.TryFlat(); flat.has_value()) { return internal::FormatStringLiteral(*flat); } return internal::FormatStringLiteral(static_cast<std::string>(cord)); })); } } std::string StringValue::DebugString() const { return StringDebugString(*this); } absl::StatusOr<size_t> StringValue::GetSerializedSize( AnyToJsonConverter&) const { return NativeValue([](const auto& bytes) -> size_t { return internal::SerializedStringValueSize(bytes); }); } absl::Status StringValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return NativeValue([&value](const auto& bytes) -> absl::Status { return internal::SerializeStringValue(bytes, value); }); } absl::StatusOr<absl::Cord> StringValue::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> StringValue::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.StringValue"); } absl::StatusOr<Any> StringValue::ConvertToAny(AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> StringValue::ConvertToJson(AnyToJsonConverter&) const { return NativeCord(); } absl::Status StringValue::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<StringValueView>(other); other_value.has_value()) { result = NativeValue([other_value](const auto& value) -> BoolValue { return other_value->NativeValue( [&value](const auto& other_value) -> BoolValue { return BoolValue{value == other_value}; }); }); return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } size_t StringValue::Size() const { return NativeValue([](const auto& alternative) -> size_t { return internal::Utf8CodePointCount(alternative); }); } bool StringValue::IsEmpty() const { return NativeValue( [](const auto& alternative) -> bool { return alternative.empty(); }); } bool StringValue::Equals(absl::string_view string) const { return NativeValue([string](const auto& alternative) -> bool { return alternative == string; }); } bool StringValue::Equals(const absl::Cord& string) const { return NativeValue([&string](const auto& alternative) -> bool { return alternative == string; }); } bool StringValue::Equals(StringValueView string) const { return string.NativeValue( [this](const auto& alternative) -> bool { return Equals(alternative); }); } namespace { int CompareImpl(absl::string_view lhs, absl::string_view rhs) { return lhs.compare(rhs); } int CompareImpl(absl::string_view lhs, const absl::Cord& rhs) { return -rhs.Compare(lhs); } int CompareImpl(const absl::Cord& lhs, absl::string_view rhs) { return lhs.Compare(rhs); } int CompareImpl(const absl::Cord& lhs, const absl::Cord& rhs) { return lhs.Compare(rhs); } } int StringValue::Compare(absl::string_view string) const { return NativeValue([string](const auto& alternative) -> int { return CompareImpl(alternative, string); }); } int StringValue::Compare(const absl::Cord& string) const { return NativeValue([&string](const auto& alternative) -> int { return CompareImpl(alternative, string); }); } int StringValue::Compare(StringValueView string) const { return string.NativeValue( [this](const auto& alternative) -> int { return Compare(alternative); }); } std::string StringValueView::DebugString() const { return StringDebugString(*this); } absl::StatusOr<size_t> StringValueView::GetSerializedSize( AnyToJsonConverter&) const { return NativeValue([](const auto& bytes) -> size_t { return internal::SerializedStringValueSize(bytes); }); } absl::Status StringValueView::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return NativeValue([&value](const auto& bytes) -> absl::Status { return internal::SerializeStringValue(bytes, value); }); } absl::StatusOr<absl::Cord> StringValueView::Serialize( AnyToJsonConverter& value_manager) const { absl::Cord value; CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value)); return value; } absl::StatusOr<std::string> StringValueView::GetTypeUrl( absl::string_view prefix) const { return MakeTypeUrlWithPrefix(prefix, "google.protobuf.StringValue"); } absl::StatusOr<Any> StringValueView::ConvertToAny( AnyToJsonConverter& value_manager, absl::string_view prefix) const { CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager)); CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix)); return MakeAny(std::move(type_url), std::move(value)); } absl::StatusOr<Json> StringValueView::ConvertToJson(AnyToJsonConverter&) const { return NativeCord(); } absl::Status StringValueView::Equal(ValueManager&, ValueView other, Value& result) const { if (auto other_value = As<StringValueView>(other); other_value.has_value()) { result = NativeValue([other_value](const auto& value) -> BoolValue { return other_value->NativeValue( [&value](const auto& other_value) -> BoolValue { return BoolValue{value == other_value}; }); }); return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } size_t StringValueView::Size() const { return NativeValue([](const auto& alternative) -> size_t { return internal::Utf8CodePointCount(alternative); }); } bool StringValueView::IsEmpty() const { return NativeValue( [](const auto& alternative) -> bool { return alternative.empty(); }); } bool StringValueView::Equals(absl::string_view string) const { return NativeValue([string](const auto& alternative) -> bool { return alternative == string; }); } bool StringValueView::Equals(const absl::Cord& string) const { return NativeValue([&string](const auto& alternative) -> bool { return alternative == string; }); } bool StringValueView::Equals(StringValueView string) const { return string.NativeValue( [this](const auto& alternative) -> bool { return Equals(alternative); }); } int StringValueView::Compare(absl::string_view string) const { return NativeValue([string](const auto& alternative) -> int { return CompareImpl(alternative, string); }); } int StringValueView::Compare(const absl::Cord& string) const { return NativeValue([&string](const auto& alternative) -> int { return CompareImpl(alternative, string); }); } int StringValueView::Compare(StringValueView string) const { return string.NativeValue( [this](const auto& alternative) -> int { return Compare(alternative); }); } }
#include <sstream> #include <string> #include "absl/hash/hash.h" #include "absl/strings/cord.h" #include "absl/strings/cord_test_helpers.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/casting.h" #include "common/json.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using cel::internal::IsOkAndHolds; using StringValueTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(StringValueTest, Kind) { EXPECT_EQ(StringValue("foo").kind(), StringValue::kKind); EXPECT_EQ(Value(StringValue(absl::Cord("foo"))).kind(), StringValue::kKind); } TEST_P(StringValueTest, DebugString) { { std::ostringstream out; out << StringValue("foo"); EXPECT_EQ(out.str(), "\"foo\""); } { std::ostringstream out; out << StringValue(absl::MakeFragmentedCord({"f", "o", "o"})); EXPECT_EQ(out.str(), "\"foo\""); } { std::ostringstream out; out << Value(StringValue(absl::Cord("foo"))); EXPECT_EQ(out.str(), "\"foo\""); } } TEST_P(StringValueTest, GetSerializedSize) { EXPECT_THAT(StringValue().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(StringValueTest, ConvertToAny) { EXPECT_THAT(StringValue().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.StringValue"), absl::Cord()))); } TEST_P(StringValueTest, ConvertToJson) { EXPECT_THAT(StringValue("foo").ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonString("foo")))); } TEST_P(StringValueTest, NativeValue) { std::string scratch; EXPECT_EQ(StringValue("foo").NativeString(), "foo"); EXPECT_EQ(StringValue("foo").NativeString(scratch), "foo"); EXPECT_EQ(StringValue("foo").NativeCord(), "foo"); } TEST_P(StringValueTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(StringValue("foo")), NativeTypeId::For<StringValue>()); EXPECT_EQ(NativeTypeId::Of(Value(StringValue(absl::Cord("foo")))), NativeTypeId::For<StringValue>()); } TEST_P(StringValueTest, InstanceOf) { EXPECT_TRUE(InstanceOf<StringValue>(StringValue("foo"))); EXPECT_TRUE(InstanceOf<StringValue>(Value(StringValue(absl::Cord("foo"))))); } TEST_P(StringValueTest, Cast) { EXPECT_THAT(Cast<StringValue>(StringValue("foo")), An<StringValue>()); EXPECT_THAT(Cast<StringValue>(Value(StringValue(absl::Cord("foo")))), An<StringValue>()); } TEST_P(StringValueTest, As) { EXPECT_THAT(As<StringValue>(StringValue("foo")), Ne(absl::nullopt)); EXPECT_THAT(As<StringValue>(Value(StringValue(absl::Cord("foo")))), Ne(absl::nullopt)); } TEST_P(StringValueTest, HashValue) { EXPECT_EQ(absl::HashOf(StringValue("foo")), absl::HashOf(absl::string_view("foo"))); EXPECT_EQ(absl::HashOf(StringValue(absl::string_view("foo"))), absl::HashOf(absl::string_view("foo"))); EXPECT_EQ(absl::HashOf(StringValue(absl::Cord("foo"))), absl::HashOf(absl::string_view("foo"))); } TEST_P(StringValueTest, Equality) { EXPECT_NE(StringValue("foo"), "bar"); EXPECT_NE("bar", StringValue("foo")); EXPECT_NE(StringValue("foo"), StringValue("bar")); EXPECT_NE(StringValue("foo"), absl::Cord("bar")); EXPECT_NE(absl::Cord("bar"), StringValue("foo")); } TEST_P(StringValueTest, LessThan) { EXPECT_LT(StringValue("bar"), "foo"); EXPECT_LT("bar", StringValue("foo")); EXPECT_LT(StringValue("bar"), StringValue("foo")); EXPECT_LT(StringValue("bar"), absl::Cord("foo")); EXPECT_LT(absl::Cord("bar"), StringValue("foo")); } INSTANTIATE_TEST_SUITE_P( StringValueTest, StringValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), StringValueTest::ToString); using StringValueViewTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(StringValueViewTest, Kind) { EXPECT_EQ(StringValueView("foo").kind(), StringValueView::kKind); EXPECT_EQ(ValueView(StringValueView("foo")).kind(), StringValueView::kKind); } TEST_P(StringValueViewTest, DebugString) { { std::ostringstream out; out << StringValueView("foo"); EXPECT_EQ(out.str(), "\"foo\""); } { std::ostringstream out; out << ValueView(StringValueView("foo")); EXPECT_EQ(out.str(), "\"foo\""); } } TEST_P(StringValueViewTest, GetSerializedSize) { EXPECT_THAT(StringValueView().GetSerializedSize(value_manager()), IsOkAndHolds(0)); } TEST_P(StringValueViewTest, ConvertToAny) { EXPECT_THAT(StringValueView().ConvertToAny(value_manager()), IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.StringValue"), absl::Cord()))); } TEST_P(StringValueViewTest, ConvertToJson) { EXPECT_THAT(StringValueView("foo").ConvertToJson(value_manager()), IsOkAndHolds(Json(JsonString("foo")))); } TEST_P(StringValueViewTest, NativeValue) { std::string scratch; EXPECT_EQ(StringValueView(StringValue("foo")).NativeString(), "foo"); EXPECT_EQ(StringValueView(StringValue("foo")).NativeString(scratch), "foo"); EXPECT_EQ(StringValueView(StringValue("foo")).NativeCord(), "foo"); } TEST_P(StringValueViewTest, NativeTypeId) { EXPECT_EQ(NativeTypeId::Of(StringValueView("foo")), NativeTypeId::For<StringValueView>()); EXPECT_EQ(NativeTypeId::Of(ValueView(StringValueView("foo"))), NativeTypeId::For<StringValueView>()); } TEST_P(StringValueViewTest, InstanceOf) { EXPECT_TRUE(InstanceOf<StringValueView>(StringValueView("foo"))); EXPECT_TRUE(InstanceOf<StringValueView>(ValueView(StringValueView("foo")))); } TEST_P(StringValueViewTest, Cast) { EXPECT_THAT(Cast<StringValueView>(StringValueView("foo")), An<StringValueView>()); EXPECT_THAT(Cast<StringValueView>(ValueView(StringValueView("foo"))), An<StringValueView>()); } TEST_P(StringValueViewTest, As) { EXPECT_THAT(As<StringValueView>(StringValueView("foo")), Ne(absl::nullopt)); EXPECT_THAT(As<StringValueView>(ValueView(StringValueView("foo"))), Ne(absl::nullopt)); } TEST_P(StringValueViewTest, HashValue) { EXPECT_EQ(absl::HashOf(StringValueView("foo")), absl::HashOf(absl::string_view("foo"))); EXPECT_EQ(absl::HashOf(StringValueView(absl::string_view("foo"))), absl::HashOf(absl::string_view("foo"))); EXPECT_EQ(absl::HashOf(StringValueView(absl::Cord("foo"))), absl::HashOf(absl::string_view("foo"))); } TEST_P(StringValueViewTest, Equality) { EXPECT_NE(StringValueView("foo"), "bar"); EXPECT_NE("bar", StringValueView("foo")); EXPECT_NE(StringValueView("foo"), StringValueView("bar")); EXPECT_NE(StringValueView("foo"), absl::Cord("bar")); EXPECT_NE(absl::Cord("bar"), StringValueView("foo")); EXPECT_NE(StringValueView("foo"), StringValue("bar")); EXPECT_NE(StringValue("bar"), StringValueView("foo")); } TEST_P(StringValueViewTest, LessThan) { EXPECT_LT(StringValueView("bar"), "foo"); EXPECT_LT("bar", StringValueView("foo")); EXPECT_LT(StringValueView("bar"), StringValueView("foo")); EXPECT_LT(StringValueView("bar"), absl::Cord("foo")); EXPECT_LT(absl::Cord("bar"), StringValueView("foo")); EXPECT_LT(StringValueView("bar"), StringValue("foo")); EXPECT_LT(StringValue("bar"), StringValueView("foo")); } INSTANTIATE_TEST_SUITE_P( StringValueViewTest, StringValueViewTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), StringValueViewTest::ToString); } }
40
cpp
google/cel-cpp
optional_value
common/values/optional_value.cc
common/values/optional_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_OPTIONAL_VALUE_H_ #define THIRD_PARTY_CEL_CPP_COMMON_VALUES_OPTIONAL_VALUE_H_ #include <memory> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "common/casting.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type.h" #include "common/value_interface.h" #include "common/value_kind.h" #include "common/values/opaque_value.h" #include "internal/status_macros.h" namespace cel { class ValueView; class Value; class ValueManager; class OptionalValueInterface; class OptionalValue; class OptionalValueView; class OptionalValueInterface : public OpaqueValueInterface { public: using alternative_type = OptionalValue; using view_alternative_type = OptionalValueView; OptionalType GetType(TypeManager& type_manager) const { return Cast<OptionalType>(GetTypeImpl(type_manager)); } absl::string_view GetTypeName() const final { return "optional_type"; } std::string DebugString() const final; virtual bool HasValue() const = 0; absl::Status Equal(ValueManager& value_manager, ValueView other, cel::Value& result) const override; virtual void Value(cel::Value& scratch) const = 0; cel::Value Value() const; private: Type GetTypeImpl(TypeManager&) const override { return OptionalType(); } NativeTypeId GetNativeTypeId() const noexcept final { return NativeTypeId::For<OptionalValueInterface>(); } }; template <> struct SubsumptionTraits<OptionalValueInterface> { static bool IsA(const ValueInterface& interface) { return interface.kind() == ValueKind::kOpaque && NativeTypeId::Of(interface) == NativeTypeId::For<OptionalValueInterface>(); } }; class OptionalValue final : public OpaqueValue { public: using interface_type = OptionalValueInterface; using view_alternative_type = OptionalValueView; ABSL_ATTRIBUTE_PURE_FUNCTION static OptionalValue None(); static OptionalValue Of(MemoryManagerRef memory_manager, cel::Value value); explicit OptionalValue(OptionalValueView value); OptionalValue() : OptionalValue(None()) {} OptionalValue(const OptionalValue&) = default; OptionalValue(OptionalValue&&) = default; OptionalValue& operator=(const OptionalValue&) = default; OptionalValue& operator=(OptionalValue&&) = default; template <typename T, typename = std::enable_if_t<std::is_base_of_v< OptionalValueInterface, std::remove_const_t<T>>>> OptionalValue(Shared<T> interface) : OpaqueValue(std::move(interface)) {} OptionalType GetType(TypeManager& type_manager) const { return (*this)->GetType(type_manager); } bool HasValue() const { return (*this)->HasValue(); } void Value(cel::Value& result) const; cel::Value Value() const; const interface_type& operator*() const { return Cast<OptionalValueInterface>(OpaqueValue::operator*()); } absl::Nonnull<const interface_type*> operator->() const { return Cast<OptionalValueInterface>(OpaqueValue::operator->()); } private: friend struct SubsumptionTraits<OptionalValue>; explicit OptionalValue(OpaqueValue&& value) noexcept : OpaqueValue(std::move(value)) {} }; template <> struct SubsumptionTraits<OptionalValue> final { static bool IsA(const OpaqueValue& value) { return NativeTypeId::Of(value) == NativeTypeId::For<OptionalValueInterface>(); } static const OptionalValue& DownCast(const OpaqueValue& value) { ABSL_DCHECK(IsA(value)); return *reinterpret_cast<const OptionalValue*>(std::addressof(value)); } static OptionalValue& DownCast(OpaqueValue& value) { ABSL_DCHECK(IsA(value)); return *reinterpret_cast<OptionalValue*>(std::addressof(value)); } static OptionalValue DownCast(OpaqueValue&& value) { ABSL_DCHECK(IsA(value)); return OptionalValue(std::move(value)); } }; class OptionalValueView final : public OpaqueValueView { public: using interface_type = OptionalValueInterface; using alternative_type = OptionalValue; ABSL_ATTRIBUTE_PURE_FUNCTION static OptionalValueView None(); OptionalValueView() : OptionalValueView(None()) {} OptionalValueView(SharedView<const OptionalValueInterface> interface) : OpaqueValueView(interface) {} OptionalValueView( const OptionalValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : OpaqueValueView(value) {} OptionalValueView& operator=( const OptionalValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) { OpaqueValueView::operator=(value); return *this; } OptionalValueView& operator=(OptionalValue&&) = delete; OptionalValueView(const OptionalValueView&) = default; OptionalValueView& operator=(const OptionalValueView&) = default; OptionalType GetType(TypeManager& type_manager) const { return (*this)->GetType(type_manager); } bool HasValue() const { return (*this)->HasValue(); } void Value(cel::Value& result) const; cel::Value Value() const; const interface_type& operator*() const { return Cast<OptionalValueInterface>(OpaqueValueView::operator*()); } absl::Nonnull<const interface_type*> operator->() const { return Cast<OptionalValueInterface>(OpaqueValueView::operator->()); } private: friend struct SubsumptionTraits<OptionalValueView>; explicit OptionalValueView(OpaqueValueView value) noexcept : OpaqueValueView(value) {} }; inline OptionalValue::OptionalValue(OptionalValueView value) : OpaqueValue(value) {} template <> struct SubsumptionTraits<OptionalValueView> final { static bool IsA(OpaqueValueView value) { return NativeTypeId::Of(value) == NativeTypeId::For<OptionalValueInterface>(); } static OptionalValueView DownCast(OpaqueValueView value) { ABSL_DCHECK(IsA(value)); return OptionalValueView(value); } }; } #endif #include <string> #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 "common/casting.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type.h" #include "common/value.h" #include "common/value_kind.h" namespace cel { namespace { class FullOptionalValue final : public OptionalValueInterface { public: explicit FullOptionalValue(cel::Value value) : value_(std::move(value)) {} bool HasValue() const override { return true; } void Value(cel::Value& result) const override { result = value_; } private: friend struct NativeTypeTraits<FullOptionalValue>; Type GetTypeImpl(TypeManager& type_manager) const override { return type_manager.CreateOptionalType(value_.GetType(type_manager)); } const cel::Value value_; }; } template <> struct NativeTypeTraits<FullOptionalValue> { static bool SkipDestructor(const FullOptionalValue& value) { return NativeType::SkipDestructor(value.value_); } }; std::string OptionalValueInterface::DebugString() const { if (HasValue()) { return absl::StrCat("optional(", Value().DebugString(), ")"); } return "optional.none()"; } OptionalValue OptionalValue::Of(MemoryManagerRef memory_manager, cel::Value value) { ABSL_DCHECK(value.kind() != ValueKind::kError && value.kind() != ValueKind::kUnknown); return OptionalValue( memory_manager.MakeShared<FullOptionalValue>(std::move(value))); } absl::Status OptionalValueInterface::Equal(ValueManager& value_manager, ValueView other, cel::Value& result) const { if (auto other_value = As<OptionalValueView>(other); other_value.has_value()) { if (HasValue() != other_value->HasValue()) { result = BoolValueView{false}; return absl::OkStatus(); } if (!HasValue()) { result = BoolValueView{true}; return absl::OkStatus(); } return Value().Equal(value_manager, other_value->Value(), result); return absl::OkStatus(); } result = BoolValueView{false}; return absl::OkStatus(); } }
#include <sstream> #include <utility> #include "absl/status/status.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_testing.h" #include "internal/testing.h" namespace cel { namespace { using testing::An; using testing::Ne; using testing::TestParamInfo; using cel::internal::StatusIs; class OptionalValueTest : public common_internal::ThreadCompatibleValueTest<> { public: OptionalValue OptionalNone() { return OptionalValue::None(); } OptionalValue OptionalOf(Value value) { return OptionalValue::Of(memory_manager(), std::move(value)); } }; TEST_P(OptionalValueTest, Kind) { auto value = OptionalNone(); EXPECT_EQ(value.kind(), OptionalValue::kKind); EXPECT_EQ(OpaqueValue(value).kind(), OptionalValue::kKind); EXPECT_EQ(Value(value).kind(), OptionalValue::kKind); } TEST_P(OptionalValueTest, Type) { auto value = OptionalNone(); EXPECT_EQ(value.GetType(type_manager()), OptionalType()); EXPECT_EQ(OpaqueValue(value).GetType(type_manager()), OptionalType()); EXPECT_EQ(Value(value).GetType(type_manager()), OptionalType()); } TEST_P(OptionalValueTest, DebugString) { auto value = OptionalNone(); { std::ostringstream out; out << value; EXPECT_EQ(out.str(), "optional.none()"); } { std::ostringstream out; out << OpaqueValue(value); EXPECT_EQ(out.str(), "optional.none()"); } { std::ostringstream out; out << Value(value); EXPECT_EQ(out.str(), "optional.none()"); } { std::ostringstream out; out << OptionalOf(IntValue()); EXPECT_EQ(out.str(), "optional(0)"); } } TEST_P(OptionalValueTest, GetSerializedSize) { EXPECT_THAT(OptionalValue().GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueTest, SerializeTo) { absl::Cord value; EXPECT_THAT(OptionalValue().SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueTest, Serialize) { EXPECT_THAT(OptionalValue().Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueTest, GetTypeUrl) { EXPECT_THAT(OptionalValue().GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueTest, ConvertToAny) { EXPECT_THAT(OptionalValue().ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueTest, ConvertToJson) { EXPECT_THAT(OptionalValue().ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueTest, InstanceOf) { auto value = OptionalNone(); EXPECT_TRUE(InstanceOf<OptionalValue>(value)); EXPECT_TRUE(InstanceOf<OptionalValue>(OpaqueValue(value))); EXPECT_TRUE(InstanceOf<OptionalValue>(Value(value))); } TEST_P(OptionalValueTest, Cast) { auto value = OptionalNone(); EXPECT_THAT(Cast<OptionalValue>(value), An<OptionalValue>()); EXPECT_THAT(Cast<OptionalValue>(OpaqueValue(value)), An<OptionalValue>()); EXPECT_THAT(Cast<OptionalValue>(Value(value)), An<OptionalValue>()); } TEST_P(OptionalValueTest, As) { auto value = OptionalNone(); EXPECT_THAT(As<OptionalValue>(value), Ne(absl::nullopt)); EXPECT_THAT(As<OptionalValue>(OpaqueValue(value)), Ne(absl::nullopt)); EXPECT_THAT(As<OptionalValue>(Value(value)), Ne(absl::nullopt)); } TEST_P(OptionalValueTest, HasValue) { auto value = OptionalNone(); EXPECT_FALSE(value.HasValue()); value = OptionalOf(IntValue()); EXPECT_TRUE(value.HasValue()); } TEST_P(OptionalValueTest, Value) { auto value = OptionalNone(); auto element = value.Value(); ASSERT_TRUE(InstanceOf<ErrorValue>(element)); EXPECT_THAT(Cast<ErrorValue>(element).NativeValue(), StatusIs(absl::StatusCode::kFailedPrecondition)); value = OptionalOf(IntValue()); element = value.Value(); ASSERT_TRUE(InstanceOf<IntValue>(element)); EXPECT_EQ(Cast<IntValue>(element), IntValue()); } INSTANTIATE_TEST_SUITE_P( OptionalValueTest, OptionalValueTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), OptionalValueTest::ToString); class OptionalValueViewTest : public common_internal::ThreadCompatibleValueTest<> { public: OptionalValueView OptionalNone() { return OptionalValueView::None(); } OptionalValue OptionalOf(Value value) { return OptionalValue::Of(memory_manager(), std::move(value)); } }; TEST_P(OptionalValueViewTest, Kind) { auto value = OptionalNone(); EXPECT_EQ(value.kind(), OptionalValueView::kKind); EXPECT_EQ(OpaqueValueView(value).kind(), OptionalValueView::kKind); EXPECT_EQ(ValueView(value).kind(), OptionalValueView::kKind); } TEST_P(OptionalValueViewTest, Type) { auto value = OptionalNone(); EXPECT_EQ(value.GetType(type_manager()), OptionalType()); EXPECT_EQ(OpaqueValueView(value).GetType(type_manager()), OptionalType()); EXPECT_EQ(ValueView(value).GetType(type_manager()), OptionalType()); } TEST_P(OptionalValueViewTest, DebugString) { auto value = OptionalNone(); { std::ostringstream out; out << value; EXPECT_EQ(out.str(), "optional.none()"); } { std::ostringstream out; out << OpaqueValueView(value); EXPECT_EQ(out.str(), "optional.none()"); } { std::ostringstream out; out << ValueView(value); EXPECT_EQ(out.str(), "optional.none()"); } { std::ostringstream out; out << OptionalOf(IntValue()); EXPECT_EQ(out.str(), "optional(0)"); } } TEST_P(OptionalValueViewTest, GetSerializedSize) { EXPECT_THAT(OptionalValueView().GetSerializedSize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueViewTest, SerializeTo) { absl::Cord value; EXPECT_THAT(OptionalValueView().SerializeTo(value_manager(), value), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueViewTest, Serialize) { EXPECT_THAT(OptionalValueView().Serialize(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueViewTest, GetTypeUrl) { EXPECT_THAT(OptionalValueView().GetTypeUrl(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueViewTest, ConvertToAny) { EXPECT_THAT(OptionalValueView().ConvertToAny(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueViewTest, ConvertToJson) { EXPECT_THAT(OptionalValueView().ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(OptionalValueViewTest, InstanceOf) { auto value = OptionalNone(); EXPECT_TRUE(InstanceOf<OptionalValueView>(value)); EXPECT_TRUE(InstanceOf<OptionalValueView>(OpaqueValueView(value))); EXPECT_TRUE(InstanceOf<OptionalValueView>(ValueView(value))); } TEST_P(OptionalValueViewTest, Cast) { auto value = OptionalNone(); EXPECT_THAT(Cast<OptionalValueView>(value), An<OptionalValueView>()); EXPECT_THAT(Cast<OptionalValueView>(OpaqueValueView(value)), An<OptionalValueView>()); EXPECT_THAT(Cast<OptionalValueView>(ValueView(value)), An<OptionalValueView>()); } TEST_P(OptionalValueViewTest, As) { auto value = OptionalNone(); EXPECT_THAT(As<OptionalValueView>(value), Ne(absl::nullopt)); EXPECT_THAT(As<OptionalValueView>(OpaqueValueView(value)), Ne(absl::nullopt)); EXPECT_THAT(As<OptionalValueView>(ValueView(value)), Ne(absl::nullopt)); } TEST_P(OptionalValueViewTest, HasValue) { auto value_view = OptionalNone(); EXPECT_FALSE(value_view.HasValue()); auto value = OptionalOf(IntValue()); EXPECT_TRUE(OptionalValueView(value).HasValue()); } TEST_P(OptionalValueViewTest, Value) { auto value_view = OptionalNone(); auto element = value_view.Value(); ASSERT_TRUE(InstanceOf<ErrorValue>(element)); EXPECT_THAT(Cast<ErrorValue>(element).NativeValue(), StatusIs(absl::StatusCode::kFailedPrecondition)); auto value = OptionalOf(IntValue()); element = OptionalValueView(value).Value(); ASSERT_TRUE(InstanceOf<IntValue>(element)); EXPECT_EQ(Cast<IntValue>(element), IntValue()); } INSTANTIATE_TEST_SUITE_P( OptionalValueViewTest, OptionalValueViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), OptionalValueViewTest::ToString); } }
41
cpp
google/cel-cpp
exercise2
codelab/solutions/exercise2.cc
codelab/exercise2_test.cc
#ifndef THIRD_PARTY_CEL_CPP_CODELAB_EXERCISE1_H_ #define THIRD_PARTY_CEL_CPP_CODELAB_EXERCISE1_H_ #include <string> #include "google/rpc/context/attribute_context.pb.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" namespace google::api::expr::codelab { absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, bool bool_var); absl::StatusOr<bool> ParseAndEvaluate( absl::string_view cel_expr, const rpc::context::AttributeContext& context); } #endif #include "codelab/exercise2.h" #include <memory> #include <string> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "eval/public/activation.h" #include "eval/public/activation_bind_helper.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 "internal/status_macros.h" #include "parser/parser.h" namespace google::api::expr::codelab { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::BindProtoToActivation; using ::google::api::expr::runtime::CelError; using ::google::api::expr::runtime::CelExpression; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::ProtoUnsetFieldOptions; using ::google::api::expr::runtime::RegisterBuiltinFunctions; using ::google::rpc::context::AttributeContext; absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, const Activation& activation, google::protobuf::Arena* arena) { CEL_ASSIGN_OR_RETURN(ParsedExpr parsed_expr, Parse(cel_expr)); InterpreterOptions options; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); CEL_RETURN_IF_ERROR( RegisterBuiltinFunctions(builder->GetRegistry(), options)); CEL_ASSIGN_OR_RETURN(std::unique_ptr<CelExpression> expression_plan, builder->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); CEL_ASSIGN_OR_RETURN(CelValue result, expression_plan->Evaluate(activation, arena)); if (bool value; result.GetValue(&value)) { return value; } else if (const CelError * value; result.GetValue(&value)) { return *value; } else { return absl::InvalidArgumentError(absl::StrCat( "expected 'bool' result got '", result.DebugString(), "'")); } } } absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, bool bool_var) { Activation activation; google::protobuf::Arena arena; activation.InsertValue("bool_var", CelValue::CreateBool(bool_var)); return ParseAndEvaluate(cel_expr, activation, &arena); } absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, const AttributeContext& context) { Activation activation; google::protobuf::Arena arena; CEL_RETURN_IF_ERROR(BindProtoToActivation( &context, &arena, &activation, ProtoUnsetFieldOptions::kBindDefault)); return ParseAndEvaluate(cel_expr, activation, &arena); } }
#include "codelab/exercise2.h" #include "google/rpc/context/attribute_context.pb.h" #include "internal/testing.h" #include "google/protobuf/text_format.h" namespace google::api::expr::codelab { namespace { using ::google::rpc::context::AttributeContext; using ::google::protobuf::TextFormat; using testing::HasSubstr; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; TEST(Exercise2Var, Simple) { EXPECT_THAT(ParseAndEvaluate("bool_var", false), IsOkAndHolds(false)); EXPECT_THAT(ParseAndEvaluate("bool_var", true), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("bool_var || true", false), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("bool_var && false", true), IsOkAndHolds(false)); } TEST(Exercise2Var, WrongTypeResultError) { EXPECT_THAT(ParseAndEvaluate("'not a bool'", false), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 'bool' result got 'string"))); } TEST(Exercise2Context, Simple) { AttributeContext context; ASSERT_TRUE(TextFormat::ParseFromString(R"pb( source { ip: "192.168.28.1" } request { host: "www.example.com" } destination { ip: "192.168.56.1" } )pb", &context)); EXPECT_THAT(ParseAndEvaluate("source.ip == '192.168.28.1'", context), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("request.host == 'api.example.com'", context), IsOkAndHolds(false)); EXPECT_THAT(ParseAndEvaluate("request.host == 'www.example.com'", context), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("destination.ip != '192.168.56.1'", context), IsOkAndHolds(false)); } TEST(Exercise2Context, WrongTypeResultError) { AttributeContext context; EXPECT_THAT(ParseAndEvaluate("request.host", context), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 'bool' result got 'string"))); } } }
42
cpp
google/cel-cpp
exercise1
codelab/solutions/exercise1.cc
codelab/exercise1_test.cc
#ifndef THIRD_PARTY_CEL_CPP_CODELAB_EXERCISE1_H_ #define THIRD_PARTY_CEL_CPP_CODELAB_EXERCISE1_H_ #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" namespace google::api::expr::codelab { absl::StatusOr<std::string> ParseAndEvaluate(absl::string_view cel_expr); } #endif #include "codelab/exercise1.h" #include <memory> #include <string> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.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 "internal/status_macros.h" #include "parser/parser.h" namespace google::api::expr::codelab { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelExpression; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::RegisterBuiltinFunctions; absl::StatusOr<std::string> ConvertResult(const CelValue& value) { if (CelValue::StringHolder inner_value; value.GetValue(&inner_value)) { return std::string(inner_value.value()); } else { return absl::InvalidArgumentError(absl::StrCat( "expected string result got '", CelValue::TypeName(value.type()), "'")); } } } absl::StatusOr<std::string> ParseAndEvaluate(absl::string_view cel_expr) { InterpreterOptions options; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); CEL_RETURN_IF_ERROR( RegisterBuiltinFunctions(builder->GetRegistry(), options)); ParsedExpr parsed_expr; CEL_ASSIGN_OR_RETURN(parsed_expr, Parse(cel_expr)); google::protobuf::Arena arena; Activation activation; CEL_ASSIGN_OR_RETURN(std::unique_ptr<CelExpression> expression_plan, builder->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); CEL_ASSIGN_OR_RETURN(CelValue result, expression_plan->Evaluate(activation, &arena)); return ConvertResult(result); } }
#include "codelab/exercise1.h" #include "internal/testing.h" namespace google::api::expr::codelab { namespace { using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; TEST(Exercise1, PrintHelloWorld) { EXPECT_THAT(ParseAndEvaluate("'Hello, World!'"), IsOkAndHolds("Hello, World!")); } TEST(Exercise1, WrongTypeResultError) { EXPECT_THAT(ParseAndEvaluate("true"), StatusIs(absl::StatusCode::kInvalidArgument, "expected string result got 'bool'")); } TEST(Exercise1, Conditional) { EXPECT_THAT(ParseAndEvaluate("(1 < 0)? 'Hello, World!' : '¡Hola, Mundo!'"), IsOkAndHolds("¡Hola, Mundo!")); } } }
43
cpp
google/cel-cpp
proto_util
internal/proto_util.cc
internal/proto_util_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_PROTO_UTIL_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_PROTO_UTIL_H_ #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/util/message_differencer.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" namespace google { namespace api { namespace expr { namespace internal { struct DefaultProtoEqual { inline bool operator()(const google::protobuf::Message& lhs, const google::protobuf::Message& rhs) const { return google::protobuf::util::MessageDifferencer::Equals(lhs, rhs); } }; template <class MessageType> absl::Status ValidateStandardMessageType( const google::protobuf::DescriptorPool& descriptor_pool) { const google::protobuf::Descriptor* descriptor = MessageType::descriptor(); const google::protobuf::Descriptor* descriptor_from_pool = descriptor_pool.FindMessageTypeByName(descriptor->full_name()); if (descriptor_from_pool == nullptr) { return absl::NotFoundError( absl::StrFormat("Descriptor '%s' not found in descriptor pool", descriptor->full_name())); } if (descriptor_from_pool == descriptor) { return absl::OkStatus(); } google::protobuf::DescriptorProto descriptor_proto; google::protobuf::DescriptorProto descriptor_from_pool_proto; descriptor->CopyTo(&descriptor_proto); descriptor_from_pool->CopyTo(&descriptor_from_pool_proto); google::protobuf::util::MessageDifferencer descriptor_differencer; const google::protobuf::FieldDescriptor* json_name_field_desc = google::protobuf::FieldDescriptorProto::descriptor()->FindFieldByName("json_name"); if (json_name_field_desc != nullptr) { descriptor_differencer.IgnoreField(json_name_field_desc); } if (!descriptor_differencer.Compare(descriptor_proto, descriptor_from_pool_proto)) { return absl::FailedPreconditionError(absl::StrFormat( "The descriptor for '%s' in the descriptor pool differs from the " "compiled-in generated version", descriptor->full_name())); } return absl::OkStatus(); } absl::Status ValidateStandardMessageTypes( const google::protobuf::DescriptorPool& descriptor_pool); } } } } #endif #include "internal/proto_util.h" #include <string> #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 "absl/status/status.h" #include "absl/strings/str_cat.h" #include "internal/status_macros.h" namespace google { namespace api { namespace expr { namespace internal { absl::Status ValidateStandardMessageTypes( const google::protobuf::DescriptorPool& descriptor_pool) { CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::Any>(descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::BoolValue>( descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::BytesValue>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::DoubleValue>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::Duration>(descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::FloatValue>( descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::Int32Value>( descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::Int64Value>( descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::ListValue>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::StringValue>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::Struct>(descriptor_pool)); CEL_RETURN_IF_ERROR(ValidateStandardMessageType<google::protobuf::Timestamp>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::UInt32Value>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::UInt64Value>( descriptor_pool)); CEL_RETURN_IF_ERROR( ValidateStandardMessageType<google::protobuf::Value>(descriptor_pool)); return absl::OkStatus(); } } } } }
#include "internal/proto_util.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/descriptor.h" #include "eval/public/structs/cel_proto_descriptor_pool_builder.h" #include "internal/testing.h" namespace cel::internal { namespace { using google::api::expr::internal::ValidateStandardMessageType; using google::api::expr::internal::ValidateStandardMessageTypes; using google::api::expr::runtime::AddStandardMessageTypesToDescriptorPool; using google::api::expr::runtime::GetStandardMessageTypesFileDescriptorSet; using testing::HasSubstr; using cel::internal::StatusIs; TEST(ProtoUtil, ValidateStandardMessageTypesOk) { google::protobuf::DescriptorPool descriptor_pool; ASSERT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool)); EXPECT_OK(ValidateStandardMessageTypes(descriptor_pool)); } TEST(ProtoUtil, ValidateStandardMessageTypesRejectsMissing) { google::protobuf::DescriptorPool descriptor_pool; EXPECT_THAT(ValidateStandardMessageTypes(descriptor_pool), StatusIs(absl::StatusCode::kNotFound, HasSubstr("not found in descriptor pool"))); } TEST(ProtoUtil, ValidateStandardMessageTypesRejectsIncompatible) { google::protobuf::DescriptorPool descriptor_pool; google::protobuf::FileDescriptorSet standard_fds = GetStandardMessageTypesFileDescriptorSet(); 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( ValidateStandardMessageType<google::protobuf::Duration>(descriptor_pool), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("differs"))); } TEST(ProtoUtil, ValidateStandardMessageTypesIgnoredJsonName) { google::protobuf::DescriptorPool descriptor_pool; google::protobuf::FileDescriptorSet standard_fds = GetStandardMessageTypesFileDescriptorSet(); bool modified = false; for (int i = 0; i < standard_fds.file_size(); ++i) { if (standard_fds.file(i).name() == "google/protobuf/duration.proto") { google::protobuf::FileDescriptorProto* fdp = standard_fds.mutable_file(i); for (int j = 0; j < fdp->message_type_size(); ++j) { if (fdp->message_type(j).name() == "Duration") { google::protobuf::DescriptorProto* dp = fdp->mutable_message_type(j); for (int k = 0; k < dp->field_size(); ++k) { if (dp->field(k).name() == "seconds") { dp->mutable_field(k)->set_json_name("FOOBAR"); modified = true; } } } } } } ASSERT_TRUE(modified); for (int i = 0; i < standard_fds.file_size(); ++i) { descriptor_pool.BuildFile(standard_fds.file(i)); } EXPECT_OK(ValidateStandardMessageTypes(descriptor_pool)); } } }
44
cpp
google/cel-cpp
time
internal/time.cc
internal/time_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_TIME_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_TIME_H_ #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" namespace cel::internal { inline absl::Duration MaxDuration() { return absl::Seconds(315576000000) + absl::Nanoseconds(999999999); } inline absl::Duration MinDuration() { return absl::Seconds(-315576000000) + absl::Nanoseconds(-999999999); } inline absl::Time MaxTimestamp() { return absl::UnixEpoch() + absl::Seconds(253402300799) + absl::Nanoseconds(999999999); } inline absl::Time MinTimestamp() { return absl::UnixEpoch() + absl::Seconds(-62135596800); } absl::Status ValidateDuration(absl::Duration duration); absl::StatusOr<absl::Duration> ParseDuration(absl::string_view input); absl::StatusOr<std::string> FormatDuration(absl::Duration duration); absl::StatusOr<std::string> EncodeDurationToJson(absl::Duration duration); std::string DebugStringDuration(absl::Duration duration); absl::Status ValidateTimestamp(absl::Time timestamp); absl::StatusOr<absl::Time> ParseTimestamp(absl::string_view input); absl::StatusOr<std::string> FormatTimestamp(absl::Time timestamp); absl::StatusOr<std::string> EncodeTimestampToJson(absl::Time timestamp); std::string DebugStringTimestamp(absl::Time timestamp); } #endif #include "internal/time.h" #include <cstdint> #include <string> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" #include "internal/status_macros.h" namespace cel::internal { namespace { std::string RawFormatTimestamp(absl::Time timestamp) { return absl::FormatTime("%Y-%m-%d%ET%H:%M:%E*SZ", timestamp, absl::UTCTimeZone()); } } absl::Status ValidateDuration(absl::Duration duration) { if (duration < MinDuration()) { return absl::InvalidArgumentError( absl::StrCat("Duration \"", absl::FormatDuration(duration), "\" below minimum allowed duration \"", absl::FormatDuration(MinDuration()), "\"")); } if (duration > MaxDuration()) { return absl::InvalidArgumentError( absl::StrCat("Duration \"", absl::FormatDuration(duration), "\" above maximum allowed duration \"", absl::FormatDuration(MaxDuration()), "\"")); } return absl::OkStatus(); } absl::StatusOr<absl::Duration> ParseDuration(absl::string_view input) { absl::Duration duration; if (!absl::ParseDuration(input, &duration)) { return absl::InvalidArgumentError("Failed to parse duration from string"); } return duration; } absl::StatusOr<std::string> FormatDuration(absl::Duration duration) { CEL_RETURN_IF_ERROR(ValidateDuration(duration)); return absl::FormatDuration(duration); } std::string DebugStringDuration(absl::Duration duration) { return absl::FormatDuration(duration); } absl::Status ValidateTimestamp(absl::Time timestamp) { if (timestamp < MinTimestamp()) { return absl::InvalidArgumentError( absl::StrCat("Timestamp \"", RawFormatTimestamp(timestamp), "\" below minimum allowed timestamp \"", RawFormatTimestamp(MinTimestamp()), "\"")); } if (timestamp > MaxTimestamp()) { return absl::InvalidArgumentError( absl::StrCat("Timestamp \"", RawFormatTimestamp(timestamp), "\" above maximum allowed timestamp \"", RawFormatTimestamp(MaxTimestamp()), "\"")); } return absl::OkStatus(); } absl::StatusOr<absl::Time> ParseTimestamp(absl::string_view input) { absl::Time timestamp; std::string err; if (!absl::ParseTime(absl::RFC3339_full, input, absl::UTCTimeZone(), &timestamp, &err)) { return err.empty() ? absl::InvalidArgumentError( "Failed to parse timestamp from string") : absl::InvalidArgumentError(absl::StrCat( "Failed to parse timestamp from string: ", err)); } CEL_RETURN_IF_ERROR(ValidateTimestamp(timestamp)); return timestamp; } absl::StatusOr<std::string> FormatTimestamp(absl::Time timestamp) { CEL_RETURN_IF_ERROR(ValidateTimestamp(timestamp)); return RawFormatTimestamp(timestamp); } std::string FormatNanos(int32_t nanos) { constexpr int32_t kNanosPerMillisecond = 1000000; constexpr int32_t kNanosPerMicrosecond = 1000; if (nanos % kNanosPerMillisecond == 0) { return absl::StrFormat("%03d", nanos / kNanosPerMillisecond); } else if (nanos % kNanosPerMicrosecond == 0) { return absl::StrFormat("%06d", nanos / kNanosPerMicrosecond); } return absl::StrFormat("%09d", nanos); } absl::StatusOr<std::string> EncodeDurationToJson(absl::Duration duration) { CEL_RETURN_IF_ERROR(ValidateDuration(duration)); std::string result; int64_t seconds = absl::IDivDuration(duration, absl::Seconds(1), &duration); int64_t nanos = absl::IDivDuration(duration, absl::Nanoseconds(1), &duration); if (seconds < 0 || nanos < 0) { result = "-"; seconds = -seconds; nanos = -nanos; } absl::StrAppend(&result, seconds); if (nanos != 0) { absl::StrAppend(&result, ".", FormatNanos(nanos)); } absl::StrAppend(&result, "s"); return result; } absl::StatusOr<std::string> EncodeTimestampToJson(absl::Time timestamp) { static constexpr absl::string_view kTimestampFormat = "%E4Y-%m-%dT%H:%M:%S"; CEL_RETURN_IF_ERROR(ValidateTimestamp(timestamp)); absl::Time unix_seconds = absl::FromUnixSeconds(absl::ToUnixSeconds(timestamp)); int64_t n = (timestamp - unix_seconds) / absl::Nanoseconds(1); std::string result = absl::FormatTime(kTimestampFormat, unix_seconds, absl::UTCTimeZone()); if (n > 0) { absl::StrAppend(&result, ".", FormatNanos(n)); } absl::StrAppend(&result, "Z"); return result; } std::string DebugStringTimestamp(absl::Time timestamp) { return RawFormatTimestamp(timestamp); } }
#include "internal/time.h" #include <string> #include "google/protobuf/util/time_util.h" #include "absl/status/status.h" #include "absl/time/time.h" #include "internal/testing.h" namespace cel::internal { namespace { using cel::internal::StatusIs; TEST(MaxDuration, ProtoEquiv) { EXPECT_EQ(MaxDuration(), absl::Seconds(google::protobuf::util::TimeUtil::kDurationMaxSeconds) + absl::Nanoseconds(999999999)); } TEST(MinDuration, ProtoEquiv) { EXPECT_EQ(MinDuration(), absl::Seconds(google::protobuf::util::TimeUtil::kDurationMinSeconds) + absl::Nanoseconds(-999999999)); } TEST(MaxTimestamp, ProtoEquiv) { EXPECT_EQ(MaxTimestamp(), absl::UnixEpoch() + absl::Seconds(google::protobuf::util::TimeUtil::kTimestampMaxSeconds) + absl::Nanoseconds(999999999)); } TEST(MinTimestamp, ProtoEquiv) { EXPECT_EQ(MinTimestamp(), absl::UnixEpoch() + absl::Seconds(google::protobuf::util::TimeUtil::kTimestampMinSeconds)); } TEST(ParseDuration, Conformance) { absl::Duration parsed; ASSERT_OK_AND_ASSIGN(parsed, internal::ParseDuration("1s")); EXPECT_EQ(parsed, absl::Seconds(1)); ASSERT_OK_AND_ASSIGN(parsed, internal::ParseDuration("0.010s")); EXPECT_EQ(parsed, absl::Milliseconds(10)); ASSERT_OK_AND_ASSIGN(parsed, internal::ParseDuration("0.000010s")); EXPECT_EQ(parsed, absl::Microseconds(10)); ASSERT_OK_AND_ASSIGN(parsed, internal::ParseDuration("0.000000010s")); EXPECT_EQ(parsed, absl::Nanoseconds(10)); EXPECT_THAT(internal::ParseDuration("abc"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(internal::ParseDuration("1c"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(FormatDuration, Conformance) { std::string formatted; ASSERT_OK_AND_ASSIGN(formatted, internal::FormatDuration(absl::Seconds(1))); EXPECT_EQ(formatted, "1s"); ASSERT_OK_AND_ASSIGN(formatted, internal::FormatDuration(absl::Milliseconds(10))); EXPECT_EQ(formatted, "10ms"); ASSERT_OK_AND_ASSIGN(formatted, internal::FormatDuration(absl::Microseconds(10))); EXPECT_EQ(formatted, "10us"); ASSERT_OK_AND_ASSIGN(formatted, internal::FormatDuration(absl::Nanoseconds(10))); EXPECT_EQ(formatted, "10ns"); EXPECT_THAT(internal::FormatDuration(absl::InfiniteDuration()), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(internal::FormatDuration(-absl::InfiniteDuration()), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ParseTimestamp, Conformance) { absl::Time parsed; ASSERT_OK_AND_ASSIGN(parsed, internal::ParseTimestamp("1-01-01T00:00:00Z")); EXPECT_EQ(parsed, MinTimestamp()); ASSERT_OK_AND_ASSIGN( parsed, internal::ParseTimestamp("9999-12-31T23:59:59.999999999Z")); EXPECT_EQ(parsed, MaxTimestamp()); ASSERT_OK_AND_ASSIGN(parsed, internal::ParseTimestamp("1970-01-01T00:00:00Z")); EXPECT_EQ(parsed, absl::UnixEpoch()); ASSERT_OK_AND_ASSIGN(parsed, internal::ParseTimestamp("1970-01-01T00:00:00.010Z")); EXPECT_EQ(parsed, absl::UnixEpoch() + absl::Milliseconds(10)); ASSERT_OK_AND_ASSIGN(parsed, internal::ParseTimestamp("1970-01-01T00:00:00.000010Z")); EXPECT_EQ(parsed, absl::UnixEpoch() + absl::Microseconds(10)); ASSERT_OK_AND_ASSIGN( parsed, internal::ParseTimestamp("1970-01-01T00:00:00.000000010Z")); EXPECT_EQ(parsed, absl::UnixEpoch() + absl::Nanoseconds(10)); EXPECT_THAT(internal::ParseTimestamp("abc"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(internal::ParseTimestamp("10000-01-01T00:00:00Z"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(FormatTimestamp, Conformance) { std::string formatted; ASSERT_OK_AND_ASSIGN(formatted, internal::FormatTimestamp(MinTimestamp())); EXPECT_EQ(formatted, "1-01-01T00:00:00Z"); ASSERT_OK_AND_ASSIGN(formatted, internal::FormatTimestamp(MaxTimestamp())); EXPECT_EQ(formatted, "9999-12-31T23:59:59.999999999Z"); ASSERT_OK_AND_ASSIGN(formatted, internal::FormatTimestamp(absl::UnixEpoch())); EXPECT_EQ(formatted, "1970-01-01T00:00:00Z"); ASSERT_OK_AND_ASSIGN( formatted, internal::FormatTimestamp(absl::UnixEpoch() + absl::Milliseconds(10))); EXPECT_EQ(formatted, "1970-01-01T00:00:00.01Z"); ASSERT_OK_AND_ASSIGN( formatted, internal::FormatTimestamp(absl::UnixEpoch() + absl::Microseconds(10))); EXPECT_EQ(formatted, "1970-01-01T00:00:00.00001Z"); ASSERT_OK_AND_ASSIGN( formatted, internal::FormatTimestamp(absl::UnixEpoch() + absl::Nanoseconds(10))); EXPECT_EQ(formatted, "1970-01-01T00:00:00.00000001Z"); EXPECT_THAT(internal::FormatTimestamp(absl::InfiniteFuture()), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(internal::FormatTimestamp(absl::InfinitePast()), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(EncodeDurationToJson, Conformance) { std::string formatted; ASSERT_OK_AND_ASSIGN(formatted, EncodeDurationToJson(absl::Seconds(1))); EXPECT_EQ(formatted, "1s"); ASSERT_OK_AND_ASSIGN(formatted, EncodeDurationToJson(absl::Milliseconds(10))); EXPECT_EQ(formatted, "0.010s"); ASSERT_OK_AND_ASSIGN(formatted, EncodeDurationToJson(absl::Microseconds(10))); EXPECT_EQ(formatted, "0.000010s"); ASSERT_OK_AND_ASSIGN(formatted, EncodeDurationToJson(absl::Nanoseconds(10))); EXPECT_EQ(formatted, "0.000000010s"); EXPECT_THAT(EncodeDurationToJson(absl::InfiniteDuration()), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(EncodeDurationToJson(-absl::InfiniteDuration()), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(EncodeTimestampToJson, Conformance) { std::string formatted; ASSERT_OK_AND_ASSIGN(formatted, EncodeTimestampToJson(MinTimestamp())); EXPECT_EQ(formatted, "0001-01-01T00:00:00Z"); ASSERT_OK_AND_ASSIGN(formatted, EncodeTimestampToJson(MaxTimestamp())); EXPECT_EQ(formatted, "9999-12-31T23:59:59.999999999Z"); ASSERT_OK_AND_ASSIGN(formatted, EncodeTimestampToJson(absl::UnixEpoch())); EXPECT_EQ(formatted, "1970-01-01T00:00:00Z"); ASSERT_OK_AND_ASSIGN( formatted, EncodeTimestampToJson(absl::UnixEpoch() + absl::Milliseconds(10))); EXPECT_EQ(formatted, "1970-01-01T00:00:00.010Z"); ASSERT_OK_AND_ASSIGN( formatted, EncodeTimestampToJson(absl::UnixEpoch() + absl::Microseconds(10))); EXPECT_EQ(formatted, "1970-01-01T00:00:00.000010Z"); ASSERT_OK_AND_ASSIGN(formatted, EncodeTimestampToJson(absl::UnixEpoch() + absl::Nanoseconds(10))); EXPECT_EQ(formatted, "1970-01-01T00:00:00.000000010Z"); EXPECT_THAT(EncodeTimestampToJson(absl::InfiniteFuture()), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(EncodeTimestampToJson(absl::InfinitePast()), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
45
cpp
google/cel-cpp
names
internal/names.cc
internal/names_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_NAMES_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_NAMES_H_ #include "absl/strings/string_view.h" namespace cel::internal { bool IsValidRelativeName(absl::string_view name); } #endif #include "internal/names.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "internal/lexis.h" namespace cel::internal { bool IsValidRelativeName(absl::string_view name) { if (name.empty()) { return false; } for (const auto& id : absl::StrSplit(name, '.')) { if (!LexisIsIdentifier(id)) { return false; } } return true; } }
#include "internal/names.h" #include "internal/testing.h" namespace cel::internal { namespace { struct NamesTestCase final { absl::string_view text; bool ok; }; using IsValidRelativeNameTest = testing::TestWithParam<NamesTestCase>; TEST_P(IsValidRelativeNameTest, Compliance) { const NamesTestCase& test_case = GetParam(); if (test_case.ok) { EXPECT_TRUE(IsValidRelativeName(test_case.text)); } else { EXPECT_FALSE(IsValidRelativeName(test_case.text)); } } INSTANTIATE_TEST_SUITE_P(IsValidRelativeNameTest, IsValidRelativeNameTest, testing::ValuesIn<NamesTestCase>({{"foo", true}, {"foo.Bar", true}, {"", false}, {".", false}, {".foo", false}, {".foo.Bar", false}, {"foo..Bar", false}, {"foo.Bar.", false}})); } }
46
cpp
google/cel-cpp
new
internal/new.cc
internal/new_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_NEW_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_NEW_H_ #include <cstddef> #include <new> #include <utility> namespace cel::internal { inline constexpr size_t kDefaultNewAlignment = #ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__ __STDCPP_DEFAULT_NEW_ALIGNMENT__ #else alignof(std::max_align_t) #endif ; void* New(size_t size); void* AlignedNew(size_t size, std::align_val_t alignment); std::pair<void*, size_t> SizeReturningNew(size_t size); std::pair<void*, size_t> SizeReturningAlignedNew(size_t size, std::align_val_t alignment); void Delete(void* ptr) noexcept; void SizedDelete(void* ptr, size_t size) noexcept; void AlignedDelete(void* ptr, std::align_val_t alignment) noexcept; void SizedAlignedDelete(void* ptr, size_t size, std::align_val_t alignment) noexcept; } #endif #include "internal/new.h" #include <cstddef> #include <cstdlib> #include <new> #include <utility> #ifdef _MSC_VER #include <malloc.h> #endif #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/numeric/bits.h" #include "internal/align.h" #if defined(__cpp_aligned_new) && __cpp_aligned_new >= 201606L #define CEL_INTERNAL_HAVE_ALIGNED_NEW 1 #endif #if defined(__cpp_sized_deallocation) && __cpp_sized_deallocation >= 201309L #define CEL_INTERNAL_HAVE_SIZED_DELETE 1 #endif namespace cel::internal { namespace { [[noreturn]] void ThrowStdBadAlloc() { #ifdef ABSL_HAVE_EXCEPTIONS throw std::bad_alloc(); #else std::abort(); #endif } } #ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__ static_assert(IsAligned(alignof(std::max_align_t), __STDCPP_DEFAULT_NEW_ALIGNMENT__)); #endif void* New(size_t size) { return ::operator new(size); } void* AlignedNew(size_t size, std::align_val_t alignment) { ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment))); #ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW return ::operator new(size, alignment); #else if (static_cast<size_t>(alignment) <= kDefaultNewAlignment) { return New(size); } #if defined(_MSC_VER) void* ptr = _aligned_malloc(size, static_cast<size_t>(alignment)); if (ABSL_PREDICT_FALSE(size != 0 && ptr == nullptr)) { ThrowStdBadAlloc(); } return ptr; #else void* ptr = std::aligned_alloc(static_cast<size_t>(alignment), size); if (ABSL_PREDICT_FALSE(size != 0 && ptr == nullptr)) { ThrowStdBadAlloc(); } return ptr; #endif #endif } std::pair<void*, size_t> SizeReturningNew(size_t size) { return std::pair{::operator new(size), size}; } std::pair<void*, size_t> SizeReturningAlignedNew(size_t size, std::align_val_t alignment) { ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment))); #ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW return std::pair{::operator new(size, alignment), size}; #else return std::pair{AlignedNew(size, alignment), size}; #endif } void Delete(void* ptr) noexcept { ::operator delete(ptr); } void SizedDelete(void* ptr, size_t size) noexcept { #ifdef CEL_INTERNAL_HAVE_SIZED_DELETE ::operator delete(ptr, size); #else ::operator delete(ptr); #endif } void AlignedDelete(void* ptr, std::align_val_t alignment) noexcept { ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment))); #ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW ::operator delete(ptr, alignment); #else if (static_cast<size_t>(alignment) <= kDefaultNewAlignment) { Delete(ptr, size); } else { #if defined(_MSC_VER) _aligned_free(ptr); #else std::free(ptr); #endif } #endif } void SizedAlignedDelete(void* ptr, size_t size, std::align_val_t alignment) noexcept { ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment))); #ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW #ifdef CEL_INTERNAL_HAVE_SIZED_DELETE ::operator delete(ptr, size, alignment); #else ::operator delete(ptr, alignment); #endif #else AlignedDelete(ptr, alignment); #endif } }
#include "internal/new.h" #include <cstddef> #include <cstdint> #include <new> #include <tuple> #include "internal/testing.h" namespace cel::internal { namespace { using testing::Ge; using testing::NotNull; TEST(New, Basic) { void* p = New(sizeof(uint64_t)); EXPECT_THAT(p, NotNull()); Delete(p); } TEST(AlignedNew, Basic) { void* p = AlignedNew(alignof(std::max_align_t) * 2, static_cast<std::align_val_t>(alignof(std::max_align_t) * 2)); EXPECT_THAT(p, NotNull()); AlignedDelete(p, static_cast<std::align_val_t>(alignof(std::max_align_t) * 2)); } TEST(SizeReturningNew, Basic) { void* p; size_t n; std::tie(p, n) = SizeReturningNew(sizeof(uint64_t)); EXPECT_THAT(p, NotNull()); EXPECT_THAT(n, Ge(sizeof(uint64_t))); SizedDelete(p, n); } TEST(SizeReturningAlignedNew, Basic) { void* p; size_t n; std::tie(p, n) = SizeReturningAlignedNew( alignof(std::max_align_t) * 2, static_cast<std::align_val_t>(alignof(std::max_align_t) * 2)); EXPECT_THAT(p, NotNull()); EXPECT_THAT(n, Ge(alignof(std::max_align_t) * 2)); SizedAlignedDelete( p, n, static_cast<std::align_val_t>(alignof(std::max_align_t) * 2)); } } }
47
cpp
google/cel-cpp
page_size
internal/page_size.cc
internal/page_size_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_PAGE_SIZE_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_PAGE_SIZE_H_ #include <cstddef> #include "absl/base/attributes.h" namespace cel::internal { ABSL_ATTRIBUTE_CONST_FUNCTION size_t PageSize(); } #endif #include "internal/page_size.h" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #else #include <unistd.h> #endif #include <cstring> namespace cel::internal { size_t PageSize() { static const size_t page_size = []() -> size_t { #ifdef _WIN32 SYSTEM_INFO system_info; std::memset(&system_info, '\0', sizeof(system_info)); ::GetSystemInfo(&system_info); return system_info.dwPageSize; #else #if defined(__wasm__) || defined(__asmjs__) return static_cast<size_t>(getpagesize()); #else return static_cast<size_t>(sysconf(_SC_PAGESIZE)); #endif #endif }(); return page_size; } }
#include "internal/page_size.h" #include "absl/numeric/bits.h" #include "internal/testing.h" namespace cel::internal { namespace { TEST(PageSize, PowerOf2) { EXPECT_TRUE(absl::has_single_bit(PageSize())); } } }
48
cpp
google/cel-cpp
lexis
internal/lexis.cc
internal/lexis_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_LEXIS_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_LEXIS_H_ #include "absl/strings/string_view.h" namespace cel::internal { bool LexisIsReserved(absl::string_view text); bool LexisIsIdentifier(absl::string_view text); } #endif #include "internal/lexis.h" #include "absl/base/call_once.h" #include "absl/base/macros.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" namespace cel::internal { namespace { ABSL_CONST_INIT absl::once_flag reserved_keywords_once_flag = {}; ABSL_CONST_INIT absl::flat_hash_set<absl::string_view>* reserved_keywords = nullptr; void InitializeReservedKeywords() { ABSL_ASSERT(reserved_keywords == nullptr); reserved_keywords = new absl::flat_hash_set<absl::string_view>(); reserved_keywords->insert("false"); reserved_keywords->insert("true"); reserved_keywords->insert("null"); reserved_keywords->insert("in"); reserved_keywords->insert("as"); reserved_keywords->insert("break"); reserved_keywords->insert("const"); reserved_keywords->insert("continue"); reserved_keywords->insert("else"); reserved_keywords->insert("for"); reserved_keywords->insert("function"); reserved_keywords->insert("if"); reserved_keywords->insert("import"); reserved_keywords->insert("let"); reserved_keywords->insert("loop"); reserved_keywords->insert("package"); reserved_keywords->insert("namespace"); reserved_keywords->insert("return"); reserved_keywords->insert("var"); reserved_keywords->insert("void"); reserved_keywords->insert("while"); } } bool LexisIsReserved(absl::string_view text) { absl::call_once(reserved_keywords_once_flag, InitializeReservedKeywords); return reserved_keywords->find(text) != reserved_keywords->end(); } bool LexisIsIdentifier(absl::string_view text) { if (text.empty()) { return false; } char first = text.front(); if (!absl::ascii_isalpha(first) && first != '_') { return false; } for (size_t index = 1; index < text.size(); index++) { if (!absl::ascii_isalnum(text[index]) && text[index] != '_') { return false; } } return !LexisIsReserved(text); } }
#include "internal/lexis.h" #include "internal/testing.h" namespace cel::internal { namespace { struct LexisTestCase final { absl::string_view text; bool ok; }; using LexisIsReservedTest = testing::TestWithParam<LexisTestCase>; TEST_P(LexisIsReservedTest, Compliance) { const LexisTestCase& test_case = GetParam(); if (test_case.ok) { EXPECT_TRUE(LexisIsReserved(test_case.text)); } else { EXPECT_FALSE(LexisIsReserved(test_case.text)); } } INSTANTIATE_TEST_SUITE_P(LexisIsReservedTest, LexisIsReservedTest, testing::ValuesIn<LexisTestCase>({{"true", true}, {"cel", false}})); using LexisIsIdentifierTest = testing::TestWithParam<LexisTestCase>; TEST_P(LexisIsIdentifierTest, Compliance) { const LexisTestCase& test_case = GetParam(); if (test_case.ok) { EXPECT_TRUE(LexisIsIdentifier(test_case.text)); } else { EXPECT_FALSE(LexisIsIdentifier(test_case.text)); } } INSTANTIATE_TEST_SUITE_P( LexisIsIdentifierTest, LexisIsIdentifierTest, testing::ValuesIn<LexisTestCase>( {{"true", false}, {"0abc", false}, {"-abc", false}, {".abc", false}, {"~abc", false}, {"!abc", false}, {"abc-", false}, {"abc.", false}, {"abc~", false}, {"abc!", false}, {"cel", true}, {"cel0", true}, {"_cel", true}, {"_cel0", true}, {"cel_", true}, {"cel0_", true}, {"cel_cel", true}, {"cel0_cel", true}, {"cel_cel0", true}, {"cel0_cel0", true}})); } }
49
cpp
google/cel-cpp
proto_time_encoding
internal/proto_time_encoding.cc
internal/proto_time_encoding_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_PROTO_TIME_ENCODING_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_PROTO_TIME_ENCODING_H_ #include "google/protobuf/duration.pb.h" #include "google/protobuf/timestamp.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" namespace cel::internal { absl::Status EncodeDuration(absl::Duration duration, google::protobuf::Duration* proto); absl::StatusOr<std::string> EncodeDurationToString(absl::Duration duration); absl::Status EncodeTime(absl::Time time, google::protobuf::Timestamp* proto); absl::StatusOr<std::string> EncodeTimeToString(absl::Time time); absl::Duration DecodeDuration(const google::protobuf::Duration& proto); absl::Time DecodeTime(const google::protobuf::Timestamp& proto); } #endif #include "internal/proto_time_encoding.h" #include <string> #include "google/protobuf/duration.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/util/time_util.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "internal/status_macros.h" #include "internal/time.h" namespace cel::internal { namespace { absl::Status Validate(absl::Time time) { if (time < cel::internal::MinTimestamp()) { return absl::InvalidArgumentError("time below min"); } if (time > cel::internal::MaxTimestamp()) { return absl::InvalidArgumentError("time above max"); } return absl::OkStatus(); } absl::Status CelValidateDuration(absl::Duration duration) { if (duration < cel::internal::MinDuration()) { return absl::InvalidArgumentError("duration below min"); } if (duration > cel::internal::MaxDuration()) { return absl::InvalidArgumentError("duration above max"); } return absl::OkStatus(); } } absl::Duration DecodeDuration(const google::protobuf::Duration& proto) { return absl::Seconds(proto.seconds()) + absl::Nanoseconds(proto.nanos()); } absl::Time DecodeTime(const google::protobuf::Timestamp& proto) { return absl::FromUnixSeconds(proto.seconds()) + absl::Nanoseconds(proto.nanos()); } absl::Status EncodeDuration(absl::Duration duration, google::protobuf::Duration* proto) { CEL_RETURN_IF_ERROR(CelValidateDuration(duration)); const int64_t s = absl::IDivDuration(duration, absl::Seconds(1), &duration); const int64_t n = absl::IDivDuration(duration, absl::Nanoseconds(1), &duration); proto->set_seconds(s); proto->set_nanos(n); return absl::OkStatus(); } absl::StatusOr<std::string> EncodeDurationToString(absl::Duration duration) { google::protobuf::Duration d; auto status = EncodeDuration(duration, &d); if (!status.ok()) { return status; } return google::protobuf::util::TimeUtil::ToString(d); } absl::Status EncodeTime(absl::Time time, google::protobuf::Timestamp* proto) { CEL_RETURN_IF_ERROR(Validate(time)); const int64_t s = absl::ToUnixSeconds(time); proto->set_seconds(s); proto->set_nanos((time - absl::FromUnixSeconds(s)) / absl::Nanoseconds(1)); return absl::OkStatus(); } absl::StatusOr<std::string> EncodeTimeToString(absl::Time time) { google::protobuf::Timestamp t; auto status = EncodeTime(time, &t); if (!status.ok()) { return status; } return google::protobuf::util::TimeUtil::ToString(t); } }
#include "internal/proto_time_encoding.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/timestamp.pb.h" #include "absl/time/time.h" #include "internal/testing.h" #include "testutil/util.h" namespace cel::internal { namespace { using ::google::api::expr::testutil::EqualsProto; TEST(EncodeDuration, Basic) { google::protobuf::Duration proto_duration; ASSERT_OK( EncodeDuration(absl::Seconds(2) + absl::Nanoseconds(3), &proto_duration)); EXPECT_THAT(proto_duration, EqualsProto("seconds: 2 nanos: 3")); } TEST(EncodeDurationToString, Basic) { ASSERT_OK_AND_ASSIGN( std::string json, EncodeDurationToString(absl::Seconds(5) + absl::Nanoseconds(20))); EXPECT_EQ(json, "5.000000020s"); } TEST(EncodeTime, Basic) { google::protobuf::Timestamp proto_timestamp; ASSERT_OK(EncodeTime(absl::FromUnixMillis(300000), &proto_timestamp)); EXPECT_THAT(proto_timestamp, EqualsProto("seconds: 300")); } TEST(EncodeTimeToString, Basic) { ASSERT_OK_AND_ASSIGN(std::string json, EncodeTimeToString(absl::FromUnixMillis(80030))); EXPECT_EQ(json, "1970-01-01T00:01:20.030Z"); } TEST(DecodeDuration, Basic) { google::protobuf::Duration proto_duration; proto_duration.set_seconds(450); proto_duration.set_nanos(4); EXPECT_EQ(DecodeDuration(proto_duration), absl::Seconds(450) + absl::Nanoseconds(4)); } TEST(DecodeTime, Basic) { google::protobuf::Timestamp proto_timestamp; proto_timestamp.set_seconds(450); EXPECT_EQ(DecodeTime(proto_timestamp), absl::FromUnixSeconds(450)); } } }
50
cpp
google/cel-cpp
proto_wire
internal/proto_wire.cc
internal/proto_wire_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_PROTO_WIRE_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_PROTO_WIRE_H_ #include <cstddef> #include <cstdint> #include <limits> #include <type_traits> #include "absl/base/attributes.h" #include "absl/base/casts.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/numeric/bits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/cord_buffer.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" namespace cel::internal { template <typename T> inline constexpr std::enable_if_t< (std::is_integral_v<T> && std::is_unsigned_v<T> && sizeof(T) <= 8), size_t> VarintSize(T x) { return static_cast<size_t>( (static_cast<uint32_t>((sizeof(T) * 8 - 1) - absl::countl_zero<T>(x | T{1})) * 9 + 73) / 64); } inline constexpr size_t VarintSize(int64_t x) { return VarintSize(static_cast<uint64_t>(x)); } inline constexpr size_t VarintSize(int32_t x) { return VarintSize(static_cast<int64_t>(x)); } inline constexpr size_t VarintSize(bool x ABSL_ATTRIBUTE_UNUSED) { return 1; } template <typename T> inline constexpr size_t kMaxVarintSize = VarintSize(static_cast<T>(~T{0})); template <> inline constexpr size_t kMaxVarintSize<bool> = 1; enum class ProtoWireType : uint32_t { kVarint = 0, kFixed64 = 1, kLengthDelimited = 2, kStartGroup = 3, kEndGroup = 4, kFixed32 = 5, }; inline constexpr uint32_t kProtoWireTypeMask = uint32_t{0x7}; inline constexpr int kFieldNumberShift = 3; class ProtoWireTag final { public: static constexpr uint32_t kTypeMask = uint32_t{0x7}; static constexpr int kFieldNumberShift = 3; constexpr explicit ProtoWireTag(uint32_t tag) : tag_(tag) {} constexpr ProtoWireTag(uint32_t field_number, ProtoWireType type) : ProtoWireTag((field_number << kFieldNumberShift) | static_cast<uint32_t>(type)) { ABSL_ASSERT(((field_number << kFieldNumberShift) >> kFieldNumberShift) == field_number); } constexpr uint32_t field_number() const { return tag_ >> kFieldNumberShift; } constexpr ProtoWireType type() const { return static_cast<ProtoWireType>(tag_ & kTypeMask); } constexpr operator uint32_t() const { return tag_; } private: uint32_t tag_; }; inline constexpr bool ProtoWireTypeIsValid(ProtoWireType type) { return (static_cast<uint32_t>(type) & uint32_t{0x7}) == static_cast<uint32_t>(type) && static_cast<uint32_t>(type) != uint32_t{0x6}; } inline constexpr uint32_t MakeProtoWireTag(uint32_t field_number, ProtoWireType type) { ABSL_ASSERT(((field_number << 3) >> 3) == field_number); return (field_number << 3) | static_cast<uint32_t>(type); } inline size_t VarintEncodeUnsafe(uint64_t value, char* buffer) { size_t length = 0; while (ABSL_PREDICT_FALSE(value >= 0x80)) { buffer[length++] = static_cast<char>(static_cast<uint8_t>(value | 0x80)); value >>= 7; } buffer[length++] = static_cast<char>(static_cast<uint8_t>(value)); return length; } inline void VarintEncode(uint64_t value, absl::Cord& buffer) { char scratch[kMaxVarintSize<uint64_t>]; buffer.Append(absl::string_view(scratch, VarintEncodeUnsafe(value, scratch))); } inline void VarintEncode(int64_t value, absl::Cord& buffer) { return VarintEncode(absl::bit_cast<uint64_t>(value), buffer); } inline void VarintEncode(uint32_t value, absl::Cord& buffer) { char scratch[kMaxVarintSize<uint32_t>]; buffer.Append(absl::string_view(scratch, VarintEncodeUnsafe(value, scratch))); } inline void VarintEncode(int32_t value, absl::Cord& buffer) { return VarintEncode(static_cast<int64_t>(value), buffer); } inline void VarintEncode(bool value, absl::Cord& buffer) { char scratch = value ? char{1} : char{0}; buffer.Append(absl::string_view(&scratch, 1)); } inline void Fixed32EncodeUnsafe(uint64_t value, char* buffer) { buffer[0] = static_cast<char>(static_cast<uint8_t>(value)); buffer[1] = static_cast<char>(static_cast<uint8_t>(value >> 8)); buffer[2] = static_cast<char>(static_cast<uint8_t>(value >> 16)); buffer[3] = static_cast<char>(static_cast<uint8_t>(value >> 24)); } inline void Fixed32Encode(uint32_t value, absl::Cord& buffer) { char scratch[4]; Fixed32EncodeUnsafe(value, scratch); buffer.Append(absl::string_view(scratch, ABSL_ARRAYSIZE(scratch))); } inline void Fixed32Encode(float value, absl::Cord& buffer) { Fixed32Encode(absl::bit_cast<uint32_t>(value), buffer); } inline void Fixed64EncodeUnsafe(uint64_t value, char* buffer) { buffer[0] = static_cast<char>(static_cast<uint8_t>(value)); buffer[1] = static_cast<char>(static_cast<uint8_t>(value >> 8)); buffer[2] = static_cast<char>(static_cast<uint8_t>(value >> 16)); buffer[3] = static_cast<char>(static_cast<uint8_t>(value >> 24)); buffer[4] = static_cast<char>(static_cast<uint8_t>(value >> 32)); buffer[5] = static_cast<char>(static_cast<uint8_t>(value >> 40)); buffer[6] = static_cast<char>(static_cast<uint8_t>(value >> 48)); buffer[7] = static_cast<char>(static_cast<uint8_t>(value >> 56)); } inline void Fixed64Encode(uint64_t value, absl::Cord& buffer) { char scratch[8]; Fixed64EncodeUnsafe(value, scratch); buffer.Append(absl::string_view(scratch, ABSL_ARRAYSIZE(scratch))); } inline void Fixed64Encode(double value, absl::Cord& buffer) { Fixed64Encode(absl::bit_cast<uint64_t>(value), buffer); } template <typename T> struct VarintDecodeResult { T value; size_t size_bytes; }; template <typename T> inline std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, absl::optional<VarintDecodeResult<T>>> VarintDecode(const absl::Cord& data) { uint64_t result = 0; int count = 0; uint64_t b; auto begin = data.char_begin(); auto end = data.char_end(); do { if (ABSL_PREDICT_FALSE(count == kMaxVarintSize<T>)) { return absl::nullopt; } if (ABSL_PREDICT_FALSE(begin == end)) { return absl::nullopt; } b = static_cast<uint8_t>(*begin); result |= (b & uint64_t{0x7f}) << (7 * count); ++begin; ++count; } while (ABSL_PREDICT_FALSE(b & uint64_t{0x80})); if (ABSL_PREDICT_FALSE(result > std::numeric_limits<T>::max())) { return absl::nullopt; } return VarintDecodeResult<T>{static_cast<T>(result), static_cast<size_t>(count)}; } template <typename T> inline std::enable_if_t<std::is_integral<T>::value && std::is_signed<T>::value, absl::optional<VarintDecodeResult<T>>> VarintDecode(const absl::Cord& data) { if (auto value = VarintDecode<uint64_t>(data); ABSL_PREDICT_TRUE(value.has_value())) { if (ABSL_PREDICT_TRUE(absl::bit_cast<int64_t>(value->value) >= std::numeric_limits<T>::min() && absl::bit_cast<int64_t>(value->value) <= std::numeric_limits<T>::max())) { return VarintDecodeResult<T>{ static_cast<T>(absl::bit_cast<int64_t>(value->value)), value->size_bytes}; } } return absl::nullopt; } template <typename T> inline std::enable_if_t<((std::is_integral<T>::value && std::is_unsigned<T>::value) || std::is_floating_point<T>::value) && sizeof(T) == 8, absl::optional<T>> Fixed64Decode(const absl::Cord& data) { if (ABSL_PREDICT_FALSE(data.size() < 8)) { return absl::nullopt; } uint64_t result = 0; auto it = data.char_begin(); result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)); ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 8; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 16; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 24; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 32; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 40; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 48; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 56; return absl::bit_cast<T>(result); } template <typename T> inline std::enable_if_t<((std::is_integral<T>::value && std::is_unsigned<T>::value) || std::is_floating_point<T>::value) && sizeof(T) == 4, absl::optional<T>> Fixed32Decode(const absl::Cord& data) { if (ABSL_PREDICT_FALSE(data.size() < 4)) { return absl::nullopt; } uint32_t result = 0; auto it = data.char_begin(); result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)); ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 8; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 16; ++it; result |= static_cast<uint64_t>(static_cast<uint8_t>(*it)) << 24; return absl::bit_cast<T>(result); } inline absl::optional<ProtoWireTag> DecodeProtoWireTag(uint32_t value) { if (ABSL_PREDICT_FALSE((value >> ProtoWireTag::kFieldNumberShift) == 0)) { return absl::nullopt; } if (ABSL_PREDICT_FALSE(!ProtoWireTypeIsValid( static_cast<ProtoWireType>(value & ProtoWireTag::kTypeMask)))) { return absl::nullopt; } return ProtoWireTag(value); } inline absl::optional<ProtoWireTag> DecodeProtoWireTag(uint64_t value) { if (ABSL_PREDICT_FALSE(value > std::numeric_limits<uint32_t>::max())) { return absl::nullopt; } return DecodeProtoWireTag(static_cast<uint32_t>(value)); } ABSL_MUST_USE_RESULT bool SkipLengthValue(absl::Cord& data, ProtoWireType type); class ProtoWireDecoder { public: ProtoWireDecoder(absl::string_view message ABSL_ATTRIBUTE_LIFETIME_BOUND, const absl::Cord& data) : message_(message), data_(data) {} bool HasNext() const { ABSL_DCHECK(!tag_.has_value()); return !data_.empty(); } absl::StatusOr<ProtoWireTag> ReadTag(); absl::Status SkipLengthValue(); template <typename T> std::enable_if_t<std::is_integral<T>::value, absl::StatusOr<T>> ReadVarint() { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kVarint); auto result = internal::VarintDecode<T>(data_); if (ABSL_PREDICT_FALSE(!result.has_value())) { return absl::DataLossError(absl::StrCat( "malformed or out of range varint encountered decoding field ", tag_->field_number(), " of ", message_)); } data_.RemovePrefix(result->size_bytes); tag_.reset(); return result->value; } template <typename T> std::enable_if_t<((std::is_integral<T>::value && std::is_unsigned<T>::value) || std::is_floating_point<T>::value) && sizeof(T) == 4, absl::StatusOr<T>> ReadFixed32() { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kFixed32); auto result = internal::Fixed32Decode<T>(data_); if (ABSL_PREDICT_FALSE(!result.has_value())) { return absl::DataLossError( absl::StrCat("malformed fixed32 encountered decoding field ", tag_->field_number(), " of ", message_)); } data_.RemovePrefix(4); tag_.reset(); return *result; } template <typename T> std::enable_if_t<((std::is_integral<T>::value && std::is_unsigned<T>::value) || std::is_floating_point<T>::value) && sizeof(T) == 8, absl::StatusOr<T>> ReadFixed64() { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kFixed64); auto result = internal::Fixed64Decode<T>(data_); if (ABSL_PREDICT_FALSE(!result.has_value())) { return absl::DataLossError( absl::StrCat("malformed fixed64 encountered decoding field ", tag_->field_number(), " of ", message_)); } data_.RemovePrefix(8); tag_.reset(); return *result; } absl::StatusOr<absl::Cord> ReadLengthDelimited(); void EnsureFullyDecoded() { ABSL_DCHECK(data_.empty()); } private: absl::string_view message_; absl::Cord data_; absl::optional<ProtoWireTag> tag_; }; class ProtoWireEncoder final { public: explicit ProtoWireEncoder(absl::string_view message ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::Cord& data ABSL_ATTRIBUTE_LIFETIME_BOUND) : message_(message), data_(data), original_data_size_(data_.size()) {} bool empty() const { return size() == 0; } size_t size() const { return data_.size() - original_data_size_; } absl::Status WriteTag(ProtoWireTag tag); template <typename T> std::enable_if_t<std::is_integral_v<T>, absl::Status> WriteVarint(T value) { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kVarint); VarintEncode(value, data_); tag_.reset(); return absl::OkStatus(); } template <typename T> std::enable_if_t<sizeof(T) == 4 && (std::is_integral_v<T> || std::is_floating_point_v<T>), absl::Status> WriteFixed32(T value) { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kFixed32); Fixed32Encode(value, data_); tag_.reset(); return absl::OkStatus(); } template <typename T> std::enable_if_t<sizeof(T) == 8 && (std::is_integral_v<T> || std::is_floating_point_v<T>), absl::Status> WriteFixed64(T value) { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kFixed64); Fixed64Encode(value, data_); tag_.reset(); return absl::OkStatus(); } absl::Status WriteLengthDelimited(absl::Cord data); absl::Status WriteLengthDelimited(absl::string_view data); void EnsureFullyEncoded() { ABSL_DCHECK(!tag_.has_value()); } private: absl::string_view message_; absl::Cord& data_; const size_t original_data_size_; absl::optional<ProtoWireTag> tag_; }; } #endif #include "internal/proto_wire.h" #include <limits> #include <string> #include <utility> #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" namespace cel::internal { bool SkipLengthValue(absl::Cord& data, ProtoWireType type) { switch (type) { case ProtoWireType::kVarint: if (auto result = VarintDecode<uint64_t>(data); ABSL_PREDICT_TRUE(result.has_value())) { data.RemovePrefix(result->size_bytes); return true; } return false; case ProtoWireType::kFixed64: if (ABSL_PREDICT_FALSE(data.size() < 8)) { return false; } data.RemovePrefix(8); return true; case ProtoWireType::kLengthDelimited: if (auto result = VarintDecode<uint32_t>(data); ABSL_PREDICT_TRUE(result.has_value())) { if (ABSL_PREDICT_TRUE(data.size() - result->size_bytes >= result->value)) { data.RemovePrefix(result->size_bytes + result->value); return true; } } return false; case ProtoWireType::kFixed32: if (ABSL_PREDICT_FALSE(data.size() < 4)) { return false; } data.RemovePrefix(4); return true; case ProtoWireType::kStartGroup: ABSL_FALLTHROUGH_INTENDED; case ProtoWireType::kEndGroup: ABSL_FALLTHROUGH_INTENDED; default: return false; } } absl::StatusOr<ProtoWireTag> ProtoWireDecoder::ReadTag() { ABSL_DCHECK(!tag_.has_value()); auto tag = internal::VarintDecode<uint32_t>(data_); if (ABSL_PREDICT_FALSE(!tag.has_value())) { return absl::DataLossError( absl::StrCat("malformed tag encountered decoding ", message_)); } auto field = internal::DecodeProtoWireTag(tag->value); if (ABSL_PREDICT_FALSE(!field.has_value())) { return absl::DataLossError( absl::StrCat("invalid wire type or field number encountered decoding ", message_, ": ", static_cast<std::string>(data_))); } data_.RemovePrefix(tag->size_bytes); tag_.emplace(*field); return *field; } absl::Status ProtoWireDecoder::SkipLengthValue() { ABSL_DCHECK(tag_.has_value()); if (ABSL_PREDICT_FALSE(!internal::SkipLengthValue(data_, tag_->type()))) { return absl::DataLossError( absl::StrCat("malformed length or value encountered decoding field ", tag_->field_number(), " of ", message_)); } tag_.reset(); return absl::OkStatus(); } absl::StatusOr<absl::Cord> ProtoWireDecoder::ReadLengthDelimited() { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kLengthDelimited); auto length = internal::VarintDecode<uint32_t>(data_); if (ABSL_PREDICT_FALSE(!length.has_value())) { return absl::DataLossError( absl::StrCat("malformed length encountered decoding field ", tag_->field_number(), " of ", message_)); } data_.RemovePrefix(length->size_bytes); if (ABSL_PREDICT_FALSE(data_.size() < length->value)) { return absl::DataLossError(absl::StrCat( "out of range length encountered decoding field ", tag_->field_number(), " of ", message_, ": ", length->value)); } auto result = data_.Subcord(0, length->value); data_.RemovePrefix(length->value); tag_.reset(); return result; } absl::Status ProtoWireEncoder::WriteTag(ProtoWireTag tag) { ABSL_DCHECK(!tag_.has_value()); if (ABSL_PREDICT_FALSE(tag.field_number() == 0)) { return absl::InvalidArgumentError( absl::StrCat("invalid field number encountered encoding ", message_)); } if (ABSL_PREDICT_FALSE(!ProtoWireTypeIsValid(tag.type()))) { return absl::InvalidArgumentError( absl::StrCat("invalid wire type encountered encoding field ", tag.field_number(), " of ", message_)); } VarintEncode(static_cast<uint32_t>(tag), data_); tag_.emplace(tag); return absl::OkStatus(); } absl::Status ProtoWireEncoder::WriteLengthDelimited(absl::Cord data) { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kLengthDelimited); if (ABSL_PREDICT_FALSE(data.size() > std::numeric_limits<uint32_t>::max())) { return absl::InvalidArgumentError( absl::StrCat("out of range length encountered encoding field ", tag_->field_number(), " of ", message_)); } VarintEncode(static_cast<uint32_t>(data.size()), data_); data_.Append(std::move(data)); tag_.reset(); return absl::OkStatus(); } absl::Status ProtoWireEncoder::WriteLengthDelimited(absl::string_view data) { ABSL_DCHECK(tag_.has_value() && tag_->type() == ProtoWireType::kLengthDelimited); if (ABSL_PREDICT_FALSE(data.size() > std::numeric_limits<uint32_t>::max())) { return absl::InvalidArgumentError( absl::StrCat("out of range length encountered encoding field ", tag_->field_number(), " of ", message_)); } VarintEncode(static_cast<uint32_t>(data.size()), data_); data_.Append(data); tag_.reset(); return absl::OkStatus(); } }
#include "internal/proto_wire.h" #include <limits> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "internal/testing.h" namespace cel::internal { template <typename T> inline constexpr bool operator==(const VarintDecodeResult<T>& lhs, const VarintDecodeResult<T>& rhs) { return lhs.value == rhs.value && lhs.size_bytes == rhs.size_bytes; } inline constexpr bool operator==(const ProtoWireTag& lhs, const ProtoWireTag& rhs) { return lhs.field_number() == rhs.field_number() && lhs.type() == rhs.type(); } namespace { using testing::Eq; using testing::Optional; using cel::internal::IsOkAndHolds; TEST(Varint, Size) { EXPECT_EQ(VarintSize(int32_t{-1}), VarintSize(std::numeric_limits<uint64_t>::max())); EXPECT_EQ(VarintSize(int64_t{-1}), VarintSize(std::numeric_limits<uint64_t>::max())); } TEST(Varint, MaxSize) { EXPECT_EQ(kMaxVarintSize<bool>, 1); EXPECT_EQ(kMaxVarintSize<int32_t>, 10); EXPECT_EQ(kMaxVarintSize<int64_t>, 10); EXPECT_EQ(kMaxVarintSize<uint32_t>, 5); EXPECT_EQ(kMaxVarintSize<uint64_t>, 10); } namespace { template <typename T> absl::Cord VarintEncode(T value) { absl::Cord cord; internal::VarintEncode(value, cord); return cord; } } TEST(Varint, Encode) { EXPECT_EQ(VarintEncode(true), "\x01"); EXPECT_EQ(VarintEncode(int32_t{1}), "\x01"); EXPECT_EQ(VarintEncode(int64_t{1}), "\x01"); EXPECT_EQ(VarintEncode(uint32_t{1}), "\x01"); EXPECT_EQ(VarintEncode(uint64_t{1}), "\x01"); EXPECT_EQ(VarintEncode(int32_t{-1}), VarintEncode(std::numeric_limits<uint64_t>::max())); EXPECT_EQ(VarintEncode(int64_t{-1}), VarintEncode(std::numeric_limits<uint64_t>::max())); EXPECT_EQ(VarintEncode(std::numeric_limits<uint32_t>::max()), "\xff\xff\xff\xff\x0f"); EXPECT_EQ(VarintEncode(std::numeric_limits<uint64_t>::max()), "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01"); } TEST(Varint, Decode) { EXPECT_THAT(VarintDecode<bool>(absl::Cord("\x01")), Optional(Eq(VarintDecodeResult<bool>{true, 1}))); EXPECT_THAT(VarintDecode<int32_t>(absl::Cord("\x01")), Optional(Eq(VarintDecodeResult<int32_t>{1, 1}))); EXPECT_THAT(VarintDecode<int64_t>(absl::Cord("\x01")), Optional(Eq(VarintDecodeResult<int64_t>{1, 1}))); EXPECT_THAT(VarintDecode<uint32_t>(absl::Cord("\x01")), Optional(Eq(VarintDecodeResult<uint32_t>{1, 1}))); EXPECT_THAT(VarintDecode<uint64_t>(absl::Cord("\x01")), Optional(Eq(VarintDecodeResult<uint64_t>{1, 1}))); EXPECT_THAT(VarintDecode<uint32_t>(absl::Cord("\xff\xff\xff\xff\x0f")), Optional(Eq(VarintDecodeResult<uint32_t>{ std::numeric_limits<uint32_t>::max(), 5}))); EXPECT_THAT(VarintDecode<int64_t>( absl::Cord("\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01")), Optional(Eq(VarintDecodeResult<int64_t>{int64_t{-1}, 10}))); EXPECT_THAT(VarintDecode<uint64_t>( absl::Cord("\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01")), Optional(Eq(VarintDecodeResult<uint64_t>{ std::numeric_limits<uint64_t>::max(), 10}))); } namespace { template <typename T> absl::Cord Fixed64Encode(T value) { absl::Cord cord; internal::Fixed64Encode(value, cord); return cord; } template <typename T> absl::Cord Fixed32Encode(T value) { absl::Cord cord; internal::Fixed32Encode(value, cord); return cord; } } TEST(Fixed64, Encode) { EXPECT_EQ(Fixed64Encode(0.0), Fixed64Encode(uint64_t{0})); } TEST(Fixed64, Decode) { EXPECT_THAT(Fixed64Decode<double>(Fixed64Encode(0.0)), Optional(Eq(0.0))); } TEST(Fixed32, Encode) { EXPECT_EQ(Fixed32Encode(0.0f), Fixed32Encode(uint32_t{0})); } TEST(Fixed32, Decode) { EXPECT_THAT(Fixed32Decode<float>( absl::Cord(absl::string_view("\x00\x00\x00\x00", 4))), Optional(Eq(0.0))); } TEST(DecodeProtoWireTag, Uint64TooLarge) { EXPECT_THAT(DecodeProtoWireTag(uint64_t{1} << 32), Eq(absl::nullopt)); } TEST(DecodeProtoWireTag, Uint64ZeroFieldNumber) { EXPECT_THAT(DecodeProtoWireTag(uint64_t{0}), Eq(absl::nullopt)); } TEST(DecodeProtoWireTag, Uint32ZeroFieldNumber) { EXPECT_THAT(DecodeProtoWireTag(uint32_t{0}), Eq(absl::nullopt)); } TEST(DecodeProtoWireTag, Success) { EXPECT_THAT(DecodeProtoWireTag(uint64_t{1} << 3), Optional(Eq(ProtoWireTag(1, ProtoWireType::kVarint)))); EXPECT_THAT(DecodeProtoWireTag(uint32_t{1} << 3), Optional(Eq(ProtoWireTag(1, ProtoWireType::kVarint)))); } void TestSkipLengthValueSuccess(absl::Cord data, ProtoWireType type, size_t skipped) { size_t before = data.size(); EXPECT_TRUE(SkipLengthValue(data, type)); EXPECT_EQ(before - skipped, data.size()); } void TestSkipLengthValueFailure(absl::Cord data, ProtoWireType type) { EXPECT_FALSE(SkipLengthValue(data, type)); } TEST(SkipLengthValue, Varint) { TestSkipLengthValueSuccess( absl::Cord("\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01"), ProtoWireType::kVarint, 10); TestSkipLengthValueSuccess(absl::Cord("\x01"), ProtoWireType::kVarint, 1); TestSkipLengthValueFailure( absl::Cord("\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01"), ProtoWireType::kVarint); } TEST(SkipLengthValue, Fixed64) { TestSkipLengthValueSuccess( absl::Cord( absl::string_view("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 8)), ProtoWireType::kFixed64, 8); TestSkipLengthValueFailure(absl::Cord(absl::string_view("\x00", 1)), ProtoWireType::kFixed64); } TEST(SkipLengthValue, LengthDelimited) { TestSkipLengthValueSuccess(absl::Cord(absl::string_view("\x00", 1)), ProtoWireType::kLengthDelimited, 1); TestSkipLengthValueSuccess(absl::Cord(absl::string_view("\x01\x00", 2)), ProtoWireType::kLengthDelimited, 2); TestSkipLengthValueFailure(absl::Cord("\x01"), ProtoWireType::kLengthDelimited); } TEST(SkipLengthValue, Fixed32) { TestSkipLengthValueSuccess( absl::Cord(absl::string_view("\x00\x00\x00\x00", 4)), ProtoWireType::kFixed32, 4); TestSkipLengthValueFailure(absl::Cord(absl::string_view("\x00", 1)), ProtoWireType::kFixed32); } TEST(SkipLengthValue, Decoder) { { ProtoWireDecoder decoder("", absl::Cord(absl::string_view("\x0a\x00", 2))); ASSERT_TRUE(decoder.HasNext()); EXPECT_THAT( decoder.ReadTag(), IsOkAndHolds(Eq(ProtoWireTag(1, ProtoWireType::kLengthDelimited)))); EXPECT_OK(decoder.SkipLengthValue()); ASSERT_FALSE(decoder.HasNext()); } } TEST(ProtoWireEncoder, BadTag) { absl::Cord data; ProtoWireEncoder encoder("foo.Bar", data); EXPECT_TRUE(encoder.empty()); EXPECT_EQ(encoder.size(), 0); EXPECT_OK(encoder.WriteTag(ProtoWireTag(1, ProtoWireType::kVarint))); EXPECT_OK(encoder.WriteVarint(1)); encoder.EnsureFullyEncoded(); EXPECT_FALSE(encoder.empty()); EXPECT_EQ(encoder.size(), 2); EXPECT_EQ(data, "\x08\x01"); } TEST(ProtoWireEncoder, Varint) { absl::Cord data; ProtoWireEncoder encoder("foo.Bar", data); EXPECT_TRUE(encoder.empty()); EXPECT_EQ(encoder.size(), 0); EXPECT_OK(encoder.WriteTag(ProtoWireTag(1, ProtoWireType::kVarint))); EXPECT_OK(encoder.WriteVarint(1)); encoder.EnsureFullyEncoded(); EXPECT_FALSE(encoder.empty()); EXPECT_EQ(encoder.size(), 2); EXPECT_EQ(data, "\x08\x01"); } TEST(ProtoWireEncoder, Fixed32) { absl::Cord data; ProtoWireEncoder encoder("foo.Bar", data); EXPECT_TRUE(encoder.empty()); EXPECT_EQ(encoder.size(), 0); EXPECT_OK(encoder.WriteTag(ProtoWireTag(1, ProtoWireType::kFixed32))); EXPECT_OK(encoder.WriteFixed32(0.0f)); encoder.EnsureFullyEncoded(); EXPECT_FALSE(encoder.empty()); EXPECT_EQ(encoder.size(), 5); EXPECT_EQ(data, absl::string_view("\x0d\x00\x00\x00\x00", 5)); } TEST(ProtoWireEncoder, Fixed64) { absl::Cord data; ProtoWireEncoder encoder("foo.Bar", data); EXPECT_TRUE(encoder.empty()); EXPECT_EQ(encoder.size(), 0); EXPECT_OK(encoder.WriteTag(ProtoWireTag(1, ProtoWireType::kFixed64))); EXPECT_OK(encoder.WriteFixed64(0.0)); encoder.EnsureFullyEncoded(); EXPECT_FALSE(encoder.empty()); EXPECT_EQ(encoder.size(), 9); EXPECT_EQ(data, absl::string_view("\x09\x00\x00\x00\x00\x00\x00\x00\x00", 9)); } TEST(ProtoWireEncoder, LengthDelimited) { absl::Cord data; ProtoWireEncoder encoder("foo.Bar", data); EXPECT_TRUE(encoder.empty()); EXPECT_EQ(encoder.size(), 0); EXPECT_OK(encoder.WriteTag(ProtoWireTag(1, ProtoWireType::kLengthDelimited))); EXPECT_OK(encoder.WriteLengthDelimited(absl::Cord("foo"))); encoder.EnsureFullyEncoded(); EXPECT_FALSE(encoder.empty()); EXPECT_EQ(encoder.size(), 5); EXPECT_EQ(data, "\x0a\x03" "foo"); } } }
51
cpp
google/cel-cpp
overflow
internal/overflow.cc
internal/overflow_test.cc
#ifndef THIRD_PARTY_CEL_CPP_COMMON_OVERFLOW_H_ #define THIRD_PARTY_CEL_CPP_COMMON_OVERFLOW_H_ #include <cstdint> #include "absl/status/statusor.h" #include "absl/time/time.h" namespace cel::internal { absl::StatusOr<int64_t> CheckedAdd(int64_t x, int64_t y); absl::StatusOr<int64_t> CheckedSub(int64_t x, int64_t y); absl::StatusOr<int64_t> CheckedNegation(int64_t v); absl::StatusOr<int64_t> CheckedMul(int64_t x, int64_t y); absl::StatusOr<int64_t> CheckedDiv(int64_t x, int64_t y); absl::StatusOr<int64_t> CheckedMod(int64_t x, int64_t y); absl::StatusOr<uint64_t> CheckedAdd(uint64_t x, uint64_t y); absl::StatusOr<uint64_t> CheckedSub(uint64_t x, uint64_t y); absl::StatusOr<uint64_t> CheckedMul(uint64_t x, uint64_t y); absl::StatusOr<uint64_t> CheckedDiv(uint64_t x, uint64_t y); absl::StatusOr<uint64_t> CheckedMod(uint64_t x, uint64_t y); absl::StatusOr<absl::Duration> CheckedAdd(absl::Duration x, absl::Duration y); absl::StatusOr<absl::Duration> CheckedSub(absl::Duration x, absl::Duration y); absl::StatusOr<absl::Duration> CheckedNegation(absl::Duration v); absl::StatusOr<absl::Time> CheckedAdd(absl::Time t, absl::Duration d); absl::StatusOr<absl::Time> CheckedSub(absl::Time t, absl::Duration d); absl::StatusOr<absl::Duration> CheckedSub(absl::Time t1, absl::Time t2); absl::StatusOr<int64_t> CheckedDoubleToInt64(double v); absl::StatusOr<uint64_t> CheckedDoubleToUint64(double v); absl::StatusOr<uint64_t> CheckedInt64ToUint64(int64_t v); absl::StatusOr<int32_t> CheckedInt64ToInt32(int64_t v); absl::StatusOr<int64_t> CheckedUint64ToInt64(uint64_t v); absl::StatusOr<uint32_t> CheckedUint64ToUint32(uint64_t v); } #endif #include "internal/overflow.h" #include <cmath> #include <cstdint> #include <limits> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/time/time.h" #include "internal/status_macros.h" #include "internal/time.h" namespace cel::internal { namespace { constexpr int64_t kInt32Max = std::numeric_limits<int32_t>::max(); constexpr int64_t kInt32Min = std::numeric_limits<int32_t>::lowest(); constexpr int64_t kInt64Max = std::numeric_limits<int64_t>::max(); constexpr int64_t kInt64Min = std::numeric_limits<int64_t>::lowest(); constexpr uint64_t kUint32Max = std::numeric_limits<uint32_t>::max(); ABSL_ATTRIBUTE_UNUSED 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); const double kDoubleTwoTo64 = std::ldexp(1.0, 64); const absl::Duration kOneSecondDuration = absl::Seconds(1); const int64_t kOneSecondNanos = absl::ToInt64Nanoseconds(kOneSecondDuration); const int64_t kMinUnixTime = absl::ToInt64Seconds(MinTimestamp() - absl::UnixEpoch()); const int64_t kMaxUnixTime = absl::ToInt64Seconds(MaxTimestamp() - absl::UnixEpoch()); absl::Status CheckRange(bool valid_expression, absl::string_view error_message) { return valid_expression ? absl::OkStatus() : absl::OutOfRangeError(error_message); } absl::Status CheckArgument(bool valid_expression, absl::string_view error_message) { return valid_expression ? absl::OkStatus() : absl::InvalidArgumentError(error_message); } bool IsFinite(absl::Duration d) { return d != absl::InfiniteDuration() && d != -absl::InfiniteDuration(); } bool IsFinite(absl::Time t) { return t != absl::InfiniteFuture() && t != absl::InfinitePast(); } } absl::StatusOr<int64_t> CheckedAdd(int64_t x, int64_t y) { #if ABSL_HAVE_BUILTIN(__builtin_add_overflow) int64_t sum; if (!__builtin_add_overflow(x, y, &sum)) { return sum; } return absl::OutOfRangeError("integer overflow"); #else CEL_RETURN_IF_ERROR(CheckRange( y > 0 ? x <= kInt64Max - y : x >= kInt64Min - y, "integer overflow")); return x + y; #endif } absl::StatusOr<int64_t> CheckedSub(int64_t x, int64_t y) { #if ABSL_HAVE_BUILTIN(__builtin_sub_overflow) int64_t diff; if (!__builtin_sub_overflow(x, y, &diff)) { return diff; } return absl::OutOfRangeError("integer overflow"); #else CEL_RETURN_IF_ERROR(CheckRange( y < 0 ? x <= kInt64Max + y : x >= kInt64Min + y, "integer overflow")); return x - y; #endif } absl::StatusOr<int64_t> CheckedNegation(int64_t v) { #if ABSL_HAVE_BUILTIN(__builtin_mul_overflow) int64_t prod; if (!__builtin_mul_overflow(v, -1, &prod)) { return prod; } return absl::OutOfRangeError("integer overflow"); #else CEL_RETURN_IF_ERROR(CheckRange(v != kInt64Min, "integer overflow")); return -v; #endif } absl::StatusOr<int64_t> CheckedMul(int64_t x, int64_t y) { #if ABSL_HAVE_BUILTIN(__builtin_mul_overflow) int64_t prod; if (!__builtin_mul_overflow(x, y, &prod)) { return prod; } return absl::OutOfRangeError("integer overflow"); #else CEL_RETURN_IF_ERROR( CheckRange(!((x == -1 && y == kInt64Min) || (y == -1 && x == kInt64Min) || (x > 0 && y > 0 && x > kInt64Max / y) || (x < 0 && y < 0 && x < kInt64Max / y) || (x > 0 && y < 0 && y < kInt64Min / x) || (x < 0 && y > 0 && x < kInt64Min / y)), "integer overflow")); return x * y; #endif } absl::StatusOr<int64_t> CheckedDiv(int64_t x, int64_t y) { CEL_RETURN_IF_ERROR( CheckRange(x != kInt64Min || y != -1, "integer overflow")); CEL_RETURN_IF_ERROR(CheckArgument(y != 0, "divide by zero")); return x / y; } absl::StatusOr<int64_t> CheckedMod(int64_t x, int64_t y) { CEL_RETURN_IF_ERROR( CheckRange(x != kInt64Min || y != -1, "integer overflow")); CEL_RETURN_IF_ERROR(CheckArgument(y != 0, "modulus by zero")); return x % y; } absl::StatusOr<uint64_t> CheckedAdd(uint64_t x, uint64_t y) { #if ABSL_HAVE_BUILTIN(__builtin_add_overflow) uint64_t sum; if (!__builtin_add_overflow(x, y, &sum)) { return sum; } return absl::OutOfRangeError("unsigned integer overflow"); #else CEL_RETURN_IF_ERROR( CheckRange(x <= kUint64Max - y, "unsigned integer overflow")); return x + y; #endif } absl::StatusOr<uint64_t> CheckedSub(uint64_t x, uint64_t y) { #if ABSL_HAVE_BUILTIN(__builtin_sub_overflow) uint64_t diff; if (!__builtin_sub_overflow(x, y, &diff)) { return diff; } return absl::OutOfRangeError("unsigned integer overflow"); #else CEL_RETURN_IF_ERROR(CheckRange(y <= x, "unsigned integer overflow")); return x - y; #endif } absl::StatusOr<uint64_t> CheckedMul(uint64_t x, uint64_t y) { #if ABSL_HAVE_BUILTIN(__builtin_mul_overflow) uint64_t prod; if (!__builtin_mul_overflow(x, y, &prod)) { return prod; } return absl::OutOfRangeError("unsigned integer overflow"); #else CEL_RETURN_IF_ERROR( CheckRange(y == 0 || x <= kUint64Max / y, "unsigned integer overflow")); return x * y; #endif } absl::StatusOr<uint64_t> CheckedDiv(uint64_t x, uint64_t y) { CEL_RETURN_IF_ERROR(CheckArgument(y != 0, "divide by zero")); return x / y; } absl::StatusOr<uint64_t> CheckedMod(uint64_t x, uint64_t y) { CEL_RETURN_IF_ERROR(CheckArgument(y != 0, "modulus by zero")); return x % y; } absl::StatusOr<absl::Duration> CheckedAdd(absl::Duration x, absl::Duration y) { CEL_RETURN_IF_ERROR( CheckRange(IsFinite(x) && IsFinite(y), "integer overflow")); CEL_ASSIGN_OR_RETURN(int64_t nanos, CheckedAdd(absl::ToInt64Nanoseconds(x), absl::ToInt64Nanoseconds(y))); return absl::Nanoseconds(nanos); } absl::StatusOr<absl::Duration> CheckedSub(absl::Duration x, absl::Duration y) { CEL_RETURN_IF_ERROR( CheckRange(IsFinite(x) && IsFinite(y), "integer overflow")); CEL_ASSIGN_OR_RETURN(int64_t nanos, CheckedSub(absl::ToInt64Nanoseconds(x), absl::ToInt64Nanoseconds(y))); return absl::Nanoseconds(nanos); } absl::StatusOr<absl::Duration> CheckedNegation(absl::Duration v) { CEL_RETURN_IF_ERROR(CheckRange(IsFinite(v), "integer overflow")); CEL_ASSIGN_OR_RETURN(int64_t nanos, CheckedNegation(absl::ToInt64Nanoseconds(v))); return absl::Nanoseconds(nanos); } absl::StatusOr<absl::Time> CheckedAdd(absl::Time t, absl::Duration d) { CEL_RETURN_IF_ERROR( CheckRange(IsFinite(t) && IsFinite(d), "timestamp overflow")); const int64_t s1 = absl::ToUnixSeconds(t); const int64_t ns1 = (t - absl::FromUnixSeconds(s1)) / absl::Nanoseconds(1); const int64_t s2 = d / kOneSecondDuration; const int64_t ns2 = absl::ToInt64Nanoseconds(d % kOneSecondDuration); CEL_ASSIGN_OR_RETURN(int64_t s, CheckedAdd(s1, s2)); absl::Duration ns = absl::Nanoseconds(ns2 + ns1); if (ns < absl::ZeroDuration() || ns >= kOneSecondDuration) { CEL_ASSIGN_OR_RETURN(s, CheckedAdd(s, ns / kOneSecondDuration)); ns -= (ns / kOneSecondDuration) * kOneSecondDuration; if (ns < absl::ZeroDuration()) { CEL_ASSIGN_OR_RETURN(s, CheckedAdd(s, -1)); ns += kOneSecondDuration; } } CEL_RETURN_IF_ERROR( CheckRange(s >= kMinUnixTime && s <= kMaxUnixTime, "timestamp overflow")); return absl::FromUnixSeconds(s) + ns; } absl::StatusOr<absl::Time> CheckedSub(absl::Time t, absl::Duration d) { CEL_ASSIGN_OR_RETURN(auto neg_duration, CheckedNegation(d)); return CheckedAdd(t, neg_duration); } absl::StatusOr<absl::Duration> CheckedSub(absl::Time t1, absl::Time t2) { CEL_RETURN_IF_ERROR( CheckRange(IsFinite(t1) && IsFinite(t2), "integer overflow")); const int64_t s1 = absl::ToUnixSeconds(t1); const int64_t ns1 = (t1 - absl::FromUnixSeconds(s1)) / absl::Nanoseconds(1); const int64_t s2 = absl::ToUnixSeconds(t2); const int64_t ns2 = (t2 - absl::FromUnixSeconds(s2)) / absl::Nanoseconds(1); CEL_ASSIGN_OR_RETURN(int64_t s, CheckedSub(s1, s2)); absl::Duration ns = absl::Nanoseconds(ns1 - ns2); CEL_ASSIGN_OR_RETURN(const int64_t t, CheckedMul(s, kOneSecondNanos)); CEL_ASSIGN_OR_RETURN(const int64_t v, CheckedAdd(t, absl::ToInt64Nanoseconds(ns))); return absl::Nanoseconds(v); } absl::StatusOr<int64_t> CheckedDoubleToInt64(double v) { CEL_RETURN_IF_ERROR( CheckRange(std::isfinite(v) && v < kDoubleToIntMax && v > kDoubleToIntMin, "double out of int64_t range")); return static_cast<int64_t>(v); } absl::StatusOr<uint64_t> CheckedDoubleToUint64(double v) { CEL_RETURN_IF_ERROR( CheckRange(std::isfinite(v) && v >= 0 && v < kDoubleTwoTo64, "double out of uint64_t range")); return static_cast<uint64_t>(v); } absl::StatusOr<uint64_t> CheckedInt64ToUint64(int64_t v) { CEL_RETURN_IF_ERROR(CheckRange(v >= 0, "int64 out of uint64_t range")); return static_cast<uint64_t>(v); } absl::StatusOr<int32_t> CheckedInt64ToInt32(int64_t v) { CEL_RETURN_IF_ERROR( CheckRange(v >= kInt32Min && v <= kInt32Max, "int64 out of int32_t range")); return static_cast<int32_t>(v); } absl::StatusOr<int64_t> CheckedUint64ToInt64(uint64_t v) { CEL_RETURN_IF_ERROR( CheckRange(v <= kUintToIntMax, "uint64 out of int64_t range")); return static_cast<int64_t>(v); } absl::StatusOr<uint32_t> CheckedUint64ToUint32(uint64_t v) { CEL_RETURN_IF_ERROR( CheckRange(v <= kUint32Max, "uint64 out of uint32_t range")); return static_cast<uint32_t>(v); } }
#include "internal/overflow.h" #include <cstdint> #include <limits> #include <string> #include <vector> #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/time/time.h" #include "internal/testing.h" namespace cel::internal { namespace { using testing::HasSubstr; using testing::ValuesIn; template <typename T> struct TestCase { std::string test_name; absl::FunctionRef<absl::StatusOr<T>()> op; absl::StatusOr<T> result; }; template <typename T> void ExpectResult(const T& test_case) { auto result = test_case.op(); ASSERT_EQ(result.status().code(), test_case.result.status().code()); if (result.ok()) { EXPECT_EQ(*result, *test_case.result); } else { EXPECT_THAT(result.status().message(), HasSubstr(test_case.result.status().message())); } } using IntTestCase = TestCase<int64_t>; using CheckedIntResultTest = testing::TestWithParam<IntTestCase>; TEST_P(CheckedIntResultTest, IntOperations) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( CheckedIntMathTest, CheckedIntResultTest, ValuesIn(std::vector<IntTestCase>{ {"OneAddOne", [] { return CheckedAdd(1L, 1L); }, 2L}, {"ZeroAddOne", [] { return CheckedAdd(0, 1L); }, 1L}, {"ZeroAddMinusOne", [] { return CheckedAdd(0, -1L); }, -1L}, {"OneAddZero", [] { return CheckedAdd(1L, 0); }, 1L}, {"MinusOneAddZero", [] { return CheckedAdd(-1L, 0); }, -1L}, {"OneAddIntMax", [] { return CheckedAdd(1L, std::numeric_limits<int64_t>::max()); }, absl::OutOfRangeError("integer overflow")}, {"MinusOneAddIntMin", [] { return CheckedAdd(-1L, std::numeric_limits<int64_t>::lowest()); }, absl::OutOfRangeError("integer overflow")}, {"TwoSubThree", [] { return CheckedSub(2L, 3L); }, -1L}, {"TwoSubZero", [] { return CheckedSub(2L, 0); }, 2L}, {"ZeroSubTwo", [] { return CheckedSub(0, 2L); }, -2L}, {"MinusTwoSubThree", [] { return CheckedSub(-2L, 3L); }, -5L}, {"MinusTwoSubZero", [] { return CheckedSub(-2L, 0); }, -2L}, {"ZeroSubMinusTwo", [] { return CheckedSub(0, -2L); }, 2L}, {"IntMinSubIntMax", [] { return CheckedSub(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::lowest()); }, absl::OutOfRangeError("integer overflow")}, {"TwoMulThree", [] { return CheckedMul(2L, 3L); }, 6L}, {"MinusTwoMulThree", [] { return CheckedMul(-2L, 3L); }, -6L}, {"MinusTwoMulMinusThree", [] { return CheckedMul(-2L, -3L); }, 6L}, {"TwoMulMinusThree", [] { return CheckedMul(2L, -3L); }, -6L}, {"TwoMulIntMax", [] { return CheckedMul(2L, std::numeric_limits<int64_t>::max()); }, absl::OutOfRangeError("integer overflow")}, {"MinusOneMulIntMin", [] { return CheckedMul(-1L, std::numeric_limits<int64_t>::lowest()); }, absl::OutOfRangeError("integer overflow")}, {"IntMinMulMinusOne", [] { return CheckedMul(std::numeric_limits<int64_t>::lowest(), -1L); }, absl::OutOfRangeError("integer overflow")}, {"IntMinMulZero", [] { return CheckedMul(std::numeric_limits<int64_t>::lowest(), 0); }, 0}, {"ZeroMulIntMin", [] { return CheckedMul(0, std::numeric_limits<int64_t>::lowest()); }, 0}, {"IntMaxMulZero", [] { return CheckedMul(std::numeric_limits<int64_t>::max(), 0); }, 0}, {"ZeroMulIntMax", [] { return CheckedMul(0, std::numeric_limits<int64_t>::max()); }, 0}, {"ZeroDivOne", [] { return CheckedDiv(0, 1L); }, 0}, {"TenDivTwo", [] { return CheckedDiv(10L, 2L); }, 5}, {"TenDivMinusOne", [] { return CheckedDiv(10L, -1L); }, -10}, {"MinusTenDivMinusOne", [] { return CheckedDiv(-10L, -1L); }, 10}, {"MinusTenDivTwo", [] { return CheckedDiv(-10L, 2L); }, -5}, {"OneDivZero", [] { return CheckedDiv(1L, 0L); }, absl::InvalidArgumentError("divide by zero")}, {"IntMinDivMinusOne", [] { return CheckedDiv(std::numeric_limits<int64_t>::lowest(), -1L); }, absl::OutOfRangeError("integer overflow")}, {"ZeroModTwo", [] { return CheckedMod(0, 2L); }, 0}, {"TwoModTwo", [] { return CheckedMod(2L, 2L); }, 0}, {"ThreeModTwo", [] { return CheckedMod(3L, 2L); }, 1L}, {"TwoModZero", [] { return CheckedMod(2L, 0); }, absl::InvalidArgumentError("modulus by zero")}, {"IntMinModTwo", [] { return CheckedMod(std::numeric_limits<int64_t>::lowest(), 2L); }, 0}, {"IntMaxModMinusOne", [] { return CheckedMod(std::numeric_limits<int64_t>::max(), -1L); }, 0}, {"IntMinModMinusOne", [] { return CheckedMod(std::numeric_limits<int64_t>::lowest(), -1L); }, absl::OutOfRangeError("integer overflow")}, {"NegateOne", [] { return CheckedNegation(1L); }, -1L}, {"NegateMinInt64", [] { return CheckedNegation(std::numeric_limits<int64_t>::lowest()); }, absl::OutOfRangeError("integer overflow")}, {"Uint64Conversion", [] { return CheckedUint64ToInt64(1UL); }, 1L}, {"Uint32MaxConversion", [] { return CheckedUint64ToInt64( static_cast<uint64_t>(std::numeric_limits<int64_t>::max())); }, std::numeric_limits<int64_t>::max()}, {"Uint32MaxConversionError", [] { return CheckedUint64ToInt64( static_cast<uint64_t>(std::numeric_limits<uint64_t>::max())); }, absl::OutOfRangeError("out of int64_t range")}, {"DoubleConversion", [] { return CheckedDoubleToInt64(100.1); }, 100L}, {"DoubleInt64MaxConversionError", [] { return CheckedDoubleToInt64( static_cast<double>(std::numeric_limits<int64_t>::max())); }, absl::OutOfRangeError("out of int64_t range")}, {"DoubleInt64MaxMinus512Conversion", [] { return CheckedDoubleToInt64( static_cast<double>(std::numeric_limits<int64_t>::max() - 512)); }, std::numeric_limits<int64_t>::max() - 1023}, {"DoubleInt64MaxMinus1024Conversion", [] { return CheckedDoubleToInt64( static_cast<double>(std::numeric_limits<int64_t>::max() - 1024)); }, std::numeric_limits<int64_t>::max() - 1023}, {"DoubleInt64MinConversionError", [] { return CheckedDoubleToInt64( static_cast<double>(std::numeric_limits<int64_t>::lowest())); }, absl::OutOfRangeError("out of int64_t range")}, {"DoubleInt64MinMinusOneConversionError", [] { return CheckedDoubleToInt64( static_cast<double>(std::numeric_limits<int64_t>::lowest()) - 1.0); }, absl::OutOfRangeError("out of int64_t range")}, {"DoubleInt64MinMinus511ConversionError", [] { return CheckedDoubleToInt64( static_cast<double>(std::numeric_limits<int64_t>::lowest()) - 511.0); }, absl::OutOfRangeError("out of int64_t range")}, {"InfiniteConversionError", [] { return CheckedDoubleToInt64(std::numeric_limits<double>::infinity()); }, absl::OutOfRangeError("out of int64_t range")}, {"NegRangeConversionError", [] { return CheckedDoubleToInt64(-1.0e99); }, absl::OutOfRangeError("out of int64_t range")}, {"PosRangeConversionError", [] { return CheckedDoubleToInt64(1.0e99); }, absl::OutOfRangeError("out of int64_t range")}, }), [](const testing::TestParamInfo<CheckedIntResultTest::ParamType>& info) { return info.param.test_name; }); using UintTestCase = TestCase<uint64_t>; using CheckedUintResultTest = testing::TestWithParam<UintTestCase>; TEST_P(CheckedUintResultTest, UnsignedOperations) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( CheckedUintMathTest, CheckedUintResultTest, ValuesIn(std::vector<UintTestCase>{ {"OneAddOne", [] { return CheckedAdd(1UL, 1UL); }, 2UL}, {"ZeroAddOne", [] { return CheckedAdd(0, 1UL); }, 1UL}, {"OneAddZero", [] { return CheckedAdd(1UL, 0); }, 1UL}, {"OneAddIntMax", [] { return CheckedAdd(1UL, std::numeric_limits<uint64_t>::max()); }, absl::OutOfRangeError("unsigned integer overflow")}, {"OneSubOne", [] { return CheckedSub(1UL, 1UL); }, 0}, {"ZeroSubOne", [] { return CheckedSub(0, 1UL); }, absl::OutOfRangeError("unsigned integer overflow")}, {"OneSubZero", [] { return CheckedSub(1UL, 0); }, 1UL}, {"OneMulOne", [] { return CheckedMul(1UL, 1UL); }, 1UL}, {"ZeroMulOne", [] { return CheckedMul(0, 1UL); }, 0}, {"OneMulZero", [] { return CheckedMul(1UL, 0); }, 0}, {"TwoMulUintMax", [] { return CheckedMul(2UL, std::numeric_limits<uint64_t>::max()); }, absl::OutOfRangeError("unsigned integer overflow")}, {"TwoDivTwo", [] { return CheckedDiv(2UL, 2UL); }, 1UL}, {"TwoDivFour", [] { return CheckedDiv(2UL, 4UL); }, 0}, {"OneDivZero", [] { return CheckedDiv(1UL, 0); }, absl::InvalidArgumentError("divide by zero")}, {"TwoModTwo", [] { return CheckedMod(2UL, 2UL); }, 0}, {"TwoModFour", [] { return CheckedMod(2UL, 4UL); }, 2UL}, {"OneModZero", [] { return CheckedMod(1UL, 0); }, absl::InvalidArgumentError("modulus by zero")}, {"Int64Conversion", [] { return CheckedInt64ToUint64(1L); }, 1UL}, {"Int64MaxConversion", [] { return CheckedInt64ToUint64(std::numeric_limits<int64_t>::max()); }, static_cast<uint64_t>(std::numeric_limits<int64_t>::max())}, {"NegativeInt64ConversionError", [] { return CheckedInt64ToUint64(-1L); }, absl::OutOfRangeError("out of uint64_t range")}, {"DoubleConversion", [] { return CheckedDoubleToUint64(100.1); }, 100UL}, {"DoubleUint64MaxConversionError", [] { return CheckedDoubleToUint64( static_cast<double>(std::numeric_limits<uint64_t>::max())); }, absl::OutOfRangeError("out of uint64_t range")}, {"DoubleUint64MaxMinus512Conversion", [] { return CheckedDoubleToUint64( static_cast<double>(std::numeric_limits<uint64_t>::max() - 512)); }, absl::OutOfRangeError("out of uint64_t range")}, {"DoubleUint64MaxMinus1024Conversion", [] { return CheckedDoubleToUint64(static_cast<double>( std::numeric_limits<uint64_t>::max() - 1024)); }, std::numeric_limits<uint64_t>::max() - 2047}, {"InfiniteConversionError", [] { return CheckedDoubleToUint64( std::numeric_limits<double>::infinity()); }, absl::OutOfRangeError("out of uint64_t range")}, {"NegConversionError", [] { return CheckedDoubleToUint64(-1.1); }, absl::OutOfRangeError("out of uint64_t range")}, {"NegRangeConversionError", [] { return CheckedDoubleToUint64(-1.0e99); }, absl::OutOfRangeError("out of uint64_t range")}, {"PosRangeConversionError", [] { return CheckedDoubleToUint64(1.0e99); }, absl::OutOfRangeError("out of uint64_t range")}, }), [](const testing::TestParamInfo<CheckedUintResultTest::ParamType>& info) { return info.param.test_name; }); using DurationTestCase = TestCase<absl::Duration>; using CheckedDurationResultTest = testing::TestWithParam<DurationTestCase>; TEST_P(CheckedDurationResultTest, DurationOperations) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( CheckedDurationMathTest, CheckedDurationResultTest, ValuesIn(std::vector<DurationTestCase>{ {"OneSecondAddOneSecond", [] { return CheckedAdd(absl::Seconds(1), absl::Seconds(1)); }, absl::Seconds(2)}, {"MaxDurationAddOneNano", [] { return CheckedAdd( absl::Nanoseconds(std::numeric_limits<int64_t>::max()), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"MinDurationAddMinusOneNano", [] { return CheckedAdd( absl::Nanoseconds(std::numeric_limits<int64_t>::lowest()), absl::Nanoseconds(-1)); }, absl::OutOfRangeError("integer overflow")}, {"InfinityAddOneNano", [] { return CheckedAdd(absl::InfiniteDuration(), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"NegInfinityAddOneNano", [] { return CheckedAdd(-absl::InfiniteDuration(), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"OneSecondAddInfinity", [] { return CheckedAdd(absl::Nanoseconds(1), absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, {"OneSecondAddNegInfinity", [] { return CheckedAdd(absl::Nanoseconds(1), -absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, {"OneSecondSubOneSecond", [] { return CheckedSub(absl::Seconds(1), absl::Seconds(1)); }, absl::ZeroDuration()}, {"MinDurationSubOneSecond", [] { return CheckedSub( absl::Nanoseconds(std::numeric_limits<int64_t>::lowest()), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"InfinitySubOneNano", [] { return CheckedSub(absl::InfiniteDuration(), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"NegInfinitySubOneNano", [] { return CheckedSub(-absl::InfiniteDuration(), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"OneNanoSubInfinity", [] { return CheckedSub(absl::Nanoseconds(1), absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, {"OneNanoSubNegInfinity", [] { return CheckedSub(absl::Nanoseconds(1), -absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, {"TimeSubOneSecond", [] { return CheckedSub(absl::FromUnixSeconds(100), absl::FromUnixSeconds(1)); }, absl::Seconds(99)}, {"TimeWithNanosPositive", [] { return CheckedSub(absl::FromUnixSeconds(2) + absl::Nanoseconds(1), absl::FromUnixSeconds(1) - absl::Nanoseconds(1)); }, absl::Seconds(1) + absl::Nanoseconds(2)}, {"TimeWithNanosNegative", [] { return CheckedSub(absl::FromUnixSeconds(1) + absl::Nanoseconds(1), absl::FromUnixSeconds(2) + absl::Seconds(1) - absl::Nanoseconds(1)); }, absl::Seconds(-2) + absl::Nanoseconds(2)}, {"MinTimestampMinusOne", [] { return CheckedSub( absl::FromUnixSeconds(std::numeric_limits<int64_t>::lowest()), absl::FromUnixSeconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"InfinitePastSubOneSecond", [] { return CheckedSub(absl::InfinitePast(), absl::FromUnixSeconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"InfiniteFutureSubOneMinusSecond", [] { return CheckedSub(absl::InfiniteFuture(), absl::FromUnixSeconds(-1)); }, absl::OutOfRangeError("integer overflow")}, {"InfiniteFutureSubInfinitePast", [] { return CheckedSub(absl::InfiniteFuture(), absl::InfinitePast()); }, absl::OutOfRangeError("integer overflow")}, {"InfinitePastSubInfiniteFuture", [] { return CheckedSub(absl::InfinitePast(), absl::InfiniteFuture()); }, absl::OutOfRangeError("integer overflow")}, {"NegateOneSecond", [] { return CheckedNegation(absl::Seconds(1)); }, absl::Seconds(-1)}, {"NegateMinDuration", [] { return CheckedNegation( absl::Nanoseconds(std::numeric_limits<int64_t>::lowest())); }, absl::OutOfRangeError("integer overflow")}, {"NegateInfiniteDuration", [] { return CheckedNegation(absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, {"NegateNegInfiniteDuration", [] { return CheckedNegation(-absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, }), [](const testing::TestParamInfo<CheckedDurationResultTest::ParamType>& info) { return info.param.test_name; }); using TimeTestCase = TestCase<absl::Time>; using CheckedTimeResultTest = testing::TestWithParam<TimeTestCase>; TEST_P(CheckedTimeResultTest, TimeDurationOperations) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( CheckedTimeDurationMathTest, CheckedTimeResultTest, ValuesIn(std::vector<TimeTestCase>{ {"DateAddOneHourMinusOneMilli", [] { return CheckedAdd(absl::FromUnixSeconds(3506), absl::Hours(1) + absl::Milliseconds(-1)); }, absl::FromUnixSeconds(7106) + absl::Milliseconds(-1)}, {"DateAddOneHourOneNano", [] { return CheckedAdd(absl::FromUnixSeconds(3506), absl::Hours(1) + absl::Nanoseconds(1)); }, absl::FromUnixSeconds(7106) + absl::Nanoseconds(1)}, {"MaxIntAddOneSecond", [] { return CheckedAdd( absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()), absl::Seconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"MaxTimestampAddOneSecond", [] { return CheckedAdd(absl::FromUnixSeconds(253402300799), absl::Seconds(1)); }, absl::OutOfRangeError("timestamp overflow")}, {"TimeWithNanosNegative", [] { return CheckedAdd(absl::FromUnixSeconds(1) + absl::Nanoseconds(1), absl::Nanoseconds(-999999999)); }, absl::FromUnixNanos(2)}, {"TimeWithNanosPositive", [] { return CheckedAdd( absl::FromUnixSeconds(1) + absl::Nanoseconds(999999999), absl::Nanoseconds(999999999)); }, absl::FromUnixSeconds(2) + absl::Nanoseconds(999999998)}, {"SecondsAddInfinity", [] { return CheckedAdd( absl::FromUnixSeconds(1) + absl::Nanoseconds(999999999), absl::InfiniteDuration()); }, absl::OutOfRangeError("timestamp overflow")}, {"SecondsAddNegativeInfinity", [] { return CheckedAdd( absl::FromUnixSeconds(1) + absl::Nanoseconds(999999999), -absl::InfiniteDuration()); }, absl::OutOfRangeError("timestamp overflow")}, {"InfiniteFutureAddNegativeInfinity", [] { return CheckedAdd(absl::InfiniteFuture(), -absl::InfiniteDuration()); }, absl::OutOfRangeError("timestamp overflow")}, {"InfinitePastAddInfinity", [] { return CheckedAdd(absl::InfinitePast(), absl::InfiniteDuration()); }, absl::OutOfRangeError("timestamp overflow")}, {"DateSubOneHour", [] { return CheckedSub(absl::FromUnixSeconds(3506), absl::Hours(1)); }, absl::FromUnixSeconds(-94)}, {"MinTimestampSubOneSecond", [] { return CheckedSub(absl::FromUnixSeconds(-62135596800), absl::Seconds(1)); }, absl::OutOfRangeError("timestamp overflow")}, {"MinIntSubOneViaNanos", [] { return CheckedSub( absl::FromUnixSeconds(std::numeric_limits<int64_t>::min()), absl::Nanoseconds(1)); }, absl::OutOfRangeError("integer overflow")}, {"MinTimestampSubOneViaNanosScaleOverflow", [] { return CheckedSub( absl::FromUnixSeconds(-62135596800) + absl::Nanoseconds(1), absl::Nanoseconds(999999999)); }, absl::OutOfRangeError("timestamp overflow")}, {"SecondsSubInfinity", [] { return CheckedSub( absl::FromUnixSeconds(1) + absl::Nanoseconds(999999999), absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, {"SecondsSubNegInfinity", [] { return CheckedSub( absl::FromUnixSeconds(1) + absl::Nanoseconds(999999999), -absl::InfiniteDuration()); }, absl::OutOfRangeError("integer overflow")}, }), [](const testing::TestParamInfo<CheckedTimeResultTest::ParamType>& info) { return info.param.test_name; }); using ConvertInt64Int32TestCase = TestCase<int32_t>; using CheckedConvertInt64Int32Test = testing::TestWithParam<ConvertInt64Int32TestCase>; TEST_P(CheckedConvertInt64Int32Test, Conversions) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( CheckedConvertInt64Int32Test, CheckedConvertInt64Int32Test, ValuesIn(std::vector<ConvertInt64Int32TestCase>{ {"SimpleConversion", [] { return CheckedInt64ToInt32(1L); }, 1}, {"Int32MaxConversion", [] { return CheckedInt64ToInt32( static_cast<int64_t>(std::numeric_limits<int32_t>::max())); }, std::numeric_limits<int32_t>::max()}, {"Int32MaxConversionError", [] { return CheckedInt64ToInt32( static_cast<int64_t>(std::numeric_limits<int64_t>::max())); }, absl::OutOfRangeError("out of int32_t range")}, {"Int32MinConversion", [] { return CheckedInt64ToInt32( static_cast<int64_t>(std::numeric_limits<int32_t>::lowest())); }, std::numeric_limits<int32_t>::lowest()}, {"Int32MinConversionError", [] { return CheckedInt64ToInt32( static_cast<int64_t>(std::numeric_limits<int64_t>::lowest())); }, absl::OutOfRangeError("out of int32_t range")}, }), [](const testing::TestParamInfo<CheckedConvertInt64Int32Test::ParamType>& info) { return info.param.test_name; }); using ConvertUint64Uint32TestCase = TestCase<uint32_t>; using CheckedConvertUint64Uint32Test = testing::TestWithParam<ConvertUint64Uint32TestCase>; TEST_P(CheckedConvertUint64Uint32Test, Conversions) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( CheckedConvertUint64Uint32Test, CheckedConvertUint64Uint32Test, ValuesIn(std::vector<ConvertUint64Uint32TestCase>{ {"SimpleConversion", [] { return CheckedUint64ToUint32(1UL); }, 1U}, {"Uint32MaxConversion", [] { return CheckedUint64ToUint32( static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())); }, std::numeric_limits<uint32_t>::max()}, {"Uint32MaxConversionError", [] { return CheckedUint64ToUint32( static_cast<uint64_t>(std::numeric_limits<uint64_t>::max())); }, absl::OutOfRangeError("out of uint32_t range")}, }), [](const testing::TestParamInfo<CheckedConvertUint64Uint32Test::ParamType>& info) { return info.param.test_name; }); } }
52
cpp
google/cel-cpp
utf8
internal/utf8.cc
internal/utf8_test.cc
#ifndef THIRD_PARTY_CEL_CPP_INTERNAL_UTF8_H_ #define THIRD_PARTY_CEL_CPP_INTERNAL_UTF8_H_ #include <cstddef> #include <string> #include <utility> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" namespace cel::internal { bool Utf8IsValid(absl::string_view str); bool Utf8IsValid(const absl::Cord& str); size_t Utf8CodePointCount(absl::string_view str); size_t Utf8CodePointCount(const absl::Cord& str); std::pair<size_t, bool> Utf8Validate(absl::string_view str); std::pair<size_t, bool> Utf8Validate(const absl::Cord& str); std::pair<char32_t, size_t> Utf8Decode(absl::string_view str); std::pair<char32_t, size_t> Utf8Decode(const absl::Cord::CharIterator& it); size_t Utf8Encode(std::string& buffer, char32_t code_point); } #endif #include "internal/utf8.h" #include <algorithm> #include <cstdint> #include <cstring> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "internal/unicode.h" namespace cel::internal { namespace { constexpr uint8_t kUtf8RuneSelf = 0x80; constexpr size_t kUtf8Max = 4; constexpr uint8_t kLow = 0x80; constexpr uint8_t kHigh = 0xbf; constexpr uint8_t kMaskX = 0x3f; constexpr uint8_t kMask2 = 0x1f; constexpr uint8_t kMask3 = 0xf; constexpr uint8_t kMask4 = 0x7; constexpr uint8_t kTX = 0x80; constexpr uint8_t kT2 = 0xc0; constexpr uint8_t kT3 = 0xe0; constexpr uint8_t kT4 = 0xf0; constexpr uint8_t kXX = 0xf1; constexpr uint8_t kAS = 0xf0; constexpr uint8_t kS1 = 0x02; constexpr uint8_t kS2 = 0x13; constexpr uint8_t kS3 = 0x03; constexpr uint8_t kS4 = 0x23; constexpr uint8_t kS5 = 0x34; constexpr uint8_t kS6 = 0x04; constexpr uint8_t kS7 = 0x44; constexpr uint8_t kLeading[256] = { kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kAS, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS1, kS2, kS3, kS3, kS3, kS3, kS3, kS3, kS3, kS3, kS3, kS3, kS3, kS3, kS4, kS3, kS3, kS5, kS6, kS6, kS6, kS7, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, kXX, }; constexpr std::pair<const uint8_t, const uint8_t> kAccept[16] = { {kLow, kHigh}, {0xa0, kHigh}, {kLow, 0x9f}, {0x90, kHigh}, {kLow, 0x8f}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, }; class StringReader final { public: constexpr explicit StringReader(absl::string_view input) : input_(input) {} size_t Remaining() const { return input_.size(); } bool HasRemaining() const { return !input_.empty(); } absl::string_view Peek(size_t n) { ABSL_ASSERT(n <= Remaining()); return input_.substr(0, n); } char Read() { ABSL_ASSERT(HasRemaining()); char value = input_.front(); input_.remove_prefix(1); return value; } void Advance(size_t n) { ABSL_ASSERT(n <= Remaining()); input_.remove_prefix(n); } void Reset(absl::string_view input) { input_ = input; } private: absl::string_view input_; }; class CordReader final { public: explicit CordReader(const absl::Cord& input) : input_(input), size_(input_.size()), buffer_(), index_(0) {} size_t Remaining() const { return size_; } bool HasRemaining() const { return size_ != 0; } absl::string_view Peek(size_t n) { ABSL_ASSERT(n <= Remaining()); if (n == 0) { return absl::string_view(); } if (n <= buffer_.size() - index_) { return absl::string_view(buffer_.data() + index_, n); } if (buffer_.capacity() >= n) { if (buffer_.capacity() - buffer_.size() < n && index_ != 0) { buffer_.erase(buffer_.begin(), buffer_.begin() + index_); index_ = 0; } } buffer_.reserve(std::max(buffer_.size() + n, kUtf8Max)); size_t to_copy = n - (buffer_.size() - index_); absl::CopyCordToString(input_.Subcord(0, to_copy), &buffer_); input_.RemovePrefix(to_copy); return absl::string_view(buffer_.data() + index_, n); } char Read() { char value = Peek(1).front(); Advance(1); return value; } void Advance(size_t n) { ABSL_ASSERT(n <= Remaining()); if (n == 0) { return; } if (index_ < buffer_.size()) { size_t count = std::min(n, buffer_.size() - index_); index_ += count; n -= count; size_ -= count; if (index_ < buffer_.size()) { return; } buffer_.clear(); index_ = 0; } input_.RemovePrefix(n); size_ -= n; } void Reset(const absl::Cord& input) { input_ = input; size_ = input_.size(); buffer_.clear(); index_ = 0; } private: absl::Cord input_; size_t size_; std::string buffer_; size_t index_; }; template <typename BufferedByteReader> bool Utf8IsValidImpl(BufferedByteReader* reader) { while (reader->HasRemaining()) { const auto b = static_cast<uint8_t>(reader->Read()); if (b < kUtf8RuneSelf) { continue; } const auto leading = kLeading[b]; if (leading == kXX) { return false; } const auto size = static_cast<size_t>(leading & 7) - 1; if (size > reader->Remaining()) { return false; } const absl::string_view segment = reader->Peek(size); const auto& accept = kAccept[leading >> 4]; if (static_cast<uint8_t>(segment[0]) < accept.first || static_cast<uint8_t>(segment[0]) > accept.second) { return false; } else if (size == 1) { } else if (static_cast<uint8_t>(segment[1]) < kLow || static_cast<uint8_t>(segment[1]) > kHigh) { return false; } else if (size == 2) { } else if (static_cast<uint8_t>(segment[2]) < kLow || static_cast<uint8_t>(segment[2]) > kHigh) { return false; } reader->Advance(size); } return true; } template <typename BufferedByteReader> size_t Utf8CodePointCountImpl(BufferedByteReader* reader) { size_t count = 0; while (reader->HasRemaining()) { count++; const auto b = static_cast<uint8_t>(reader->Read()); if (b < kUtf8RuneSelf) { continue; } const auto leading = kLeading[b]; if (leading == kXX) { continue; } auto size = static_cast<size_t>(leading & 7) - 1; if (size > reader->Remaining()) { continue; } const absl::string_view segment = reader->Peek(size); const auto& accept = kAccept[leading >> 4]; if (static_cast<uint8_t>(segment[0]) < accept.first || static_cast<uint8_t>(segment[0]) > accept.second) { size = 0; } else if (size == 1) { } else if (static_cast<uint8_t>(segment[1]) < kLow || static_cast<uint8_t>(segment[1]) > kHigh) { size = 0; } else if (size == 2) { } else if (static_cast<uint8_t>(segment[2]) < kLow || static_cast<uint8_t>(segment[2]) > kHigh) { size = 0; } reader->Advance(size); } return count; } template <typename BufferedByteReader> std::pair<size_t, bool> Utf8ValidateImpl(BufferedByteReader* reader) { size_t count = 0; while (reader->HasRemaining()) { const auto b = static_cast<uint8_t>(reader->Read()); if (b < kUtf8RuneSelf) { count++; continue; } const auto leading = kLeading[b]; if (leading == kXX) { return {count, false}; } const auto size = static_cast<size_t>(leading & 7) - 1; if (size > reader->Remaining()) { return {count, false}; } const absl::string_view segment = reader->Peek(size); const auto& accept = kAccept[leading >> 4]; if (static_cast<uint8_t>(segment[0]) < accept.first || static_cast<uint8_t>(segment[0]) > accept.second) { return {count, false}; } else if (size == 1) { count++; } else if (static_cast<uint8_t>(segment[1]) < kLow || static_cast<uint8_t>(segment[1]) > kHigh) { return {count, false}; } else if (size == 2) { count++; } else if (static_cast<uint8_t>(segment[2]) < kLow || static_cast<uint8_t>(segment[2]) > kHigh) { return {count, false}; } else { count++; } reader->Advance(size); } return {count, true}; } } bool Utf8IsValid(absl::string_view str) { StringReader reader(str); bool valid = Utf8IsValidImpl(&reader); ABSL_ASSERT((reader.Reset(str), valid == Utf8ValidateImpl(&reader).second)); return valid; } bool Utf8IsValid(const absl::Cord& str) { CordReader reader(str); bool valid = Utf8IsValidImpl(&reader); ABSL_ASSERT((reader.Reset(str), valid == Utf8ValidateImpl(&reader).second)); return valid; } size_t Utf8CodePointCount(absl::string_view str) { StringReader reader(str); return Utf8CodePointCountImpl(&reader); } size_t Utf8CodePointCount(const absl::Cord& str) { CordReader reader(str); return Utf8CodePointCountImpl(&reader); } std::pair<size_t, bool> Utf8Validate(absl::string_view str) { StringReader reader(str); auto result = Utf8ValidateImpl(&reader); ABSL_ASSERT((reader.Reset(str), result.second == Utf8IsValidImpl(&reader))); return result; } std::pair<size_t, bool> Utf8Validate(const absl::Cord& str) { CordReader reader(str); auto result = Utf8ValidateImpl(&reader); ABSL_ASSERT((reader.Reset(str), result.second == Utf8IsValidImpl(&reader))); return result; } namespace { std::pair<char32_t, size_t> Utf8DecodeImpl(uint8_t b, uint8_t leading, size_t size, absl::string_view str) { const auto& accept = kAccept[leading >> 4]; const auto b1 = static_cast<uint8_t>(str.front()); if (ABSL_PREDICT_FALSE(b1 < accept.first || b1 > accept.second)) { return {kUnicodeReplacementCharacter, 1}; } if (size <= 1) { return {(static_cast<char32_t>(b & kMask2) << 6) | static_cast<char32_t>(b1 & kMaskX), 2}; } str.remove_prefix(1); const auto b2 = static_cast<uint8_t>(str.front()); if (ABSL_PREDICT_FALSE(b2 < kLow || b2 > kHigh)) { return {kUnicodeReplacementCharacter, 1}; } if (size <= 2) { return {(static_cast<char32_t>(b & kMask3) << 12) | (static_cast<char32_t>(b1 & kMaskX) << 6) | static_cast<char32_t>(b2 & kMaskX), 3}; } str.remove_prefix(1); const auto b3 = static_cast<uint8_t>(str.front()); if (ABSL_PREDICT_FALSE(b3 < kLow || b3 > kHigh)) { return {kUnicodeReplacementCharacter, 1}; } return {(static_cast<char32_t>(b & kMask4) << 18) | (static_cast<char32_t>(b1 & kMaskX) << 12) | (static_cast<char32_t>(b2 & kMaskX) << 6) | static_cast<char32_t>(b3 & kMaskX), 4}; } } std::pair<char32_t, size_t> Utf8Decode(absl::string_view str) { ABSL_DCHECK(!str.empty()); const auto b = static_cast<uint8_t>(str.front()); if (b < kUtf8RuneSelf) { return {static_cast<char32_t>(b), 1}; } const auto leading = kLeading[b]; if (ABSL_PREDICT_FALSE(leading == kXX)) { return {kUnicodeReplacementCharacter, 1}; } auto size = static_cast<size_t>(leading & 7) - 1; str.remove_prefix(1); if (ABSL_PREDICT_FALSE(size > str.size())) { return {kUnicodeReplacementCharacter, 1}; } return Utf8DecodeImpl(b, leading, size, str); } std::pair<char32_t, size_t> Utf8Decode(const absl::Cord::CharIterator& it) { absl::string_view str = absl::Cord::ChunkRemaining(it); ABSL_DCHECK(!str.empty()); const auto b = static_cast<uint8_t>(str.front()); if (b < kUtf8RuneSelf) { return {static_cast<char32_t>(b), 1}; } const auto leading = kLeading[b]; if (ABSL_PREDICT_FALSE(leading == kXX)) { return {kUnicodeReplacementCharacter, 1}; } auto size = static_cast<size_t>(leading & 7) - 1; str.remove_prefix(1); if (ABSL_PREDICT_TRUE(size <= str.size())) { return Utf8DecodeImpl(b, leading, size, str); } absl::Cord::CharIterator current = it; absl::Cord::Advance(&current, 1); char buffer[3]; size_t buffer_len = 0; while (buffer_len < size) { str = absl::Cord::ChunkRemaining(current); if (ABSL_PREDICT_FALSE(str.empty())) { return {kUnicodeReplacementCharacter, 1}; } size_t to_copy = std::min(size_t{3} - buffer_len, str.size()); std::memcpy(buffer + buffer_len, str.data(), to_copy); buffer_len += to_copy; absl::Cord::Advance(&current, to_copy); } return Utf8DecodeImpl(b, leading, size, absl::string_view(buffer, buffer_len)); } size_t Utf8Encode(std::string& buffer, char32_t code_point) { if (ABSL_PREDICT_FALSE(!UnicodeIsValid(code_point))) { code_point = kUnicodeReplacementCharacter; } char storage[4]; size_t storage_len = 0; if (code_point <= 0x7f) { storage[storage_len++] = static_cast<char>(static_cast<uint8_t>(code_point)); } else if (code_point <= 0x7ff) { storage[storage_len++] = static_cast<char>(kT2 | static_cast<uint8_t>(code_point >> 6)); storage[storage_len++] = static_cast<char>(kTX | (static_cast<uint8_t>(code_point) & kMaskX)); } else if (code_point <= 0xffff) { storage[storage_len++] = static_cast<char>(kT3 | static_cast<uint8_t>(code_point >> 12)); storage[storage_len++] = static_cast<char>( kTX | (static_cast<uint8_t>(code_point >> 6) & kMaskX)); storage[storage_len++] = static_cast<char>(kTX | (static_cast<uint8_t>(code_point) & kMaskX)); } else { storage[storage_len++] = static_cast<char>(kT4 | static_cast<uint8_t>(code_point >> 18)); storage[storage_len++] = static_cast<char>( kTX | (static_cast<uint8_t>(code_point >> 12) & kMaskX)); storage[storage_len++] = static_cast<char>( kTX | (static_cast<uint8_t>(code_point >> 6) & kMaskX)); storage[storage_len++] = static_cast<char>(kTX | (static_cast<uint8_t>(code_point) & kMaskX)); } buffer.append(storage, storage_len); return storage_len; } }
#include "internal/utf8.h" #include <string> #include <vector> #include "absl/strings/cord.h" #include "absl/strings/cord_test_helpers.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "internal/benchmark.h" #include "internal/testing.h" namespace cel::internal { namespace { TEST(Utf8IsValid, String) { EXPECT_TRUE(Utf8IsValid("")); EXPECT_TRUE(Utf8IsValid("a")); EXPECT_TRUE(Utf8IsValid("abc")); EXPECT_TRUE(Utf8IsValid("\xd0\x96")); EXPECT_TRUE(Utf8IsValid("\xd0\x96\xd0\x96")); EXPECT_TRUE(Utf8IsValid( "\xd0\xb1\xd1\x80\xd1\x8d\xd0\xb4-\xd0\x9b\xd0\x93\xd0\xa2\xd0\x9c")); EXPECT_TRUE(Utf8IsValid("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9")); EXPECT_TRUE(Utf8IsValid("a\ufffdb")); EXPECT_TRUE(Utf8IsValid("\xf4\x8f\xbf\xbf")); EXPECT_FALSE(Utf8IsValid("\x42\xfa")); EXPECT_FALSE(Utf8IsValid("\x42\xfa\x43")); EXPECT_FALSE(Utf8IsValid("\xf4\x90\x80\x80")); EXPECT_FALSE(Utf8IsValid("\xf7\xbf\xbf\xbf")); EXPECT_FALSE(Utf8IsValid("\xfb\xbf\xbf\xbf\xbf")); EXPECT_FALSE(Utf8IsValid("\xc0\x80")); EXPECT_FALSE(Utf8IsValid("\xed\xa0\x80")); EXPECT_FALSE(Utf8IsValid("\xed\xbf\xbf")); } TEST(Utf8IsValid, Cord) { EXPECT_TRUE(Utf8IsValid(absl::Cord(""))); EXPECT_TRUE(Utf8IsValid(absl::Cord("a"))); EXPECT_TRUE(Utf8IsValid(absl::Cord("abc"))); EXPECT_TRUE(Utf8IsValid(absl::Cord("\xd0\x96"))); EXPECT_TRUE(Utf8IsValid(absl::Cord("\xd0\x96\xd0\x96"))); EXPECT_TRUE(Utf8IsValid(absl::Cord( "\xd0\xb1\xd1\x80\xd1\x8d\xd0\xb4-\xd0\x9b\xd0\x93\xd0\xa2\xd0\x9c"))); EXPECT_TRUE(Utf8IsValid(absl::Cord("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9"))); EXPECT_TRUE(Utf8IsValid(absl::Cord("a\ufffdb"))); EXPECT_TRUE(Utf8IsValid(absl::Cord("\xf4\x8f\xbf\xbf"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\x42\xfa"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\x42\xfa\x43"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\xf4\x90\x80\x80"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\xf7\xbf\xbf\xbf"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\xfb\xbf\xbf\xbf\xbf"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\xc0\x80"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\xed\xa0\x80"))); EXPECT_FALSE(Utf8IsValid(absl::Cord("\xed\xbf\xbf"))); } TEST(Utf8CodePointCount, String) { EXPECT_EQ(Utf8CodePointCount("abcd"), 4); EXPECT_EQ(Utf8CodePointCount("1,2,3,4"), 7); EXPECT_EQ(Utf8CodePointCount("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9"), 3); EXPECT_EQ(Utf8CodePointCount(absl::string_view("\xe2\x00", 2)), 2); EXPECT_EQ(Utf8CodePointCount("\xe2\x80"), 2); EXPECT_EQ(Utf8CodePointCount("a\xe2\x80"), 3); } TEST(Utf8CodePointCount, Cord) { EXPECT_EQ(Utf8CodePointCount(absl::Cord("abcd")), 4); EXPECT_EQ(Utf8CodePointCount(absl::Cord("1,2,3,4")), 7); EXPECT_EQ( Utf8CodePointCount(absl::Cord("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9")), 3); EXPECT_EQ(Utf8CodePointCount(absl::Cord(absl::string_view("\xe2\x00", 2))), 2); EXPECT_EQ(Utf8CodePointCount(absl::Cord("\xe2\x80")), 2); EXPECT_EQ(Utf8CodePointCount(absl::Cord("a\xe2\x80")), 3); } TEST(Utf8Validate, String) { EXPECT_TRUE(Utf8Validate("").second); EXPECT_TRUE(Utf8Validate("a").second); EXPECT_TRUE(Utf8Validate("abc").second); EXPECT_TRUE(Utf8Validate("\xd0\x96").second); EXPECT_TRUE(Utf8Validate("\xd0\x96\xd0\x96").second); EXPECT_TRUE( Utf8Validate( "\xd0\xb1\xd1\x80\xd1\x8d\xd0\xb4-\xd0\x9b\xd0\x93\xd0\xa2\xd0\x9c") .second); EXPECT_TRUE(Utf8Validate("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9").second); EXPECT_TRUE(Utf8Validate("a\ufffdb").second); EXPECT_TRUE(Utf8Validate("\xf4\x8f\xbf\xbf").second); EXPECT_FALSE(Utf8Validate("\x42\xfa").second); EXPECT_FALSE(Utf8Validate("\x42\xfa\x43").second); EXPECT_FALSE(Utf8Validate("\xf4\x90\x80\x80").second); EXPECT_FALSE(Utf8Validate("\xf7\xbf\xbf\xbf").second); EXPECT_FALSE(Utf8Validate("\xfb\xbf\xbf\xbf\xbf").second); EXPECT_FALSE(Utf8Validate("\xc0\x80").second); EXPECT_FALSE(Utf8Validate("\xed\xa0\x80").second); EXPECT_FALSE(Utf8Validate("\xed\xbf\xbf").second); EXPECT_EQ(Utf8Validate("abcd").first, 4); EXPECT_EQ(Utf8Validate("1,2,3,4").first, 7); EXPECT_EQ(Utf8Validate("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9").first, 3); EXPECT_EQ(Utf8Validate(absl::string_view("\xe2\x00", 2)).first, 0); EXPECT_EQ(Utf8Validate("\xe2\x80").first, 0); EXPECT_EQ(Utf8Validate("a\xe2\x80").first, 1); } TEST(Utf8Validate, Cord) { EXPECT_TRUE(Utf8Validate(absl::Cord("")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("a")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("abc")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("\xd0\x96")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("\xd0\x96\xd0\x96")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("\xd0\xb1\xd1\x80\xd1\x8d\xd0\xb4-" "\xd0\x9b\xd0\x93\xd0\xa2\xd0\x9c")) .second); EXPECT_TRUE( Utf8Validate(absl::Cord("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("a\ufffdb")).second); EXPECT_TRUE(Utf8Validate(absl::Cord("\xf4\x8f\xbf\xbf")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\x42\xfa")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\x42\xfa\x43")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\xf4\x90\x80\x80")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\xf7\xbf\xbf\xbf")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\xfb\xbf\xbf\xbf\xbf")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\xc0\x80")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\xed\xa0\x80")).second); EXPECT_FALSE(Utf8Validate(absl::Cord("\xed\xbf\xbf")).second); EXPECT_EQ(Utf8Validate(absl::Cord("abcd")).first, 4); EXPECT_EQ(Utf8Validate(absl::Cord("1,2,3,4")).first, 7); EXPECT_EQ( Utf8Validate(absl::Cord("\xe2\x98\xba\xe2\x98\xbb\xe2\x98\xb9")).first, 3); EXPECT_EQ(Utf8Validate(absl::Cord(absl::string_view("\xe2\x00", 2))).first, 0); EXPECT_EQ(Utf8Validate(absl::Cord("\xe2\x80")).first, 0); EXPECT_EQ(Utf8Validate(absl::Cord("a\xe2\x80")).first, 1); } struct Utf8EncodeTestCase final { char32_t code_point; absl::string_view code_units; }; using Utf8EncodeTest = testing::TestWithParam<Utf8EncodeTestCase>; TEST_P(Utf8EncodeTest, Compliance) { const Utf8EncodeTestCase& test_case = GetParam(); std::string result; EXPECT_EQ(Utf8Encode(result, test_case.code_point), test_case.code_units.size()); EXPECT_EQ(result, test_case.code_units); } INSTANTIATE_TEST_SUITE_P(Utf8EncodeTest, Utf8EncodeTest, testing::ValuesIn<Utf8EncodeTestCase>({ {0x0000, absl::string_view("\x00", 1)}, {0x0001, "\x01"}, {0x007e, "\x7e"}, {0x007f, "\x7f"}, {0x0080, "\xc2\x80"}, {0x0081, "\xc2\x81"}, {0x00bf, "\xc2\xbf"}, {0x00c0, "\xc3\x80"}, {0x00c1, "\xc3\x81"}, {0x00c8, "\xc3\x88"}, {0x00d0, "\xc3\x90"}, {0x00e0, "\xc3\xa0"}, {0x00f0, "\xc3\xb0"}, {0x00f8, "\xc3\xb8"}, {0x00ff, "\xc3\xbf"}, {0x0100, "\xc4\x80"}, {0x07ff, "\xdf\xbf"}, {0x0400, "\xd0\x80"}, {0x0800, "\xe0\xa0\x80"}, {0x0801, "\xe0\xa0\x81"}, {0x1000, "\xe1\x80\x80"}, {0xd000, "\xed\x80\x80"}, {0xd7ff, "\xed\x9f\xbf"}, {0xe000, "\xee\x80\x80"}, {0xfffe, "\xef\xbf\xbe"}, {0xffff, "\xef\xbf\xbf"}, {0x10000, "\xf0\x90\x80\x80"}, {0x10001, "\xf0\x90\x80\x81"}, {0x40000, "\xf1\x80\x80\x80"}, {0x10fffe, "\xf4\x8f\xbf\xbe"}, {0x10ffff, "\xf4\x8f\xbf\xbf"}, {0xFFFD, "\xef\xbf\xbd"}, })); struct Utf8DecodeTestCase final { char32_t code_point; absl::string_view code_units; }; using Utf8DecodeTest = testing::TestWithParam<Utf8DecodeTestCase>; TEST_P(Utf8DecodeTest, StringView) { const Utf8DecodeTestCase& test_case = GetParam(); auto [code_point, code_units] = Utf8Decode(test_case.code_units); EXPECT_EQ(code_units, test_case.code_units.size()) << absl::CHexEscape(test_case.code_units); EXPECT_EQ(code_point, test_case.code_point) << absl::CHexEscape(test_case.code_units); } TEST_P(Utf8DecodeTest, Cord) { const Utf8DecodeTestCase& test_case = GetParam(); auto cord = absl::Cord(test_case.code_units); auto it = cord.char_begin(); auto [code_point, code_units] = Utf8Decode(it); absl::Cord::Advance(&it, code_units); EXPECT_EQ(it, cord.char_end()); EXPECT_EQ(code_units, test_case.code_units.size()) << absl::CHexEscape(test_case.code_units); EXPECT_EQ(code_point, test_case.code_point) << absl::CHexEscape(test_case.code_units); } std::vector<std::string> FragmentString(absl::string_view text) { std::vector<std::string> fragments; fragments.reserve(text.size()); for (const auto& c : text) { fragments.emplace_back().push_back(c); } return fragments; } TEST_P(Utf8DecodeTest, CordFragmented) { const Utf8DecodeTestCase& test_case = GetParam(); auto cord = absl::MakeFragmentedCord(FragmentString(test_case.code_units)); auto it = cord.char_begin(); auto [code_point, code_units] = Utf8Decode(it); absl::Cord::Advance(&it, code_units); EXPECT_EQ(it, cord.char_end()); EXPECT_EQ(code_units, test_case.code_units.size()) << absl::CHexEscape(test_case.code_units); EXPECT_EQ(code_point, test_case.code_point) << absl::CHexEscape(test_case.code_units); } INSTANTIATE_TEST_SUITE_P(Utf8DecodeTest, Utf8DecodeTest, testing::ValuesIn<Utf8DecodeTestCase>({ {0x0000, absl::string_view("\x00", 1)}, {0x0001, "\x01"}, {0x007e, "\x7e"}, {0x007f, "\x7f"}, {0x0080, "\xc2\x80"}, {0x0081, "\xc2\x81"}, {0x00bf, "\xc2\xbf"}, {0x00c0, "\xc3\x80"}, {0x00c1, "\xc3\x81"}, {0x00c8, "\xc3\x88"}, {0x00d0, "\xc3\x90"}, {0x00e0, "\xc3\xa0"}, {0x00f0, "\xc3\xb0"}, {0x00f8, "\xc3\xb8"}, {0x00ff, "\xc3\xbf"}, {0x0100, "\xc4\x80"}, {0x07ff, "\xdf\xbf"}, {0x0400, "\xd0\x80"}, {0x0800, "\xe0\xa0\x80"}, {0x0801, "\xe0\xa0\x81"}, {0x1000, "\xe1\x80\x80"}, {0xd000, "\xed\x80\x80"}, {0xd7ff, "\xed\x9f\xbf"}, {0xe000, "\xee\x80\x80"}, {0xfffe, "\xef\xbf\xbe"}, {0xffff, "\xef\xbf\xbf"}, {0x10000, "\xf0\x90\x80\x80"}, {0x10001, "\xf0\x90\x80\x81"}, {0x40000, "\xf1\x80\x80\x80"}, {0x10fffe, "\xf4\x8f\xbf\xbe"}, {0x10ffff, "\xf4\x8f\xbf\xbf"}, {0xFFFD, "\xef\xbf\xbd"}, })); void BM_Utf8CodePointCount_String_AsciiTen(benchmark::State& state) { for (auto s : state) { benchmark::DoNotOptimize(Utf8CodePointCount("0123456789")); } } BENCHMARK(BM_Utf8CodePointCount_String_AsciiTen); void BM_Utf8CodePointCount_Cord_AsciiTen(benchmark::State& state) { absl::Cord value("0123456789"); for (auto s : state) { benchmark::DoNotOptimize(Utf8CodePointCount(value)); } } BENCHMARK(BM_Utf8CodePointCount_Cord_AsciiTen); void BM_Utf8CodePointCount_String_JapaneseTen(benchmark::State& state) { for (auto s : state) { benchmark::DoNotOptimize(Utf8CodePointCount( "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa" "\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5")); } } BENCHMARK(BM_Utf8CodePointCount_String_JapaneseTen); void BM_Utf8CodePointCount_Cord_JapaneseTen(benchmark::State& state) { absl::Cord value( "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa" "\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5"); for (auto s : state) { benchmark::DoNotOptimize(Utf8CodePointCount(value)); } } BENCHMARK(BM_Utf8CodePointCount_Cord_JapaneseTen); void BM_Utf8IsValid_String_AsciiTen(benchmark::State& state) { for (auto s : state) { benchmark::DoNotOptimize(Utf8IsValid("0123456789")); } } BENCHMARK(BM_Utf8IsValid_String_AsciiTen); void BM_Utf8IsValid_Cord_AsciiTen(benchmark::State& state) { absl::Cord value("0123456789"); for (auto s : state) { benchmark::DoNotOptimize(Utf8IsValid(value)); } } BENCHMARK(BM_Utf8IsValid_Cord_AsciiTen); void BM_Utf8IsValid_String_JapaneseTen(benchmark::State& state) { for (auto s : state) { benchmark::DoNotOptimize(Utf8IsValid( "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa" "\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5")); } } BENCHMARK(BM_Utf8IsValid_String_JapaneseTen); void BM_Utf8IsValid_Cord_JapaneseTen(benchmark::State& state) { absl::Cord value( "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa" "\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5"); for (auto s : state) { benchmark::DoNotOptimize(Utf8IsValid(value)); } } BENCHMARK(BM_Utf8IsValid_Cord_JapaneseTen); void BM_Utf8Validate_String_AsciiTen(benchmark::State& state) { for (auto s : state) { benchmark::DoNotOptimize(Utf8Validate("0123456789")); } } BENCHMARK(BM_Utf8Validate_String_AsciiTen); void BM_Utf8Validate_Cord_AsciiTen(benchmark::State& state) { absl::Cord value("0123456789"); for (auto s : state) { benchmark::DoNotOptimize(Utf8Validate(value)); } } BENCHMARK(BM_Utf8Validate_Cord_AsciiTen); void BM_Utf8Validate_String_JapaneseTen(benchmark::State& state) { for (auto s : state) { benchmark::DoNotOptimize(Utf8Validate( "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa" "\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5")); } } BENCHMARK(BM_Utf8Validate_String_JapaneseTen); void BM_Utf8Validate_Cord_JapaneseTen(benchmark::State& state) { absl::Cord value( "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa" "\x9e\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe6\x97\xa5"); for (auto s : state) { benchmark::DoNotOptimize(Utf8Validate(value)); } } BENCHMARK(BM_Utf8Validate_Cord_JapaneseTen); } }
53
cpp
google/cel-cpp
strings
extensions/strings.cc
extensions/strings_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_STRINGS_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_STRINGS_H_ #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel::extensions { absl::Status RegisterStringsFunctions(FunctionRegistry& registry, const RuntimeOptions& options); absl::Status RegisterStringsFunctions( google::api::expr::runtime::CelFunctionRegistry* registry, const google::api::expr::runtime::InterpreterOptions& options); } #endif #include "extensions/strings.h" #include <cstddef> #include <cstdint> #include <limits> #include <string> #include <tuple> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/casting.h" #include "common/type.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "internal/status_macros.h" #include "internal/utf8.h" #include "runtime/function_adapter.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/runtime_options.h" namespace cel::extensions { namespace { struct AppendToStringVisitor { std::string& append_to; void operator()(absl::string_view string) const { append_to.append(string); } void operator()(const absl::Cord& cord) const { append_to.append(static_cast<std::string>(cord)); } }; absl::StatusOr<Value> Join2(ValueManager& value_manager, const ListValue& value, const StringValue& separator) { std::string result; CEL_ASSIGN_OR_RETURN(auto iterator, value.NewIterator(value_manager)); Value element; if (iterator->HasNext()) { CEL_RETURN_IF_ERROR(iterator->Next(value_manager, element)); if (auto string_element = As<StringValue>(element); string_element) { string_element->NativeValue(AppendToStringVisitor{result}); } else { return ErrorValue{ runtime_internal::CreateNoMatchingOverloadError("join")}; } } std::string separator_scratch; absl::string_view separator_view = separator.NativeString(separator_scratch); while (iterator->HasNext()) { result.append(separator_view); CEL_RETURN_IF_ERROR(iterator->Next(value_manager, element)); if (auto string_element = As<StringValue>(element); string_element) { string_element->NativeValue(AppendToStringVisitor{result}); } else { return ErrorValue{ runtime_internal::CreateNoMatchingOverloadError("join")}; } } result.shrink_to_fit(); return value_manager.CreateUncheckedStringValue(std::move(result)); } absl::StatusOr<Value> Join1(ValueManager& value_manager, const ListValue& value) { return Join2(value_manager, value, StringValue{}); } struct SplitWithEmptyDelimiter { ValueManager& value_manager; int64_t& limit; ListValueBuilder& builder; absl::StatusOr<Value> operator()(absl::string_view string) const { char32_t rune; size_t count; std::string buffer; buffer.reserve(4); while (!string.empty() && limit > 1) { std::tie(rune, count) = internal::Utf8Decode(string); buffer.clear(); internal::Utf8Encode(buffer, rune); CEL_RETURN_IF_ERROR(builder.Add( value_manager.CreateUncheckedStringValue(absl::string_view(buffer)))); --limit; string.remove_prefix(count); } if (!string.empty()) { CEL_RETURN_IF_ERROR( builder.Add(value_manager.CreateUncheckedStringValue(string))); } return std::move(builder).Build(); } absl::StatusOr<Value> operator()(const absl::Cord& string) const { auto begin = string.char_begin(); auto end = string.char_end(); char32_t rune; size_t count; std::string buffer; while (begin != end && limit > 1) { std::tie(rune, count) = internal::Utf8Decode(begin); buffer.clear(); internal::Utf8Encode(buffer, rune); CEL_RETURN_IF_ERROR(builder.Add( value_manager.CreateUncheckedStringValue(absl::string_view(buffer)))); --limit; absl::Cord::Advance(&begin, count); } if (begin != end) { buffer.clear(); while (begin != end) { auto chunk = absl::Cord::ChunkRemaining(begin); buffer.append(chunk); absl::Cord::Advance(&begin, chunk.size()); } buffer.shrink_to_fit(); CEL_RETURN_IF_ERROR(builder.Add( value_manager.CreateUncheckedStringValue(std::move(buffer)))); } return std::move(builder).Build(); } }; absl::StatusOr<Value> Split3(ValueManager& value_manager, const StringValue& string, const StringValue& delimiter, int64_t limit) { if (limit == 0) { return ListValue{}; } if (limit < 0) { limit = std::numeric_limits<int64_t>::max(); } CEL_ASSIGN_OR_RETURN(auto builder, value_manager.NewListValueBuilder(ListTypeView{})); if (string.IsEmpty()) { builder->Reserve(1); CEL_RETURN_IF_ERROR(builder->Add(StringValue{})); return std::move(*builder).Build(); } if (delimiter.IsEmpty()) { return string.NativeValue( SplitWithEmptyDelimiter{value_manager, limit, *builder}); } std::string delimiter_scratch; absl::string_view delimiter_view = delimiter.NativeString(delimiter_scratch); std::string content_scratch; absl::string_view content_view = string.NativeString(content_scratch); while (limit > 1 && !content_view.empty()) { auto pos = content_view.find(delimiter_view); if (pos == absl::string_view::npos) { break; } CEL_RETURN_IF_ERROR(builder->Add( value_manager.CreateUncheckedStringValue(content_view.substr(0, pos)))); --limit; content_view.remove_prefix(pos + delimiter_view.size()); if (content_view.empty()) { CEL_RETURN_IF_ERROR(builder->Add(StringValue{})); return std::move(*builder).Build(); } } CEL_RETURN_IF_ERROR( builder->Add(value_manager.CreateUncheckedStringValue(content_view))); return std::move(*builder).Build(); } absl::StatusOr<Value> Split2(ValueManager& value_manager, const StringValue& string, const StringValue& delimiter) { return Split3(value_manager, string, delimiter, -1); } absl::StatusOr<Value> LowerAscii(ValueManager& value_manager, const StringValue& string) { std::string content = string.NativeString(); absl::AsciiStrToLower(&content); return value_manager.CreateUncheckedStringValue(std::move(content)); } } absl::Status RegisterStringsFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, ListValue>::CreateDescriptor( "join", true), UnaryFunctionAdapter<absl::StatusOr<Value>, ListValue>::WrapFunction( Join1))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, ListValue, StringValue>:: CreateDescriptor("join", true), BinaryFunctionAdapter<absl::StatusOr<Value>, ListValue, StringValue>::WrapFunction(Join2))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, StringValue, StringValue>:: CreateDescriptor("split", true), BinaryFunctionAdapter<absl::StatusOr<Value>, StringValue, StringValue>::WrapFunction(Split2))); CEL_RETURN_IF_ERROR(registry.Register( VariadicFunctionAdapter< absl::StatusOr<Value>, StringValue, StringValue, int64_t>::CreateDescriptor("split", true), VariadicFunctionAdapter<absl::StatusOr<Value>, StringValue, StringValue, int64_t>::WrapFunction(Split3))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, StringValue>:: CreateDescriptor("lowerAscii", true), UnaryFunctionAdapter<absl::StatusOr<Value>, StringValue>::WrapFunction( LowerAscii))); return absl::OkStatus(); } absl::Status RegisterStringsFunctions( google::api::expr::runtime::CelFunctionRegistry* registry, const google::api::expr::runtime::InterpreterOptions& options) { return RegisterStringsFunctions( registry->InternalGetRegistry(), google::api::expr::runtime::ConvertToRuntimeOptions(options)); } }
#include "extensions/strings.h" #include <memory> #include <utility> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/strings/cord.h" #include "common/memory.h" #include "common/value.h" #include "common/values/legacy_value_manager.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/options.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" namespace cel::extensions { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::parser::ParserOptions; TEST(Strings, SplitWithEmptyDelimiterCord) { MemoryManagerRef memory_manager = MemoryManagerRef::ReferenceCounting(); const auto options = RuntimeOptions{}; ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(options)); EXPECT_OK(RegisterStringsFunctions(builder.function_registry(), options)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("foo.split('') == ['h', 'e', 'l', 'l', 'o', ' ', " "'w', 'o', 'r', 'l', 'd', '!']", "<input>", ParserOptions{})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); common_internal::LegacyValueManager value_factory(memory_manager, runtime->GetTypeProvider()); Activation activation; activation.InsertOrAssignValue("foo", StringValue{absl::Cord("hello world!")}); ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); ASSERT_TRUE(result.Is<BoolValue>()); EXPECT_TRUE(result.As<BoolValue>().NativeValue()); } } }
54
cpp
google/cel-cpp
macro_registry
parser/macro_registry.cc
parser/macro_registry_test.cc
#ifndef THIRD_PARTY_CEL_CPP_PARSER_MACRO_REGISTRY_H_ #define THIRD_PARTY_CEL_CPP_PARSER_MACRO_REGISTRY_H_ #include <cstddef> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "parser/macro.h" namespace cel { class MacroRegistry final { public: MacroRegistry() = default; MacroRegistry(MacroRegistry&&) = default; MacroRegistry& operator=(MacroRegistry&&) = default; absl::Status RegisterMacro(const Macro& macro); absl::Status RegisterMacros(absl::Span<const Macro> macros); absl::optional<Macro> FindMacro(absl::string_view name, size_t arg_count, bool receiver_style) const; private: bool RegisterMacroImpl(const Macro& macro); absl::flat_hash_map<absl::string_view, Macro> macros_; }; } #endif #include "parser/macro_registry.h" #include <cstddef> #include <utility> #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "parser/macro.h" namespace cel { absl::Status MacroRegistry::RegisterMacro(const Macro& macro) { if (!RegisterMacroImpl(macro)) { return absl::AlreadyExistsError( absl::StrCat("macro already exists: ", macro.key())); } return absl::OkStatus(); } absl::Status MacroRegistry::RegisterMacros(absl::Span<const Macro> macros) { for (size_t i = 0; i < macros.size(); ++i) { const auto& macro = macros[i]; if (!RegisterMacroImpl(macro)) { for (size_t j = 0; j < i; ++j) { macros_.erase(macros[j].key()); } return absl::AlreadyExistsError( absl::StrCat("macro already exists: ", macro.key())); } } return absl::OkStatus(); } absl::optional<Macro> MacroRegistry::FindMacro(absl::string_view name, size_t arg_count, bool receiver_style) const { if (name.empty() || absl::StrContains(name, ':')) { return absl::nullopt; } auto key = absl::StrCat(name, ":", arg_count, ":", receiver_style ? "true" : "false"); if (auto it = macros_.find(key); it != macros_.end()) { return it->second; } key = absl::StrCat(name, ":*:", receiver_style ? "true" : "false"); if (auto it = macros_.find(key); it != macros_.end()) { return it->second; } return absl::nullopt; } bool MacroRegistry::RegisterMacroImpl(const Macro& macro) { return macros_.insert(std::pair{macro.key(), macro}).second; } }
#include "parser/macro_registry.h" #include "absl/status/status.h" #include "absl/types/optional.h" #include "internal/testing.h" #include "parser/macro.h" namespace cel { namespace { using testing::Eq; using testing::Ne; using cel::internal::IsOk; using cel::internal::StatusIs; TEST(MacroRegistry, RegisterAndFind) { MacroRegistry macros; EXPECT_THAT(macros.RegisterMacro(HasMacro()), IsOk()); EXPECT_THAT(macros.FindMacro("has", 1, false), Ne(absl::nullopt)); } TEST(MacroRegistry, RegisterRollsback) { MacroRegistry macros; EXPECT_THAT(macros.RegisterMacros({HasMacro(), AllMacro(), AllMacro()}), StatusIs(absl::StatusCode::kAlreadyExists)); EXPECT_THAT(macros.FindMacro("has", 1, false), Eq(absl::nullopt)); } } }
55
cpp
google/cel-cpp
macro_expr_factory
parser/macro_expr_factory.cc
parser/macro_expr_factory_test.cc
#ifndef THIRD_PARTY_CEL_CPP_PARSER_MACRO_EXPR_FACTORY_H_ #define THIRD_PARTY_CEL_CPP_PARSER_MACRO_EXPR_FACTORY_H_ #include <algorithm> #include <cstdint> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/strings/string_view.h" #include "common/expr.h" #include "common/expr_factory.h" namespace cel { class ParserMacroExprFactory; class TestMacroExprFactory; class MacroExprFactory : protected ExprFactory { protected: using ExprFactory::IsArrayLike; using ExprFactory::IsExprLike; using ExprFactory::IsStringLike; template <typename T, typename U> struct IsRValue : std::bool_constant< std::disjunction_v<std::is_same<T, U>, std::is_same<T, U&&>>> {}; public: ABSL_MUST_USE_RESULT Expr Copy(const Expr& expr); ABSL_MUST_USE_RESULT ListExprElement Copy(const ListExprElement& element); ABSL_MUST_USE_RESULT StructExprField Copy(const StructExprField& field); ABSL_MUST_USE_RESULT MapExprEntry Copy(const MapExprEntry& entry); ABSL_MUST_USE_RESULT Expr NewUnspecified() { return NewUnspecified(NextId()); } ABSL_MUST_USE_RESULT Expr NewNullConst() { return NewNullConst(NextId()); } ABSL_MUST_USE_RESULT Expr NewBoolConst(bool value) { return NewBoolConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewIntConst(int64_t value) { return NewIntConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewUintConst(uint64_t value) { return NewUintConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewDoubleConst(double value) { return NewDoubleConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewBytesConst(std::string value) { return NewBytesConst(NextId(), std::move(value)); } ABSL_MUST_USE_RESULT Expr NewBytesConst(absl::string_view value) { return NewBytesConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewBytesConst(absl::Nullable<const char*> value) { return NewBytesConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewStringConst(std::string value) { return NewStringConst(NextId(), std::move(value)); } ABSL_MUST_USE_RESULT Expr NewStringConst(absl::string_view value) { return NewStringConst(NextId(), value); } ABSL_MUST_USE_RESULT Expr NewStringConst(absl::Nullable<const char*> value) { return NewStringConst(NextId(), value); } template <typename Name, typename = std::enable_if_t<IsStringLike<Name>::value>> ABSL_MUST_USE_RESULT Expr NewIdent(Name name) { return NewIdent(NextId(), std::move(name)); } ABSL_MUST_USE_RESULT Expr NewAccuIdent() { return NewAccuIdent(NextId()); } template <typename Operand, typename Field, typename = std::enable_if_t<IsExprLike<Operand>::value>, typename = std::enable_if_t<IsStringLike<Field>::value>> ABSL_MUST_USE_RESULT Expr NewSelect(Operand operand, Field field) { return NewSelect(NextId(), std::move(operand), std::move(field)); } template <typename Operand, typename Field, typename = std::enable_if_t<IsExprLike<Operand>::value>, typename = std::enable_if_t<IsStringLike<Field>::value>> ABSL_MUST_USE_RESULT Expr NewPresenceTest(Operand operand, Field field) { return NewPresenceTest(NextId(), std::move(operand), std::move(field)); } template < typename Function, typename... Args, typename = std::enable_if_t<IsStringLike<Function>::value>, typename = std::enable_if_t<std::conjunction_v<IsRValue<Expr, Args>...>>> ABSL_MUST_USE_RESULT Expr NewCall(Function function, Args&&... args) { std::vector<Expr> array; array.reserve(sizeof...(Args)); (array.push_back(std::forward<Args>(args)), ...); return NewCall(NextId(), std::move(function), std::move(array)); } template <typename Function, typename Args, typename = std::enable_if_t<IsStringLike<Function>::value>, typename = std::enable_if_t<IsArrayLike<Expr, Args>::value>> ABSL_MUST_USE_RESULT Expr NewCall(Function function, Args args) { return NewCall(NextId(), std::move(function), std::move(args)); } template < typename Function, typename Target, typename... Args, typename = std::enable_if_t<IsStringLike<Function>::value>, typename = std::enable_if_t<IsExprLike<Target>::value>, typename = std::enable_if_t<std::conjunction_v<IsRValue<Expr, Args>...>>> ABSL_MUST_USE_RESULT Expr NewMemberCall(Function function, Target target, Args&&... args) { std::vector<Expr> array; array.reserve(sizeof...(Args)); (array.push_back(std::forward<Args>(args)), ...); return NewMemberCall(NextId(), std::move(function), std::move(target), std::move(array)); } template <typename Function, typename Target, typename Args, typename = std::enable_if_t<IsStringLike<Function>::value>, typename = std::enable_if_t<IsExprLike<Target>::value>, typename = std::enable_if_t<IsArrayLike<Expr, Args>::value>> ABSL_MUST_USE_RESULT Expr NewMemberCall(Function function, Target target, Args args) { return NewMemberCall(NextId(), std::move(function), std::move(target), std::move(args)); } using ExprFactory::NewListElement; template <typename... Elements, typename = std::enable_if_t< std::conjunction_v<IsRValue<ListExprElement, Elements>...>>> ABSL_MUST_USE_RESULT Expr NewList(Elements&&... elements) { std::vector<ListExprElement> array; array.reserve(sizeof...(Elements)); (array.push_back(std::forward<Elements>(elements)), ...); return NewList(NextId(), std::move(array)); } template <typename Elements, typename = std::enable_if_t<IsArrayLike<ListExprElement, Elements>::value>> ABSL_MUST_USE_RESULT Expr NewList(Elements elements) { return NewList(NextId(), std::move(elements)); } template <typename Name, typename Value, typename = std::enable_if_t<IsStringLike<Name>::value>, typename = std::enable_if_t<IsExprLike<Value>::value>> ABSL_MUST_USE_RESULT StructExprField NewStructField(Name name, Value value, bool optional = false) { return NewStructField(NextId(), std::move(name), std::move(value), optional); } template <typename Name, typename... Fields, typename = std::enable_if_t<IsStringLike<Name>::value>, typename = std::enable_if_t< std::conjunction_v<IsRValue<StructExprField, Fields>...>>> ABSL_MUST_USE_RESULT Expr NewStruct(Name name, Fields&&... fields) { std::vector<StructExprField> array; array.reserve(sizeof...(Fields)); (array.push_back(std::forward<Fields>(fields)), ...); return NewStruct(NextId(), std::move(name), std::move(array)); } template < typename Name, typename Fields, typename = std::enable_if_t<IsStringLike<Name>::value>, typename = std::enable_if_t<IsArrayLike<StructExprField, Fields>::value>> ABSL_MUST_USE_RESULT Expr NewStruct(Name name, Fields fields) { return NewStruct(NextId(), std::move(name), std::move(fields)); } template <typename Key, typename Value, typename = std::enable_if_t<IsExprLike<Key>::value>, typename = std::enable_if_t<IsExprLike<Value>::value>> ABSL_MUST_USE_RESULT MapExprEntry NewMapEntry(Key key, Value value, bool optional = false) { return NewMapEntry(NextId(), std::move(key), std::move(value), optional); } template <typename... Entries, typename = std::enable_if_t<std::conjunction_v< IsRValue<MapExprEntry, Entries>...>>> ABSL_MUST_USE_RESULT Expr NewMap(Entries&&... entries) { std::vector<MapExprEntry> array; array.reserve(sizeof...(Entries)); (array.push_back(std::forward<Entries>(entries)), ...); return NewMap(NextId(), std::move(array)); } template <typename Entries, typename = std::enable_if_t< IsArrayLike<MapExprEntry, Entries>::value>> ABSL_MUST_USE_RESULT Expr NewMap(Entries entries) { return NewMap(NextId(), std::move(entries)); } template <typename IterVar, typename IterRange, typename AccuVar, typename AccuInit, typename LoopCondition, typename LoopStep, typename Result, typename = std::enable_if_t<IsStringLike<IterVar>::value>, typename = std::enable_if_t<IsExprLike<IterRange>::value>, typename = std::enable_if_t<IsStringLike<AccuVar>::value>, typename = std::enable_if_t<IsExprLike<AccuInit>::value>, typename = std::enable_if_t<IsExprLike<LoopStep>::value>, typename = std::enable_if_t<IsExprLike<LoopCondition>::value>, typename = std::enable_if_t<IsExprLike<Result>::value>> ABSL_MUST_USE_RESULT Expr NewComprehension(IterVar iter_var, IterRange iter_range, AccuVar accu_var, AccuInit accu_init, LoopCondition loop_condition, LoopStep loop_step, Result result) { return NewComprehension(NextId(), std::move(iter_var), std::move(iter_range), std::move(accu_var), std::move(accu_init), std::move(loop_condition), std::move(loop_step), std::move(result)); } ABSL_MUST_USE_RESULT virtual Expr ReportError(absl::string_view message) = 0; ABSL_MUST_USE_RESULT virtual Expr ReportErrorAt( const Expr& expr, absl::string_view message) = 0; protected: using ExprFactory::NewAccuIdent; using ExprFactory::NewBoolConst; using ExprFactory::NewBytesConst; using ExprFactory::NewCall; using ExprFactory::NewComprehension; using ExprFactory::NewConst; using ExprFactory::NewDoubleConst; using ExprFactory::NewIdent; using ExprFactory::NewIntConst; using ExprFactory::NewList; using ExprFactory::NewMap; using ExprFactory::NewMapEntry; using ExprFactory::NewMemberCall; using ExprFactory::NewNullConst; using ExprFactory::NewPresenceTest; using ExprFactory::NewSelect; using ExprFactory::NewStringConst; using ExprFactory::NewStruct; using ExprFactory::NewStructField; using ExprFactory::NewUintConst; using ExprFactory::NewUnspecified; ABSL_MUST_USE_RESULT virtual ExprId NextId() = 0; ABSL_MUST_USE_RESULT virtual ExprId CopyId(ExprId id) = 0; ABSL_MUST_USE_RESULT ExprId CopyId(const Expr& expr) { return CopyId(expr.id()); } private: friend class ParserMacroExprFactory; friend class TestMacroExprFactory; MacroExprFactory() : ExprFactory() {} }; } #endif #include "parser/macro_expr_factory.h" #include <utility> #include <vector> #include "absl/functional/overload.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "common/constant.h" #include "common/expr.h" namespace cel { Expr MacroExprFactory::Copy(const Expr& expr) { return absl::visit( absl::Overload( [this, &expr](const UnspecifiedExpr&) -> Expr { return NewUnspecified(CopyId(expr)); }, [this, &expr](const Constant& const_expr) -> Expr { return NewConst(CopyId(expr), const_expr); }, [this, &expr](const IdentExpr& ident_expr) -> Expr { return NewIdent(CopyId(expr), ident_expr.name()); }, [this, &expr](const SelectExpr& select_expr) -> Expr { const auto id = CopyId(expr); return select_expr.test_only() ? NewPresenceTest(id, Copy(select_expr.operand()), select_expr.field()) : NewSelect(id, Copy(select_expr.operand()), select_expr.field()); }, [this, &expr](const CallExpr& call_expr) -> Expr { const auto id = CopyId(expr); absl::optional<Expr> target; if (call_expr.has_target()) { target = Copy(call_expr.target()); } std::vector<Expr> args; args.reserve(call_expr.args().size()); for (const auto& arg : call_expr.args()) { args.push_back(Copy(arg)); } return target.has_value() ? NewMemberCall(id, call_expr.function(), std::move(*target), std::move(args)) : NewCall(id, call_expr.function(), std::move(args)); }, [this, &expr](const ListExpr& list_expr) -> Expr { const auto id = CopyId(expr); std::vector<ListExprElement> elements; elements.reserve(list_expr.elements().size()); for (const auto& element : list_expr.elements()) { elements.push_back(Copy(element)); } return NewList(id, std::move(elements)); }, [this, &expr](const StructExpr& struct_expr) -> Expr { const auto id = CopyId(expr); std::vector<StructExprField> fields; fields.reserve(struct_expr.fields().size()); for (const auto& field : struct_expr.fields()) { fields.push_back(Copy(field)); } return NewStruct(id, struct_expr.name(), std::move(fields)); }, [this, &expr](const MapExpr& map_expr) -> Expr { const auto id = CopyId(expr); std::vector<MapExprEntry> entries; entries.reserve(map_expr.entries().size()); for (const auto& entry : map_expr.entries()) { entries.push_back(Copy(entry)); } return NewMap(id, std::move(entries)); }, [this, &expr](const ComprehensionExpr& comprehension_expr) -> Expr { const auto id = CopyId(expr); auto iter_range = Copy(comprehension_expr.iter_range()); auto accu_init = Copy(comprehension_expr.accu_init()); auto loop_condition = Copy(comprehension_expr.loop_condition()); auto loop_step = Copy(comprehension_expr.loop_step()); auto result = Copy(comprehension_expr.result()); return NewComprehension( id, comprehension_expr.iter_var(), std::move(iter_range), comprehension_expr.accu_var(), std::move(accu_init), std::move(loop_condition), std::move(loop_step), std::move(result)); }), expr.kind()); } ListExprElement MacroExprFactory::Copy(const ListExprElement& element) { return NewListElement(Copy(element.expr()), element.optional()); } StructExprField MacroExprFactory::Copy(const StructExprField& field) { auto field_id = CopyId(field.id()); auto field_value = Copy(field.value()); return NewStructField(field_id, field.name(), std::move(field_value), field.optional()); } MapExprEntry MacroExprFactory::Copy(const MapExprEntry& entry) { auto entry_id = CopyId(entry.id()); auto entry_key = Copy(entry.key()); auto entry_value = Copy(entry.value()); return NewMapEntry(entry_id, std::move(entry_key), std::move(entry_value), entry.optional()); } }
#include "parser/macro_expr_factory.h" #include <cstdint> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "common/expr.h" #include "common/expr_factory.h" #include "internal/testing.h" namespace cel { class TestMacroExprFactory final : public MacroExprFactory { public: TestMacroExprFactory() : MacroExprFactory() {} ExprId id() const { return id_; } Expr ReportError(absl::string_view) override { return NewUnspecified(NextId()); } Expr ReportErrorAt(const Expr&, absl::string_view) override { return NewUnspecified(NextId()); } using MacroExprFactory::NewBoolConst; using MacroExprFactory::NewCall; using MacroExprFactory::NewComprehension; using MacroExprFactory::NewIdent; using MacroExprFactory::NewList; using MacroExprFactory::NewListElement; using MacroExprFactory::NewMap; using MacroExprFactory::NewMapEntry; using MacroExprFactory::NewMemberCall; using MacroExprFactory::NewSelect; using MacroExprFactory::NewStruct; using MacroExprFactory::NewStructField; using MacroExprFactory::NewUnspecified; protected: ExprId NextId() override { return id_++; } ExprId CopyId(ExprId id) override { if (id == 0) { return 0; } return NextId(); } private: int64_t id_ = 1; }; namespace { TEST(MacroExprFactory, CopyUnspecified) { TestMacroExprFactory factory; EXPECT_EQ(factory.Copy(factory.NewUnspecified()), factory.NewUnspecified(2)); } TEST(MacroExprFactory, CopyIdent) { TestMacroExprFactory factory; EXPECT_EQ(factory.Copy(factory.NewIdent("foo")), factory.NewIdent(2, "foo")); } TEST(MacroExprFactory, CopyConst) { TestMacroExprFactory factory; EXPECT_EQ(factory.Copy(factory.NewBoolConst(true)), factory.NewBoolConst(2, true)); } TEST(MacroExprFactory, CopySelect) { TestMacroExprFactory factory; EXPECT_EQ(factory.Copy(factory.NewSelect(factory.NewIdent("foo"), "bar")), factory.NewSelect(3, factory.NewIdent(4, "foo"), "bar")); } TEST(MacroExprFactory, CopyCall) { TestMacroExprFactory factory; std::vector<Expr> copied_args; copied_args.reserve(1); copied_args.push_back(factory.NewIdent(6, "baz")); EXPECT_EQ(factory.Copy(factory.NewMemberCall("bar", factory.NewIdent("foo"), factory.NewIdent("baz"))), factory.NewMemberCall(4, "bar", factory.NewIdent(5, "foo"), absl::MakeSpan(copied_args))); } TEST(MacroExprFactory, CopyList) { TestMacroExprFactory factory; std::vector<ListExprElement> copied_elements; copied_elements.reserve(1); copied_elements.push_back(factory.NewListElement(factory.NewIdent(4, "foo"))); EXPECT_EQ(factory.Copy(factory.NewList( factory.NewListElement(factory.NewIdent("foo")))), factory.NewList(3, absl::MakeSpan(copied_elements))); } TEST(MacroExprFactory, CopyStruct) { TestMacroExprFactory factory; std::vector<StructExprField> copied_fields; copied_fields.reserve(1); copied_fields.push_back( factory.NewStructField(5, "bar", factory.NewIdent(6, "baz"))); EXPECT_EQ(factory.Copy(factory.NewStruct( "foo", factory.NewStructField("bar", factory.NewIdent("baz")))), factory.NewStruct(4, "foo", absl::MakeSpan(copied_fields))); } TEST(MacroExprFactory, CopyMap) { TestMacroExprFactory factory; std::vector<MapExprEntry> copied_entries; copied_entries.reserve(1); copied_entries.push_back(factory.NewMapEntry(6, factory.NewIdent(7, "bar"), factory.NewIdent(8, "baz"))); EXPECT_EQ(factory.Copy(factory.NewMap(factory.NewMapEntry( factory.NewIdent("bar"), factory.NewIdent("baz")))), factory.NewMap(5, absl::MakeSpan(copied_entries))); } TEST(MacroExprFactory, CopyComprehension) { TestMacroExprFactory factory; EXPECT_EQ( factory.Copy(factory.NewComprehension( "foo", factory.NewList(), "bar", factory.NewBoolConst(true), factory.NewIdent("baz"), factory.NewIdent("foo"), factory.NewIdent("bar"))), factory.NewComprehension( 7, "foo", factory.NewList(8, std::vector<ListExprElement>()), "bar", factory.NewBoolConst(9, true), factory.NewIdent(10, "baz"), factory.NewIdent(11, "foo"), factory.NewIdent(12, "bar"))); } } }
56
cpp
google/cel-cpp
parser
parser/parser.cc
parser/parser_test.cc
#ifndef THIRD_PARTY_CEL_CPP_PARSER_PARSER_H_ #define THIRD_PARTY_CEL_CPP_PARSER_PARSER_H_ #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "common/source.h" #include "parser/macro.h" #include "parser/macro_registry.h" #include "parser/options.h" #include "parser/source_factory.h" namespace google::api::expr::parser { class VerboseParsedExpr { public: VerboseParsedExpr(google::api::expr::v1alpha1::ParsedExpr parsed_expr, EnrichedSourceInfo enriched_source_info) : parsed_expr_(std::move(parsed_expr)), enriched_source_info_(std::move(enriched_source_info)) {} const google::api::expr::v1alpha1::ParsedExpr& parsed_expr() const { return parsed_expr_; } const EnrichedSourceInfo& enriched_source_info() const { return enriched_source_info_; } private: google::api::expr::v1alpha1::ParsedExpr parsed_expr_; EnrichedSourceInfo enriched_source_info_; }; absl::StatusOr<VerboseParsedExpr> EnrichedParse( absl::string_view expression, const std::vector<Macro>& macros, absl::string_view description = "<input>", const ParserOptions& options = ParserOptions()); absl::StatusOr<google::api::expr::v1alpha1::ParsedExpr> Parse( absl::string_view expression, absl::string_view description = "<input>", const ParserOptions& options = ParserOptions()); absl::StatusOr<google::api::expr::v1alpha1::ParsedExpr> ParseWithMacros( absl::string_view expression, const std::vector<Macro>& macros, absl::string_view description = "<input>", const ParserOptions& options = ParserOptions()); absl::StatusOr<VerboseParsedExpr> EnrichedParse( const cel::Source& source, const cel::MacroRegistry& registry, const ParserOptions& options = ParserOptions()); absl::StatusOr<google::api::expr::v1alpha1::ParsedExpr> Parse( const cel::Source& source, const cel::MacroRegistry& registry, const ParserOptions& options = ParserOptions()); } #endif #include "parser/parser.h" #include <algorithm> #include <any> #include <array> #include <cstddef> #include <cstdint> #include <exception> #include <functional> #include <iterator> #include <limits> #include <map> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/container/btree_map.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/overload.h" #include "absl/memory/memory.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/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "antlr4-runtime.h" #include "common/ast.h" #include "common/constant.h" #include "common/expr_factory.h" #include "common/operators.h" #include "common/source.h" #include "extensions/protobuf/internal/ast.h" #include "internal/lexis.h" #include "internal/status_macros.h" #include "internal/strings.h" #include "internal/utf8.h" #include "parser/internal/CelBaseVisitor.h" #include "parser/internal/CelLexer.h" #include "parser/internal/CelParser.h" #include "parser/macro.h" #include "parser/macro_expr_factory.h" #include "parser/macro_registry.h" #include "parser/options.h" #include "parser/source_factory.h" namespace google::api::expr::parser { namespace { class ParserVisitor; } } namespace cel { namespace { std::any ExprPtrToAny(std::unique_ptr<Expr>&& expr) { return std::make_any<Expr*>(expr.release()); } std::any ExprToAny(Expr&& expr) { return ExprPtrToAny(std::make_unique<Expr>(std::move(expr))); } std::unique_ptr<Expr> ExprPtrFromAny(std::any&& any) { return absl::WrapUnique(std::any_cast<Expr*>(std::move(any))); } Expr ExprFromAny(std::any&& any) { auto expr = ExprPtrFromAny(std::move(any)); return std::move(*expr); } struct ParserError { std::string message; SourceRange range; }; std::string DisplayParserError(const cel::Source& source, const ParserError& error) { auto location = source.GetLocation(error.range.begin).value_or(SourceLocation{}); return absl::StrCat(absl::StrFormat("ERROR: %s:%zu:%zu: %s", source.description(), location.line, location.column + 1, error.message), source.DisplayErrorLocation(location)); } int32_t PositiveOrMax(int32_t value) { return value >= 0 ? value : std::numeric_limits<int32_t>::max(); } SourceRange SourceRangeFromToken(const antlr4::Token* token) { SourceRange range; if (token != nullptr) { if (auto start = token->getStartIndex(); start != INVALID_INDEX) { range.begin = static_cast<int32_t>(start); } if (auto end = token->getStopIndex(); end != INVALID_INDEX) { range.end = static_cast<int32_t>(end + 1); } } return range; } SourceRange SourceRangeFromParserRuleContext( const antlr4::ParserRuleContext* context) { SourceRange range; if (context != nullptr) { if (auto start = context->getStart() != nullptr ? context->getStart()->getStartIndex() : INVALID_INDEX; start != INVALID_INDEX) { range.begin = static_cast<int32_t>(start); } if (auto end = context->getStop() != nullptr ? context->getStop()->getStopIndex() : INVALID_INDEX; end != INVALID_INDEX) { range.end = static_cast<int32_t>(end + 1); } } return range; } } class ParserMacroExprFactory final : public MacroExprFactory { public: explicit ParserMacroExprFactory(const cel::Source& source) : MacroExprFactory(), source_(source) {} void BeginMacro(SourceRange macro_position) { macro_position_ = macro_position; } void EndMacro() { macro_position_ = SourceRange{}; } Expr ReportError(absl::string_view message) override { return ReportError(macro_position_, message); } Expr ReportError(int64_t expr_id, absl::string_view message) { return ReportError(GetSourceRange(expr_id), message); } Expr ReportError(SourceRange range, absl::string_view message) { ++error_count_; if (errors_.size() <= 100) { errors_.push_back(ParserError{std::string(message), range}); } return NewUnspecified(NextId(range)); } Expr ReportErrorAt(const Expr& expr, absl::string_view message) override { return ReportError(GetSourceRange(expr.id()), message); } SourceRange GetSourceRange(int64_t id) const { if (auto it = positions_.find(id); it != positions_.end()) { return it->second; } return SourceRange{}; } int64_t NextId(const SourceRange& range) { auto id = expr_id_++; if (range.begin != -1 || range.end != -1) { positions_.insert(std::pair{id, range}); } return id; } bool HasErrors() const { return error_count_ != 0; } std::string ErrorMessage() { std::stable_sort( errors_.begin(), errors_.end(), [](const ParserError& lhs, const ParserError& rhs) -> bool { auto lhs_begin = PositiveOrMax(lhs.range.begin); auto lhs_end = PositiveOrMax(lhs.range.end); auto rhs_begin = PositiveOrMax(rhs.range.begin); auto rhs_end = PositiveOrMax(rhs.range.end); return lhs_begin < rhs_begin || (lhs_begin == rhs_begin && lhs_end < rhs_end); }); bool errors_truncated = error_count_ > 100; std::vector<std::string> messages; messages.reserve( errors_.size() + errors_truncated); std::transform(errors_.begin(), errors_.end(), std::back_inserter(messages), [this](const ParserError& error) { return cel::DisplayParserError(source_, error); }); if (errors_truncated) { messages.emplace_back( absl::StrCat(error_count_ - 100, " more errors were truncated.")); } return absl::StrJoin(messages, "\n"); } void AddMacroCall(int64_t macro_id, absl::string_view function, absl::optional<Expr> target, std::vector<Expr> arguments) { macro_calls_.insert( {macro_id, target.has_value() ? NewMemberCall(0, function, std::move(*target), std::move(arguments)) : NewCall(0, function, std::move(arguments))}); } Expr BuildMacroCallArg(const Expr& expr) { if (auto it = macro_calls_.find(expr.id()); it != macro_calls_.end()) { return NewUnspecified(expr.id()); } return absl::visit( absl::Overload( [this, &expr](const UnspecifiedExpr&) -> Expr { return NewUnspecified(expr.id()); }, [this, &expr](const Constant& const_expr) -> Expr { return NewConst(expr.id(), const_expr); }, [this, &expr](const IdentExpr& ident_expr) -> Expr { return NewIdent(expr.id(), ident_expr.name()); }, [this, &expr](const SelectExpr& select_expr) -> Expr { return select_expr.test_only() ? NewPresenceTest( expr.id(), BuildMacroCallArg(select_expr.operand()), select_expr.field()) : NewSelect(expr.id(), BuildMacroCallArg(select_expr.operand()), select_expr.field()); }, [this, &expr](const CallExpr& call_expr) -> Expr { std::vector<Expr> macro_arguments; macro_arguments.reserve(call_expr.args().size()); for (const auto& argument : call_expr.args()) { macro_arguments.push_back(BuildMacroCallArg(argument)); } absl::optional<Expr> macro_target; if (call_expr.has_target()) { macro_target = BuildMacroCallArg(call_expr.target()); } return macro_target.has_value() ? NewMemberCall(expr.id(), call_expr.function(), std::move(*macro_target), std::move(macro_arguments)) : NewCall(expr.id(), call_expr.function(), std::move(macro_arguments)); }, [this, &expr](const ListExpr& list_expr) -> Expr { std::vector<ListExprElement> macro_elements; macro_elements.reserve(list_expr.elements().size()); for (const auto& element : list_expr.elements()) { auto& cloned_element = macro_elements.emplace_back(); if (element.has_expr()) { cloned_element.set_expr(BuildMacroCallArg(element.expr())); } cloned_element.set_optional(element.optional()); } return NewList(expr.id(), std::move(macro_elements)); }, [this, &expr](const StructExpr& struct_expr) -> Expr { std::vector<StructExprField> macro_fields; macro_fields.reserve(struct_expr.fields().size()); for (const auto& field : struct_expr.fields()) { auto& macro_field = macro_fields.emplace_back(); macro_field.set_id(field.id()); macro_field.set_name(field.name()); macro_field.set_value(BuildMacroCallArg(field.value())); macro_field.set_optional(field.optional()); } return NewStruct(expr.id(), struct_expr.name(), std::move(macro_fields)); }, [this, &expr](const MapExpr& map_expr) -> Expr { std::vector<MapExprEntry> macro_entries; macro_entries.reserve(map_expr.entries().size()); for (const auto& entry : map_expr.entries()) { auto& macro_entry = macro_entries.emplace_back(); macro_entry.set_id(entry.id()); macro_entry.set_key(BuildMacroCallArg(entry.key())); macro_entry.set_value(BuildMacroCallArg(entry.value())); macro_entry.set_optional(entry.optional()); } return NewMap(expr.id(), std::move(macro_entries)); }, [this, &expr](const ComprehensionExpr& comprehension_expr) -> Expr { return NewComprehension( expr.id(), comprehension_expr.iter_var(), BuildMacroCallArg(comprehension_expr.iter_range()), comprehension_expr.accu_var(), BuildMacroCallArg(comprehension_expr.accu_init()), BuildMacroCallArg(comprehension_expr.loop_condition()), BuildMacroCallArg(comprehension_expr.loop_step()), BuildMacroCallArg(comprehension_expr.result())); }), expr.kind()); } using ExprFactory::NewBoolConst; using ExprFactory::NewBytesConst; using ExprFactory::NewCall; using ExprFactory::NewComprehension; using ExprFactory::NewConst; using ExprFactory::NewDoubleConst; using ExprFactory::NewIdent; using ExprFactory::NewIntConst; using ExprFactory::NewList; using ExprFactory::NewListElement; using ExprFactory::NewMap; using ExprFactory::NewMapEntry; using ExprFactory::NewMemberCall; using ExprFactory::NewNullConst; using ExprFactory::NewPresenceTest; using ExprFactory::NewSelect; using ExprFactory::NewStringConst; using ExprFactory::NewStruct; using ExprFactory::NewStructField; using ExprFactory::NewUintConst; using ExprFactory::NewUnspecified; const absl::btree_map<int64_t, SourceRange>& positions() const { return positions_; } const absl::flat_hash_map<int64_t, Expr>& macro_calls() const { return macro_calls_; } void EraseId(ExprId id) { positions_.erase(id); if (expr_id_ == id + 1) { --expr_id_; } } protected: int64_t NextId() override { return NextId(macro_position_); } int64_t CopyId(int64_t id) override { if (id == 0) { return 0; } return NextId(GetSourceRange(id)); } private: int64_t expr_id_ = 1; absl::btree_map<int64_t, SourceRange> positions_; absl::flat_hash_map<int64_t, Expr> macro_calls_; std::vector<ParserError> errors_; size_t error_count_ = 0; const Source& source_; SourceRange macro_position_; }; } namespace google::api::expr::parser { namespace { using ::antlr4::CharStream; using ::antlr4::CommonTokenStream; using ::antlr4::DefaultErrorStrategy; using ::antlr4::ParseCancellationException; using ::antlr4::Parser; using ::antlr4::ParserRuleContext; using ::antlr4::Token; using ::antlr4::misc::IntervalSet; using ::antlr4::tree::ErrorNode; using ::antlr4::tree::ParseTreeListener; using ::antlr4::tree::TerminalNode; using ::cel::Expr; using ::cel::ExprFromAny; using ::cel::ExprKind; using ::cel::ExprToAny; using ::cel::IdentExpr; using ::cel::ListExprElement; using ::cel::MapExprEntry; using ::cel::SelectExpr; using ::cel::SourceRangeFromParserRuleContext; using ::cel::SourceRangeFromToken; using ::cel::StructExprField; using ::cel_parser_internal::CelBaseVisitor; using ::cel_parser_internal::CelLexer; using ::cel_parser_internal::CelParser; using common::CelOperator; using common::ReverseLookupOperator; using ::google::api::expr::v1alpha1::ParsedExpr; class CodePointStream final : public CharStream { public: CodePointStream(cel::SourceContentView buffer, absl::string_view source_name) : buffer_(buffer), source_name_(source_name), size_(buffer_.size()), index_(0) {} void consume() override { if (ABSL_PREDICT_FALSE(index_ >= size_)) { ABSL_ASSERT(LA(1) == IntStream::EOF); throw antlr4::IllegalStateException("cannot consume EOF"); } index_++; } size_t LA(ssize_t i) override { if (ABSL_PREDICT_FALSE(i == 0)) { return 0; } auto p = static_cast<ssize_t>(index_); if (i < 0) { i++; if (p + i - 1 < 0) { return IntStream::EOF; } } if (p + i - 1 >= static_cast<ssize_t>(size_)) { return IntStream::EOF; } return buffer_.at(static_cast<size_t>(p + i - 1)); } ssize_t mark() override { return -1; } void release(ssize_t marker) override {} size_t index() override { return index_; } void seek(size_t index) override { index_ = std::min(index, size_); } size_t size() override { return size_; } std::string getSourceName() const override { return source_name_.empty() ? IntStream::UNKNOWN_SOURCE_NAME : std::string(source_name_); } std::string getText(const antlr4::misc::Interval& interval) override { if (ABSL_PREDICT_FALSE(interval.a < 0 || interval.b < 0)) { return std::string(); } size_t start = static_cast<size_t>(interval.a); if (ABSL_PREDICT_FALSE(start >= size_)) { return std::string(); } size_t stop = static_cast<size_t>(interval.b); if (ABSL_PREDICT_FALSE(stop >= size_)) { stop = size_ - 1; } return buffer_.ToString(static_cast<cel::SourcePosition>(start), static_cast<cel::SourcePosition>(stop) + 1); } std::string toString() const override { return buffer_.ToString(); } private: cel::SourceContentView const buffer_; const absl::string_view source_name_; const size_t size_; size_t index_; }; class ScopedIncrement final { public: explicit ScopedIncrement(int& recursion_depth) : recursion_depth_(recursion_depth) { ++recursion_depth_; } ~ScopedIncrement() { --recursion_depth_; } private: int& recursion_depth_; }; class ExpressionBalancer final { public: ExpressionBalancer(cel::ParserMacroExprFactory& factory, std::string function, Expr expr); void AddTerm(int64_t op, Expr term); Expr Balance(); private: Expr BalancedTree(int lo, int hi); private: cel::ParserMacroExprFactory& factory_; std::string function_; std::vector<Expr> terms_; std::vector<int64_t> ops_; }; ExpressionBalancer::ExpressionBalancer(cel::ParserMacroExprFactory& factory, std::string function, Expr expr) : factory_(factory), function_(std::move(function)) { terms_.push_back(std::move(expr)); } void ExpressionBalancer::AddTerm(int64_t op, Expr term) { terms_.push_back(std::move(term)); ops_.push_back(op); } Expr ExpressionBalancer::Balance() { if (terms_.size() == 1) { return std::move(terms_[0]); } return BalancedTree(0, ops_.size() - 1); } Expr ExpressionBalancer::BalancedTree(int lo, int hi) { int mid = (lo + hi + 1) / 2; std::vector<Expr> arguments; arguments.reserve(2); if (mid == lo) { arguments.push_back(std::move(terms_[mid])); } else { arguments.push_back(BalancedTree(lo, mid - 1)); } if (mid == hi) { arguments.push_back(std::move(terms_[mid + 1])); } else { arguments.push_back(BalancedTree(mid + 1, hi)); } return factory_.NewCall(ops_[mid], function_, std::move(arguments)); } class ParserVisitor final : public CelBaseVisitor, public antlr4::BaseErrorListener { public: ParserVisitor(const cel::Source& source, int max_recursion_depth, const cel::MacroRegistry& macro_registry, bool add_macro_calls = false, bool enable_optional_syntax = false); ~ParserVisitor() override; std::any visit(antlr4::tree::ParseTree* tree) override; std::any visitStart(CelParser::StartContext* ctx) override; std::any visitExpr(CelParser::ExprContext* ctx) override; std::any visitConditionalOr(CelParser::ConditionalOrContext* ctx) override; std::any visitConditionalAnd(CelParser::ConditionalAndContext* ctx) override; std::any visitRelation(CelParser::RelationContext* ctx) override; std::any visitCalc(CelParser::CalcContext* ctx) override; std::any visitUnary(CelParser::UnaryContext* ctx); std::any visitLogicalNot(CelParser::LogicalNotContext* ctx) override; std::any visitNegate(CelParser::NegateContext* ctx) override; std::any visitSelect(CelParser::SelectContext* ctx) override; std::any visitMemberCall(CelParser::MemberCallContext* ctx) override; std::any visitIndex(CelParser::IndexContext* ctx) override; std::any visitCreateMessage(CelParser::CreateMessageContext* ctx) override; std::any visitFieldInitializerList( CelParser::FieldInitializerListContext* ctx) override; std::vector<StructExprField> visitFields( CelParser::FieldInitializerListContext* ctx); std::any visitIdentOrGlobalCall( CelParser::IdentOrGlobalCallContext* ctx) override; std::any visitNested(CelParser::NestedContext* ctx) override; std::any visitCreateList(CelParser::CreateListContext* ctx) override; std::vector<ListExprElement> visitList(CelParser::ListInitContext* ctx); std::vector<Expr> visitList(CelParser::ExprListContext* ctx); std::any visitCreateStruct(CelParser::CreateStructContext* ctx) override; std::any visitConstantLiteral( CelParser::ConstantLiteralContext* ctx) override; std::any visitPrimaryExpr(CelParser::PrimaryExprContext* ctx) override; std::any visitMemberExpr(CelParser::MemberExprContext* ctx) override; std::any visitMapInitializerList( CelParser::MapInitializerListContext* ctx) override; std::vector<MapExprEntry> visitEntries( CelParser::MapInitializerListContext* ctx); std::any visitInt(CelParser::IntContext* ctx) override; std::any visitUint(CelParser::UintContext* ctx) override; std::any visitDouble(CelParser::DoubleContext* ctx) override; std::any visitString(CelParser::StringContext* ctx) override; std::any visitBytes(CelParser::BytesContext* ctx) override; std::any visitBoolTrue(CelParser::BoolTrueContext* ctx) override; std::any visitBoolFalse(CelParser::BoolFalseContext* ctx) override; std::any visitNull(CelParser::NullContext* ctx) override; absl::Status GetSourceInfo(google::api::expr::v1alpha1::SourceInfo* source_info) const; EnrichedSourceInfo enriched_source_info() const; void syntaxError(antlr4::Recognizer* recognizer, antlr4::Token* offending_symbol, size_t line, size_t col, const std::string& msg, std::exception_ptr e) override; bool HasErrored() const; std::string ErrorMessage(); private: template <typename... Args> Expr GlobalCallOrMacro(int64_t expr_id, absl::string_view function, Args&&... args) { std::vector<Expr> arguments; arguments.reserve(sizeof...(Args)); (arguments.push_back(std::forward<Args>(args)), ...); return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); } template <typename... Args> Expr ReceiverCallOrMacro(int64_t expr_id, absl::string_view function, Expr target, Args&&... args) { std::vector<Expr> arguments; arguments.reserve(sizeof...(Args)); (arguments.push_back(std::forward<Args>(args)), ...); return ReceiverCallOrMacroImpl(expr_id, function, std::move(target), std::move(arguments)); } Expr GlobalCallOrMacroImpl(int64_t expr_id, absl::string_view function, std::vector<Expr> args); Expr ReceiverCallOrMacroImpl(int64_t expr_id, absl::string_view function, Expr target, std::vector<Expr> args); std::string ExtractQualifiedName(antlr4::ParserRuleContext* ctx, const Expr& e); antlr4::tree::ParseTree* UnnestContext(antlr4::tree::ParseTree* tree); private: const cel::Source& source_; cel::ParserMacroExprFactory factory_; const cel::MacroRegistry& macro_registry_; int recursion_depth_; const int max_recursion_depth_; const bool add_macro_calls_; const bool enable_optional_syntax_; }; ParserVisitor::ParserVisitor(const cel::Source& source, const int max_recursion_depth, const cel::MacroRegistry& macro_registry, const bool add_macro_calls, bool enable_optional_syntax) : source_(source), factory_(source_), macro_registry_(macro_registry), recursion_depth_(0), max_recursion_depth_(max_recursion_depth), add_macro_calls_(add_macro_calls), enable_optional_syntax_(enable_optional_syntax) {} ParserVisitor::~ParserVisitor() {} template <typename T, typename = std::enable_if_t< std::is_base_of<antlr4::tree::ParseTree, T>::value>> T* tree_as(antlr4::tree::ParseTree* tree) { return dynamic_cast<T*>(tree); } std::any ParserVisitor::visit(antlr4::tree::ParseTree* tree) { ScopedIncrement inc(recursion_depth_); if (recursion_depth_ > max_recursion_depth_) { return ExprToAny(factory_.ReportError( absl::StrFormat("Exceeded max recursion depth of %d when parsing.", max_recursion_depth_))); } tree = UnnestContext(tree); if (auto* ctx = tree_as<CelParser::StartContext>(tree)) { return visitStart(ctx); } else if (auto* ctx = tree_as<CelParser::ExprContext>(tree)) { return visitExpr(ctx); } else if (auto* ctx = tree_as<CelParser::ConditionalAndContext>(tree)) { return visitConditionalAnd(ctx); } else if (auto* ctx = tree_as<CelParser::ConditionalOrContext>(tree)) { return visitConditionalOr(ctx); } else if (auto* ctx = tree_as<CelParser::RelationContext>(tree)) { return visitRelation(ctx); } else if (auto* ctx = tree_as<CelParser::CalcContext>(tree)) { return visitCalc(ctx); } else if (auto* ctx = tree_as<CelParser::LogicalNotContext>(tree)) { return visitLogicalNot(ctx); } else if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(tree)) { return visitPrimaryExpr(ctx); } else if (auto* ctx = tree_as<CelParser::MemberExprContext>(tree)) { return visitMemberExpr(ctx); } else if (auto* ctx = tree_as<CelParser::SelectContext>(tree)) { return visitSelect(ctx); } else if (auto* ctx = tree_as<CelParser::MemberCallContext>(tree)) { return visitMemberCall(ctx); } else if (auto* ctx = tree_as<CelParser::MapInitializerListContext>(tree)) { return visitMapInitializerList(ctx); } else if (auto* ctx = tree_as<CelParser::NegateContext>(tree)) { return visitNegate(ctx); } else if (auto* ctx = tree_as<CelParser::IndexContext>(tree)) { return visitIndex(ctx); } else if (auto* ctx = tree_as<CelParser::UnaryContext>(tree)) { return visitUnary(ctx); } else if (auto* ctx = tree_as<CelParser::CreateListContext>(tree)) { return visitCreateList(ctx); } else if (auto* ctx = tree_as<CelParser::CreateMessageContext>(tree)) { return visitCreateMessage(ctx); } else if (auto* ctx = tree_as<CelParser::CreateStructContext>(tree)) { return visitCreateStruct(ctx); } if (tree) { return ExprToAny( factory_.ReportError(SourceRangeFromParserRuleContext( tree_as<antlr4::ParserRuleContext>(tree)), "unknown parsetree type")); } return ExprToAny(factory_.ReportError("<<nil>> parsetree")); } std::any ParserVisitor::visitPrimaryExpr(CelParser::PrimaryExprContext* pctx) { CelParser::PrimaryContext* primary = pctx->primary(); if (auto* ctx = tree_as<CelParser::NestedContext>(primary)) { return visitNested(ctx); } else if (auto* ctx = tree_as<CelParser::IdentOrGlobalCallContext>(primary)) { return visitIdentOrGlobalCall(ctx); } else if (auto* ctx = tree_as<CelParser::CreateListContext>(primary)) { return visitCreateList(ctx); } else if (auto* ctx = tree_as<CelParser::CreateStructContext>(primary)) { return visitCreateStruct(ctx); } else if (auto* ctx = tree_as<CelParser::CreateMessageContext>(primary)) { return visitCreateMessage(ctx); } else if (auto* ctx = tree_as<CelParser::ConstantLiteralContext>(primary)) { return visitConstantLiteral(ctx); } if (factory_.HasErrors()) { return ExprToAny(factory_.NewUnspecified(factory_.NextId({}))); } return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(pctx), "invalid primary expression")); } std::any ParserVisitor::visitMemberExpr(CelParser::MemberExprContext* mctx) { CelParser::MemberContext* member = mctx->member(); if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(member)) { return visitPrimaryExpr(ctx); } else if (auto* ctx = tree_as<CelParser::SelectContext>(member)) { return visitSelect(ctx); } else if (auto* ctx = tree_as<CelParser::MemberCallContext>(member)) { return visitMemberCall(ctx); } else if (auto* ctx = tree_as<CelParser::IndexContext>(member)) { return visitIndex(ctx); } return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(mctx), "unsupported simple expression")); } std::any ParserVisitor::visitStart(CelParser::StartContext* ctx) { return visit(ctx->expr()); } antlr4::tree::ParseTree* ParserVisitor::UnnestContext( antlr4::tree::ParseTree* tree) { antlr4::tree::ParseTree* last = nullptr; while (tree != last) { last =
#include "parser/parser.h" #include <list> #include <string> #include <thread> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/algorithm/container.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/types/optional.h" #include "internal/benchmark.h" #include "internal/testing.h" #include "parser/macro.h" #include "parser/options.h" #include "parser/source_factory.h" #include "testutil/expr_printer.h" namespace google::api::expr::parser { namespace { using ::google::api::expr::v1alpha1::Expr; using testing::HasSubstr; using testing::Not; using cel::internal::IsOk; struct TestInfo { TestInfo(const std::string& I, const std::string& P, const std::string& E = "", const std::string& L = "", const std::string& R = "", const std::string& M = "", bool benchmark = true) : I(I), P(P), E(E), L(L), R(R), M(M), benchmark(benchmark) {} std::string I; std::string P; std::string E; std::string L; std::string R; std::string M; bool benchmark; }; std::vector<TestInfo> test_cases = { {"x * 2", "_*_(\n" " x^#1:Expr.Ident#,\n" " 2^#3:int64#\n" ")^#2:Expr.Call#"}, {"x * 2u", "_*_(\n" " x^#1:Expr.Ident#,\n" " 2u^#3:uint64#\n" ")^#2:Expr.Call#"}, {"x * 2.0", "_*_(\n" " x^#1:Expr.Ident#,\n" " 2.^#3:double#\n" ")^#2:Expr.Call#"}, {"\"\\u2764\"", "\"\u2764\"^#1:string#"}, {"\"\u2764\"", "\"\u2764\"^#1:string#"}, {"! false", "!_(\n" " false^#2:bool#\n" ")^#1:Expr.Call#"}, {"-a", "-_(\n" " a^#2:Expr.Ident#\n" ")^#1:Expr.Call#"}, {"a.b(5)", "a^#1:Expr.Ident#.b(\n" " 5^#3:int64#\n" ")^#2:Expr.Call#"}, {"a[3]", "_[_](\n" " a^#1:Expr.Ident#,\n" " 3^#3:int64#\n" ")^#2:Expr.Call#"}, {"SomeMessage{foo: 5, bar: \"xyz\"}", "SomeMessage{\n" " foo:5^#3:int64#^#2:Expr.CreateStruct.Entry#,\n" " bar:\"xyz\"^#5:string#^#4:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"[3, 4, 5]", "[\n" " 3^#2:int64#,\n" " 4^#3:int64#,\n" " 5^#4:int64#\n" "]^#1:Expr.CreateList#"}, {"{foo: 5, bar: \"xyz\"}", "{\n" " foo^#3:Expr.Ident#:5^#4:int64#^#2:Expr.CreateStruct.Entry#,\n" " bar^#6:Expr.Ident#:\"xyz\"^#7:string#^#5:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"a > 5 && a < 10", "_&&_(\n" " _>_(\n" " a^#1:Expr.Ident#,\n" " 5^#3:int64#\n" " )^#2:Expr.Call#,\n" " _<_(\n" " a^#4:Expr.Ident#,\n" " 10^#6:int64#\n" " )^#5:Expr.Call#\n" ")^#7:Expr.Call#"}, {"a < 5 || a > 10", "_||_(\n" " _<_(\n" " a^#1:Expr.Ident#,\n" " 5^#3:int64#\n" " )^#2:Expr.Call#,\n" " _>_(\n" " a^#4:Expr.Ident#,\n" " 10^#6:int64#\n" " )^#5:Expr.Call#\n" ")^#7:Expr.Call#"}, {"{", "", "ERROR: <input>:1:2: Syntax error: mismatched input '<EOF>' expecting " "{'[', " "'{', '}', '(', '.', ',', '-', '!', '\\u003F', 'true', 'false', 'null', " "NUM_FLOAT, " "NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n | {\n" " | .^"}, {"\"A\"", "\"A\"^#1:string#"}, {"true", "true^#1:bool#"}, {"false", "false^#1:bool#"}, {"0", "0^#1:int64#"}, {"42", "42^#1:int64#"}, {"0u", "0u^#1:uint64#"}, {"23u", "23u^#1:uint64#"}, {"24u", "24u^#1:uint64#"}, {"0xAu", "10u^#1:uint64#"}, {"-0xA", "-10^#1:int64#"}, {"0xA", "10^#1:int64#"}, {"-1", "-1^#1:int64#"}, {"4--4", "_-_(\n" " 4^#1:int64#,\n" " -4^#3:int64#\n" ")^#2:Expr.Call#"}, {"4--4.1", "_-_(\n" " 4^#1:int64#,\n" " -4.1^#3:double#\n" ")^#2:Expr.Call#"}, {"b\"abc\"", "b\"abc\"^#1:bytes#"}, {"23.39", "23.39^#1:double#"}, {"!a", "!_(\n" " a^#2:Expr.Ident#\n" ")^#1:Expr.Call#"}, {"null", "null^#1:NullValue#"}, {"a", "a^#1:Expr.Ident#"}, {"a?b:c", "_?_:_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#,\n" " c^#4:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a || b", "_||_(\n" " a^#1:Expr.Ident#,\n" " b^#2:Expr.Ident#\n" ")^#3:Expr.Call#"}, {"a || b || c || d || e || f ", "_||_(\n" " _||_(\n" " _||_(\n" " a^#1:Expr.Ident#,\n" " b^#2:Expr.Ident#\n" " )^#3:Expr.Call#,\n" " c^#4:Expr.Ident#\n" " )^#5:Expr.Call#,\n" " _||_(\n" " _||_(\n" " d^#6:Expr.Ident#,\n" " e^#8:Expr.Ident#\n" " )^#9:Expr.Call#,\n" " f^#10:Expr.Ident#\n" " )^#11:Expr.Call#\n" ")^#7:Expr.Call#"}, {"a && b", "_&&_(\n" " a^#1:Expr.Ident#,\n" " b^#2:Expr.Ident#\n" ")^#3:Expr.Call#"}, {"a && b && c && d && e && f && g", "_&&_(\n" " _&&_(\n" " _&&_(\n" " a^#1:Expr.Ident#,\n" " b^#2:Expr.Ident#\n" " )^#3:Expr.Call#,\n" " _&&_(\n" " c^#4:Expr.Ident#,\n" " d^#6:Expr.Ident#\n" " )^#7:Expr.Call#\n" " )^#5:Expr.Call#,\n" " _&&_(\n" " _&&_(\n" " e^#8:Expr.Ident#,\n" " f^#10:Expr.Ident#\n" " )^#11:Expr.Call#,\n" " g^#12:Expr.Ident#\n" " )^#13:Expr.Call#\n" ")^#9:Expr.Call#"}, {"a && b && c && d || e && f && g && h", "_||_(\n" " _&&_(\n" " _&&_(\n" " a^#1:Expr.Ident#,\n" " b^#2:Expr.Ident#\n" " )^#3:Expr.Call#,\n" " _&&_(\n" " c^#4:Expr.Ident#,\n" " d^#6:Expr.Ident#\n" " )^#7:Expr.Call#\n" " )^#5:Expr.Call#,\n" " _&&_(\n" " _&&_(\n" " e^#8:Expr.Ident#,\n" " f^#9:Expr.Ident#\n" " )^#10:Expr.Call#,\n" " _&&_(\n" " g^#11:Expr.Ident#,\n" " h^#13:Expr.Ident#\n" " )^#14:Expr.Call#\n" " )^#12:Expr.Call#\n" ")^#15:Expr.Call#"}, {"a + b", "_+_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a - b", "_-_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a * b", "_*_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a / b", "_/_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, { "a % b", "_%_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#", }, {"a in b", "@in(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a == b", "_==_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a != b", "_!=_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a > b", "_>_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a >= b", "_>=_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a < b", "_<_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a <= b", "_<=_(\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"a.b", "a^#1:Expr.Ident#.b^#2:Expr.Select#"}, {"a.b.c", "a^#1:Expr.Ident#.b^#2:Expr.Select#.c^#3:Expr.Select#"}, {"a[b]", "_[_](\n" " a^#1:Expr.Ident#,\n" " b^#3:Expr.Ident#\n" ")^#2:Expr.Call#"}, {"foo{ }", "foo{}^#1:Expr.CreateStruct#"}, {"foo{ a:b }", "foo{\n" " a:b^#3:Expr.Ident#^#2:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"foo{ a:b, c:d }", "foo{\n" " a:b^#3:Expr.Ident#^#2:Expr.CreateStruct.Entry#,\n" " c:d^#5:Expr.Ident#^#4:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"{}", "{}^#1:Expr.CreateStruct#"}, {"{a:b, c:d}", "{\n" " a^#3:Expr.Ident#:b^#4:Expr.Ident#^#2:Expr.CreateStruct.Entry#,\n" " c^#6:Expr.Ident#:d^#7:Expr.Ident#^#5:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"[]", "[]^#1:Expr.CreateList#"}, {"[a]", "[\n" " a^#2:Expr.Ident#\n" "]^#1:Expr.CreateList#"}, {"[a, b, c]", "[\n" " a^#2:Expr.Ident#,\n" " b^#3:Expr.Ident#,\n" " c^#4:Expr.Ident#\n" "]^#1:Expr.CreateList#"}, {"(a)", "a^#1:Expr.Ident#"}, {"((a))", "a^#1:Expr.Ident#"}, {"a()", "a()^#1:Expr.Call#"}, {"a(b)", "a(\n" " b^#2:Expr.Ident#\n" ")^#1:Expr.Call#"}, {"a(b, c)", "a(\n" " b^#2:Expr.Ident#,\n" " c^#3:Expr.Ident#\n" ")^#1:Expr.Call#"}, {"a.b()", "a^#1:Expr.Ident#.b()^#2:Expr.Call#"}, { "a.b(c)", "a^#1:Expr.Ident#.b(\n" " c^#3:Expr.Ident#\n" ")^#2:Expr.Call#", "", "a^#1[1,0]#.b(\n" " c^#3[1,4]#\n" ")^#2[1,3]#", "[1,0,0]^#[2,3,3]^#[3,4,4]", }, { "aaa.bbb(ccc)", "aaa^#1:Expr.Ident#.bbb(\n" " ccc^#3:Expr.Ident#\n" ")^#2:Expr.Call#", "", "aaa^#1[1,0]#.bbb(\n" " ccc^#3[1,8]#\n" ")^#2[1,7]#", "[1,0,2]^#[2,7,7]^#[3,8,10]", }, {"*@a | b", "", "ERROR: <input>:1:1: Syntax error: extraneous input '*' expecting {'[', " "'{', " "'(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | *@a | b\n" " | ^\n" "ERROR: <input>:1:2: Syntax error: token recognition error at: '@'\n" " | *@a | b\n" " | .^\n" "ERROR: <input>:1:5: Syntax error: token recognition error at: '| '\n" " | *@a | b\n" " | ....^\n" "ERROR: <input>:1:7: Syntax error: extraneous input 'b' expecting <EOF>\n" " | *@a | b\n" " | ......^"}, {"a | b", "", "ERROR: <input>:1:3: Syntax error: token recognition error at: '| '\n" " | a | b\n" " | ..^\n" "ERROR: <input>:1:5: Syntax error: extraneous input 'b' expecting <EOF>\n" " | a | b\n" " | ....^"}, {"?", "", "ERROR: <input>:1:1: Syntax error: mismatched input '?' expecting " "{'[', '{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, " "NUM_INT, NUM_UINT, STRING, BYTES, IDENTIFIER}\n | ?\n | ^\n" "ERROR: <input>:1:2: Syntax error: mismatched input '<EOF>' expecting " "{'[', '{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, " "NUM_INT, NUM_UINT, STRING, BYTES, IDENTIFIER}\n | ?\n | .^\n" "ERROR: <input>:4294967295:0: <<nil>> parsetree"}, {"t{>C}", "", "ERROR: <input>:1:3: Syntax error: extraneous input '>' expecting {'}', " "',', '\\u003F', IDENTIFIER}\n | t{>C}\n | ..^\nERROR: <input>:1:5: " "Syntax error: " "mismatched input '}' expecting ':'\n | t{>C}\n | ....^"}, {"has(m.f)", "m^#2:Expr.Ident#.f~test-only~^#4:Expr.Select#", "", "m^#2[1,4]#.f~test-only~^#4[1,3]#", "[2,4,4]^#[3,5,5]^#[4,3,3]", "has(\n" " m^#2:Expr.Ident#.f^#3:Expr.Select#\n" ")^#4:has"}, {"m.exists_one(v, f)", "__comprehension__(\n" " " v,\n" " " m^#1:Expr.Ident#,\n" " " __result__,\n" " " 0^#5:int64#,\n" " " true^#6:bool#,\n" " " _?_:_(\n" " f^#4:Expr.Ident#,\n" " _+_(\n" " __result__^#7:Expr.Ident#,\n" " 1^#8:int64#\n" " )^#9:Expr.Call#,\n" " __result__^#10:Expr.Ident#\n" " )^#11:Expr.Call#,\n" " " _==_(\n" " __result__^#12:Expr.Ident#,\n" " 1^#13:int64#\n" " )^#14:Expr.Call#)^#15:Expr.Comprehension#", "", "", "", "m^#1:Expr.Ident#.exists_one(\n" " v^#3:Expr.Ident#,\n" " f^#4:Expr.Ident#\n" ")^#15:exists_one"}, {"m.map(v, f)", "__comprehension__(\n" " " v,\n" " " m^#1:Expr.Ident#,\n" " " __result__,\n" " " []^#5:Expr.CreateList#,\n" " " true^#6:bool#,\n" " " _+_(\n" " __result__^#7:Expr.Ident#,\n" " [\n" " f^#4:Expr.Ident#\n" " ]^#8:Expr.CreateList#\n" " )^#9:Expr.Call#,\n" " " __result__^#10:Expr.Ident#)^#11:Expr.Comprehension#", "", "", "", "m^#1:Expr.Ident#.map(\n" " v^#3:Expr.Ident#,\n" " f^#4:Expr.Ident#\n" ")^#11:map"}, {"m.map(v, p, f)", "__comprehension__(\n" " " v,\n" " " m^#1:Expr.Ident#,\n" " " __result__,\n" " " []^#6:Expr.CreateList#,\n" " " true^#7:bool#,\n" " " _?_:_(\n" " p^#4:Expr.Ident#,\n" " _+_(\n" " __result__^#8:Expr.Ident#,\n" " [\n" " f^#5:Expr.Ident#\n" " ]^#9:Expr.CreateList#\n" " )^#10:Expr.Call#,\n" " __result__^#11:Expr.Ident#\n" " )^#12:Expr.Call#,\n" " " __result__^#13:Expr.Ident#)^#14:Expr.Comprehension#", "", "", "", "m^#1:Expr.Ident#.map(\n" " v^#3:Expr.Ident#,\n" " p^#4:Expr.Ident#,\n" " f^#5:Expr.Ident#\n" ")^#14:map"}, {"m.filter(v, p)", "__comprehension__(\n" " " v,\n" " " m^#1:Expr.Ident#,\n" " " __result__,\n" " " []^#5:Expr.CreateList#,\n" " " true^#6:bool#,\n" " " _?_:_(\n" " p^#4:Expr.Ident#,\n" " _+_(\n" " __result__^#7:Expr.Ident#,\n" " [\n" " v^#3:Expr.Ident#\n" " ]^#8:Expr.CreateList#\n" " )^#9:Expr.Call#,\n" " __result__^#10:Expr.Ident#\n" " )^#11:Expr.Call#,\n" " " __result__^#12:Expr.Ident#)^#13:Expr.Comprehension#", "", "", "", "m^#1:Expr.Ident#.filter(\n" " v^#3:Expr.Ident#,\n" " p^#4:Expr.Ident#\n" ")^#13:filter"}, {"[] + [1,2,3,] + [4]", "_+_(\n" " _+_(\n" " []^#1:Expr.CreateList#,\n" " [\n" " 1^#4:int64#,\n" " 2^#5:int64#,\n" " 3^#6:int64#\n" " ]^#3:Expr.CreateList#\n" " )^#2:Expr.Call#,\n" " [\n" " 4^#9:int64#\n" " ]^#8:Expr.CreateList#\n" ")^#7:Expr.Call#"}, {"{1:2u, 2:3u}", "{\n" " 1^#3:int64#:2u^#4:uint64#^#2:Expr.CreateStruct.Entry#,\n" " 2^#6:int64#:3u^#7:uint64#^#5:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"TestAllTypes{single_int32: 1, single_int64: 2}", "TestAllTypes{\n" " single_int32:1^#3:int64#^#2:Expr.CreateStruct.Entry#,\n" " single_int64:2^#5:int64#^#4:Expr.CreateStruct.Entry#\n" "}^#1:Expr.CreateStruct#"}, {"TestAllTypes(){single_int32: 1, single_int64: 2}", "", "ERROR: <input>:1:15: Syntax error: mismatched input '{' expecting <EOF>\n" " | TestAllTypes(){single_int32: 1, single_int64: 2}\n" " | ..............^"}, {"size(x) == x.size()", "_==_(\n" " size(\n" " x^#2:Expr.Ident#\n" " )^#1:Expr.Call#,\n" " x^#4:Expr.Ident#.size()^#5:Expr.Call#\n" ")^#3:Expr.Call#"}, {"1 + $", "", "ERROR: <input>:1:5: Syntax error: token recognition error at: '$'\n" " | 1 + $\n" " | ....^\n" "ERROR: <input>:1:6: Syntax error: mismatched input '<EOF>' expecting " "{'[', " "'{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | 1 + $\n" " | .....^"}, {"1 + 2\n" "3 +", "", "ERROR: <input>:2:1: Syntax error: mismatched input '3' expecting <EOF>\n" " | 3 +\n" " | ^"}, {"\"\\\"\"", "\"\\\"\"^#1:string#"}, {"[1,3,4][0]", "_[_](\n" " [\n" " 1^#2:int64#,\n" " 3^#3:int64#,\n" " 4^#4:int64#\n" " ]^#1:Expr.CreateList#,\n" " 0^#6:int64#\n" ")^#5:Expr.Call#"}, {"1.all(2, 3)", "", "ERROR: <input>:1:7: all() variable name must be a simple identifier\n" " | 1.all(2, 3)\n" " | ......^"}, {"x[\"a\"].single_int32 == 23", "_==_(\n" " _[_](\n" " x^#1:Expr.Ident#,\n" " \"a\"^#3:string#\n" " )^#2:Expr.Call#.single_int32^#4:Expr.Select#,\n" " 23^#6:int64#\n" ")^#5:Expr.Call#"}, {"x.single_nested_message != null", "_!=_(\n" " x^#1:Expr.Ident#.single_nested_message^#2:Expr.Select#,\n" " null^#4:NullValue#\n" ")^#3:Expr.Call#"}, {"false && !true || false ? 2 : 3", "_?_:_(\n" " _||_(\n" " _&&_(\n" " false^#1:bool#,\n" " !_(\n" " true^#3:bool#\n" " )^#2:Expr.Call#\n" " )^#4:Expr.Call#,\n" " false^#5:bool#\n" " )^#6:Expr.Call#,\n" " 2^#8:int64#,\n" " 3^#9:int64#\n" ")^#7:Expr.Call#"}, {"b\"abc\" + B\"def\"", "_+_(\n" " b\"abc\"^#1:bytes#,\n" " b\"def\"^#3:bytes#\n" ")^#2:Expr.Call#"}, {"1 + 2 * 3 - 1 / 2 == 6 % 1", "_==_(\n" " _-_(\n" " _+_(\n" " 1^#1:int64#,\n" " _*_(\n" " 2^#3:int64#,\n" " 3^#5:int64#\n" " )^#4:Expr.Call#\n" " )^#2:Expr.Call#,\n" " _/_(\n" " 1^#7:int64#,\n" " 2^#9:int64#\n" " )^#8:Expr.Call#\n" " )^#6:Expr.Call#,\n" " _%_(\n" " 6^#11:int64#,\n" " 1^#13:int64#\n" " )^#12:Expr.Call#\n" ")^#10:Expr.Call#"}, {"---a", "-_(\n" " a^#2:Expr.Ident#\n" ")^#1:Expr.Call#"}, {"1 + +", "", "ERROR: <input>:1:5: Syntax error: mismatched input '+' expecting {'[', " "'{'," " '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT," " STRING, BYTES, IDENTIFIER}\n" " | 1 + +\n" " | ....^\n" "ERROR: <input>:1:6: Syntax error: mismatched input '<EOF>' expecting " "{'[', " "'{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | 1 + +\n" " | .....^"}, {"\"abc\" + \"def\"", "_+_(\n" " \"abc\"^#1:string#,\n" " \"def\"^#3:string#\n" ")^#2:Expr.Call#"}, {"{\"a\": 1}.\"a\"", "", "ERROR: <input>:1:10: Syntax error: no viable alternative at input " "'.\"a\"'\n" " | {\"a\": 1}.\"a\"\n" " | .........^"}, {"\"\\xC3\\XBF\"", "\"ÿ\"^#1:string#"}, {"\"\\303\\277\"", "\"ÿ\"^#1:string#"}, {"\"hi\\u263A \\u263Athere\"", "\"hi☺ ☺there\"^#1:string#"}, {"\"\\U000003A8\\?\"", "\"Ψ?\"^#1:string#"}, {"\"\\a\\b\\f\\n\\r\\t\\v'\\\"\\\\\\? Legal escapes\"", "\"\\x07\\x08\\x0c\\n\\r\\t\\x0b'\\\"\\\\? Legal escapes\"^#1:string#"}, {"\"\\xFh\"", "", "ERROR: <input>:1:1: Syntax error: token recognition error at: '\"\\xFh'\n" " | \"\\xFh\"\n" " | ^\n" "ERROR: <input>:1:6: Syntax error: token recognition error at: '\"'\n" " | \"\\xFh\"\n" " | .....^\n" "ERROR: <input>:1:7: Syntax error: mismatched input '<EOF>' expecting " "{'[', " "'{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | \"\\xFh\"\n" " | ......^"}, {"\"\\a\\b\\f\\n\\r\\t\\v\\'\\\"\\\\\\? Illegal escape \\>\"", "", "ERROR: <input>:1:1: Syntax error: token recognition error at: " "'\"\\a\\b\\f\\n\\r\\t\\v\\'\\\"\\\\\\? Illegal escape \\>'\n" " | \"\\a\\b\\f\\n\\r\\t\\v\\'\\\"\\\\\\? Illegal escape \\>\"\n" " | ^\n" "ERROR: <input>:1:42: Syntax error: token recognition error at: '\"'\n" " | \"\\a\\b\\f\\n\\r\\t\\v\\'\\\"\\\\\\? Illegal escape \\>\"\n" " | .........................................^\n" "ERROR: <input>:1:43: Syntax error: mismatched input '<EOF>' expecting " "{'['," " '{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | \"\\a\\b\\f\\n\\r\\t\\v\\'\\\"\\\\\\? Illegal escape \\>\"\n" " | ..........................................^"}, {"'😁' in ['😁', '😑', '😦']", "@in(\n" " \"😁\"^#1:string#,\n" " [\n" " \"😁\"^#4:string#,\n" " \"😑\"^#5:string#,\n" " \"😦\"^#6:string#\n" " ]^#3:Expr.CreateList#\n" ")^#2:Expr.Call#"}, {"'\u00ff' in ['\u00ff', '\u00ff', '\u00ff']", "@in(\n" " \"\u00ff\"^#1:string#,\n" " [\n" " \"\u00ff\"^#4:string#,\n" " \"\u00ff\"^#5:string#,\n" " \"\u00ff\"^#6:string#\n" " ]^#3:Expr.CreateList#\n" ")^#2:Expr.Call#"}, {"'\u00ff' in ['\uffff', '\U00100000', '\U0010ffff']", "@in(\n" " \"\u00ff\"^#1:string#,\n" " [\n" " \"\uffff\"^#4:string#,\n" " \"\U00100000\"^#5:string#,\n" " \"\U0010ffff\"^#6:string#\n" " ]^#3:Expr.CreateList#\n" ")^#2:Expr.Call#"}, {"'\u00ff' in ['\U00100000', '\uffff', '\U0010ffff']", "@in(\n" " \"\u00ff\"^#1:string#,\n" " [\n" " \"\U00100000\"^#4:string#,\n" " \"\uffff\"^#5:string#,\n" " \"\U0010ffff\"^#6:string#\n" " ]^#3:Expr.CreateList#\n" ")^#2:Expr.Call#"}, {"'😁' in ['😁', '😑', '😦']\n" " && in.😁", "", "ERROR: <input>:2:7: Syntax error: extraneous input 'in' expecting {'[', " "'{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | && in.😁\n" " | ......^\n" "ERROR: <input>:2:10: Syntax error: token recognition error at: '😁'\n" " | && in.😁\n" " | .........^\n" "ERROR: <input>:2:11: Syntax error: no viable alternative at input '.'\n" " | && in.😁\n" " | ..........^"}, {"as", "", "ERROR: <input>:1:1: reserved identifier: as\n" " | as\n" " | ^"}, {"break", "", "ERROR: <input>:1:1: reserved identifier: break\n" " | break\n" " | ^"}, {"const", "", "ERROR: <input>:1:1: reserved identifier: const\n" " | const\n" " | ^"}, {"continue", "", "ERROR: <input>:1:1: reserved identifier: continue\n" " | continue\n" " | ^"}, {"else", "", "ERROR: <input>:1:1: reserved identifier: else\n" " | else\n" " | ^"}, {"for", "", "ERROR: <input>:1:1: reserved identifier: for\n" " | for\n" " | ^"}, {"function", "", "ERROR: <input>:1:1: reserved identifier: function\n" " | function\n" " | ^"}, {"if", "", "ERROR: <input>:1:1: reserved identifier: if\n" " | if\n" " | ^"}, {"import", "", "ERROR: <input>:1:1: reserved identifier: import\n" " | import\n" " | ^"}, {"in", "", "ERROR: <input>:1:1: Syntax error: mismatched input 'in' expecting {'[', " "'{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | in\n" " | ^\n" "ERROR: <input>:1:3: Syntax error: mismatched input '<EOF>' expecting " "{'[', " "'{', '(', '.', '-', '!', 'true', 'false', 'null', NUM_FLOAT, NUM_INT, " "NUM_UINT, STRING, BYTES, IDENTIFIER}\n" " | in\n" " | ..^"}, {"let", "", "ERROR: <input>:1:1: reserved identifier: let\n" " | let\n" " | ^"}, {"loop", "", "ERROR: <input>:1:1: reserved identifier: loop\n" " | loop\n" " | ^"}, {"package", "", "ERROR: <input>:1:1: reserved identifier: package\n" " | package\n" " | ^"}, {"namespace", "", "ERROR: <input>:1:1: reserved identifier: namespace\n" " | namespace\n" " | ^"}, {"return", "", "ERROR: <input>:1:1: reserved identifier: return\n" " | return\n" " | ^"}, {"var", "", "ERROR: <input>:1:1: reserved identifier: var\n" " | var\n" " | ^"}, {"void", "", "ERROR: <input>:1:1: reserved identifier: void\n" " | void\n" " | ^"}, {"while", "", "ERROR: <input>:1:1: reserved identifier: while\n" " | while\n" " | ^"}, {"[1, 2, 3].map(var, var * var)", "", "ERROR: <input>:1:15: reserved identifier: var\n" " | [1, 2, 3].map(var, var * var)\n" " | ..............^\n" "ERROR: <input>:1:15: map() variable name must be a simple identifier\n" " | [1, 2, 3].map(var, var * var)\n" " | ..............^\n" "ERROR: <input>:1:20: reserved identifier: var\n" " | [1, 2, 3].map(var, var * var)\n" " | ...................^\n" "ERROR: <input>:1:26: reserved identifier: var\n" " | [1, 2, 3].map(var, var * var)\n" " | .........................^"}, {"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[['too many']]]]]]]]]]]]]]]]]]]]]]]]]]]]" "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" "]]]]]]", "", "Expression recursion limit exceeded. limit: 32", "", "", "", false}, { "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[['just fine'],[1],[2],[3],[4],[5]]]]]]]" "]]]]]]]]]]]]]]]]]]]]]]]]", "", "", "", "", "", false, }, { "[\n\t\r[\n\t\r[\n\t\r]\n\t\r]\n\t\r", "", "ERROR: <input>:6:3: Syntax error: mismatched input '<EOF>' expecting " "{']', ','}\n" " | \r\n" " | ..^", }, {"x.filter(y, y.filter(z, z > 0))", "__comprehension__(\n" " " y,\n" " " x^#1:Expr.Ident#,\n" " " __result__,\n" " " []^#19:Expr.CreateList#,\n" " " true^#20:bool#,\n" " " _?_:_(\n" " __comprehension__(\n" " " z,\n" " " y^#4:Expr.Ident#,\n" " " __result__,\n" " " []^#10:Expr.CreateList#,\n" " " true^#11:bool#,\n" " " _?_:_(\n" " _>_(\n" " z^#7:Expr.Ident#,\n" " 0^#9:int64#\n" " )^#8:Expr.Call#,\n" " _+_(\n" " __result__^#12:Expr.Ident#,\n" " [\n" " z^#6:Expr.Ident#\n" " ]^#13:Expr.CreateList#\n" " )^#14:Expr.Call#,\n" " __result__^#15:Expr.Ident#\n" " )^#16:Expr.Call#,\n" " " __result__^#17:Expr.Ident#)^#18:Expr.Comprehension#,\n" " _+_(\n" " __result__^#21:Expr.Ident#,\n" " [\n" " y^#3:Expr.Ident#\n" " ]^#22:Expr.CreateList#\n" " )^#23:Expr.Call#,\n" " __result__^#24:Expr.Ident#\n" " )^#25:Expr.Call#,\n" " " __result__^#26:Expr.Ident#)^#27:Expr.Comprehension#" "", "", "", "", "x^#1:Expr.Ident#.filter(\n" " y^#3:Expr.Ident#,\n" " ^#18:filter#\n" ")^#27:filter#,\n" "y^#4:Expr.Ident#.filter(\n" " z^#6:Expr.Ident#,\n" " _>_(\n" " z^#7:Expr.Ident#,\n" " 0^#9:int64#\n" " )^#8:Expr.Call#\n" ")^#18:filter"}, {"has(a.b).filter(c, c)", "__comprehension__(\n" " " c,\n" " " a^#2:Expr.Ident#.b~test-only~^#4:Expr.Select#,\n" " " __result__,\n" " " []^#8:Expr.CreateList#,\n" " " true^#9:bool#,\n" " " _?_:_(\n" " c^#7:Expr.Ident#,\n" " _+_(\n" " __result__^#10:Expr.Ident#,\n" " [\n" " c^#6:Expr.Ident#\n" " ]^#11:Expr.CreateList#\n" " )^#12:Expr.Call#,\n" " __result__^#13:Expr.Ident#\n" " )^#14:Expr.Call#,\n" " " __result__^#15:Expr.Ident#)^#16:Expr.Comprehension#", "", "", "", "^#4:has#.filter(\n" " c^#6:Expr.Ident#,\n" " c^#7:Expr.Ident#\n" ")^#16:filter#,\n" "has(\n" " a^#2:Expr.Ident#.b^#3:Expr.Select#\n" ")^#4:has"}, {"x.filter(y, y.exists(z, has(z.a)) && y.exists(z, has(z.b)))", "__comprehension__(\n" " " y,\n" " " x^#1:Expr.Ident#,\n" " " __result__,\n" " " []^#35:Expr.CreateList#,\n" " " true^#36:bool#,\n" " " _?_:_(\n" " _&&_(\n" " __comprehension__(\n" " " z,\n" " " y^#4:Expr.Ident#,\n" " " __result__,\n" " " false^#11:bool#,\n" " " @not_strictly_false(\n" " !_(\n" " __result__^#12:Expr.Ident#\n" " )^#13:Expr.Call#\n" " )^#14:Expr.Call#,\n" " " _||_(\n" " __result__^#15:Expr.Ident#,\n" " z^#8:Expr.Ident#.a~test-only~^#10:Expr.Select#\n" " )^#16:Expr.Call#,\n" " " __result__^#17:Expr.Ident#)^#18:Expr.Comprehension#,\n" " __comprehension__(\n" " " z,\n" " " y^#19:Expr.Ident#,\n" " " __result__,\n" " " false^#26:bool#,\n" " " @not_strictly_false(\n" " !_(\n" " __result__^#27:Expr.Ident#\n" " )^#28:Expr.Call#\n" " )^#29:Expr.Call#,\n" " " _||_(\n" " __result__^#30:Expr.Ident#,\n" " z^#23:Expr.Ident#.b~test-only~^#25:Expr.Select#\n" " )^#31:Expr.Call#,\n" " " __result__^#32:Expr.Ident#)^#33:Expr.Comprehension#\n" " )^#34:Expr.Call#,\n" " _+_(\n" " __result__^#37:Expr.Ident#,\n" " [\n
57
cpp
google/cel-cpp
ast_impl
base/ast_internal/ast_impl.cc
base/ast_internal/ast_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_BASE_AST_INTERNAL_AST_IMPL_H_ #define THIRD_PARTY_CEL_CPP_BASE_AST_INTERNAL_AST_IMPL_H_ #include <cstdint> #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "base/ast.h" #include "base/ast_internal/expr.h" #include "internal/casts.h" namespace cel::ast_internal { class AstImpl : public Ast { public: static AstImpl& CastFromPublicAst(Ast& ast) { return cel::internal::down_cast<AstImpl&>(ast); } static const AstImpl& CastFromPublicAst(const Ast& ast) { return cel::internal::down_cast<const AstImpl&>(ast); } static AstImpl* CastFromPublicAst(Ast* ast) { return cel::internal::down_cast<AstImpl*>(ast); } static const AstImpl* CastFromPublicAst(const Ast* ast) { return cel::internal::down_cast<const AstImpl*>(ast); } AstImpl(const AstImpl& other) = delete; AstImpl& operator=(const AstImpl& other) = delete; AstImpl(AstImpl&& other) = default; AstImpl& operator=(AstImpl&& other) = default; explicit AstImpl(Expr expr, SourceInfo source_info) : root_expr_(std::move(expr)), source_info_(std::move(source_info)), is_checked_(false) {} explicit AstImpl(ParsedExpr expr) : root_expr_(std::move(expr.mutable_expr())), source_info_(std::move(expr.mutable_source_info())), is_checked_(false) {} explicit AstImpl(CheckedExpr expr) : root_expr_(std::move(expr.mutable_expr())), source_info_(std::move(expr.mutable_source_info())), reference_map_(std::move(expr.mutable_reference_map())), type_map_(std::move(expr.mutable_type_map())), expr_version_(std::move(expr.mutable_expr_version())), is_checked_(true) {} bool IsChecked() const override { return is_checked_; } const Expr& root_expr() const { return root_expr_; } Expr& root_expr() { return root_expr_; } const SourceInfo& source_info() const { return source_info_; } SourceInfo& source_info() { return source_info_; } const Type& GetType(int64_t expr_id) const; const Type& GetReturnType() const; const Reference* GetReference(int64_t expr_id) const; const absl::flat_hash_map<int64_t, Reference>& reference_map() const { return reference_map_; } absl::flat_hash_map<int64_t, Reference>& reference_map() { return reference_map_; } const absl::flat_hash_map<int64_t, Type>& type_map() const { return type_map_; } absl::string_view expr_version() const { return expr_version_; } private: Expr root_expr_; SourceInfo source_info_; absl::flat_hash_map<int64_t, Reference> reference_map_; absl::flat_hash_map<int64_t, Type> type_map_; std::string expr_version_; bool is_checked_; }; } #endif #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 "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, ParsedExprCtor) { ParsedExpr parsed_expr; auto& call = parsed_expr.mutable_expr().mutable_call_expr(); parsed_expr.mutable_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); parsed_expr.mutable_source_info().mutable_positions()[5] = 6; AstImpl ast_impl(std::move(parsed_expr)); 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, 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) { CheckedExpr expr; expr.mutable_expr().mutable_ident_expr().set_name("int_value"); expr.mutable_expr().set_id(1); Reference ref; ref.set_name("com.int_value"); expr.mutable_reference_map()[1] = Reference(ref); expr.mutable_type_map()[1] = Type(PrimitiveType::kInt64); expr.mutable_source_info().set_syntax_version("1.0"); AstImpl ast_impl(std::move(expr)); 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"); } TEST(AstImpl, CheckedExprDeepCopy) { CheckedExpr expr; auto& root = expr.mutable_expr(); 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]; expr.mutable_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"); expr.mutable_reference_map()[1] = std::move(ref); expr.mutable_type_map()[1] = Type(PrimitiveType::kInt64); rhs.mutable_const_expr().set_int_value(2); rhs.set_id(2); expr.mutable_type_map()[2] = Type(PrimitiveType::kInt64); expr.mutable_source_info().set_syntax_version("1.0"); AstImpl ast_impl(std::move(expr)); 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"); } } }
58
cpp
google/cel-cpp
unknown_set
base/internal/unknown_set.cc
eval/public/unknown_set_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_UNKNOWN_SET_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_UNKNOWN_SET_H_ #include "base/internal/unknown_set.h" #include "eval/public/unknown_attribute_set.h" #include "eval/public/unknown_function_result_set.h" namespace google { namespace api { namespace expr { namespace runtime { using UnknownSet = ::cel::base_internal::UnknownSet; } } } } #endif #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))); } } } } } }
59
cpp
google/cel-cpp
branch_coverage
tools/branch_coverage.cc
tools/branch_coverage_test.cc
#ifndef THIRD_PARTY_CEL_CPP_TOOLS_BRANCH_COVERAGE_H_ #define THIRD_PARTY_CEL_CPP_TOOLS_BRANCH_COVERAGE_H_ #include <cstdint> #include <memory> #include "google/api/expr/v1alpha1/checked.pb.h" #include "absl/base/attributes.h" #include "common/value.h" #include "eval/public/cel_value.h" #include "tools/navigable_ast.h" namespace cel { class BranchCoverage { public: struct NodeCoverageStats { bool is_boolean; int evaluation_count; int boolean_true_count; int boolean_false_count; int error_count; }; virtual ~BranchCoverage() = default; virtual void Record(int64_t expr_id, const Value& value) = 0; virtual void RecordLegacyValue( int64_t expr_id, const google::api::expr::runtime::CelValue& value) = 0; virtual NodeCoverageStats StatsForNode(int64_t expr_id) const = 0; virtual const NavigableAst& ast() const ABSL_ATTRIBUTE_LIFETIME_BOUND = 0; virtual const google::api::expr::v1alpha1::CheckedExpr& expr() const ABSL_ATTRIBUTE_LIFETIME_BOUND = 0; }; std::unique_ptr<BranchCoverage> CreateBranchCoverage( const google::api::expr::v1alpha1::CheckedExpr& expr); } #endif #include "tools/branch_coverage.h" #include <cstdint> #include <memory> #include "google/api/expr/v1alpha1/checked.pb.h" #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "absl/types/variant.h" #include "common/value.h" #include "eval/internal/interop.h" #include "eval/public/cel_value.h" #include "tools/navigable_ast.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::v1alpha1::Type; using ::google::api::expr::runtime::CelValue; const absl::Status& UnsupportedConversionError() { static absl::NoDestructor<absl::Status> kErr( absl::StatusCode::kInternal, "Conversion to legacy type unsupported."); return *kErr; } struct ConstantNode {}; struct BoolNode { int result_true; int result_false; int result_error; }; struct OtherNode { int result_error; }; struct CoverageNode { int evaluate_count; absl::variant<ConstantNode, OtherNode, BoolNode> kind; }; absl::Nullable<const Type*> FindCheckerType(const CheckedExpr& expr, int64_t expr_id) { if (auto it = expr.type_map().find(expr_id); it != expr.type_map().end()) { return &it->second; } return nullptr; } class BranchCoverageImpl : public BranchCoverage { public: explicit BranchCoverageImpl(const CheckedExpr& expr) : expr_(expr) {} void Record(int64_t expr_id, const Value& value) override { auto value_or = interop_internal::ToLegacyValue(&arena_, value); if (!value_or.ok()) { RecordImpl(expr_id, CelValue::CreateError(&UnsupportedConversionError())); } else { return RecordImpl(expr_id, *value_or); } } void RecordLegacyValue(int64_t expr_id, const CelValue& value) override { return RecordImpl(expr_id, value); } BranchCoverage::NodeCoverageStats StatsForNode( int64_t expr_id) const override; const NavigableAst& ast() const override; const CheckedExpr& expr() const override; void Init(); private: friend class BranchCoverage; void RecordImpl(int64_t expr_id, const CelValue& value); bool InferredBoolType(const AstNode& node) const; CheckedExpr expr_; NavigableAst ast_; mutable absl::Mutex coverage_nodes_mu_; absl::flat_hash_map<int64_t, CoverageNode> coverage_nodes_ ABSL_GUARDED_BY(coverage_nodes_mu_); absl::flat_hash_set<int64_t> unexpected_expr_ids_ ABSL_GUARDED_BY(coverage_nodes_mu_); google::protobuf::Arena arena_; }; BranchCoverage::NodeCoverageStats BranchCoverageImpl::StatsForNode( int64_t expr_id) const { BranchCoverage::NodeCoverageStats stats{ false, 0, 0, 0, 0, }; absl::MutexLock lock(&coverage_nodes_mu_); auto it = coverage_nodes_.find(expr_id); if (it != coverage_nodes_.end()) { const CoverageNode& coverage_node = it->second; stats.evaluation_count = coverage_node.evaluate_count; absl::visit(absl::Overload([&](const ConstantNode& cov) {}, [&](const OtherNode& cov) { stats.error_count = cov.result_error; }, [&](const BoolNode& cov) { stats.is_boolean = true; stats.boolean_true_count = cov.result_true; stats.boolean_false_count = cov.result_false; stats.error_count = cov.result_error; }), coverage_node.kind); return stats; } return stats; } const NavigableAst& BranchCoverageImpl::ast() const { return ast_; } const CheckedExpr& BranchCoverageImpl::expr() const { return expr_; } bool BranchCoverageImpl::InferredBoolType(const AstNode& node) const { int64_t expr_id = node.expr()->id(); const auto* checker_type = FindCheckerType(expr_, expr_id); if (checker_type != nullptr) { return checker_type->has_primitive() && checker_type->primitive() == Type::BOOL; } return false; } void BranchCoverageImpl::Init() ABSL_NO_THREAD_SAFETY_ANALYSIS { ast_ = NavigableAst::Build(expr_.expr()); for (const AstNode& node : ast_.Root().DescendantsPreorder()) { int64_t expr_id = node.expr()->id(); CoverageNode& coverage_node = coverage_nodes_[expr_id]; coverage_node.evaluate_count = 0; if (node.node_kind() == NodeKind::kConstant) { coverage_node.kind = ConstantNode{}; } else if (InferredBoolType(node)) { coverage_node.kind = BoolNode{0, 0, 0}; } else { coverage_node.kind = OtherNode{0}; } } } void BranchCoverageImpl::RecordImpl(int64_t expr_id, const CelValue& value) { absl::MutexLock lock(&coverage_nodes_mu_); auto it = coverage_nodes_.find(expr_id); if (it == coverage_nodes_.end()) { unexpected_expr_ids_.insert(expr_id); it = coverage_nodes_.insert({expr_id, CoverageNode{0, {}}}).first; if (value.IsBool()) { it->second.kind = BoolNode{0, 0, 0}; } } CoverageNode& coverage_node = it->second; coverage_node.evaluate_count++; bool is_error = value.IsError() && value.ErrorOrDie() != &UnsupportedConversionError(); absl::visit(absl::Overload([&](ConstantNode& node) {}, [&](OtherNode& cov) { if (is_error) { cov.result_error++; } }, [&](BoolNode& cov) { if (value.IsBool()) { bool held_value = value.BoolOrDie(); if (held_value) { cov.result_true++; } else { cov.result_false++; } } else if (is_error) { cov.result_error++; } }), coverage_node.kind); } } std::unique_ptr<BranchCoverage> CreateBranchCoverage(const CheckedExpr& expr) { auto result = std::make_unique<BranchCoverageImpl>(expr); result->Init(); return result; } }
#include "tools/branch_coverage.h" #include <cstdint> #include <string> #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/strings/substitute.h" #include "base/builtins.h" #include "base/type_provider.h" #include "common/memory.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_value.h" #include "internal/proto_file_util.h" #include "internal/testing.h" #include "runtime/managed_value_factory.h" #include "tools/navigable_ast.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::cel::internal::test::ReadTextProtoFromFile; using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::RegisterBuiltinFunctions; constexpr char kCoverageExamplePath[] = "tools/testdata/coverage_example.textproto"; const CheckedExpr& TestExpression() { static absl::NoDestructor<CheckedExpr> expression([]() { CheckedExpr value; ABSL_CHECK_OK(ReadTextProtoFromFile(kCoverageExamplePath, value)); return value; }()); return *expression; } std::string FormatNodeStats(const BranchCoverage::NodeCoverageStats& stats) { return absl::Substitute( "is_bool: $0; evaluated: $1; bool_true: $2; bool_false: $3; error: $4", stats.is_boolean, stats.evaluation_count, stats.boolean_true_count, stats.boolean_false_count, stats.error_count); } google::api::expr::runtime::CelEvaluationListener EvaluationListenerForCoverage( BranchCoverage* coverage) { return [coverage](int64_t id, const CelValue& value, google::protobuf::Arena* arena) { coverage->RecordLegacyValue(id, value); return absl::OkStatus(); }; } MATCHER_P(MatchesNodeStats, expected, "") { const BranchCoverage::NodeCoverageStats& actual = arg; *result_listener << "\n"; *result_listener << "Expected: " << FormatNodeStats(expected); *result_listener << "\n"; *result_listener << "Got: " << FormatNodeStats(actual); return actual.is_boolean == expected.is_boolean && actual.evaluation_count == expected.evaluation_count && actual.boolean_true_count == expected.boolean_true_count && actual.boolean_false_count == expected.boolean_false_count && actual.error_count == expected.error_count; } MATCHER(NodeStatsIsBool, "") { const BranchCoverage::NodeCoverageStats& actual = arg; *result_listener << "\n"; *result_listener << "Expected: " << FormatNodeStats({true, 0, 0, 0, 0}); *result_listener << "\n"; *result_listener << "Got: " << FormatNodeStats(actual); return actual.is_boolean == true; } TEST(BranchCoverage, DefaultsForUntrackedId) { auto coverage = CreateBranchCoverage(TestExpression()); using Stats = BranchCoverage::NodeCoverageStats; EXPECT_THAT(coverage->StatsForNode(99), MatchesNodeStats(Stats{false, 0, 0, 0, 0})); } TEST(BranchCoverage, Record) { auto coverage = CreateBranchCoverage(TestExpression()); int64_t root_id = coverage->expr().expr().id(); cel::ManagedValueFactory factory(cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); coverage->Record(root_id, factory.get().CreateBoolValue(false)); using Stats = BranchCoverage::NodeCoverageStats; EXPECT_THAT(coverage->StatsForNode(root_id), MatchesNodeStats(Stats{true, 1, 0, 1, 0})); } TEST(BranchCoverage, RecordUnexpectedId) { auto coverage = CreateBranchCoverage(TestExpression()); int64_t unexpected_id = 99; cel::ManagedValueFactory factory(cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); coverage->Record(unexpected_id, factory.get().CreateBoolValue(false)); using Stats = BranchCoverage::NodeCoverageStats; EXPECT_THAT(coverage->StatsForNode(unexpected_id), MatchesNodeStats(Stats{true, 1, 0, 1, 0})); } TEST(BranchCoverage, IncrementsCounters) { auto coverage = CreateBranchCoverage(TestExpression()); EXPECT_TRUE(static_cast<bool>(coverage->ast())); auto builder = CreateCelExpressionBuilder(); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto program, builder->CreateExpression(&TestExpression())); google::protobuf::Arena arena; Activation activation; activation.InsertValue("bool1", CelValue::CreateBool(false)); activation.InsertValue("bool2", CelValue::CreateBool(false)); activation.InsertValue("int1", CelValue::CreateInt64(42)); activation.InsertValue("int2", CelValue::CreateInt64(43)); activation.InsertValue("int_divisor", CelValue::CreateInt64(4)); activation.InsertValue("ternary_c", CelValue::CreateBool(true)); activation.InsertValue("ternary_t", CelValue::CreateBool(true)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( auto result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == true); using Stats = BranchCoverage::NodeCoverageStats; const NavigableAst& ast = coverage->ast(); auto root_node_stats = coverage->StatsForNode(ast.Root().expr()->id()); EXPECT_THAT(root_node_stats, MatchesNodeStats(Stats{true, 1, 1, 0, 0})); const AstNode* ternary; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kTernary) { ternary = &node; break; } } ASSERT_NE(ternary, nullptr); auto ternary_node_stats = coverage->StatsForNode(ternary->expr()->id()); EXPECT_THAT(ternary_node_stats, NodeStatsIsBool()); const auto* false_node = ternary->children().at(2); auto false_node_stats = coverage->StatsForNode(false_node->expr()->id()); EXPECT_THAT(false_node_stats, MatchesNodeStats(Stats{true, 0, 0, 0, 0})); const AstNode* not_arg_expr; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kNot) { not_arg_expr = node.children().at(0); break; } } ASSERT_NE(not_arg_expr, nullptr); auto not_expr_node_stats = coverage->StatsForNode(not_arg_expr->expr()->id()); EXPECT_THAT(not_expr_node_stats, MatchesNodeStats(Stats{true, 1, 0, 1, 0})); const AstNode* div_expr; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kDivide) { div_expr = &node; break; } } ASSERT_NE(div_expr, nullptr); auto div_expr_stats = coverage->StatsForNode(div_expr->expr()->id()); EXPECT_THAT(div_expr_stats, MatchesNodeStats(Stats{false, 1, 0, 0, 0})); } TEST(BranchCoverage, AccumulatesAcrossRuns) { auto coverage = CreateBranchCoverage(TestExpression()); EXPECT_TRUE(static_cast<bool>(coverage->ast())); auto builder = CreateCelExpressionBuilder(); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto program, builder->CreateExpression(&TestExpression())); google::protobuf::Arena arena; Activation activation; activation.InsertValue("bool1", CelValue::CreateBool(false)); activation.InsertValue("bool2", CelValue::CreateBool(false)); activation.InsertValue("int1", CelValue::CreateInt64(42)); activation.InsertValue("int2", CelValue::CreateInt64(43)); activation.InsertValue("int_divisor", CelValue::CreateInt64(4)); activation.InsertValue("ternary_c", CelValue::CreateBool(true)); activation.InsertValue("ternary_t", CelValue::CreateBool(true)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( auto result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == true); activation.RemoveValueEntry("ternary_c"); activation.RemoveValueEntry("ternary_f"); activation.InsertValue("ternary_c", CelValue::CreateBool(false)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == false) << result.DebugString(); using Stats = BranchCoverage::NodeCoverageStats; const NavigableAst& ast = coverage->ast(); auto root_node_stats = coverage->StatsForNode(ast.Root().expr()->id()); EXPECT_THAT(root_node_stats, MatchesNodeStats(Stats{true, 2, 1, 1, 0})); const AstNode* ternary; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kTernary) { ternary = &node; break; } } ASSERT_NE(ternary, nullptr); auto ternary_node_stats = coverage->StatsForNode(ternary->expr()->id()); EXPECT_THAT(ternary_node_stats, NodeStatsIsBool()); const auto* false_node = ternary->children().at(2); auto false_node_stats = coverage->StatsForNode(false_node->expr()->id()); EXPECT_THAT(false_node_stats, MatchesNodeStats(Stats{true, 1, 0, 1, 0})); } TEST(BranchCoverage, CountsErrors) { auto coverage = CreateBranchCoverage(TestExpression()); EXPECT_TRUE(static_cast<bool>(coverage->ast())); auto builder = CreateCelExpressionBuilder(); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto program, builder->CreateExpression(&TestExpression())); google::protobuf::Arena arena; Activation activation; activation.InsertValue("bool1", CelValue::CreateBool(false)); activation.InsertValue("bool2", CelValue::CreateBool(false)); activation.InsertValue("int1", CelValue::CreateInt64(42)); activation.InsertValue("int2", CelValue::CreateInt64(43)); activation.InsertValue("int_divisor", CelValue::CreateInt64(0)); activation.InsertValue("ternary_c", CelValue::CreateBool(true)); activation.InsertValue("ternary_t", CelValue::CreateBool(false)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( auto result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == false); using Stats = BranchCoverage::NodeCoverageStats; const NavigableAst& ast = coverage->ast(); auto root_node_stats = coverage->StatsForNode(ast.Root().expr()->id()); EXPECT_THAT(root_node_stats, MatchesNodeStats(Stats{true, 1, 0, 1, 0})); const AstNode* ternary; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kTernary) { ternary = &node; break; } } const AstNode* div_expr; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kDivide) { div_expr = &node; break; } } ASSERT_NE(div_expr, nullptr); auto div_expr_stats = coverage->StatsForNode(div_expr->expr()->id()); EXPECT_THAT(div_expr_stats, MatchesNodeStats(Stats{false, 1, 0, 0, 1})); } } }
60
cpp
google/cel-cpp
flatbuffers_backed_impl
tools/flatbuffers_backed_impl.cc
tools/flatbuffers_backed_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_TOOLS_FLATBUFFERS_BACKED_IMPL_H_ #define THIRD_PARTY_CEL_CPP_TOOLS_FLATBUFFERS_BACKED_IMPL_H_ #include "eval/public/cel_value.h" #include "flatbuffers/reflection.h" namespace google { namespace api { namespace expr { namespace runtime { class FlatBuffersMapImpl : public CelMap { public: FlatBuffersMapImpl(const flatbuffers::Table& table, const reflection::Schema& schema, const reflection::Object& object, google::protobuf::Arena* arena) : arena_(arena), table_(table), schema_(schema) { keys_.fields = object.fields(); } int size() const override { return keys_.fields->size(); } absl::StatusOr<bool> Has(const CelValue& key) const override; absl::optional<CelValue> operator[](CelValue cel_key) const override; using CelMap::ListKeys; absl::StatusOr<const CelList*> ListKeys() const override { return &keys_; } private: struct FieldList : public CelList { int size() const override { return fields->size(); } CelValue operator[](int index) const override { auto name = fields->Get(index)->name(); return CelValue::CreateStringView( absl::string_view(name->c_str(), name->size())); } const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>>* fields; }; FieldList keys_; google::protobuf::Arena* arena_; const flatbuffers::Table& table_; const reflection::Schema& schema_; }; const CelMap* CreateFlatBuffersBackedObject(const uint8_t* flatbuf, const reflection::Schema& schema, google::protobuf::Arena* arena); } } } } #endif #include "tools/flatbuffers_backed_impl.h" #include <algorithm> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/optional.h" #include "eval/public/cel_value.h" #include "flatbuffers/flatbuffers.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { CelValue CreateValue(int64_t value) { return CelValue::CreateInt64(value); } CelValue CreateValue(uint64_t value) { return CelValue::CreateUint64(value); } CelValue CreateValue(double value) { return CelValue::CreateDouble(value); } CelValue CreateValue(bool value) { return CelValue::CreateBool(value); } template <typename T, typename U> class FlatBuffersListImpl : public CelList { public: FlatBuffersListImpl(const flatbuffers::Table& table, const reflection::Field& field) : list_(table.GetPointer<const flatbuffers::Vector<T>*>(field.offset())) { } int size() const override { return list_ ? list_->size() : 0; } CelValue operator[](int index) const override { return CreateValue(static_cast<U>(list_->Get(index))); } private: const flatbuffers::Vector<T>* list_; }; class StringListImpl : public CelList { public: explicit StringListImpl( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>* list) : list_(list) {} int size() const override { return list_ ? list_->size() : 0; } CelValue operator[](int index) const override { auto value = list_->Get(index); return CelValue::CreateStringView( absl::string_view(value->c_str(), value->size())); } private: const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>* list_; }; class ObjectListImpl : public CelList { public: ObjectListImpl( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list, const reflection::Schema& schema, const reflection::Object& object, google::protobuf::Arena* arena) : arena_(arena), list_(list), schema_(schema), object_(object) {} int size() const override { return list_ ? list_->size() : 0; } CelValue operator[](int index) const override { auto value = list_->Get(index); return CelValue::CreateMap(google::protobuf::Arena::Create<FlatBuffersMapImpl>( arena_, *value, schema_, object_, arena_)); } private: google::protobuf::Arena* arena_; const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list_; const reflection::Schema& schema_; const reflection::Object& object_; }; class ObjectStringIndexedMapImpl : public CelMap { public: ObjectStringIndexedMapImpl( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list, const reflection::Schema& schema, const reflection::Object& object, const reflection::Field& index, google::protobuf::Arena* arena) : arena_(arena), list_(list), schema_(schema), object_(object), index_(index) { keys_.parent = this; } int size() const override { return list_ ? list_->size() : 0; } absl::StatusOr<bool> Has(const CelValue& key) const override { auto lookup_result = (*this)[key]; if (!lookup_result.has_value()) { return false; } auto result = *lookup_result; if (result.IsError()) { return *(result.ErrorOrDie()); } return true; } absl::optional<CelValue> operator[](CelValue cel_key) const override { if (!cel_key.IsString()) { return CreateErrorValue( arena_, absl::InvalidArgumentError( absl::StrCat("Invalid map key type: '", CelValue::TypeName(cel_key.type()), "'"))); } const absl::string_view key = cel_key.StringOrDie().value(); const auto it = std::lower_bound( list_->begin(), list_->end(), key, [this](const flatbuffers::Table* t, const absl::string_view key) { auto value = flatbuffers::GetFieldS(*t, index_); auto sv = value ? absl::string_view(value->c_str(), value->size()) : absl::string_view(); return sv < key; }); if (it != list_->end()) { auto value = flatbuffers::GetFieldS(**it, index_); auto sv = value ? absl::string_view(value->c_str(), value->size()) : absl::string_view(); if (sv == key) { return CelValue::CreateMap(google::protobuf::Arena::Create<FlatBuffersMapImpl>( arena_, **it, schema_, object_, arena_)); } } return absl::nullopt; } absl::StatusOr<const CelList*> ListKeys() const override { return &keys_; } private: struct KeyList : public CelList { int size() const override { return parent->size(); } CelValue operator[](int index) const override { auto value = flatbuffers::GetFieldS(*(parent->list_->Get(index)), parent->index_); if (value == nullptr) { return CelValue::CreateStringView(absl::string_view()); } return CelValue::CreateStringView( absl::string_view(value->c_str(), value->size())); } ObjectStringIndexedMapImpl* parent; }; google::protobuf::Arena* arena_; const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list_; const reflection::Schema& schema_; const reflection::Object& object_; const reflection::Field& index_; KeyList keys_; }; const reflection::Field* findStringKeyField(const reflection::Object& object) { for (const auto field : *object.fields()) { if (field->key() && field->type()->base_type() == reflection::String) { return field; } } return nullptr; } } absl::StatusOr<bool> FlatBuffersMapImpl::Has(const CelValue& key) const { auto lookup_result = (*this)[key]; if (!lookup_result.has_value()) { return false; } auto result = *lookup_result; if (result.IsError()) { return *(result.ErrorOrDie()); } return true; } absl::optional<CelValue> FlatBuffersMapImpl::operator[]( CelValue cel_key) const { if (!cel_key.IsString()) { return CreateErrorValue( arena_, absl::InvalidArgumentError( absl::StrCat("Invalid map key type: '", CelValue::TypeName(cel_key.type()), "'"))); } auto field = keys_.fields->LookupByKey(cel_key.StringOrDie().value().data()); if (field == nullptr) { return absl::nullopt; } switch (field->type()->base_type()) { case reflection::Byte: return CelValue::CreateInt64( flatbuffers::GetFieldI<int8_t>(table_, *field)); case reflection::Short: return CelValue::CreateInt64( flatbuffers::GetFieldI<int16_t>(table_, *field)); case reflection::Int: return CelValue::CreateInt64( flatbuffers::GetFieldI<int32_t>(table_, *field)); case reflection::Long: return CelValue::CreateInt64( flatbuffers::GetFieldI<int64_t>(table_, *field)); case reflection::UByte: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint8_t>(table_, *field)); case reflection::UShort: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint16_t>(table_, *field)); case reflection::UInt: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint32_t>(table_, *field)); case reflection::ULong: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint64_t>(table_, *field)); case reflection::Float: return CelValue::CreateDouble( flatbuffers::GetFieldF<float>(table_, *field)); case reflection::Double: return CelValue::CreateDouble( flatbuffers::GetFieldF<double>(table_, *field)); case reflection::Bool: return CelValue::CreateBool( flatbuffers::GetFieldI<int8_t>(table_, *field)); case reflection::String: { auto value = flatbuffers::GetFieldS(table_, *field); if (value == nullptr) { return CelValue::CreateStringView(absl::string_view()); } return CelValue::CreateStringView( absl::string_view(value->c_str(), value->size())); } case reflection::Obj: { const auto* field_schema = schema_.objects()->Get(field->type()->index()); const auto* field_table = flatbuffers::GetFieldT(table_, *field); if (field_table == nullptr) { return CelValue::CreateNull(); } if (field_schema) { return CelValue::CreateMap(google::protobuf::Arena::Create<FlatBuffersMapImpl>( arena_, *field_table, schema_, *field_schema, arena_)); } break; } case reflection::Vector: { switch (field->type()->element()) { case reflection::Byte: case reflection::UByte: { const auto* field_table = flatbuffers::GetFieldAnyV(table_, *field); if (field_table == nullptr) { return CelValue::CreateBytesView(absl::string_view()); } return CelValue::CreateBytesView(absl::string_view( reinterpret_cast<const char*>(field_table->Data()), field_table->size())); } case reflection::Short: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<int16_t, int64_t>>( arena_, table_, *field)); case reflection::Int: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<int32_t, int64_t>>( arena_, table_, *field)); case reflection::Long: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<int64_t, int64_t>>( arena_, table_, *field)); case reflection::UShort: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint16_t, uint64_t>>( arena_, table_, *field)); case reflection::UInt: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint32_t, uint64_t>>( arena_, table_, *field)); case reflection::ULong: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint64_t, uint64_t>>( arena_, table_, *field)); case reflection::Float: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<float, double>>( arena_, table_, *field)); case reflection::Double: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<double, double>>( arena_, table_, *field)); case reflection::Bool: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint8_t, bool>>( arena_, table_, *field)); case reflection::String: return CelValue::CreateList(google::protobuf::Arena::Create<StringListImpl>( arena_, table_.GetPointer<const flatbuffers::Vector< flatbuffers::Offset<flatbuffers::String>>*>( field->offset()))); case reflection::Obj: { const auto* field_schema = schema_.objects()->Get(field->type()->index()); if (field_schema) { const auto* index = findStringKeyField(*field_schema); if (index) { return CelValue::CreateMap( google::protobuf::Arena::Create<ObjectStringIndexedMapImpl>( arena_, table_.GetPointer<const flatbuffers::Vector< flatbuffers::Offset<flatbuffers::Table>>*>( field->offset()), schema_, *field_schema, *index, arena_)); } else { return CelValue::CreateList(google::protobuf::Arena::Create<ObjectListImpl>( arena_, table_.GetPointer<const flatbuffers::Vector< flatbuffers::Offset<flatbuffers::Table>>*>( field->offset()), schema_, *field_schema, arena_)); } } break; } default: return absl::nullopt; } break; } default: return absl::nullopt; } return absl::nullopt; } const CelMap* CreateFlatBuffersBackedObject(const uint8_t* flatbuf, const reflection::Schema& schema, google::protobuf::Arena* arena) { return google::protobuf::Arena::Create<const FlatBuffersMapImpl>( arena, *flatbuffers::GetAnyRoot(flatbuf), schema, *schema.root_table(), arena); } } } } }
#include "tools/flatbuffers_backed_impl.h" #include <string> #include "internal/status_macros.h" #include "internal/testing.h" #include "flatbuffers/idl.h" #include "flatbuffers/reflection.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { constexpr char kReflectionBufferPath[] = "tools/testdata/" "flatbuffers.bfbs"; constexpr absl::string_view kByteField = "f_byte"; constexpr absl::string_view kUbyteField = "f_ubyte"; constexpr absl::string_view kShortField = "f_short"; constexpr absl::string_view kUshortField = "f_ushort"; constexpr absl::string_view kIntField = "f_int"; constexpr absl::string_view kUintField = "f_uint"; constexpr absl::string_view kLongField = "f_long"; constexpr absl::string_view kUlongField = "f_ulong"; constexpr absl::string_view kFloatField = "f_float"; constexpr absl::string_view kDoubleField = "f_double"; constexpr absl::string_view kBoolField = "f_bool"; constexpr absl::string_view kStringField = "f_string"; constexpr absl::string_view kObjField = "f_obj"; constexpr absl::string_view kUnknownField = "f_unknown"; constexpr absl::string_view kBytesField = "r_byte"; constexpr absl::string_view kUbytesField = "r_ubyte"; constexpr absl::string_view kShortsField = "r_short"; constexpr absl::string_view kUshortsField = "r_ushort"; constexpr absl::string_view kIntsField = "r_int"; constexpr absl::string_view kUintsField = "r_uint"; constexpr absl::string_view kLongsField = "r_long"; constexpr absl::string_view kUlongsField = "r_ulong"; constexpr absl::string_view kFloatsField = "r_float"; constexpr absl::string_view kDoublesField = "r_double"; constexpr absl::string_view kBoolsField = "r_bool"; constexpr absl::string_view kStringsField = "r_string"; constexpr absl::string_view kObjsField = "r_obj"; constexpr absl::string_view kIndexedField = "r_indexed"; const int64_t kNumFields = 27; class FlatBuffersTest : public testing::Test { public: FlatBuffersTest() { EXPECT_TRUE( flatbuffers::LoadFile(kReflectionBufferPath, true, &schema_file_)); flatbuffers::Verifier verifier( reinterpret_cast<const uint8_t*>(schema_file_.data()), schema_file_.size()); EXPECT_TRUE(reflection::VerifySchemaBuffer(verifier)); EXPECT_TRUE(parser_.Deserialize( reinterpret_cast<const uint8_t*>(schema_file_.data()), schema_file_.size())); schema_ = reflection::GetSchema(schema_file_.data()); } const CelMap& loadJson(std::string data) { EXPECT_TRUE(parser_.Parse(data.data())); const CelMap* value = CreateFlatBuffersBackedObject( parser_.builder_.GetBufferPointer(), *schema_, &arena_); EXPECT_NE(nullptr, value); EXPECT_EQ(kNumFields, value->size()); const CelList* keys = value->ListKeys().value(); EXPECT_NE(nullptr, keys); EXPECT_EQ(kNumFields, keys->size()); EXPECT_TRUE((*keys)[2].IsString()); return *value; } protected: std::string schema_file_; flatbuffers::Parser parser_; const reflection::Schema* schema_; google::protobuf::Arena arena_; }; TEST_F(FlatBuffersTest, PrimitiveFields) { const CelMap& value = loadJson(R"({ f_byte: -1, f_ubyte: 1, f_short: -2, f_ushort: 2, f_int: -3, f_uint: 3, f_long: -4, f_ulong: 4, f_float: 5.0, f_double: 6.0, f_bool: false, f_string: "test" })"); { auto f = value[CelValue::CreateStringView(kByteField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-1, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUbyteField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(1, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kShortField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-2, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUshortField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(2, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kIntField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-3, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUintField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(3, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kLongField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-4, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUlongField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(4, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kFloatField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsDouble()); EXPECT_EQ(5.0, f->DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kDoubleField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsDouble()); EXPECT_EQ(6.0, f->DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kBoolField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBool()); EXPECT_EQ(false, f->BoolOrDie()); } { auto f = value[CelValue::CreateStringView(kStringField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsString()); EXPECT_EQ("test", f->StringOrDie().value()); } { CelValue bad_field = CelValue::CreateInt64(1); auto f = value[bad_field]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsError()); auto presence = value.Has(bad_field); EXPECT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); } { auto f = value[CelValue::CreateStringView(kUnknownField)]; EXPECT_FALSE(f.has_value()); } } TEST_F(FlatBuffersTest, PrimitiveFieldDefaults) { const CelMap& value = loadJson("{}"); { auto f = value[CelValue::CreateStringView(kByteField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(0, f->Int64OrDie()); } { auto f = value[CelValue::CreateStringView(kShortField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(150, f->Int64OrDie()); } { auto f = value[CelValue::CreateStringView(kBoolField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBool()); EXPECT_EQ(true, f->BoolOrDie()); } { auto f = value[CelValue::CreateStringView(kStringField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsString()); EXPECT_EQ("", f->StringOrDie().value()); } } TEST_F(FlatBuffersTest, ObjectField) { const CelMap& value = loadJson(R"({ f_obj: { f_string: "entry", f_int: 16 } })"); CelValue field = CelValue::CreateStringView(kObjField); auto presence = value.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto f = value[field]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(2, m.size()); { auto obj_field = CelValue::CreateStringView(kStringField); auto member_presence = m.Has(obj_field); EXPECT_OK(member_presence); EXPECT_TRUE(*member_presence); auto mf = m[obj_field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsString()); EXPECT_EQ("entry", mf->StringOrDie().value()); } { auto obj_field = CelValue::CreateStringView(kIntField); auto member_presence = m.Has(obj_field); EXPECT_OK(member_presence); EXPECT_TRUE(*member_presence); auto mf = m[obj_field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsInt64()); EXPECT_EQ(16, mf->Int64OrDie()); } { std::string undefined = "f_undefined"; CelValue undefined_field = CelValue::CreateStringView(undefined); auto presence = m.Has(undefined_field); EXPECT_OK(presence); EXPECT_FALSE(*presence); auto v = m[undefined_field]; EXPECT_FALSE(v.has_value()); presence = m.Has(CelValue::CreateBool(false)); EXPECT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); } } TEST_F(FlatBuffersTest, ObjectFieldDefault) { const CelMap& value = loadJson("{}"); auto f = value[CelValue::CreateStringView(kObjField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsNull()); } TEST_F(FlatBuffersTest, PrimitiveVectorFields) { const CelMap& value = loadJson(R"({ r_byte: [-97], r_ubyte: [97, 98, 99], r_short: [-2], r_ushort: [2], r_int: [-3], r_uint: [3], r_long: [-4], r_ulong: [4], r_float: [5.0], r_double: [6.0], r_bool: [false], r_string: ["test"] })"); { auto f = value[CelValue::CreateStringView(kBytesField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBytes()); EXPECT_EQ("\x9F", f->BytesOrDie().value()); } { auto uf = value[CelValue::CreateStringView(kUbytesField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsBytes()); EXPECT_EQ("abc", uf->BytesOrDie().value()); } { auto f = value[CelValue::CreateStringView(kShortsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(-2, l[0].Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUshortsField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsList()); const CelList& l = *uf->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(2, l[0].Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kIntsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(-3, l[0].Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUintsField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsList()); const CelList& l = *uf->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(3, l[0].Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kLongsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(-4, l[0].Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUlongsField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsList()); const CelList& l = *uf->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(4, l[0].Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kFloatsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(5.0, l[0].DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kDoublesField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(6.0, l[0].DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kBoolsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(false, l[0].BoolOrDie()); } { auto f = value[CelValue::CreateStringView(kStringsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ("test", l[0].StringOrDie().value()); } } TEST_F(FlatBuffersTest, ObjectVectorField) { const CelMap& value = loadJson(R"({ r_obj: [{ f_string: "entry", f_int: 16 },{ f_int: 32 }] })"); auto f = value[CelValue::CreateStringView(kObjsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(2, l.size()); { EXPECT_TRUE(l[0].IsMap()); const CelMap& m = *l[0].MapOrDie(); EXPECT_EQ(2, m.size()); { CelValue field = CelValue::CreateStringView(kStringField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsString()); EXPECT_EQ("entry", mf->StringOrDie().value()); } { CelValue field = CelValue::CreateStringView(kIntField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsInt64()); EXPECT_EQ(16, mf->Int64OrDie()); } } { EXPECT_TRUE(l[1].IsMap()); const CelMap& m = *l[1].MapOrDie(); EXPECT_EQ(2, m.size()); { CelValue field = CelValue::CreateStringView(kStringField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsString()); EXPECT_EQ("", mf->StringOrDie().value()); } { CelValue field = CelValue::CreateStringView(kIntField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsInt64()); EXPECT_EQ(32, mf->Int64OrDie()); } { std::string undefined = "f_undefined"; CelValue field = CelValue::CreateStringView(undefined); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_FALSE(*presence); auto mf = m[field]; EXPECT_FALSE(mf.has_value()); } } } TEST_F(FlatBuffersTest, VectorFieldDefaults) { const CelMap& value = loadJson("{}"); for (const auto field : std::vector<absl::string_view>{ kIntsField, kBoolsField, kStringsField, kObjsField}) { auto f = value[CelValue::CreateStringView(field)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(0, l.size()); } { auto f = value[CelValue::CreateStringView(kIndexedField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(0, m.size()); EXPECT_EQ(0, (*m.ListKeys())->size()); } { auto f = value[CelValue::CreateStringView(kBytesField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBytes()); EXPECT_EQ("", f->BytesOrDie().value()); } } TEST_F(FlatBuffersTest, IndexedObjectVectorField) { const CelMap& value = loadJson(R"({ r_indexed: [ { f_string: "a", f_int: 16 }, { f_string: "b", f_int: 32 }, { f_string: "c", f_int: 64 }, { f_string: "d", f_int: 128 } ] })"); auto f = value[CelValue::CreateStringView(kIndexedField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(4, m.size()); const CelList& l = *m.ListKeys().value(); EXPECT_EQ(4, l.size()); EXPECT_TRUE(l[0].IsString()); EXPECT_TRUE(l[1].IsString()); EXPECT_TRUE(l[2].IsString()); EXPECT_TRUE(l[3].IsString()); std::string a = "a"; std::string b = "b"; std::string c = "c"; std::string d = "d"; EXPECT_EQ(a, l[0].StringOrDie().value()); EXPECT_EQ(b, l[1].StringOrDie().value()); EXPECT_EQ(c, l[2].StringOrDie().value()); EXPECT_EQ(d, l[3].StringOrDie().value()); for (const std::string& key : std::vector<std::string>{a, b, c, d}) { auto v = m[CelValue::CreateString(&key)]; EXPECT_TRUE(v.has_value()); const CelMap& vm = *v->MapOrDie(); EXPECT_EQ(2, vm.size()); auto vf = vm[CelValue::CreateStringView(kStringField)]; EXPECT_TRUE(vf.has_value()); EXPECT_TRUE(vf->IsString()); EXPECT_EQ(key, vf->StringOrDie().value()); auto vi = vm[CelValue::CreateStringView(kIntField)]; EXPECT_TRUE(vi.has_value()); EXPECT_TRUE(vi->IsInt64()); } { std::string bb = "bb"; std::string dd = "dd"; EXPECT_FALSE(m[CelValue::CreateString(&bb)].has_value()); EXPECT_FALSE(m[CelValue::CreateString(&dd)].has_value()); EXPECT_FALSE( m[CelValue::CreateStringView(absl::string_view())].has_value()); } } TEST_F(FlatBuffersTest, IndexedObjectVectorFieldDefaults) { const CelMap& value = loadJson(R"({ r_indexed: [ { f_string: "", f_int: 16 } ] })"); CelValue field = CelValue::CreateStringView(kIndexedField); auto presence = value.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto f = value[field]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(1, m.size()); const CelList& l = *m.ListKeys().value(); EXPECT_EQ(1, l.size()); EXPECT_TRUE(l[0].IsString()); EXPECT_EQ("", l[0].StringOrDie().value()); CelValue map_field = CelValue::CreateStringView(absl::string_view()); presence = m.Has(map_field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto v = m[map_field]; EXPECT_TRUE(v.has_value()); std::string undefined = "f_undefined"; CelValue undefined_field = CelValue::CreateStringView(undefined); presence = m.Has(undefined_field); EXPECT_OK(presence); EXPECT_FALSE(*presence); v = m[undefined_field]; EXPECT_FALSE(v.has_value()); presence = m.Has(CelValue::CreateBool(false)); EXPECT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); } } } } } }
61
cpp
google/cel-cpp
navigable_ast
tools/navigable_ast.cc
tools/navigable_ast_test.cc
#ifndef THIRD_PARTY_CEL_CPP_TOOLS_NAVIGABLE_AST_H_ #define THIRD_PARTY_CEL_CPP_TOOLS_NAVIGABLE_AST_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/types/span.h" #include "tools/internal/navigable_ast_internal.h" namespace cel { enum class ChildKind { kUnspecified, kSelectOperand, kCallReceiver, kCallArg, kListElem, kMapKey, kMapValue, kStructValue, kComprehensionRange, kComprehensionInit, kComprehensionCondition, kComprehensionLoopStep, kComprensionResult }; enum class NodeKind { kUnspecified, kConstant, kIdent, kSelect, kCall, kList, kMap, kStruct, kComprehension, }; std::string ChildKindName(ChildKind kind); template <typename Sink> void AbslStringify(Sink& sink, ChildKind kind) { absl::Format(&sink, "%s", ChildKindName(kind)); } std::string NodeKindName(NodeKind kind); template <typename Sink> void AbslStringify(Sink& sink, NodeKind kind) { absl::Format(&sink, "%s", NodeKindName(kind)); } class AstNode; namespace tools_internal { struct AstMetadata; struct AstNodeData { AstNode* parent; const ::google::api::expr::v1alpha1::Expr* expr; ChildKind parent_relation; NodeKind node_kind; const AstMetadata* metadata; size_t index; size_t weight; std::vector<AstNode*> children; }; struct AstMetadata { std::vector<std::unique_ptr<AstNode>> nodes; std::vector<const AstNode*> postorder; absl::flat_hash_map<int64_t, size_t> id_to_node; absl::flat_hash_map<const google::api::expr::v1alpha1::Expr*, size_t> expr_to_node; AstNodeData& NodeDataAt(size_t index); size_t AddNode(); }; struct PostorderTraits { using UnderlyingType = const AstNode*; static const AstNode& Adapt(const AstNode* const node) { return *node; } }; struct PreorderTraits { using UnderlyingType = std::unique_ptr<AstNode>; static const AstNode& Adapt(const std::unique_ptr<AstNode>& node) { return *node; } }; } class AstNode { private: using PreorderRange = tools_internal::SpanRange<tools_internal::PreorderTraits>; using PostorderRange = tools_internal::SpanRange<tools_internal::PostorderTraits>; public: absl::Nullable<const AstNode*> parent() const { return data_.parent; } absl::Nonnull<const google::api::expr::v1alpha1::Expr*> expr() const { return data_.expr; } int child_index() const; ChildKind parent_relation() const { return data_.parent_relation; } NodeKind node_kind() const { return data_.node_kind; } absl::Span<const AstNode* const> children() const { return absl::MakeConstSpan(data_.children); } PreorderRange DescendantsPreorder() const; PostorderRange DescendantsPostorder() const; private: friend struct tools_internal::AstMetadata; AstNode() = default; AstNode(const AstNode&) = delete; AstNode& operator=(const AstNode&) = delete; tools_internal::AstNodeData data_; }; class NavigableAst { public: static NavigableAst Build(const google::api::expr::v1alpha1::Expr& expr); NavigableAst() = default; NavigableAst(const NavigableAst&) = delete; NavigableAst& operator=(const NavigableAst&) = delete; NavigableAst(NavigableAst&&) = default; NavigableAst& operator=(NavigableAst&&) = default; absl::Nullable<const AstNode*> FindId(int64_t id) const { auto it = metadata_->id_to_node.find(id); if (it == metadata_->id_to_node.end()) { return nullptr; } return metadata_->nodes[it->second].get(); } absl::Nullable<const AstNode*> FindExpr( const google::api::expr::v1alpha1::Expr* expr) const { auto it = metadata_->expr_to_node.find(expr); if (it == metadata_->expr_to_node.end()) { return nullptr; } return metadata_->nodes[it->second].get(); } const AstNode& Root() const { return *metadata_->nodes[0]; } bool IdsAreUnique() const { return metadata_->id_to_node.size() == metadata_->nodes.size(); } bool operator==(const NavigableAst& other) const { return metadata_ == other.metadata_; } bool operator!=(const NavigableAst& other) const { return metadata_ != other.metadata_; } explicit operator bool() const { return metadata_ != nullptr; } private: explicit NavigableAst(std::unique_ptr<tools_internal::AstMetadata> metadata) : metadata_(std::move(metadata)) {} std::unique_ptr<tools_internal::AstMetadata> metadata_; }; } #endif #include "tools/navigable_ast.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/checked.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "eval/public/ast_traverse.h" #include "eval/public/ast_visitor.h" #include "eval/public/ast_visitor_base.h" #include "eval/public/source_position.h" namespace cel { namespace tools_internal { AstNodeData& AstMetadata::NodeDataAt(size_t index) { ABSL_CHECK(index < nodes.size()); return nodes[index]->data_; } size_t AstMetadata::AddNode() { size_t index = nodes.size(); nodes.push_back(absl::WrapUnique(new AstNode())); return index; } } namespace { using google::api::expr::v1alpha1::Expr; using google::api::expr::runtime::AstTraverse; using google::api::expr::runtime::SourcePosition; NodeKind GetNodeKind(const Expr& expr) { switch (expr.expr_kind_case()) { case Expr::kConstExpr: return NodeKind::kConstant; case Expr::kIdentExpr: return NodeKind::kIdent; case Expr::kSelectExpr: return NodeKind::kSelect; case Expr::kCallExpr: return NodeKind::kCall; case Expr::kListExpr: return NodeKind::kList; case Expr::kStructExpr: if (!expr.struct_expr().message_name().empty()) { return NodeKind::kStruct; } else { return NodeKind::kMap; } case Expr::kComprehensionExpr: return NodeKind::kComprehension; case Expr::EXPR_KIND_NOT_SET: default: return NodeKind::kUnspecified; } } ChildKind GetChildKind(const tools_internal::AstNodeData& parent_node, size_t child_index) { constexpr size_t kComprehensionRangeArgIndex = google::api::expr::runtime::ITER_RANGE; constexpr size_t kComprehensionInitArgIndex = google::api::expr::runtime::ACCU_INIT; constexpr size_t kComprehensionConditionArgIndex = google::api::expr::runtime::LOOP_CONDITION; constexpr size_t kComprehensionLoopStepArgIndex = google::api::expr::runtime::LOOP_STEP; constexpr size_t kComprehensionResultArgIndex = google::api::expr::runtime::RESULT; switch (parent_node.node_kind) { case NodeKind::kStruct: return ChildKind::kStructValue; case NodeKind::kMap: if (child_index % 2 == 0) { return ChildKind::kMapKey; } return ChildKind::kMapValue; case NodeKind::kList: return ChildKind::kListElem; case NodeKind::kSelect: return ChildKind::kSelectOperand; case NodeKind::kCall: if (child_index == 0 && parent_node.expr->call_expr().has_target()) { return ChildKind::kCallReceiver; } return ChildKind::kCallArg; case NodeKind::kComprehension: switch (child_index) { case kComprehensionRangeArgIndex: return ChildKind::kComprehensionRange; case kComprehensionInitArgIndex: return ChildKind::kComprehensionInit; case kComprehensionConditionArgIndex: return ChildKind::kComprehensionCondition; case kComprehensionLoopStepArgIndex: return ChildKind::kComprehensionLoopStep; case kComprehensionResultArgIndex: return ChildKind::kComprensionResult; default: return ChildKind::kUnspecified; } default: return ChildKind::kUnspecified; } } class NavigableExprBuilderVisitor : public google::api::expr::runtime::AstVisitorBase { public: NavigableExprBuilderVisitor() : metadata_(std::make_unique<tools_internal::AstMetadata>()) {} void PreVisitExpr(const Expr* expr, const SourcePosition* position) override { AstNode* parent = parent_stack_.empty() ? nullptr : metadata_->nodes[parent_stack_.back()].get(); size_t index = metadata_->AddNode(); tools_internal::AstNodeData& node_data = metadata_->NodeDataAt(index); node_data.parent = parent; node_data.expr = expr; node_data.parent_relation = ChildKind::kUnspecified; node_data.node_kind = GetNodeKind(*expr); node_data.weight = 1; node_data.index = index; node_data.metadata = metadata_.get(); metadata_->id_to_node.insert({expr->id(), index}); metadata_->expr_to_node.insert({expr, index}); if (!parent_stack_.empty()) { auto& parent_node_data = metadata_->NodeDataAt(parent_stack_.back()); size_t child_index = parent_node_data.children.size(); parent_node_data.children.push_back(metadata_->nodes[index].get()); node_data.parent_relation = GetChildKind(parent_node_data, child_index); } parent_stack_.push_back(index); } void PostVisitExpr(const Expr* expr, const SourcePosition* position) override { size_t idx = parent_stack_.back(); parent_stack_.pop_back(); metadata_->postorder.push_back(metadata_->nodes[idx].get()); tools_internal::AstNodeData& node = metadata_->NodeDataAt(idx); if (!parent_stack_.empty()) { tools_internal::AstNodeData& parent_node_data = metadata_->NodeDataAt(parent_stack_.back()); parent_node_data.weight += node.weight; } } std::unique_ptr<tools_internal::AstMetadata> Consume() && { return std::move(metadata_); } private: std::unique_ptr<tools_internal::AstMetadata> metadata_; std::vector<size_t> parent_stack_; }; } std::string ChildKindName(ChildKind kind) { switch (kind) { case ChildKind::kUnspecified: return "Unspecified"; case ChildKind::kSelectOperand: return "SelectOperand"; case ChildKind::kCallReceiver: return "CallReceiver"; case ChildKind::kCallArg: return "CallArg"; case ChildKind::kListElem: return "ListElem"; case ChildKind::kMapKey: return "MapKey"; case ChildKind::kMapValue: return "MapValue"; case ChildKind::kStructValue: return "StructValue"; case ChildKind::kComprehensionRange: return "ComprehensionRange"; case ChildKind::kComprehensionInit: return "ComprehensionInit"; case ChildKind::kComprehensionCondition: return "ComprehensionCondition"; case ChildKind::kComprehensionLoopStep: return "ComprehensionLoopStep"; case ChildKind::kComprensionResult: return "ComprehensionResult"; default: return absl::StrCat("Unknown ChildKind ", static_cast<int>(kind)); } } std::string NodeKindName(NodeKind kind) { switch (kind) { case NodeKind::kUnspecified: return "Unspecified"; case NodeKind::kConstant: return "Constant"; case NodeKind::kIdent: return "Ident"; case NodeKind::kSelect: return "Select"; case NodeKind::kCall: return "Call"; case NodeKind::kList: return "List"; case NodeKind::kMap: return "Map"; case NodeKind::kStruct: return "Struct"; case NodeKind::kComprehension: return "Comprehension"; default: return absl::StrCat("Unknown NodeKind ", static_cast<int>(kind)); } } int AstNode::child_index() const { if (data_.parent == nullptr) { return -1; } int i = 0; for (const AstNode* ptr : data_.parent->children()) { if (ptr->expr() == expr()) { return i; } i++; } return -1; } AstNode::PreorderRange AstNode::DescendantsPreorder() const { return AstNode::PreorderRange(absl::MakeConstSpan(data_.metadata->nodes) .subspan(data_.index, data_.weight)); } AstNode::PostorderRange AstNode::DescendantsPostorder() const { return AstNode::PostorderRange(absl::MakeConstSpan(data_.metadata->postorder) .subspan(data_.index, data_.weight)); } NavigableAst NavigableAst::Build(const Expr& expr) { NavigableExprBuilderVisitor visitor; AstTraverse(&expr, nullptr, &visitor); return NavigableAst(std::move(visitor).Consume()); } }
#include "tools/navigable_ast.h" #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/casts.h" #include "absl/strings/str_cat.h" #include "base/builtins.h" #include "internal/testing.h" #include "parser/parser.h" namespace cel { namespace { using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::parser::Parse; using testing::ElementsAre; using testing::IsEmpty; using testing::Pair; using testing::SizeIs; TEST(NavigableAst, Basic) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); EXPECT_TRUE(ast.IdsAreUnique()); const AstNode& root = ast.Root(); EXPECT_EQ(root.expr(), &const_node); EXPECT_THAT(root.children(), IsEmpty()); EXPECT_TRUE(root.parent() == nullptr); EXPECT_EQ(root.child_index(), -1); EXPECT_EQ(root.node_kind(), NodeKind::kConstant); EXPECT_EQ(root.parent_relation(), ChildKind::kUnspecified); } TEST(NavigableAst, DefaultCtorEmpty) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); EXPECT_EQ(ast, ast); NavigableAst empty; EXPECT_NE(ast, empty); EXPECT_EQ(empty, empty); EXPECT_TRUE(static_cast<bool>(ast)); EXPECT_FALSE(static_cast<bool>(empty)); NavigableAst moved = std::move(ast); EXPECT_EQ(ast, empty); EXPECT_FALSE(static_cast<bool>(ast)); EXPECT_TRUE(static_cast<bool>(moved)); } TEST(NavigableAst, FindById) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); const AstNode& root = ast.Root(); EXPECT_EQ(ast.FindId(const_node.id()), &root); EXPECT_EQ(ast.FindId(-1), nullptr); } MATCHER_P(AstNodeWrapping, expr, "") { const AstNode* ptr = arg; return ptr != nullptr && ptr->expr() == expr; } TEST(NavigableAst, ToleratesNonUnique) { Expr call_node; call_node.set_id(1); call_node.mutable_call_expr()->set_function(cel::builtin::kNot); Expr* const_node = call_node.mutable_call_expr()->add_args(); const_node->mutable_const_expr()->set_bool_value(false); const_node->set_id(1); NavigableAst ast = NavigableAst::Build(call_node); const AstNode& root = ast.Root(); EXPECT_EQ(ast.FindId(1), &root); EXPECT_EQ(ast.FindExpr(&call_node), &root); EXPECT_FALSE(ast.IdsAreUnique()); EXPECT_THAT(ast.FindExpr(const_node), AstNodeWrapping(const_node)); } TEST(NavigableAst, FindByExprPtr) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); const AstNode& root = ast.Root(); EXPECT_EQ(ast.FindExpr(&const_node), &root); EXPECT_EQ(ast.FindExpr(&Expr::default_instance()), nullptr); } TEST(NavigableAst, Children) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("1 + 2")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.expr(), &parsed_expr.expr()); EXPECT_THAT(root.children(), SizeIs(2)); EXPECT_TRUE(root.parent() == nullptr); EXPECT_EQ(root.child_index(), -1); EXPECT_EQ(root.parent_relation(), ChildKind::kUnspecified); EXPECT_EQ(root.node_kind(), NodeKind::kCall); EXPECT_THAT( root.children(), ElementsAre(AstNodeWrapping(&parsed_expr.expr().call_expr().args(0)), AstNodeWrapping(&parsed_expr.expr().call_expr().args(1)))); ASSERT_THAT(root.children(), SizeIs(2)); const auto* child1 = root.children()[0]; EXPECT_EQ(child1->child_index(), 0); EXPECT_EQ(child1->parent(), &root); EXPECT_EQ(child1->parent_relation(), ChildKind::kCallArg); EXPECT_EQ(child1->node_kind(), NodeKind::kConstant); EXPECT_THAT(child1->children(), IsEmpty()); const auto* child2 = root.children()[1]; EXPECT_EQ(child2->child_index(), 1); } TEST(NavigableAst, UnspecifiedExpr) { Expr expr; expr.set_id(1); NavigableAst ast = NavigableAst::Build(expr); const AstNode& root = ast.Root(); EXPECT_EQ(root.expr(), &expr); EXPECT_THAT(root.children(), SizeIs(0)); EXPECT_TRUE(root.parent() == nullptr); EXPECT_EQ(root.child_index(), -1); EXPECT_EQ(root.node_kind(), NodeKind::kUnspecified); } TEST(NavigableAst, ParentRelationSelect) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("a.b")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kSelectOperand); EXPECT_EQ(child->node_kind(), NodeKind::kIdent); } TEST(NavigableAst, ParentRelationCallReceiver) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("a.b()")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kCallReceiver); EXPECT_EQ(child->node_kind(), NodeKind::kIdent); } TEST(NavigableAst, ParentRelationCreateStruct) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("com.example.Type{field: '123'}")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kStruct); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kStructValue); EXPECT_EQ(child->node_kind(), NodeKind::kConstant); } TEST(NavigableAst, ParentRelationCreateMap) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("{'a': 123}")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kMap); ASSERT_THAT(root.children(), SizeIs(2)); const auto* key = root.children()[0]; const auto* value = root.children()[1]; EXPECT_EQ(key->parent_relation(), ChildKind::kMapKey); EXPECT_EQ(key->node_kind(), NodeKind::kConstant); EXPECT_EQ(value->parent_relation(), ChildKind::kMapValue); EXPECT_EQ(value->node_kind(), NodeKind::kConstant); } TEST(NavigableAst, ParentRelationCreateList) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("[123]")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kList); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kListElem); EXPECT_EQ(child->node_kind(), NodeKind::kConstant); } TEST(NavigableAst, ParentRelationComprehension) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("[1].all(x, x < 2)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kComprehension); ASSERT_THAT(root.children(), SizeIs(5)); const auto* range = root.children()[0]; const auto* init = root.children()[1]; const auto* condition = root.children()[2]; const auto* step = root.children()[3]; const auto* finish = root.children()[4]; EXPECT_EQ(range->parent_relation(), ChildKind::kComprehensionRange); EXPECT_EQ(init->parent_relation(), ChildKind::kComprehensionInit); EXPECT_EQ(condition->parent_relation(), ChildKind::kComprehensionCondition); EXPECT_EQ(step->parent_relation(), ChildKind::kComprehensionLoopStep); EXPECT_EQ(finish->parent_relation(), ChildKind::kComprensionResult); } TEST(NavigableAst, DescendantsPostorder) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("1 + (x * 3)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kCall); std::vector<int> constants; std::vector<NodeKind> node_kinds; for (const AstNode& node : root.DescendantsPostorder()) { if (node.node_kind() == NodeKind::kConstant) { constants.push_back(node.expr()->const_expr().int64_value()); } node_kinds.push_back(node.node_kind()); } EXPECT_THAT(node_kinds, ElementsAre(NodeKind::kConstant, NodeKind::kIdent, NodeKind::kConstant, NodeKind::kCall, NodeKind::kCall)); EXPECT_THAT(constants, ElementsAre(1, 3)); } TEST(NavigableAst, DescendantsPreorder) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("1 + (x * 3)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kCall); std::vector<int> constants; std::vector<NodeKind> node_kinds; for (const AstNode& node : root.DescendantsPreorder()) { if (node.node_kind() == NodeKind::kConstant) { constants.push_back(node.expr()->const_expr().int64_value()); } node_kinds.push_back(node.node_kind()); } EXPECT_THAT(node_kinds, ElementsAre(NodeKind::kCall, NodeKind::kConstant, NodeKind::kCall, NodeKind::kIdent, NodeKind::kConstant)); EXPECT_THAT(constants, ElementsAre(1, 3)); } TEST(NavigableAst, DescendantsPreorderComprehension) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("[1, 2, 3].map(x, x + 1)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kComprehension); std::vector<std::pair<NodeKind, ChildKind>> node_kinds; for (const AstNode& node : root.DescendantsPreorder()) { node_kinds.push_back( std::make_pair(node.node_kind(), node.parent_relation())); } EXPECT_THAT( node_kinds, ElementsAre(Pair(NodeKind::kComprehension, ChildKind::kUnspecified), Pair(NodeKind::kList, ChildKind::kComprehensionRange), Pair(NodeKind::kConstant, ChildKind::kListElem), Pair(NodeKind::kConstant, ChildKind::kListElem), Pair(NodeKind::kConstant, ChildKind::kListElem), Pair(NodeKind::kList, ChildKind::kComprehensionInit), Pair(NodeKind::kConstant, ChildKind::kComprehensionCondition), Pair(NodeKind::kCall, ChildKind::kComprehensionLoopStep), Pair(NodeKind::kIdent, ChildKind::kCallArg), Pair(NodeKind::kList, ChildKind::kCallArg), Pair(NodeKind::kCall, ChildKind::kListElem), Pair(NodeKind::kIdent, ChildKind::kCallArg), Pair(NodeKind::kConstant, ChildKind::kCallArg), Pair(NodeKind::kIdent, ChildKind::kComprensionResult))); } TEST(NavigableAst, DescendantsPreorderCreateMap) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("{'key1': 1, 'key2': 2}")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kMap); std::vector<std::pair<NodeKind, ChildKind>> node_kinds; for (const AstNode& node : root.DescendantsPreorder()) { node_kinds.push_back( std::make_pair(node.node_kind(), node.parent_relation())); } EXPECT_THAT(node_kinds, ElementsAre(Pair(NodeKind::kMap, ChildKind::kUnspecified), Pair(NodeKind::kConstant, ChildKind::kMapKey), Pair(NodeKind::kConstant, ChildKind::kMapValue), Pair(NodeKind::kConstant, ChildKind::kMapKey), Pair(NodeKind::kConstant, ChildKind::kMapValue))); } TEST(NodeKind, Stringify) { EXPECT_EQ(absl::StrCat(NodeKind::kConstant), "Constant"); EXPECT_EQ(absl::StrCat(NodeKind::kIdent), "Ident"); EXPECT_EQ(absl::StrCat(NodeKind::kSelect), "Select"); EXPECT_EQ(absl::StrCat(NodeKind::kCall), "Call"); EXPECT_EQ(absl::StrCat(NodeKind::kList), "List"); EXPECT_EQ(absl::StrCat(NodeKind::kMap), "Map"); EXPECT_EQ(absl::StrCat(NodeKind::kStruct), "Struct"); EXPECT_EQ(absl::StrCat(NodeKind::kComprehension), "Comprehension"); EXPECT_EQ(absl::StrCat(NodeKind::kUnspecified), "Unspecified"); EXPECT_EQ(absl::StrCat(absl::bit_cast<NodeKind>(255)), "Unknown NodeKind 255"); } TEST(ChildKind, Stringify) { EXPECT_EQ(absl::StrCat(ChildKind::kSelectOperand), "SelectOperand"); EXPECT_EQ(absl::StrCat(ChildKind::kCallReceiver), "CallReceiver"); EXPECT_EQ(absl::StrCat(ChildKind::kCallArg), "CallArg"); EXPECT_EQ(absl::StrCat(ChildKind::kListElem), "ListElem"); EXPECT_EQ(absl::StrCat(ChildKind::kMapKey), "MapKey"); EXPECT_EQ(absl::StrCat(ChildKind::kMapValue), "MapValue"); EXPECT_EQ(absl::StrCat(ChildKind::kStructValue), "StructValue"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionRange), "ComprehensionRange"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionInit), "ComprehensionInit"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionCondition), "ComprehensionCondition"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionLoopStep), "ComprehensionLoopStep"); EXPECT_EQ(absl::StrCat(ChildKind::kComprensionResult), "ComprehensionResult"); EXPECT_EQ(absl::StrCat(ChildKind::kUnspecified), "Unspecified"); EXPECT_EQ(absl::StrCat(absl::bit_cast<ChildKind>(255)), "Unknown ChildKind 255"); } } }
62
cpp
google/cel-cpp
bindings_ext
extensions/bindings_ext.cc
extensions/bindings_ext_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_BINDINGS_EXT_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_BINDINGS_EXT_H_ #include <vector> #include "absl/status/status.h" #include "parser/macro.h" #include "parser/macro_registry.h" #include "parser/options.h" namespace cel::extensions { std::vector<Macro> bindings_macros(); inline absl::Status RegisterBindingsMacros(MacroRegistry& registry, const ParserOptions&) { return registry.RegisterMacros(bindings_macros()); } } #endif #include "extensions/bindings_ext.h" #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "common/ast.h" #include "parser/macro.h" #include "parser/macro_expr_factory.h" namespace cel::extensions { namespace { static constexpr char kCelNamespace[] = "cel"; static constexpr char kBind[] = "bind"; static constexpr char kUnusedIterVar[] = "#unused"; bool IsTargetNamespace(const Expr& target) { return target.has_ident_expr() && target.ident_expr().name() == kCelNamespace; } } std::vector<Macro> bindings_macros() { absl::StatusOr<Macro> cel_bind = Macro::Receiver( kBind, 3, [](MacroExprFactory& factory, Expr& target, absl::Span<Expr> args) -> absl::optional<Expr> { if (!IsTargetNamespace(target)) { return absl::nullopt; } if (!args[0].has_ident_expr()) { return factory.ReportErrorAt( args[0], "cel.bind() variable name must be a simple identifier"); } auto var_name = args[0].ident_expr().name(); return factory.NewComprehension(kUnusedIterVar, factory.NewList(), std::move(var_name), std::move(args[1]), factory.NewBoolConst(false), std::move(args[0]), std::move(args[2])); }); return {*cel_bind}; } }
#include "extensions/bindings_ext.h" #include <memory> #include <string> #include <tuple> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/strings/string_view.h" #include "base/attribute.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_function.h" #include "eval/public/cel_function_adapter.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "internal/testing.h" #include "parser/parser.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/text_format.h" namespace cel::extensions { namespace { 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::ParseWithMacros; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelFunction; using ::google::api::expr::runtime::CelFunctionDescriptor; using ::google::api::expr::runtime::CelProtoWrapper; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::FunctionAdapter; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::RegisterBuiltinFunctions; using ::google::api::expr::runtime::UnknownProcessingOptions; using ::google::api::expr::test::v1::proto2::NestedTestAllTypes; using ::google::protobuf::Arena; using ::google::protobuf::TextFormat; using testing::HasSubstr; using cel::internal::IsOk; using cel::internal::StatusIs; struct TestInfo { std::string expr; std::string err = ""; }; class TestFunction : public CelFunction { public: explicit TestFunction(absl::string_view name) : CelFunction(CelFunctionDescriptor( name, true, {CelValue::Type::kBool, CelValue::Type::kBool, CelValue::Type::kBool, CelValue::Type::kBool})) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, Arena* arena) const override { *result = CelValue::CreateBool(true); return absl::OkStatus(); } }; constexpr absl::string_view kBind = "bind"; std::unique_ptr<CelFunction> CreateBindFunction() { return std::make_unique<TestFunction>(kBind); } class BindingsExtTest : public testing::TestWithParam<std::tuple<TestInfo, bool, bool>> { protected: const TestInfo& GetTestInfo() { return std::get<0>(GetParam()); } bool GetEnableConstantFolding() { return std::get<1>(GetParam()); } bool GetEnableRecursivePlan() { return std::get<2>(GetParam()); } }; TEST_P(BindingsExtTest, EndToEnd) { const TestInfo& test_info = GetTestInfo(); Arena arena; std::vector<Macro> all_macros = Macro::AllMacros(); std::vector<Macro> bindings_macros = cel::extensions::bindings_macros(); all_macros.insert(all_macros.end(), bindings_macros.begin(), bindings_macros.end()); auto result = ParseWithMacros(test_info.expr, all_macros, "<input>"); if (!test_info.err.empty()) { EXPECT_THAT(result.status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr(test_info.err))); return; } EXPECT_THAT(result, IsOk()); ParsedExpr parsed_expr = *result; Expr expr = parsed_expr.expr(); SourceInfo source_info = parsed_expr.source_info(); InterpreterOptions options; options.enable_heterogeneous_equality = true; options.enable_empty_wrapper_null_unboxing = true; options.constant_folding = GetEnableConstantFolding(); options.constant_arena = &arena; options.max_recursion_depth = GetEnableRecursivePlan() ? -1 : 0; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(&expr, &source_info)); Activation activation; ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsBool()) << out.DebugString(); EXPECT_EQ(out.BoolOrDie(), true); } INSTANTIATE_TEST_SUITE_P( CelBindingsExtTest, BindingsExtTest, testing::Combine( testing::ValuesIn<TestInfo>( {{"cel.bind(t, true, t)"}, {"cel.bind(msg, \"hello\", msg + msg + msg) == " "\"hellohellohello\""}, {"cel.bind(t1, true, cel.bind(t2, true, t1 && t2))"}, {"cel.bind(valid_elems, [1, 2, 3], " "[3, 4, 5].exists(e, e in valid_elems))"}, {"cel.bind(valid_elems, [1, 2, 3], " "![4, 5].exists(e, e in valid_elems))"}, {R"( cel.bind( my_list, ['a', 'b', 'c'].map(x, x + '_'), [0, 1, 2].map(y, my_list[y] + string(y))) == ['a_0', 'b_1', 'c_2'])"}, {"cel.bind(x, 1, " " cel.bind(x, x + 1, x)) == 2"}, {"false.bind(false, false, false)"}, {"cel.bind(bad.name, true, bad.name)", "variable name must be a simple identifier"}}), testing::Bool(), testing::Bool())); constexpr absl::string_view kFieldSelectTestExpr = R"pb( reference_map: { key: 4 value: { name: "msg" } } reference_map: { key: 8 value: { overload_id: "conditional" } } reference_map: { key: 9 value: { name: "google.api.expr.test.v1.proto2.TestAllTypes" } } reference_map: { key: 13 value: { name: "submsg" } } reference_map: { key: 18 value: { name: "submsg" } } type_map: { key: 4 value: { message_type: "google.api.expr.test.v1.proto2.NestedTestAllTypes" } } type_map: { key: 5 value: { message_type: "google.api.expr.test.v1.proto2.NestedTestAllTypes" } } type_map: { key: 6 value: { message_type: "google.api.expr.test.v1.proto2.NestedTestAllTypes" } } type_map: { key: 7 value: { primitive: BOOL } } type_map: { key: 8 value: { primitive: INT64 } } type_map: { key: 9 value: { message_type: "google.api.expr.test.v1.proto2.TestAllTypes" } } type_map: { key: 11 value: { primitive: INT64 } } type_map: { key: 12 value: { primitive: INT64 } } type_map: { key: 13 value: { message_type: "google.api.expr.test.v1.proto2.NestedTestAllTypes" } } type_map: { key: 14 value: { message_type: "google.api.expr.test.v1.proto2.TestAllTypes" } } type_map: { key: 15 value: { primitive: INT64 } } type_map: { key: 16 value: { list_type: { elem_type: { dyn: {} } } } } type_map: { key: 17 value: { primitive: BOOL } } type_map: { key: 18 value: { message_type: "google.api.expr.test.v1.proto2.NestedTestAllTypes" } } type_map: { key: 19 value: { primitive: INT64 } } source_info: { location: "<input>" line_offsets: 120 positions: { key: 1 value: 0 } positions: { key: 2 value: 8 } positions: { key: 3 value: 9 } positions: { key: 4 value: 17 } positions: { key: 5 value: 20 } positions: { key: 6 value: 26 } positions: { key: 7 value: 35 } positions: { key: 8 value: 42 } positions: { key: 9 value: 56 } positions: { key: 10 value: 69 } positions: { key: 11 value: 71 } positions: { key: 12 value: 75 } positions: { key: 13 value: 91 } positions: { key: 14 value: 97 } positions: { key: 15 value: 105 } positions: { key: 16 value: 8 } positions: { key: 17 value: 8 } positions: { key: 18 value: 8 } positions: { key: 19 value: 8 } macro_calls: { key: 19 value: { call_expr: { target: { id: 1 ident_expr: { name: "cel" } } function: "bind" args: { id: 3 ident_expr: { name: "submsg" } } args: { id: 6 select_expr: { operand: { id: 5 select_expr: { operand: { id: 4 ident_expr: { name: "msg" } } field: "child" } } field: "child" } } args: { id: 8 call_expr: { function: "_?_:_" args: { id: 7 const_expr: { bool_value: false } } args: { id: 12 select_expr: { operand: { id: 9 struct_expr: { message_name: "google.api.expr.test.v1.proto2.TestAllTypes" entries: { id: 10 field_key: "single_int64" value: { id: 11 const_expr: { int64_value: -42 } } } } } field: "single_int64" } } args: { id: 15 select_expr: { operand: { id: 14 select_expr: { operand: { id: 13 ident_expr: { name: "submsg" } } field: "payload" } } field: "single_int64" } } } } } } } } expr: { id: 19 comprehension_expr: { iter_var: "#unused" iter_range: { id: 16 list_expr: {} } accu_var: "submsg" accu_init: { id: 6 select_expr: { operand: { id: 5 select_expr: { operand: { id: 4 ident_expr: { name: "msg" } } field: "child" } } field: "child" } } loop_condition: { id: 17 const_expr: { bool_value: false } } loop_step: { id: 18 ident_expr: { name: "submsg" } } result: { id: 8 call_expr: { function: "_?_:_" args: { id: 7 const_expr: { bool_value: false } } args: { id: 12 select_expr: { operand: { id: 9 struct_expr: { message_name: "google.api.expr.test.v1.proto2.TestAllTypes" entries: { id: 10 field_key: "single_int64" value: { id: 11 const_expr: { int64_value: -42 } } } } } field: "single_int64" } } args: { id: 15 select_expr: { operand: { id: 14 select_expr: { operand: { id: 13 ident_expr: { name: "submsg" } } field: "payload" } } field: "single_int64" } } } } } })pb"; class BindingsExtInteractionsTest : public testing::TestWithParam<bool> { protected: bool GetEnableSelectOptimization() { return GetParam(); } }; TEST_P(BindingsExtInteractionsTest, SelectOptimization) { CheckedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kFieldSelectTestExpr, &expr)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(&expr)); Arena arena; Activation activation; NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsInt64()); EXPECT_EQ(out.Int64OrDie(), 42); } TEST_P(BindingsExtInteractionsTest, UnknownAttributesSelectOptimization) { CheckedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kFieldSelectTestExpr, &expr)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.unknown_processing = UnknownProcessingOptions::kAttributeOnly; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(&expr)); Arena arena; Activation activation; activation.set_unknown_attribute_patterns({AttributePattern( "msg", {AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("child")})}); NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsUnknownSet()); EXPECT_THAT(out.UnknownSetOrDie()->unknown_attributes(), testing::ElementsAre( Attribute("msg", {AttributeQualifier::OfString("child"), AttributeQualifier::OfString("child")}))); } TEST_P(BindingsExtInteractionsTest, UnknownAttributeSelectOptimizationReturnValue) { CheckedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kFieldSelectTestExpr, &expr)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.unknown_processing = UnknownProcessingOptions::kAttributeOnly; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(&expr)); Arena arena; Activation activation; activation.set_unknown_attribute_patterns({AttributePattern( "msg", {AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("payload"), AttributeQualifierPattern::OfString("single_int64")})}); NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsUnknownSet()) << out.DebugString(); EXPECT_THAT(out.UnknownSetOrDie()->unknown_attributes(), testing::ElementsAre(Attribute( "msg", {AttributeQualifier::OfString("child"), AttributeQualifier::OfString("child"), AttributeQualifier::OfString("payload"), AttributeQualifier::OfString("single_int64")}))); } TEST_P(BindingsExtInteractionsTest, MissingAttributesSelectOptimization) { CheckedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kFieldSelectTestExpr, &expr)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.enable_missing_attribute_errors = true; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(&expr)); Arena arena; Activation activation; activation.set_missing_attribute_patterns({AttributePattern( "msg", {AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("payload"), AttributeQualifierPattern::OfString("single_int64")})}); NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsError()) << out.DebugString(); EXPECT_THAT(out.ErrorOrDie()->ToString(), HasSubstr("msg.child.child.payload.single_int64")); } TEST_P(BindingsExtInteractionsTest, UnknownAttribute) { std::vector<Macro> all_macros = Macro::AllMacros(); std::vector<Macro> bindings_macros = cel::extensions::bindings_macros(); all_macros.insert(all_macros.end(), bindings_macros.begin(), bindings_macros.end()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithMacros( R"( cel.bind( x, msg.child.payload.single_int64, x < 42 || 1 == 1))", all_macros)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.unknown_processing = UnknownProcessingOptions::kAttributeOnly; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression( &expr.expr(), &expr.source_info())); Arena arena; Activation activation; activation.set_unknown_attribute_patterns({AttributePattern( "msg", {AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("payload"), AttributeQualifierPattern::OfString("single_int64")})}); NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsBool()) << out.DebugString(); EXPECT_TRUE(out.BoolOrDie()); } TEST_P(BindingsExtInteractionsTest, UnknownAttributeReturnValue) { std::vector<Macro> all_macros = Macro::AllMacros(); std::vector<Macro> bindings_macros = cel::extensions::bindings_macros(); all_macros.insert(all_macros.end(), bindings_macros.begin(), bindings_macros.end()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithMacros( R"( cel.bind( x, msg.child.payload.single_int64, x))", all_macros)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.unknown_processing = UnknownProcessingOptions::kAttributeOnly; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression( &expr.expr(), &expr.source_info())); Arena arena; Activation activation; activation.set_unknown_attribute_patterns({AttributePattern( "msg", {AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("payload"), AttributeQualifierPattern::OfString("single_int64")})}); NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsUnknownSet()) << out.DebugString(); EXPECT_THAT(out.UnknownSetOrDie()->unknown_attributes(), testing::ElementsAre(Attribute( "msg", {AttributeQualifier::OfString("child"), AttributeQualifier::OfString("payload"), AttributeQualifier::OfString("single_int64")}))); } TEST_P(BindingsExtInteractionsTest, MissingAttribute) { std::vector<Macro> all_macros = Macro::AllMacros(); std::vector<Macro> bindings_macros = cel::extensions::bindings_macros(); all_macros.insert(all_macros.end(), bindings_macros.begin(), bindings_macros.end()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithMacros( R"( cel.bind( x, msg.child.payload.single_int64, x < 42 || 1 == 2))", all_macros)); InterpreterOptions options; options.enable_empty_wrapper_null_unboxing = true; options.enable_missing_attribute_errors = true; options.enable_select_optimization = GetEnableSelectOptimization(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateBindFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression( &expr.expr(), &expr.source_info())); Arena arena; Activation activation; activation.set_missing_attribute_patterns({AttributePattern( "msg", {AttributeQualifierPattern::OfString("child"), AttributeQualifierPattern::OfString("payload"), AttributeQualifierPattern::OfString("single_int64")})}); NestedTestAllTypes msg; msg.mutable_child()->mutable_child()->mutable_payload()->set_single_int64(42); activation.InsertValue("msg", CelProtoWrapper::CreateMessage(&msg, &arena)); ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsError()) << out.DebugString(); EXPECT_THAT(out.ErrorOrDie()->ToString(), HasSubstr("msg.child.payload.single_int64")); } INSTANTIATE_TEST_SUITE_P(BindingsExtInteractionsTest, BindingsExtInteractionsTest, testing::Bool()); } }
63
cpp
google/cel-cpp
regex_functions
extensions/regex_functions.cc
extensions/regex_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_REGEX_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_REGEX_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterRegexFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/regex_functions.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "re2/re2.h" namespace cel { namespace {} absl::Status RegisterRegexFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (options.enable_regex) { auto regex_matches = [max_size = options.regex_max_program_size]( ValueManager& value_factory, const StringValue& target, const StringValue& regex) -> Value { RE2 re2(regex.ToString()); if (max_size > 0 && re2.ProgramSize() > max_size) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("exceeded RE2 max program size")); } if (!re2.ok()) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("invalid regex for match")); } return value_factory.CreateBoolValue( RE2::PartialMatch(target.ToString(), re2)); }; for (bool receiver_style : {true, false}) { using MatchFnAdapter = BinaryFunctionAdapter<Value, const StringValue&, const StringValue&>; CEL_RETURN_IF_ERROR( registry.Register(MatchFnAdapter::CreateDescriptor( cel::builtin::kRegexMatch, receiver_style), MatchFnAdapter::WrapFunction(regex_matches))); } } return absl::OkStatus(); } }
#include "runtime/standard/regex_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using testing::IsEmpty; using testing::UnorderedElementsAre; enum class CallStyle { kFree, kReceiver }; MATCHER_P2(MatchesDescriptor, name, call_style, "") { bool receiver_style; switch (call_style) { case CallStyle::kReceiver: receiver_style = true; break; case CallStyle::kFree: receiver_style = false; break; } const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{Kind::kString, Kind::kString}; return descriptor.name() == name && descriptor.receiver_style() == receiver_style && descriptor.types() == types; } TEST(RegisterRegexFunctions, Registered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterRegexFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT(overloads[builtin::kRegexMatch], UnorderedElementsAre( MatchesDescriptor(builtin::kRegexMatch, CallStyle::kReceiver), MatchesDescriptor(builtin::kRegexMatch, CallStyle::kFree))); } TEST(RegisterRegexFunctions, NotRegisteredIfDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_regex = false; ASSERT_OK(RegisterRegexFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT(overloads[builtin::kRegexMatch], IsEmpty()); } } }
64
cpp
google/cel-cpp
math_ext
extensions/math_ext.cc
extensions/math_ext_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_MATH_EXT_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_MATH_EXT_H_ #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel::extensions { absl::Status RegisterMathExtensionFunctions(FunctionRegistry& registry, const RuntimeOptions& options); absl::Status RegisterMathExtensionFunctions( google::api::expr::runtime::CelFunctionRegistry* registry, const google::api::expr::runtime::InterpreterOptions& options); } #endif #include "extensions/math_ext.h" #include <cstdint> #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/value.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_number.h" #include "eval/public/cel_options.h" #include "internal/status_macros.h" #include "runtime/function_adapter.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel::extensions { namespace { using ::google::api::expr::runtime::CelFunctionRegistry; using ::google::api::expr::runtime::CelNumber; using ::google::api::expr::runtime::InterpreterOptions; static constexpr char kMathMin[] = "math.@min"; static constexpr char kMathMax[] = "math.@max"; struct ToValueVisitor { Value operator()(uint64_t v) const { return UintValue{v}; } Value operator()(int64_t v) const { return IntValue{v}; } Value operator()(double v) const { return DoubleValue{v}; } }; Value NumberToValue(CelNumber number) { return number.visit<Value>(ToValueVisitor{}); } absl::StatusOr<CelNumber> ValueToNumber(ValueView value, absl::string_view function) { if (auto int_value = As<IntValueView>(value); int_value) { return CelNumber::FromInt64(int_value->NativeValue()); } if (auto uint_value = As<UintValueView>(value); uint_value) { return CelNumber::FromUint64(uint_value->NativeValue()); } if (auto double_value = As<DoubleValueView>(value); double_value) { return CelNumber::FromDouble(double_value->NativeValue()); } return absl::InvalidArgumentError( absl::StrCat(function, " arguments must be numeric")); } CelNumber MinNumber(CelNumber v1, CelNumber v2) { if (v2 < v1) { return v2; } return v1; } Value MinValue(CelNumber v1, CelNumber v2) { return NumberToValue(MinNumber(v1, v2)); } template <typename T> Value Identity(ValueManager &, T v1) { return NumberToValue(CelNumber(v1)); } template <typename T, typename U> Value Min(ValueManager &, T v1, U v2) { return MinValue(CelNumber(v1), CelNumber(v2)); } absl::StatusOr<Value> MinList(ValueManager &value_manager, const ListValue &values) { CEL_ASSIGN_OR_RETURN(auto iterator, values.NewIterator(value_manager)); if (!iterator->HasNext()) { return ErrorValue( absl::InvalidArgumentError("math.@min argument must not be empty")); } Value value; CEL_RETURN_IF_ERROR(iterator->Next(value_manager, value)); absl::StatusOr<CelNumber> current = ValueToNumber(value, kMathMin); if (!current.ok()) { return ErrorValue{current.status()}; } CelNumber min = *current; while (iterator->HasNext()) { CEL_RETURN_IF_ERROR(iterator->Next(value_manager, value)); absl::StatusOr<CelNumber> other = ValueToNumber(value, kMathMin); if (!other.ok()) { return ErrorValue{other.status()}; } min = MinNumber(min, *other); } return NumberToValue(min); } CelNumber MaxNumber(CelNumber v1, CelNumber v2) { if (v2 > v1) { return v2; } return v1; } Value MaxValue(CelNumber v1, CelNumber v2) { return NumberToValue(MaxNumber(v1, v2)); } template <typename T, typename U> Value Max(ValueManager &, T v1, U v2) { return MaxValue(CelNumber(v1), CelNumber(v2)); } absl::StatusOr<Value> MaxList(ValueManager &value_manager, const ListValue &values) { CEL_ASSIGN_OR_RETURN(auto iterator, values.NewIterator(value_manager)); if (!iterator->HasNext()) { return ErrorValue( absl::InvalidArgumentError("math.@max argument must not be empty")); } Value value; CEL_RETURN_IF_ERROR(iterator->Next(value_manager, value)); absl::StatusOr<CelNumber> current = ValueToNumber(value, kMathMax); if (!current.ok()) { return ErrorValue{current.status()}; } CelNumber min = *current; while (iterator->HasNext()) { CEL_RETURN_IF_ERROR(iterator->Next(value_manager, value)); absl::StatusOr<CelNumber> other = ValueToNumber(value, kMathMax); if (!other.ok()) { return ErrorValue{other.status()}; } min = MaxNumber(min, *other); } return NumberToValue(min); } template <typename T, typename U> absl::Status RegisterCrossNumericMin(FunctionRegistry &registry) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, T, U>::CreateDescriptor( kMathMin, false), BinaryFunctionAdapter<Value, T, U>::WrapFunction(Min<T, U>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, U, T>::CreateDescriptor( kMathMin, false), BinaryFunctionAdapter<Value, U, T>::WrapFunction(Min<U, T>))); return absl::OkStatus(); } template <typename T, typename U> absl::Status RegisterCrossNumericMax(FunctionRegistry &registry) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, T, U>::CreateDescriptor( kMathMax, false), BinaryFunctionAdapter<Value, T, U>::WrapFunction(Max<T, U>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, U, T>::CreateDescriptor( kMathMax, false), BinaryFunctionAdapter<Value, U, T>::WrapFunction(Max<U, T>))); return absl::OkStatus(); } } absl::Status RegisterMathExtensionFunctions(FunctionRegistry &registry, const RuntimeOptions &options) { CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, int64_t>::CreateDescriptor( kMathMin, false), UnaryFunctionAdapter<Value, int64_t>::WrapFunction(Identity<int64_t>))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, double>::CreateDescriptor( kMathMin, false), UnaryFunctionAdapter<Value, double>::WrapFunction(Identity<double>))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, uint64_t>::CreateDescriptor( kMathMin, false), UnaryFunctionAdapter<Value, uint64_t>::WrapFunction(Identity<uint64_t>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, int64_t, int64_t>::CreateDescriptor( kMathMin, false), BinaryFunctionAdapter<Value, int64_t, int64_t>::WrapFunction( Min<int64_t, int64_t>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, double, double>::CreateDescriptor( kMathMin, false), BinaryFunctionAdapter<Value, double, double>::WrapFunction( Min<double, double>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, uint64_t, uint64_t>::CreateDescriptor( kMathMin, false), BinaryFunctionAdapter<Value, uint64_t, uint64_t>::WrapFunction( Min<uint64_t, uint64_t>))); CEL_RETURN_IF_ERROR((RegisterCrossNumericMin<int64_t, uint64_t>(registry))); CEL_RETURN_IF_ERROR((RegisterCrossNumericMin<int64_t, double>(registry))); CEL_RETURN_IF_ERROR((RegisterCrossNumericMin<double, uint64_t>(registry))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, ListValue>::CreateDescriptor( kMathMin, false), UnaryFunctionAdapter<absl::StatusOr<Value>, ListValue>::WrapFunction( MinList))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, int64_t>::CreateDescriptor( kMathMax, false), UnaryFunctionAdapter<Value, int64_t>::WrapFunction(Identity<int64_t>))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, double>::CreateDescriptor( kMathMax, false), UnaryFunctionAdapter<Value, double>::WrapFunction(Identity<double>))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, uint64_t>::CreateDescriptor( kMathMax, false), UnaryFunctionAdapter<Value, uint64_t>::WrapFunction(Identity<uint64_t>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, int64_t, int64_t>::CreateDescriptor( kMathMax, false), BinaryFunctionAdapter<Value, int64_t, int64_t>::WrapFunction( Max<int64_t, int64_t>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, double, double>::CreateDescriptor( kMathMax, false), BinaryFunctionAdapter<Value, double, double>::WrapFunction( Max<double, double>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, uint64_t, uint64_t>::CreateDescriptor( kMathMax, false), BinaryFunctionAdapter<Value, uint64_t, uint64_t>::WrapFunction( Max<uint64_t, uint64_t>))); CEL_RETURN_IF_ERROR((RegisterCrossNumericMax<int64_t, uint64_t>(registry))); CEL_RETURN_IF_ERROR((RegisterCrossNumericMax<int64_t, double>(registry))); CEL_RETURN_IF_ERROR((RegisterCrossNumericMax<double, uint64_t>(registry))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, ListValue>::CreateDescriptor( kMathMax, false), UnaryFunctionAdapter<absl::StatusOr<Value>, ListValue>::WrapFunction( MaxList))); return absl::OkStatus(); } absl::Status RegisterMathExtensionFunctions(CelFunctionRegistry *registry, const InterpreterOptions &options) { return RegisterMathExtensionFunctions( registry->InternalGetRegistry(), google::api::expr::runtime::ConvertToRuntimeOptions(options)); } }
#include "extensions/math_ext.h" #include <memory> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/types/optional.h" #include "absl/types/span.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_function.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/testing/matchers.h" #include "extensions/math_ext_macros.h" #include "internal/testing.h" #include "parser/parser.h" #include "google/protobuf/arena.h" namespace cel::extensions { namespace { using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::v1alpha1::SourceInfo; using ::google::api::expr::parser::ParseWithMacros; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelFunction; using ::google::api::expr::runtime::CelFunctionDescriptor; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::ContainerBackedListImpl; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::RegisterBuiltinFunctions; using ::google::api::expr::runtime::test::EqualsCelValue; using ::google::protobuf::Arena; using testing::HasSubstr; using cel::internal::StatusIs; constexpr absl::string_view kMathMin = "math.@min"; constexpr absl::string_view kMathMax = "math.@max"; struct TestCase { absl::string_view operation; CelValue arg1; absl::optional<CelValue> arg2; CelValue result; }; TestCase MinCase(CelValue v1, CelValue v2, CelValue result) { return TestCase{kMathMin, v1, v2, result}; } TestCase MinCase(CelValue list, CelValue result) { return TestCase{kMathMin, list, absl::nullopt, result}; } TestCase MaxCase(CelValue v1, CelValue v2, CelValue result) { return TestCase{kMathMax, v1, v2, result}; } TestCase MaxCase(CelValue list, CelValue result) { return TestCase{kMathMax, list, absl::nullopt, result}; } struct MacroTestCase { absl::string_view expr; absl::string_view err = ""; }; class TestFunction : public CelFunction { public: explicit TestFunction(absl::string_view name) : CelFunction(CelFunctionDescriptor( name, true, {CelValue::Type::kBool, CelValue::Type::kInt64, CelValue::Type::kInt64})) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, Arena* arena) const override { *result = CelValue::CreateBool(true); return absl::OkStatus(); } }; constexpr absl::string_view kGreatest = "greatest"; std::unique_ptr<CelFunction> CreateGreatestFunction() { return std::make_unique<TestFunction>(kGreatest); } constexpr absl::string_view kLeast = "least"; std::unique_ptr<CelFunction> CreateLeastFunction() { return std::make_unique<TestFunction>(kLeast); } Expr CallExprOneArg(absl::string_view operation) { Expr expr; auto call = expr.mutable_call_expr(); call->set_function(operation); auto arg = call->add_args(); auto ident = arg->mutable_ident_expr(); ident->set_name("a"); return expr; } Expr CallExprTwoArgs(absl::string_view operation) { Expr expr; auto call = expr.mutable_call_expr(); call->set_function(operation); auto arg = call->add_args(); auto ident = arg->mutable_ident_expr(); ident->set_name("a"); arg = call->add_args(); ident = arg->mutable_ident_expr(); ident->set_name("b"); return expr; } void ExpectResult(const TestCase& test_case) { Expr expr; Activation activation; activation.InsertValue("a", test_case.arg1); if (test_case.arg2.has_value()) { activation.InsertValue("b", *test_case.arg2); expr = CallExprTwoArgs(test_case.operation); } else { expr = CallExprOneArg(test_case.operation); } SourceInfo source_info; InterpreterOptions options; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterMathExtensionFunctions(builder->GetRegistry(), options)); ASSERT_OK_AND_ASSIGN(auto cel_expression, builder->CreateExpression(&expr, &source_info)); google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(auto value, cel_expression->Evaluate(activation, &arena)); if (!test_case.result.IsError()) { EXPECT_THAT(value, EqualsCelValue(test_case.result)); } else { auto expected = test_case.result.ErrorOrDie(); EXPECT_THAT(*value.ErrorOrDie(), StatusIs(expected->code(), HasSubstr(expected->message()))); } } using MathExtParamsTest = testing::TestWithParam<TestCase>; TEST_P(MathExtParamsTest, MinMaxTests) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( MathExtParamsTest, MathExtParamsTest, testing::ValuesIn<TestCase>({ MinCase(CelValue::CreateInt64(3L), CelValue::CreateInt64(2L), CelValue::CreateInt64(2L)), MinCase(CelValue::CreateInt64(-1L), CelValue::CreateUint64(2u), CelValue::CreateInt64(-1L)), MinCase(CelValue::CreateInt64(-1L), CelValue::CreateDouble(-1.1), CelValue::CreateDouble(-1.1)), MinCase(CelValue::CreateDouble(-2.0), CelValue::CreateDouble(-1.1), CelValue::CreateDouble(-2.0)), MinCase(CelValue::CreateDouble(3.1), CelValue::CreateInt64(2), CelValue::CreateInt64(2)), MinCase(CelValue::CreateDouble(2.5), CelValue::CreateUint64(2u), CelValue::CreateUint64(2u)), MinCase(CelValue::CreateUint64(2u), CelValue::CreateDouble(-1.1), CelValue::CreateDouble(-1.1)), MinCase(CelValue::CreateUint64(3u), CelValue::CreateInt64(20), CelValue::CreateUint64(3u)), MinCase(CelValue::CreateUint64(4u), CelValue::CreateUint64(2u), CelValue::CreateUint64(2u)), MinCase(CelValue::CreateInt64(2L), CelValue::CreateUint64(2u), CelValue::CreateInt64(2L)), MinCase(CelValue::CreateInt64(-1L), CelValue::CreateDouble(-1.0), CelValue::CreateInt64(-1L)), MinCase(CelValue::CreateDouble(2.0), CelValue::CreateInt64(2), CelValue::CreateDouble(2.0)), MinCase(CelValue::CreateDouble(2.0), CelValue::CreateUint64(2u), CelValue::CreateDouble(2.0)), MinCase(CelValue::CreateUint64(2u), CelValue::CreateDouble(2.0), CelValue::CreateUint64(2u)), MinCase(CelValue::CreateUint64(3u), CelValue::CreateInt64(3), CelValue::CreateUint64(3u)), MaxCase(CelValue::CreateInt64(3L), CelValue::CreateInt64(2L), CelValue::CreateInt64(3L)), MaxCase(CelValue::CreateInt64(-1L), CelValue::CreateUint64(2u), CelValue::CreateUint64(2u)), MaxCase(CelValue::CreateInt64(-1L), CelValue::CreateDouble(-1.1), CelValue::CreateInt64(-1L)), MaxCase(CelValue::CreateDouble(-2.0), CelValue::CreateDouble(-1.1), CelValue::CreateDouble(-1.1)), MaxCase(CelValue::CreateDouble(3.1), CelValue::CreateInt64(2), CelValue::CreateDouble(3.1)), MaxCase(CelValue::CreateDouble(2.5), CelValue::CreateUint64(2u), CelValue::CreateDouble(2.5)), MaxCase(CelValue::CreateUint64(2u), CelValue::CreateDouble(-1.1), CelValue::CreateUint64(2u)), MaxCase(CelValue::CreateUint64(3u), CelValue::CreateInt64(20), CelValue::CreateInt64(20)), MaxCase(CelValue::CreateUint64(4u), CelValue::CreateUint64(2u), CelValue::CreateUint64(4u)), MaxCase(CelValue::CreateInt64(2L), CelValue::CreateUint64(2u), CelValue::CreateInt64(2L)), MaxCase(CelValue::CreateInt64(-1L), CelValue::CreateDouble(-1.0), CelValue::CreateInt64(-1L)), MaxCase(CelValue::CreateDouble(2.0), CelValue::CreateInt64(2), CelValue::CreateDouble(2.0)), MaxCase(CelValue::CreateDouble(2.0), CelValue::CreateUint64(2u), CelValue::CreateDouble(2.0)), MaxCase(CelValue::CreateUint64(2u), CelValue::CreateDouble(2.0), CelValue::CreateUint64(2u)), MaxCase(CelValue::CreateUint64(3u), CelValue::CreateInt64(3), CelValue::CreateUint64(3u)), })); TEST(MathExtTest, MinMaxList) { ContainerBackedListImpl single_item_list({CelValue::CreateInt64(1)}); ExpectResult(MinCase(CelValue::CreateList(&single_item_list), CelValue::CreateInt64(1))); ExpectResult(MaxCase(CelValue::CreateList(&single_item_list), CelValue::CreateInt64(1))); ContainerBackedListImpl list({CelValue::CreateInt64(1), CelValue::CreateUint64(2u), CelValue::CreateDouble(-1.1)}); ExpectResult( MinCase(CelValue::CreateList(&list), CelValue::CreateDouble(-1.1))); ExpectResult( MaxCase(CelValue::CreateList(&list), CelValue::CreateUint64(2u))); absl::Status empty_list_err = absl::InvalidArgumentError("argument must not be empty"); CelValue err_value = CelValue::CreateError(&empty_list_err); ContainerBackedListImpl empty_list({}); ExpectResult(MinCase(CelValue::CreateList(&empty_list), err_value)); ExpectResult(MaxCase(CelValue::CreateList(&empty_list), err_value)); absl::Status bad_arg_err = absl::InvalidArgumentError("arguments must be numeric"); err_value = CelValue::CreateError(&bad_arg_err); ContainerBackedListImpl bad_single_item({CelValue::CreateBool(true)}); ExpectResult(MinCase(CelValue::CreateList(&bad_single_item), err_value)); ExpectResult(MaxCase(CelValue::CreateList(&bad_single_item), err_value)); ContainerBackedListImpl bad_middle_item({CelValue::CreateInt64(1), CelValue::CreateBool(false), CelValue::CreateDouble(-1.1)}); ExpectResult(MinCase(CelValue::CreateList(&bad_middle_item), err_value)); ExpectResult(MaxCase(CelValue::CreateList(&bad_middle_item), err_value)); } using MathExtMacroParamsTest = testing::TestWithParam<MacroTestCase>; TEST_P(MathExtMacroParamsTest, MacroTests) { const MacroTestCase& test_case = GetParam(); auto result = ParseWithMacros(test_case.expr, cel::extensions::math_macros(), "<input>"); if (!test_case.err.empty()) { EXPECT_THAT(result.status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr(test_case.err))); return; } ASSERT_OK(result); ParsedExpr parsed_expr = *result; Expr expr = parsed_expr.expr(); SourceInfo source_info = parsed_expr.source_info(); InterpreterOptions options; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(builder->GetRegistry()->Register(CreateGreatestFunction())); ASSERT_OK(builder->GetRegistry()->Register(CreateLeastFunction())); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), options)); ASSERT_OK(RegisterMathExtensionFunctions(builder->GetRegistry(), options)); ASSERT_OK_AND_ASSIGN(auto cel_expression, builder->CreateExpression(&expr, &source_info)); google::protobuf::Arena arena; Activation activation; ASSERT_OK_AND_ASSIGN(auto value, cel_expression->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsBool()); EXPECT_EQ(value.BoolOrDie(), true); } INSTANTIATE_TEST_SUITE_P( MathExtMacrosParamsTest, MathExtMacroParamsTest, testing::ValuesIn<MacroTestCase>({ {"math.least(-0.5) == -0.5"}, {"math.least(-1) == -1"}, {"math.least(1u) == 1u"}, {"math.least(42.0, -0.5) == -0.5"}, {"math.least(-1, 0) == -1"}, {"math.least(-1, -1) == -1"}, {"math.least(1u, 42u) == 1u"}, {"math.least(42.0, -0.5, -0.25) == -0.5"}, {"math.least(-1, 0, 1) == -1"}, {"math.least(-1, -1, -1) == -1"}, {"math.least(1u, 42u, 0u) == 0u"}, {"math.least(1, 1.0) == 1"}, {"math.least(1, -2.0) == -2.0"}, {"math.least(2, 1u) == 1u"}, {"math.least(1.5, 2) == 1.5"}, {"math.least(1.5, -2) == -2"}, {"math.least(2.5, 1u) == 1u"}, {"math.least(1u, 2) == 1u"}, {"math.least(1u, -2) == -2"}, {"math.least(2u, 2.5) == 2u"}, {"math.least(1u, dyn(42)) == 1"}, {"math.least(1u, dyn(42), dyn(0.0)) == 0u"}, {"math.least([1u, 42u, 0u]) == 0u"}, { "math.least()", "math.least() requires at least one argument.", }, { "math.least('hello')", "math.least() invalid single argument value.", }, { "math.least({})", "math.least() invalid single argument value", }, { "math.least([])", "math.least() invalid single argument value", }, { "math.least([1, true])", "math.least() invalid single argument value", }, { "math.least(1, true)", "math.least() simple literal arguments must be numeric", }, { "math.least(1, 2, true)", "math.least() simple literal arguments must be numeric", }, {"math.greatest(-0.5) == -0.5"}, {"math.greatest(-1) == -1"}, {"math.greatest(1u) == 1u"}, {"math.greatest(42.0, -0.5) == 42.0"}, {"math.greatest(-1, 0) == 0"}, {"math.greatest(-1, -1) == -1"}, {"math.greatest(1u, 42u) == 42u"}, {"math.greatest(42.0, -0.5, -0.25) == 42.0"}, {"math.greatest(-1, 0, 1) == 1"}, {"math.greatest(-1, -1, -1) == -1"}, {"math.greatest(1u, 42u, 0u) == 42u"}, {"math.greatest(1, 1.0) == 1"}, {"math.greatest(1, -2.0) == 1"}, {"math.greatest(2, 1u) == 2"}, {"math.greatest(1.5, 2) == 2"}, {"math.greatest(1.5, -2) == 1.5"}, {"math.greatest(2.5, 1u) == 2.5"}, {"math.greatest(1u, 2) == 2"}, {"math.greatest(1u, -2) == 1u"}, {"math.greatest(2u, 2.5) == 2.5"}, {"math.greatest(1u, dyn(42)) == 42.0"}, {"math.greatest(1u, dyn(0.0), 0u) == 1"}, {"math.greatest([1u, dyn(0.0), 0u]) == 1"}, { "math.greatest()", "math.greatest() requires at least one argument.", }, { "math.greatest('hello')", "math.greatest() invalid single argument value.", }, { "math.greatest({})", "math.greatest() invalid single argument value", }, { "math.greatest([])", "math.greatest() invalid single argument value", }, { "math.greatest([1, true])", "math.greatest() invalid single argument value", }, { "math.greatest(1, true)", "math.greatest() simple literal arguments must be numeric", }, { "math.greatest(1, 2, true)", "math.greatest() simple literal arguments must be numeric", }, { "false.greatest(1,2)", }, { "true.least(1,2)", }, })); } }
65
cpp
google/cel-cpp
sets_functions
extensions/sets_functions.cc
extensions/sets_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_SETS_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_SETS_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel::extensions { absl::Status RegisterSetsFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "extensions/sets_functions.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel::extensions { namespace { absl::StatusOr<Value> SetsContains(ValueManager& value_factory, const ListValue& list, const ListValue& sublist) { bool any_missing = false; CEL_RETURN_IF_ERROR(sublist.ForEach( value_factory, [&list, &value_factory, &any_missing](ValueView sublist_element) -> absl::StatusOr<bool> { CEL_ASSIGN_OR_RETURN(auto contains, list.Contains(value_factory, sublist_element)); any_missing = !contains->Is<BoolValue>() || !contains->As<BoolValue>().NativeValue(); return !any_missing; })); return value_factory.CreateBoolValue(!any_missing); } absl::StatusOr<Value> SetsIntersects(ValueManager& value_factory, const ListValue& list, const ListValue& sublist) { bool exists = false; CEL_RETURN_IF_ERROR(list.ForEach( value_factory, [&value_factory, &sublist, &exists](ValueView list_element) -> absl::StatusOr<bool> { CEL_ASSIGN_OR_RETURN(auto contains, sublist.Contains(value_factory, list_element)); exists = contains->Is<BoolValue>() && contains->As<BoolValue>().NativeValue(); return !exists; })); return value_factory.CreateBoolValue(exists); } absl::StatusOr<Value> SetsEquivalent(ValueManager& value_factory, const ListValue& list, const ListValue& sublist) { CEL_ASSIGN_OR_RETURN(auto contains_sublist, SetsContains(value_factory, list, sublist)); if (contains_sublist->Is<BoolValue>() && !contains_sublist->As<BoolValue>().NativeValue()) { return contains_sublist; } return SetsContains(value_factory, sublist, list); } absl::Status RegisterSetsContainsFunction(FunctionRegistry& registry) { return registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, const ListValue&, const ListValue&>::CreateDescriptor("sets.contains", false), BinaryFunctionAdapter<absl::StatusOr<Value>, const ListValue&, const ListValue&>::WrapFunction(SetsContains)); } absl::Status RegisterSetsIntersectsFunction(FunctionRegistry& registry) { return registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, const ListValue&, const ListValue&>::CreateDescriptor("sets.intersects", false), BinaryFunctionAdapter<absl::StatusOr<Value>, const ListValue&, const ListValue&>::WrapFunction(SetsIntersects)); } absl::Status RegisterSetsEquivalentFunction(FunctionRegistry& registry) { return registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, const ListValue&, const ListValue&>::CreateDescriptor("sets.equivalent", false), BinaryFunctionAdapter<absl::StatusOr<Value>, const ListValue&, const ListValue&>::WrapFunction(SetsEquivalent)); } } absl::Status RegisterSetsFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterSetsContainsFunction(registry)); CEL_RETURN_IF_ERROR(RegisterSetsIntersectsFunction(registry)); CEL_RETURN_IF_ERROR(RegisterSetsEquivalentFunction(registry)); return absl::OkStatus(); } }
#include "extensions/sets_functions.h" #include <memory> #include <string> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.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_function_adapter.h" #include "eval/public/cel_options.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace cel::extensions { namespace { using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::v1alpha1::SourceInfo; using ::google::api::expr::parser::ParseWithMacros; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::FunctionAdapter; using ::google::api::expr::runtime::InterpreterOptions; using ::google::protobuf::Arena; using cel::internal::IsOk; struct TestInfo { std::string expr; }; class CelSetsFunctionsTest : public testing::TestWithParam<TestInfo> {}; TEST_P(CelSetsFunctionsTest, EndToEnd) { const TestInfo& test_info = GetParam(); std::vector<Macro> all_macros = Macro::AllMacros(); auto result = ParseWithMacros(test_info.expr, all_macros, "<input>"); EXPECT_THAT(result, IsOk()); ParsedExpr parsed_expr = *result; Expr expr = parsed_expr.expr(); SourceInfo source_info = parsed_expr.source_info(); InterpreterOptions options; options.enable_heterogeneous_equality = true; options.enable_empty_wrapper_null_unboxing = true; options.enable_qualified_identifier_rewrites = true; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterSetsFunctions(builder->GetRegistry()->InternalGetRegistry(), cel::RuntimeOptions{})); ASSERT_OK(google::api::expr::runtime::RegisterBuiltinFunctions( builder->GetRegistry(), options)); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder->CreateExpression(&expr, &source_info)); Arena arena; Activation activation; ASSERT_OK_AND_ASSIGN(CelValue out, cel_expr->Evaluate(activation, &arena)); ASSERT_TRUE(out.IsBool()) << test_info.expr << " -> " << out.DebugString(); EXPECT_TRUE(out.BoolOrDie()) << test_info.expr << " -> " << out.DebugString(); } INSTANTIATE_TEST_SUITE_P( CelSetsFunctionsTest, CelSetsFunctionsTest, testing::ValuesIn<TestInfo>({ {"sets.contains([], [])"}, {"sets.contains([1], [])"}, {"sets.contains([1], [1])"}, {"sets.contains([1], [1, 1])"}, {"sets.contains([1, 1], [1])"}, {"sets.contains([2, 1], [1])"}, {"sets.contains([1], [1.0, 1u])"}, {"sets.contains([1, 2], [2u, 2.0])"}, {"sets.contains([1, 2u], [2, 2.0])"}, {"!sets.contains([1], [2])"}, {"!sets.contains([1], [1, 2])"}, {"!sets.contains([1], [\"1\", 1])"}, {"!sets.contains([1], [1.1, 2])"}, {"sets.intersects([1], [1])"}, {"sets.intersects([1], [1, 1])"}, {"sets.intersects([1, 1], [1])"}, {"sets.intersects([2, 1], [1])"}, {"sets.intersects([1], [1, 2])"}, {"sets.intersects([1], [1.0, 2])"}, {"sets.intersects([1, 2], [2u, 2, 2.0])"}, {"sets.intersects([1, 2], [1u, 2, 2.3])"}, {"!sets.intersects([], [])"}, {"!sets.intersects([1], [])"}, {"!sets.intersects([1], [2])"}, {"!sets.intersects([1], [\"1\", 2])"}, {"!sets.intersects([1], [1.1, 2u])"}, {"sets.equivalent([], [])"}, {"sets.equivalent([1], [1])"}, {"sets.equivalent([1], [1, 1])"}, {"sets.equivalent([1, 1, 2], [2, 2, 1])"}, {"sets.equivalent([1, 1], [1])"}, {"sets.equivalent([1], [1u, 1.0])"}, {"sets.equivalent([1], [1u, 1.0])"}, {"sets.equivalent([1, 2, 3], [3u, 2.0, 1])"}, {"!sets.equivalent([2, 1], [1])"}, {"!sets.equivalent([1], [1, 2])"}, {"!sets.equivalent([1, 2], [2u, 2, 2.0])"}, {"!sets.equivalent([1, 2], [1u, 2, 2.3])"}, {"sets.equivalent([false, true], [true, false])"}, {"!sets.equivalent([true], [false])"}, {"sets.equivalent(['foo', 'bar'], ['bar', 'foo'])"}, {"!sets.equivalent(['foo'], ['bar'])"}, {"sets.equivalent([b'foo', b'bar'], [b'bar', b'foo'])"}, {"!sets.equivalent([b'foo'], [b'bar'])"}, {"sets.equivalent([null], [null])"}, {"!sets.equivalent([null], [])"}, {"sets.equivalent([type(1), type(1u)], [type(1u), type(1)])"}, {"!sets.equivalent([type(1)], [type(1u)])"}, {"sets.equivalent([duration('0s'), duration('1s')], [duration('1s'), " "duration('0s')])"}, {"!sets.equivalent([duration('0s')], [duration('1s')])"}, {"sets.equivalent([timestamp('1970-01-01T00:00:00Z'), " "timestamp('1970-01-01T00:00:01Z')], " "[timestamp('1970-01-01T00:00:01Z'), " "timestamp('1970-01-01T00:00:00Z')])"}, {"!sets.equivalent([timestamp('1970-01-01T00:00:00Z')], " "[timestamp('1970-01-01T00:00:01Z')])"}, {"sets.equivalent([[false, true]], [[false, true]])"}, {"!sets.equivalent([[false, true]], [[true, false]])"}, {"sets.equivalent([{'foo': true, 'bar': false}], [{'bar': false, " "'foo': true}])"}, })); } }
66
cpp
google/cel-cpp
type
extensions/protobuf/type.cc
extensions/protobuf/type_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_H_ #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "common/type.h" #include "common/type_factory.h" #include "internal/status_macros.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { absl::StatusOr<TypeView> ProtoTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::Descriptor*> desc, Type& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND); inline absl::StatusOr<Type> ProtoTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::Descriptor*> desc) { Type scratch; CEL_ASSIGN_OR_RETURN(auto result, ProtoTypeToType(type_factory, desc, scratch)); return Type{result}; } absl::StatusOr<TypeView> ProtoEnumTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::EnumDescriptor*> desc, Type& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND); inline absl::StatusOr<Type> ProtoEnumTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::EnumDescriptor*> desc) { Type scratch; CEL_ASSIGN_OR_RETURN(auto result, ProtoEnumTypeToType(type_factory, desc, scratch)); return Type{result}; } absl::StatusOr<TypeView> ProtoFieldTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::FieldDescriptor*> field_desc, Type& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND); inline absl::StatusOr<Type> ProtoFieldTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::FieldDescriptor*> field_desc) { Type scratch; CEL_ASSIGN_OR_RETURN(auto result, ProtoFieldTypeToType(type_factory, field_desc, scratch)); return Type{result}; } } #endif #include "extensions/protobuf/type.h" #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common/type.h" #include "common/type_factory.h" #include "common/types/type_cache.h" #include "internal/status_macros.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { namespace { absl::StatusOr<TypeView> ProtoSingularFieldTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::FieldDescriptor*> field_desc, Type& scratch) { switch (field_desc->type()) { case google::protobuf::FieldDescriptor::TYPE_FLOAT: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_DOUBLE: return DoubleTypeView{}; case google::protobuf::FieldDescriptor::TYPE_SFIXED32: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_SINT32: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_INT32: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_SFIXED64: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_SINT64: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_INT64: return IntTypeView{}; case google::protobuf::FieldDescriptor::TYPE_FIXED32: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_UINT32: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_FIXED64: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_UINT64: return UintTypeView{}; case google::protobuf::FieldDescriptor::TYPE_BOOL: return BoolTypeView{}; case google::protobuf::FieldDescriptor::TYPE_STRING: return StringTypeView{}; case google::protobuf::FieldDescriptor::TYPE_GROUP: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::FieldDescriptor::TYPE_MESSAGE: return ProtoTypeToType(type_factory, field_desc->message_type(), scratch); case google::protobuf::FieldDescriptor::TYPE_BYTES: return BytesTypeView{}; case google::protobuf::FieldDescriptor::TYPE_ENUM: return ProtoEnumTypeToType(type_factory, field_desc->enum_type(), scratch); default: return absl::InvalidArgumentError( absl::StrCat("unexpected protocol buffer message field type: ", google::protobuf::FieldDescriptor::TypeName(field_desc->type()))); } } } absl::StatusOr<TypeView> ProtoTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::Descriptor*> desc, Type& scratch) { switch (desc->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: return DoubleWrapperTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: return IntWrapperTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: return UintWrapperTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: return StringWrapperTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: return BytesWrapperTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: return BoolWrapperTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY: return AnyTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION: return DurationTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP: return TimestampTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE: return DynTypeView{}; case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE: return common_internal::ProcessLocalTypeCache::Get()->GetDynListType(); case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT: return common_internal::ProcessLocalTypeCache::Get() ->GetStringDynMapType(); default: scratch = type_factory.CreateStructType(desc->full_name()); return scratch; } } absl::StatusOr<TypeView> ProtoEnumTypeToType( TypeFactory&, absl::Nonnull<const google::protobuf::EnumDescriptor*> desc, Type&) { if (desc->full_name() == "google.protobuf.NullValue") { return NullTypeView{}; } return IntTypeView{}; } absl::StatusOr<TypeView> ProtoFieldTypeToType( TypeFactory& type_factory, absl::Nonnull<const google::protobuf::FieldDescriptor*> field_desc, Type& scratch) { if (field_desc->is_map()) { Type map_key_scratch; Type map_value_scratch; CEL_ASSIGN_OR_RETURN( auto key_type, ProtoFieldTypeToType( type_factory, field_desc->message_type()->map_key(), map_key_scratch)); CEL_ASSIGN_OR_RETURN( auto value_type, ProtoFieldTypeToType(type_factory, field_desc->message_type()->map_value(), map_value_scratch)); scratch = type_factory.CreateMapType(key_type, value_type); return scratch; } if (field_desc->is_repeated()) { Type element_scratch; CEL_ASSIGN_OR_RETURN(auto element_type, ProtoSingularFieldTypeToType(type_factory, field_desc, element_scratch)); scratch = type_factory.CreateListType(element_type); return scratch; } return ProtoSingularFieldTypeToType(type_factory, field_desc, scratch); } }
#include "extensions/protobuf/type.h" #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 "common/type.h" #include "common/type_testing.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/generated_enum_reflection.h" namespace cel::extensions { namespace { using ::google::api::expr::test::v1::proto2::TestAllTypes; using testing::Eq; using cel::internal::IsOkAndHolds; class ProtoTypeTest : public common_internal::ThreadCompatibleTypeTest<> {}; TEST_P(ProtoTypeTest, ProtoTypeToType) { EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::FloatValue::GetDescriptor()), IsOkAndHolds(Eq(DoubleWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::DoubleValue::GetDescriptor()), IsOkAndHolds(Eq(DoubleWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::Int32Value::GetDescriptor()), IsOkAndHolds(Eq(IntWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::Int64Value::GetDescriptor()), IsOkAndHolds(Eq(IntWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::UInt32Value::GetDescriptor()), IsOkAndHolds(Eq(UintWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::UInt64Value::GetDescriptor()), IsOkAndHolds(Eq(UintWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::StringValue::GetDescriptor()), IsOkAndHolds(Eq(StringWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::BytesValue::GetDescriptor()), IsOkAndHolds(Eq(BytesWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::BoolValue::GetDescriptor()), IsOkAndHolds(Eq(BoolWrapperType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::Duration::GetDescriptor()), IsOkAndHolds(Eq(DurationType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::Timestamp::GetDescriptor()), IsOkAndHolds(Eq(TimestampType{}))); EXPECT_THAT( ProtoTypeToType(type_factory(), google::protobuf::Any::GetDescriptor()), IsOkAndHolds(Eq(AnyType{}))); EXPECT_THAT( ProtoTypeToType(type_factory(), google::protobuf::Value::GetDescriptor()), IsOkAndHolds(Eq(DynType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::ListValue::GetDescriptor()), IsOkAndHolds(Eq(ListType{}))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::Struct::GetDescriptor()), IsOkAndHolds(Eq(MapType(type_factory().GetStringDynMapType())))); EXPECT_THAT(ProtoTypeToType(type_factory(), google::protobuf::Struct::GetDescriptor()), IsOkAndHolds(Eq(MapType(type_factory().GetStringDynMapType())))); EXPECT_THAT( ProtoTypeToType(type_factory(), TestAllTypes::GetDescriptor()), IsOkAndHolds(Eq(StructType(memory_manager(), TestAllTypes::GetDescriptor()->full_name())))); } TEST_P(ProtoTypeTest, ProtoEnumTypeToType) { EXPECT_THAT(ProtoEnumTypeToType( type_factory(), google::protobuf::GetEnumDescriptor<google::protobuf::NullValue>()), IsOkAndHolds(Eq(NullType{}))); EXPECT_THAT(ProtoEnumTypeToType( type_factory(), google::protobuf::GetEnumDescriptor<TestAllTypes::NestedEnum>()), IsOkAndHolds(Eq(IntType{}))); } TEST_P(ProtoTypeTest, ProtoFieldTypeToType) { EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_int32")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_int64")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_sint32")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_sint64")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_sfixed32")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_sfixed64")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_uint32")), IsOkAndHolds(Eq(UintType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_uint32")), IsOkAndHolds(Eq(UintType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_fixed32")), IsOkAndHolds(Eq(UintType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_fixed64")), IsOkAndHolds(Eq(UintType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_float")), IsOkAndHolds(Eq(DoubleType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_double")), IsOkAndHolds(Eq(DoubleType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_bool")), IsOkAndHolds(Eq(BoolType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_string")), IsOkAndHolds(Eq(StringType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("single_bytes")), IsOkAndHolds(Eq(BytesType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("standalone_message")), IsOkAndHolds(Eq(StructType{ memory_manager(), TestAllTypes::NestedMessage::GetDescriptor()->full_name()}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("standalone_enum")), IsOkAndHolds(Eq(IntType{}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("repeated_bool")), IsOkAndHolds(Eq(ListType{memory_manager(), BoolType{}}))); EXPECT_THAT( ProtoFieldTypeToType( type_factory(), TestAllTypes::GetDescriptor()->FindFieldByName("map_bool_bool")), IsOkAndHolds(Eq(MapType{memory_manager(), BoolType{}, BoolType{}}))); } INSTANTIATE_TEST_SUITE_P( ProtoTypeTest, ProtoTypeTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoTypeTest::ToString); } }
67
cpp
google/cel-cpp
ast_converters
extensions/protobuf/ast_converters.cc
extensions/protobuf/ast_converters_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_AST_CONVERTERS_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_AST_CONVERTERS_H_ #include <memory> #include "google/api/expr/v1alpha1/checked.pb.h" #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/statusor.h" #include "base/ast.h" #include "base/ast_internal/expr.h" namespace cel::extensions { namespace internal { absl::StatusOr<ast_internal::Expr> ConvertProtoExprToNative( const google::api::expr::v1alpha1::Expr& expr); absl::StatusOr<ast_internal::SourceInfo> ConvertProtoSourceInfoToNative( const google::api::expr::v1alpha1::SourceInfo& source_info); absl::StatusOr<ast_internal::ParsedExpr> ConvertProtoParsedExprToNative( const google::api::expr::v1alpha1::ParsedExpr& parsed_expr); absl::StatusOr<ast_internal::Type> ConvertProtoTypeToNative( const google::api::expr::v1alpha1::Type& type); absl::StatusOr<ast_internal::Reference> ConvertProtoReferenceToNative( const google::api::expr::v1alpha1::Reference& reference); absl::StatusOr<ast_internal::CheckedExpr> ConvertProtoCheckedExprToNative( const google::api::expr::v1alpha1::CheckedExpr& checked_expr); absl::StatusOr<ast_internal::Constant> ConvertConstant( const google::api::expr::v1alpha1::Constant& constant); } absl::StatusOr<std::unique_ptr<Ast>> CreateAstFromParsedExpr( const google::api::expr::v1alpha1::Expr& expr, const google::api::expr::v1alpha1::SourceInfo* source_info = nullptr); absl::StatusOr<std::unique_ptr<Ast>> CreateAstFromParsedExpr( const google::api::expr::v1alpha1::ParsedExpr& parsed_expr); absl::StatusOr<google::api::expr::v1alpha1::ParsedExpr> CreateParsedExprFromAst( const Ast& ast); absl::StatusOr<std::unique_ptr<Ast>> CreateAstFromCheckedExpr( const google::api::expr::v1alpha1::CheckedExpr& checked_expr); absl::StatusOr<google::api::expr::v1alpha1::CheckedExpr> CreateCheckedExprFromAst( const Ast& ast); } #endif #include "extensions/protobuf/ast_converters.h" #include <cstdint> #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/duration.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/timestamp.pb.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/time/time.h" #include "absl/types/variant.h" #include "base/ast.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "common/constant.h" #include "extensions/protobuf/internal/ast.h" #include "internal/proto_time_encoding.h" #include "internal/status_macros.h" namespace cel::extensions { namespace internal { namespace { using ::cel::ast_internal::AbstractType; using ::cel::ast_internal::Bytes; using ::cel::ast_internal::Call; using ::cel::ast_internal::CheckedExpr; using ::cel::ast_internal::Comprehension; using ::cel::ast_internal::Constant; using ::cel::ast_internal::CreateList; using ::cel::ast_internal::CreateStruct; using ::cel::ast_internal::DynamicType; using ::cel::ast_internal::ErrorType; using ::cel::ast_internal::Expr; using ::cel::ast_internal::Extension; using ::cel::ast_internal::FunctionType; using ::cel::ast_internal::Ident; using ::cel::ast_internal::ListType; using ::cel::ast_internal::MapType; using ::cel::ast_internal::MessageType; using ::cel::ast_internal::NullValue; using ::cel::ast_internal::ParamType; using ::cel::ast_internal::ParsedExpr; using ::cel::ast_internal::PrimitiveType; using ::cel::ast_internal::PrimitiveTypeWrapper; using ::cel::ast_internal::Reference; using ::cel::ast_internal::Select; using ::cel::ast_internal::SourceInfo; using ::cel::ast_internal::Type; using ::cel::ast_internal::WellKnownType; using ExprPb = google::api::expr::v1alpha1::Expr; using ParsedExprPb = google::api::expr::v1alpha1::ParsedExpr; using CheckedExprPb = google::api::expr::v1alpha1::CheckedExpr; using ExtensionPb = google::api::expr::v1alpha1::SourceInfo::Extension; } absl::StatusOr<Constant> ConvertConstant( const google::api::expr::v1alpha1::Constant& constant) { switch (constant.constant_kind_case()) { case google::api::expr::v1alpha1::Constant::CONSTANT_KIND_NOT_SET: return Constant(); case google::api::expr::v1alpha1::Constant::kNullValue: return Constant(nullptr); case google::api::expr::v1alpha1::Constant::kBoolValue: return Constant(constant.bool_value()); case google::api::expr::v1alpha1::Constant::kInt64Value: return Constant(constant.int64_value()); case google::api::expr::v1alpha1::Constant::kUint64Value: return Constant(constant.uint64_value()); case google::api::expr::v1alpha1::Constant::kDoubleValue: return Constant(constant.double_value()); case google::api::expr::v1alpha1::Constant::kStringValue: return Constant(StringConstant{constant.string_value()}); case google::api::expr::v1alpha1::Constant::kBytesValue: return Constant(BytesConstant{constant.bytes_value()}); case google::api::expr::v1alpha1::Constant::kDurationValue: return Constant(absl::Seconds(constant.duration_value().seconds()) + absl::Nanoseconds(constant.duration_value().nanos())); case google::api::expr::v1alpha1::Constant::kTimestampValue: return Constant( absl::FromUnixSeconds(constant.timestamp_value().seconds()) + absl::Nanoseconds(constant.timestamp_value().nanos())); default: return absl::InvalidArgumentError("Unsupported constant type"); } } absl::StatusOr<Expr> ConvertProtoExprToNative( const google::api::expr::v1alpha1::Expr& expr) { Expr native_expr; CEL_RETURN_IF_ERROR(protobuf_internal::ExprFromProto(expr, native_expr)); return native_expr; } absl::StatusOr<SourceInfo> ConvertProtoSourceInfoToNative( const google::api::expr::v1alpha1::SourceInfo& source_info) { absl::flat_hash_map<int64_t, Expr> macro_calls; for (const auto& pair : source_info.macro_calls()) { auto native_expr = ConvertProtoExprToNative(pair.second); if (!native_expr.ok()) { return native_expr.status(); } macro_calls.emplace(pair.first, *(std::move(native_expr))); } std::vector<Extension> extensions; extensions.reserve(source_info.extensions_size()); for (const auto& extension : source_info.extensions()) { std::vector<Extension::Component> components; components.reserve(extension.affected_components().size()); for (const auto& component : extension.affected_components()) { switch (component) { case ExtensionPb::COMPONENT_PARSER: components.push_back(Extension::Component::kParser); break; case ExtensionPb::COMPONENT_TYPE_CHECKER: components.push_back(Extension::Component::kTypeChecker); break; case ExtensionPb::COMPONENT_RUNTIME: components.push_back(Extension::Component::kRuntime); break; default: components.push_back(Extension::Component::kUnspecified); break; } } extensions.push_back( Extension(extension.id(), std::make_unique<Extension::Version>( extension.version().major(), extension.version().minor()), std::move(components))); } return SourceInfo( source_info.syntax_version(), source_info.location(), std::vector<int32_t>(source_info.line_offsets().begin(), source_info.line_offsets().end()), absl::flat_hash_map<int64_t, int32_t>(source_info.positions().begin(), source_info.positions().end()), std::move(macro_calls), std::move(extensions)); } absl::StatusOr<ParsedExpr> ConvertProtoParsedExprToNative( const google::api::expr::v1alpha1::ParsedExpr& parsed_expr) { auto native_expr = ConvertProtoExprToNative(parsed_expr.expr()); if (!native_expr.ok()) { return native_expr.status(); } auto native_source_info = ConvertProtoSourceInfoToNative(parsed_expr.source_info()); if (!native_source_info.ok()) { return native_source_info.status(); } return ParsedExpr(*(std::move(native_expr)), *(std::move(native_source_info))); } absl::StatusOr<PrimitiveType> ToNative( google::api::expr::v1alpha1::Type::PrimitiveType primitive_type) { switch (primitive_type) { case google::api::expr::v1alpha1::Type::PRIMITIVE_TYPE_UNSPECIFIED: return PrimitiveType::kPrimitiveTypeUnspecified; case google::api::expr::v1alpha1::Type::BOOL: return PrimitiveType::kBool; case google::api::expr::v1alpha1::Type::INT64: return PrimitiveType::kInt64; case google::api::expr::v1alpha1::Type::UINT64: return PrimitiveType::kUint64; case google::api::expr::v1alpha1::Type::DOUBLE: return PrimitiveType::kDouble; case google::api::expr::v1alpha1::Type::STRING: return PrimitiveType::kString; case google::api::expr::v1alpha1::Type::BYTES: return PrimitiveType::kBytes; default: return absl::InvalidArgumentError( "Illegal type specified for " "google::api::expr::v1alpha1::Type::PrimitiveType."); } } absl::StatusOr<WellKnownType> ToNative( google::api::expr::v1alpha1::Type::WellKnownType well_known_type) { switch (well_known_type) { case google::api::expr::v1alpha1::Type::WELL_KNOWN_TYPE_UNSPECIFIED: return WellKnownType::kWellKnownTypeUnspecified; case google::api::expr::v1alpha1::Type::ANY: return WellKnownType::kAny; case google::api::expr::v1alpha1::Type::TIMESTAMP: return WellKnownType::kTimestamp; case google::api::expr::v1alpha1::Type::DURATION: return WellKnownType::kDuration; default: return absl::InvalidArgumentError( "Illegal type specified for " "google::api::expr::v1alpha1::Type::WellKnownType."); } } absl::StatusOr<ListType> ToNative( const google::api::expr::v1alpha1::Type::ListType& list_type) { auto native_elem_type = ConvertProtoTypeToNative(list_type.elem_type()); if (!native_elem_type.ok()) { return native_elem_type.status(); } return ListType(std::make_unique<Type>(*(std::move(native_elem_type)))); } absl::StatusOr<MapType> ToNative( const google::api::expr::v1alpha1::Type::MapType& map_type) { auto native_key_type = ConvertProtoTypeToNative(map_type.key_type()); if (!native_key_type.ok()) { return native_key_type.status(); } auto native_value_type = ConvertProtoTypeToNative(map_type.value_type()); if (!native_value_type.ok()) { return native_value_type.status(); } return MapType(std::make_unique<Type>(*(std::move(native_key_type))), std::make_unique<Type>(*(std::move(native_value_type)))); } absl::StatusOr<FunctionType> ToNative( const google::api::expr::v1alpha1::Type::FunctionType& function_type) { std::vector<Type> arg_types; arg_types.reserve(function_type.arg_types_size()); for (const auto& arg_type : function_type.arg_types()) { auto native_arg = ConvertProtoTypeToNative(arg_type); if (!native_arg.ok()) { return native_arg.status(); } arg_types.emplace_back(*(std::move(native_arg))); } auto native_result = ConvertProtoTypeToNative(function_type.result_type()); if (!native_result.ok()) { return native_result.status(); } return FunctionType(std::make_unique<Type>(*(std::move(native_result))), std::move(arg_types)); } absl::StatusOr<AbstractType> ToNative( const google::api::expr::v1alpha1::Type::AbstractType& abstract_type) { std::vector<Type> parameter_types; for (const auto& parameter_type : abstract_type.parameter_types()) { auto native_parameter_type = ConvertProtoTypeToNative(parameter_type); if (!native_parameter_type.ok()) { return native_parameter_type.status(); } parameter_types.emplace_back(*(std::move(native_parameter_type))); } return AbstractType(abstract_type.name(), std::move(parameter_types)); } absl::StatusOr<Type> ConvertProtoTypeToNative( const google::api::expr::v1alpha1::Type& type) { switch (type.type_kind_case()) { case google::api::expr::v1alpha1::Type::kDyn: return Type(DynamicType()); case google::api::expr::v1alpha1::Type::kNull: return Type(nullptr); case google::api::expr::v1alpha1::Type::kPrimitive: { auto native_primitive = ToNative(type.primitive()); if (!native_primitive.ok()) { return native_primitive.status(); } return Type(*(std::move(native_primitive))); } case google::api::expr::v1alpha1::Type::kWrapper: { auto native_wrapper = ToNative(type.wrapper()); if (!native_wrapper.ok()) { return native_wrapper.status(); } return Type(PrimitiveTypeWrapper(*(std::move(native_wrapper)))); } case google::api::expr::v1alpha1::Type::kWellKnown: { auto native_well_known = ToNative(type.well_known()); if (!native_well_known.ok()) { return native_well_known.status(); } return Type(*std::move(native_well_known)); } case google::api::expr::v1alpha1::Type::kListType: { auto native_list_type = ToNative(type.list_type()); if (!native_list_type.ok()) { return native_list_type.status(); } return Type(*(std::move(native_list_type))); } case google::api::expr::v1alpha1::Type::kMapType: { auto native_map_type = ToNative(type.map_type()); if (!native_map_type.ok()) { return native_map_type.status(); } return Type(*(std::move(native_map_type))); } case google::api::expr::v1alpha1::Type::kFunction: { auto native_function = ToNative(type.function()); if (!native_function.ok()) { return native_function.status(); } return Type(*(std::move(native_function))); } case google::api::expr::v1alpha1::Type::kMessageType: return Type(MessageType(type.message_type())); case google::api::expr::v1alpha1::Type::kTypeParam: return Type(ParamType(type.type_param())); case google::api::expr::v1alpha1::Type::kType: { auto native_type = ConvertProtoTypeToNative(type.type()); if (!native_type.ok()) { return native_type.status(); } return Type(std::make_unique<Type>(*std::move(native_type))); } case google::api::expr::v1alpha1::Type::kError: return Type(ErrorType::kErrorTypeValue); case google::api::expr::v1alpha1::Type::kAbstractType: { auto native_abstract = ToNative(type.abstract_type()); if (!native_abstract.ok()) { return native_abstract.status(); } return Type(*(std::move(native_abstract))); } default: return absl::InvalidArgumentError( "Illegal type specified for google::api::expr::v1alpha1::Type."); } } absl::StatusOr<Reference> ConvertProtoReferenceToNative( const google::api::expr::v1alpha1::Reference& reference) { Reference ret_val; ret_val.set_name(reference.name()); ret_val.mutable_overload_id().reserve(reference.overload_id_size()); for (const auto& elem : reference.overload_id()) { ret_val.mutable_overload_id().emplace_back(elem); } if (reference.has_value()) { auto native_value = ConvertConstant(reference.value()); if (!native_value.ok()) { return native_value.status(); } ret_val.set_value(*(std::move(native_value))); } return ret_val; } absl::StatusOr<CheckedExpr> ConvertProtoCheckedExprToNative( const CheckedExprPb& checked_expr) { CheckedExpr ret_val; for (const auto& pair : checked_expr.reference_map()) { auto native_reference = ConvertProtoReferenceToNative(pair.second); if (!native_reference.ok()) { return native_reference.status(); } ret_val.mutable_reference_map().emplace(pair.first, *(std::move(native_reference))); } for (const auto& pair : checked_expr.type_map()) { auto native_type = ConvertProtoTypeToNative(pair.second); if (!native_type.ok()) { return native_type.status(); } ret_val.mutable_type_map().emplace(pair.first, *(std::move(native_type))); } auto native_source_info = ConvertProtoSourceInfoToNative(checked_expr.source_info()); if (!native_source_info.ok()) { return native_source_info.status(); } ret_val.set_source_info(*(std::move(native_source_info))); ret_val.set_expr_version(checked_expr.expr_version()); auto native_checked_expr = ConvertProtoExprToNative(checked_expr.expr()); if (!native_checked_expr.ok()) { return native_checked_expr.status(); } ret_val.set_expr(*(std::move(native_checked_expr))); return ret_val; } } namespace { using ::cel::ast_internal::AbstractType; using ::cel::ast_internal::Bytes; using ::cel::ast_internal::Call; using ::cel::ast_internal::Comprehension; using ::cel::ast_internal::Constant; using ::cel::ast_internal::CreateList; using ::cel::ast_internal::CreateStruct; using ::cel::ast_internal::DynamicType; using ::cel::ast_internal::ErrorType; using ::cel::ast_internal::Expr; using ::cel::ast_internal::Extension; using ::cel::ast_internal::FunctionType; using ::cel::ast_internal::Ident; using ::cel::ast_internal::ListType; using ::cel::ast_internal::MapType; using ::cel::ast_internal::MessageType; using ::cel::ast_internal::NullValue; using ::cel::ast_internal::ParamType; using ::cel::ast_internal::PrimitiveType; using ::cel::ast_internal::PrimitiveTypeWrapper; using ::cel::ast_internal::Reference; using ::cel::ast_internal::Select; using ::cel::ast_internal::SourceInfo; using ::cel::ast_internal::Type; using ::cel::ast_internal::WellKnownType; using ExprPb = google::api::expr::v1alpha1::Expr; using ParsedExprPb = google::api::expr::v1alpha1::ParsedExpr; using CheckedExprPb = google::api::expr::v1alpha1::CheckedExpr; using SourceInfoPb = google::api::expr::v1alpha1::SourceInfo; using ExtensionPb = google::api::expr::v1alpha1::SourceInfo::Extension; using ReferencePb = google::api::expr::v1alpha1::Reference; using TypePb = google::api::expr::v1alpha1::Type; struct ToProtoStackEntry { absl::Nonnull<const Expr*> source; absl::Nonnull<ExprPb*> dest; }; absl::Status ConstantToProto(const ast_internal::Constant& source, google::api::expr::v1alpha1::Constant& dest) { return absl::visit(absl::Overload( [&](absl::monostate) -> absl::Status { dest.clear_constant_kind(); return absl::OkStatus(); }, [&](NullValue) -> absl::Status { dest.set_null_value(google::protobuf::NULL_VALUE); return absl::OkStatus(); }, [&](bool value) { dest.set_bool_value(value); return absl::OkStatus(); }, [&](int64_t value) { dest.set_int64_value(value); return absl::OkStatus(); }, [&](uint64_t value) { dest.set_uint64_value(value); return absl::OkStatus(); }, [&](double value) { dest.set_double_value(value); return absl::OkStatus(); }, [&](const StringConstant& value) { dest.set_string_value(value); return absl::OkStatus(); }, [&](const BytesConstant& value) { dest.set_bytes_value(value); return absl::OkStatus(); }, [&](absl::Time time) { return cel::internal::EncodeTime( time, dest.mutable_timestamp_value()); }, [&](absl::Duration duration) { return cel::internal::EncodeDuration( duration, dest.mutable_duration_value()); }), source.constant_kind()); } absl::StatusOr<ExprPb> ExprToProto(const Expr& expr) { ExprPb proto_expr; CEL_RETURN_IF_ERROR(protobuf_internal::ExprToProto(expr, &proto_expr)); return proto_expr; } absl::StatusOr<SourceInfoPb> SourceInfoToProto(const SourceInfo& source_info) { SourceInfoPb result; result.set_syntax_version(source_info.syntax_version()); result.set_location(source_info.location()); for (int32_t line_offset : source_info.line_offsets()) { result.add_line_offsets(line_offset); } for (auto pos_iter = source_info.positions().begin(); pos_iter != source_info.positions().end(); ++pos_iter) { (*result.mutable_positions())[pos_iter->first] = pos_iter->second; } for (auto macro_iter = source_info.macro_calls().begin(); macro_iter != source_info.macro_calls().end(); ++macro_iter) { ExprPb& dest_macro = (*result.mutable_macro_calls())[macro_iter->first]; CEL_ASSIGN_OR_RETURN(dest_macro, ExprToProto(macro_iter->second)); } for (const auto& extension : source_info.extensions()) { auto* extension_pb = result.add_extensions(); extension_pb->set_id(extension.id()); auto* version_pb = extension_pb->mutable_version(); version_pb->set_major(extension.version().major()); version_pb->set_minor(extension.version().minor()); for (auto component : extension.affected_components()) { switch (component) { case Extension::Component::kParser: extension_pb->add_affected_components(ExtensionPb::COMPONENT_PARSER); break; case Extension::Component::kTypeChecker: extension_pb->add_affected_components( ExtensionPb::COMPONENT_TYPE_CHECKER); break; case Extension::Component::kRuntime: extension_pb->add_affected_components(ExtensionPb::COMPONENT_RUNTIME); break; default: extension_pb->add_affected_components( ExtensionPb::COMPONENT_UNSPECIFIED); break; } } } return result; } absl::StatusOr<ReferencePb> ReferenceToProto(const Reference& reference) { ReferencePb result; result.set_name(reference.name()); for (const auto& overload_id : reference.overload_id()) { result.add_overload_id(overload_id); } if (reference.has_value()) { CEL_RETURN_IF_ERROR( ConstantToProto(reference.value(), *result.mutable_value())); } return result; } absl::Status TypeToProto(const Type& type, TypePb* result); struct TypeKindToProtoVisitor { absl::Status operator()(PrimitiveType primitive) { switch (primitive) { case PrimitiveType::kPrimitiveTypeUnspecified: result->set_primitive(TypePb::PRIMITIVE_TYPE_UNSPECIFIED); return absl::OkStatus(); case PrimitiveType::kBool: result->set_primitive(TypePb::BOOL); return absl::OkStatus(); case PrimitiveType::kInt64: result->set_primitive(TypePb::INT64); return absl::OkStatus(); case PrimitiveType::kUint64: result->set_primitive(TypePb::UINT64); return absl::OkStatus(); case PrimitiveType::kDouble: result->set_primitive(TypePb::DOUBLE); return absl::OkStatus(); case PrimitiveType::kString: result->set_primitive(TypePb::STRING); return absl::OkStatus(); case PrimitiveType::kBytes: result->set_primitive(TypePb::BYTES); return absl::OkStatus(); default: break; } return absl::InvalidArgumentError("Unsupported primitive type"); } absl::Status operator()(PrimitiveTypeWrapper wrapper) { CEL_RETURN_IF_ERROR(this->operator()(wrapper.type())); auto wrapped = result->primitive(); result->set_wrapper(wrapped); return absl::OkStatus(); } absl::Status operator()(DynamicType) { result->mutable_dyn(); return absl::OkStatus(); } absl::Status operator()(ErrorType) { result->mutable_error(); return absl::OkStatus(); } absl::Status operator()(NullValue) { result->set_null(google::protobuf::NULL_VALUE); return absl::OkStatus(); } absl::Status operator()(const ListType& list_type) { return TypeToProto(list_type.elem_type(), result->mutable_list_type()->mutable_elem_type()); } absl::Status operator()(const MapType& map_type) { CEL_RETURN_IF_ERROR(TypeToProto( map_type.key_type(), result->mutable_map_type()->mutable_key_type())); return TypeToProto(map_type.value_type(), result->mutable_map_type()->mutable_value_type()); } absl::Status operator()(const MessageType& message_type) { result->set_message_type(message_type.type()); return absl::OkStatus(); } absl::Status operator()(const WellKnownType& well_known_type) { switch (well_known_type) { case WellKnownType::kWellKnownTypeUnspecified: result->set_well_known(TypePb::WELL_KNOWN_TYPE_UNSPECIFIED); return absl::OkStatus(); case WellKnownType::kAny: result->set_well_known(TypePb::ANY); return absl::OkStatus(); case WellKnownType::kDuration: result->set_well_known(TypePb::DURATION); return absl::OkStatus(); case WellKnownType::kTimestamp: result->set_well_known(TypePb::TIMESTAMP); return absl::OkStatus(); default: break; } return absl::InvalidArgumentError("Unsupported well-known type"); } absl::Status operator()(const FunctionType& function_type) { CEL_RETURN_IF_ERROR( TypeToProto(function_type.result_type(), result->mutable_function()->mutable_result_type())); for (const Type& arg_type : function_type.arg_types()) { CEL_RETURN_IF_ERROR( TypeToProto(arg_type, result->mutable_function()->add_arg_types())); } return absl::OkStatus(); } absl::Status operator()(const AbstractType& type) { auto* abstract_type_pb = result->mutable_abstract_type(); abstract_type_pb->set_name(type.name()); for (const Type& type_param : type.parameter_types()) { CEL_RETURN_IF_ERROR( TypeToProto(type_param, abstract_type_pb->add_parameter_types())); } return absl::OkStatus(); } absl::Status operator()(const std::unique_ptr<Type>& type_type) { return TypeToProto(*type_type, result->mutable_type()); } absl::Status operator()(const ParamType& param_type) { result->set_type_param(param_type.type()); return absl::OkStatus(); } TypePb* result; }; absl::Status TypeToProto(const Type& type, TypePb* result) { return absl::visit(TypeKindToProtoVisitor{result}, type.type_kind()); } } absl::StatusOr<std::unique_ptr<Ast>> CreateAstFromParsedExpr( const google::api::expr::v1alpha1::Expr& expr, const google::api::expr::v1alpha1::SourceInfo* source_info) { CEL_ASSIGN_OR_RETURN(auto runtime_expr, internal::ConvertProtoExprToNative(expr)); cel::ast_internal::SourceInfo runtime_source_info; if (source_info != nullptr) { CEL_ASSIGN_OR_RETURN( runtime_source_info, internal::ConvertProtoSourceInfoToNative(*source_info)); } return std::make_unique<cel::ast_internal::AstImpl>( std::move(runtime_expr), std::move(runtime_source_info)); } absl::StatusOr<std::unique_ptr<Ast>> CreateAstFromParsedExpr( const ParsedExprPb& parsed_expr) { CEL_ASSIGN_OR_RETURN(cel::ast_internal::ParsedExpr expr, internal::ConvertProtoParsedExprToNative(parsed_expr)); return std::make_unique<cel::ast_internal::AstImpl>(std::move(expr)); } absl::StatusOr<ParsedExprPb> CreateParsedExprFromAst(const Ast& ast) { const auto& ast_impl = ast_internal::AstImpl::CastFromPublicAst(ast); ParsedExprPb parsed_expr; CEL_ASSIGN_OR_RETURN(*parsed_expr.mutable_expr(), ExprToProto(ast_impl.root_expr())); CEL_ASSIGN_OR_RETURN(*parsed_expr.mutable_source_info(), SourceInfoToProto(ast_impl.source_info())); return parsed_expr; } absl::StatusOr<std::unique_ptr<Ast>> CreateAstFromCheckedExpr( const CheckedExprPb& checked_expr) { CEL_ASSIGN_OR_RETURN(cel::ast_internal::CheckedExpr expr, internal::ConvertProtoCheckedExprToNative(checked_expr)); return std::make_unique<cel::ast_internal::AstImpl>(std::move(expr)); } absl::StatusOr<google::api::expr::v1alpha1::CheckedExpr> CreateCheckedExprFromAst( const Ast& ast) { if (!ast.IsChecked()) { return absl::InvalidArgumentError("AST is not type-checked"); } const auto& ast_impl = ast_internal::AstImpl::CastFromPublicAst(ast); CheckedExprPb checked_expr; checked_expr.set_expr_version(ast_impl.expr_version()); CEL_ASSIGN_OR_RETURN(*checked_expr.mutable_expr(), ExprToProto(ast_impl.root_expr())); CEL_ASSIGN_OR_RETURN(*checked_expr.mutable_source_info(), SourceInfoToProto(ast_impl.source_info())); for (auto it = ast_impl.reference_map().begin(); it != ast_impl.reference_map().end(); ++it) { ReferencePb& dest_reference = (*checked_expr.mutable_reference_map())[it->first]; CEL_ASSIGN_OR_RETURN(dest_reference, ReferenceToProto(it->second)); } for (auto it = ast_impl.type_map().begin(); it != ast_impl.type_map().end(); ++it) { TypePb& dest_type = (*checked_expr.mutable_type_map())[it->first]; CEL_RETURN_IF_ERROR(TypeToProto(it->second, &dest_type)); } return checked_expr; } }
#include "extensions/protobuf/ast_converters.h" #include <cstdint> #include <memory> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/checked.pb.h" #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/timestamp.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "internal/proto_matchers.h" #include "internal/testing.h" #include "parser/options.h" #include "parser/parser.h" #include "google/protobuf/text_format.h" namespace cel::extensions { namespace internal { namespace { using ::cel::ast_internal::NullValue; using ::cel::ast_internal::PrimitiveType; using ::cel::ast_internal::WellKnownType; using cel::internal::StatusIs; TEST(AstConvertersTest, SourceInfoToNative) { google::api::expr::v1alpha1::SourceInfo source_info; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } )pb", &source_info)); auto native_source_info = ConvertProtoSourceInfoToNative(source_info); EXPECT_EQ(native_source_info->syntax_version(), "version"); EXPECT_EQ(native_source_info->location(), "location"); EXPECT_EQ(native_source_info->line_offsets(), std::vector<int32_t>({1, 2})); EXPECT_EQ(native_source_info->positions().at(1), 2); EXPECT_EQ(native_source_info->positions().at(3), 4); ASSERT_TRUE(native_source_info->macro_calls().at(1).has_ident_expr()); ASSERT_EQ(native_source_info->macro_calls().at(1).ident_expr().name(), "name"); } TEST(AstConvertersTest, ParsedExprToNative) { google::api::expr::v1alpha1::ParsedExpr parsed_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( expr { ident_expr { name: "name" } } source_info { syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } } )pb", &parsed_expr)); auto native_parsed_expr = ConvertProtoParsedExprToNative(parsed_expr); ASSERT_TRUE(native_parsed_expr->expr().has_ident_expr()); ASSERT_EQ(native_parsed_expr->expr().ident_expr().name(), "name"); auto& native_source_info = native_parsed_expr->source_info(); EXPECT_EQ(native_source_info.syntax_version(), "version"); EXPECT_EQ(native_source_info.location(), "location"); EXPECT_EQ(native_source_info.line_offsets(), std::vector<int32_t>({1, 2})); EXPECT_EQ(native_source_info.positions().at(1), 2); EXPECT_EQ(native_source_info.positions().at(3), 4); ASSERT_TRUE(native_source_info.macro_calls().at(1).has_ident_expr()); ASSERT_EQ(native_source_info.macro_calls().at(1).ident_expr().name(), "name"); } TEST(AstConvertersTest, PrimitiveTypeUnspecifiedToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::PRIMITIVE_TYPE_UNSPECIFIED); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kPrimitiveTypeUnspecified); } TEST(AstConvertersTest, PrimitiveTypeBoolToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::BOOL); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kBool); } TEST(AstConvertersTest, PrimitiveTypeInt64ToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::INT64); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kInt64); } TEST(AstConvertersTest, PrimitiveTypeUint64ToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::UINT64); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kUint64); } TEST(AstConvertersTest, PrimitiveTypeDoubleToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::DOUBLE); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kDouble); } TEST(AstConvertersTest, PrimitiveTypeStringToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::STRING); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kString); } TEST(AstConvertersTest, PrimitiveTypeBytesToNative) { google::api::expr::v1alpha1::Type type; type.set_primitive(google::api::expr::v1alpha1::Type::BYTES); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_primitive()); EXPECT_EQ(native_type->primitive(), PrimitiveType::kBytes); } TEST(AstConvertersTest, PrimitiveTypeError) { google::api::expr::v1alpha1::Type type; type.set_primitive(::google::api::expr::v1alpha1::Type_PrimitiveType(7)); auto native_type = ConvertProtoTypeToNative(type); EXPECT_EQ(native_type.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_THAT(native_type.status().message(), ::testing::HasSubstr("Illegal type specified for " "google::api::expr::v1alpha1::Type::PrimitiveType.")); } TEST(AstConvertersTest, WellKnownTypeUnspecifiedToNative) { google::api::expr::v1alpha1::Type type; type.set_well_known(google::api::expr::v1alpha1::Type::WELL_KNOWN_TYPE_UNSPECIFIED); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_well_known()); EXPECT_EQ(native_type->well_known(), WellKnownType::kWellKnownTypeUnspecified); } TEST(AstConvertersTest, WellKnownTypeAnyToNative) { google::api::expr::v1alpha1::Type type; type.set_well_known(google::api::expr::v1alpha1::Type::ANY); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_well_known()); EXPECT_EQ(native_type->well_known(), WellKnownType::kAny); } TEST(AstConvertersTest, WellKnownTypeTimestampToNative) { google::api::expr::v1alpha1::Type type; type.set_well_known(google::api::expr::v1alpha1::Type::TIMESTAMP); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_well_known()); EXPECT_EQ(native_type->well_known(), WellKnownType::kTimestamp); } TEST(AstConvertersTest, WellKnownTypeDuraionToNative) { google::api::expr::v1alpha1::Type type; type.set_well_known(google::api::expr::v1alpha1::Type::DURATION); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_well_known()); EXPECT_EQ(native_type->well_known(), WellKnownType::kDuration); } TEST(AstConvertersTest, WellKnownTypeError) { google::api::expr::v1alpha1::Type type; type.set_well_known(::google::api::expr::v1alpha1::Type_WellKnownType(4)); auto native_type = ConvertProtoTypeToNative(type); EXPECT_EQ(native_type.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_THAT(native_type.status().message(), ::testing::HasSubstr("Illegal type specified for " "google::api::expr::v1alpha1::Type::WellKnownType.")); } TEST(AstConvertersTest, ListTypeToNative) { google::api::expr::v1alpha1::Type type; type.mutable_list_type()->mutable_elem_type()->set_primitive( google::api::expr::v1alpha1::Type::BOOL); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_list_type()); auto& native_list_type = native_type->list_type(); ASSERT_TRUE(native_list_type.elem_type().has_primitive()); EXPECT_EQ(native_list_type.elem_type().primitive(), PrimitiveType::kBool); } TEST(AstConvertersTest, MapTypeToNative) { google::api::expr::v1alpha1::Type type; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( map_type { key_type { primitive: BOOL } value_type { primitive: DOUBLE } } )pb", &type)); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_map_type()); auto& native_map_type = native_type->map_type(); ASSERT_TRUE(native_map_type.key_type().has_primitive()); EXPECT_EQ(native_map_type.key_type().primitive(), PrimitiveType::kBool); ASSERT_TRUE(native_map_type.value_type().has_primitive()); EXPECT_EQ(native_map_type.value_type().primitive(), PrimitiveType::kDouble); } TEST(AstConvertersTest, FunctionTypeToNative) { google::api::expr::v1alpha1::Type type; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( function { result_type { primitive: BOOL } arg_types { primitive: DOUBLE } arg_types { primitive: STRING } } )pb", &type)); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_function()); auto& native_function_type = native_type->function(); ASSERT_TRUE(native_function_type.result_type().has_primitive()); EXPECT_EQ(native_function_type.result_type().primitive(), PrimitiveType::kBool); ASSERT_TRUE(native_function_type.arg_types().at(0).has_primitive()); EXPECT_EQ(native_function_type.arg_types().at(0).primitive(), PrimitiveType::kDouble); ASSERT_TRUE(native_function_type.arg_types().at(1).has_primitive()); EXPECT_EQ(native_function_type.arg_types().at(1).primitive(), PrimitiveType::kString); } TEST(AstConvertersTest, AbstractTypeToNative) { google::api::expr::v1alpha1::Type type; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( abstract_type { name: "name" parameter_types { primitive: DOUBLE } parameter_types { primitive: STRING } } )pb", &type)); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_abstract_type()); auto& native_abstract_type = native_type->abstract_type(); EXPECT_EQ(native_abstract_type.name(), "name"); ASSERT_TRUE(native_abstract_type.parameter_types().at(0).has_primitive()); EXPECT_EQ(native_abstract_type.parameter_types().at(0).primitive(), PrimitiveType::kDouble); ASSERT_TRUE(native_abstract_type.parameter_types().at(1).has_primitive()); EXPECT_EQ(native_abstract_type.parameter_types().at(1).primitive(), PrimitiveType::kString); } TEST(AstConvertersTest, DynamicTypeToNative) { google::api::expr::v1alpha1::Type type; type.mutable_dyn(); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_dyn()); } TEST(AstConvertersTest, NullTypeToNative) { google::api::expr::v1alpha1::Type type; type.set_null(google::protobuf::NULL_VALUE); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_null()); EXPECT_EQ(native_type->null(), nullptr); } TEST(AstConvertersTest, PrimitiveTypeWrapperToNative) { google::api::expr::v1alpha1::Type type; type.set_wrapper(google::api::expr::v1alpha1::Type::BOOL); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_wrapper()); EXPECT_EQ(native_type->wrapper(), PrimitiveType::kBool); } TEST(AstConvertersTest, MessageTypeToNative) { google::api::expr::v1alpha1::Type type; type.set_message_type("message"); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_message_type()); EXPECT_EQ(native_type->message_type().type(), "message"); } TEST(AstConvertersTest, ParamTypeToNative) { google::api::expr::v1alpha1::Type type; type.set_type_param("param"); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_type_param()); EXPECT_EQ(native_type->type_param().type(), "param"); } TEST(AstConvertersTest, NestedTypeToNative) { google::api::expr::v1alpha1::Type type; type.mutable_type()->mutable_dyn(); auto native_type = ConvertProtoTypeToNative(type); ASSERT_TRUE(native_type->has_type()); EXPECT_TRUE(native_type->type().has_dyn()); } TEST(AstConvertersTest, TypeError) { auto native_type = ConvertProtoTypeToNative(google::api::expr::v1alpha1::Type()); EXPECT_EQ(native_type.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_THAT(native_type.status().message(), ::testing::HasSubstr( "Illegal type specified for google::api::expr::v1alpha1::Type.")); } TEST(AstConvertersTest, ReferenceToNative) { google::api::expr::v1alpha1::Reference reference; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( name: "name" overload_id: "id1" overload_id: "id2" value { bool_value: true } )pb", &reference)); auto native_reference = ConvertProtoReferenceToNative(reference); EXPECT_EQ(native_reference->name(), "name"); EXPECT_EQ(native_reference->overload_id(), std::vector<std::string>({"id1", "id2"})); EXPECT_TRUE(native_reference->value().bool_value()); } TEST(AstConvertersTest, CheckedExprToNative) { google::api::expr::v1alpha1::CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( reference_map { key: 1 value { name: "name" overload_id: "id1" overload_id: "id2" value { bool_value: true } } } type_map { key: 1 value { dyn {} } } source_info { syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } } expr_version: "version" expr { ident_expr { name: "expr" } } )pb", &checked_expr)); auto native_checked_expr = ConvertProtoCheckedExprToNative(checked_expr); EXPECT_EQ(native_checked_expr->reference_map().at(1).name(), "name"); EXPECT_EQ(native_checked_expr->reference_map().at(1).overload_id(), std::vector<std::string>({"id1", "id2"})); EXPECT_TRUE(native_checked_expr->reference_map().at(1).value().bool_value()); auto& native_source_info = native_checked_expr->source_info(); EXPECT_EQ(native_source_info.syntax_version(), "version"); EXPECT_EQ(native_source_info.location(), "location"); EXPECT_EQ(native_source_info.line_offsets(), std::vector<int32_t>({1, 2})); EXPECT_EQ(native_source_info.positions().at(1), 2); EXPECT_EQ(native_source_info.positions().at(3), 4); ASSERT_TRUE(native_source_info.macro_calls().at(1).has_ident_expr()); ASSERT_EQ(native_source_info.macro_calls().at(1).ident_expr().name(), "name"); EXPECT_EQ(native_checked_expr->expr_version(), "version"); ASSERT_TRUE(native_checked_expr->expr().has_ident_expr()); EXPECT_EQ(native_checked_expr->expr().ident_expr().name(), "expr"); } } } namespace { using ::cel::internal::test::EqualsProto; using ::google::api::expr::parser::Parse; using testing::HasSubstr; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; using ParsedExprPb = google::api::expr::v1alpha1::ParsedExpr; using CheckedExprPb = google::api::expr::v1alpha1::CheckedExpr; using TypePb = google::api::expr::v1alpha1::Type; TEST(AstConvertersTest, CheckedExprToAst) { CheckedExprPb checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( reference_map { key: 1 value { name: "name" overload_id: "id1" overload_id: "id2" value { bool_value: true } } } type_map { key: 1 value { dyn {} } } source_info { syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } } expr_version: "version" expr { ident_expr { name: "expr" } } )pb", &checked_expr)); ASSERT_OK_AND_ASSIGN(auto ast, CreateAstFromCheckedExpr(checked_expr)); ASSERT_TRUE(ast->IsChecked()); } TEST(AstConvertersTest, AstToCheckedExprBasic) { ast_internal::Expr expr; expr.set_id(1); expr.mutable_ident_expr().set_name("expr"); ast_internal::SourceInfo source_info; source_info.set_syntax_version("version"); source_info.set_location("location"); source_info.mutable_line_offsets().push_back(1); source_info.mutable_line_offsets().push_back(2); source_info.mutable_positions().insert({1, 2}); source_info.mutable_positions().insert({3, 4}); ast_internal::Expr macro; macro.mutable_ident_expr().set_name("name"); source_info.mutable_macro_calls().insert({1, std::move(macro)}); absl::flat_hash_map<int64_t, ast_internal::Type> type_map; absl::flat_hash_map<int64_t, ast_internal::Reference> reference_map; ast_internal::Reference reference; reference.set_name("name"); reference.mutable_overload_id().push_back("id1"); reference.mutable_overload_id().push_back("id2"); reference.mutable_value().set_bool_value(true); ast_internal::Type type; type.set_type_kind(ast_internal::DynamicType()); ast_internal::CheckedExpr checked_expr; checked_expr.mutable_reference_map().insert({1, std::move(reference)}); checked_expr.mutable_type_map().insert({1, std::move(type)}); checked_expr.mutable_source_info() = std::move(source_info); checked_expr.set_expr_version("version"); checked_expr.mutable_expr() = std::move(expr); ast_internal::AstImpl ast(std::move(checked_expr)); ASSERT_OK_AND_ASSIGN(auto checked_pb, CreateCheckedExprFromAst(ast)); EXPECT_THAT(checked_pb, EqualsProto(R"pb( reference_map { key: 1 value { name: "name" overload_id: "id1" overload_id: "id2" value { bool_value: true } } } type_map { key: 1 value { dyn {} } } source_info { syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } } expr_version: "version" expr { id: 1 ident_expr { name: "expr" } } )pb")); } constexpr absl::string_view kTypesTestCheckedExpr = R"pb(reference_map: { key: 1 value: { name: "x" } } type_map: { key: 1 value: { primitive: INT64 } } source_info: { location: "<input>" line_offsets: 2 positions: { key: 1 value: 0 } } expr: { id: 1 ident_expr: { name: "x" } })pb"; struct CheckedExprToAstTypesTestCase { absl::string_view type; }; class CheckedExprToAstTypesTest : public testing::TestWithParam<CheckedExprToAstTypesTestCase> { public: void SetUp() override { ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kTypesTestCheckedExpr, &checked_expr_)); } protected: CheckedExprPb checked_expr_; }; TEST_P(CheckedExprToAstTypesTest, CheckedExprToAstTypes) { TypePb test_type; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(GetParam().type, &test_type)); (*checked_expr_.mutable_type_map())[1] = test_type; ASSERT_OK_AND_ASSIGN(auto ast, CreateAstFromCheckedExpr(checked_expr_)); EXPECT_THAT(CreateCheckedExprFromAst(*ast), IsOkAndHolds(EqualsProto(checked_expr_))); } INSTANTIATE_TEST_SUITE_P( Types, CheckedExprToAstTypesTest, testing::ValuesIn<CheckedExprToAstTypesTestCase>({ {R"pb(list_type { elem_type { primitive: INT64 } })pb"}, {R"pb(map_type { key_type { primitive: STRING } value_type { primitive: INT64 } })pb"}, {R"pb(message_type: "com.example.TestType")pb"}, {R"pb(primitive: BOOL)pb"}, {R"pb(primitive: INT64)pb"}, {R"pb(primitive: UINT64)pb"}, {R"pb(primitive: DOUBLE)pb"}, {R"pb(primitive: STRING)pb"}, {R"pb(primitive: BYTES)pb"}, {R"pb(wrapper: BOOL)pb"}, {R"pb(wrapper: INT64)pb"}, {R"pb(wrapper: UINT64)pb"}, {R"pb(wrapper: DOUBLE)pb"}, {R"pb(wrapper: STRING)pb"}, {R"pb(wrapper: BYTES)pb"}, {R"pb(well_known: TIMESTAMP)pb"}, {R"pb(well_known: DURATION)pb"}, {R"pb(well_known: ANY)pb"}, {R"pb(dyn {})pb"}, {R"pb(error {})pb"}, {R"pb(null: NULL_VALUE)pb"}, {R"pb( abstract_type { name: "MyType" parameter_types { primitive: INT64 } } )pb"}, {R"pb( type { primitive: INT64 } )pb"}, {R"pb(type_param: "T")pb"}, {R"pb( function { result_type { primitive: INT64 } arg_types { primitive: INT64 } } )pb"}, })); TEST(AstConvertersTest, ParsedExprToAst) { ParsedExprPb parsed_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( source_info { syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } } expr { ident_expr { name: "expr" } } )pb", &parsed_expr)); ASSERT_OK_AND_ASSIGN(auto ast, cel::extensions::CreateAstFromParsedExpr(parsed_expr)); } TEST(AstConvertersTest, AstToParsedExprBasic) { ast_internal::Expr expr; expr.set_id(1); expr.mutable_ident_expr().set_name("expr"); ast_internal::SourceInfo source_info; source_info.set_syntax_version("version"); source_info.set_location("location"); source_info.mutable_line_offsets().push_back(1); source_info.mutable_line_offsets().push_back(2); source_info.mutable_positions().insert({1, 2}); source_info.mutable_positions().insert({3, 4}); ast_internal::Expr macro; macro.mutable_ident_expr().set_name("name"); source_info.mutable_macro_calls().insert({1, std::move(macro)}); ast_internal::ParsedExpr parsed_expr; parsed_expr.mutable_source_info() = std::move(source_info); parsed_expr.mutable_expr() = std::move(expr); ast_internal::AstImpl ast(std::move(parsed_expr)); ASSERT_OK_AND_ASSIGN(auto checked_pb, CreateParsedExprFromAst(ast)); EXPECT_THAT(checked_pb, EqualsProto(R"pb( source_info { syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } } expr { id: 1 ident_expr { name: "expr" } } )pb")); } TEST(AstConvertersTest, ExprToAst) { google::api::expr::v1alpha1::Expr expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( ident_expr { name: "expr" } )pb", &expr)); ASSERT_OK_AND_ASSIGN(auto ast, cel::extensions::CreateAstFromParsedExpr(expr)); } TEST(AstConvertersTest, ExprAndSourceInfoToAst) { google::api::expr::v1alpha1::Expr expr; google::api::expr::v1alpha1::SourceInfo source_info; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( syntax_version: "version" location: "location" line_offsets: 1 line_offsets: 2 positions { key: 1 value: 2 } positions { key: 3 value: 4 } macro_calls { key: 1 value { ident_expr { name: "name" } } } )pb", &source_info)); ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( ident_expr { name: "expr" } )pb", &expr)); ASSERT_OK_AND_ASSIGN( auto ast, cel::extensions::CreateAstFromParsedExpr(expr, &source_info)); } TEST(AstConvertersTest, EmptyNodeRoundTrip) { ParsedExprPb parsed_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( expr { id: 1 select_expr { operand { id: 2 # no kind set. } field: "field" } } source_info {} )pb", &parsed_expr)); ASSERT_OK_AND_ASSIGN(auto ast, CreateAstFromParsedExpr(parsed_expr)); ASSERT_OK_AND_ASSIGN(ParsedExprPb copy, CreateParsedExprFromAst(*ast)); EXPECT_THAT(copy, EqualsProto(parsed_expr)); } TEST(AstConvertersTest, DurationConstantRoundTrip) { ParsedExprPb parsed_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( expr { id: 1 const_expr { # deprecated, but support existing ASTs. duration_value { seconds: 10 } } } source_info {} )pb", &parsed_expr)); ASSERT_OK_AND_ASSIGN(auto ast, CreateAstFromParsedExpr(parsed_expr)); ASSERT_OK_AND_ASSIGN(ParsedExprPb copy, CreateParsedExprFromAst(*ast)); EXPECT_THAT(copy, EqualsProto(parsed_expr)); } TEST(AstConvertersTest, TimestampConstantRoundTrip) { ParsedExprPb parsed_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( expr { id: 1 const_expr { # deprecated, but support existing ASTs. timestamp_value { seconds: 10 } } } source_info {} )pb", &parsed_expr)); ASSERT_OK_AND_ASSIGN(auto ast, CreateAstFromParsedExpr(parsed_expr)); ASSERT_OK_AND_ASSIGN(ParsedExprPb copy, CreateParsedExprFromAst(*ast)); EXPECT_THAT(copy, EqualsProto(parsed_expr)); } struct ConversionRoundTripCase { absl::string_view expr; }; class ConversionRoundTripTest : public testing::TestWithParam<ConversionRoundTripCase> { public: ConversionRoundTripTest() { options_.add_macro_calls = true; options_.enable_optional_syntax = true; } protected: ParserOptions options_; }; TEST_P(ConversionRoundTripTest, ParsedExprCopyable) { ASSERT_OK_AND_ASSIGN(ParsedExprPb parsed_expr, Parse(GetParam().expr, "<input>", options_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> ast, CreateAstFromParsedExpr(parsed_expr)); const auto& impl = ast_internal::AstImpl::CastFromPublicAst(*ast); EXPECT_THAT(CreateCheckedExprFromAst(impl), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("AST is not type-checked"))); EXPECT_THAT(CreateParsedExprFromAst(impl), IsOkAndHolds(EqualsProto(parsed_expr))); } TEST_P(ConversionRoundTripTest, CheckedExprCopyable) { ASSERT_OK_AND_ASSIGN(ParsedExprPb parsed_expr, Parse(GetParam().expr, "<input>", options_)); CheckedExprPb checked_expr; *checked_expr.mutable_expr() = parsed_expr.expr(); *checked_expr.mutable_source_info() = parsed_expr.source_info(); int64_t root_id = checked_expr.expr().id(); (*checked_expr.mutable_reference_map())[root_id].add_overload_id("_==_"); (*checked_expr.mutable_type_map())[root_id].set_primitive(TypePb::BOOL); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> ast, CreateAstFromCheckedExpr(checked_expr)); const auto& impl = ast_internal::AstImpl::CastFromPublicAst(*ast); EXPECT_THAT(CreateCheckedExprFromAst(impl), IsOkAndHolds(EqualsProto(checked_expr))); } INSTANTIATE_TEST_SUITE_P( ExpressionCases, ConversionRoundTripTest, testing::ValuesIn<ConversionRoundTripCase>( {{R"cel(null == null)cel"}, {R"cel(1 == 2)cel"}, {R"cel(1u == 2u)cel"}, {R"cel(1.1 == 2.1)cel"}, {R"cel(b"1" == b"2")cel"}, {R"cel("42" == "42")cel"}, {R"cel("s".startsWith("s") == true)cel"}, {R"cel([1, 2, 3] == [1, 2, 3])cel"}, {R"cel(TestAllTypes{single_int64: 42}.single_int64 == 42)cel"}, {R"cel([1, 2, 3].map(x, x + 2).size() == 3)cel"}, {R"cel({"a": 1, "b": 2}["a"] == 1)cel"}, {R"cel(ident == 42)cel"}, {R"cel(ident.field == 42)cel"}, {R"cel({?"abc": {}[?1]}.?abc.orValue(42) == 42)cel"}, {R"cel([1, 2, ?optional.none()].size() == 2)cel"}})); TEST(ExtensionConversionRoundTripTest, RoundTrip) { ParsedExprPb parsed_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( expr { id: 1 ident_expr { name: "unused" } } source_info { extensions { id: "extension" version { major: 1 minor: 2 } affected_components: COMPONENT_UNSPECIFIED affected_components: COMPONENT_PARSER affected_components: COMPONENT_TYPE_CHECKER affected_components: COMPONENT_RUNTIME } } )pb", &parsed_expr)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> ast, CreateAstFromParsedExpr(parsed_expr)); const auto& impl = ast_internal::AstImpl::CastFromPublicAst(*ast); EXPECT_THAT(CreateCheckedExprFromAst(impl), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("AST is not type-checked"))); EXPECT_THAT(CreateParsedExprFromAst(impl), IsOkAndHolds(EqualsProto(parsed_expr))); } } }
68
cpp
google/cel-cpp
bind_proto_to_activation
extensions/protobuf/bind_proto_to_activation.cc
extensions/protobuf/bind_proto_to_activation_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_BIND_PROTO_TO_ACTIVATION_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_BIND_PROTO_TO_ACTIVATION_H_ #include "absl/status/status.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "extensions/protobuf/internal/message.h" #include "extensions/protobuf/value.h" #include "internal/status_macros.h" #include "runtime/activation.h" #include "google/protobuf/descriptor.h" namespace cel::extensions { enum class BindProtoUnsetFieldBehavior { kBindDefaultValue, kSkip }; namespace protobuf_internal { absl::Status BindProtoToActivation( const google::protobuf::Descriptor& descriptor, const StructValue& struct_value, ValueManager& value_manager, Activation& activation, BindProtoUnsetFieldBehavior unset_field_behavior = BindProtoUnsetFieldBehavior::kSkip); } template <typename T> absl::Status BindProtoToActivation( const T& context, ValueManager& value_manager, Activation& activation, BindProtoUnsetFieldBehavior unset_field_behavior = BindProtoUnsetFieldBehavior::kSkip) { static_assert(protobuf_internal::IsProtoMessage<T>); CEL_ASSIGN_OR_RETURN(Value parent, ProtoMessageToValue(value_manager, context)); if (!InstanceOf<StructValue>(parent)) { return absl::InvalidArgumentError( absl::StrCat("context is a well-known type: ", context.GetTypeName())); } const StructValue& struct_value = Cast<StructValue>(parent); const google::protobuf::Descriptor* descriptor = context.GetDescriptor(); if (descriptor == nullptr) { return absl::InvalidArgumentError( absl::StrCat("context missing descriptor: ", context.GetTypeName())); } return protobuf_internal::BindProtoToActivation(*descriptor, struct_value, value_manager, activation, unset_field_behavior); } } #endif #include "extensions/protobuf/bind_proto_to_activation.h" #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/value.h" #include "internal/status_macros.h" #include "runtime/activation.h" #include "google/protobuf/descriptor.h" namespace cel::extensions::protobuf_internal { namespace { using ::google::protobuf::Descriptor; absl::StatusOr<bool> ShouldBindField( const google::protobuf::FieldDescriptor* field_desc, const StructValue& struct_value, BindProtoUnsetFieldBehavior unset_field_behavior, ValueManager& value_manager) { if (unset_field_behavior == BindProtoUnsetFieldBehavior::kBindDefaultValue || field_desc->is_repeated()) { return true; } return struct_value.HasFieldByNumber(field_desc->number()); } absl::StatusOr<Value> GetFieldValue(const google::protobuf::FieldDescriptor* field_desc, const StructValue& struct_value, ValueManager& value_manager) { if (field_desc->cpp_type() == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE && field_desc->message_type()->well_known_type() == Descriptor::WELLKNOWNTYPE_ANY) { CEL_ASSIGN_OR_RETURN(bool present, struct_value.HasFieldByNumber(field_desc->number())); if (!present) { return NullValue(); } } return struct_value.GetFieldByNumber(value_manager, field_desc->number()); } } absl::Status BindProtoToActivation( const Descriptor& descriptor, const StructValue& struct_value, ValueManager& value_manager, Activation& activation, BindProtoUnsetFieldBehavior unset_field_behavior) { for (int i = 0; i < descriptor.field_count(); i++) { const google::protobuf::FieldDescriptor* field_desc = descriptor.field(i); CEL_ASSIGN_OR_RETURN(bool should_bind, ShouldBindField(field_desc, struct_value, unset_field_behavior, value_manager)); if (!should_bind) { continue; } CEL_ASSIGN_OR_RETURN( Value field, GetFieldValue(field_desc, struct_value, value_manager)); activation.InsertOrAssignValue(field_desc->name(), std::move(field)); } return absl::OkStatus(); } }
#include "extensions/protobuf/bind_proto_to_activation.h" #include "google/protobuf/wrappers.pb.h" #include "absl/status/status.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/value.h" #include "common/value_testing.h" #include "extensions/protobuf/type_reflector.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "google/protobuf/arena.h" namespace cel::extensions { namespace { using ::cel::test::IntValueIs; using ::google::api::expr::test::v1::proto2::TestAllTypes; using testing::Eq; using testing::HasSubstr; using testing::Optional; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; class BindProtoToActivationTest : public common_internal::ThreadCompatibleValueTest<> { public: BindProtoToActivationTest() = default; }; TEST_P(BindProtoToActivationTest, BindProtoToActivation) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.set_single_int64(123); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "single_int64"), IsOkAndHolds(Optional(IntValueIs(123)))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationWktUnsupported) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); google::protobuf::Int64Value int64_value; int64_value.set_value(123); Activation activation; EXPECT_THAT( BindProtoToActivation(int64_value, value_factory.get(), activation), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("google.protobuf.Int64Value"))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationSkip) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.set_single_int64(123); Activation activation; ASSERT_OK(BindProtoToActivation(test_all_types, value_factory.get(), activation, BindProtoUnsetFieldBehavior::kSkip)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "single_int32"), IsOkAndHolds(Eq(absl::nullopt))); EXPECT_THAT(activation.FindVariable(value_factory.get(), "single_sint32"), IsOkAndHolds(Eq(absl::nullopt))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationDefault) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.set_single_int64(123); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation, BindProtoUnsetFieldBehavior::kBindDefaultValue)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "single_int32"), IsOkAndHolds(Optional(IntValueIs(-32)))); EXPECT_THAT(activation.FindVariable(value_factory.get(), "single_sint32"), IsOkAndHolds(Optional(IntValueIs(0)))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationDefaultAny) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.set_single_int64(123); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation, BindProtoUnsetFieldBehavior::kBindDefaultValue)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "single_any"), IsOkAndHolds(Optional(test::IsNullValue()))); } MATCHER_P(IsListValueOfSize, size, "") { const Value& v = arg; auto value = As<ListValue>(v); if (!value) { return false; } auto s = value->Size(); return s.ok() && *s == size; } TEST_P(BindProtoToActivationTest, BindProtoToActivationRepeated) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.add_repeated_int64(123); test_all_types.add_repeated_int64(456); test_all_types.add_repeated_int64(789); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "repeated_int64"), IsOkAndHolds(Optional(IsListValueOfSize(3)))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationRepeatedEmpty) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.set_single_int64(123); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "repeated_int32"), IsOkAndHolds(Optional(IsListValueOfSize(0)))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationRepeatedComplex) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; auto* nested = test_all_types.add_repeated_nested_message(); nested->set_bb(123); nested = test_all_types.add_repeated_nested_message(); nested->set_bb(456); nested = test_all_types.add_repeated_nested_message(); nested->set_bb(789); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT( activation.FindVariable(value_factory.get(), "repeated_nested_message"), IsOkAndHolds(Optional(IsListValueOfSize(3)))); } MATCHER_P(IsMapValueOfSize, size, "") { const Value& v = arg; auto value = As<MapValue>(v); if (!value) { return false; } auto s = value->Size(); return s.ok() && *s == size; } TEST_P(BindProtoToActivationTest, BindProtoToActivationMap) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; (*test_all_types.mutable_map_int64_int64())[1] = 2; (*test_all_types.mutable_map_int64_int64())[2] = 4; Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "map_int64_int64"), IsOkAndHolds(Optional(IsMapValueOfSize(2)))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationMapEmpty) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; test_all_types.set_single_int64(123); Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "map_int32_int32"), IsOkAndHolds(Optional(IsMapValueOfSize(0)))); } TEST_P(BindProtoToActivationTest, BindProtoToActivationMapComplex) { ProtoTypeReflector provider; ManagedValueFactory value_factory(provider, memory_manager()); TestAllTypes test_all_types; TestAllTypes::NestedMessage value; value.set_bb(42); (*test_all_types.mutable_map_int64_message())[1] = value; (*test_all_types.mutable_map_int64_message())[2] = value; Activation activation; ASSERT_OK( BindProtoToActivation(test_all_types, value_factory.get(), activation)); EXPECT_THAT(activation.FindVariable(value_factory.get(), "map_int64_message"), IsOkAndHolds(Optional(IsMapValueOfSize(2)))); } INSTANTIATE_TEST_SUITE_P(Runner, BindProtoToActivationTest, ::testing::Values(MemoryManagement::kReferenceCounting, MemoryManagement::kPooling)); } }
69
cpp
google/cel-cpp
memory_manager
extensions/protobuf/memory_manager.cc
extensions/protobuf/memory_manager_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_MEMORY_MANAGER_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_MEMORY_MANAGER_H_ #include <utility> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "common/memory.h" #include "google/protobuf/arena.h" namespace cel::extensions { MemoryManager ProtoMemoryManager(google::protobuf::Arena* arena); inline MemoryManager ProtoMemoryManagerRef(google::protobuf::Arena* arena) { return ProtoMemoryManager(arena); } absl::Nullable<google::protobuf::Arena*> ProtoMemoryManagerArena( MemoryManager memory_manager); template <typename T, typename... Args> ABSL_MUST_USE_RESULT T* NewInProtoArena(MemoryManager memory_manager, Args&&... args) { return google::protobuf::Arena::Create<T>(ProtoMemoryManagerArena(memory_manager), std::forward<Args>(args)...); } } #endif #include "extensions/protobuf/memory_manager.h" #include "absl/base/nullability.h" #include "common/memory.h" #include "google/protobuf/arena.h" namespace cel { namespace extensions { MemoryManagerRef ProtoMemoryManager(google::protobuf::Arena* arena) { return arena != nullptr ? MemoryManagerRef::Pooling(arena) : MemoryManagerRef::ReferenceCounting(); } absl::Nullable<google::protobuf::Arena*> ProtoMemoryManagerArena( MemoryManager memory_manager) { return memory_manager.arena(); } } }
#include "extensions/protobuf/memory_manager.h" #include "common/memory.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel::extensions { namespace { using testing::Eq; using testing::IsNull; using testing::NotNull; TEST(ProtoMemoryManager, MemoryManagement) { google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManager(&arena); EXPECT_EQ(memory_manager.memory_management(), MemoryManagement::kPooling); } TEST(ProtoMemoryManager, Arena) { google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManager(&arena); EXPECT_THAT(ProtoMemoryManagerArena(memory_manager), NotNull()); } TEST(ProtoMemoryManagerRef, MemoryManagement) { google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); EXPECT_EQ(memory_manager.memory_management(), MemoryManagement::kPooling); memory_manager = ProtoMemoryManagerRef(nullptr); EXPECT_EQ(memory_manager.memory_management(), MemoryManagement::kReferenceCounting); } TEST(ProtoMemoryManagerRef, Arena) { google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); EXPECT_THAT(ProtoMemoryManagerArena(memory_manager), Eq(&arena)); memory_manager = ProtoMemoryManagerRef(nullptr); EXPECT_THAT(ProtoMemoryManagerArena(memory_manager), IsNull()); } } }
70
cpp
google/cel-cpp
struct
extensions/protobuf/internal/struct.cc
extensions/protobuf/internal/struct_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_STRUCT_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_STRUCT_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/json.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<Json> DynamicValueProtoToJson(const google::protobuf::Message& message); absl::StatusOr<Json> DynamicListValueProtoToJson( const google::protobuf::Message& message); absl::StatusOr<Json> DynamicStructProtoToJson(const google::protobuf::Message& message); absl::Status DynamicValueProtoFromJson(const Json& json, google::protobuf::Message& message); absl::Status DynamicListValueProtoFromJson(const JsonArray& json, google::protobuf::Message& message); absl::Status DynamicStructProtoFromJson(const JsonObject& json, google::protobuf::Message& message); } #endif #include "extensions/protobuf/internal/struct.h" #include <string> #include <utility> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/functional/overload.h" #include "absl/log/absl_check.h" #include "absl/memory/memory.h" #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/types/variant.h" #include "common/json.h" #include "extensions/protobuf/internal/map_reflection.h" #include "extensions/protobuf/internal/struct_lite.h" #include "internal/status_macros.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/map_field.h" #include "google/protobuf/message.h" #include "google/protobuf/reflection.h" namespace cel::extensions::protobuf_internal { namespace { absl::StatusOr<absl::Nonnull<const google::protobuf::Descriptor*>> GetDescriptor( const google::protobuf::Message& message) { const auto* descriptor = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } return descriptor; } absl::StatusOr<absl::Nonnull<const google::protobuf::Reflection*>> GetReflection( const google::protobuf::Message& message) { const auto* reflection = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflection == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } return reflection; } absl::StatusOr<absl::Nonnull<const google::protobuf::FieldDescriptor*>> FindFieldByNumber( absl::Nonnull<const google::protobuf::Descriptor*> descriptor, int number) { const auto* field = descriptor->FindFieldByNumber(number); if (ABSL_PREDICT_FALSE(field == nullptr)) { return absl::InternalError( absl::StrCat(descriptor->full_name(), " missing descriptor for field number: ", number)); } return field; } absl::StatusOr<absl::Nonnull<const google::protobuf::OneofDescriptor*>> FindOneofByName( absl::Nonnull<const google::protobuf::Descriptor*> descriptor, absl::string_view name) { const auto* oneof = descriptor->FindOneofByName(name); if (ABSL_PREDICT_FALSE(oneof == nullptr)) { return absl::InternalError(absl::StrCat( descriptor->full_name(), " missing descriptor for oneof: ", name)); } return oneof; } absl::Status CheckFieldType(absl::Nonnull<const google::protobuf::FieldDescriptor*> field, google::protobuf::FieldDescriptor::CppType type) { if (ABSL_PREDICT_FALSE(field->cpp_type() != type)) { return absl::InternalError(absl::StrCat( field->full_name(), " has unexpected type: ", field->cpp_type_name())); } return absl::OkStatus(); } absl::Status CheckFieldSingular( absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { if (ABSL_PREDICT_FALSE(field->is_repeated() || field->is_map())) { return absl::InternalError(absl::StrCat( field->full_name(), " has unexpected cardinality: REPEATED")); } return absl::OkStatus(); } absl::Status CheckFieldRepeated( absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { if (ABSL_PREDICT_FALSE(!field->is_repeated() && !field->is_map())) { return absl::InternalError(absl::StrCat( field->full_name(), " has unexpected cardinality: SINGULAR")); } return absl::OkStatus(); } absl::Status CheckFieldMap( absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { if (ABSL_PREDICT_FALSE(!field->is_map())) { if (field->is_repeated()) { return absl::InternalError( absl::StrCat(field->full_name(), " has unexpected type: ", field->cpp_type_name())); } else { return absl::InternalError(absl::StrCat( field->full_name(), " has unexpected cardinality: SINGULAR")); } } return absl::OkStatus(); } absl::Status CheckFieldEnumType( absl::Nonnull<const google::protobuf::FieldDescriptor*> field, absl::string_view name) { CEL_RETURN_IF_ERROR( CheckFieldType(field, google::protobuf::FieldDescriptor::CPPTYPE_ENUM)); if (ABSL_PREDICT_FALSE(field->enum_type()->full_name() != name)) { return absl::InternalError(absl::StrCat( field->full_name(), " has unexpected type: ", field->enum_type()->full_name())); } return absl::OkStatus(); } absl::Status CheckFieldMessageType( absl::Nonnull<const google::protobuf::FieldDescriptor*> field, absl::string_view name) { CEL_RETURN_IF_ERROR( CheckFieldType(field, google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE)); if (ABSL_PREDICT_FALSE(field->message_type()->full_name() != name)) { return absl::InternalError(absl::StrCat( field->full_name(), " has unexpected type: ", field->message_type()->full_name())); } return absl::OkStatus(); } } absl::StatusOr<Json> DynamicValueProtoToJson(const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(message)); if (ABSL_PREDICT_TRUE(desc == google::protobuf::Value::descriptor())) { return GeneratedValueProtoToJson( google::protobuf::DownCastToGenerated<google::protobuf::Value>(message)); } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(message)); CEL_ASSIGN_OR_RETURN(const auto* kind_desc, FindOneofByName(desc, "kind")); const auto* value_desc = reflection->GetOneofFieldDescriptor(message, kind_desc); if (value_desc == nullptr) { return kJsonNull; } switch (value_desc->number()) { case google::protobuf::Value::kNullValueFieldNumber: CEL_RETURN_IF_ERROR( CheckFieldEnumType(value_desc, "google.protobuf.NullValue")); CEL_RETURN_IF_ERROR(CheckFieldSingular(value_desc)); return kJsonNull; case google::protobuf::Value::kNumberValueFieldNumber: CEL_RETURN_IF_ERROR( CheckFieldType(value_desc, google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE)); CEL_RETURN_IF_ERROR(CheckFieldSingular(value_desc)); return reflection->GetDouble(message, value_desc); case google::protobuf::Value::kStringValueFieldNumber: CEL_RETURN_IF_ERROR( CheckFieldType(value_desc, google::protobuf::FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldSingular(value_desc)); return reflection->GetCord(message, value_desc); case google::protobuf::Value::kBoolValueFieldNumber: CEL_RETURN_IF_ERROR( CheckFieldType(value_desc, google::protobuf::FieldDescriptor::CPPTYPE_BOOL)); CEL_RETURN_IF_ERROR(CheckFieldSingular(value_desc)); return reflection->GetBool(message, value_desc); case google::protobuf::Value::kStructValueFieldNumber: CEL_RETURN_IF_ERROR( CheckFieldMessageType(value_desc, "google.protobuf.Struct")); CEL_RETURN_IF_ERROR(CheckFieldSingular(value_desc)); return DynamicStructProtoToJson( reflection->GetMessage(message, value_desc)); case google::protobuf::Value::kListValueFieldNumber: CEL_RETURN_IF_ERROR( CheckFieldMessageType(value_desc, "google.protobuf.ListValue")); CEL_RETURN_IF_ERROR(CheckFieldSingular(value_desc)); return DynamicListValueProtoToJson( reflection->GetMessage(message, value_desc)); default: return absl::InternalError( absl::StrCat(value_desc->full_name(), " has unexpected number: ", value_desc->number())); } } absl::StatusOr<Json> DynamicListValueProtoToJson( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.ListValue"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(message)); if (ABSL_PREDICT_TRUE(desc == google::protobuf::ListValue::descriptor())) { return GeneratedListValueProtoToJson( google::protobuf::DownCastToGenerated<google::protobuf::ListValue>(message)); } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(message)); CEL_ASSIGN_OR_RETURN( const auto* values_field, FindFieldByNumber(desc, google::protobuf::ListValue::kValuesFieldNumber)); CEL_RETURN_IF_ERROR( CheckFieldMessageType(values_field, "google.protobuf.Value")); CEL_RETURN_IF_ERROR(CheckFieldRepeated(values_field)); const auto& repeated_field_ref = reflection->GetRepeatedFieldRef<google::protobuf::Message>(message, values_field); JsonArrayBuilder builder; builder.reserve(repeated_field_ref.size()); for (const auto& element : repeated_field_ref) { CEL_ASSIGN_OR_RETURN(auto value, DynamicValueProtoToJson(element)); builder.push_back(std::move(value)); } return std::move(builder).Build(); } absl::StatusOr<Json> DynamicStructProtoToJson(const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Struct"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(message)); if (ABSL_PREDICT_TRUE(desc == google::protobuf::Struct::descriptor())) { return GeneratedStructProtoToJson( google::protobuf::DownCastToGenerated<google::protobuf::Struct>(message)); } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(message)); CEL_ASSIGN_OR_RETURN( const auto* fields_field, FindFieldByNumber(desc, google::protobuf::Struct::kFieldsFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldMap(fields_field)); CEL_RETURN_IF_ERROR(CheckFieldType(fields_field->message_type()->map_key(), google::protobuf::FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldMessageType( fields_field->message_type()->map_value(), "google.protobuf.Value")); auto map_begin = protobuf_internal::MapBegin(*reflection, message, *fields_field); auto map_end = protobuf_internal::MapEnd(*reflection, message, *fields_field); JsonObjectBuilder builder; builder.reserve( protobuf_internal::MapSize(*reflection, message, *fields_field)); for (; map_begin != map_end; ++map_begin) { CEL_ASSIGN_OR_RETURN( auto value, DynamicValueProtoToJson(map_begin.GetValueRef().GetMessageValue())); builder.insert_or_assign(absl::Cord(map_begin.GetKey().GetStringValue()), std::move(value)); } return std::move(builder).Build(); } absl::Status DynamicValueProtoFromJson(const Json& json, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(message)); if (ABSL_PREDICT_TRUE(desc == google::protobuf::Value::descriptor())) { return GeneratedValueProtoFromJson( json, google::protobuf::DownCastToGenerated<google::protobuf::Value>(message)); } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(message)); return absl::visit( absl::Overload( [&message, &desc, &reflection](JsonNull) -> absl::Status { CEL_ASSIGN_OR_RETURN( const auto* null_value_field, FindFieldByNumber( desc, google::protobuf::Value::kNullValueFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldEnumType( null_value_field, "google.protobuf.NullValue")); CEL_RETURN_IF_ERROR(CheckFieldSingular(null_value_field)); reflection->SetEnumValue(&message, null_value_field, 0); return absl::OkStatus(); }, [&message, &desc, &reflection](JsonBool value) -> absl::Status { CEL_ASSIGN_OR_RETURN( const auto* bool_value_field, FindFieldByNumber( desc, google::protobuf::Value::kBoolValueFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldType( bool_value_field, google::protobuf::FieldDescriptor::CPPTYPE_BOOL)); CEL_RETURN_IF_ERROR(CheckFieldSingular(bool_value_field)); reflection->SetBool(&message, bool_value_field, value); return absl::OkStatus(); }, [&message, &desc, &reflection](JsonNumber value) -> absl::Status { CEL_ASSIGN_OR_RETURN( const auto* number_value_field, FindFieldByNumber( desc, google::protobuf::Value::kNumberValueFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldType( number_value_field, google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE)); CEL_RETURN_IF_ERROR(CheckFieldSingular(number_value_field)); reflection->SetDouble(&message, number_value_field, value); return absl::OkStatus(); }, [&message, &desc, &reflection](const JsonString& value) -> absl::Status { CEL_ASSIGN_OR_RETURN( const auto* string_value_field, FindFieldByNumber( desc, google::protobuf::Value::kStringValueFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldType( string_value_field, google::protobuf::FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldSingular(string_value_field)); reflection->SetString(&message, string_value_field, static_cast<std::string>(value)); return absl::OkStatus(); }, [&message, &desc, &reflection](const JsonArray& value) -> absl::Status { CEL_ASSIGN_OR_RETURN( const auto* list_value_field, FindFieldByNumber( desc, google::protobuf::Value::kListValueFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldMessageType( list_value_field, "google.protobuf.ListValue")); CEL_RETURN_IF_ERROR(CheckFieldSingular(list_value_field)); return DynamicListValueProtoFromJson( value, *reflection->MutableMessage(&message, list_value_field)); }, [&message, &desc, &reflection](const JsonObject& value) -> absl::Status { CEL_ASSIGN_OR_RETURN( const auto* struct_value_field, FindFieldByNumber( desc, google::protobuf::Value::kStructValueFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldMessageType( struct_value_field, "google.protobuf.Struct")); CEL_RETURN_IF_ERROR(CheckFieldSingular(struct_value_field)); return DynamicStructProtoFromJson( value, *reflection->MutableMessage(&message, struct_value_field)); }), json); } absl::Status DynamicListValueProtoFromJson(const JsonArray& json, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.ListValue"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(message)); if (ABSL_PREDICT_TRUE(desc == google::protobuf::ListValue::descriptor())) { return GeneratedListValueProtoFromJson( json, google::protobuf::DownCastToGenerated<google::protobuf::ListValue>(message)); } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(message)); CEL_ASSIGN_OR_RETURN( const auto* values_field, FindFieldByNumber(desc, google::protobuf::ListValue::kValuesFieldNumber)); CEL_RETURN_IF_ERROR( CheckFieldMessageType(values_field, "google.protobuf.Value")); CEL_RETURN_IF_ERROR(CheckFieldRepeated(values_field)); auto repeated_field_ref = reflection->GetMutableRepeatedFieldRef<google::protobuf::Message>(&message, values_field); repeated_field_ref.Clear(); for (const auto& element : json) { auto scratch = absl::WrapUnique(repeated_field_ref.NewMessage()); CEL_RETURN_IF_ERROR(DynamicValueProtoFromJson(element, *scratch)); repeated_field_ref.Add(*scratch); } return absl::OkStatus(); } absl::Status DynamicStructProtoFromJson(const JsonObject& json, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Struct"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(message)); if (ABSL_PREDICT_TRUE(desc == google::protobuf::Struct::descriptor())) { return GeneratedStructProtoFromJson( json, google::protobuf::DownCastToGenerated<google::protobuf::Struct>(message)); } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(message)); CEL_ASSIGN_OR_RETURN( const auto* fields_field, FindFieldByNumber(desc, google::protobuf::Struct::kFieldsFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldMap(fields_field)); CEL_RETURN_IF_ERROR(CheckFieldType(fields_field->message_type()->map_key(), google::protobuf::FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldMessageType( fields_field->message_type()->map_value(), "google.protobuf.Value")); for (const auto& entry : json) { google::protobuf::MapKey map_key; map_key.SetStringValue(static_cast<std::string>(entry.first)); google::protobuf::MapValueRef map_value; protobuf_internal::InsertOrLookupMapValue( *reflection, &message, *fields_field, map_key, &map_value); CEL_RETURN_IF_ERROR(DynamicValueProtoFromJson( entry.second, *map_value.MutableMessageValue())); } return absl::OkStatus(); } }
#include "extensions/protobuf/internal/struct.h" #include <memory> #include "google/protobuf/struct.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "common/json.h" #include "extensions/protobuf/internal/struct_lite.h" #include "internal/testing.h" #include "testutil/util.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor_database.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/text_format.h" namespace cel::extensions::protobuf_internal { namespace { using ::google::api::expr::testutil::EqualsProto; using testing::IsEmpty; using testing::VariantWith; using cel::internal::IsOkAndHolds; template <typename T> T ParseTextOrDie(absl::string_view text) { T proto; ABSL_CHECK(google::protobuf::TextFormat::ParseFromString(text, &proto)); return proto; } std::unique_ptr<google::protobuf::Message> ParseTextOrDie( absl::string_view text, const google::protobuf::Message& prototype) { auto message = absl::WrapUnique(prototype.New()); ABSL_CHECK(google::protobuf::TextFormat::ParseFromString(text, message.get())); return message; } TEST(Value, Generated) { google::protobuf::Value proto; EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonNull>(kJsonNull))); proto.set_null_value(google::protobuf::NULL_VALUE); EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonNull>(kJsonNull))); proto.Clear(); EXPECT_OK(GeneratedValueProtoFromJson(Json(), proto)); EXPECT_THAT(proto, EqualsProto(ParseTextOrDie<google::protobuf::Value>( R"pb(null_value: 0)pb"))); proto.set_bool_value(true); EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonBool>(true))); proto.Clear(); EXPECT_OK(GeneratedValueProtoFromJson(Json(true), proto)); EXPECT_THAT(proto, EqualsProto(ParseTextOrDie<google::protobuf::Value>( R"pb(bool_value: true)pb"))); proto.set_number_value(1.0); EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonNumber>(1.0))); proto.Clear(); EXPECT_OK(GeneratedValueProtoFromJson(Json(1.0), proto)); EXPECT_THAT(proto, EqualsProto(ParseTextOrDie<google::protobuf::Value>( R"pb(number_value: 1.0)pb"))); proto.set_string_value("foo"); EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonString>(JsonString("foo")))); proto.Clear(); EXPECT_OK(GeneratedValueProtoFromJson(Json(JsonString("foo")), proto)); EXPECT_THAT(proto, EqualsProto(ParseTextOrDie<google::protobuf::Value>( R"pb(string_value: "foo")pb"))); proto.mutable_list_value(); EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonArray>(IsEmpty()))); proto.Clear(); EXPECT_OK(GeneratedValueProtoFromJson(Json(JsonArray()), proto)); EXPECT_THAT(proto, EqualsProto(ParseTextOrDie<google::protobuf::Value>( R"pb(list_value: {})pb"))); proto.mutable_struct_value(); EXPECT_THAT(GeneratedValueProtoToJson(proto), IsOkAndHolds(VariantWith<JsonObject>(IsEmpty()))); proto.Clear(); EXPECT_OK(GeneratedValueProtoFromJson(Json(JsonObject()), proto)); EXPECT_THAT(proto, EqualsProto(ParseTextOrDie<google::protobuf::Value>( R"pb(struct_value: {})pb"))); } TEST(Value, Dynamic) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Value::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique( factory.GetPrototype(pool.FindMessageTypeByName("google.protobuf.Value")) ->New()); const auto* reflection = proto->GetReflection(); const auto* descriptor = proto->GetDescriptor(); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonNull>(kJsonNull))); reflection->SetEnumValue(proto.get(), descriptor->FindFieldByName("null_value"), 0); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonNull>(kJsonNull))); proto->Clear(); EXPECT_OK(DynamicValueProtoFromJson(Json(), *proto)); EXPECT_THAT(*proto, EqualsProto(*ParseTextOrDie(R"pb(null_value: 0)pb", *proto))); reflection->SetBool(proto.get(), descriptor->FindFieldByName("bool_value"), true); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonBool>(true))); proto->Clear(); EXPECT_OK(DynamicValueProtoFromJson(Json(true), *proto)); EXPECT_THAT(*proto, EqualsProto(*ParseTextOrDie(R"pb(bool_value: true)pb", *proto))); reflection->SetDouble(proto.get(), descriptor->FindFieldByName("number_value"), 1.0); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonNumber>(1.0))); proto->Clear(); EXPECT_OK(DynamicValueProtoFromJson(Json(1.0), *proto)); EXPECT_THAT(*proto, EqualsProto(*ParseTextOrDie(R"pb(number_value: 1.0)pb", *proto))); reflection->SetString(proto.get(), descriptor->FindFieldByName("string_value"), "foo"); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonString>(JsonString("foo")))); proto->Clear(); EXPECT_OK(DynamicValueProtoFromJson(Json(JsonString("foo")), *proto)); EXPECT_THAT(*proto, EqualsProto(*ParseTextOrDie(R"pb(string_value: "foo")pb", *proto))); reflection->MutableMessage( proto.get(), descriptor->FindFieldByName("list_value"), &factory); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonArray>(IsEmpty()))); proto->Clear(); EXPECT_OK(DynamicValueProtoFromJson(Json(JsonArray()), *proto)); EXPECT_THAT(*proto, EqualsProto(*ParseTextOrDie(R"pb(list_value: {})pb", *proto))); reflection->MutableMessage( proto.get(), descriptor->FindFieldByName("struct_value"), &factory); EXPECT_THAT(DynamicValueProtoToJson(*proto), IsOkAndHolds(VariantWith<JsonObject>(IsEmpty()))); EXPECT_OK(DynamicValueProtoFromJson(Json(JsonObject()), *proto)); EXPECT_THAT(*proto, EqualsProto(*ParseTextOrDie(R"pb(struct_value: {})pb", *proto))); } } }
71
cpp
google/cel-cpp
message
extensions/protobuf/internal/message.cc
extensions/protobuf/internal/message_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_MESSAGE_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_MESSAGE_H_ #include <cstddef> #include <memory> #include <type_traits> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/memory.h" #include "common/value.h" #include "common/value_manager.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { template <typename T> inline constexpr bool IsProtoMessage = std::conjunction_v<std::is_base_of<google::protobuf::Message, std::decay_t<T>>, std::negation<std::is_same<google::protobuf::Message, T>>>; template <typename T> struct ProtoMessageTraits { static_assert(IsProtoMessage<T>); static absl::Nonnull<google::protobuf::Message*> ArenaCopyConstruct( absl::Nonnull<google::protobuf::Arena*> arena, absl::Nonnull<const google::protobuf::Message*> from) { if constexpr (google::protobuf::Arena::is_arena_constructable<T>::value) { return google::protobuf::Arena::Create<T>(arena, *google::protobuf::DynamicCastToGenerated<T>(from)); } else { auto* to = google::protobuf::Arena::Create<T>(arena); *to = *google::protobuf::DynamicCastToGenerated<T>(from); return to; } } static absl::Nonnull<google::protobuf::Message*> CopyConstruct( absl::Nonnull<void*> address, absl::Nonnull<const google::protobuf::Message*> from) { return ::new (address) T(*google::protobuf::DynamicCastToGenerated<T>(from)); } static absl::Nonnull<google::protobuf::Message*> ArenaMoveConstruct( absl::Nonnull<google::protobuf::Arena*> arena, absl::Nonnull<google::protobuf::Message*> from) { if constexpr (google::protobuf::Arena::is_arena_constructable<T>::value) { return google::protobuf::Arena::Create<T>( arena, std::move(*google::protobuf::DynamicCastToGenerated<T>(from))); } else { auto* to = google::protobuf::Arena::Create<T>(arena); *to = std::move(*google::protobuf::DynamicCastToGenerated<T>(from)); return to; } } static absl::Nonnull<google::protobuf::Message*> MoveConstruct( absl::Nonnull<void*> address, absl::Nonnull<google::protobuf::Message*> from) { return ::new (address) T(std::move(*google::protobuf::DynamicCastToGenerated<T>(from))); } }; absl::StatusOr<absl::Nonnull<const google::protobuf::Descriptor*>> GetDescriptor( const google::protobuf::Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND); absl::StatusOr<absl::Nonnull<const google::protobuf::Reflection*>> GetReflection( const google::protobuf::Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND); ABSL_ATTRIBUTE_PURE_FUNCTION absl::Nonnull<const google::protobuf::Reflection*> GetReflectionOrDie( const google::protobuf::Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND); using ProtoMessageArenaCopyConstructor = absl::Nonnull<google::protobuf::Message*> (*)( absl::Nonnull<google::protobuf::Arena*>, absl::Nonnull<const google::protobuf::Message*>); using ProtoMessageCopyConstructor = absl::Nonnull<google::protobuf::Message*> (*)( absl::Nonnull<void*>, absl::Nonnull<const google::protobuf::Message*>); using ProtoMessageArenaMoveConstructor = absl::Nonnull<google::protobuf::Message*> (*)( absl::Nonnull<google::protobuf::Arena*>, absl::Nonnull<google::protobuf::Message*>); using ProtoMessageMoveConstructor = absl::Nonnull<google::protobuf::Message*> (*)( absl::Nonnull<void*>, absl::Nonnull<google::protobuf::Message*>); absl::StatusOr<Value> ProtoMessageToValueImpl( ValueManager& value_manager, absl::Nonnull<const google::protobuf::Message*> message, size_t size, size_t align, absl::Nonnull<ProtoMessageArenaCopyConstructor> arena_copy_construct, absl::Nonnull<ProtoMessageCopyConstructor> copy_construct); absl::StatusOr<Value> ProtoMessageToValueImpl( ValueManager& value_manager, absl::Nonnull<google::protobuf::Message*> message, size_t size, size_t align, absl::Nonnull<ProtoMessageArenaMoveConstructor> arena_move_construct, absl::Nonnull<ProtoMessageMoveConstructor> move_construct); absl::StatusOr<Value> ProtoMessageToValueImpl( ValueManager& value_manager, Shared<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message); StructValue ProtoMessageAsStructValueImpl( ValueFactory& value_factory, absl::Nonnull<google::protobuf::Message*> message); absl::StatusOr<Value> ProtoMessageToValueImpl( ValueFactory& value_factory, const TypeReflector& type_reflector, absl::Nonnull<const google::protobuf::Message*> prototype, const absl::Cord& serialized); absl::StatusOr<absl::Nonnull<google::protobuf::Message*>> ProtoMessageFromValueImpl( ValueView value, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, google::protobuf::Arena* arena); inline absl::StatusOr<absl::Nonnull<google::protobuf::Message*>> ProtoMessageFromValueImpl(ValueView value, google::protobuf::Arena* arena) { return ProtoMessageFromValueImpl( value, google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory(), arena); } absl::Status ProtoMessageFromValueImpl( ValueView value, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, absl::Nonnull<google::protobuf::Message*> message); inline absl::Status ProtoMessageFromValueImpl( ValueView value, absl::Nonnull<google::protobuf::Message*> message) { return ProtoMessageFromValueImpl( value, google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory(), message); } using ProtoMapKeyFromValueConverter = absl::Status (*)(ValueView, google::protobuf::MapKey&); absl::StatusOr<ProtoMapKeyFromValueConverter> GetProtoMapKeyFromValueConverter( google::protobuf::FieldDescriptor::CppType cpp_type); using ProtoMapValueFromValueConverter = absl::Status (*)(ValueView, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef&); absl::StatusOr<ProtoMapValueFromValueConverter> GetProtoMapValueFromValueConverter( absl::Nonnull<const google::protobuf::FieldDescriptor*> field); struct DefaultArenaDeleter { template <typename T> void operator()(T* message) const { if (arena == nullptr) { delete message; } } google::protobuf::Arena* arena = nullptr; }; template <typename T> using ArenaUniquePtr = std::unique_ptr<T, DefaultArenaDeleter>; } #endif #include "extensions/protobuf/internal/message.h" #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #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 "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/numeric/bits.h" #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/types/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "base/attribute.h" #include "base/internal/message_wrapper.h" #include "common/any.h" #include "common/casting.h" #include "common/internal/reference_count.h" #include "common/json.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_factory.h" #include "common/value_kind.h" #include "common/value_manager.h" #include "extensions/protobuf/internal/any.h" #include "extensions/protobuf/internal/duration.h" #include "extensions/protobuf/internal/json.h" #include "extensions/protobuf/internal/map_reflection.h" #include "extensions/protobuf/internal/qualify.h" #include "extensions/protobuf/internal/struct.h" #include "extensions/protobuf/internal/timestamp.h" #include "extensions/protobuf/internal/wrappers.h" #include "extensions/protobuf/json.h" #include "extensions/protobuf/memory_manager.h" #include "internal/align.h" #include "internal/casts.h" #include "internal/new.h" #include "internal/status_macros.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/map_field.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "google/protobuf/util/message_differencer.h" namespace cel { namespace extensions::protobuf_internal { namespace { class PooledParsedProtoStructValueInterface; class ParsedProtoListValueInterface; class ParsedProtoMapValueInterface; } } template <> struct NativeTypeTraits< extensions::protobuf_internal::PooledParsedProtoStructValueInterface> { static bool SkipDestructor(const extensions::protobuf_internal:: PooledParsedProtoStructValueInterface&) { return true; } }; template <> struct NativeTypeTraits< extensions::protobuf_internal::ParsedProtoListValueInterface> { static bool SkipDestructor( const extensions::protobuf_internal::ParsedProtoListValueInterface&) { return true; } }; template <> struct NativeTypeTraits< extensions::protobuf_internal::ParsedProtoMapValueInterface> { static bool SkipDestructor( const extensions::protobuf_internal::ParsedProtoMapValueInterface&) { return true; } }; namespace extensions::protobuf_internal { namespace { absl::StatusOr<absl::Nonnull<ArenaUniquePtr<google::protobuf::Message>>> NewProtoMessage( absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, absl::string_view name, google::protobuf::Arena* arena) { const auto* desc = pool->FindMessageTypeByName(name); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::NotFoundError( absl::StrCat("descriptor missing: `", name, "`")); } const auto* proto = factory->GetPrototype(desc); if (ABSL_PREDICT_FALSE(proto == nullptr)) { return absl::NotFoundError(absl::StrCat("prototype missing: `", name, "`")); } return ArenaUniquePtr<google::protobuf::Message>(proto->New(arena), DefaultArenaDeleter{arena}); } absl::Status ProtoMapKeyTypeMismatch(google::protobuf::FieldDescriptor::CppType expected, google::protobuf::FieldDescriptor::CppType got) { if (ABSL_PREDICT_FALSE(got != expected)) { return absl::InternalError( absl::StrCat("protocol buffer map key type mismatch: ", google::protobuf::FieldDescriptor::CppTypeName(expected), " vs ", google::protobuf::FieldDescriptor::CppTypeName(got))); } return absl::OkStatus(); } template <typename T> class AliasingValue : public T { public: template <typename U, typename... Args> explicit AliasingValue(Shared<U> alias, Args&&... args) : T(std::forward<Args>(args)...), alias_(std::move(alias)) {} private: Shared<const void> alias_; }; absl::Status ProtoBoolMapKeyFromValueConverter(ValueView value, google::protobuf::MapKey& key) { if (auto bool_value = As<BoolValueView>(value); bool_value) { key.SetBoolValue(bool_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } absl::Status ProtoInt32MapKeyFromValueConverter(ValueView value, google::protobuf::MapKey& key) { if (auto int_value = As<IntValueView>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int32_t>::min() || int_value->NativeValue() > std::numeric_limits<int32_t>::max()) { return absl::OutOfRangeError("int64 to int32_t overflow"); } key.SetInt32Value(static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoInt64MapKeyFromValueConverter(ValueView value, google::protobuf::MapKey& key) { if (auto int_value = As<IntValueView>(value); int_value) { key.SetInt64Value(int_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoUInt32MapKeyFromValueConverter(ValueView value, google::protobuf::MapKey& key) { if (auto uint_value = As<UintValueView>(value); uint_value) { if (uint_value->NativeValue() > std::numeric_limits<uint32_t>::max()) { return absl::OutOfRangeError("uint64 to uint32_t overflow"); } key.SetUInt32Value(static_cast<uint32_t>(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoUInt64MapKeyFromValueConverter(ValueView value, google::protobuf::MapKey& key) { if (auto uint_value = As<UintValueView>(value); uint_value) { key.SetUInt64Value(uint_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoStringMapKeyFromValueConverter(ValueView value, google::protobuf::MapKey& key) { if (auto string_value = As<StringValueView>(value); string_value) { key.SetStringValue(string_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } } absl::StatusOr<ProtoMapKeyFromValueConverter> GetProtoMapKeyFromValueConverter( google::protobuf::FieldDescriptor::CppType cpp_type) { switch (cpp_type) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return ProtoBoolMapKeyFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32MapKeyFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64MapKeyFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32MapKeyFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64MapKeyFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return ProtoStringMapKeyFromValueConverter; default: return absl::InvalidArgumentError( absl::StrCat("unexpected protocol buffer map key type: ", google::protobuf::FieldDescriptor::CppTypeName(cpp_type))); } } namespace { using ProtoMapKeyToValueConverter = absl::StatusOr<ValueView> (*)(const google::protobuf::MapKey&, ValueManager&, Value&); absl::StatusOr<ValueView> ProtoBoolMapKeyToValueConverter( const google::protobuf::MapKey& key, ValueManager&, Value&) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_BOOL, key.type())); return BoolValueView{key.GetBoolValue()}; } absl::StatusOr<ValueView> ProtoInt32MapKeyToValueConverter( const google::protobuf::MapKey& key, ValueManager&, Value&) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_INT32, key.type())); return IntValueView{key.GetInt32Value()}; } absl::StatusOr<ValueView> ProtoInt64MapKeyToValueConverter( const google::protobuf::MapKey& key, ValueManager&, Value&) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_INT64, key.type())); return IntValueView{key.GetInt64Value()}; } absl::StatusOr<ValueView> ProtoUInt32MapKeyToValueConverter( const google::protobuf::MapKey& key, ValueManager&, Value&) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_UINT32, key.type())); return UintValueView{key.GetUInt32Value()}; } absl::StatusOr<ValueView> ProtoUInt64MapKeyToValueConverter( const google::protobuf::MapKey& key, ValueManager&, Value&) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_UINT64, key.type())); return UintValueView{key.GetUInt64Value()}; } absl::StatusOr<ValueView> ProtoStringMapKeyToValueConverter( const google::protobuf::MapKey& key, ValueManager& value_manager, Value&) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_STRING, key.type())); return StringValueView{key.GetStringValue()}; } absl::StatusOr<ProtoMapKeyToValueConverter> GetProtoMapKeyToValueConverter( absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { ABSL_DCHECK(field->is_map()); const auto* key_field = field->message_type()->map_key(); switch (key_field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return ProtoBoolMapKeyToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32MapKeyToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64MapKeyToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32MapKeyToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64MapKeyToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return ProtoStringMapKeyToValueConverter; default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer map key type: ", google::protobuf::FieldDescriptor::CppTypeName(key_field->cpp_type()))); } } absl::Status ProtoBoolMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto bool_value = As<BoolValueView>(value); bool_value) { value_ref.SetBoolValue(bool_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } absl::Status ProtoInt32MapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto int_value = As<IntValueView>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int32_t>::min() || int_value->NativeValue() > std::numeric_limits<int32_t>::max()) { return absl::OutOfRangeError("int64 to int32_t overflow"); } value_ref.SetInt32Value(static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoInt64MapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto int_value = As<IntValueView>(value); int_value) { value_ref.SetInt64Value(int_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoUInt32MapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto uint_value = As<UintValueView>(value); uint_value) { if (uint_value->NativeValue() > std::numeric_limits<uint32_t>::max()) { return absl::OutOfRangeError("uint64 to uint32_t overflow"); } value_ref.SetUInt32Value(static_cast<uint32_t>(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoUInt64MapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto uint_value = As<UintValueView>(value); uint_value) { value_ref.SetUInt64Value(uint_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoFloatMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto double_value = As<DoubleValueView>(value); double_value) { value_ref.SetFloatValue(double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status ProtoDoubleMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto double_value = As<DoubleValueView>(value); double_value) { value_ref.SetDoubleValue(double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status ProtoBytesMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto bytes_value = As<BytesValueView>(value); bytes_value) { value_ref.SetStringValue(bytes_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bytes").NativeValue(); } absl::Status ProtoStringMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto string_value = As<StringValueView>(value); string_value) { value_ref.SetStringValue(string_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } absl::Status ProtoNullMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (InstanceOf<NullValueView>(value) || InstanceOf<IntValueView>(value)) { value_ref.SetEnumValue(0); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "google.protobuf.NullValue") .NativeValue(); } absl::Status ProtoEnumMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, google::protobuf::MapValueRef& value_ref) { if (auto int_value = As<IntValueView>(value); int_value) { if (int_value->NativeValue() < std::numeric_limits<int32_t>::min() || int_value->NativeValue() > std::numeric_limits<int32_t>::max()) { return absl::OutOfRangeError("int64 to int32_t overflow"); } value_ref.SetEnumValue(static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "enum").NativeValue(); } absl::Status ProtoMessageMapValueFromValueConverter( ValueView value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { return ProtoMessageFromValueImpl(value, value_ref.MutableMessageValue()); } } absl::StatusOr<ProtoMapValueFromValueConverter> GetProtoMapValueFromValueConverter( absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { ABSL_DCHECK(field->is_map()); const auto* value_field = field->message_type()->map_value(); switch (value_field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return ProtoBoolMapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32MapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64MapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32MapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64MapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return ProtoFloatMapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return ProtoDoubleMapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (value_field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { return ProtoBytesMapValueFromValueConverter; } return ProtoStringMapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: if (value_field->enum_type()->full_name() == "google.protobuf.NullValue") { return ProtoNullMapValueFromValueConverter; } return ProtoEnumMapValueFromValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageMapValueFromValueConverter; default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer map value type: ", google::protobuf::FieldDescriptor::CppTypeName(value_field->cpp_type()))); } } namespace { using ProtoMapValueToValueConverter = absl::StatusOr<ValueView> (*)( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*>, const google::protobuf::MapValueConstRef&, ValueManager&, Value&); absl::StatusOr<ValueView> ProtoBoolMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return BoolValueView{value_ref.GetBoolValue()}; } absl::StatusOr<ValueView> ProtoInt32MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return IntValueView{value_ref.GetInt32Value()}; } absl::StatusOr<ValueView> ProtoInt64MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return IntValueView{value_ref.GetInt64Value()}; } absl::StatusOr<ValueView> ProtoUInt32MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return UintValueView{value_ref.GetUInt32Value()}; } absl::StatusOr<ValueView> ProtoUInt64MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return UintValueView{value_ref.GetUInt64Value()}; } absl::StatusOr<ValueView> ProtoFloatMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return DoubleValueView{value_ref.GetFloatValue()}; } absl::StatusOr<ValueView> ProtoDoubleMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return DoubleValueView{value_ref.GetDoubleValue()}; } absl::StatusOr<ValueView> ProtoBytesMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return BytesValueView{value_ref.GetStringValue()}; } absl::StatusOr<ValueView> ProtoStringMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& value) { return StringValueView{value_ref.GetStringValue()}; } absl::StatusOr<ValueView> ProtoNullMapValueToValueConverter( SharedView<const
#include "extensions/protobuf/internal/message.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" namespace cel::extensions::protobuf_internal { namespace { using ::google::api::expr::test::v1::proto2::TestAllTypes; using testing::NotNull; using cel::internal::IsOkAndHolds; TEST(GetDescriptor, NotNull) { TestAllTypes message; EXPECT_THAT(GetDescriptor(message), IsOkAndHolds(NotNull())); } TEST(GetReflection, NotNull) { TestAllTypes message; EXPECT_THAT(GetReflection(message), IsOkAndHolds(NotNull())); } TEST(GetReflectionOrDie, DoesNotDie) { TestAllTypes message; EXPECT_THAT(GetReflectionOrDie(message), NotNull()); } } }
72
cpp
google/cel-cpp
field_mask
extensions/protobuf/internal/field_mask.cc
extensions/protobuf/internal/field_mask_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_FIELD_MASK_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_FIELD_MASK_H_ #include "absl/status/statusor.h" #include "common/json.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<JsonString> DynamicFieldMaskProtoToJsonString( const google::protobuf::Message& message); } #endif #include "extensions/protobuf/internal/field_mask.h" #include <string> #include "google/protobuf/field_mask.pb.h" #include "absl/base/optimization.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/str_join.h" #include "common/json.h" #include "extensions/protobuf/internal/field_mask_lite.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "google/protobuf/reflection.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<JsonString> DynamicFieldMaskProtoToJsonString( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.FieldMask"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (ABSL_PREDICT_TRUE(desc == google::protobuf::FieldMask::descriptor())) { return GeneratedFieldMaskProtoToJsonString( google::protobuf::DownCastToGenerated<google::protobuf::FieldMask>(message)); } const auto* reflection = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflection == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* paths_field = desc->FindFieldByNumber(google::protobuf::FieldMask::kPathsFieldNumber); if (ABSL_PREDICT_FALSE(paths_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing paths field descriptor")); } if (ABSL_PREDICT_FALSE(paths_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_STRING)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected paths field type: ", paths_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(!paths_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected paths field cardinality: UNKNOWN")); } return JsonString(absl::StrJoin( reflection->GetRepeatedFieldRef<std::string>(message, paths_field), ",")); } }
#include "extensions/protobuf/internal/field_mask.h" #include <memory> #include "google/protobuf/field_mask.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/memory/memory.h" #include "extensions/protobuf/internal/field_mask_lite.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor_database.h" #include "google/protobuf/dynamic_message.h" namespace cel::extensions::protobuf_internal { namespace { using testing::Eq; using cel::internal::IsOkAndHolds; TEST(FieldMask, GeneratedFromProto) { google::protobuf::FieldMask proto; proto.add_paths("foo"); proto.add_paths("bar"); EXPECT_THAT(GeneratedFieldMaskProtoToJsonString(proto), IsOkAndHolds(Eq(JsonString("foo,bar")))); } TEST(Any, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::FieldMask::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique( factory .GetPrototype(pool.FindMessageTypeByName("google.protobuf.FieldMask")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* paths_field = descriptor->FindFieldByName("paths"); ASSERT_NE(paths_field, nullptr); reflection->AddString(proto.get(), paths_field, "foo"); reflection->AddString(proto.get(), paths_field, "bar"); EXPECT_THAT(DynamicFieldMaskProtoToJsonString(*proto), IsOkAndHolds(Eq(JsonString("foo,bar")))); } } }
73
cpp
google/cel-cpp
timestamp
extensions/protobuf/internal/timestamp.cc
extensions/protobuf/internal/timestamp_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_TIMESTAMP_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_TIMESTAMP_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/time/time.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<absl::Time> UnwrapDynamicTimestampProto( const google::protobuf::Message& message); absl::Status WrapDynamicTimestampProto(absl::Time value, google::protobuf::Message& message); } #endif #include "extensions/protobuf/internal/timestamp.h" #include <cstdint> #include "google/protobuf/timestamp.pb.h" #include "absl/base/optimization.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/time/time.h" #include "extensions/protobuf/internal/timestamp_lite.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<absl::Time> UnwrapDynamicTimestampProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Timestamp"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (desc == google::protobuf::Timestamp::descriptor()) { return UnwrapGeneratedTimestampProto( google::protobuf::DownCastToGenerated<google::protobuf::Timestamp>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* seconds_field = desc->FindFieldByNumber(google::protobuf::Timestamp::kSecondsFieldNumber); if (ABSL_PREDICT_FALSE(seconds_field == nullptr)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " missing seconds field descriptor")); } if (ABSL_PREDICT_FALSE(seconds_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT64)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected seconds field type: ", seconds_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(seconds_field->is_map() || seconds_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", seconds_field->name(), " field cardinality: REPEATED")); } const auto* nanos_field = desc->FindFieldByNumber(google::protobuf::Timestamp::kNanosFieldNumber); if (ABSL_PREDICT_FALSE(nanos_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing nanos field descriptor")); } if (ABSL_PREDICT_FALSE(nanos_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT32)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected nanos field type: ", nanos_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(nanos_field->is_map() || nanos_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", nanos_field->name(), " field cardinality: REPEATED")); } return absl::UnixEpoch() + absl::Seconds(reflect->GetInt64(message, seconds_field)) + absl::Nanoseconds(reflect->GetInt32(message, nanos_field)); } absl::Status WrapDynamicTimestampProto(absl::Time value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Timestamp"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (ABSL_PREDICT_TRUE(desc == google::protobuf::Timestamp::descriptor())) { return WrapGeneratedTimestampProto( value, google::protobuf::DownCastToGenerated<google::protobuf::Timestamp>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* seconds_field = desc->FindFieldByNumber(google::protobuf::Timestamp::kSecondsFieldNumber); if (ABSL_PREDICT_FALSE(seconds_field == nullptr)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " missing seconds field descriptor")); } if (ABSL_PREDICT_FALSE(seconds_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT64)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected seconds field type: ", seconds_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(seconds_field->is_map() || seconds_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", seconds_field->name(), " field cardinality: REPEATED")); } const auto* nanos_field = desc->FindFieldByNumber(google::protobuf::Timestamp::kNanosFieldNumber); if (ABSL_PREDICT_FALSE(nanos_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing nanos field descriptor")); } if (ABSL_PREDICT_FALSE(nanos_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT32)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected nanos field type: ", nanos_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(nanos_field->is_map() || nanos_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", nanos_field->name(), " field cardinality: REPEATED")); } auto duration = value - absl::UnixEpoch(); reflect->SetInt64(&message, seconds_field, absl::IDivDuration(duration, absl::Seconds(1), &duration)); reflect->SetInt32(&message, nanos_field, static_cast<int32_t>(absl::IDivDuration( duration, absl::Nanoseconds(1), &duration))); return absl::OkStatus(); } }
#include "extensions/protobuf/internal/timestamp.h" #include <memory> #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/memory/memory.h" #include "absl/time/time.h" #include "extensions/protobuf/internal/timestamp_lite.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor_database.h" #include "google/protobuf/dynamic_message.h" namespace cel::extensions::protobuf_internal { namespace { using testing::Eq; using cel::internal::IsOkAndHolds; TEST(Timestamp, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedTimestampProto(google::protobuf::Timestamp()), IsOkAndHolds(Eq(absl::UnixEpoch()))); } TEST(Timestamp, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Timestamp::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicTimestampProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.Timestamp"))), IsOkAndHolds(Eq(absl::UnixEpoch()))); } TEST(Timestamp, GeneratedToProto) { google::protobuf::Timestamp proto; ASSERT_OK(WrapGeneratedTimestampProto( absl::UnixEpoch() + absl::Seconds(1) + absl::Nanoseconds(2), proto)); EXPECT_EQ(proto.seconds(), 1); EXPECT_EQ(proto.nanos(), 2); } TEST(Timestamp, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Timestamp::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique( factory .GetPrototype(pool.FindMessageTypeByName("google.protobuf.Timestamp")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* seconds_field = descriptor->FindFieldByName("seconds"); ASSERT_NE(seconds_field, nullptr); const auto* nanos_field = descriptor->FindFieldByName("nanos"); ASSERT_NE(nanos_field, nullptr); ASSERT_OK(WrapDynamicTimestampProto( absl::UnixEpoch() + absl::Seconds(1) + absl::Nanoseconds(2), *proto)); EXPECT_EQ(reflection->GetInt64(*proto, seconds_field), 1); EXPECT_EQ(reflection->GetInt32(*proto, nanos_field), 2); } } }
74
cpp
google/cel-cpp
ast
extensions/protobuf/internal/ast.cc
extensions/protobuf/internal/ast_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_AST_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_AST_H_ #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "common/ast.h" namespace cel::extensions::protobuf_internal { absl::Status ExprToProto(const Expr& expr, absl::Nonnull<google::api::expr::v1alpha1::Expr*> proto); absl::Status ExprFromProto(const google::api::expr::v1alpha1::Expr& proto, Expr& expr); } #endif #include "extensions/protobuf/internal/ast.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <stack> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/struct.pb.h" #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/types/variant.h" #include "common/ast.h" #include "common/constant.h" #include "extensions/protobuf/internal/constant.h" #include "internal/status_macros.h" namespace cel::extensions::protobuf_internal { namespace { using ExprProto = google::api::expr::v1alpha1::Expr; using ConstantProto = google::api::expr::v1alpha1::Constant; using StructExprProto = google::api::expr::v1alpha1::Expr::CreateStruct; class ExprToProtoState final { private: struct Frame final { absl::Nonnull<const Expr*> expr; absl::Nonnull<google::api::expr::v1alpha1::Expr*> proto; }; public: absl::Status ExprToProto(const Expr& expr, absl::Nonnull<google::api::expr::v1alpha1::Expr*> proto) { Push(expr, proto); Frame frame; while (Pop(frame)) { CEL_RETURN_IF_ERROR(ExprToProtoImpl(*frame.expr, frame.proto)); } return absl::OkStatus(); } private: absl::Status ExprToProtoImpl(const Expr& expr, absl::Nonnull<google::api::expr::v1alpha1::Expr*> proto) { return absl::visit( absl::Overload( [&expr, proto](const UnspecifiedExpr&) -> absl::Status { proto->Clear(); proto->set_id(expr.id()); return absl::OkStatus(); }, [this, &expr, proto](const Constant& const_expr) -> absl::Status { return ConstExprToProto(expr, const_expr, proto); }, [this, &expr, proto](const IdentExpr& ident_expr) -> absl::Status { return IdentExprToProto(expr, ident_expr, proto); }, [this, &expr, proto](const SelectExpr& select_expr) -> absl::Status { return SelectExprToProto(expr, select_expr, proto); }, [this, &expr, proto](const CallExpr& call_expr) -> absl::Status { return CallExprToProto(expr, call_expr, proto); }, [this, &expr, proto](const ListExpr& list_expr) -> absl::Status { return ListExprToProto(expr, list_expr, proto); }, [this, &expr, proto](const StructExpr& struct_expr) -> absl::Status { return StructExprToProto(expr, struct_expr, proto); }, [this, &expr, proto](const MapExpr& map_expr) -> absl::Status { return MapExprToProto(expr, map_expr, proto); }, [this, &expr, proto]( const ComprehensionExpr& comprehension_expr) -> absl::Status { return ComprehensionExprToProto(expr, comprehension_expr, proto); }), expr.kind()); } absl::Status ConstExprToProto(const Expr& expr, const Constant& const_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); proto->set_id(expr.id()); return ConstantToProto(const_expr, proto->mutable_const_expr()); } absl::Status IdentExprToProto(const Expr& expr, const IdentExpr& ident_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* ident_proto = proto->mutable_ident_expr(); proto->set_id(expr.id()); ident_proto->set_name(ident_expr.name()); return absl::OkStatus(); } absl::Status SelectExprToProto(const Expr& expr, const SelectExpr& select_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* select_proto = proto->mutable_select_expr(); proto->set_id(expr.id()); if (select_expr.has_operand()) { Push(select_expr.operand(), select_proto->mutable_operand()); } select_proto->set_field(select_expr.field()); select_proto->set_test_only(select_expr.test_only()); return absl::OkStatus(); } absl::Status CallExprToProto(const Expr& expr, const CallExpr& call_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* call_proto = proto->mutable_call_expr(); proto->set_id(expr.id()); if (call_expr.has_target()) { Push(call_expr.target(), call_proto->mutable_target()); } call_proto->set_function(call_expr.function()); if (!call_expr.args().empty()) { call_proto->mutable_args()->Reserve( static_cast<int>(call_expr.args().size())); for (const auto& argument : call_expr.args()) { Push(argument, call_proto->add_args()); } } return absl::OkStatus(); } absl::Status ListExprToProto(const Expr& expr, const ListExpr& list_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* list_proto = proto->mutable_list_expr(); proto->set_id(expr.id()); if (!list_expr.elements().empty()) { list_proto->mutable_elements()->Reserve( static_cast<int>(list_expr.elements().size())); for (size_t i = 0; i < list_expr.elements().size(); ++i) { const auto& element_expr = list_expr.elements()[i]; auto* element_proto = list_proto->add_elements(); if (element_expr.has_expr()) { Push(element_expr.expr(), element_proto); } if (element_expr.optional()) { list_proto->add_optional_indices(static_cast<int32_t>(i)); } } } return absl::OkStatus(); } absl::Status StructExprToProto(const Expr& expr, const StructExpr& struct_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* struct_proto = proto->mutable_struct_expr(); proto->set_id(expr.id()); struct_proto->set_message_name(struct_expr.name()); if (!struct_expr.fields().empty()) { struct_proto->mutable_entries()->Reserve( static_cast<int>(struct_expr.fields().size())); for (const auto& field_expr : struct_expr.fields()) { auto* field_proto = struct_proto->add_entries(); field_proto->set_id(field_expr.id()); field_proto->set_field_key(field_expr.name()); if (field_expr.has_value()) { Push(field_expr.value(), field_proto->mutable_value()); } if (field_expr.optional()) { field_proto->set_optional_entry(true); } } } return absl::OkStatus(); } absl::Status MapExprToProto(const Expr& expr, const MapExpr& map_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* map_proto = proto->mutable_struct_expr(); proto->set_id(expr.id()); if (!map_expr.entries().empty()) { map_proto->mutable_entries()->Reserve( static_cast<int>(map_expr.entries().size())); for (const auto& entry_expr : map_expr.entries()) { auto* entry_proto = map_proto->add_entries(); entry_proto->set_id(entry_expr.id()); if (entry_expr.has_key()) { Push(entry_expr.key(), entry_proto->mutable_map_key()); } if (entry_expr.has_value()) { Push(entry_expr.value(), entry_proto->mutable_value()); } if (entry_expr.optional()) { entry_proto->set_optional_entry(true); } } } return absl::OkStatus(); } absl::Status ComprehensionExprToProto( const Expr& expr, const ComprehensionExpr& comprehension_expr, absl::Nonnull<ExprProto*> proto) { proto->Clear(); auto* comprehension_proto = proto->mutable_comprehension_expr(); proto->set_id(expr.id()); comprehension_proto->set_iter_var(comprehension_expr.iter_var()); if (comprehension_expr.has_iter_range()) { Push(comprehension_expr.iter_range(), comprehension_proto->mutable_iter_range()); } comprehension_proto->set_accu_var(comprehension_expr.accu_var()); if (comprehension_expr.has_accu_init()) { Push(comprehension_expr.accu_init(), comprehension_proto->mutable_accu_init()); } if (comprehension_expr.has_loop_condition()) { Push(comprehension_expr.loop_condition(), comprehension_proto->mutable_loop_condition()); } if (comprehension_expr.has_loop_step()) { Push(comprehension_expr.loop_step(), comprehension_proto->mutable_loop_step()); } if (comprehension_expr.has_result()) { Push(comprehension_expr.result(), comprehension_proto->mutable_result()); } return absl::OkStatus(); } void Push(const Expr& expr, absl::Nonnull<ExprProto*> proto) { frames_.push(Frame{&expr, proto}); } bool Pop(Frame& frame) { if (frames_.empty()) { return false; } frame = frames_.top(); frames_.pop(); return true; } std::stack<Frame, std::vector<Frame>> frames_; }; class ExprFromProtoState final { private: struct Frame final { absl::Nonnull<const ExprProto*> proto; absl::Nonnull<Expr*> expr; }; public: absl::Status ExprFromProto(const ExprProto& proto, Expr& expr) { Push(proto, expr); Frame frame; while (Pop(frame)) { CEL_RETURN_IF_ERROR(ExprFromProtoImpl(*frame.proto, *frame.expr)); } return absl::OkStatus(); } private: absl::Status ExprFromProtoImpl(const ExprProto& proto, Expr& expr) { switch (proto.expr_kind_case()) { case ExprProto::EXPR_KIND_NOT_SET: expr.Clear(); expr.set_id(proto.id()); return absl::OkStatus(); case ExprProto::kConstExpr: return ConstExprFromProto(proto, proto.const_expr(), expr); case ExprProto::kIdentExpr: return IdentExprFromProto(proto, proto.ident_expr(), expr); case ExprProto::kSelectExpr: return SelectExprFromProto(proto, proto.select_expr(), expr); case ExprProto::kCallExpr: return CallExprFromProto(proto, proto.call_expr(), expr); case ExprProto::kListExpr: return ListExprFromProto(proto, proto.list_expr(), expr); case ExprProto::kStructExpr: if (proto.struct_expr().message_name().empty()) { return MapExprFromProto(proto, proto.struct_expr(), expr); } return StructExprFromProto(proto, proto.struct_expr(), expr); case ExprProto::kComprehensionExpr: return ComprehensionExprFromProto(proto, proto.comprehension_expr(), expr); default: return absl::InvalidArgumentError( absl::StrCat("unexpected ExprKindCase: ", static_cast<int>(proto.expr_kind_case()))); } } absl::Status ConstExprFromProto(const ExprProto& proto, const ConstantProto& const_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); return ConstantFromProto(const_proto, expr.mutable_const_expr()); } absl::Status IdentExprFromProto(const ExprProto& proto, const ExprProto::Ident& ident_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& ident_expr = expr.mutable_ident_expr(); ident_expr.set_name(ident_proto.name()); return absl::OkStatus(); } absl::Status SelectExprFromProto(const ExprProto& proto, const ExprProto::Select& select_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& select_expr = expr.mutable_select_expr(); if (select_proto.has_operand()) { Push(select_proto.operand(), select_expr.mutable_operand()); } select_expr.set_field(select_proto.field()); select_expr.set_test_only(select_proto.test_only()); return absl::OkStatus(); } absl::Status CallExprFromProto(const ExprProto& proto, const ExprProto::Call& call_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& call_expr = expr.mutable_call_expr(); call_expr.set_function(call_proto.function()); if (call_proto.has_target()) { Push(call_proto.target(), call_expr.mutable_target()); } call_expr.mutable_args().reserve( static_cast<size_t>(call_proto.args().size())); for (const auto& argument_proto : call_proto.args()) { Push(argument_proto, call_expr.add_args()); } return absl::OkStatus(); } absl::Status ListExprFromProto(const ExprProto& proto, const ExprProto::CreateList& list_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& list_expr = expr.mutable_list_expr(); list_expr.mutable_elements().reserve( static_cast<size_t>(list_proto.elements().size())); for (int i = 0; i < list_proto.elements().size(); ++i) { const auto& element_proto = list_proto.elements()[i]; auto& element_expr = list_expr.add_elements(); Push(element_proto, element_expr.mutable_expr()); const auto& optional_indicies_proto = list_proto.optional_indices(); element_expr.set_optional(std::find(optional_indicies_proto.begin(), optional_indicies_proto.end(), i) != optional_indicies_proto.end()); } return absl::OkStatus(); } absl::Status StructExprFromProto(const ExprProto& proto, const StructExprProto& struct_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& struct_expr = expr.mutable_struct_expr(); struct_expr.set_name(struct_proto.message_name()); struct_expr.mutable_fields().reserve( static_cast<size_t>(struct_proto.entries().size())); for (const auto& field_proto : struct_proto.entries()) { switch (field_proto.key_kind_case()) { case StructExprProto::Entry::KEY_KIND_NOT_SET: ABSL_FALLTHROUGH_INTENDED; case StructExprProto::Entry::kFieldKey: break; case StructExprProto::Entry::kMapKey: return absl::InvalidArgumentError("encountered map entry in struct"); default: return absl::InvalidArgumentError(absl::StrCat( "unexpected struct field kind: ", field_proto.key_kind_case())); } auto& field_expr = struct_expr.add_fields(); field_expr.set_id(field_proto.id()); field_expr.set_name(field_proto.field_key()); if (field_proto.has_value()) { Push(field_proto.value(), field_expr.mutable_value()); } field_expr.set_optional(field_proto.optional_entry()); } return absl::OkStatus(); } absl::Status MapExprFromProto(const ExprProto& proto, const ExprProto::CreateStruct& map_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& map_expr = expr.mutable_map_expr(); map_expr.mutable_entries().reserve( static_cast<size_t>(map_proto.entries().size())); for (const auto& entry_proto : map_proto.entries()) { switch (entry_proto.key_kind_case()) { case StructExprProto::Entry::KEY_KIND_NOT_SET: ABSL_FALLTHROUGH_INTENDED; case StructExprProto::Entry::kMapKey: break; case StructExprProto::Entry::kFieldKey: return absl::InvalidArgumentError("encountered struct field in map"); default: return absl::InvalidArgumentError(absl::StrCat( "unexpected map entry kind: ", entry_proto.key_kind_case())); } auto& entry_expr = map_expr.add_entries(); entry_expr.set_id(entry_proto.id()); if (entry_proto.has_map_key()) { Push(entry_proto.map_key(), entry_expr.mutable_key()); } if (entry_proto.has_value()) { Push(entry_proto.value(), entry_expr.mutable_value()); } entry_expr.set_optional(entry_proto.optional_entry()); } return absl::OkStatus(); } absl::Status ComprehensionExprFromProto( const ExprProto& proto, const ExprProto::Comprehension& comprehension_proto, Expr& expr) { expr.Clear(); expr.set_id(proto.id()); auto& comprehension_expr = expr.mutable_comprehension_expr(); comprehension_expr.set_iter_var(comprehension_proto.iter_var()); comprehension_expr.set_accu_var(comprehension_proto.accu_var()); if (comprehension_proto.has_iter_range()) { Push(comprehension_proto.iter_range(), comprehension_expr.mutable_iter_range()); } if (comprehension_proto.has_accu_init()) { Push(comprehension_proto.accu_init(), comprehension_expr.mutable_accu_init()); } if (comprehension_proto.has_loop_condition()) { Push(comprehension_proto.loop_condition(), comprehension_expr.mutable_loop_condition()); } if (comprehension_proto.has_loop_step()) { Push(comprehension_proto.loop_step(), comprehension_expr.mutable_loop_step()); } if (comprehension_proto.has_result()) { Push(comprehension_proto.result(), comprehension_expr.mutable_result()); } return absl::OkStatus(); } void Push(const ExprProto& proto, Expr& expr) { frames_.push(Frame{&proto, &expr}); } bool Pop(Frame& frame) { if (frames_.empty()) { return false; } frame = frames_.top(); frames_.pop(); return true; } std::stack<Frame, std::vector<Frame>> frames_; }; } absl::Status ExprToProto(const Expr& expr, absl::Nonnull<google::api::expr::v1alpha1::Expr*> proto) { ExprToProtoState state; return state.ExprToProto(expr, proto); } absl::Status ExprFromProto(const google::api::expr::v1alpha1::Expr& proto, Expr& expr) { ExprFromProtoState state; return state.ExprFromProto(proto, expr); } }
#include "extensions/protobuf/internal/ast.h" #include <string> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "common/ast.h" #include "internal/proto_matchers.h" #include "internal/testing.h" #include "google/protobuf/text_format.h" namespace cel::extensions::protobuf_internal { namespace { using ::cel::internal::test::EqualsProto; using cel::internal::IsOk; using cel::internal::StatusIs; using ExprProto = google::api::expr::v1alpha1::Expr; struct ExprRoundtripTestCase { std::string input; }; using ExprRoundTripTest = ::testing::TestWithParam<ExprRoundtripTestCase>; TEST_P(ExprRoundTripTest, RoundTrip) { const auto& test_case = GetParam(); ExprProto original_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(test_case.input, &original_proto)); Expr expr; ASSERT_THAT(ExprFromProto(original_proto, expr), IsOk()); ExprProto proto; ASSERT_THAT(ExprToProto(expr, &proto), IsOk()); EXPECT_THAT(proto, EqualsProto(original_proto)); } INSTANTIATE_TEST_SUITE_P( ExprRoundTripTest, ExprRoundTripTest, ::testing::ValuesIn<ExprRoundtripTestCase>({ {R"pb( )pb"}, {R"pb( id: 1 )pb"}, {R"pb( id: 1 const_expr {} )pb"}, {R"pb( id: 1 const_expr { null_value: NULL_VALUE } )pb"}, {R"pb( id: 1 const_expr { bool_value: true } )pb"}, {R"pb( id: 1 const_expr { int64_value: 1 } )pb"}, {R"pb( id: 1 const_expr { uint64_value: 1 } )pb"}, {R"pb( id: 1 const_expr { double_value: 1 } )pb"}, {R"pb( id: 1 const_expr { string_value: "foo" } )pb"}, {R"pb( id: 1 const_expr { bytes_value: "foo" } )pb"}, {R"pb( id: 1 const_expr { duration_value { seconds: 1 nanos: 1 } } )pb"}, {R"pb( id: 1 const_expr { timestamp_value { seconds: 1 nanos: 1 } } )pb"}, {R"pb( id: 1 ident_expr { name: "foo" } )pb"}, {R"pb( id: 1 select_expr { operand { id: 2 ident_expr { name: "bar" } } field: "foo" test_only: true } )pb"}, {R"pb( id: 1 call_expr { target { id: 2 ident_expr { name: "bar" } } function: "foo" args { id: 3 ident_expr { name: "baz" } } } )pb"}, {R"pb( id: 1 list_expr { elements { id: 2 ident_expr { name: "bar" } } elements { id: 3 ident_expr { name: "baz" } } optional_indices: 0 } )pb"}, {R"pb( id: 1 struct_expr { message_name: "google.type.Expr" entries { id: 2 field_key: "description" value { id: 3 const_expr { string_value: "foo" } } optional_entry: true } entries { id: 4 field_key: "expr" value { id: 5 const_expr { string_value: "bar" } } } } )pb"}, {R"pb( id: 1 struct_expr { entries { id: 2 map_key { id: 3 const_expr { string_value: "description" } } value { id: 4 const_expr { string_value: "foo" } } optional_entry: true } entries { id: 5 map_key { id: 6 const_expr { string_value: "expr" } } value { id: 7 const_expr { string_value: "foo" } } optional_entry: true } } )pb"}, {R"pb( id: 1 comprehension_expr { iter_var: "foo" iter_range { id: 2 list_expr {} } accu_var: "bar" accu_init { id: 3 list_expr {} } loop_condition { id: 4 const_expr { bool_value: true } } loop_step { id: 4 ident_expr { name: "bar" } } result { id: 5 ident_expr { name: "foo" } } } )pb"}, })); TEST(ExprFromProto, StructFieldInMap) { ExprProto original_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( id: 1 struct_expr: { entries: { id: 2 field_key: "foo" value: { id: 3 ident_expr: { name: "bar" } } } } )pb", &original_proto)); Expr expr; ASSERT_THAT(ExprFromProto(original_proto, expr), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExprFromProto, MapEntryInStruct) { ExprProto original_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( id: 1 struct_expr: { message_name: "some.Message" entries: { id: 2 map_key: { id: 3 ident_expr: { name: "foo" } } value: { id: 4 ident_expr: { name: "bar" } } } } )pb", &original_proto)); Expr expr; ASSERT_THAT(ExprFromProto(original_proto, expr), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
75
cpp
google/cel-cpp
wrappers
extensions/protobuf/internal/wrappers.cc
extensions/protobuf/internal/wrappers_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_WRAPPERS_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_WRAPPERS_H_ #include <cstdint> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<bool> UnwrapDynamicBoolValueProto( const google::protobuf::Message& message); absl::StatusOr<absl::Cord> UnwrapDynamicBytesValueProto( const google::protobuf::Message& message); absl::StatusOr<double> UnwrapDynamicFloatValueProto( const google::protobuf::Message& message); absl::StatusOr<double> UnwrapDynamicDoubleValueProto( const google::protobuf::Message& message); absl::StatusOr<int64_t> UnwrapDynamicInt32ValueProto( const google::protobuf::Message& message); absl::StatusOr<int64_t> UnwrapDynamicInt64ValueProto( const google::protobuf::Message& message); absl::StatusOr<absl::Cord> UnwrapDynamicStringValueProto( const google::protobuf::Message& message); absl::StatusOr<uint64_t> UnwrapDynamicUInt32ValueProto( const google::protobuf::Message& message); absl::StatusOr<uint64_t> UnwrapDynamicUInt64ValueProto( const google::protobuf::Message& message); absl::Status WrapDynamicBoolValueProto(bool value, google::protobuf::Message& message); absl::Status WrapDynamicBytesValueProto(const absl::Cord& value, google::protobuf::Message& message); absl::Status WrapDynamicFloatValueProto(float value, google::protobuf::Message& message); absl::Status WrapDynamicDoubleValueProto(double value, google::protobuf::Message& message); absl::Status WrapDynamicInt32ValueProto(int32_t value, google::protobuf::Message& message); absl::Status WrapDynamicInt64ValueProto(int64_t value, google::protobuf::Message& message); absl::Status WrapDynamicStringValueProto(const absl::Cord& value, google::protobuf::Message& message); absl::Status WrapDynamicUInt32ValueProto(uint32_t value, google::protobuf::Message& message); absl::Status WrapDynamicUInt64ValueProto(uint64_t value, google::protobuf::Message& message); } #endif #include "extensions/protobuf/internal/wrappers.h" #include <cstdint> #include <string> #include "google/protobuf/wrappers.pb.h" #include "absl/base/optimization.h" #include "absl/functional/function_ref.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "extensions/protobuf/internal/wrappers_lite.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { namespace { template <typename P> using FieldGetterRef = absl::FunctionRef<P(const google::protobuf::Reflection&, const google::protobuf::Message&, const google::protobuf::FieldDescriptor*)>; template <typename T, typename P> using GeneratedUnwrapperRef = absl::FunctionRef<absl::StatusOr<P>(const T&)>; template <typename P> using FieldSetterRef = absl::FunctionRef<void(const google::protobuf::Reflection&, google::protobuf::Message*, const google::protobuf::FieldDescriptor*, const P&)>; template <typename T, typename P> using GeneratedWrapperRef = absl::FunctionRef<absl::Status(const P&, T&)>; template <typename T, typename P> absl::StatusOr<P> UnwrapValueProto(const google::protobuf::Message& message, google::protobuf::FieldDescriptor::CppType cpp_type, GeneratedUnwrapperRef<T, P> unwrapper, FieldGetterRef<P> getter) { const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (ABSL_PREDICT_TRUE(desc == T::descriptor())) { return unwrapper(google::protobuf::DownCastToGenerated<T>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* value_field = desc->FindFieldByNumber(T::kValueFieldNumber); if (ABSL_PREDICT_FALSE(value_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing value field descriptor")); } if (ABSL_PREDICT_FALSE(value_field->cpp_type() != cpp_type)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected value field type: ", value_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(value_field->is_map() || value_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected value field cardinality: REPEATED")); } return getter(*reflect, message, value_field); } template <typename T, typename P> absl::Status WrapValueProto(google::protobuf::Message& message, const P& value, google::protobuf::FieldDescriptor::CppType cpp_type, GeneratedWrapperRef<T, P> wrapper, FieldSetterRef<P> setter) { const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (ABSL_PREDICT_TRUE(desc == T::descriptor())) { return wrapper(value, google::protobuf::DownCastToGenerated<T>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* value_field = desc->FindFieldByNumber(T::kValueFieldNumber); if (ABSL_PREDICT_FALSE(value_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing value field descriptor")); } if (ABSL_PREDICT_FALSE(value_field->cpp_type() != cpp_type)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected value field type: ", value_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(value_field->is_map() || value_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected value field cardinality: REPEATED")); } setter(*reflect, &message, value_field, value); return absl::OkStatus(); } } absl::StatusOr<bool> UnwrapDynamicBoolValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.BoolValue"); return UnwrapValueProto<google::protobuf::BoolValue, bool>( message, google::protobuf::FieldDescriptor::CPPTYPE_BOOL, UnwrapGeneratedBoolValueProto, &google::protobuf::Reflection::GetBool); } absl::StatusOr<absl::Cord> UnwrapDynamicBytesValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.BytesValue"); return UnwrapValueProto<google::protobuf::BytesValue, absl::Cord>( message, google::protobuf::FieldDescriptor::CPPTYPE_STRING, UnwrapGeneratedBytesValueProto, &google::protobuf::Reflection::GetCord); } absl::StatusOr<double> UnwrapDynamicFloatValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.FloatValue"); return UnwrapValueProto<google::protobuf::FloatValue, double>( message, google::protobuf::FieldDescriptor::CPPTYPE_FLOAT, UnwrapGeneratedFloatValueProto, &google::protobuf::Reflection::GetFloat); } absl::StatusOr<double> UnwrapDynamicDoubleValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.DoubleValue"); return UnwrapValueProto<google::protobuf::DoubleValue, double>( message, google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE, UnwrapGeneratedDoubleValueProto, &google::protobuf::Reflection::GetDouble); } absl::StatusOr<int64_t> UnwrapDynamicInt32ValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Int32Value"); return UnwrapValueProto<google::protobuf::Int32Value, int64_t>( message, google::protobuf::FieldDescriptor::CPPTYPE_INT32, UnwrapGeneratedInt32ValueProto, &google::protobuf::Reflection::GetInt32); } absl::StatusOr<int64_t> UnwrapDynamicInt64ValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Int64Value"); return UnwrapValueProto<google::protobuf::Int64Value, int64_t>( message, google::protobuf::FieldDescriptor::CPPTYPE_INT64, UnwrapGeneratedInt64ValueProto, &google::protobuf::Reflection::GetInt64); } absl::StatusOr<absl::Cord> UnwrapDynamicStringValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.StringValue"); return UnwrapValueProto<google::protobuf::StringValue, absl::Cord>( message, google::protobuf::FieldDescriptor::CPPTYPE_STRING, UnwrapGeneratedStringValueProto, &google::protobuf::Reflection::GetCord); } absl::StatusOr<uint64_t> UnwrapDynamicUInt32ValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.UInt32Value"); return UnwrapValueProto<google::protobuf::UInt32Value, uint64_t>( message, google::protobuf::FieldDescriptor::CPPTYPE_UINT32, UnwrapGeneratedUInt32ValueProto, &google::protobuf::Reflection::GetUInt32); } absl::StatusOr<uint64_t> UnwrapDynamicUInt64ValueProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.UInt64Value"); return UnwrapValueProto<google::protobuf::UInt64Value, uint64_t>( message, google::protobuf::FieldDescriptor::CPPTYPE_UINT64, UnwrapGeneratedUInt64ValueProto, &google::protobuf::Reflection::GetUInt64); } absl::Status WrapDynamicBoolValueProto(bool value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.BoolValue"); return WrapValueProto<google::protobuf::BoolValue, bool>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_BOOL, WrapGeneratedBoolValueProto, &google::protobuf::Reflection::SetBool); } absl::Status WrapDynamicBytesValueProto(const absl::Cord& value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.BytesValue"); return WrapValueProto<google::protobuf::BytesValue, absl::Cord>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_STRING, WrapGeneratedBytesValueProto, [](const google::protobuf::Reflection& reflection, google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, const absl::Cord& value) -> void { reflection.SetString(message, field, value); }); } absl::Status WrapDynamicFloatValueProto(float value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.FloatValue"); return WrapValueProto<google::protobuf::FloatValue, float>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_FLOAT, WrapGeneratedFloatValueProto, &google::protobuf::Reflection::SetFloat); } absl::Status WrapDynamicDoubleValueProto(double value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.DoubleValue"); return WrapValueProto<google::protobuf::DoubleValue, double>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE, WrapGeneratedDoubleValueProto, &google::protobuf::Reflection::SetDouble); } absl::Status WrapDynamicInt32ValueProto(int32_t value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Int32Value"); return WrapValueProto<google::protobuf::Int32Value, int32_t>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_INT32, WrapGeneratedInt32ValueProto, &google::protobuf::Reflection::SetInt32); } absl::Status WrapDynamicInt64ValueProto(int64_t value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Int64Value"); return WrapValueProto<google::protobuf::Int64Value, int64_t>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_INT64, WrapGeneratedInt64ValueProto, &google::protobuf::Reflection::SetInt64); } absl::Status WrapDynamicUInt32ValueProto(uint32_t value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.UInt32Value"); return WrapValueProto<google::protobuf::UInt32Value, uint32_t>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_UINT32, WrapGeneratedUInt32ValueProto, &google::protobuf::Reflection::SetUInt32); } absl::Status WrapDynamicUInt64ValueProto(uint64_t value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.UInt64Value"); return WrapValueProto<google::protobuf::UInt64Value, uint64_t>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_UINT64, WrapGeneratedUInt64ValueProto, &google::protobuf::Reflection::SetUInt64); } absl::Status WrapDynamicStringValueProto(const absl::Cord& value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.StringValue"); return WrapValueProto<google::protobuf::StringValue, absl::Cord>( message, value, google::protobuf::FieldDescriptor::CPPTYPE_STRING, WrapGeneratedStringValueProto, [](const google::protobuf::Reflection& reflection, google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, const absl::Cord& value) -> void { reflection.SetString(message, field, static_cast<std::string>(value)); }); } }
#include "extensions/protobuf/internal/wrappers.h" #include <limits> #include <memory> #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "extensions/protobuf/internal/wrappers_lite.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor_database.h" #include "google/protobuf/dynamic_message.h" namespace cel::extensions::protobuf_internal { namespace { using testing::Eq; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; TEST(BoolWrapper, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedBoolValueProto(google::protobuf::BoolValue()), IsOkAndHolds(Eq(false))); } TEST(BoolWrapper, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::BoolValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicBoolValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.BoolValue"))), IsOkAndHolds(Eq(false))); } TEST(BoolWrapper, GeneratedToProto) { google::protobuf::BoolValue proto; ASSERT_OK(WrapGeneratedBoolValueProto(true, proto)); EXPECT_TRUE(proto.value()); } TEST(BoolWrapper, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::BoolValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique( factory .GetPrototype(pool.FindMessageTypeByName("google.protobuf.BoolValue")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicBoolValueProto(true, *proto)); EXPECT_TRUE(reflection->GetBool(*proto, value_field)); } TEST(BytesWrapper, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedBytesValueProto(google::protobuf::BytesValue()), IsOkAndHolds(Eq(absl::Cord()))); } TEST(BytesWrapper, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::BytesValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicBytesValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.BytesValue"))), IsOkAndHolds(Eq(absl::Cord()))); } TEST(BytesWrapper, GeneratedToProto) { google::protobuf::BytesValue proto; ASSERT_OK(WrapGeneratedBytesValueProto(absl::Cord("foo"), proto)); EXPECT_EQ(proto.value(), "foo"); } TEST(BytesWrapper, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::BytesValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.BytesValue")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicBytesValueProto(absl::Cord("foo"), *proto)); EXPECT_EQ(reflection->GetString(*proto, value_field), "foo"); } TEST(DoubleWrapper, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedFloatValueProto(google::protobuf::FloatValue()), IsOkAndHolds(Eq(0.0f))); EXPECT_THAT(UnwrapGeneratedDoubleValueProto(google::protobuf::DoubleValue()), IsOkAndHolds(Eq(0.0))); } TEST(DoubleWrapper, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::DoubleValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicFloatValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.FloatValue"))), IsOkAndHolds(Eq(0.0f))); EXPECT_THAT(UnwrapDynamicDoubleValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.DoubleValue"))), IsOkAndHolds(Eq(0.0))); } TEST(DoubleWrapper, GeneratedToProto) { { google::protobuf::FloatValue proto; ASSERT_OK(WrapGeneratedFloatValueProto(1.0f, proto)); EXPECT_EQ(proto.value(), 1.0f); } { google::protobuf::DoubleValue proto; ASSERT_OK(WrapGeneratedDoubleValueProto(1.0, proto)); EXPECT_EQ(proto.value(), 1.0); } } TEST(DoubleWrapper, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::DoubleValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); { std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.FloatValue")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicFloatValueProto(1.0f, *proto)); EXPECT_EQ(reflection->GetFloat(*proto, value_field), 1.0f); } { std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.DoubleValue")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicDoubleValueProto(1.0, *proto)); EXPECT_EQ(reflection->GetDouble(*proto, value_field), 1.0); } } TEST(IntWrapper, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedInt32ValueProto(google::protobuf::Int32Value()), IsOkAndHolds(Eq(0))); EXPECT_THAT(UnwrapGeneratedInt64ValueProto(google::protobuf::Int64Value()), IsOkAndHolds(Eq(0))); } TEST(IntWrapper, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Int64Value::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicInt32ValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.Int32Value"))), IsOkAndHolds(Eq(0))); EXPECT_THAT(UnwrapDynamicInt64ValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.Int64Value"))), IsOkAndHolds(Eq(0))); } TEST(IntWrapper, GeneratedToProto) { { google::protobuf::Int32Value proto; ASSERT_OK(WrapGeneratedInt32ValueProto(1, proto)); EXPECT_EQ(proto.value(), 1); } { google::protobuf::Int64Value proto; ASSERT_OK(WrapGeneratedInt64ValueProto(1, proto)); EXPECT_EQ(proto.value(), 1); } } TEST(IntWrapper, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Int64Value::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); { std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.Int32Value")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicInt32ValueProto(1, *proto)); EXPECT_EQ(reflection->GetInt32(*proto, value_field), 1); } { std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.Int64Value")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicInt64ValueProto(1, *proto)); EXPECT_EQ(reflection->GetInt64(*proto, value_field), 1); } } TEST(StringWrapper, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedStringValueProto(google::protobuf::StringValue()), IsOkAndHolds(absl::Cord())); } TEST(StringWrapper, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::StringValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicStringValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.StringValue"))), IsOkAndHolds(absl::Cord())); } TEST(StringWrapper, GeneratedToProto) { google::protobuf::StringValue proto; ASSERT_OK(WrapGeneratedStringValueProto(absl::Cord("foo"), proto)); EXPECT_EQ(proto.value(), "foo"); } TEST(StringWrapper, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::StringValue::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.StringValue")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicStringValueProto(absl::Cord("foo"), *proto)); EXPECT_EQ(reflection->GetString(*proto, value_field), "foo"); } TEST(UintWrapper, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedUInt32ValueProto(google::protobuf::UInt32Value()), IsOkAndHolds(Eq(0u))); EXPECT_THAT(UnwrapGeneratedUInt64ValueProto(google::protobuf::UInt64Value()), IsOkAndHolds(Eq(0u))); } TEST(UintWrapper, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::UInt64Value::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicUInt32ValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.UInt32Value"))), IsOkAndHolds(Eq(0u))); EXPECT_THAT(UnwrapDynamicUInt64ValueProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.UInt64Value"))), IsOkAndHolds(Eq(0u))); } TEST(UintWrapper, GeneratedToProto) { { google::protobuf::UInt32Value proto; ASSERT_OK(WrapGeneratedUInt32ValueProto(1, proto)); EXPECT_EQ(proto.value(), 1); } { google::protobuf::UInt64Value proto; ASSERT_OK(WrapGeneratedUInt64ValueProto(1, proto)); EXPECT_EQ(proto.value(), 1); } } TEST(UintWrapper, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::UInt64Value::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); { std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.UInt32Value")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicUInt32ValueProto(1, *proto)); EXPECT_EQ(reflection->GetUInt32(*proto, value_field), 1); } { std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique(factory .GetPrototype(pool.FindMessageTypeByName( "google.protobuf.UInt64Value")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* value_field = descriptor->FindFieldByName("value"); ASSERT_NE(value_field, nullptr); ASSERT_OK(WrapDynamicUInt64ValueProto(1, *proto)); EXPECT_EQ(reflection->GetUInt64(*proto, value_field), 1); } } } }
76
cpp
google/cel-cpp
duration
extensions/protobuf/internal/duration.cc
extensions/protobuf/internal/duration_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_DURATION_H_ #define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_DURATION_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/time/time.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<absl::Duration> UnwrapDynamicDurationProto( const google::protobuf::Message& message); absl::Status WrapDynamicDurationProto(absl::Duration value, google::protobuf::Message& message); } #endif #include "extensions/protobuf/internal/duration.h" #include <cstdint> #include "google/protobuf/duration.pb.h" #include "absl/base/optimization.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/time/time.h" #include "extensions/protobuf/internal/duration_lite.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::extensions::protobuf_internal { absl::StatusOr<absl::Duration> UnwrapDynamicDurationProto( const google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Duration"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (desc == google::protobuf::Duration::descriptor()) { return UnwrapGeneratedDurationProto( google::protobuf::DownCastToGenerated<google::protobuf::Duration>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* seconds_field = desc->FindFieldByNumber(google::protobuf::Duration::kSecondsFieldNumber); if (ABSL_PREDICT_FALSE(seconds_field == nullptr)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " missing seconds field descriptor")); } if (ABSL_PREDICT_FALSE(seconds_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT64)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected seconds field type: ", seconds_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(seconds_field->is_map() || seconds_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", seconds_field->name(), " field cardinality: REPEATED")); } const auto* nanos_field = desc->FindFieldByNumber(google::protobuf::Duration::kNanosFieldNumber); if (ABSL_PREDICT_FALSE(nanos_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing nanos field descriptor")); } if (ABSL_PREDICT_FALSE(nanos_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT32)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected nanos field type: ", nanos_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(nanos_field->is_map() || nanos_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", nanos_field->name(), " field cardinality: REPEATED")); } return absl::Seconds(reflect->GetInt64(message, seconds_field)) + absl::Nanoseconds(reflect->GetInt32(message, nanos_field)); } absl::Status WrapDynamicDurationProto(absl::Duration value, google::protobuf::Message& message) { ABSL_DCHECK_EQ(message.GetTypeName(), "google.protobuf.Duration"); const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing descriptor")); } if (ABSL_PREDICT_TRUE(desc == google::protobuf::Duration::descriptor())) { return WrapGeneratedDurationProto( value, google::protobuf::DownCastToGenerated<google::protobuf::Duration>(message)); } const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing reflection")); } const auto* seconds_field = desc->FindFieldByNumber(google::protobuf::Duration::kSecondsFieldNumber); if (ABSL_PREDICT_FALSE(seconds_field == nullptr)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " missing seconds field descriptor")); } if (ABSL_PREDICT_FALSE(seconds_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT64)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected seconds field type: ", seconds_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(seconds_field->is_map() || seconds_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", seconds_field->name(), " field cardinality: REPEATED")); } const auto* nanos_field = desc->FindFieldByNumber(google::protobuf::Duration::kNanosFieldNumber); if (ABSL_PREDICT_FALSE(nanos_field == nullptr)) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " missing nanos field descriptor")); } if (ABSL_PREDICT_FALSE(nanos_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_INT32)) { return absl::InternalError(absl::StrCat( message.GetTypeName(), " has unexpected nanos field type: ", nanos_field->cpp_type_name())); } if (ABSL_PREDICT_FALSE(nanos_field->is_map() || nanos_field->is_repeated())) { return absl::InternalError( absl::StrCat(message.GetTypeName(), " has unexpected ", nanos_field->name(), " field cardinality: REPEATED")); } reflect->SetInt64(&message, seconds_field, absl::IDivDuration(value, absl::Seconds(1), &value)); reflect->SetInt32(&message, nanos_field, static_cast<int32_t>(absl::IDivDuration( value, absl::Nanoseconds(1), &value))); return absl::OkStatus(); } }
#include "extensions/protobuf/internal/duration.h" #include <memory> #include "google/protobuf/duration.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/memory/memory.h" #include "absl/time/time.h" #include "extensions/protobuf/internal/duration_lite.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor_database.h" #include "google/protobuf/dynamic_message.h" namespace cel::extensions::protobuf_internal { namespace { using testing::Eq; using cel::internal::IsOkAndHolds; TEST(Duration, GeneratedFromProto) { EXPECT_THAT(UnwrapGeneratedDurationProto(google::protobuf::Duration()), IsOkAndHolds(Eq(absl::ZeroDuration()))); } TEST(Duration, CustomFromProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Duration::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); EXPECT_THAT(UnwrapDynamicDurationProto(*factory.GetPrototype( pool.FindMessageTypeByName("google.protobuf.Duration"))), IsOkAndHolds(Eq(absl::ZeroDuration()))); } TEST(Duration, GeneratedToProto) { google::protobuf::Duration proto; ASSERT_OK(WrapGeneratedDurationProto(absl::Seconds(1) + absl::Nanoseconds(2), proto)); EXPECT_EQ(proto.seconds(), 1); EXPECT_EQ(proto.nanos(), 2); } TEST(Duration, CustomToProto) { google::protobuf::SimpleDescriptorDatabase database; { google::protobuf::FileDescriptorProto fd; google::protobuf::Duration::descriptor()->file()->CopyTo(&fd); ASSERT_TRUE(database.Add(fd)); } google::protobuf::DescriptorPool pool(&database); pool.AllowUnknownDependencies(); google::protobuf::DynamicMessageFactory factory(&pool); factory.SetDelegateToGeneratedFactory(false); std::unique_ptr<google::protobuf::Message> proto = absl::WrapUnique( factory .GetPrototype(pool.FindMessageTypeByName("google.protobuf.Duration")) ->New()); const auto* descriptor = proto->GetDescriptor(); const auto* reflection = proto->GetReflection(); const auto* seconds_field = descriptor->FindFieldByName("seconds"); ASSERT_NE(seconds_field, nullptr); const auto* nanos_field = descriptor->FindFieldByName("nanos"); ASSERT_NE(nanos_field, nullptr); ASSERT_OK(WrapDynamicDurationProto(absl::Seconds(1) + absl::Nanoseconds(2), *proto)); EXPECT_EQ(reflection->GetInt64(*proto, seconds_field), 1); EXPECT_EQ(reflection->GetInt32(*proto, nanos_field), 2); } } }
77
cpp
google/cel-cpp
instrumentation
eval/compiler/instrumentation.cc
eval/compiler/instrumentation_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_INSTRUMENTATION_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_INSTRUMENTATION_H_ #include <cstdint> #include <functional> #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "base/ast_internal/ast_impl.h" #include "common/value.h" #include "eval/compiler/flat_expr_builder_extensions.h" namespace google::api::expr::runtime { using Instrumentation = std::function<absl::Status(int64_t expr_id, const cel::Value&)>; using InstrumentationFactory = absl::AnyInvocable<Instrumentation( const cel::ast_internal::AstImpl&) const>; ProgramOptimizerFactory CreateInstrumentationExtension( InstrumentationFactory factory); } #endif #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->As<IntValue>().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->As<cel::BoolValue>().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)); } } }
78
cpp
google/cel-cpp
flat_expr_builder
eval/compiler/flat_expr_builder.cc
eval/compiler/flat_expr_builder_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "base/ast.h" #include "eval/compiler/flat_expr_builder_extensions.h" #include "eval/eval/evaluator_core.h" #include "eval/public/cel_type_registry.h" #include "runtime/function_registry.h" #include "runtime/runtime_issue.h" #include "runtime/runtime_options.h" #include "runtime/type_registry.h" namespace google::api::expr::runtime { class FlatExprBuilder { public: FlatExprBuilder(const cel::FunctionRegistry& function_registry, const CelTypeRegistry& type_registry, const cel::RuntimeOptions& options) : options_(options), container_(options.container), function_registry_(function_registry), type_registry_(type_registry.InternalGetModernRegistry()) {} FlatExprBuilder(const cel::FunctionRegistry& function_registry, const cel::TypeRegistry& type_registry, const cel::RuntimeOptions& options) : options_(options), container_(options.container), function_registry_(function_registry), type_registry_(type_registry) {} FlatExprBuilder(const cel::FunctionRegistry& function_registry, const CelTypeRegistry& type_registry) : options_(cel::RuntimeOptions()), function_registry_(function_registry), type_registry_(type_registry.InternalGetModernRegistry()) {} void AddAstTransform(std::unique_ptr<AstTransform> transform) { ast_transforms_.push_back(std::move(transform)); } void AddProgramOptimizer(ProgramOptimizerFactory optimizer) { program_optimizers_.push_back(std::move(optimizer)); } void set_container(std::string container) { container_ = std::move(container); } absl::StatusOr<FlatExpression> CreateExpressionImpl( std::unique_ptr<cel::Ast> ast, std::vector<cel::RuntimeIssue>* issues) const; const cel::RuntimeOptions& options() const { return options_; } void enable_optional_types() { enable_optional_types_ = true; } private: cel::RuntimeOptions options_; std::string container_; bool enable_optional_types_ = false; const cel::FunctionRegistry& function_registry_; const cel::TypeRegistry& type_registry_; std::vector<std::unique_ptr<AstTransform>> ast_transforms_; std::vector<ProgramOptimizerFactory> program_optimizers_; }; } #endif #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/str_cat.h" #include "absl/strings/string_view.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(); } 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), parent_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; } program_builder_.EnterSubexpression(&expr); parent_expr_ = &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())); } } 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 (!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}; } } } 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(CreateCheckLazyInitStep(slot.slot, slot.subexpression + 1, expr.id())); AddStep(CreateAssignSlotStep(slot.slot)); } 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 { 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::InvalidArgumentErro
#include "eval/compiler/flat_expr_builder.h" #include <cstddef> #include <fstream> #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 "google/protobuf/text_format.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/str_format.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 ::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; using cel::internal::StatusIs; 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));
79
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
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_CEL_EXPRESSION_BUILDER_FLAT_IMPL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_CEL_EXPRESSION_BUILDER_FLAT_IMPL_H_ #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 "absl/status/status.h" #include "absl/status/statusor.h" #include "base/ast.h" #include "eval/compiler/flat_expr_builder.h" #include "eval/public/cel_expression.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { class CelExpressionBuilderFlatImpl : public CelExpressionBuilder { public: explicit CelExpressionBuilderFlatImpl(const cel::RuntimeOptions& options) : flat_expr_builder_(GetRegistry()->InternalGetRegistry(), *GetTypeRegistry(), options) {} CelExpressionBuilderFlatImpl() : flat_expr_builder_(GetRegistry()->InternalGetRegistry(), *GetTypeRegistry()) {} absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info, std::vector<absl::Status>* warnings) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::CheckedExpr* checked_expr) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::CheckedExpr* checked_expr, std::vector<absl::Status>* warnings) const override; FlatExprBuilder& flat_expr_builder() { return flat_expr_builder_; } void set_container(std::string container) override { CelExpressionBuilder::set_container(container); flat_expr_builder_.set_container(std::move(container)); } private: absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpressionImpl( std::unique_ptr<cel::Ast> converted_ast, std::vector<absl::Status>* warnings) const; FlatExprBuilder flat_expr_builder_; }; } #endif #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 ::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; using cel::internal::StatusIs; 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")))); } } }
80
cpp
google/cel-cpp
flat_expr_builder_extensions
eval/compiler/flat_expr_builder_extensions.cc
eval/compiler/flat_expr_builder_extensions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_EXTENSIONS_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_EXTENSIONS_H_ #include <cstddef> #include <memory> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "base/ast.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/compiler/resolver.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/trace_step.h" #include "internal/casts.h" #include "runtime/internal/issue_collector.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { class ProgramBuilder { public: class Subexpression; private: using SubprogramMap = absl::flat_hash_map<const cel::ast_internal::Expr*, ProgramBuilder::Subexpression*>; public: class Subexpression { private: using Element = absl::variant<std::unique_ptr<ExpressionStep>, std::unique_ptr<Subexpression>>; using TreePlan = std::vector<Element>; using FlattenedPlan = std::vector<std::unique_ptr<const ExpressionStep>>; public: struct RecursiveProgram { std::unique_ptr<DirectExpressionStep> step; int depth; }; ~Subexpression(); Subexpression(const Subexpression&) = delete; Subexpression& operator=(const Subexpression&) = delete; Subexpression(Subexpression&&) = delete; Subexpression& operator=(Subexpression&&) = delete; bool AddStep(std::unique_ptr<ExpressionStep> step) { if (IsRecursive()) { return false; } if (IsFlattened()) { flattened_elements().push_back(std::move(step)); return true; } elements().push_back({std::move(step)}); return true; } void AddSubexpression(std::unique_ptr<Subexpression> expr) { ABSL_DCHECK(!IsFlattened()); ABSL_DCHECK(!IsRecursive()); elements().push_back({std::move(expr)}); } std::vector<Element>& elements() { ABSL_DCHECK(!IsFlattened()); return absl::get<TreePlan>(program_); } const std::vector<Element>& elements() const { ABSL_DCHECK(!IsFlattened()); return absl::get<TreePlan>(program_); } std::vector<std::unique_ptr<const ExpressionStep>>& flattened_elements() { ABSL_DCHECK(IsFlattened()); return absl::get<FlattenedPlan>(program_); } const std::vector<std::unique_ptr<const ExpressionStep>>& flattened_elements() const { ABSL_DCHECK(IsFlattened()); return absl::get<FlattenedPlan>(program_); } void set_recursive_program(std::unique_ptr<DirectExpressionStep> step, int depth) { program_ = RecursiveProgram{std::move(step), depth}; } const RecursiveProgram& recursive_program() const { ABSL_DCHECK(IsRecursive()); return absl::get<RecursiveProgram>(program_); } absl::optional<int> RecursiveDependencyDepth() const; std::vector<std::unique_ptr<DirectExpressionStep>> ExtractRecursiveDependencies() const; RecursiveProgram ExtractRecursiveProgram(); bool IsRecursive() const { return absl::holds_alternative<RecursiveProgram>(program_); } size_t ComputeSize() const; int CalculateOffset(int base, int target) const; std::unique_ptr<Subexpression> ExtractChild(Subexpression* child); void Flatten(); bool IsFlattened() const { return absl::holds_alternative<FlattenedPlan>(program_); } bool ExtractTo(std::vector<std::unique_ptr<const ExpressionStep>>& out); private: Subexpression(const cel::ast_internal::Expr* self, ProgramBuilder* owner); friend class ProgramBuilder; absl::variant<TreePlan, FlattenedPlan, RecursiveProgram> program_; const cel::ast_internal::Expr* self_; absl::Nullable<const cel::ast_internal::Expr*> parent_; std::weak_ptr<SubprogramMap> subprogram_map_; }; ProgramBuilder(); ExecutionPath FlattenMain(); std::vector<ExecutionPath> FlattenSubexpressions(); absl::Nullable<Subexpression*> current() { return current_; } absl::Nullable<Subexpression*> EnterSubexpression( const cel::ast_internal::Expr* expr); absl::Nullable<Subexpression*> ExitSubexpression( const cel::ast_internal::Expr* expr); absl::Nullable<Subexpression*> GetSubexpression( const cel::ast_internal::Expr* expr); absl::Nullable<Subexpression*> GetExtractedSubexpression(size_t index) { if (index >= extracted_subexpressions_.size()) { return nullptr; } return extracted_subexpressions_[index].get(); } int ExtractSubexpression(const cel::ast_internal::Expr* expr); void AddStep(std::unique_ptr<ExpressionStep> step); private: static std::vector<std::unique_ptr<const ExpressionStep>> FlattenSubexpression(std::unique_ptr<Subexpression> expr); std::unique_ptr<Subexpression> MakeSubexpression( const cel::ast_internal::Expr* expr); std::unique_ptr<Subexpression> root_; std::vector<std::unique_ptr<Subexpression>> extracted_subexpressions_; Subexpression* current_; std::shared_ptr<SubprogramMap> subprogram_map_; }; template <typename Subclass> const Subclass* TryDowncastDirectStep(const DirectExpressionStep* step) { if (step == nullptr) { return nullptr; } auto type_id = step->GetNativeTypeId(); if (type_id == cel::NativeTypeId::For<TraceStep>()) { const auto* trace_step = cel::internal::down_cast<const TraceStep*>(step); auto deps = trace_step->GetDependencies(); if (!deps.has_value() || deps->size() != 1) { return nullptr; } step = deps->at(0); type_id = step->GetNativeTypeId(); } if (type_id == cel::NativeTypeId::For<Subclass>()) { return cel::internal::down_cast<const Subclass*>(step); } return nullptr; } class PlannerContext { public: explicit PlannerContext( const Resolver& resolver, const cel::RuntimeOptions& options, cel::ValueManager& value_factory, cel::runtime_internal::IssueCollector& issue_collector, ProgramBuilder& program_builder) : resolver_(resolver), value_factory_(value_factory), options_(options), issue_collector_(issue_collector), program_builder_(program_builder) {} ProgramBuilder& program_builder() { return program_builder_; } bool IsSubplanInspectable(const cel::ast_internal::Expr& node) const; ExecutionPathView GetSubplan(const cel::ast_internal::Expr& node); absl::StatusOr<ExecutionPath> ExtractSubplan( const cel::ast_internal::Expr& node); absl::Status ReplaceSubplan(const cel::ast_internal::Expr& node, ExecutionPath path); absl::Status ReplaceSubplan(const cel::ast_internal::Expr& node, std::unique_ptr<DirectExpressionStep> step, int depth); absl::Status AddSubplanStep(const cel::ast_internal::Expr& node, std::unique_ptr<ExpressionStep> step); const Resolver& resolver() const { return resolver_; } cel::ValueManager& value_factory() const { return value_factory_; } const cel::RuntimeOptions& options() const { return options_; } cel::runtime_internal::IssueCollector& issue_collector() { return issue_collector_; } private: const Resolver& resolver_; cel::ValueManager& value_factory_; const cel::RuntimeOptions& options_; cel::runtime_internal::IssueCollector& issue_collector_; ProgramBuilder& program_builder_; }; class AstTransform { public: virtual ~AstTransform() = default; virtual absl::Status UpdateAst(PlannerContext& context, cel::ast_internal::AstImpl& ast) const = 0; }; class ProgramOptimizer { public: virtual ~ProgramOptimizer() = default; virtual absl::Status OnPreVisit(PlannerContext& context, const cel::ast_internal::Expr& node) = 0; virtual absl::Status OnPostVisit(PlannerContext& context, const cel::ast_internal::Expr& node) = 0; }; using ProgramOptimizerFactory = absl::AnyInvocable<absl::StatusOr<std::unique_ptr<ProgramOptimizer>>( PlannerContext&, const cel::ast_internal::AstImpl&) const>; } #endif #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 ::cel::RuntimeIssue; using ::cel::ast_internal::Expr; using ::cel::runtime_internal::IssueCollector; using testing::ElementsAre; using testing::IsEmpty; using testing::Optional; using cel::internal::StatusIs; 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>()); } } }
81
cpp
google/cel-cpp
comprehension_vulnerability_check
eval/compiler/comprehension_vulnerability_check.cc
runtime/comprehension_vulnerability_check_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_COMPREHENSION_VULNERABILITY_CHECK_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_COMPREHENSION_VULNERABILITY_CHECK_H_ #include "absl/status/status.h" #include "runtime/runtime_builder.h" namespace cel { absl::Status EnableComprehensionVulnerabiltyCheck(RuntimeBuilder& builder); } #endif #include "runtime/comprehension_vulnerability_check.h" #include "absl/base/macros.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/native_type.h" #include "eval/compiler/comprehension_vulnerability_check.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" namespace cel { namespace { using ::cel::internal::down_cast; using ::cel::runtime_internal::RuntimeFriendAccess; using ::cel::runtime_internal::RuntimeImpl; using ::google::api::expr::runtime::CreateComprehensionVulnerabilityCheck; absl::StatusOr<runtime_internal::RuntimeImpl*> RuntimeImplFromBuilder( RuntimeBuilder& builder) { Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(builder); if (RuntimeFriendAccess::RuntimeTypeId(runtime) != NativeTypeId::For<RuntimeImpl>()) { return absl::UnimplementedError( "constant folding only supported on the default cel::Runtime " "implementation."); } RuntimeImpl& runtime_impl = down_cast<RuntimeImpl&>(runtime); return &runtime_impl; } } absl::Status EnableComprehensionVulnerabiltyCheck( cel::RuntimeBuilder& builder) { CEL_ASSIGN_OR_RETURN(RuntimeImpl * runtime_impl, RuntimeImplFromBuilder(builder)); ABSL_ASSERT(runtime_impl != nullptr); runtime_impl->expr_builder().AddProgramOptimizer( CreateComprehensionVulnerabilityCheck()); return absl::OkStatus(); } }
#include "runtime/comprehension_vulnerability_check.h" #include <utility> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" #include "google/protobuf/text_format.h" namespace cel { namespace { using ::cel::extensions::ProtobufRuntimeAdapter; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::protobuf::TextFormat; using testing::HasSubstr; using cel::internal::IsOk; using cel::internal::StatusIs; constexpr absl::string_view kVulnerableExpr = R"pb( expr { id: 1 comprehension_expr { iter_var: "unused" accu_var: "accu" result { id: 2 ident_expr { name: "accu" } } accu_init { id: 11 list_expr { elements { id: 12 const_expr { int64_value: 0 } } } } loop_condition { id: 13 const_expr { bool_value: true } } loop_step { id: 3 call_expr { function: "_+_" args { id: 4 ident_expr { name: "accu" } } args { id: 5 ident_expr { name: "accu" } } } } iter_range { id: 6 list_expr { elements { id: 7 const_expr { int64_value: 0 } } elements { id: 8 const_expr { int64_value: 0 } } elements { id: 9 const_expr { int64_value: 0 } } elements { id: 10 const_expr { int64_value: 0 } } } } } } )pb"; TEST(ComprehensionVulnerabilityCheck, EnabledVulnerable) { RuntimeOptions runtime_options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(runtime_options)); ASSERT_OK(EnableComprehensionVulnerabiltyCheck(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ParsedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kVulnerableExpr, &expr)); EXPECT_THAT( ProtobufRuntimeAdapter::CreateProgram(*runtime, expr), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("Comprehension contains memory exhaustion vulnerability"))); } TEST(ComprehensionVulnerabilityCheck, EnabledNotVulnerable) { RuntimeOptions runtime_options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(runtime_options)); ASSERT_OK(EnableComprehensionVulnerabiltyCheck(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("[0, 0, 0, 0].map(x, x + 1)")); EXPECT_THAT(ProtobufRuntimeAdapter::CreateProgram(*runtime, expr), IsOk()); } TEST(ComprehensionVulnerabilityCheck, DisabledVulnerable) { RuntimeOptions runtime_options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(runtime_options)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ParsedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kVulnerableExpr, &expr)); EXPECT_THAT(ProtobufRuntimeAdapter::CreateProgram(*runtime, expr), IsOk()); } } }
82
cpp
google/cel-cpp
regex_precompilation_optimization
eval/compiler/regex_precompilation_optimization.cc
eval/compiler/regex_precompilation_optimization_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_REGEX_PRECOMPILATION_OPTIMIZATION_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_REGEX_PRECOMPILATION_OPTIMIZATION_H_ #include "eval/compiler/flat_expr_builder_extensions.h" namespace google::api::expr::runtime { ProgramOptimizerFactory CreateRegexPrecompilationExtension( int regex_max_program_size); } #endif #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/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 <utility> #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 "base/ast_internal/expr.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::ast_internal::CheckedExpr; 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; CheckedExpr expr; cel::ast_internal::AstImpl ast_impl(std::move(expr)); 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()); } }
83
cpp
google/cel-cpp
qualified_reference_resolver
eval/compiler/qualified_reference_resolver.cc
eval/compiler/qualified_reference_resolver_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_QUALIFIED_REFERENCE_RESOLVER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_QUALIFIED_REFERENCE_RESOLVER_H_ #include <memory> #include "absl/status/statusor.h" #include "base/ast.h" #include "base/ast_internal/ast_impl.h" #include "eval/compiler/flat_expr_builder_extensions.h" #include "eval/compiler/resolver.h" #include "runtime/internal/issue_collector.h" namespace google::api::expr::runtime { absl::StatusOr<bool> ResolveReferences( const Resolver& resolver, cel::runtime_internal::IssueCollector& issues, cel::ast_internal::AstImpl& ast); enum class ReferenceResolverOption { kAlways, kCheckedOnly, }; std::unique_ptr<AstTransform> NewReferenceResolverExtension( ReferenceResolverOption option); } #endif #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; } 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 ::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; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; 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 {
84
cpp
google/cel-cpp
constant_folding
eval/compiler/constant_folding.cc
eval/compiler/constant_folding_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_CONSTANT_FOLDING_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_CONSTANT_FOLDING_H_ #include "absl/status/status.h" #include "common/memory.h" #include "runtime/runtime_builder.h" namespace cel::extensions { absl::Status EnableConstantFolding(RuntimeBuilder& builder, MemoryManagerRef memory_manager); } #endif #include "runtime/constant_folding.h" #include "absl/base/macros.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/memory.h" #include "common/native_type.h" #include "eval/compiler/constant_folding.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" namespace cel::extensions { namespace { using ::cel::internal::down_cast; using ::cel::runtime_internal::RuntimeFriendAccess; using ::cel::runtime_internal::RuntimeImpl; absl::StatusOr<RuntimeImpl*> RuntimeImplFromBuilder(RuntimeBuilder& builder) { Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(builder); if (RuntimeFriendAccess::RuntimeTypeId(runtime) != NativeTypeId::For<RuntimeImpl>()) { return absl::UnimplementedError( "constant folding only supported on the default cel::Runtime " "implementation."); } RuntimeImpl& runtime_impl = down_cast<RuntimeImpl&>(runtime); return &runtime_impl; } } absl::Status EnableConstantFolding(RuntimeBuilder& builder, MemoryManagerRef memory_manager) { CEL_ASSIGN_OR_RETURN(RuntimeImpl * runtime_impl, RuntimeImplFromBuilder(builder)); ABSL_ASSERT(runtime_impl != nullptr); runtime_impl->expr_builder().AddProgramOptimizer( runtime_internal::CreateConstantFoldingOptimizer(memory_manager)); return absl::OkStatus(); } }
#include "runtime/constant_folding.h" #include <string> #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/match.h" #include "base/function_adapter.h" #include "common/value.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" namespace cel::extensions { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using testing::HasSubstr; using cel::internal::StatusIs; using ValueMatcher = testing::Matcher<Value>; struct TestCase { std::string name; std::string expression; ValueMatcher result_matcher; absl::Status status; }; MATCHER_P(IsIntValue, expected, "") { const Value& value = arg; return value->Is<IntValue>() && value->As<IntValue>().NativeValue() == expected; } MATCHER_P(IsBoolValue, expected, "") { const Value& value = arg; return value->Is<BoolValue>() && value->As<BoolValue>().NativeValue() == expected; } MATCHER_P(IsErrorValue, expected_substr, "") { const Value& value = arg; return value->Is<ErrorValue>() && absl::StrContains(value->As<ErrorValue>().NativeValue().message(), expected_substr); } class ConstantFoldingExtTest : public testing::TestWithParam<TestCase> {}; TEST_P(ConstantFoldingExtTest, Runner) { RuntimeOptions options; const TestCase& test_case = GetParam(); ASSERT_OK_AND_ASSIGN(cel::RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const StringValue&>>:: RegisterGlobalOverload( "prepend", [](ValueManager& f, const StringValue& value, const StringValue& prefix) { return StringValue::Concat(f, prefix, value); }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK( EnableConstantFolding(builder, MemoryManagerRef::ReferenceCounting())); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse(test_case.expression)); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, parsed_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; auto result = program->Evaluate(activation, value_factory.get()); if (test_case.status.ok()) { ASSERT_OK_AND_ASSIGN(Value value, std::move(result)); EXPECT_THAT(value, test_case.result_matcher); return; } EXPECT_THAT(result.status(), StatusIs(test_case.status.code(), HasSubstr(test_case.status.message()))); } INSTANTIATE_TEST_SUITE_P( Cases, ConstantFoldingExtTest, testing::ValuesIn(std::vector<TestCase>{ {"sum", "1 + 2 + 3", IsIntValue(6)}, {"list_create", "[1, 2, 3, 4].filter(x, x < 4).size()", IsIntValue(3)}, {"string_concat", "('12' + '34' + '56' + '78' + '90').size()", IsIntValue(10)}, {"comprehension", "[1, 2, 3, 4].exists(x, x in [4, 5, 6, 7])", IsBoolValue(true)}, {"nested_comprehension", "[1, 2, 3, 4].exists(x, [1, 2, 3, 4].all(y, y <= x))", IsBoolValue(true)}, {"runtime_error", "[1, 2, 3, 4].exists(x, ['4'].all(y, y <= x))", IsErrorValue("No matching overloads")}, {"custom_function", "prepend('def', 'abc') == 'abcdef'", IsBoolValue(true)}}), [](const testing::TestParamInfo<TestCase>& info) { return info.param.name; }); } }
85
cpp
google/cel-cpp
resolver
eval/compiler/resolver.cc
eval/compiler/resolver_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_RESOLVER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_RESOLVER_H_ #include <cstdint> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/kind.h" #include "common/value.h" #include "common/value_manager.h" #include "runtime/function_overload_reference.h" #include "runtime/function_registry.h" #include "runtime/type_registry.h" namespace google::api::expr::runtime { class Resolver { public: Resolver( absl::string_view container, const cel::FunctionRegistry& function_registry, const cel::TypeRegistry& type_registry, cel::ValueManager& value_factory, const absl::flat_hash_map<std::string, cel::TypeRegistry::Enumeration>& resolveable_enums, bool resolve_qualified_type_identifiers = true); ~Resolver() = default; absl::optional<cel::Value> FindConstant(absl::string_view name, int64_t expr_id) const; absl::StatusOr<absl::optional<std::pair<std::string, cel::Type>>> FindType( absl::string_view name, int64_t expr_id) const; std::vector<cel::FunctionRegistry::LazyOverload> FindLazyOverloads( absl::string_view name, bool receiver_style, const std::vector<cel::Kind>& types, int64_t expr_id = -1) const; std::vector<cel::FunctionOverloadReference> FindOverloads( absl::string_view name, bool receiver_style, const std::vector<cel::Kind>& types, int64_t expr_id = -1) const; std::vector<std::string> FullyQualifiedNames(absl::string_view base_name, int64_t expr_id = -1) const; private: std::vector<std::string> namespace_prefixes_; absl::flat_hash_map<std::string, cel::Value> enum_value_map_; const cel::FunctionRegistry& function_registry_; cel::ValueManager& value_factory_; const absl::flat_hash_map<std::string, cel::TypeRegistry::Enumeration>& resolveable_enums_; bool resolve_qualified_type_identifiers_; }; inline std::vector<cel::Kind> ArgumentsMatcher(int argument_count) { std::vector<cel::Kind> argument_matcher(argument_count); for (int i = 0; i < argument_count; i++) { argument_matcher[i] = cel::Kind::kAny; } return argument_matcher; } } #endif #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).As<IntValue>().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).As<IntValue>().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).As<TypeValue>().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).As<TypeValue>().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)); } } }
86
cpp
google/cel-cpp
cel_value_equal
eval/internal/cel_value_equal.cc
eval/internal/cel_value_equal_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_INTERNAL_CEL_VALUE_EQUAL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_INTERNAL_CEL_VALUE_EQUAL_H_ #include "absl/types/optional.h" #include "eval/public/cel_value.h" namespace cel::interop_internal { absl::optional<bool> CelValueEqualImpl( const google::api::expr::runtime::CelValue& v1, const google::api::expr::runtime::CelValue& v2); } #endif #include "eval/internal/cel_value_equal.h" #include <cstdint> #include "absl/time/time.h" #include "absl/types/optional.h" #include "base/kind.h" #include "eval/public/cel_number.h" #include "eval/public/cel_value.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 "internal/number.h" #include "google/protobuf/arena.h" namespace cel::interop_internal { namespace { using ::cel::internal::Number; using ::google::api::expr::runtime::CelList; using ::google::api::expr::runtime::CelMap; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::GetNumberFromCelValue; using ::google::api::expr::runtime::LegacyTypeAccessApis; using ::google::api::expr::runtime::LegacyTypeInfoApis; struct HeterogeneousEqualProvider { absl::optional<bool> operator()(const CelValue& lhs, const CelValue& rhs) const; }; template <class Type> absl::optional<bool> Inequal(Type lhs, Type rhs) { return lhs != rhs; } template <class Type> absl::optional<bool> Equal(Type lhs, Type rhs) { return lhs == rhs; } template <typename EqualsProvider> absl::optional<bool> ListEqual(const CelList* t1, const CelList* t2) { if (t1 == t2) { return true; } int index_size = t1->size(); if (t2->size() != index_size) { return false; } google::protobuf::Arena arena; for (int i = 0; i < index_size; i++) { CelValue e1 = (*t1).Get(&arena, i); CelValue e2 = (*t2).Get(&arena, i); absl::optional<bool> eq = EqualsProvider()(e1, e2); if (eq.has_value()) { if (!(*eq)) { return false; } } else { return eq; } } return true; } template <typename EqualsProvider> absl::optional<bool> MapEqual(const CelMap* t1, const CelMap* t2) { if (t1 == t2) { return true; } if (t1->size() != t2->size()) { return false; } google::protobuf::Arena arena; auto list_keys = t1->ListKeys(&arena); if (!list_keys.ok()) { return absl::nullopt; } const CelList* keys = *list_keys; for (int i = 0; i < keys->size(); i++) { CelValue key = (*keys).Get(&arena, i); CelValue v1 = (*t1).Get(&arena, key).value(); absl::optional<CelValue> v2 = (*t2).Get(&arena, key); if (!v2.has_value()) { auto number = GetNumberFromCelValue(key); if (!number.has_value()) { return false; } if (!key.IsInt64() && number->LosslessConvertibleToInt()) { CelValue int_key = CelValue::CreateInt64(number->AsInt()); absl::optional<bool> eq = EqualsProvider()(key, int_key); if (eq.has_value() && *eq) { v2 = (*t2).Get(&arena, int_key); } } if (!key.IsUint64() && !v2.has_value() && number->LosslessConvertibleToUint()) { CelValue uint_key = CelValue::CreateUint64(number->AsUint()); absl::optional<bool> eq = EqualsProvider()(key, uint_key); if (eq.has_value() && *eq) { v2 = (*t2).Get(&arena, uint_key); } } } if (!v2.has_value()) { return false; } absl::optional<bool> eq = EqualsProvider()(v1, *v2); if (!eq.has_value() || !*eq) { return eq; } } return true; } bool MessageEqual(const CelValue::MessageWrapper& m1, const CelValue::MessageWrapper& m2) { const LegacyTypeInfoApis* lhs_type_info = m1.legacy_type_info(); const LegacyTypeInfoApis* rhs_type_info = m2.legacy_type_info(); if (lhs_type_info->GetTypename(m1) != rhs_type_info->GetTypename(m2)) { return false; } const LegacyTypeAccessApis* accessor = lhs_type_info->GetAccessApis(m1); if (accessor == nullptr) { return false; } return accessor->IsEqualTo(m1, m2); } template <class EqualityProvider> absl::optional<bool> HomogenousCelValueEqual(const CelValue& t1, const CelValue& t2) { if (t1.type() != t2.type()) { return absl::nullopt; } switch (t1.type()) { case Kind::kNullType: return Equal<CelValue::NullType>(CelValue::NullType(), CelValue::NullType()); case Kind::kBool: return Equal<bool>(t1.BoolOrDie(), t2.BoolOrDie()); case Kind::kInt64: return Equal<int64_t>(t1.Int64OrDie(), t2.Int64OrDie()); case Kind::kUint64: return Equal<uint64_t>(t1.Uint64OrDie(), t2.Uint64OrDie()); case Kind::kDouble: return Equal<double>(t1.DoubleOrDie(), t2.DoubleOrDie()); case Kind::kString: return Equal<CelValue::StringHolder>(t1.StringOrDie(), t2.StringOrDie()); case Kind::kBytes: return Equal<CelValue::BytesHolder>(t1.BytesOrDie(), t2.BytesOrDie()); case Kind::kDuration: return Equal<absl::Duration>(t1.DurationOrDie(), t2.DurationOrDie()); case Kind::kTimestamp: return Equal<absl::Time>(t1.TimestampOrDie(), t2.TimestampOrDie()); case Kind::kList: return ListEqual<EqualityProvider>(t1.ListOrDie(), t2.ListOrDie()); case Kind::kMap: return MapEqual<EqualityProvider>(t1.MapOrDie(), t2.MapOrDie()); case Kind::kCelType: return Equal<CelValue::CelTypeHolder>(t1.CelTypeOrDie(), t2.CelTypeOrDie()); default: break; } return absl::nullopt; } absl::optional<bool> HeterogeneousEqualProvider::operator()( const CelValue& lhs, const CelValue& rhs) const { return CelValueEqualImpl(lhs, rhs); } } absl::optional<bool> CelValueEqualImpl(const CelValue& v1, const CelValue& v2) { if (v1.type() == v2.type()) { if (CelValue::MessageWrapper lhs, rhs; v1.GetValue(&lhs) && v2.GetValue(&rhs)) { return MessageEqual(lhs, rhs); } return HomogenousCelValueEqual<HeterogeneousEqualProvider>(v1, v2); } absl::optional<Number> lhs = GetNumberFromCelValue(v1); absl::optional<Number> rhs = GetNumberFromCelValue(v2); if (rhs.has_value() && lhs.has_value()) { return *lhs == *rhs; } if (v1.IsError() || v1.IsUnknownSet() || v2.IsError() || v2.IsUnknownSet()) { return absl::nullopt; } return false; } }
#include "eval/internal/cel_value_equal.h" #include <array> #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "google/rpc/context/attribute_context.pb.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "absl/types/variant.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/cel_proto_wrapper.h" #include "eval/public/structs/trivial_legacy_type_info.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" namespace cel::interop_internal { namespace { using ::google::api::expr::runtime::CelList; using ::google::api::expr::runtime::CelMap; using ::google::api::expr::runtime::CelProtoWrapper; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::ContainerBackedListImpl; using ::google::api::expr::runtime::CreateContainerBackedMap; using ::google::api::expr::runtime::MessageWrapper; using ::google::api::expr::runtime::TestMessage; using ::google::api::expr::runtime::TrivialTypeInfo; using testing::_; using testing::Combine; using testing::Optional; using testing::Values; using testing::ValuesIn; struct EqualityTestCase { enum class ErrorKind { kMissingOverload, kMissingIdentifier }; absl::string_view expr; absl::variant<bool, ErrorKind> result; CelValue lhs = CelValue::CreateNull(); CelValue rhs = CelValue::CreateNull(); }; bool IsNumeric(CelValue::Type type) { return type == CelValue::Type::kDouble || type == CelValue::Type::kInt64 || type == CelValue::Type::kUint64; } const CelList& CelListExample1() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(1)}); return *example; } const CelList& CelListExample2() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(2)}); return *example; } const CelMap& CelMapExample1() { static CelMap* example = []() { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}}; auto map = CreateContainerBackedMap(absl::MakeSpan(values)); return map->release(); }(); return *example; } const CelMap& CelMapExample2() { static CelMap* example = []() { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}}; auto map = CreateContainerBackedMap(absl::MakeSpan(values)); return map->release(); }(); return *example; } const std::vector<CelValue>& ValueExamples1() { static std::vector<CelValue>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<CelValue>>(); result->push_back(CelValue::CreateNull()); result->push_back(CelValue::CreateBool(false)); result->push_back(CelValue::CreateInt64(1)); result->push_back(CelValue::CreateUint64(1)); result->push_back(CelValue::CreateDouble(1.0)); result->push_back(CelValue::CreateStringView("string")); result->push_back(CelValue::CreateBytesView("bytes")); result->push_back(CelProtoWrapper::CreateMessage( std::make_unique<TestMessage>().release(), &arena)); result->push_back(CelValue::CreateDuration(absl::Seconds(1))); result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(1))); result->push_back(CelValue::CreateList(&CelListExample1())); result->push_back(CelValue::CreateMap(&CelMapExample1())); result->push_back(CelValue::CreateCelTypeView("type")); return result.release(); }(); return *examples; } const std::vector<CelValue>& ValueExamples2() { static std::vector<CelValue>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<CelValue>>(); auto message2 = std::make_unique<TestMessage>(); message2->set_int64_value(2); result->push_back(CelValue::CreateNull()); result->push_back(CelValue::CreateBool(true)); result->push_back(CelValue::CreateInt64(2)); result->push_back(CelValue::CreateUint64(2)); result->push_back(CelValue::CreateDouble(2.0)); result->push_back(CelValue::CreateStringView("string2")); result->push_back(CelValue::CreateBytesView("bytes2")); result->push_back( CelProtoWrapper::CreateMessage(message2.release(), &arena)); result->push_back(CelValue::CreateDuration(absl::Seconds(2))); result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(2))); result->push_back(CelValue::CreateList(&CelListExample2())); result->push_back(CelValue::CreateMap(&CelMapExample2())); result->push_back(CelValue::CreateCelTypeView("type2")); return result.release(); }(); return *examples; } class CelValueEqualImplTypesTest : public testing::TestWithParam<std::tuple<CelValue, CelValue, bool>> { public: CelValueEqualImplTypesTest() = default; const CelValue& lhs() { return std::get<0>(GetParam()); } const CelValue& rhs() { return std::get<1>(GetParam()); } bool should_be_equal() { return std::get<2>(GetParam()); } }; std::string CelValueEqualTestName( const testing::TestParamInfo<std::tuple<CelValue, CelValue, bool>>& test_case) { return absl::StrCat(CelValue::TypeName(std::get<0>(test_case.param).type()), CelValue::TypeName(std::get<1>(test_case.param).type()), (std::get<2>(test_case.param)) ? "Equal" : "Inequal"); } TEST_P(CelValueEqualImplTypesTest, Basic) { absl::optional<bool> result = CelValueEqualImpl(lhs(), rhs()); if (lhs().IsNull() || rhs().IsNull()) { if (lhs().IsNull() && rhs().IsNull()) { EXPECT_THAT(result, Optional(true)); } else { EXPECT_THAT(result, Optional(false)); } } else if (lhs().type() == rhs().type() || (IsNumeric(lhs().type()) && IsNumeric(rhs().type()))) { EXPECT_THAT(result, Optional(should_be_equal())); } else { EXPECT_THAT(result, Optional(false)); } } INSTANTIATE_TEST_SUITE_P(EqualityBetweenTypes, CelValueEqualImplTypesTest, Combine(ValuesIn(ValueExamples1()), ValuesIn(ValueExamples1()), Values(true)), &CelValueEqualTestName); INSTANTIATE_TEST_SUITE_P(InequalityBetweenTypes, CelValueEqualImplTypesTest, Combine(ValuesIn(ValueExamples1()), ValuesIn(ValueExamples2()), Values(false)), &CelValueEqualTestName); struct NumericInequalityTestCase { std::string name; CelValue a; CelValue b; }; const std::vector<NumericInequalityTestCase>& NumericValuesNotEqualExample() { static std::vector<NumericInequalityTestCase>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<NumericInequalityTestCase>>(); result->push_back({"NegativeIntAndUint", CelValue::CreateInt64(-1), CelValue::CreateUint64(2)}); result->push_back( {"IntAndLargeUint", CelValue::CreateInt64(1), CelValue::CreateUint64( static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1)}); result->push_back( {"IntAndLargeDouble", CelValue::CreateInt64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::max()) + 1025)}); result->push_back( {"IntAndSmallDouble", CelValue::CreateInt64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::lowest()) - 1025)}); result->push_back( {"UintAndLargeDouble", CelValue::CreateUint64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<uint64_t>::max()) + 2049)}); result->push_back({"NegativeDoubleAndUint", CelValue::CreateDouble(-2.0), CelValue::CreateUint64(123)}); result->push_back({"NanAndDouble", CelValue::CreateDouble(NAN), CelValue::CreateDouble(1.0)}); result->push_back({"NanAndNan", CelValue::CreateDouble(NAN), CelValue::CreateDouble(NAN)}); result->push_back({"DoubleAndNan", CelValue::CreateDouble(1.0), CelValue::CreateDouble(NAN)}); result->push_back( {"IntAndNan", CelValue::CreateInt64(1), CelValue::CreateDouble(NAN)}); result->push_back( {"NanAndInt", CelValue::CreateDouble(NAN), CelValue::CreateInt64(1)}); result->push_back( {"UintAndNan", CelValue::CreateUint64(1), CelValue::CreateDouble(NAN)}); result->push_back( {"NanAndUint", CelValue::CreateDouble(NAN), CelValue::CreateUint64(1)}); return result.release(); }(); return *examples; } using NumericInequalityTest = testing::TestWithParam<NumericInequalityTestCase>; TEST_P(NumericInequalityTest, NumericValues) { NumericInequalityTestCase test_case = GetParam(); absl::optional<bool> result = CelValueEqualImpl(test_case.a, test_case.b); EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, false); } INSTANTIATE_TEST_SUITE_P( InequalityBetweenNumericTypesTest, NumericInequalityTest, ValuesIn(NumericValuesNotEqualExample()), [](const testing::TestParamInfo<NumericInequalityTest::ParamType>& info) { return info.param.name; }); TEST(CelValueEqualImplTest, LossyNumericEquality) { absl::optional<bool> result = CelValueEqualImpl( CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::max()) - 1), CelValue::CreateInt64(std::numeric_limits<int64_t>::max())); EXPECT_TRUE(result.has_value()); EXPECT_TRUE(*result); } TEST(CelValueEqualImplTest, ListMixedTypesInequal) { ContainerBackedListImpl lhs({CelValue::CreateInt64(1)}); ContainerBackedListImpl rhs({CelValue::CreateStringView("abc")}); EXPECT_THAT( CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)), Optional(false)); } TEST(CelValueEqualImplTest, NestedList) { ContainerBackedListImpl inner_lhs({CelValue::CreateInt64(1)}); ContainerBackedListImpl lhs({CelValue::CreateList(&inner_lhs)}); ContainerBackedListImpl inner_rhs({CelValue::CreateNull()}); ContainerBackedListImpl rhs({CelValue::CreateList(&inner_rhs)}); EXPECT_THAT( CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)), Optional(false)); } TEST(CelValueEqualImplTest, MapMixedValueTypesInequal) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, MapMixedKeyTypesEqual) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateUint64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(true)); } TEST(CelValueEqualImplTest, MapMixedKeyTypesInequal) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(2), CelValue::CreateInt64(2)}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, NestedMaps) { std::vector<std::pair<CelValue, CelValue>> inner_lhs_data{ {CelValue::CreateInt64(2), CelValue::CreateStringView("abc")}}; ASSERT_OK_AND_ASSIGN( std::unique_ptr<CelMap> inner_lhs, CreateContainerBackedMap(absl::MakeSpan(inner_lhs_data))); std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateMap(inner_lhs.get())}}; std::vector<std::pair<CelValue, CelValue>> inner_rhs_data{ {CelValue::CreateInt64(2), CelValue::CreateNull()}}; ASSERT_OK_AND_ASSIGN( std::unique_ptr<CelMap> inner_rhs, CreateContainerBackedMap(absl::MakeSpan(inner_rhs_data))); std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateMap(inner_rhs.get())}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityDifferingTypenameInequal) { google::protobuf::Arena arena; TestMessage example; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &example)); CelValue lhs = CelProtoWrapper::CreateMessage(&example, &arena); CelValue rhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityNoAccessorInequal) { google::protobuf::Arena arena; TestMessage example; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &example)); CelValue lhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); CelValue rhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityAny) { google::protobuf::Arena arena; TestMessage packed_value; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &packed_value)); TestMessage lhs; lhs.mutable_any_value()->PackFrom(packed_value); TestMessage rhs; rhs.mutable_any_value()->PackFrom(packed_value); EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena), CelProtoWrapper::CreateMessage(&rhs, &arena)), Optional(true)); lhs.mutable_any_value()->clear_type_url(); rhs.mutable_any_value()->clear_type_url(); EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena), CelProtoWrapper::CreateMessage(&rhs, &arena)), Optional(true)); } bool AddDepsToPool(const google::protobuf::FileDescriptor* descriptor, google::protobuf::DescriptorPool& pool) { for (int i = 0; i < descriptor->dependency_count(); i++) { if (!AddDepsToPool(descriptor->dependency(i), pool)) { return false; } } google::protobuf::FileDescriptorProto descriptor_proto; descriptor->CopyTo(&descriptor_proto); return pool.BuildFile(descriptor_proto) != nullptr; } TEST(CelValueEqualImplTest, DynamicDescriptorAndGeneratedInequal) { google::protobuf::DescriptorPool pool; google::protobuf::DynamicMessageFactory factory; google::protobuf::Arena arena; factory.SetDelegateToGeneratedFactory(false); ASSERT_TRUE(AddDepsToPool(TestMessage::descriptor()->file(), pool)); TestMessage example_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int64_value: 12345 bool_list: false bool_list: true message_value { float_value: 1.0 } )pb", &example_message)); std::unique_ptr<google::protobuf::Message> example_dynamic_message( factory .GetPrototype(pool.FindMessageTypeByName( TestMessage::descriptor()->full_name())) ->New()); ASSERT_TRUE(example_dynamic_message->ParseFromString( example_message.SerializeAsString())); EXPECT_THAT(CelValueEqualImpl( CelProtoWrapper::CreateMessage(&example_message, &arena), CelProtoWrapper::CreateMessage(example_dynamic_message.get(), &arena)), Optional(false)); } TEST(CelValueEqualImplTest, DynamicMessageAndMessageEqual) { google::protobuf::DynamicMessageFactory factory; google::protobuf::Arena arena; factory.SetDelegateToGeneratedFactory(false); TestMessage example_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int64_value: 12345 bool_list: false bool_list: true message_value { float_value: 1.0 } )pb", &example_message)); std::unique_ptr<google::protobuf::Message> example_dynamic_message( factory.GetPrototype(TestMessage::descriptor())->New()); ASSERT_TRUE(example_dynamic_message->ParseFromString( example_message.SerializeAsString())); EXPECT_THAT(CelValueEqualImpl( CelProtoWrapper::CreateMessage(&example_message, &arena), CelProtoWrapper::CreateMessage(example_dynamic_message.get(), &arena)), Optional(true)); } } }
87
cpp
google/cel-cpp
container_function_registrar
eval/public/container_function_registrar.cc
eval/public/container_function_registrar_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINER_FUNCTION_REGISTRAR_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINER_FUNCTION_REGISTRAR_H_ #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" namespace google::api::expr::runtime { absl::Status RegisterContainerFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options); } #endif #include "eval/public/container_function_registrar.h" #include "eval/public/cel_options.h" #include "runtime/runtime_options.h" #include "runtime/standard/container_functions.h" namespace google::api::expr::runtime { absl::Status RegisterContainerFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { cel::RuntimeOptions runtime_options = ConvertToRuntimeOptions(options); return cel::RegisterContainerFunctions(registry->InternalGetRegistry(), runtime_options); } }
#include "eval/public/container_function_registrar.h" #include <memory> #include <string> #include "eval/public/activation.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/equality_function_registrar.h" #include "eval/public/testing/matchers.h" #include "internal/testing.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using google::api::expr::v1alpha1::Expr; using google::api::expr::v1alpha1::SourceInfo; using testing::ValuesIn; struct TestCase { std::string test_name; std::string expr; absl::StatusOr<CelValue> result = CelValue::CreateBool(true); }; const CelList& CelNumberListExample() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(1)}); return *example; } void ExpectResult(const TestCase& test_case) { auto parsed_expr = parser::Parse(test_case.expr); ASSERT_OK(parsed_expr); const Expr& expr_ast = parsed_expr->expr(); const SourceInfo& source_info = parsed_expr->source_info(); InterpreterOptions options; options.enable_timestamp_duration_overflow_errors = true; options.enable_comprehension_list_append = true; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterContainerFunctions(builder->GetRegistry(), options)); ASSERT_OK(RegisterEqualityFunctions(builder->GetRegistry(), options)); ASSERT_OK_AND_ASSIGN(auto cel_expression, builder->CreateExpression(&expr_ast, &source_info)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(auto value, cel_expression->Evaluate(activation, &arena)); EXPECT_THAT(value, test::EqualsCelValue(*test_case.result)); } using ContainerFunctionParamsTest = testing::TestWithParam<TestCase>; TEST_P(ContainerFunctionParamsTest, StandardFunctions) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( ContainerFunctionParamsTest, ContainerFunctionParamsTest, ValuesIn<TestCase>( {{"FilterNumbers", "[1, 2, 3].filter(num, num == 1)", CelValue::CreateList(&CelNumberListExample())}, {"ListConcatEmptyInputs", "[] + [] == []", CelValue::CreateBool(true)}, {"ListConcatRightEmpty", "[1] + [] == [1]", CelValue::CreateBool(true)}, {"ListConcatLeftEmpty", "[] + [1] == [1]", CelValue::CreateBool(true)}, {"ListConcat", "[2] + [1] == [2, 1]", CelValue::CreateBool(true)}, {"ListSize", "[1, 2, 3].size() == 3", CelValue::CreateBool(true)}, {"MapSize", "{1: 2, 2: 4}.size() == 2", CelValue::CreateBool(true)}, {"EmptyListSize", "size({}) == 0", CelValue::CreateBool(true)}}), [](const testing::TestParamInfo<ContainerFunctionParamsTest::ParamType>& info) { return info.param.test_name; }); } }
88
cpp
google/cel-cpp
equality_function_registrar
eval/public/equality_function_registrar.cc
eval/public/equality_function_registrar_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_EQUALITY_FUNCTION_REGISTRAR_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_EQUALITY_FUNCTION_REGISTRAR_H_ #include "absl/status/status.h" #include "eval/internal/cel_value_equal.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" namespace google::api::expr::runtime { using cel::interop_internal::CelValueEqualImpl; absl::Status RegisterEqualityFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options); } #endif #include "eval/public/equality_function_registrar.h" #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "runtime/runtime_options.h" #include "runtime/standard/equality_functions.h" namespace google::api::expr::runtime { absl::Status RegisterEqualityFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { cel::RuntimeOptions runtime_options = ConvertToRuntimeOptions(options); return cel::RegisterEqualityFunctions(registry->InternalGetRegistry(), runtime_options); } }
#include "eval/public/equality_function_registrar.h" #include <array> #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/any.pb.h" #include "google/rpc/context/attribute_context.pb.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.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/time/time.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "eval/public/activation.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_registry.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/message_wrapper.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/structs/trivial_legacy_type_info.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_message.pb.h" #include "internal/benchmark.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::rpc::context::AttributeContext; using testing::_; using testing::Combine; using testing::HasSubstr; using testing::Optional; using testing::Values; using testing::ValuesIn; using cel::internal::StatusIs; MATCHER_P2(DefinesHomogenousOverload, name, argument_type, absl::StrCat(name, " for ", CelValue::TypeName(argument_type))) { const CelFunctionRegistry& registry = arg; return !registry .FindOverloads(name, false, {argument_type, argument_type}) .empty(); return false; } struct EqualityTestCase { enum class ErrorKind { kMissingOverload, kMissingIdentifier }; absl::string_view expr; absl::variant<bool, ErrorKind> result; CelValue lhs = CelValue::CreateNull(); CelValue rhs = CelValue::CreateNull(); }; bool IsNumeric(CelValue::Type type) { return type == CelValue::Type::kDouble || type == CelValue::Type::kInt64 || type == CelValue::Type::kUint64; } const CelList& CelListExample1() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(1)}); return *example; } const CelList& CelListExample2() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(2)}); return *example; } const CelMap& CelMapExample1() { static CelMap* example = []() { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}}; auto map = CreateContainerBackedMap(absl::MakeSpan(values)); return map->release(); }(); return *example; } const CelMap& CelMapExample2() { static CelMap* example = []() { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}}; auto map = CreateContainerBackedMap(absl::MakeSpan(values)); return map->release(); }(); return *example; } const std::vector<CelValue>& ValueExamples1() { static std::vector<CelValue>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<CelValue>>(); result->push_back(CelValue::CreateNull()); result->push_back(CelValue::CreateBool(false)); result->push_back(CelValue::CreateInt64(1)); result->push_back(CelValue::CreateUint64(1)); result->push_back(CelValue::CreateDouble(1.0)); result->push_back(CelValue::CreateStringView("string")); result->push_back(CelValue::CreateBytesView("bytes")); result->push_back(CelProtoWrapper::CreateMessage( std::make_unique<TestMessage>().release(), &arena)); result->push_back(CelValue::CreateDuration(absl::Seconds(1))); result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(1))); result->push_back(CelValue::CreateList(&CelListExample1())); result->push_back(CelValue::CreateMap(&CelMapExample1())); result->push_back(CelValue::CreateCelTypeView("type")); return result.release(); }(); return *examples; } const std::vector<CelValue>& ValueExamples2() { static std::vector<CelValue>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<CelValue>>(); auto message2 = std::make_unique<TestMessage>(); message2->set_int64_value(2); result->push_back(CelValue::CreateNull()); result->push_back(CelValue::CreateBool(true)); result->push_back(CelValue::CreateInt64(2)); result->push_back(CelValue::CreateUint64(2)); result->push_back(CelValue::CreateDouble(2.0)); result->push_back(CelValue::CreateStringView("string2")); result->push_back(CelValue::CreateBytesView("bytes2")); result->push_back( CelProtoWrapper::CreateMessage(message2.release(), &arena)); result->push_back(CelValue::CreateDuration(absl::Seconds(2))); result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(2))); result->push_back(CelValue::CreateList(&CelListExample2())); result->push_back(CelValue::CreateMap(&CelMapExample2())); result->push_back(CelValue::CreateCelTypeView("type2")); return result.release(); }(); return *examples; } class CelValueEqualImplTypesTest : public testing::TestWithParam<std::tuple<CelValue, CelValue, bool>> { public: CelValueEqualImplTypesTest() = default; const CelValue& lhs() { return std::get<0>(GetParam()); } const CelValue& rhs() { return std::get<1>(GetParam()); } bool should_be_equal() { return std::get<2>(GetParam()); } }; std::string CelValueEqualTestName( const testing::TestParamInfo<std::tuple<CelValue, CelValue, bool>>& test_case) { return absl::StrCat(CelValue::TypeName(std::get<0>(test_case.param).type()), CelValue::TypeName(std::get<1>(test_case.param).type()), (std::get<2>(test_case.param)) ? "Equal" : "Inequal"); } TEST_P(CelValueEqualImplTypesTest, Basic) { absl::optional<bool> result = CelValueEqualImpl(lhs(), rhs()); if (lhs().IsNull() || rhs().IsNull()) { if (lhs().IsNull() && rhs().IsNull()) { EXPECT_THAT(result, Optional(true)); } else { EXPECT_THAT(result, Optional(false)); } } else if (lhs().type() == rhs().type() || (IsNumeric(lhs().type()) && IsNumeric(rhs().type()))) { EXPECT_THAT(result, Optional(should_be_equal())); } else { EXPECT_THAT(result, Optional(false)); } } INSTANTIATE_TEST_SUITE_P(EqualityBetweenTypes, CelValueEqualImplTypesTest, Combine(ValuesIn(ValueExamples1()), ValuesIn(ValueExamples1()), Values(true)), &CelValueEqualTestName); INSTANTIATE_TEST_SUITE_P(InequalityBetweenTypes, CelValueEqualImplTypesTest, Combine(ValuesIn(ValueExamples1()), ValuesIn(ValueExamples2()), Values(false)), &CelValueEqualTestName); struct NumericInequalityTestCase { std::string name; CelValue a; CelValue b; }; const std::vector<NumericInequalityTestCase>& NumericValuesNotEqualExample() { static std::vector<NumericInequalityTestCase>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<NumericInequalityTestCase>>(); result->push_back({"NegativeIntAndUint", CelValue::CreateInt64(-1), CelValue::CreateUint64(2)}); result->push_back( {"IntAndLargeUint", CelValue::CreateInt64(1), CelValue::CreateUint64( static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1)}); result->push_back( {"IntAndLargeDouble", CelValue::CreateInt64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::max()) + 1025)}); result->push_back( {"IntAndSmallDouble", CelValue::CreateInt64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::lowest()) - 1025)}); result->push_back( {"UintAndLargeDouble", CelValue::CreateUint64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<uint64_t>::max()) + 2049)}); result->push_back({"NegativeDoubleAndUint", CelValue::CreateDouble(-2.0), CelValue::CreateUint64(123)}); result->push_back({"NanAndDouble", CelValue::CreateDouble(NAN), CelValue::CreateDouble(1.0)}); result->push_back({"NanAndNan", CelValue::CreateDouble(NAN), CelValue::CreateDouble(NAN)}); result->push_back({"DoubleAndNan", CelValue::CreateDouble(1.0), CelValue::CreateDouble(NAN)}); result->push_back( {"IntAndNan", CelValue::CreateInt64(1), CelValue::CreateDouble(NAN)}); result->push_back( {"NanAndInt", CelValue::CreateDouble(NAN), CelValue::CreateInt64(1)}); result->push_back( {"UintAndNan", CelValue::CreateUint64(1), CelValue::CreateDouble(NAN)}); result->push_back( {"NanAndUint", CelValue::CreateDouble(NAN), CelValue::CreateUint64(1)}); return result.release(); }(); return *examples; } using NumericInequalityTest = testing::TestWithParam<NumericInequalityTestCase>; TEST_P(NumericInequalityTest, NumericValues) { NumericInequalityTestCase test_case = GetParam(); absl::optional<bool> result = CelValueEqualImpl(test_case.a, test_case.b); EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, false); } INSTANTIATE_TEST_SUITE_P( InequalityBetweenNumericTypesTest, NumericInequalityTest, ValuesIn(NumericValuesNotEqualExample()), [](const testing::TestParamInfo<NumericInequalityTest::ParamType>& info) { return info.param.name; }); TEST(CelValueEqualImplTest, LossyNumericEquality) { absl::optional<bool> result = CelValueEqualImpl( CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::max()) - 1), CelValue::CreateInt64(std::numeric_limits<int64_t>::max())); EXPECT_TRUE(result.has_value()); EXPECT_TRUE(*result); } TEST(CelValueEqualImplTest, ListMixedTypesInequal) { ContainerBackedListImpl lhs({CelValue::CreateInt64(1)}); ContainerBackedListImpl rhs({CelValue::CreateStringView("abc")}); EXPECT_THAT( CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)), Optional(false)); } TEST(CelValueEqualImplTest, NestedList) { ContainerBackedListImpl inner_lhs({CelValue::CreateInt64(1)}); ContainerBackedListImpl lhs({CelValue::CreateList(&inner_lhs)}); ContainerBackedListImpl inner_rhs({CelValue::CreateNull()}); ContainerBackedListImpl rhs({CelValue::CreateList(&inner_rhs)}); EXPECT_THAT( CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)), Optional(false)); } TEST(CelValueEqualImplTest, MapMixedValueTypesInequal) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, MapMixedKeyTypesEqual) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateUint64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(true)); } TEST(CelValueEqualImplTest, MapMixedKeyTypesInequal) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(2), CelValue::CreateInt64(2)}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, NestedMaps) { std::vector<std::pair<CelValue, CelValue>> inner_lhs_data{ {CelValue::CreateInt64(2), CelValue::CreateStringView("abc")}}; ASSERT_OK_AND_ASSIGN( std::unique_ptr<CelMap> inner_lhs, CreateContainerBackedMap(absl::MakeSpan(inner_lhs_data))); std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateMap(inner_lhs.get())}}; std::vector<std::pair<CelValue, CelValue>> inner_rhs_data{ {CelValue::CreateInt64(2), CelValue::CreateNull()}}; ASSERT_OK_AND_ASSIGN( std::unique_ptr<CelMap> inner_rhs, CreateContainerBackedMap(absl::MakeSpan(inner_rhs_data))); std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateMap(inner_rhs.get())}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityDifferingTypenameInequal) { google::protobuf::Arena arena; TestMessage example; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &example)); CelValue lhs = CelProtoWrapper::CreateMessage(&example, &arena); CelValue rhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityNoAccessorInequal) { google::protobuf::Arena arena; TestMessage example; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &example)); CelValue lhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); CelValue rhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityAny) { google::protobuf::Arena arena; TestMessage packed_value; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &packed_value)); TestMessage lhs; lhs.mutable_any_value()->PackFrom(packed_value); TestMessage rhs; rhs.mutable_any_value()->PackFrom(packed_value); EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena), CelProtoWrapper::CreateMessage(&rhs, &arena)), Optional(true)); lhs.mutable_any_value()->clear_type_url(); rhs.mutable_any_value()->clear_type_url(); EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena), CelProtoWrapper::CreateMessage(&rhs, &arena)), Optional(true)); } bool AddDepsToPool(const google::protobuf::FileDescriptor* descriptor, google::protobuf::DescriptorPool& pool) { for (int i = 0; i < descriptor->dependency_count(); i++) { if (!AddDepsToPool(descriptor->dependency(i), pool)) { return false; } } google::protobuf::FileDescriptorProto descriptor_proto; descriptor->CopyTo(&descriptor_proto); return pool.BuildFile(descriptor_proto) != nullptr; } TEST(CelValueEqualImplTest, DynamicDescriptorAndGeneratedInequal) { google::protobuf::DescriptorPool pool; google::protobuf::DynamicMessageFactory factory; google::protobuf::Arena arena; factory.SetDelegateToGeneratedFactory(false); ASSERT_TRUE(AddDepsToPool(TestMessage::descriptor()->file(), pool)); TestMessage example_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int64_value: 12345 bool_list: false bool_list: true message_value { float_value: 1.0 } )pb", &example_message)); std::unique_ptr<google::protobuf::Message> example_dynamic_message( factory .GetPrototype(pool.FindMessageTypeByName( TestMessage::descriptor()->full_name())) ->New()); ASSERT_TRUE(example_dynamic_message->ParseFromString( example_message.SerializeAsString())); EXPECT_THAT(CelValueEqualImpl( CelProtoWrapper::CreateMessage(&example_message, &arena), CelProtoWrapper::CreateMessage(example_dynamic_message.get(), &arena)), Optional(false)); } TEST(CelValueEqualImplTest, DynamicMessageAndMessageEqual) { google::protobuf::DynamicMessageFactory factory; google::protobuf::Arena arena; factory.SetDelegateToGeneratedFactory(false); TestMessage example_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int64_value: 12345 bool_list: false bool_list: true message_value { float_value: 1.0 } )pb", &example_message)); std::unique_ptr<google::protobuf::Message> example_dynamic_message( factory.GetPrototype(TestMessage::descriptor())->New()); ASSERT_TRUE(example_dynamic_message->ParseFromString( example_message.SerializeAsString())); EXPECT_THAT(CelValueEqualImpl( CelProtoWrapper::CreateMessage(&example_message, &arena), CelProtoWrapper::CreateMessage(example_dynamic_message.get(), &arena)), Optional(true)); } class EqualityFunctionTest : public testing::TestWithParam<std::tuple<EqualityTestCase, bool>> { public: EqualityFunctionTest() { options_.enable_heterogeneous_equality = std::get<1>(GetParam()); options_.enable_empty_wrapper_null_unboxing = true; builder_ = CreateCelExpressionBuilder(options_); } CelFunctionRegistry& registry() { return *builder_->GetRegistry(); } absl::StatusOr<CelValue> Evaluate(absl::string_view expr, const CelValue& lhs, const CelValue& rhs) { CEL_ASSIGN_OR_RETURN(ParsedExpr parsed_expr, parser::Parse(expr)); Activation activation; activation.InsertValue("lhs", lhs); activation.InsertValue("rhs", rhs); CEL_ASSIGN_OR_RETURN(auto expression, builder_->CreateExpression( &parsed_expr.expr(), &parsed_expr.source_info())); return expression->Evaluate(activation, &arena_); } protected: std::unique_ptr<CelExpressionBuilder> builder_; InterpreterOptions options_; google::protobuf::Arena arena_; }; constexpr std::array<CelValue::Type, 11> kEqualableTypes = { CelValue::Type::kInt64, CelValue::Type::kUint64, CelValue::Type::kString, CelValue::Type::kDouble, CelValue::Type::kBytes, CelValue::Type::kDuration, CelValue::Type::kMap, CelValue::Type::kList, CelValue::Type::kBool, CelValue::Type::kTimestamp}; TEST(RegisterEqualityFunctionsTest, EqualDefined) { InterpreterOptions default_options; CelFunctionRegistry registry; ASSERT_OK(RegisterEqualityFunctions(&registry, default_options)); for (CelValue::Type type : kEqualableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kEqual, type)); } } TEST(RegisterEqualityFunctionsTest, InequalDefined) { InterpreterOptions default_options; CelFunctionRegistry registry; ASSERT_OK(RegisterEqualityFunctions(&registry, default_options)); for (CelValue::Type type : kEqualableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kInequal, type)); } } TEST_P(EqualityFunctionTest, SmokeTest) { EqualityTestCase test_case = std::get<0>(GetParam()); google::protobuf::LinkMessageReflection<AttributeContext>(); ASSERT_OK(RegisterEqualityFunctions(&registry(), options_)); ASSERT_OK_AND_ASSIGN(auto result, Evaluate(test_case.expr, test_case.lhs, test_case.rhs)); if (absl::holds_alternative<bool>(test_case.result)) { EXPECT_THAT(result, test::IsCelBool(absl::get<bool>(test_case.result))); } else { switch (absl::get<EqualityTestCase::ErrorKind>(test_case.result)) { case EqualityTestCase::ErrorKind::kMissingOverload: EXPECT_THAT(result, test::IsCelError( StatusIs(absl::StatusCode::kUnknown, HasSubstr("No matching overloads")))) << test_case.expr; break; case EqualityTestCase::ErrorKind::kMissingIdentifier: EXPECT_THAT(result, test::IsCelError( StatusIs(absl::StatusCode::kUnknown, HasSubstr("found in Activation")))); break; default: EXPECT_THAT(result, test::IsCelError(_)); break; } } } INSTANTIATE_TEST_SUITE_P( Equality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null == null", true}, {"true == false", false}, {"1 == 1", true}, {"-2 == -1", false}, {"1.1 == 1.2", false}, {"'a' == 'a'", true}, {"lhs == rhs", false, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs == rhs", false, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs == rhs", true, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(20))}, {"no_such_identifier == 1", EqualityTestCase::ErrorKind::kMissingIdentifier}, {"{1: no_such_identifier} == {1: 1}", EqualityTestCase::ErrorKind::kMissingIdentifier}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P( Inequality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null != null", false}, {"true != false", true}, {"1 != 1", false}, {"-2 != -1", true}, {"1.1 != 1.2", true}, {"'a' != 'a'", false}, {"lhs != rhs", true, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs != rhs", true, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs != rhs", true, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(30))}, {"no_such_identifier != 1", EqualityTestCase::ErrorKind::kMissingIdentifier}, {"{1: no_such_identifier} != {1: 1}", EqualityTestCase::ErrorKind::kMissingIdentifier}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P(HeterogeneousNumericContainers, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>({ {"{1: 2} == {1u: 2}", true}, {"{1: 2} == {2u: 2}", false}, {"{1: 2} == {true: 2}", false}, {"{1: 2} != {1u: 2}", false}, {"{1: 2} != {2u: 2}", true}, {"{1: 2} != {true: 2}", true}, {"[1u, 2u, 3.0] != [1, 2.0, 3]", false}, {"[1u, 2u, 3.0] == [1, 2.0, 3]", true}, {"[1u, 2u, 3.0] != [1, 2.1, 3]", true}, {"[1u, 2u, 3.0] == [1, 2.1, 3]", false}, }), testing::Values(true))); INSTANTIATE_TEST_SUITE_P( HomogenousNumericContainers, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>({ {"{1: 2} == {1u: 2}", false}, {"{1: 2} == {2u: 2}", false}, {"{1: 2} == {true: 2}", false}, {"{1: 2} != {1u: 2}", true}, {"{1: 2} != {2u: 2}", true}, {"{1: 2} != {true: 2}", true}, {"[1u, 2u, 3.0] != [1, 2.0, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, {"[1u, 2u, 3.0] == [1, 2.0, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, {"[1u, 2u, 3.0] != [1, 2.1, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, {"[1u, 2u, 3.0] == [1, 2.1, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, }), testing::Values(false))); INSTANTIATE_TEST_SUITE_P( NullInequalityLegacy, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null != null", false}, {"true != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1 != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"-2 != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1.1 != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"'a' != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"lhs != null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateBytesView("a")}, {"lhs != null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateDuration(absl::Seconds(1))}, {"lhs != null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateTimestamp(absl::FromUnixSeconds(20))}}), testing::Values<bool>(false))); INSTANTIATE_TEST_SUITE_P( NullEqualityLegacy, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null == null", true}, {"true == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1 == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"-2 == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1.1 == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"'a' == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"lhs == null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateBytesView("a")}, {"lhs == null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateDuration(absl::Seconds(1))}, {"lhs == null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateTimestamp(absl::FromUnixSeconds(20))}}), testing::Values<bool>(false))); INSTANTIATE_TEST_SUITE_P( NullInequality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null != null", false}, {"true != null", true}, {"null != false", true}, {"1 != null", true}, {"null != 1", true}, {"-2 != null", true}, {"null != -2", true}, {"1.1 != null", true}, {"null != 1.1", true}, {"'a' != null", true}, {"lhs != null", true, CelValue::CreateBytesView("a")}, {"lhs != null", true, CelValue::CreateDuration(absl::Seconds(1))}, {"google.api.expr.runtime.TestMessage{} != null", true}, {"google.api.expr.runtime.TestMessage{}.string_wrapper_value" " != null", false}, {"google.api.expr.runtime.TestMessage{string_wrapper_value: " "google.protobuf.StringValue{}}.string_wrapper_value != null", true}, {"{} != null", true}, {"[] != null", true}}),
89
cpp
google/cel-cpp
cel_function_registry
eval/public/cel_function_registry.cc
eval/public/cel_function_registry_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_FUNCTION_REGISTRY_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_FUNCTION_REGISTRY_H_ #include <initializer_list> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_map.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "eval/public/cel_function.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "runtime/function_overload_reference.h" #include "runtime/function_registry.h" namespace google::api::expr::runtime { class CelFunctionRegistry { public: using LazyOverload = cel::FunctionRegistry::LazyOverload; CelFunctionRegistry() = default; ~CelFunctionRegistry() = default; using Registrar = absl::Status (*)(CelFunctionRegistry*, const InterpreterOptions&); absl::Status Register(std::unique_ptr<CelFunction> function) { auto descriptor = function->descriptor(); return Register(descriptor, std::move(function)); } absl::Status Register(const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> implementation) { return modern_registry_.Register(descriptor, std::move(implementation)); } absl::Status RegisterAll(std::initializer_list<Registrar> registrars, const InterpreterOptions& opts); absl::Status RegisterLazyFunction(const CelFunctionDescriptor& descriptor) { return modern_registry_.RegisterLazyFunction(descriptor); } std::vector<const CelFunction*> FindOverloads( absl::string_view name, bool receiver_style, const std::vector<CelValue::Type>& types) const; std::vector<cel::FunctionOverloadReference> FindStaticOverloads( absl::string_view name, bool receiver_style, const std::vector<cel::Kind>& types) const { return modern_registry_.FindStaticOverloads(name, receiver_style, types); } std::vector<const CelFunctionDescriptor*> FindLazyOverloads( absl::string_view name, bool receiver_style, const std::vector<CelValue::Type>& types) const; std::vector<LazyOverload> ModernFindLazyOverloads( absl::string_view name, bool receiver_style, const std::vector<CelValue::Type>& types) const { return modern_registry_.FindLazyOverloads(name, receiver_style, types); } absl::node_hash_map<std::string, std::vector<const cel::FunctionDescriptor*>> ListFunctions() const { return modern_registry_.ListFunctions(); } const cel::FunctionRegistry& InternalGetRegistry() const { return modern_registry_; } cel::FunctionRegistry& InternalGetRegistry() { return modern_registry_; } private: cel::FunctionRegistry modern_registry_; mutable absl::Mutex mu_; mutable absl::flat_hash_map<const cel::Function*, std::unique_ptr<CelFunction>> functions_ ABSL_GUARDED_BY(mu_); }; } #endif #include "eval/public/cel_function_registry.h" #include <algorithm> #include <initializer_list> #include <iterator> #include <memory> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/type_provider.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "eval/internal/interop.h" #include "eval/public/cel_function.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "runtime/function_overload_reference.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::extensions::ProtoMemoryManagerRef; class ProxyToModernCelFunction : public CelFunction { public: ProxyToModernCelFunction(const cel::FunctionDescriptor& descriptor, const cel::Function& implementation) : CelFunction(descriptor), implementation_(&implementation) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { auto memory_manager = ProtoMemoryManagerRef(arena); cel::common_internal::LegacyValueManager manager( memory_manager, cel::TypeProvider::Builtin()); cel::FunctionEvaluationContext context(manager); std::vector<cel::Value> modern_args = cel::interop_internal::LegacyValueToModernValueOrDie(arena, args); CEL_ASSIGN_OR_RETURN(auto modern_result, implementation_->Invoke(context, modern_args)); *result = cel::interop_internal::ModernValueToLegacyValueOrDie( arena, modern_result); return absl::OkStatus(); } private: const cel::Function* implementation_; }; } absl::Status CelFunctionRegistry::RegisterAll( std::initializer_list<Registrar> registrars, const InterpreterOptions& opts) { for (Registrar registrar : registrars) { CEL_RETURN_IF_ERROR(registrar(this, opts)); } return absl::OkStatus(); } std::vector<const CelFunction*> CelFunctionRegistry::FindOverloads( absl::string_view name, bool receiver_style, const std::vector<CelValue::Type>& types) const { std::vector<cel::FunctionOverloadReference> matched_funcs = modern_registry_.FindStaticOverloads(name, receiver_style, types); std::vector<const CelFunction*> results; results.reserve(matched_funcs.size()); { absl::MutexLock lock(&mu_); for (cel::FunctionOverloadReference entry : matched_funcs) { std::unique_ptr<CelFunction>& legacy_impl = functions_[&entry.implementation]; if (legacy_impl == nullptr) { legacy_impl = std::make_unique<ProxyToModernCelFunction>( entry.descriptor, entry.implementation); } results.push_back(legacy_impl.get()); } } return results; } std::vector<const CelFunctionDescriptor*> CelFunctionRegistry::FindLazyOverloads( absl::string_view name, bool receiver_style, const std::vector<CelValue::Type>& types) const { std::vector<LazyOverload> lazy_overloads = modern_registry_.FindLazyOverloads(name, receiver_style, types); std::vector<const CelFunctionDescriptor*> result; result.reserve(lazy_overloads.size()); for (const LazyOverload& overload : lazy_overloads) { result.push_back(&overload.descriptor); } return result; } }
#include "eval/public/cel_function_registry.h" #include <memory> #include <tuple> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "base/kind.h" #include "eval/internal/adapter_activation_impl.h" #include "eval/public/activation.h" #include "eval/public/cel_function.h" #include "internal/testing.h" #include "runtime/function_overload_reference.h" namespace google::api::expr::runtime { namespace { using testing::ElementsAre; using testing::Eq; using testing::HasSubstr; using testing::Property; using testing::SizeIs; using testing::Truly; using cel::internal::StatusIs; class ConstCelFunction : public CelFunction { public: ConstCelFunction() : CelFunction(MakeDescriptor()) {} explicit ConstCelFunction(const CelFunctionDescriptor& desc) : CelFunction(desc) {} static CelFunctionDescriptor MakeDescriptor() { return {"ConstFunction", false, {}}; } absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* output, google::protobuf::Arena* arena) const override { *output = CelValue::CreateInt64(42); return absl::OkStatus(); } }; TEST(CelFunctionRegistryTest, InsertAndRetrieveLazyFunction) { CelFunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; CelFunctionRegistry registry; Activation activation; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); const auto descriptors = registry.FindLazyOverloads("LazyFunction", false, {}); EXPECT_THAT(descriptors, testing::SizeIs(1)); } TEST(CelFunctionRegistryTest, LazyAndStaticFunctionShareDescriptorSpace) { CelFunctionRegistry registry; CelFunctionDescriptor desc = ConstCelFunction::MakeDescriptor(); ASSERT_OK(registry.RegisterLazyFunction(desc)); absl::Status status = registry.Register(ConstCelFunction::MakeDescriptor(), std::make_unique<ConstCelFunction>()); EXPECT_FALSE(status.ok()); } TEST(CelFunctionRegistryTest, FindStaticOverloadsReturns) { CelFunctionRegistry registry; CelFunctionDescriptor desc = ConstCelFunction::MakeDescriptor(); ASSERT_OK(registry.Register(desc, std::make_unique<ConstCelFunction>(desc))); std::vector<cel::FunctionOverloadReference> overloads = registry.FindStaticOverloads(desc.name(), false, {}); EXPECT_THAT(overloads, ElementsAre(Truly( [](const cel::FunctionOverloadReference& overload) -> bool { return overload.descriptor.name() == "ConstFunction"; }))) << "Expected single ConstFunction()"; } TEST(CelFunctionRegistryTest, ListFunctions) { CelFunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; CelFunctionRegistry registry; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); EXPECT_OK(registry.Register(ConstCelFunction::MakeDescriptor(), std::make_unique<ConstCelFunction>())); auto registered_functions = registry.ListFunctions(); EXPECT_THAT(registered_functions, SizeIs(2)); EXPECT_THAT(registered_functions["LazyFunction"], SizeIs(1)); EXPECT_THAT(registered_functions["ConstFunction"], SizeIs(1)); } TEST(CelFunctionRegistryTest, LegacyFindLazyOverloads) { CelFunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; CelFunctionRegistry registry; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); ASSERT_OK(registry.Register(ConstCelFunction::MakeDescriptor(), std::make_unique<ConstCelFunction>())); EXPECT_THAT(registry.FindLazyOverloads("LazyFunction", false, {}), ElementsAre(Truly([](const CelFunctionDescriptor* descriptor) { return descriptor->name() == "LazyFunction"; }))) << "Expected single lazy overload for LazyFunction()"; } TEST(CelFunctionRegistryTest, DefaultLazyProvider) { CelFunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; CelFunctionRegistry registry; Activation activation; cel::interop_internal::AdapterActivationImpl modern_activation(activation); EXPECT_OK(registry.RegisterLazyFunction(lazy_function_desc)); EXPECT_OK(activation.InsertFunction( std::make_unique<ConstCelFunction>(lazy_function_desc))); auto providers = registry.ModernFindLazyOverloads("LazyFunction", false, {}); EXPECT_THAT(providers, testing::SizeIs(1)); ASSERT_OK_AND_ASSIGN(auto func, providers[0].provider.GetFunction( lazy_function_desc, modern_activation)); ASSERT_TRUE(func.has_value()); EXPECT_THAT(func->descriptor, Property(&cel::FunctionDescriptor::name, Eq("LazyFunction"))); } TEST(CelFunctionRegistryTest, DefaultLazyProviderNoOverloadFound) { CelFunctionRegistry registry; Activation legacy_activation; cel::interop_internal::AdapterActivationImpl activation(legacy_activation); CelFunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; EXPECT_OK(registry.RegisterLazyFunction(lazy_function_desc)); EXPECT_OK(legacy_activation.InsertFunction( std::make_unique<ConstCelFunction>(lazy_function_desc))); const auto providers = registry.ModernFindLazyOverloads("LazyFunction", false, {}); ASSERT_THAT(providers, testing::SizeIs(1)); const auto& provider = providers[0].provider; auto func = provider.GetFunction({"LazyFunc", false, {cel::Kind::kInt64}}, activation); ASSERT_OK(func.status()); EXPECT_EQ(*func, absl::nullopt); } TEST(CelFunctionRegistryTest, DefaultLazyProviderAmbiguousLookup) { CelFunctionRegistry registry; Activation legacy_activation; cel::interop_internal::AdapterActivationImpl activation(legacy_activation); CelFunctionDescriptor desc1{"LazyFunc", false, {CelValue::Type::kInt64}}; CelFunctionDescriptor desc2{"LazyFunc", false, {CelValue::Type::kUint64}}; CelFunctionDescriptor match_desc{"LazyFunc", false, {CelValue::Type::kAny}}; ASSERT_OK(registry.RegisterLazyFunction(match_desc)); ASSERT_OK(legacy_activation.InsertFunction( std::make_unique<ConstCelFunction>(desc1))); ASSERT_OK(legacy_activation.InsertFunction( std::make_unique<ConstCelFunction>(desc2))); auto providers = registry.ModernFindLazyOverloads("LazyFunc", false, {cel::Kind::kAny}); ASSERT_THAT(providers, testing::SizeIs(1)); const auto& provider = providers[0].provider; auto func = provider.GetFunction(match_desc, activation); EXPECT_THAT(std::string(func.status().message()), HasSubstr("Couldn't resolve function")); } TEST(CelFunctionRegistryTest, CanRegisterNonStrictFunction) { { CelFunctionRegistry registry; CelFunctionDescriptor descriptor("NonStrictFunction", false, {CelValue::Type::kAny}, false); ASSERT_OK(registry.Register( descriptor, std::make_unique<ConstCelFunction>(descriptor))); EXPECT_THAT(registry.FindStaticOverloads("NonStrictFunction", false, {CelValue::Type::kAny}), SizeIs(1)); } { CelFunctionRegistry registry; CelFunctionDescriptor descriptor("NonStrictLazyFunction", false, {CelValue::Type::kAny}, false); EXPECT_OK(registry.RegisterLazyFunction(descriptor)); EXPECT_THAT(registry.FindLazyOverloads("NonStrictLazyFunction", false, {CelValue::Type::kAny}), SizeIs(1)); } } using NonStrictTestCase = std::tuple<bool, bool>; using NonStrictRegistrationFailTest = testing::TestWithParam<NonStrictTestCase>; TEST_P(NonStrictRegistrationFailTest, IfOtherOverloadExistsRegisteringNonStrictFails) { bool existing_function_is_lazy, new_function_is_lazy; std::tie(existing_function_is_lazy, new_function_is_lazy) = GetParam(); CelFunctionRegistry registry; CelFunctionDescriptor descriptor("OverloadedFunction", false, {CelValue::Type::kAny}, true); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK(registry.Register( descriptor, std::make_unique<ConstCelFunction>(descriptor))); } CelFunctionDescriptor new_descriptor( "OverloadedFunction", false, {CelValue::Type::kAny, CelValue::Type::kAny}, false); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register( new_descriptor, std::make_unique<ConstCelFunction>(new_descriptor)); } EXPECT_THAT(status, StatusIs(absl::StatusCode::kAlreadyExists, HasSubstr("Only one overload"))); } TEST_P(NonStrictRegistrationFailTest, IfOtherNonStrictExistsRegisteringStrictFails) { bool existing_function_is_lazy, new_function_is_lazy; std::tie(existing_function_is_lazy, new_function_is_lazy) = GetParam(); CelFunctionRegistry registry; CelFunctionDescriptor descriptor("OverloadedFunction", false, {CelValue::Type::kAny}, false); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK(registry.Register( descriptor, std::make_unique<ConstCelFunction>(descriptor))); } CelFunctionDescriptor new_descriptor( "OverloadedFunction", false, {CelValue::Type::kAny, CelValue::Type::kAny}, true); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register( new_descriptor, std::make_unique<ConstCelFunction>(new_descriptor)); } EXPECT_THAT(status, StatusIs(absl::StatusCode::kAlreadyExists, HasSubstr("Only one overload"))); } TEST_P(NonStrictRegistrationFailTest, CanRegisterStrictFunctionsWithoutLimit) { bool existing_function_is_lazy, new_function_is_lazy; std::tie(existing_function_is_lazy, new_function_is_lazy) = GetParam(); CelFunctionRegistry registry; CelFunctionDescriptor descriptor("OverloadedFunction", false, {CelValue::Type::kAny}, true); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK(registry.Register( descriptor, std::make_unique<ConstCelFunction>(descriptor))); } CelFunctionDescriptor new_descriptor( "OverloadedFunction", false, {CelValue::Type::kAny, CelValue::Type::kAny}, true); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register( new_descriptor, std::make_unique<ConstCelFunction>(new_descriptor)); } EXPECT_OK(status); } INSTANTIATE_TEST_SUITE_P(NonStrictRegistrationFailTest, NonStrictRegistrationFailTest, testing::Combine(testing::Bool(), testing::Bool())); } }
90
cpp
google/cel-cpp
activation_bind_helper
eval/public/activation_bind_helper.cc
eval/public/activation_bind_helper_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_ACTIVATION_BIND_HELPER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_ACTIVATION_BIND_HELPER_H_ #include "eval/public/activation.h" namespace google { namespace api { namespace expr { namespace runtime { enum class ProtoUnsetFieldOptions { kSkip, kBindDefault }; absl::Status BindProtoToActivation( const google::protobuf::Message* message, google::protobuf::Arena* arena, Activation* activation, ProtoUnsetFieldOptions options = ProtoUnsetFieldOptions::kSkip); } } } } #endif #include "eval/public/activation_bind_helper.h" #include "absl/status/status.h" #include "eval/public/containers/field_access.h" #include "eval/public/containers/field_backed_list_impl.h" #include "eval/public/containers/field_backed_map_impl.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { using google::protobuf::Arena; using google::protobuf::Message; using google::protobuf::FieldDescriptor; using google::protobuf::Descriptor; absl::Status CreateValueFromField(const google::protobuf::Message* msg, const FieldDescriptor* field_desc, google::protobuf::Arena* arena, CelValue* result) { if (field_desc->is_map()) { *result = CelValue::CreateMap(google::protobuf::Arena::Create<FieldBackedMapImpl>( arena, msg, field_desc, arena)); return absl::OkStatus(); } else if (field_desc->is_repeated()) { *result = CelValue::CreateList(google::protobuf::Arena::Create<FieldBackedListImpl>( arena, msg, field_desc, arena)); return absl::OkStatus(); } else { return CreateValueFromSingleField(msg, field_desc, arena, result); } } } absl::Status BindProtoToActivation(const Message* message, Arena* arena, Activation* activation, ProtoUnsetFieldOptions options) { if (arena == nullptr) { return absl::InvalidArgumentError( "arena must not be null for BindProtoToActivation."); } const Descriptor* desc = message->GetDescriptor(); const google::protobuf::Reflection* reflection = message->GetReflection(); for (int i = 0; i < desc->field_count(); i++) { CelValue value; const FieldDescriptor* field_desc = desc->field(i); if (options == ProtoUnsetFieldOptions::kSkip) { if (!field_desc->is_repeated() && !reflection->HasField(*message, field_desc)) { continue; } } auto status = CreateValueFromField(message, field_desc, arena, &value); if (!status.ok()) { return status; } activation->InsertValue(field_desc->name(), value); } return absl::OkStatus(); } } } } }
#include "eval/public/activation_bind_helper.h" #include "absl/status/status.h" #include "eval/public/activation.h" #include "eval/testutil/test_message.pb.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "testutil/util.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { using testutil::EqualsProto; TEST(ActivationBindHelperTest, TestSingleBoolBind) { TestMessage message; message.set_bool_value(true); google::protobuf::Arena arena; Activation activation; ASSERT_OK(BindProtoToActivation(&message, &arena, &activation)); auto result = activation.FindValue("bool_value", &arena); ASSERT_TRUE(result.has_value()); CelValue value = result.value(); ASSERT_TRUE(value.IsBool()); EXPECT_EQ(value.BoolOrDie(), true); } TEST(ActivationBindHelperTest, TestSingleInt32Bind) { TestMessage message; message.set_int32_value(42); google::protobuf::Arena arena; Activation activation; ASSERT_OK(BindProtoToActivation(&message, &arena, &activation)); auto result = activation.FindValue("int32_value", &arena); ASSERT_TRUE(result.has_value()); CelValue value = result.value(); ASSERT_TRUE(value.IsInt64()); EXPECT_EQ(value.Int64OrDie(), 42); } TEST(ActivationBindHelperTest, TestUnsetRepeatedIsEmptyList) { TestMessage message; google::protobuf::Arena arena; Activation activation; ASSERT_OK(BindProtoToActivation(&message, &arena, &activation)); auto result = activation.FindValue("int32_list", &arena); ASSERT_TRUE(result.has_value()); CelValue value = result.value(); ASSERT_TRUE(value.IsList()); EXPECT_TRUE(value.ListOrDie()->empty()); } TEST(ActivationBindHelperTest, TestSkipUnsetFields) { TestMessage message; message.set_int32_value(42); google::protobuf::Arena arena; Activation activation; ASSERT_OK(BindProtoToActivation(&message, &arena, &activation, ProtoUnsetFieldOptions::kSkip)); auto result = activation.FindValue("int32_value", &arena); ASSERT_TRUE(result.has_value()); CelValue value = result.value(); ASSERT_TRUE(value.IsInt64()); EXPECT_EQ(value.Int64OrDie(), 42); result = activation.FindValue("message_value", &arena); ASSERT_FALSE(result.has_value()); } TEST(ActivationBindHelperTest, TestBindDefaultFields) { TestMessage message; message.set_int32_value(42); google::protobuf::Arena arena; Activation activation; ASSERT_OK(BindProtoToActivation(&message, &arena, &activation, ProtoUnsetFieldOptions::kBindDefault)); auto result = activation.FindValue("int32_value", &arena); ASSERT_TRUE(result.has_value()); CelValue value = result.value(); ASSERT_TRUE(value.IsInt64()); EXPECT_EQ(value.Int64OrDie(), 42); result = activation.FindValue("message_value", &arena); ASSERT_TRUE(result.has_value()); EXPECT_NE(nullptr, result->MessageOrDie()); EXPECT_THAT(TestMessage::default_instance(), EqualsProto(*result->MessageOrDie())); } TEST(ActivationBindHelperTest, RejectsNullArena) { TestMessage message; message.set_bool_value(true); Activation activation; ASSERT_EQ(BindProtoToActivation(&message, nullptr, &activation), absl::InvalidArgumentError( "arena must not be null for BindProtoToActivation.")); } } } } } }
91
cpp
google/cel-cpp
unknown_function_result_set
eval/public/unknown_function_result_set.cc
eval/public/unknown_function_result_set_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_UNKNOWN_FUNCTION_RESULT_SET_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_UNKNOWN_FUNCTION_RESULT_SET_H_ #include "base/function_result.h" #include "base/function_result_set.h" namespace google { namespace api { namespace expr { namespace runtime { using UnknownFunctionResult = ::cel::FunctionResult; using UnknownFunctionResultSet = ::cel::FunctionResultSet; } } } } #endif #include "eval/public/unknown_function_result_set.h"
#include "eval/public/unknown_function_result_set.h" #include <sys/ucontext.h> #include <memory> #include <string> #include "google/protobuf/duration.pb.h" #include "google/protobuf/empty.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/arena.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "eval/public/cel_function.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 "internal/testing.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { using ::google::protobuf::ListValue; using ::google::protobuf::Struct; using ::google::protobuf::Arena; using testing::Eq; using testing::SizeIs; CelFunctionDescriptor kTwoInt("TwoInt", false, {CelValue::Type::kInt64, CelValue::Type::kInt64}); CelFunctionDescriptor kOneInt("OneInt", false, {CelValue::Type::kInt64}); TEST(UnknownFunctionResult, Equals) { UnknownFunctionResult call1(kTwoInt, 0); UnknownFunctionResult call2(kTwoInt, 0); EXPECT_TRUE(call1.IsEqualTo(call2)); UnknownFunctionResult call3(kOneInt, 0); UnknownFunctionResult call4(kOneInt, 0); EXPECT_TRUE(call3.IsEqualTo(call4)); UnknownFunctionResultSet call_set({call1, call3}); EXPECT_EQ(call_set.size(), 2); EXPECT_EQ(*call_set.begin(), call3); EXPECT_EQ(*(++call_set.begin()), call1); } TEST(UnknownFunctionResult, InequalDescriptor) { UnknownFunctionResult call1(kTwoInt, 0); UnknownFunctionResult call2(kOneInt, 0); EXPECT_FALSE(call1.IsEqualTo(call2)); CelFunctionDescriptor one_uint("OneInt", false, {CelValue::Type::kUint64}); UnknownFunctionResult call3(kOneInt, 0); UnknownFunctionResult call4(one_uint, 0); EXPECT_FALSE(call3.IsEqualTo(call4)); UnknownFunctionResultSet call_set({call1, call3, call4}); EXPECT_EQ(call_set.size(), 3); auto it = call_set.begin(); EXPECT_EQ(*it++, call3); EXPECT_EQ(*it++, call4); EXPECT_EQ(*it++, call1); } } } } } }
92
cpp
google/cel-cpp
cel_value
eval/public/cel_value.cc
eval/public/cel_value_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_VALUE_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_VALUE_H_ #include <cstdint> #include "google/protobuf/message.h" #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/optimization.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/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "base/kind.h" #include "common/memory.h" #include "common/native_type.h" #include "eval/public/cel_value_internal.h" #include "eval/public/message_wrapper.h" #include "eval/public/unknown_set.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "internal/utf8.h" namespace cel::interop_internal { struct CelListAccess; struct CelMapAccess; } namespace google::api::expr::runtime { using CelError = absl::Status; class CelList; class CelMap; class LegacyTypeAdapter; class CelValue { public: template <int N> class StringHolderBase { public: StringHolderBase() : value_(absl::string_view()) {} StringHolderBase(const StringHolderBase&) = default; StringHolderBase& operator=(const StringHolderBase&) = default; explicit StringHolderBase(const std::string* str) : value_(*str) {} absl::string_view value() const { return value_; } friend bool operator==(StringHolderBase value1, StringHolderBase value2) { return value1.value_ == value2.value_; } friend bool operator!=(StringHolderBase value1, StringHolderBase value2) { return value1.value_ != value2.value_; } friend bool operator<(StringHolderBase value1, StringHolderBase value2) { return value1.value_ < value2.value_; } friend bool operator<=(StringHolderBase value1, StringHolderBase value2) { return value1.value_ <= value2.value_; } friend bool operator>(StringHolderBase value1, StringHolderBase value2) { return value1.value_ > value2.value_; } friend bool operator>=(StringHolderBase value1, StringHolderBase value2) { return value1.value_ >= value2.value_; } friend class CelValue; private: explicit StringHolderBase(absl::string_view other) : value_(other) {} absl::string_view value_; }; using StringHolder = StringHolderBase<0>; using BytesHolder = StringHolderBase<1>; using CelTypeHolder = StringHolderBase<2>; using NullType = absl::monostate; using MessageWrapper = google::api::expr::runtime::MessageWrapper; private: using ValueHolder = internal::ValueHolder< NullType, bool, int64_t, uint64_t, double, StringHolder, BytesHolder, MessageWrapper, absl::Duration, absl::Time, const CelList*, const CelMap*, const UnknownSet*, CelTypeHolder, const CelError*>; public: template <class T> using IndexOf = ValueHolder::IndexOf<T>; using Type = ::cel::Kind; enum class LegacyType { kNullType = IndexOf<NullType>::value, kBool = IndexOf<bool>::value, kInt64 = IndexOf<int64_t>::value, kUint64 = IndexOf<uint64_t>::value, kDouble = IndexOf<double>::value, kString = IndexOf<StringHolder>::value, kBytes = IndexOf<BytesHolder>::value, kMessage = IndexOf<MessageWrapper>::value, kDuration = IndexOf<absl::Duration>::value, kTimestamp = IndexOf<absl::Time>::value, kList = IndexOf<const CelList*>::value, kMap = IndexOf<const CelMap*>::value, kUnknownSet = IndexOf<const UnknownSet*>::value, kCelType = IndexOf<CelTypeHolder>::value, kError = IndexOf<const CelError*>::value, kAny }; CelValue() : CelValue(NullType()) {} Type type() const { return static_cast<Type>(value_.index()); } const std::string DebugString() const; static CelValue CreateNull() { return CelValue(NullType()); } static CelValue CreateNullTypedValue() { return CelValue(NullType()); } static CelValue CreateBool(bool value) { return CelValue(value); } static CelValue CreateInt64(int64_t value) { return CelValue(value); } static CelValue CreateUint64(uint64_t value) { return CelValue(value); } static CelValue CreateDouble(double value) { return CelValue(value); } static CelValue CreateString(StringHolder holder) { ABSL_ASSERT(::cel::internal::Utf8IsValid(holder.value())); return CelValue(holder); } static CelValue CreateStringView(absl::string_view value) { return CelValue(StringHolder(value)); } static CelValue CreateString(const std::string* str) { return CelValue(StringHolder(str)); } static CelValue CreateBytes(BytesHolder holder) { return CelValue(holder); } static CelValue CreateBytesView(absl::string_view value) { return CelValue(BytesHolder(value)); } static CelValue CreateBytes(const std::string* str) { return CelValue(BytesHolder(str)); } static CelValue CreateDuration(absl::Duration value); static CelValue CreateUncheckedDuration(absl::Duration value) { return CelValue(value); } static CelValue CreateTimestamp(absl::Time value) { return CelValue(value); } static CelValue CreateList(const CelList* value) { CheckNullPointer(value, Type::kList); return CelValue(value); } static CelValue CreateList(); static CelValue CreateMap(const CelMap* value) { CheckNullPointer(value, Type::kMap); return CelValue(value); } static CelValue CreateMap(); static CelValue CreateUnknownSet(const UnknownSet* value) { CheckNullPointer(value, Type::kUnknownSet); return CelValue(value); } static CelValue CreateCelType(CelTypeHolder holder) { return CelValue(holder); } static CelValue CreateCelTypeView(absl::string_view value) { return CelValue(CelTypeHolder(value)); } static CelValue CreateError(const CelError* value) { CheckNullPointer(value, Type::kError); return CelValue(value); } static absl::Status CheckMapKeyType(const CelValue& key); CelValue ObtainCelType() const; bool BoolOrDie() const { return GetValueOrDie<bool>(Type::kBool); } int64_t Int64OrDie() const { return GetValueOrDie<int64_t>(Type::kInt64); } uint64_t Uint64OrDie() const { return GetValueOrDie<uint64_t>(Type::kUint64); } double DoubleOrDie() const { return GetValueOrDie<double>(Type::kDouble); } StringHolder StringOrDie() const { return GetValueOrDie<StringHolder>(Type::kString); } BytesHolder BytesOrDie() const { return GetValueOrDie<BytesHolder>(Type::kBytes); } const google::protobuf::Message* MessageOrDie() const { MessageWrapper wrapped = MessageWrapperOrDie(); ABSL_ASSERT(wrapped.HasFullProto()); return static_cast<const google::protobuf::Message*>(wrapped.message_ptr()); } MessageWrapper MessageWrapperOrDie() const { return GetValueOrDie<MessageWrapper>(Type::kMessage); } const absl::Duration DurationOrDie() const { return GetValueOrDie<absl::Duration>(Type::kDuration); } const absl::Time TimestampOrDie() const { return GetValueOrDie<absl::Time>(Type::kTimestamp); } const CelList* ListOrDie() const { return GetValueOrDie<const CelList*>(Type::kList); } const CelMap* MapOrDie() const { return GetValueOrDie<const CelMap*>(Type::kMap); } CelTypeHolder CelTypeOrDie() const { return GetValueOrDie<CelTypeHolder>(Type::kCelType); } const UnknownSet* UnknownSetOrDie() const { return GetValueOrDie<const UnknownSet*>(Type::kUnknownSet); } const CelError* ErrorOrDie() const { return GetValueOrDie<const CelError*>(Type::kError); } bool IsNull() const { return value_.template Visit<bool>(NullCheckOp()); } bool IsBool() const { return value_.is<bool>(); } bool IsInt64() const { return value_.is<int64_t>(); } bool IsUint64() const { return value_.is<uint64_t>(); } bool IsDouble() const { return value_.is<double>(); } bool IsString() const { return value_.is<StringHolder>(); } bool IsBytes() const { return value_.is<BytesHolder>(); } bool IsMessage() const { return value_.is<MessageWrapper>(); } bool IsDuration() const { return value_.is<absl::Duration>(); } bool IsTimestamp() const { return value_.is<absl::Time>(); } bool IsList() const { return value_.is<const CelList*>(); } bool IsMap() const { return value_.is<const CelMap*>(); } bool IsUnknownSet() const { return value_.is<const UnknownSet*>(); } bool IsCelType() const { return value_.is<CelTypeHolder>(); } bool IsError() const { return value_.is<const CelError*>(); } template <class ReturnType, class Op> ReturnType InternalVisit(Op&& op) const { return value_.template Visit<ReturnType>(std::forward<Op>(op)); } template <class ReturnType, class Op> ReturnType Visit(Op&& op) const { return value_.template Visit<ReturnType>( internal::MessageVisitAdapter<Op, ReturnType>(std::forward<Op>(op))); } template <typename Arg> bool GetValue(Arg* value) const { return this->template InternalVisit<bool>(AssignerOp<Arg>(value)); } static std::string TypeName(Type value_type); static CelValue CreateMessageWrapper(MessageWrapper value) { CheckNullPointer(value.message_ptr(), Type::kMessage); CheckNullPointer(value.legacy_type_info(), Type::kMessage); return CelValue(value); } private: ValueHolder value_; template <typename T, class = void> struct AssignerOp { explicit AssignerOp(T* val) : value(val) {} template <typename U> bool operator()(const U&) { return false; } bool operator()(const T& arg) { *value = arg; return true; } T* value; }; template <typename T> struct AssignerOp< T, std::enable_if_t<std::is_same_v<T, const google::protobuf::Message*>>> { explicit AssignerOp(const google::protobuf::Message** val) : value(val) {} template <typename U> bool operator()(const U&) { return false; } bool operator()(const MessageWrapper& held_value) { if (!held_value.HasFullProto()) { return false; } *value = static_cast<const google::protobuf::Message*>(held_value.message_ptr()); return true; } const google::protobuf::Message** value; }; struct NullCheckOp { template <typename T> bool operator()(const T&) const { return false; } bool operator()(NullType) const { return true; } bool operator()(const MessageWrapper& arg) const { return arg.message_ptr() == nullptr; } }; template <class T> explicit CelValue(T value) : value_(value) {} static void CrashNullPointer(Type type) ABSL_ATTRIBUTE_COLD { ABSL_LOG(FATAL) << "Null pointer supplied for " << TypeName(type); } static void CheckNullPointer(const void* ptr, Type type) { if (ABSL_PREDICT_FALSE(ptr == nullptr)) { CrashNullPointer(type); } } static void CrashTypeMismatch(Type requested_type, Type actual_type) ABSL_ATTRIBUTE_COLD { ABSL_LOG(FATAL) << "Type mismatch" << ": expected " << TypeName(requested_type) << ", encountered " << TypeName(actual_type); } template <class T> T GetValueOrDie(Type requested_type) const { auto value_ptr = value_.get<T>(); if (ABSL_PREDICT_FALSE(value_ptr == nullptr)) { CrashTypeMismatch(requested_type, type()); } return *value_ptr; } friend class CelProtoWrapper; friend class ProtoMessageTypeAdapter; friend class EvaluatorStack; friend class TestOnly_FactoryAccessor; }; static_assert(absl::is_trivially_destructible<CelValue>::value, "Non-trivially-destructible CelValue impacts " "performance"); class CelList { public: virtual CelValue operator[](int index) const = 0; virtual CelValue Get(google::protobuf::Arena* arena, int index) const { static_cast<void>(arena); return (*this)[index]; } virtual int size() const = 0; virtual bool empty() const { return size() == 0; } virtual ~CelList() {} private: friend struct cel::interop_internal::CelListAccess; friend struct cel::NativeTypeTraits<CelList>; virtual cel::NativeTypeId GetNativeTypeId() const { return cel::NativeTypeId(); } }; class CelMap { public: virtual absl::optional<CelValue> operator[](CelValue key) const = 0; virtual absl::optional<CelValue> Get(google::protobuf::Arena* arena, CelValue key) const { static_cast<void>(arena); return (*this)[key]; } virtual absl::StatusOr<bool> Has(const CelValue& key) const { CEL_RETURN_IF_ERROR(CelValue::CheckMapKeyType(key)); google::protobuf::Arena arena; auto value = (*this).Get(&arena, key); if (!value.has_value()) { return false; } if (value->IsError()) { return *value->ErrorOrDie(); } return true; } virtual int size() const = 0; virtual bool empty() const { return size() == 0; } virtual absl::StatusOr<const CelList*> ListKeys() const = 0; virtual absl::StatusOr<const CelList*> ListKeys(google::protobuf::Arena* arena) const { static_cast<void>(arena); return ListKeys(); } virtual ~CelMap() {} private: friend struct cel::interop_internal::CelMapAccess; friend struct cel::NativeTypeTraits<CelMap>; virtual cel::NativeTypeId GetNativeTypeId() const { return cel::NativeTypeId(); } }; CelValue CreateErrorValue( cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::string_view message, absl::StatusCode error_code = absl::StatusCode::kUnknown); CelValue CreateErrorValue( google::protobuf::Arena* arena, absl::string_view message, absl::StatusCode error_code = absl::StatusCode::kUnknown); CelValue CreateErrorValue(cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, const absl::Status& status); CelValue CreateErrorValue(google::protobuf::Arena* arena, const absl::Status& status); CelValue CreateNoMatchingOverloadError(cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::string_view fn = ""); ABSL_DEPRECATED("Prefer using the generic MemoryManager overload") CelValue CreateNoMatchingOverloadError(google::protobuf::Arena* arena, absl::string_view fn = ""); bool CheckNoMatchingOverloadError(CelValue value); CelValue CreateNoSuchFieldError(cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::string_view field = ""); ABSL_DEPRECATED("Prefer using the generic MemoryManager overload") CelValue CreateNoSuchFieldError(google::protobuf::Arena* arena, absl::string_view field = ""); CelValue CreateNoSuchKeyError(cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::string_view key); ABSL_DEPRECATED("Prefer using the generic MemoryManager overload") CelValue CreateNoSuchKeyError(google::protobuf::Arena* arena, absl::string_view key); bool CheckNoSuchKeyError(CelValue value); CelValue CreateMissingAttributeError(cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::string_view missing_attribute_path); ABSL_DEPRECATED("Prefer using the generic MemoryManager overload") CelValue CreateMissingAttributeError(google::protobuf::Arena* arena, absl::string_view missing_attribute_path); ABSL_CONST_INIT extern const absl::string_view kPayloadUrlMissingAttributePath; bool IsMissingAttributeError(const CelValue& value); CelValue CreateUnknownFunctionResultError(cel::MemoryManagerRef manager ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::string_view help_message); ABSL_DEPRECATED("Prefer using the generic MemoryManager overload") CelValue CreateUnknownFunctionResultError(google::protobuf::Arena* arena, absl::string_view help_message); bool IsUnknownFunctionResult(const CelValue& value); } namespace cel { template <> struct NativeTypeTraits<google::api::expr::runtime::CelList> final { static NativeTypeId Id(const google::api::expr::runtime::CelList& cel_list) { return cel_list.GetNativeTypeId(); } }; template <typename T> struct NativeTypeTraits< T, std::enable_if_t<std::conjunction_v< std::is_base_of<google::api::expr::runtime::CelList, T>, std::negation<std::is_same<T, google::api::expr::runtime::CelList>>>>> final { static NativeTypeId Id(const google::api::expr::runtime::CelList& cel_list) { return NativeTypeTraits<google::api::expr::runtime::CelList>::Id(cel_list); } }; template <> struct NativeTypeTraits<google::api::expr::runtime::CelMap> final { static NativeTypeId Id(const google::api::expr::runtime::CelMap& cel_map) { return cel_map.GetNativeTypeId(); } }; template <typename T> struct NativeTypeTraits< T, std::enable_if_t<std::conjunction_v< std::is_base_of<google::api::expr::runtime::CelMap, T>, std::negation<std::is_same<T, google::api::expr::runtime::CelMap>>>>> final { static NativeTypeId Id(const google::api::expr::runtime::CelMap& cel_map) { return NativeTypeTraits<google::api::expr::runtime::CelMap>::Id(cel_map); } }; } #endif #include "eval/public/cel_value.h" #include <cstdint> #include <string> #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) { const CelList* keys = arg->ListKeys(arena).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:
#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 ::cel::extensions::ProtoMemoryManagerRef; using ::cel::runtime_internal::kDurationHigh; using ::cel::runtime_internal::kDurationLow; using testing::Eq; using testing::HasSubstr; using testing::NotNull; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; 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)); } }
93
cpp
google/cel-cpp
source_position
eval/public/source_position.cc
eval/public/source_position_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_SOURCE_POSITION_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_SOURCE_POSITION_H_ #include "google/api/expr/v1alpha1/syntax.pb.h" namespace google { namespace api { namespace expr { namespace runtime { class SourcePosition { public: SourcePosition(const int64_t expr_id, const google::api::expr::v1alpha1::SourceInfo* source_info) : expr_id_(expr_id), source_info_(source_info) {} SourcePosition(const SourcePosition& other) = delete; SourcePosition& operator=(const SourcePosition& other) = delete; virtual ~SourcePosition() {} int32_t line() const; int32_t column() const; int32_t character_offset() const; private: const int64_t expr_id_; const google::api::expr::v1alpha1::SourceInfo* source_info_; }; } } } } #endif #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)); } } } } } }
94
cpp
google/cel-cpp
cel_number
eval/public/cel_number.cc
eval/public/cel_number_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_NUMERIC_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_NUMERIC_H_ #include <cmath> #include <cstdint> #include <limits> #include "absl/types/optional.h" #include "eval/public/cel_value.h" #include "internal/number.h" namespace google::api::expr::runtime { using CelNumber = cel::internal::Number; absl::optional<CelNumber> GetNumberFromCelValue(const CelValue& value); } #endif #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); } } }
95
cpp
google/cel-cpp
comparison_functions
eval/public/comparison_functions.cc
eval/public/comparison_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_COMPARISON_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_COMPARISON_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterComparisonFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/comparison_functions.h" #include <cstdint> #include "absl/status/status.h" #include "absl/time/time.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::cel::internal::Number; template <class Type> bool LessThan(ValueManager&, Type t1, Type t2) { return (t1 < t2); } template <class Type> bool LessThanOrEqual(ValueManager&, Type t1, Type t2) { return (t1 <= t2); } template <class Type> bool GreaterThan(ValueManager& factory, Type t1, Type t2) { return LessThan(factory, t2, t1); } template <class Type> bool GreaterThanOrEqual(ValueManager& factory, Type t1, Type t2) { return LessThanOrEqual(factory, t2, t1); } template <> bool LessThan(ValueManager&, const StringValue& t1, const StringValue& t2) { return t1.Compare(t2) < 0; } template <> bool LessThanOrEqual(ValueManager&, const StringValue& t1, const StringValue& t2) { return t1.Compare(t2) <= 0; } template <> bool GreaterThan(ValueManager&, const StringValue& t1, const StringValue& t2) { return t1.Compare(t2) > 0; } template <> bool GreaterThanOrEqual(ValueManager&, const StringValue& t1, const StringValue& t2) { return t1.Compare(t2) >= 0; } template <> bool LessThan(ValueManager&, const BytesValue& t1, const BytesValue& t2) { return t1.Compare(t2) < 0; } template <> bool LessThanOrEqual(ValueManager&, const BytesValue& t1, const BytesValue& t2) { return t1.Compare(t2) <= 0; } template <> bool GreaterThan(ValueManager&, const BytesValue& t1, const BytesValue& t2) { return t1.Compare(t2) > 0; } template <> bool GreaterThanOrEqual(ValueManager&, const BytesValue& t1, const BytesValue& t2) { return t1.Compare(t2) >= 0; } template <> bool LessThan(ValueManager&, absl::Duration t1, absl::Duration t2) { return absl::operator<(t1, t2); } template <> bool LessThanOrEqual(ValueManager&, absl::Duration t1, absl::Duration t2) { return absl::operator<=(t1, t2); } template <> bool GreaterThan(ValueManager&, absl::Duration t1, absl::Duration t2) { return absl::operator>(t1, t2); } template <> bool GreaterThanOrEqual(ValueManager&, absl::Duration t1, absl::Duration t2) { return absl::operator>=(t1, t2); } template <> bool LessThan(ValueManager&, absl::Time t1, absl::Time t2) { return absl::operator<(t1, t2); } template <> bool LessThanOrEqual(ValueManager&, absl::Time t1, absl::Time t2) { return absl::operator<=(t1, t2); } template <> bool GreaterThan(ValueManager&, absl::Time t1, absl::Time t2) { return absl::operator>(t1, t2); } template <> bool GreaterThanOrEqual(ValueManager&, absl::Time t1, absl::Time t2) { return absl::operator>=(t1, t2); } template <typename T, typename U> bool CrossNumericLessThan(ValueManager&, T t, U u) { return Number(t) < Number(u); } template <typename T, typename U> bool CrossNumericGreaterThan(ValueManager&, T t, U u) { return Number(t) > Number(u); } template <typename T, typename U> bool CrossNumericLessOrEqualTo(ValueManager&, T t, U u) { return Number(t) <= Number(u); } template <typename T, typename U> bool CrossNumericGreaterOrEqualTo(ValueManager&, T t, U u) { return Number(t) >= Number(u); } template <class Type> absl::Status RegisterComparisonFunctionsForType( cel::FunctionRegistry& registry) { using FunctionAdapter = BinaryFunctionAdapter<bool, Type, Type>; CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kLess, false), FunctionAdapter::WrapFunction(LessThan<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kLessOrEqual, false), FunctionAdapter::WrapFunction(LessThanOrEqual<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kGreater, false), FunctionAdapter::WrapFunction(GreaterThan<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kGreaterOrEqual, false), FunctionAdapter::WrapFunction(GreaterThanOrEqual<Type>))); return absl::OkStatus(); } absl::Status RegisterHomogenousComparisonFunctions( cel::FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<bool>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<int64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<uint64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<double>(registry)); CEL_RETURN_IF_ERROR( RegisterComparisonFunctionsForType<const StringValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterComparisonFunctionsForType<const BytesValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterComparisonFunctionsForType<absl::Duration>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<absl::Time>(registry)); return absl::OkStatus(); } template <typename T, typename U> absl::Status RegisterCrossNumericComparisons(cel::FunctionRegistry& registry) { using FunctionAdapter = BinaryFunctionAdapter<bool, T, U>; CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kLess, false), FunctionAdapter::WrapFunction(&CrossNumericLessThan<T, U>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kGreater, false), FunctionAdapter::WrapFunction(&CrossNumericGreaterThan<T, U>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kGreaterOrEqual, false), FunctionAdapter::WrapFunction(&CrossNumericGreaterOrEqualTo<T, U>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kLessOrEqual, false), FunctionAdapter::WrapFunction(&CrossNumericLessOrEqualTo<T, U>))); return absl::OkStatus(); } absl::Status RegisterHeterogeneousComparisonFunctions( cel::FunctionRegistry& registry) { CEL_RETURN_IF_ERROR( (RegisterCrossNumericComparisons<double, int64_t>(registry))); CEL_RETURN_IF_ERROR( (RegisterCrossNumericComparisons<double, uint64_t>(registry))); CEL_RETURN_IF_ERROR( (RegisterCrossNumericComparisons<uint64_t, double>(registry))); CEL_RETURN_IF_ERROR( (RegisterCrossNumericComparisons<uint64_t, int64_t>(registry))); CEL_RETURN_IF_ERROR( (RegisterCrossNumericComparisons<int64_t, double>(registry))); CEL_RETURN_IF_ERROR( (RegisterCrossNumericComparisons<int64_t, uint64_t>(registry))); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<bool>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<int64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<uint64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<double>(registry)); CEL_RETURN_IF_ERROR( RegisterComparisonFunctionsForType<const StringValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterComparisonFunctionsForType<const BytesValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterComparisonFunctionsForType<absl::Duration>(registry)); CEL_RETURN_IF_ERROR(RegisterComparisonFunctionsForType<absl::Time>(registry)); return absl::OkStatus(); } } absl::Status RegisterComparisonFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (options.enable_heterogeneous_equality) { CEL_RETURN_IF_ERROR(RegisterHeterogeneousComparisonFunctions(registry)); } else { CEL_RETURN_IF_ERROR(RegisterHomogenousComparisonFunctions(registry)); } return absl::OkStatus(); } }
#include "runtime/standard/comparison_functions.h" #include <array> #include "absl/strings/str_cat.h" #include "base/builtins.h" #include "base/kind.h" #include "internal/testing.h" namespace cel { namespace { MATCHER_P2(DefinesHomogenousOverload, name, argument_kind, absl::StrCat(name, " for ", KindToString(argument_kind))) { const cel::FunctionRegistry& registry = arg; return !registry .FindStaticOverloads(name, false, {argument_kind, argument_kind}) .empty(); } constexpr std::array<Kind, 8> kOrderableTypes = { Kind::kBool, Kind::kInt64, Kind::kUint64, Kind::kString, Kind::kDouble, Kind::kBytes, Kind::kDuration, Kind::kTimestamp}; TEST(RegisterComparisonFunctionsTest, LessThanDefined) { RuntimeOptions default_options; FunctionRegistry registry; ASSERT_OK(RegisterComparisonFunctions(registry, default_options)); for (Kind kind : kOrderableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kLess, kind)); } } TEST(RegisterComparisonFunctionsTest, LessThanOrEqualDefined) { RuntimeOptions default_options; FunctionRegistry registry; ASSERT_OK(RegisterComparisonFunctions(registry, default_options)); for (Kind kind : kOrderableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kLessOrEqual, kind)); } } TEST(RegisterComparisonFunctionsTest, GreaterThanDefined) { RuntimeOptions default_options; FunctionRegistry registry; ASSERT_OK(RegisterComparisonFunctions(registry, default_options)); for (Kind kind : kOrderableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kGreater, kind)); } } TEST(RegisterComparisonFunctionsTest, GreaterThanOrEqualDefined) { RuntimeOptions default_options; FunctionRegistry registry; ASSERT_OK(RegisterComparisonFunctions(registry, default_options)); for (Kind kind : kOrderableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kGreaterOrEqual, kind)); } } } }
96
cpp
google/cel-cpp
set_util
eval/public/set_util.cc
eval/public/set_util_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_SET_UTIL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_SET_UTIL_H_ #include "eval/public/cel_value.h" namespace google { namespace api { namespace expr { namespace runtime { bool CelValueLessThan(CelValue lhs, CelValue rhs); bool CelValueEqual(CelValue lhs, CelValue rhs); bool CelValueGreaterThan(CelValue lhs, CelValue rhs); int CelValueCompare(CelValue lhs, CelValue rhs); using CelValueLessThanComparator = decltype(&CelValueLessThan); using CelValueEqualComparator = decltype(&CelValueEqual); using CelValueGreaterThanComparator = decltype(&CelValueGreaterThan); } } } } #endif #include "eval/public/set_util.h" #include <algorithm> #include <vector> namespace google::api::expr::runtime { namespace { template <typename T> int ComparisonImpl(T lhs, T rhs) { if (lhs < rhs) { return -1; } else if (lhs > rhs) { return 1; } else { return 0; } } template <> int ComparisonImpl(const CelError* lhs, const CelError* rhs) { if (*lhs == *rhs) { return 0; } return lhs < rhs ? -1 : 1; } template <> int ComparisonImpl(CelValue::MessageWrapper lhs_wrapper, CelValue::MessageWrapper rhs_wrapper) { auto* lhs = lhs_wrapper.message_ptr(); auto* rhs = rhs_wrapper.message_ptr(); if (lhs < rhs) { return -1; } else if (lhs > rhs) { return 1; } else { return 0; } } template <> int ComparisonImpl(const CelList* lhs, const CelList* rhs) { int size_comparison = ComparisonImpl(lhs->size(), rhs->size()); if (size_comparison != 0) { return size_comparison; } google::protobuf::Arena arena; for (int i = 0; i < lhs->size(); i++) { CelValue lhs_i = lhs->Get(&arena, i); CelValue rhs_i = rhs->Get(&arena, i); int value_comparison = CelValueCompare(lhs_i, rhs_i); if (value_comparison != 0) { return value_comparison; } } return 0; } template <> int ComparisonImpl(const CelMap* lhs, const CelMap* rhs) { int size_comparison = ComparisonImpl(lhs->size(), rhs->size()); if (size_comparison != 0) { return size_comparison; } google::protobuf::Arena arena; std::vector<CelValue> lhs_keys; std::vector<CelValue> rhs_keys; lhs_keys.reserve(lhs->size()); rhs_keys.reserve(lhs->size()); const CelList* lhs_key_view = lhs->ListKeys(&arena).value(); const CelList* rhs_key_view = rhs->ListKeys(&arena).value(); for (int i = 0; i < lhs->size(); i++) { lhs_keys.push_back(lhs_key_view->Get(&arena, i)); rhs_keys.push_back(rhs_key_view->Get(&arena, i)); } std::sort(lhs_keys.begin(), lhs_keys.end(), &CelValueLessThan); std::sort(rhs_keys.begin(), rhs_keys.end(), &CelValueLessThan); for (size_t i = 0; i < lhs_keys.size(); i++) { auto lhs_key_i = lhs_keys[i]; auto rhs_key_i = rhs_keys[i]; int key_comparison = CelValueCompare(lhs_key_i, rhs_key_i); if (key_comparison != 0) { return key_comparison; } auto lhs_value_i = lhs->Get(&arena, lhs_key_i).value(); auto rhs_value_i = rhs->Get(&arena, rhs_key_i).value(); int value_comparison = CelValueCompare(lhs_value_i, rhs_value_i); if (value_comparison != 0) { return value_comparison; } } return 0; } struct ComparisonVisitor { explicit ComparisonVisitor(CelValue rhs) : rhs(rhs) {} template <typename T> int operator()(T lhs_value) { T rhs_value; if (!rhs.GetValue(&rhs_value)) { return ComparisonImpl(CelValue::Type(CelValue::IndexOf<T>::value), rhs.type()); } return ComparisonImpl(lhs_value, rhs_value); } CelValue rhs; }; } int CelValueCompare(CelValue lhs, CelValue rhs) { return lhs.InternalVisit<int>(ComparisonVisitor(rhs)); } bool CelValueLessThan(CelValue lhs, CelValue rhs) { return lhs.InternalVisit<int>(ComparisonVisitor(rhs)) < 0; } bool CelValueEqual(CelValue lhs, CelValue rhs) { return lhs.InternalVisit<int>(ComparisonVisitor(rhs)) == 0; } bool CelValueGreaterThan(CelValue lhs, CelValue rhs) { return lhs.InternalVisit<int>(ComparisonVisitor(rhs)) > 0; } }
#include "eval/public/set_util.h" #include <cstddef> #include <set> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/protobuf/empty.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/message.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/time/clock.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/structs/cel_proto_wrapper.h" #include "eval/public/unknown_set.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { using google::protobuf::Arena; using protobuf::Empty; using protobuf::ListValue; using protobuf::Struct; constexpr char kExampleText[] = "abc"; constexpr char kExampleText2[] = "abd"; std::string* ExampleStr() { static std::string* example = new std::string(kExampleText); return example; } std::string* ExampleStr2() { static std::string* example = new std::string(kExampleText2); return example; } std::vector<CelValue> TypeExamples(Arena* arena) { Empty* empty = Arena::Create<Empty>(arena); Struct* proto_map = Arena::Create<Struct>(arena); ListValue* proto_list = Arena::Create<ListValue>(arena); UnknownSet* unknown_set = Arena::Create<UnknownSet>(arena); return {CelValue::CreateBool(false), CelValue::CreateInt64(0), CelValue::CreateUint64(0), CelValue::CreateDouble(0.0), CelValue::CreateStringView(kExampleText), CelValue::CreateBytes(ExampleStr()), CelProtoWrapper::CreateMessage(empty, arena), CelValue::CreateDuration(absl::ZeroDuration()), CelValue::CreateTimestamp(absl::Now()), CelProtoWrapper::CreateMessage(proto_list, arena), CelProtoWrapper::CreateMessage(proto_map, arena), CelValue::CreateUnknownSet(unknown_set), CreateErrorValue(arena, "test", absl::StatusCode::kInternal)}; } class TypeOrderingTest : public testing::TestWithParam<std::tuple<int, int>> { public: TypeOrderingTest() { i_ = std::get<0>(GetParam()); j_ = std::get<1>(GetParam()); } protected: int i_; int j_; Arena arena_; }; TEST_P(TypeOrderingTest, TypeLessThan) { auto examples = TypeExamples(&arena_); CelValue lhs = examples[i_]; CelValue rhs = examples[j_]; EXPECT_EQ(CelValueLessThan(lhs, rhs), i_ < j_); EXPECT_EQ(CelValueEqual(lhs, rhs), i_ == j_); } std::string TypeOrderingTestName( testing::TestParamInfo<std::tuple<int, int>> param) { int i = std::get<0>(param.param); int j = std::get<1>(param.param); return absl::StrCat(CelValue::TypeName(CelValue::Type(i)), "_", CelValue::TypeName(CelValue::Type(j))); } INSTANTIATE_TEST_SUITE_P(TypePairs, TypeOrderingTest, testing::Combine(testing::Range(0, 13), testing::Range(0, 13)), &TypeOrderingTestName); TEST(CelValueLessThanComparator, StdSetSupport) { Arena arena; auto examples = TypeExamples(&arena); std::set<CelValue, CelValueLessThanComparator> value_set(&CelValueLessThan); for (CelValue value : examples) { auto insert = value_set.insert(value); bool was_inserted = insert.second; EXPECT_TRUE(was_inserted) << absl::StrCat("Insertion failed ", CelValue::TypeName(value.type())); } for (CelValue value : examples) { auto insert = value_set.insert(value); bool was_inserted = insert.second; EXPECT_FALSE(was_inserted) << absl::StrCat( "Re-insertion succeeded ", CelValue::TypeName(value.type())); } } enum class ExpectedCmp { kEq, kLt, kGt }; struct PrimitiveCmpTestCase { CelValue lhs; CelValue rhs; ExpectedCmp expected; }; class PrimitiveCmpTest : public testing::TestWithParam<PrimitiveCmpTestCase> { public: PrimitiveCmpTest() { lhs_ = GetParam().lhs; rhs_ = GetParam().rhs; expected_ = GetParam().expected; } protected: CelValue lhs_; CelValue rhs_; ExpectedCmp expected_; }; TEST_P(PrimitiveCmpTest, Basic) { switch (expected_) { case ExpectedCmp::kLt: EXPECT_TRUE(CelValueLessThan(lhs_, rhs_)); break; case ExpectedCmp::kGt: EXPECT_TRUE(CelValueGreaterThan(lhs_, rhs_)); break; case ExpectedCmp::kEq: EXPECT_TRUE(CelValueEqual(lhs_, rhs_)); break; } } std::string PrimitiveCmpTestName( testing::TestParamInfo<PrimitiveCmpTestCase> info) { absl::string_view cmp_name; switch (info.param.expected) { case ExpectedCmp::kEq: cmp_name = "Eq"; break; case ExpectedCmp::kLt: cmp_name = "Lt"; break; case ExpectedCmp::kGt: cmp_name = "Gt"; break; } return absl::StrCat(CelValue::TypeName(info.param.lhs.type()), "_", cmp_name); } INSTANTIATE_TEST_SUITE_P( Pairs, PrimitiveCmpTest, testing::ValuesIn(std::vector<PrimitiveCmpTestCase>{ {CelValue::CreateStringView(kExampleText), CelValue::CreateStringView(kExampleText), ExpectedCmp::kEq}, {CelValue::CreateStringView(kExampleText), CelValue::CreateStringView(kExampleText2), ExpectedCmp::kLt}, {CelValue::CreateStringView(kExampleText2), CelValue::CreateStringView(kExampleText), ExpectedCmp::kGt}, {CelValue::CreateBytes(ExampleStr()), CelValue::CreateBytes(ExampleStr()), ExpectedCmp::kEq}, {CelValue::CreateBytes(ExampleStr()), CelValue::CreateBytes(ExampleStr2()), ExpectedCmp::kLt}, {CelValue::CreateBytes(ExampleStr2()), CelValue::CreateBytes(ExampleStr()), ExpectedCmp::kGt}, {CelValue::CreateBool(false), CelValue::CreateBool(false), ExpectedCmp::kEq}, {CelValue::CreateBool(false), CelValue::CreateBool(true), ExpectedCmp::kLt}, {CelValue::CreateBool(true), CelValue::CreateBool(false), ExpectedCmp::kGt}, {CelValue::CreateInt64(1), CelValue::CreateInt64(1), ExpectedCmp::kEq}, {CelValue::CreateInt64(1), CelValue::CreateInt64(2), ExpectedCmp::kLt}, {CelValue::CreateInt64(2), CelValue::CreateInt64(1), ExpectedCmp::kGt}, {CelValue::CreateUint64(1), CelValue::CreateUint64(1), ExpectedCmp::kEq}, {CelValue::CreateUint64(1), CelValue::CreateUint64(2), ExpectedCmp::kLt}, {CelValue::CreateUint64(2), CelValue::CreateUint64(1), ExpectedCmp::kGt}, {CelValue::CreateDuration(absl::Minutes(1)), CelValue::CreateDuration(absl::Minutes(1)), ExpectedCmp::kEq}, {CelValue::CreateDuration(absl::Minutes(1)), CelValue::CreateDuration(absl::Minutes(2)), ExpectedCmp::kLt}, {CelValue::CreateDuration(absl::Minutes(2)), CelValue::CreateDuration(absl::Minutes(1)), ExpectedCmp::kGt}, {CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), ExpectedCmp::kEq}, {CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), CelValue::CreateTimestamp(absl::FromUnixSeconds(2)), ExpectedCmp::kLt}, {CelValue::CreateTimestamp(absl::FromUnixSeconds(2)), CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), ExpectedCmp::kGt}}), &PrimitiveCmpTestName); TEST(CelValueLessThan, PtrCmpMessage) { Arena arena; CelValue lhs = CelProtoWrapper::CreateMessage(Arena::Create<Empty>(&arena), &arena); CelValue rhs = CelProtoWrapper::CreateMessage(Arena::Create<Empty>(&arena), &arena); if (lhs.MessageOrDie() > rhs.MessageOrDie()) { std::swap(lhs, rhs); } EXPECT_TRUE(CelValueLessThan(lhs, rhs)); EXPECT_FALSE(CelValueLessThan(rhs, lhs)); EXPECT_FALSE(CelValueLessThan(lhs, lhs)); } TEST(CelValueLessThan, PtrCmpUnknownSet) { Arena arena; CelValue lhs = CelValue::CreateUnknownSet(Arena::Create<UnknownSet>(&arena)); CelValue rhs = CelValue::CreateUnknownSet(Arena::Create<UnknownSet>(&arena)); if (lhs.UnknownSetOrDie() > rhs.UnknownSetOrDie()) { std::swap(lhs, rhs); } EXPECT_TRUE(CelValueLessThan(lhs, rhs)); EXPECT_FALSE(CelValueLessThan(rhs, lhs)); EXPECT_FALSE(CelValueLessThan(lhs, lhs)); } TEST(CelValueLessThan, PtrCmpError) { Arena arena; CelValue lhs = CreateErrorValue(&arena, "test1", absl::StatusCode::kInternal); CelValue rhs = CreateErrorValue(&arena, "test2", absl::StatusCode::kInternal); if (lhs.ErrorOrDie() > rhs.ErrorOrDie()) { std::swap(lhs, rhs); } EXPECT_TRUE(CelValueLessThan(lhs, rhs)); EXPECT_FALSE(CelValueLessThan(rhs, lhs)); EXPECT_FALSE(CelValueLessThan(lhs, lhs)); } TEST(CelValueLessThan, CelListSameSize) { ContainerBackedListImpl cel_list_1(std::vector<CelValue>{ CelValue::CreateInt64(1), CelValue::CreateInt64(2)}); ContainerBackedListImpl cel_list_2(std::vector<CelValue>{ CelValue::CreateInt64(1), CelValue::CreateInt64(3)}); EXPECT_TRUE(CelValueLessThan(CelValue::CreateList(&cel_list_1), CelValue::CreateList(&cel_list_2))); } TEST(CelValueLessThan, CelListDifferentSizes) { ContainerBackedListImpl cel_list_1( std::vector<CelValue>{CelValue::CreateInt64(2)}); ContainerBackedListImpl cel_list_2(std::vector<CelValue>{ CelValue::CreateInt64(1), CelValue::CreateInt64(3)}); EXPECT_TRUE(CelValueLessThan(CelValue::CreateList(&cel_list_1), CelValue::CreateList(&cel_list_2))); } TEST(CelValueLessThan, CelListEqual) { ContainerBackedListImpl cel_list_1(std::vector<CelValue>{ CelValue::CreateInt64(1), CelValue::CreateInt64(2)}); ContainerBackedListImpl cel_list_2(std::vector<CelValue>{ CelValue::CreateInt64(1), CelValue::CreateInt64(2)}); EXPECT_FALSE(CelValueLessThan(CelValue::CreateList(&cel_list_1), CelValue::CreateList(&cel_list_2))); EXPECT_TRUE(CelValueEqual(CelValue::CreateList(&cel_list_2), CelValue::CreateList(&cel_list_1))); } TEST(CelValueLessThan, CelListSupportProtoListCompatible) { Arena arena; 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("abc"); CelValue proto_list = CelProtoWrapper::CreateMessage(&list_value, &arena); ASSERT_TRUE(proto_list.IsList()); std::vector<CelValue> list_values{CelValue::CreateBool(true), CelValue::CreateDouble(1.0), CelValue::CreateStringView("abd")}; ContainerBackedListImpl list_backing(list_values); CelValue cel_list = CelValue::CreateList(&list_backing); EXPECT_TRUE(CelValueLessThan(proto_list, cel_list)); } TEST(CelValueLessThan, CelMapSameSize) { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(3), CelValue::CreateInt64(6)}}; auto cel_map_backing_1 = CreateContainerBackedMap(absl::MakeSpan(values)).value(); std::vector<std::pair<CelValue, CelValue>> values2{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(4), CelValue::CreateInt64(6)}}; auto cel_map_backing_2 = CreateContainerBackedMap(absl::MakeSpan(values2)).value(); std::vector<std::pair<CelValue, CelValue>> values3{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(3), CelValue::CreateInt64(8)}}; auto cel_map_backing_3 = CreateContainerBackedMap(absl::MakeSpan(values3)).value(); CelValue map1 = CelValue::CreateMap(cel_map_backing_1.get()); CelValue map2 = CelValue::CreateMap(cel_map_backing_2.get()); CelValue map3 = CelValue::CreateMap(cel_map_backing_3.get()); EXPECT_TRUE(CelValueLessThan(map1, map2)); EXPECT_TRUE(CelValueLessThan(map1, map3)); EXPECT_TRUE(CelValueLessThan(map3, map2)); } TEST(CelValueLessThan, CelMapDifferentSizes) { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}}; auto cel_map_1 = CreateContainerBackedMap(absl::MakeSpan(values)).value(); std::vector<std::pair<CelValue, CelValue>> values2{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}, {CelValue::CreateInt64(3), CelValue::CreateInt64(6)}}; auto cel_map_2 = CreateContainerBackedMap(absl::MakeSpan(values2)).value(); EXPECT_TRUE(CelValueLessThan(CelValue::CreateMap(cel_map_1.get()), CelValue::CreateMap(cel_map_2.get()))); } TEST(CelValueLessThan, CelMapEqual) { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}, {CelValue::CreateInt64(3), CelValue::CreateInt64(6)}}; auto cel_map_1 = CreateContainerBackedMap(absl::MakeSpan(values)).value(); std::vector<std::pair<CelValue, CelValue>> values2{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}, {CelValue::CreateInt64(3), CelValue::CreateInt64(6)}}; auto cel_map_2 = CreateContainerBackedMap(absl::MakeSpan(values2)).value(); EXPECT_FALSE(CelValueLessThan(CelValue::CreateMap(cel_map_1.get()), CelValue::CreateMap(cel_map_2.get()))); EXPECT_TRUE(CelValueEqual(CelValue::CreateMap(cel_map_2.get()), CelValue::CreateMap(cel_map_1.get()))); } TEST(CelValueLessThan, CelMapSupportProtoMapCompatible) { Arena arena; 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 proto_struct = CelProtoWrapper::CreateMessage(&value_struct, &arena); ASSERT_TRUE(proto_struct.IsMap()); std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateStringView(kFields[2]), CelValue::CreateStringView("test")}, {CelValue::CreateStringView(kFields[1]), CelValue::CreateDouble(1.0)}, {CelValue::CreateStringView(kFields[0]), CelValue::CreateBool(true)}}; auto backing_map = CreateContainerBackedMap(absl::MakeSpan(values)).value(); CelValue cel_map = CelValue::CreateMap(backing_map.get()); EXPECT_TRUE(!CelValueLessThan(cel_map, proto_struct) && !CelValueGreaterThan(cel_map, proto_struct)); } TEST(CelValueLessThan, NestedMap) { Arena arena; 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"); std::vector<CelValue> list_values{CelValue::CreateBool(true), CelValue::CreateDouble(1.0), CelValue::CreateStringView("test")}; ContainerBackedListImpl list_backing(list_values); CelValue cel_list = CelValue::CreateList(&list_backing); Struct value_struct; *(value_struct.mutable_fields()->operator[]("field").mutable_list_value()) = list_value; std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateStringView("field"), cel_list}}; auto backing_map = CreateContainerBackedMap(absl::MakeSpan(values)).value(); CelValue cel_map = CelValue::CreateMap(backing_map.get()); CelValue proto_map = CelProtoWrapper::CreateMessage(&value_struct, &arena); EXPECT_TRUE(!CelValueLessThan(cel_map, proto_map) && !CelValueLessThan(proto_map, cel_map)); } } } } } }
97
cpp
google/cel-cpp
activation
eval/public/activation.cc
eval/public/activation_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_ACTIVATION_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_ACTIVATION_H_ #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/attribute.h" #include "base/function.h" #include "base/function_descriptor.h" #include "common/value.h" #include "common/value_manager.h" #include "runtime/activation_interface.h" #include "runtime/function_overload_reference.h" namespace cel { class Activation final : public ActivationInterface { public: using ValueProvider = absl::AnyInvocable<absl::StatusOr<absl::optional<Value>>( ValueManager&, absl::string_view)>; Activation() = default; absl::StatusOr<absl::optional<ValueView>> FindVariable( ValueManager& factory, absl::string_view name, Value& scratch) const override; using ActivationInterface::FindVariable; std::vector<FunctionOverloadReference> FindFunctionOverloads( absl::string_view name) const override; absl::Span<const cel::AttributePattern> GetUnknownAttributes() const override { return unknown_patterns_; } absl::Span<const cel::AttributePattern> GetMissingAttributes() const override { return missing_patterns_; } bool InsertOrAssignValue(absl::string_view name, Value value); bool InsertOrAssignValueProvider(absl::string_view name, ValueProvider provider); void SetUnknownPatterns(std::vector<cel::AttributePattern> patterns) { unknown_patterns_ = std::move(patterns); } void SetMissingPatterns(std::vector<cel::AttributePattern> patterns) { missing_patterns_ = std::move(patterns); } bool InsertFunction(const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> impl); private: struct ValueEntry { absl::optional<Value> value; absl::optional<ValueProvider> provider; }; struct FunctionEntry { std::unique_ptr<cel::FunctionDescriptor> descriptor; std::unique_ptr<cel::Function> implementation; }; absl::StatusOr<absl::optional<ValueView>> ProvideValue( ValueManager& value_factory, absl::string_view name, Value& scratch) const; mutable absl::Mutex mutex_; mutable absl::flat_hash_map<std::string, ValueEntry> values_; std::vector<cel::AttributePattern> unknown_patterns_; std::vector<cel::AttributePattern> missing_patterns_; absl::flat_hash_map<std::string, std::vector<FunctionEntry>> functions_; }; } #endif #include "runtime/activation.h" #include <memory> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "base/function.h" #include "base/function_descriptor.h" #include "common/value.h" #include "internal/status_macros.h" #include "runtime/function_overload_reference.h" namespace cel { absl::StatusOr<absl::optional<ValueView>> Activation::FindVariable( ValueManager& factory, absl::string_view name, Value& scratch) const { auto iter = values_.find(name); if (iter == values_.end()) { return absl::nullopt; } const ValueEntry& entry = iter->second; if (entry.provider.has_value()) { return ProvideValue(factory, name, scratch); } if (entry.value.has_value()) { scratch = *entry.value; return scratch; } return absl::nullopt; } absl::StatusOr<absl::optional<ValueView>> Activation::ProvideValue( ValueManager& factory, absl::string_view name, Value& scratch) const { absl::MutexLock lock(&mutex_); auto iter = values_.find(name); ABSL_ASSERT(iter != values_.end()); ValueEntry& entry = iter->second; if (entry.value.has_value()) { scratch = *entry.value; return scratch; } CEL_ASSIGN_OR_RETURN(auto result, (*entry.provider)(factory, name)); if (result.has_value()) { entry.value = std::move(result); scratch = *entry.value; return scratch; } return absl::nullopt; } std::vector<FunctionOverloadReference> Activation::FindFunctionOverloads( absl::string_view name) const { std::vector<FunctionOverloadReference> result; auto iter = functions_.find(name); if (iter != functions_.end()) { const std::vector<FunctionEntry>& overloads = iter->second; result.reserve(overloads.size()); for (const auto& overload : overloads) { result.push_back({*overload.descriptor, *overload.implementation}); } } return result; } bool Activation::InsertOrAssignValue(absl::string_view name, Value value) { return values_ .insert_or_assign(name, ValueEntry{std::move(value), absl::nullopt}) .second; } bool Activation::InsertOrAssignValueProvider(absl::string_view name, ValueProvider provider) { return values_ .insert_or_assign(name, ValueEntry{absl::nullopt, std::move(provider)}) .second; } bool Activation::InsertFunction(const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> impl) { auto& overloads = functions_[descriptor.name()]; for (auto& overload : overloads) { if (overload.descriptor->ShapeMatches(descriptor)) { return false; } } overloads.push_back( {std::make_unique<FunctionDescriptor>(descriptor), std::move(impl)}); return true; } }
#include "runtime/activation.h" #include <memory> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "base/attribute.h" #include "base/function.h" #include "base/function_descriptor.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 "internal/status_macros.h" #include "internal/testing.h" namespace cel { namespace { using testing::ElementsAre; using testing::Eq; using testing::IsEmpty; using testing::Optional; using testing::Truly; using testing::UnorderedElementsAre; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; MATCHER_P(IsIntValue, x, absl::StrCat("is IntValue Handle with value ", x)) { const Value& handle = arg; return handle->Is<IntValue>() && handle.As<IntValue>().NativeValue() == x; } MATCHER_P(AttributePatternMatches, val, "matches AttributePattern") { const AttributePattern& pattern = arg; const Attribute& expected = val; return pattern.IsMatch(expected) == AttributePattern::MatchType::FULL; } class FunctionImpl : public cel::Function { public: FunctionImpl() = default; absl::StatusOr<Value> Invoke(const FunctionEvaluationContext& ctx, absl::Span<const Value> args) const override { return NullValue(); } }; class ActivationTest : public testing::Test { public: ActivationTest() : value_factory_(MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()) {} protected: common_internal::LegacyValueManager value_factory_; }; TEST_F(ActivationTest, ValueNotFound) { Activation activation; EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Eq(absl::nullopt))); } TEST_F(ActivationTest, InsertValue) { Activation activation; EXPECT_TRUE(activation.InsertOrAssignValue( "var1", value_factory_.CreateIntValue(42))); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(42)))); } TEST_F(ActivationTest, InsertValueOverwrite) { Activation activation; EXPECT_TRUE(activation.InsertOrAssignValue( "var1", value_factory_.CreateIntValue(42))); EXPECT_FALSE( activation.InsertOrAssignValue("var1", value_factory_.CreateIntValue(0))); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(0)))); } TEST_F(ActivationTest, InsertProvider) { Activation activation; EXPECT_TRUE(activation.InsertOrAssignValueProvider( "var1", [](ValueManager& factory, absl::string_view name) { return factory.CreateIntValue(42); })); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(42)))); } TEST_F(ActivationTest, InsertProviderForwardsNotFound) { Activation activation; EXPECT_TRUE(activation.InsertOrAssignValueProvider( "var1", [](ValueManager& factory, absl::string_view name) { return absl::nullopt; })); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Eq(absl::nullopt))); } TEST_F(ActivationTest, InsertProviderForwardsStatus) { Activation activation; EXPECT_TRUE(activation.InsertOrAssignValueProvider( "var1", [](ValueManager& factory, absl::string_view name) { return absl::InternalError("test"); })); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), StatusIs(absl::StatusCode::kInternal, "test")); } TEST_F(ActivationTest, ProviderMemoized) { Activation activation; int call_count = 0; EXPECT_TRUE(activation.InsertOrAssignValueProvider( "var1", [&call_count](ValueManager& factory, absl::string_view name) { call_count++; return factory.CreateIntValue(42); })); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(42)))); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(42)))); EXPECT_EQ(call_count, 1); } TEST_F(ActivationTest, InsertProviderOverwrite) { Activation activation; EXPECT_TRUE(activation.InsertOrAssignValueProvider( "var1", [](ValueManager& factory, absl::string_view name) { return factory.CreateIntValue(42); })); EXPECT_FALSE(activation.InsertOrAssignValueProvider( "var1", [](ValueManager& factory, absl::string_view name) { return factory.CreateIntValue(0); })); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(0)))); } TEST_F(ActivationTest, ValuesAndProvidersShareNamespace) { Activation activation; bool called = false; EXPECT_TRUE(activation.InsertOrAssignValue( "var1", value_factory_.CreateIntValue(41))); EXPECT_TRUE(activation.InsertOrAssignValue( "var2", value_factory_.CreateIntValue(41))); EXPECT_FALSE(activation.InsertOrAssignValueProvider( "var1", [&called](ValueManager& factory, absl::string_view name) { called = true; return factory.CreateIntValue(42); })); EXPECT_THAT(activation.FindVariable(value_factory_, "var1"), IsOkAndHolds(Optional(IsIntValue(42)))); EXPECT_THAT(activation.FindVariable(value_factory_, "var2"), IsOkAndHolds(Optional(IsIntValue(41)))); EXPECT_TRUE(called); } TEST_F(ActivationTest, SetUnknownAttributes) { Activation activation; activation.SetUnknownPatterns( {AttributePattern("var1", {AttributeQualifierPattern::OfString("field1")}), AttributePattern("var1", {AttributeQualifierPattern::OfString("field2")})}); EXPECT_THAT( activation.GetUnknownAttributes(), ElementsAre(AttributePatternMatches(Attribute( "var1", {AttributeQualifier::OfString("field1")})), AttributePatternMatches(Attribute( "var1", {AttributeQualifier::OfString("field2")})))); } TEST_F(ActivationTest, ClearUnknownAttributes) { Activation activation; activation.SetUnknownPatterns( {AttributePattern("var1", {AttributeQualifierPattern::OfString("field1")}), AttributePattern("var1", {AttributeQualifierPattern::OfString("field2")})}); activation.SetUnknownPatterns({}); EXPECT_THAT(activation.GetUnknownAttributes(), IsEmpty()); } TEST_F(ActivationTest, SetMissingAttributes) { Activation activation; activation.SetMissingPatterns( {AttributePattern("var1", {AttributeQualifierPattern::OfString("field1")}), AttributePattern("var1", {AttributeQualifierPattern::OfString("field2")})}); EXPECT_THAT( activation.GetMissingAttributes(), ElementsAre(AttributePatternMatches(Attribute( "var1", {AttributeQualifier::OfString("field1")})), AttributePatternMatches(Attribute( "var1", {AttributeQualifier::OfString("field2")})))); } TEST_F(ActivationTest, ClearMissingAttributes) { Activation activation; activation.SetMissingPatterns( {AttributePattern("var1", {AttributeQualifierPattern::OfString("field1")}), AttributePattern("var1", {AttributeQualifierPattern::OfString("field2")})}); activation.SetMissingPatterns({}); EXPECT_THAT(activation.GetMissingAttributes(), IsEmpty()); } TEST_F(ActivationTest, InsertFunctionOk) { Activation activation; EXPECT_TRUE( activation.InsertFunction(FunctionDescriptor("Fn", false, {Kind::kUint}), std::make_unique<FunctionImpl>())); EXPECT_TRUE( activation.InsertFunction(FunctionDescriptor("Fn", false, {Kind::kInt}), std::make_unique<FunctionImpl>())); EXPECT_TRUE( activation.InsertFunction(FunctionDescriptor("Fn2", false, {Kind::kInt}), std::make_unique<FunctionImpl>())); EXPECT_THAT( activation.FindFunctionOverloads("Fn"), UnorderedElementsAre( Truly([](const FunctionOverloadReference& ref) { return ref.descriptor.name() == "Fn" && ref.descriptor.types() == std::vector<Kind>{Kind::kUint}; }), Truly([](const FunctionOverloadReference& ref) { return ref.descriptor.name() == "Fn" && ref.descriptor.types() == std::vector<Kind>{Kind::kInt}; }))) << "expected overloads Fn(int), Fn(uint)"; } TEST_F(ActivationTest, InsertFunctionFails) { Activation activation; EXPECT_TRUE( activation.InsertFunction(FunctionDescriptor("Fn", false, {Kind::kAny}), std::make_unique<FunctionImpl>())); EXPECT_FALSE( activation.InsertFunction(FunctionDescriptor("Fn", false, {Kind::kInt}), std::make_unique<FunctionImpl>())); EXPECT_THAT(activation.FindFunctionOverloads("Fn"), ElementsAre(Truly([](const FunctionOverloadReference& ref) { return ref.descriptor.name() == "Fn" && ref.descriptor.types() == std::vector<Kind>{Kind::kAny}; }))) << "expected overload Fn(any)"; } } }
98
cpp
google/cel-cpp
value_export_util
eval/public/value_export_util.cc
eval/public/value_export_util_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_VALUE_EXPORT_UTIL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_VALUE_EXPORT_UTIL_H_ #include "google/protobuf/struct.pb.h" #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "eval/public/cel_value.h" namespace google::api::expr::runtime { absl::Status ExportAsProtoValue(const CelValue& in_value, google::protobuf::Value* out_value, google::protobuf::Arena* arena); inline absl::Status ExportAsProtoValue(const CelValue& in_value, google::protobuf::Value* out_value) { google::protobuf::Arena arena; return ExportAsProtoValue(in_value, out_value, &arena); } } #endif #include "eval/public/value_export_util.h" #include <string> #include "google/protobuf/util/json_util.h" #include "google/protobuf/util/time_util.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "internal/proto_time_encoding.h" namespace google::api::expr::runtime { using google::protobuf::Duration; using google::protobuf::Timestamp; using google::protobuf::Value; using google::protobuf::util::TimeUtil; absl::Status KeyAsString(const CelValue& value, std::string* key) { switch (value.type()) { case CelValue::Type::kInt64: { *key = absl::StrCat(value.Int64OrDie()); break; } case CelValue::Type::kUint64: { *key = absl::StrCat(value.Uint64OrDie()); break; } case CelValue::Type::kString: { key->assign(value.StringOrDie().value().data(), value.StringOrDie().value().size()); break; } default: { return absl::InvalidArgumentError("Unsupported map type"); } } return absl::OkStatus(); } absl::Status ExportAsProtoValue(const CelValue& in_value, Value* out_value, google::protobuf::Arena* arena) { if (in_value.IsNull()) { out_value->set_null_value(google::protobuf::NULL_VALUE); return absl::OkStatus(); } switch (in_value.type()) { case CelValue::Type::kBool: { out_value->set_bool_value(in_value.BoolOrDie()); break; } case CelValue::Type::kInt64: { out_value->set_number_value(static_cast<double>(in_value.Int64OrDie())); break; } case CelValue::Type::kUint64: { out_value->set_number_value(static_cast<double>(in_value.Uint64OrDie())); break; } case CelValue::Type::kDouble: { out_value->set_number_value(in_value.DoubleOrDie()); break; } case CelValue::Type::kString: { auto value = in_value.StringOrDie().value(); out_value->set_string_value(value.data(), value.size()); break; } case CelValue::Type::kBytes: { absl::Base64Escape(in_value.BytesOrDie().value(), out_value->mutable_string_value()); break; } case CelValue::Type::kDuration: { Duration duration; auto status = cel::internal::EncodeDuration(in_value.DurationOrDie(), &duration); if (!status.ok()) { return status; } out_value->set_string_value(TimeUtil::ToString(duration)); break; } case CelValue::Type::kTimestamp: { Timestamp timestamp; auto status = cel::internal::EncodeTime(in_value.TimestampOrDie(), &timestamp); if (!status.ok()) { return status; } out_value->set_string_value(TimeUtil::ToString(timestamp)); break; } case CelValue::Type::kMessage: { google::protobuf::util::JsonPrintOptions json_options; json_options.preserve_proto_field_names = true; std::string json; auto status = google::protobuf::util::MessageToJsonString(*in_value.MessageOrDie(), &json, json_options); if (!status.ok()) { return absl::InternalError(status.ToString()); } google::protobuf::util::JsonParseOptions json_parse_options; status = google::protobuf::util::JsonStringToMessage(json, out_value, json_parse_options); if (!status.ok()) { return absl::InternalError(status.ToString()); } break; } case CelValue::Type::kList: { const CelList* cel_list = in_value.ListOrDie(); auto out_values = out_value->mutable_list_value(); for (int i = 0; i < cel_list->size(); i++) { auto status = ExportAsProtoValue((*cel_list).Get(arena, i), out_values->add_values(), arena); if (!status.ok()) { return status; } } break; } case CelValue::Type::kMap: { const CelMap* cel_map = in_value.MapOrDie(); CEL_ASSIGN_OR_RETURN(auto keys_list, cel_map->ListKeys(arena)); auto out_values = out_value->mutable_struct_value()->mutable_fields(); for (int i = 0; i < keys_list->size(); i++) { std::string key; CelValue map_key = (*keys_list).Get(arena, i); auto status = KeyAsString(map_key, &key); if (!status.ok()) { return status; } auto map_value_ref = (*cel_map).Get(arena, map_key); CelValue map_value = (map_value_ref) ? map_value_ref.value() : CelValue(); status = ExportAsProtoValue(map_value, &((*out_values)[key]), arena); if (!status.ok()) { return status; } } break; } default: { return absl::InvalidArgumentError("Unsupported value type"); } } return absl::OkStatus(); } }
#include "eval/public/value_export_util.h" #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.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/testutil/test_message.pb.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "testutil/util.h" namespace google::api::expr::runtime { namespace { using google::protobuf::Duration; using google::protobuf::ListValue; using google::protobuf::Struct; using google::protobuf::Timestamp; using google::protobuf::Value; using google::protobuf::Arena; TEST(ValueExportUtilTest, ConvertBoolValue) { CelValue cel_value = CelValue::CreateBool(true); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kBoolValue); EXPECT_EQ(value.bool_value(), true); } TEST(ValueExportUtilTest, ConvertInt64Value) { CelValue cel_value = CelValue::CreateInt64(-1); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kNumberValue); EXPECT_DOUBLE_EQ(value.number_value(), -1); } TEST(ValueExportUtilTest, ConvertUint64Value) { CelValue cel_value = CelValue::CreateUint64(1); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kNumberValue); EXPECT_DOUBLE_EQ(value.number_value(), 1); } TEST(ValueExportUtilTest, ConvertDoubleValue) { CelValue cel_value = CelValue::CreateDouble(1.3); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kNumberValue); EXPECT_DOUBLE_EQ(value.number_value(), 1.3); } TEST(ValueExportUtilTest, ConvertStringValue) { std::string test = "test"; CelValue cel_value = CelValue::CreateString(&test); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStringValue); EXPECT_EQ(value.string_value(), "test"); } TEST(ValueExportUtilTest, ConvertBytesValue) { std::string test = "test"; CelValue cel_value = CelValue::CreateBytes(&test); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStringValue); EXPECT_EQ(value.string_value(), "dGVzdA=="); } TEST(ValueExportUtilTest, ConvertDurationValue) { Duration duration; duration.set_seconds(2); duration.set_nanos(3); CelValue cel_value = CelProtoWrapper::CreateDuration(&duration); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStringValue); EXPECT_EQ(value.string_value(), "2.000000003s"); } TEST(ValueExportUtilTest, ConvertTimestampValue) { Timestamp timestamp; timestamp.set_seconds(1000000000); timestamp.set_nanos(3); CelValue cel_value = CelProtoWrapper::CreateTimestamp(&timestamp); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStringValue); EXPECT_EQ(value.string_value(), "2001-09-09T01:46:40.000000003Z"); } TEST(ValueExportUtilTest, ConvertStructMessage) { Struct struct_msg; (*struct_msg.mutable_fields())["string_value"].set_string_value("test"); Arena arena; CelValue cel_value = CelProtoWrapper::CreateMessage(&struct_msg, &arena); Value value; EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); EXPECT_THAT(value.struct_value(), testutil::EqualsProto(struct_msg)); } TEST(ValueExportUtilTest, ConvertValueMessage) { Value value_in; (*value_in.mutable_struct_value()->mutable_fields())["boolean_value"] .set_bool_value(true); Arena arena; CelValue cel_value = CelProtoWrapper::CreateMessage(&value_in, &arena); Value value_out; EXPECT_OK(ExportAsProtoValue(cel_value, &value_out)); EXPECT_THAT(value_in, testutil::EqualsProto(value_out)); } TEST(ValueExportUtilTest, ConvertListValueMessage) { ListValue list_value; list_value.add_values()->set_string_value("test"); list_value.add_values()->set_bool_value(true); Arena arena; CelValue cel_value = CelProtoWrapper::CreateMessage(&list_value, &arena); Value value_out; EXPECT_OK(ExportAsProtoValue(cel_value, &value_out)); EXPECT_THAT(list_value, testutil::EqualsProto(value_out.list_value())); } TEST(ValueExportUtilTest, ConvertRepeatedBoolValue) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_bool_list(true); msg->add_bool_list(false); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("bool_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_EQ(list_value.list_value().values(0).bool_value(), true); EXPECT_EQ(list_value.list_value().values(1).bool_value(), false); } TEST(ValueExportUtilTest, ConvertRepeatedInt32Value) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_int32_list(2); msg->add_int32_list(3); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("int32_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_DOUBLE_EQ(list_value.list_value().values(0).number_value(), 2); EXPECT_DOUBLE_EQ(list_value.list_value().values(1).number_value(), 3); } TEST(ValueExportUtilTest, ConvertRepeatedInt64Value) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_int64_list(2); msg->add_int64_list(3); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("int64_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_EQ(list_value.list_value().values(0).string_value(), "2"); EXPECT_EQ(list_value.list_value().values(1).string_value(), "3"); } TEST(ValueExportUtilTest, ConvertRepeatedUint64Value) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_uint64_list(2); msg->add_uint64_list(3); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("uint64_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_EQ(list_value.list_value().values(0).string_value(), "2"); EXPECT_EQ(list_value.list_value().values(1).string_value(), "3"); } TEST(ValueExportUtilTest, ConvertRepeatedDoubleValue) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_double_list(2); msg->add_double_list(3); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("double_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_DOUBLE_EQ(list_value.list_value().values(0).number_value(), 2); EXPECT_DOUBLE_EQ(list_value.list_value().values(1).number_value(), 3); } TEST(ValueExportUtilTest, ConvertRepeatedStringValue) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_string_list("test1"); msg->add_string_list("test2"); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("string_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_EQ(list_value.list_value().values(0).string_value(), "test1"); EXPECT_EQ(list_value.list_value().values(1).string_value(), "test2"); } TEST(ValueExportUtilTest, ConvertRepeatedBytesValue) { Arena arena; Value value; TestMessage* msg = Arena::Create<TestMessage>(&arena); msg->add_bytes_list("test1"); msg->add_bytes_list("test2"); CelValue cel_value = CelProtoWrapper::CreateMessage(msg, &arena); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); Value list_value = value.struct_value().fields().at("bytes_list"); EXPECT_TRUE(list_value.has_list_value()); EXPECT_EQ(list_value.list_value().values(0).string_value(), "dGVzdDE="); EXPECT_EQ(list_value.list_value().values(1).string_value(), "dGVzdDI="); } TEST(ValueExportUtilTest, ConvertCelList) { Arena arena; Value value; std::vector<CelValue> values; values.push_back(CelValue::CreateInt64(2)); values.push_back(CelValue::CreateInt64(3)); CelList *cel_list = Arena::Create<ContainerBackedListImpl>(&arena, values); CelValue cel_value = CelValue::CreateList(cel_list); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kListValue); EXPECT_DOUBLE_EQ(value.list_value().values(0).number_value(), 2); EXPECT_DOUBLE_EQ(value.list_value().values(1).number_value(), 3); } TEST(ValueExportUtilTest, ConvertCelMapWithStringKey) { Value value; std::vector<std::pair<CelValue, CelValue>> map_entries; std::string key1 = "key1"; std::string key2 = "key2"; std::string value1 = "value1"; std::string value2 = "value2"; map_entries.push_back( {CelValue::CreateString(&key1), CelValue::CreateString(&value1)}); map_entries.push_back( {CelValue::CreateString(&key2), CelValue::CreateString(&value2)}); auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(map_entries)) .value(); CelValue cel_value = CelValue::CreateMap(cel_map.get()); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); const auto& fields = value.struct_value().fields(); EXPECT_EQ(fields.at(key1).string_value(), value1); EXPECT_EQ(fields.at(key2).string_value(), value2); } TEST(ValueExportUtilTest, ConvertCelMapWithInt64Key) { Value value; std::vector<std::pair<CelValue, CelValue>> map_entries; int key1 = -1; int key2 = 2; std::string value1 = "value1"; std::string value2 = "value2"; map_entries.push_back( {CelValue::CreateInt64(key1), CelValue::CreateString(&value1)}); map_entries.push_back( {CelValue::CreateInt64(key2), CelValue::CreateString(&value2)}); auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(map_entries)) .value(); CelValue cel_value = CelValue::CreateMap(cel_map.get()); EXPECT_OK(ExportAsProtoValue(cel_value, &value)); EXPECT_EQ(value.kind_case(), Value::KindCase::kStructValue); const auto& fields = value.struct_value().fields(); EXPECT_EQ(fields.at(absl::StrCat(key1)).string_value(), value1); EXPECT_EQ(fields.at(absl::StrCat(key2)).string_value(), value2); } } }
99
cpp
google/cel-cpp
portable_cel_expr_builder_factory
eval/public/portable_cel_expr_builder_factory.cc
eval/public/portable_cel_expr_builder_factory_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_PORTABLE_CEL_EXPR_BUILDER_FACTORY_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_PORTABLE_CEL_EXPR_BUILDER_FACTORY_H_ #include "eval/public/cel_expression.h" #include "eval/public/cel_options.h" #include "eval/public/structs/legacy_type_provider.h" namespace google { namespace api { namespace expr { namespace runtime { std::unique_ptr<CelExpressionBuilder> CreatePortableExprBuilder( std::unique_ptr<LegacyTypeProvider> type_provider, const InterpreterOptions& options = InterpreterOptions()); } } } } #endif #include "eval/public/portable_cel_expr_builder_factory.h" #include <memory> #include <utility> #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "base/ast_internal/ast_impl.h" #include "base/kind.h" #include "common/memory.h" #include "common/values/legacy_type_reflector.h" #include "eval/compiler/cel_expression_builder_flat_impl.h" #include "eval/compiler/comprehension_vulnerability_check.h" #include "eval/compiler/constant_folding.h" #include "eval/compiler/flat_expr_builder.h" #include "eval/compiler/flat_expr_builder_extensions.h" #include "eval/compiler/qualified_reference_resolver.h" #include "eval/compiler/regex_precompilation_optimization.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_function.h" #include "eval/public/cel_options.h" #include "eval/public/structs/legacy_type_provider.h" #include "extensions/protobuf/memory_manager.h" #include "extensions/select_optimization.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::MemoryManagerRef; using ::cel::ast_internal::AstImpl; using ::cel::extensions::CreateSelectOptimizationProgramOptimizer; using ::cel::extensions::kCelAttribute; using ::cel::extensions::kCelHasField; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::extensions::SelectOptimizationAstUpdater; using ::cel::runtime_internal::CreateConstantFoldingOptimizer; struct ArenaBackedConstfoldingFactory { MemoryManagerRef memory_manager; absl::StatusOr<std::unique_ptr<ProgramOptimizer>> operator()( PlannerContext& ctx, const AstImpl& ast) const { return CreateConstantFoldingOptimizer(memory_manager)(ctx, ast); } }; } std::unique_ptr<CelExpressionBuilder> CreatePortableExprBuilder( std::unique_ptr<LegacyTypeProvider> type_provider, const InterpreterOptions& options) { if (type_provider == nullptr) { ABSL_LOG(ERROR) << "Cannot pass nullptr as type_provider to " "CreatePortableExprBuilder"; return nullptr; } cel::RuntimeOptions runtime_options = ConvertToRuntimeOptions(options); auto builder = std::make_unique<CelExpressionBuilderFlatImpl>(runtime_options); builder->GetTypeRegistry() ->InternalGetModernRegistry() .set_use_legacy_container_builders(options.use_legacy_container_builders); builder->GetTypeRegistry()->RegisterTypeProvider(std::move(type_provider)); FlatExprBuilder& flat_expr_builder = builder->flat_expr_builder(); flat_expr_builder.AddAstTransform(NewReferenceResolverExtension( (options.enable_qualified_identifier_rewrites) ? ReferenceResolverOption::kAlways : ReferenceResolverOption::kCheckedOnly)); if (options.enable_comprehension_vulnerability_check) { builder->flat_expr_builder().AddProgramOptimizer( CreateComprehensionVulnerabilityCheck()); } if (options.constant_folding) { builder->flat_expr_builder().AddProgramOptimizer( ArenaBackedConstfoldingFactory{ ProtoMemoryManagerRef(options.constant_arena)}); } if (options.enable_regex_precompilation) { flat_expr_builder.AddProgramOptimizer( CreateRegexPrecompilationExtension(options.regex_max_program_size)); } if (options.enable_select_optimization) { flat_expr_builder.AddAstTransform( std::make_unique<SelectOptimizationAstUpdater>()); absl::Status status = builder->GetRegistry()->RegisterLazyFunction(CelFunctionDescriptor( kCelAttribute, false, {cel::Kind::kAny, cel::Kind::kList})); if (!status.ok()) { ABSL_LOG(ERROR) << "Failed to register " << kCelAttribute << ": " << status; } status = builder->GetRegistry()->RegisterLazyFunction(CelFunctionDescriptor( kCelHasField, false, {cel::Kind::kAny, cel::Kind::kList})); if (!status.ok()) { ABSL_LOG(ERROR) << "Failed to register " << kCelHasField << ": " << status; } flat_expr_builder.AddProgramOptimizer( CreateSelectOptimizationProgramOptimizer()); } return builder; } }
#include "eval/public/portable_cel_expr_builder_factory.h" #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "google/protobuf/duration.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/wrappers.pb.h" #include "absl/container/node_hash_set.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_options.h" #include "eval/public/cel_value.h" #include "eval/public/structs/legacy_type_adapter.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "eval/public/structs/legacy_type_provider.h" #include "eval/testutil/test_message.pb.h" #include "extensions/protobuf/memory_manager.h" #include "internal/casts.h" #include "internal/proto_time_encoding.h" #include "internal/testing.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::protobuf::Int64Value; absl::optional<CelValue> Unwrap(const google::protobuf::MessageLite* wrapper) { if (wrapper->GetTypeName() == "google.protobuf.Duration") { const auto* duration = cel::internal::down_cast<const google::protobuf::Duration*>(wrapper); return CelValue::CreateDuration(cel::internal::DecodeDuration(*duration)); } else if (wrapper->GetTypeName() == "google.protobuf.Timestamp") { const auto* timestamp = cel::internal::down_cast<const google::protobuf::Timestamp*>(wrapper); return CelValue::CreateTimestamp(cel::internal::DecodeTime(*timestamp)); } return absl::nullopt; } struct NativeToCelValue { template <typename T> absl::optional<CelValue> Convert(T arg) const { return absl::nullopt; } absl::optional<CelValue> Convert(int64_t v) const { return CelValue::CreateInt64(v); } absl::optional<CelValue> Convert(const std::string& str) const { return CelValue::CreateString(&str); } absl::optional<CelValue> Convert(double v) const { return CelValue::CreateDouble(v); } absl::optional<CelValue> Convert(bool v) const { return CelValue::CreateBool(v); } absl::optional<CelValue> Convert(const Int64Value& v) const { return CelValue::CreateInt64(v.value()); } }; template <typename MessageT, typename FieldT> class FieldImpl; template <typename MessageT> class ProtoField { public: template <typename FieldT> using FieldImpl = FieldImpl<MessageT, FieldT>; virtual ~ProtoField() = default; virtual absl::Status Set(MessageT* m, CelValue v) const = 0; virtual absl::StatusOr<CelValue> Get(const MessageT* m) const = 0; virtual bool Has(const MessageT* m) const = 0; }; template <typename MessageT, typename FieldT> struct ScalarApiWrap { using GetFn = FieldT (MessageT::*)() const; using HasFn = bool (MessageT::*)() const; using SetFn = void (MessageT::*)(FieldT); ScalarApiWrap(GetFn get_fn, HasFn has_fn, SetFn set_fn) : get_fn(get_fn), has_fn(has_fn), set_fn(set_fn) {} FieldT InvokeGet(const MessageT* msg) const { return std::invoke(get_fn, msg); } bool InvokeHas(const MessageT* msg) const { if (has_fn == nullptr) return true; return std::invoke(has_fn, msg); } void InvokeSet(MessageT* msg, FieldT arg) const { if (set_fn != nullptr) { std::invoke(set_fn, msg, arg); } } GetFn get_fn; HasFn has_fn; SetFn set_fn; }; template <typename MessageT, typename FieldT> struct ComplexTypeApiWrap { public: using GetFn = const FieldT& (MessageT::*)() const; using HasFn = bool (MessageT::*)() const; using SetAllocatedFn = void (MessageT::*)(FieldT*); ComplexTypeApiWrap(GetFn get_fn, HasFn has_fn, SetAllocatedFn set_allocated_fn) : get_fn(get_fn), has_fn(has_fn), set_allocated_fn(set_allocated_fn) {} const FieldT& InvokeGet(const MessageT* msg) const { return std::invoke(get_fn, msg); } bool InvokeHas(const MessageT* msg) const { if (has_fn == nullptr) return true; return std::invoke(has_fn, msg); } void InvokeSetAllocated(MessageT* msg, FieldT* arg) const { if (set_allocated_fn != nullptr) { std::invoke(set_allocated_fn, msg, arg); } } GetFn get_fn; HasFn has_fn; SetAllocatedFn set_allocated_fn; }; template <typename MessageT, typename FieldT> class FieldImpl : public ProtoField<MessageT> { private: using ApiWrap = ScalarApiWrap<MessageT, FieldT>; public: FieldImpl(typename ApiWrap::GetFn get_fn, typename ApiWrap::HasFn has_fn, typename ApiWrap::SetFn set_fn) : api_wrapper_(get_fn, has_fn, set_fn) {} absl::Status Set(TestMessage* m, CelValue v) const override { FieldT arg; if (!v.GetValue(&arg)) { return absl::InvalidArgumentError("wrong type for set"); } api_wrapper_.InvokeSet(m, arg); return absl::OkStatus(); } absl::StatusOr<CelValue> Get(const TestMessage* m) const override { FieldT result = api_wrapper_.InvokeGet(m); auto converted = NativeToCelValue().Convert(result); if (converted.has_value()) { return *converted; } return absl::UnimplementedError("not implemented for type"); } bool Has(const TestMessage* m) const override { return api_wrapper_.InvokeHas(m); } private: ApiWrap api_wrapper_; }; template <typename MessageT> class FieldImpl<MessageT, Int64Value> : public ProtoField<MessageT> { using ApiWrap = ComplexTypeApiWrap<MessageT, Int64Value>; public: FieldImpl(typename ApiWrap::GetFn get_fn, typename ApiWrap::HasFn has_fn, typename ApiWrap::SetAllocatedFn set_fn) : api_wrapper_(get_fn, has_fn, set_fn) {} absl::Status Set(TestMessage* m, CelValue v) const override { int64_t arg; if (!v.GetValue(&arg)) { return absl::InvalidArgumentError("wrong type for set"); } Int64Value* proto_value = new Int64Value(); proto_value->set_value(arg); api_wrapper_.InvokeSetAllocated(m, proto_value); return absl::OkStatus(); } absl::StatusOr<CelValue> Get(const TestMessage* m) const override { if (!api_wrapper_.InvokeHas(m)) { return CelValue::CreateNull(); } Int64Value result = api_wrapper_.InvokeGet(m); auto converted = NativeToCelValue().Convert(std::move(result)); if (converted.has_value()) { return *converted; } return absl::UnimplementedError("not implemented for type"); } bool Has(const TestMessage* m) const override { return api_wrapper_.InvokeHas(m); } private: ApiWrap api_wrapper_; }; class DemoTypeProvider; class DemoTimestamp : public LegacyTypeInfoApis, public LegacyTypeMutationApis { public: DemoTimestamp() {} std::string DebugString( const MessageWrapper& wrapped_message) const override { return GetTypename(wrapped_message); } const std::string& GetTypename( const MessageWrapper& wrapped_message) const override { static const std::string* kTypename = []() { return new std::string("google.protobuf.Timestamp"); }(); return *kTypename; } const LegacyTypeAccessApis* GetAccessApis( const MessageWrapper& wrapped_message) const override { return nullptr; } bool DefinesField(absl::string_view field_name) const override { return field_name == "seconds" || field_name == "nanos"; } absl::StatusOr<CelValue::MessageWrapper::Builder> NewInstance( cel::MemoryManagerRef memory_manager) const override; absl::StatusOr<CelValue> AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const override; absl::Status SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const override; private: absl::Status Validate(const google::protobuf::MessageLite* wrapped_message) const { if (wrapped_message->GetTypeName() != "google.protobuf.Timestamp") { return absl::InvalidArgumentError("not a timestamp"); } return absl::OkStatus(); } }; class DemoTypeInfo : public LegacyTypeInfoApis { public: explicit DemoTypeInfo(const DemoTypeProvider* owning_provider) : owning_provider_(*owning_provider) {} std::string DebugString(const MessageWrapper& wrapped_message) const override; const std::string& GetTypename( const MessageWrapper& wrapped_message) const override; const LegacyTypeAccessApis* GetAccessApis( const MessageWrapper& wrapped_message) const override; private: const DemoTypeProvider& owning_provider_; }; class DemoTestMessage : public LegacyTypeInfoApis, public LegacyTypeMutationApis, public LegacyTypeAccessApis { public: explicit DemoTestMessage(const DemoTypeProvider* owning_provider); std::string DebugString( const MessageWrapper& wrapped_message) const override { return GetTypename(wrapped_message); } const std::string& GetTypename( const MessageWrapper& wrapped_message) const override { static const std::string* kTypename = []() { return new std::string("google.api.expr.runtime.TestMessage"); }(); return *kTypename; } const LegacyTypeAccessApis* GetAccessApis( const MessageWrapper& wrapped_message) const override { return this; } const LegacyTypeMutationApis* GetMutationApis( const MessageWrapper& wrapped_message) const override { return this; } absl::optional<FieldDescription> FindFieldByName( absl::string_view name) const override { if (auto it = fields_.find(name); it != fields_.end()) { return FieldDescription{0, name}; } return absl::nullopt; } bool DefinesField(absl::string_view field_name) const override { return fields_.contains(field_name); } absl::StatusOr<CelValue::MessageWrapper::Builder> NewInstance( cel::MemoryManagerRef memory_manager) const override; absl::StatusOr<CelValue> AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const override; absl::Status SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const override; absl::StatusOr<bool> HasField( absl::string_view field_name, const CelValue::MessageWrapper& value) const override; absl::StatusOr<CelValue> GetField( absl::string_view field_name, const CelValue::MessageWrapper& instance, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) const override; std::vector<absl::string_view> ListFields( const CelValue::MessageWrapper& instance) const override { std::vector<absl::string_view> fields; fields.reserve(fields_.size()); for (const auto& field : fields_) { fields.emplace_back(field.first); } return fields; } private: using Field = ProtoField<TestMessage>; const DemoTypeProvider& owning_provider_; absl::flat_hash_map<absl::string_view, std::unique_ptr<Field>> fields_; }; class DemoTypeProvider : public LegacyTypeProvider { public: DemoTypeProvider() : timestamp_type_(), test_message_(this), info_(this) {} const LegacyTypeInfoApis* GetTypeInfoInstance() const { return &info_; } absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const override { if (name == "google.protobuf.Timestamp") { return LegacyTypeAdapter(nullptr, &timestamp_type_); } else if (name == "google.api.expr.runtime.TestMessage") { return LegacyTypeAdapter(&test_message_, &test_message_); } return absl::nullopt; } absl::optional<const LegacyTypeInfoApis*> ProvideLegacyTypeInfo( absl::string_view name) const override { if (name == "google.protobuf.Timestamp") { return &timestamp_type_; } else if (name == "google.api.expr.runtime.TestMessage") { return &test_message_; } return absl::nullopt; } const std::string& GetStableType( const google::protobuf::MessageLite* wrapped_message) const { std::string name = wrapped_message->GetTypeName(); auto [iter, inserted] = stable_types_.insert(name); return *iter; } CelValue WrapValue(const google::protobuf::MessageLite* message) const { return CelValue::CreateMessageWrapper( CelValue::MessageWrapper(message, GetTypeInfoInstance())); } private: DemoTimestamp timestamp_type_; DemoTestMessage test_message_; DemoTypeInfo info_; mutable absl::node_hash_set<std::string> stable_types_; }; std::string DemoTypeInfo::DebugString( const MessageWrapper& wrapped_message) const { return wrapped_message.message_ptr()->GetTypeName(); } const std::string& DemoTypeInfo::GetTypename( const MessageWrapper& wrapped_message) const { return owning_provider_.GetStableType(wrapped_message.message_ptr()); } const LegacyTypeAccessApis* DemoTypeInfo::GetAccessApis( const MessageWrapper& wrapped_message) const { auto adapter = owning_provider_.ProvideLegacyType( wrapped_message.message_ptr()->GetTypeName()); if (adapter.has_value()) { return adapter->access_apis(); } return nullptr; } absl::StatusOr<CelValue::MessageWrapper::Builder> DemoTimestamp::NewInstance( cel::MemoryManagerRef memory_manager) const { auto* ts = google::protobuf::Arena::Create<google::protobuf::Timestamp>( cel::extensions::ProtoMemoryManagerArena(memory_manager)); return CelValue::MessageWrapper::Builder(ts); } absl::StatusOr<CelValue> DemoTimestamp::AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const { auto value = Unwrap(instance.message_ptr()); ABSL_ASSERT(value.has_value()); return *value; } absl::Status DemoTimestamp::SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const { ABSL_ASSERT(Validate(instance.message_ptr()).ok()); auto* mutable_ts = cel::internal::down_cast<google::protobuf::Timestamp*>( instance.message_ptr()); if (field_name == "seconds" && value.IsInt64()) { mutable_ts->set_seconds(value.Int64OrDie()); } else if (field_name == "nanos" && value.IsInt64()) { mutable_ts->set_nanos(value.Int64OrDie()); } else { return absl::UnknownError("no such field"); } return absl::OkStatus(); } DemoTestMessage::DemoTestMessage(const DemoTypeProvider* owning_provider) : owning_provider_(*owning_provider) { fields_["int64_value"] = std::make_unique<Field::FieldImpl<int64_t>>( &TestMessage::int64_value, nullptr, &TestMessage::set_int64_value); fields_["double_value"] = std::make_unique<Field::FieldImpl<double>>( &TestMessage::double_value, nullptr, &TestMessage::set_double_value); fields_["bool_value"] = std::make_unique<Field::FieldImpl<bool>>( &TestMessage::bool_value, nullptr, &TestMessage::set_bool_value); fields_["int64_wrapper_value"] = std::make_unique<Field::FieldImpl<Int64Value>>( &TestMessage::int64_wrapper_value, &TestMessage::has_int64_wrapper_value, &TestMessage::set_allocated_int64_wrapper_value); } absl::StatusOr<CelValue::MessageWrapper::Builder> DemoTestMessage::NewInstance( cel::MemoryManagerRef memory_manager) const { auto* ts = google::protobuf::Arena::Create<TestMessage>( cel::extensions::ProtoMemoryManagerArena(memory_manager)); return CelValue::MessageWrapper::Builder(ts); } absl::Status DemoTestMessage::SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const { auto iter = fields_.find(field_name); if (iter == fields_.end()) { return absl::UnknownError("no such field"); } auto* mutable_test_msg = cel::internal::down_cast<TestMessage*>(instance.message_ptr()); return iter->second->Set(mutable_test_msg, value); } absl::StatusOr<CelValue> DemoTestMessage::AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const { return CelValue::CreateMessageWrapper( instance.Build(owning_provider_.GetTypeInfoInstance())); } absl::StatusOr<bool> DemoTestMessage::HasField( absl::string_view field_name, const CelValue::MessageWrapper& value) const { auto iter = fields_.find(field_name); if (iter == fields_.end()) { return absl::UnknownError("no such field"); } auto* test_msg = cel::internal::down_cast<const TestMessage*>(value.message_ptr()); return iter->second->Has(test_msg); } absl::StatusOr<CelValue> DemoTestMessage::GetField( absl::string_view field_name, const CelValue::MessageWrapper& instance, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) const { auto iter = fields_.find(field_name); if (iter == fields_.end()) { return absl::UnknownError("no such field"); } auto* test_msg = cel::internal::down_cast<const TestMessage*>(instance.message_ptr()); return iter->second->Get(test_msg); } TEST(PortableCelExprBuilderFactoryTest, CreateNullOnMissingTypeProvider) { std::unique_ptr<CelExpressionBuilder> builder = CreatePortableExprBuilder(nullptr); ASSERT_EQ(builder, nullptr); } TEST(PortableCelExprBuilderFactoryTest, CreateSuccess) { google::protobuf::Arena arena; InterpreterOptions opts; Activation activation; std::unique_ptr<CelExpressionBuilder> builder = CreatePortableExprBuilder(std::make_unique<DemoTypeProvider>(), opts); ASSERT_OK_AND_ASSIGN( ParsedExpr expr, parser::Parse("google.protobuf.Timestamp{seconds: 3000, nanos: 20}")); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN( auto plan, builder->CreateExpression(&expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena)); absl::Time result_time; ASSERT_TRUE(result.GetValue(&result_time)); EXPECT_EQ(result_time, absl::UnixEpoch() + absl::Minutes(50) + absl::Nanoseconds(20)); } TEST(PortableCelExprBuilderFactoryTest, CreateCustomMessage) { google::protobuf::Arena arena; InterpreterOptions opts; Activation activation; std::unique_ptr<CelExpressionBuilder> builder = CreatePortableExprBuilder(std::make_unique<DemoTypeProvider>(), opts); ASSERT_OK_AND_ASSIGN( ParsedExpr expr, parser::Parse("google.api.expr.runtime.TestMessage{int64_value: 20, " "double_value: 3.5}.double_value")); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), opts)); ASSERT_OK_AND_ASSIGN( auto plan, builder->CreateExpression(&expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena)); double result_double; ASSERT_TRUE(result.GetValue(&result_double)) << result.DebugString(); EXPECT_EQ(result_double, 3.5); } TEST(PortableCelExprBuilderFactoryTest, ActivationAndCreate) { google::protobuf::Arena arena; InterpreterOptions opts; Activation activation; auto provider = std::make_unique<DemoTypeProvider>(); auto* provider_view = provider.get(); std::unique_ptr<CelExpressionBuilder> builder = CreatePortableExprBuilder(std::move(provider), opts); builder->set_container("google.api.expr.runtime"); ASSERT_OK_AND_ASSIGN( ParsedExpr expr, parser::Parse("TestMessage{int64_value: 20, bool_value: " "false}.bool_value || my_var.bool_value ? 1 : 2")); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), opts)); ASSERT_OK_AND_ASSIGN( auto plan, builder->CreateExpression(&expr.expr(), &expr.source_info())); TestMessage my_var; my_var.set_bool_value(true); activation.InsertValue("my_var", provider_view->WrapValue(&my_var)); ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena)); int64_t result_int64; ASSERT_TRUE(result.GetValue(&result_int64)) << result.DebugString(); EXPECT_EQ(result_int64, 1); } TEST(PortableCelExprBuilderFactoryTest, WrapperTypes) { google::protobuf::Arena arena; InterpreterOptions opts; opts.enable_heterogeneous_equality = true; Activation activation; auto provider = std::make_unique<DemoTypeProvider>(); const auto* provider_view = provider.get(); std::unique_ptr<CelExpressionBuilder> builder = CreatePortableExprBuilder(std::move(provider), opts); builder->set_container("google.api.expr.runtime"); ASSERT_OK_AND_ASSIGN(ParsedExpr null_expr, parser::Parse("my_var.int64_wrapper_value != null ? " "my_var.int64_wrapper_value > 29 : null")); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), opts)); TestMessage my_var; my_var.set_bool_value(true); activation.InsertValue("my_var", provider_view->WrapValue(&my_var)); ASSERT_OK_AND_ASSIGN( auto plan, builder->CreateExpression(&null_expr.expr(), &null_expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena)); EXPECT_TRUE(result.IsNull()) << result.DebugString(); my_var.mutable_int64_wrapper_value()->set_value(30); ASSERT_OK_AND_ASSIGN(result, plan->Evaluate(activation, &arena)); bool result_bool; ASSERT_TRUE(result.GetValue(&result_bool)) << result.DebugString(); EXPECT_TRUE(result_bool); } TEST(PortableCelExprBuilderFactoryTest, SimpleBuiltinFunctions) { google::protobuf::Arena arena; InterpreterOptions opts; opts.enable_heterogeneous_equality = true; Activation activation; auto provider = std::make_unique<DemoTypeProvider>(); std::unique_ptr<CelExpressionBuilder> builder = CreatePortableExprBuilder(std::move(provider), opts); builder->set_container("google.api.expr.runtime"); ASSERT_OK_AND_ASSIGN( ParsedExpr ternary_expr, parser::Parse( "TestMessage{int64_value: 2}.int64_value + 1 < " " TestMessage{double_value: 3.5}.double_value - 0.1 ? " " (google.protobuf.Timestamp{seconds: 300} - timestamp(240) " " >= duration('1m') ? 'yes' : 'no') :" " null")); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry(), opts)); ASSERT_OK_AND_ASSIGN(auto plan, builder->CreateExpression(&ternary_expr.expr(), &ternary_expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, plan->Evaluate(activation, &arena)); ASSERT_TRUE(result.IsString()) << result.DebugString(); EXPECT_EQ(result.StringOrDie().value(), "yes"); } } }