ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
64d18beb-abd6-4bb5-acc6-c4532760ac83
cpp
google/cel-cpp
string_pool
internal/string_pool.cc
internal/string_pool_test.cc
#include "internal/string_pool.h" #include <cstring> #include <string> #include "absl/base/optimization.h" #include "absl/strings/string_view.h" #include "google/protobuf/arena.h" namespace cel::internal { absl::string_view StringPool::InternString(absl::string_view string) { if (string.empty()) { return ""; } return *strings_.lazy_emplace(string, [&](const auto& ctor) { ABSL_ASSUME(arena_ != nullptr); char* data = google::protobuf::Arena::CreateArray<char>(arena_, string.size()); std::memcpy(data, string.data(), string.size()); ctor(absl::string_view(data, string.size())); }); } }
#include "internal/string_pool.h" #include "absl/strings/string_view.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel::internal { namespace { TEST(StringPool, EmptyString) { google::protobuf::Arena arena; StringPool string_pool(&arena); absl::string_view interned_string = string_pool.InternString(""); EXPECT_EQ(interned_string.data(), string_pool.InternString("").data()); } TEST(StringPool, InternString) { google::protobuf::Arena arena; StringPool string_pool(&arena); absl::string_view interned_string = string_pool.InternString("Hello, world!"); EXPECT_EQ(interned_string.data(), string_pool.InternString("Hello, world!").data()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/string_pool.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/string_pool_test.cc
4552db5798fb0853b131b783d8875794334fae7f
b64966ca-5157-4ae3-9ed8-a270cc43f1ea
cpp
google/cel-cpp
json
common/json.cc
common/json_test.cc
#include "common/json.h" #include <initializer_list> #include <string> #include <utility> #include "absl/base/no_destructor.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "common/any.h" #include "internal/copy_on_write.h" #include "internal/proto_wire.h" #include "internal/status_macros.h" namespace cel { internal::CopyOnWrite<typename JsonArray::Container> JsonArray::Empty() { static const absl::NoDestructor<internal::CopyOnWrite<Container>> empty; return *empty; } internal::CopyOnWrite<typename JsonObject::Container> JsonObject::Empty() { static const absl::NoDestructor<internal::CopyOnWrite<Container>> empty; return *empty; } Json JsonInt(int64_t value) { if (value < kJsonMinInt || value > kJsonMaxInt) { return JsonString(absl::StrCat(value)); } return Json(static_cast<double>(value)); } Json JsonUint(uint64_t value) { if (value > kJsonMaxUint) { return JsonString(absl::StrCat(value)); } return Json(static_cast<double>(value)); } Json JsonBytes(absl::string_view value) { return JsonString(absl::Base64Escape(value)); } Json JsonBytes(const absl::Cord& value) { if (auto flat = value.TryFlat(); flat.has_value()) { return JsonBytes(*flat); } return JsonBytes(absl::string_view(static_cast<std::string>(value))); } bool JsonArrayBuilder::empty() const { return impl_.get().empty(); } JsonArray JsonArrayBuilder::Build() && { return JsonArray(std::move(impl_)); } JsonArrayBuilder::JsonArrayBuilder(JsonArray array) : impl_(std::move(array.impl_)) {} JsonObjectBuilder::JsonObjectBuilder(JsonObject object) : impl_(std::move(object.impl_)) {} void JsonObjectBuilder::insert(std::initializer_list<value_type> il) { impl_.mutable_get().insert(il); } JsonArrayBuilder::size_type JsonArrayBuilder::size() const { return impl_.get().size(); } JsonArrayBuilder::iterator JsonArrayBuilder::begin() { return impl_.mutable_get().begin(); } JsonArrayBuilder::const_iterator JsonArrayBuilder::begin() const { return impl_.get().begin(); } JsonArrayBuilder::iterator JsonArrayBuilder::end() { return impl_.mutable_get().end(); } JsonArrayBuilder::const_iterator JsonArrayBuilder::end() const { return impl_.get().end(); } JsonArrayBuilder::reverse_iterator JsonArrayBuilder::rbegin() { return impl_.mutable_get().rbegin(); } JsonArrayBuilder::reverse_iterator JsonArrayBuilder::rend() { return impl_.mutable_get().rend(); } JsonArrayBuilder::reference JsonArrayBuilder::at(size_type index) { return impl_.mutable_get().at(index); } JsonArrayBuilder::reference JsonArrayBuilder::operator[](size_type index) { return (impl_.mutable_get())[index]; } void JsonArrayBuilder::reserve(size_type n) { if (n != 0) { impl_.mutable_get().reserve(n); } } void JsonArrayBuilder::clear() { impl_.mutable_get().clear(); } void JsonArrayBuilder::push_back(Json json) { impl_.mutable_get().push_back(std::move(json)); } void JsonArrayBuilder::pop_back() { impl_.mutable_get().pop_back(); } JsonArrayBuilder::operator JsonArray() && { return std::move(*this).Build(); } bool JsonArray::empty() const { return impl_.get().empty(); } JsonArray::JsonArray(internal::CopyOnWrite<Container> impl) : impl_(std::move(impl)) { if (impl_.get().empty()) { impl_ = Empty(); } } JsonArray::size_type JsonArray::size() const { return impl_.get().size(); } JsonArray::const_iterator JsonArray::begin() const { return impl_.get().begin(); } JsonArray::const_iterator JsonArray::cbegin() const { return begin(); } JsonArray::const_iterator JsonArray::end() const { return impl_.get().end(); } JsonArray::const_iterator JsonArray::cend() const { return begin(); } JsonArray::const_reverse_iterator JsonArray::rbegin() const { return impl_.get().rbegin(); } JsonArray::const_reverse_iterator JsonArray::crbegin() const { return impl_.get().crbegin(); } JsonArray::const_reverse_iterator JsonArray::rend() const { return impl_.get().rend(); } JsonArray::const_reverse_iterator JsonArray::crend() const { return impl_.get().crend(); } JsonArray::const_reference JsonArray::at(size_type index) const { return impl_.get().at(index); } JsonArray::const_reference JsonArray::operator[](size_type index) const { return (impl_.get())[index]; } bool operator==(const JsonArray& lhs, const JsonArray& rhs) { return lhs.impl_.get() == rhs.impl_.get(); } bool operator!=(const JsonArray& lhs, const JsonArray& rhs) { return lhs.impl_.get() != rhs.impl_.get(); } JsonObjectBuilder::operator JsonObject() && { return std::move(*this).Build(); } bool JsonObjectBuilder::empty() const { return impl_.get().empty(); } JsonObjectBuilder::size_type JsonObjectBuilder::size() const { return impl_.get().size(); } JsonObjectBuilder::iterator JsonObjectBuilder::begin() { return impl_.mutable_get().begin(); } JsonObjectBuilder::const_iterator JsonObjectBuilder::begin() const { return impl_.get().begin(); } JsonObjectBuilder::iterator JsonObjectBuilder::end() { return impl_.mutable_get().end(); } JsonObjectBuilder::const_iterator JsonObjectBuilder::end() const { return impl_.get().end(); } void JsonObjectBuilder::clear() { impl_.mutable_get().clear(); } JsonObject JsonObjectBuilder::Build() && { return JsonObject(std::move(impl_)); } void JsonObjectBuilder::erase(const_iterator pos) { impl_.mutable_get().erase(std::move(pos)); } void JsonObjectBuilder::reserve(size_type n) { if (n != 0) { impl_.mutable_get().reserve(n); } } JsonObject MakeJsonObject( std::initializer_list<std::pair<JsonString, Json>> il) { JsonObjectBuilder builder; builder.reserve(il.size()); for (const auto& entry : il) { builder.insert(entry); } return std::move(builder).Build(); } JsonObject::JsonObject(internal::CopyOnWrite<Container> impl) : impl_(std::move(impl)) { if (impl_.get().empty()) { impl_ = Empty(); } } bool JsonObject::empty() const { return impl_.get().empty(); } JsonObject::size_type JsonObject::size() const { return impl_.get().size(); } JsonObject::const_iterator JsonObject::begin() const { return impl_.get().begin(); } JsonObject::const_iterator JsonObject::cbegin() const { return begin(); } JsonObject::const_iterator JsonObject::end() const { return impl_.get().end(); } JsonObject::const_iterator JsonObject::cend() const { return end(); } bool operator==(const JsonObject& lhs, const JsonObject& rhs) { return lhs.impl_.get() == rhs.impl_.get(); } bool operator!=(const JsonObject& lhs, const JsonObject& rhs) { return lhs.impl_.get() != rhs.impl_.get(); } namespace { using internal::ProtoWireEncoder; using internal::ProtoWireTag; using internal::ProtoWireType; inline constexpr absl::string_view kJsonTypeName = "google.protobuf.Value"; inline constexpr absl::string_view kJsonArrayTypeName = "google.protobuf.ListValue"; inline constexpr absl::string_view kJsonObjectTypeName = "google.protobuf.Struct"; inline constexpr ProtoWireTag kValueNullValueFieldTag = ProtoWireTag(1, ProtoWireType::kVarint); inline constexpr ProtoWireTag kValueBoolValueFieldTag = ProtoWireTag(4, ProtoWireType::kVarint); inline constexpr ProtoWireTag kValueNumberValueFieldTag = ProtoWireTag(2, ProtoWireType::kFixed64); inline constexpr ProtoWireTag kValueStringValueFieldTag = ProtoWireTag(3, ProtoWireType::kLengthDelimited); inline constexpr ProtoWireTag kValueListValueFieldTag = ProtoWireTag(6, ProtoWireType::kLengthDelimited); inline constexpr ProtoWireTag kValueStructValueFieldTag = ProtoWireTag(5, ProtoWireType::kLengthDelimited); inline constexpr ProtoWireTag kListValueValuesFieldTag = ProtoWireTag(1, ProtoWireType::kLengthDelimited); inline constexpr ProtoWireTag kStructFieldsEntryKeyFieldTag = ProtoWireTag(1, ProtoWireType::kLengthDelimited); inline constexpr ProtoWireTag kStructFieldsEntryValueFieldTag = ProtoWireTag(2, ProtoWireType::kLengthDelimited); absl::StatusOr<absl::Cord> JsonObjectEntryToAnyValue(const absl::Cord& key, const Json& value) { absl::Cord data; ProtoWireEncoder encoder("google.protobuf.Struct.FieldsEntry", data); absl::Cord subdata; CEL_RETURN_IF_ERROR(JsonToAnyValue(value, subdata)); CEL_RETURN_IF_ERROR(encoder.WriteTag(kStructFieldsEntryKeyFieldTag)); CEL_RETURN_IF_ERROR(encoder.WriteLengthDelimited(std::move(key))); CEL_RETURN_IF_ERROR(encoder.WriteTag(kStructFieldsEntryValueFieldTag)); CEL_RETURN_IF_ERROR(encoder.WriteLengthDelimited(std::move(subdata))); encoder.EnsureFullyEncoded(); return data; } inline constexpr ProtoWireTag kStructFieldsFieldTag = ProtoWireTag(1, ProtoWireType::kLengthDelimited); } absl::Status JsonToAnyValue(const Json& json, absl::Cord& data) { ProtoWireEncoder encoder(kJsonTypeName, data); absl::Status status = absl::visit( absl::Overload( [&encoder](JsonNull) -> absl::Status { CEL_RETURN_IF_ERROR(encoder.WriteTag(kValueNullValueFieldTag)); return encoder.WriteVarint(0); }, [&encoder](JsonBool value) -> absl::Status { CEL_RETURN_IF_ERROR(encoder.WriteTag(kValueBoolValueFieldTag)); return encoder.WriteVarint(value); }, [&encoder](JsonNumber value) -> absl::Status { CEL_RETURN_IF_ERROR(encoder.WriteTag(kValueNumberValueFieldTag)); return encoder.WriteFixed64(value); }, [&encoder](const JsonString& value) -> absl::Status { CEL_RETURN_IF_ERROR(encoder.WriteTag(kValueStringValueFieldTag)); return encoder.WriteLengthDelimited(value); }, [&encoder](const JsonArray& value) -> absl::Status { absl::Cord subdata; CEL_RETURN_IF_ERROR(JsonArrayToAnyValue(value, subdata)); CEL_RETURN_IF_ERROR(encoder.WriteTag(kValueListValueFieldTag)); return encoder.WriteLengthDelimited(std::move(subdata)); }, [&encoder](const JsonObject& value) -> absl::Status { absl::Cord subdata; CEL_RETURN_IF_ERROR(JsonObjectToAnyValue(value, subdata)); CEL_RETURN_IF_ERROR(encoder.WriteTag(kValueStructValueFieldTag)); return encoder.WriteLengthDelimited(std::move(subdata)); }), json); CEL_RETURN_IF_ERROR(status); encoder.EnsureFullyEncoded(); return absl::OkStatus(); } absl::Status JsonArrayToAnyValue(const JsonArray& json, absl::Cord& data) { ProtoWireEncoder encoder(kJsonArrayTypeName, data); for (const auto& element : json) { absl::Cord subdata; CEL_RETURN_IF_ERROR(JsonToAnyValue(element, subdata)); CEL_RETURN_IF_ERROR(encoder.WriteTag(kListValueValuesFieldTag)); CEL_RETURN_IF_ERROR(encoder.WriteLengthDelimited(std::move(subdata))); } encoder.EnsureFullyEncoded(); return absl::OkStatus(); } absl::Status JsonObjectToAnyValue(const JsonObject& json, absl::Cord& data) { ProtoWireEncoder encoder(kJsonObjectTypeName, data); for (const auto& entry : json) { CEL_ASSIGN_OR_RETURN(auto subdata, JsonObjectEntryToAnyValue(entry.first, entry.second)); CEL_RETURN_IF_ERROR(encoder.WriteTag(kStructFieldsFieldTag)); CEL_RETURN_IF_ERROR(encoder.WriteLengthDelimited(std::move(subdata))); } encoder.EnsureFullyEncoded(); return absl::OkStatus(); } absl::StatusOr<google::protobuf::Any> JsonToAny(const Json& json) { absl::Cord data; CEL_RETURN_IF_ERROR(JsonToAnyValue(json, data)); return MakeAny(MakeTypeUrl(kJsonTypeName), std::move(data)); } absl::StatusOr<google::protobuf::Any> JsonArrayToAny(const JsonArray& json) { absl::Cord data; CEL_RETURN_IF_ERROR(JsonArrayToAnyValue(json, data)); return MakeAny(MakeTypeUrl(kJsonArrayTypeName), std::move(data)); } absl::StatusOr<google::protobuf::Any> JsonObjectToAny(const JsonObject& json) { absl::Cord data; CEL_RETURN_IF_ERROR(JsonObjectToAnyValue(json, data)); return MakeAny(MakeTypeUrl(kJsonObjectTypeName), std::move(data)); } }
#include "common/json.h" #include "absl/hash/hash_testing.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "internal/testing.h" namespace cel::internal { namespace { using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::UnorderedElementsAre; using ::testing::VariantWith; TEST(Json, DefaultConstructor) { EXPECT_THAT(Json(), VariantWith<JsonNull>(Eq(kJsonNull))); } TEST(Json, NullConstructor) { EXPECT_THAT(Json(kJsonNull), VariantWith<JsonNull>(Eq(kJsonNull))); } TEST(Json, FalseConstructor) { EXPECT_THAT(Json(false), VariantWith<JsonBool>(IsFalse())); } TEST(Json, TrueConstructor) { EXPECT_THAT(Json(true), VariantWith<JsonBool>(IsTrue())); } TEST(Json, NumberConstructor) { EXPECT_THAT(Json(1.0), VariantWith<JsonNumber>(1)); } TEST(Json, StringConstructor) { EXPECT_THAT(Json(JsonString("foo")), VariantWith<JsonString>(Eq("foo"))); } TEST(Json, ArrayConstructor) { EXPECT_THAT(Json(JsonArray()), VariantWith<JsonArray>(Eq(JsonArray()))); } TEST(Json, ObjectConstructor) { EXPECT_THAT(Json(JsonObject()), VariantWith<JsonObject>(Eq(JsonObject()))); } TEST(Json, ImplementsAbslHashCorrectly) { EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {Json(), Json(true), Json(1.0), Json(JsonString("foo")), Json(JsonArray()), Json(JsonObject())})); } TEST(JsonArrayBuilder, DefaultConstructor) { JsonArrayBuilder builder; EXPECT_TRUE(builder.empty()); EXPECT_EQ(builder.size(), 0); } TEST(JsonArrayBuilder, OneOfEach) { JsonArrayBuilder builder; builder.reserve(6); builder.push_back(kJsonNull); builder.push_back(true); builder.push_back(1.0); builder.push_back(JsonString("foo")); builder.push_back(JsonArray()); builder.push_back(JsonObject()); EXPECT_FALSE(builder.empty()); EXPECT_EQ(builder.size(), 6); EXPECT_THAT(builder, ElementsAre(kJsonNull, true, 1.0, JsonString("foo"), JsonArray(), JsonObject())); builder.pop_back(); EXPECT_FALSE(builder.empty()); EXPECT_EQ(builder.size(), 5); EXPECT_THAT(builder, ElementsAre(kJsonNull, true, 1.0, JsonString("foo"), JsonArray())); builder.clear(); EXPECT_TRUE(builder.empty()); EXPECT_EQ(builder.size(), 0); } TEST(JsonObjectBuilder, DefaultConstructor) { JsonObjectBuilder builder; EXPECT_TRUE(builder.empty()); EXPECT_EQ(builder.size(), 0); } TEST(JsonObjectBuilder, OneOfEach) { JsonObjectBuilder builder; builder.reserve(6); builder.insert_or_assign(JsonString("foo"), kJsonNull); builder.insert_or_assign(JsonString("bar"), true); builder.insert_or_assign(JsonString("baz"), 1.0); builder.insert_or_assign(JsonString("qux"), JsonString("foo")); builder.insert_or_assign(JsonString("quux"), JsonArray()); builder.insert_or_assign(JsonString("corge"), JsonObject()); EXPECT_FALSE(builder.empty()); EXPECT_EQ(builder.size(), 6); EXPECT_THAT(builder, UnorderedElementsAre( std::make_pair(JsonString("foo"), kJsonNull), std::make_pair(JsonString("bar"), true), std::make_pair(JsonString("baz"), 1.0), std::make_pair(JsonString("qux"), JsonString("foo")), std::make_pair(JsonString("quux"), JsonArray()), std::make_pair(JsonString("corge"), JsonObject()))); builder.erase(JsonString("corge")); EXPECT_FALSE(builder.empty()); EXPECT_EQ(builder.size(), 5); EXPECT_THAT(builder, UnorderedElementsAre( std::make_pair(JsonString("foo"), kJsonNull), std::make_pair(JsonString("bar"), true), std::make_pair(JsonString("baz"), 1.0), std::make_pair(JsonString("qux"), JsonString("foo")), std::make_pair(JsonString("quux"), JsonArray()))); builder.clear(); EXPECT_TRUE(builder.empty()); EXPECT_EQ(builder.size(), 0); } TEST(JsonInt, Basic) { EXPECT_THAT(JsonInt(1), VariantWith<JsonNumber>(1.0)); EXPECT_THAT(JsonInt(std::numeric_limits<int64_t>::max()), VariantWith<JsonString>( Eq(absl::StrCat(std::numeric_limits<int64_t>::max())))); } TEST(JsonUint, Basic) { EXPECT_THAT(JsonUint(1), VariantWith<JsonNumber>(1.0)); EXPECT_THAT(JsonUint(std::numeric_limits<uint64_t>::max()), VariantWith<JsonString>( Eq(absl::StrCat(std::numeric_limits<uint64_t>::max())))); } TEST(JsonBytes, Basic) { EXPECT_THAT(JsonBytes("foo"), VariantWith<JsonString>(Eq(absl::Base64Escape("foo")))); EXPECT_THAT(JsonBytes(absl::Cord("foo")), VariantWith<JsonString>(Eq(absl::Base64Escape("foo")))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/json.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/json_test.cc
4552db5798fb0853b131b783d8875794334fae7f
0ea8a6b6-b2a9-416e-9b86-777aa27c03fe
cpp
google/cel-cpp
proto_time_encoding
internal/proto_time_encoding.cc
internal/proto_time_encoding_test.cc
#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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/proto_time_encoding.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/proto_time_encoding_test.cc
4552db5798fb0853b131b783d8875794334fae7f
8163b5c8-cb29-47ef-96a7-84b47fec4f55
cpp
google/cel-cpp
strings
extensions/strings.cc
extensions/strings_test.cc
#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(ListType{})); 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.GetBool().NativeValue()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/strings.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/strings_test.cc
4552db5798fb0853b131b783d8875794334fae7f
4e99a540-5aba-4af7-a26a-89e32aee742d
cpp
google/cel-cpp
proto_util
internal/proto_util.cc
internal/proto_util_test.cc
#include "internal/proto_util.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 "absl/status/status.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 ::absl_testing::StatusIs; using ::testing::HasSubstr; 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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/proto_util.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/proto_util_test.cc
4552db5798fb0853b131b783d8875794334fae7f
ee3c1432-be08-420c-8fd2-095a457add68
cpp
google/cel-cpp
names
internal/names.cc
internal/names_test.cc
#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}})); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/names.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/names_test.cc
4552db5798fb0853b131b783d8875794334fae7f
b291c2ed-7b74-4ed8-8198-339942ef74bb
cpp
google/cel-cpp
new
internal/new.cc
internal/new_test.cc
#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, maybe_unused]] void ThrowStdBadAlloc() { #ifdef ABSL_HAVE_EXCEPTIONS throw std::bad_alloc(); #else std::abort(); #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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/new.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/new_test.cc
4552db5798fb0853b131b783d8875794334fae7f
40856a9f-870b-42bd-a43a-53b03f6a6ef2
cpp
google/cel-cpp
proto_wire
internal/proto_wire.cc
internal/proto_wire_test.cc
#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 ::absl_testing::IsOkAndHolds; using ::testing::Eq; using ::testing::Optional; 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"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/proto_wire.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/proto_wire_test.cc
4552db5798fb0853b131b783d8875794334fae7f
132383d5-a84f-45ff-9829-fb63d2ae5943
cpp
google/cel-cpp
utf8
internal/utf8.cc
internal/utf8_test.cc
#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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/utf8.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/utf8_test.cc
4552db5798fb0853b131b783d8875794334fae7f
00b03a32-708c-468a-bb5c-d92f15479138
cpp
google/cel-cpp
lexis
internal/lexis.cc
internal/lexis_test.cc
#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}})); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/lexis.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/lexis_test.cc
4552db5798fb0853b131b783d8875794334fae7f
70cab951-f568-4125-8238-ab87fb041758
cpp
google/cel-cpp
overflow
internal/overflow.cc
internal/overflow_test.cc
#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; }); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/overflow.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/overflow_test.cc
4552db5798fb0853b131b783d8875794334fae7f
1e029fa7-a92b-4f6b-89f9-6779c761db00
cpp
google/cel-cpp
minimal_descriptor_pool
internal/minimal_descriptor_pool.cc
internal/minimal_descriptor_pool_test.cc
#include "internal/minimal_descriptor_pool.h" #include <cstdint> #include "google/protobuf/descriptor.pb.h" #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "google/protobuf/descriptor.h" namespace cel::internal { namespace { ABSL_CONST_INIT const uint8_t kMinimalDescriptorSet[] = { #include "internal/minimal_descriptor_set_embed.inc" }; } absl::Nonnull<const google::protobuf::DescriptorPool*> GetMinimalDescriptorPool() { static absl::Nonnull<const google::protobuf::DescriptorPool* const> pool = []() { google::protobuf::FileDescriptorSet file_desc_set; ABSL_CHECK(file_desc_set.ParseFromArray( kMinimalDescriptorSet, ABSL_ARRAYSIZE(kMinimalDescriptorSet))); auto* pool = new google::protobuf::DescriptorPool(); for (const auto& file_desc : file_desc_set.file()) { ABSL_CHECK(pool->BuildFile(file_desc) != nullptr); } return pool; }(); return pool; } }
#include "internal/minimal_descriptor_pool.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" namespace cel::internal { namespace { using ::testing::NotNull; TEST(MinimalDescriptorPool, NullValue) { ASSERT_THAT(GetMinimalDescriptorPool()->FindEnumTypeByName( "google.protobuf.NullValue"), NotNull()); } TEST(MinimalDescriptorPool, BoolValue) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.BoolValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE); } TEST(MinimalDescriptorPool, Int32Value) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.Int32Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE); } TEST(MinimalDescriptorPool, Int64Value) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.Int64Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE); } TEST(MinimalDescriptorPool, UInt32Value) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.UInt32Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE); } TEST(MinimalDescriptorPool, UInt64Value) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.UInt64Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE); } TEST(MinimalDescriptorPool, FloatValue) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.FloatValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE); } TEST(MinimalDescriptorPool, DoubleValue) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.DoubleValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE); } TEST(MinimalDescriptorPool, BytesValue) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.BytesValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE); } TEST(MinimalDescriptorPool, StringValue) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.StringValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE); } TEST(MinimalDescriptorPool, Any) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName("google.protobuf.Any"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_ANY); } TEST(MinimalDescriptorPool, Duration) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.Duration"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION); } TEST(MinimalDescriptorPool, Timestamp) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.Timestamp"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP); } TEST(MinimalDescriptorPool, Value) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE); } TEST(MinimalDescriptorPool, ListValue) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.ListValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE); } TEST(MinimalDescriptorPool, Struct) { const auto* desc = GetMinimalDescriptorPool()->FindMessageTypeByName( "google.protobuf.Struct"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/minimal_descriptor_pool.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/minimal_descriptor_pool_test.cc
4552db5798fb0853b131b783d8875794334fae7f
15e81774-698f-4cbc-a34a-ff70cdd6ccf9
cpp
google/cel-cpp
well_known_types
internal/well_known_types.cc
internal/well_known_types_test.cc
#include "internal/well_known_types.h" #include <cstddef> #include <cstdint> #include <functional> #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 "google/protobuf/descriptor.pb.h" #include "absl/base/attributes.h" #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/base/optimization.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_join.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/time/time.h" #include "absl/types/variant.h" #include "common/json.h" #include "common/memory.h" #include "extensions/protobuf/internal/map_reflection.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" #include "google/protobuf/message_lite.h" #include "google/protobuf/reflection.h" #include "google/protobuf/util/time_util.h" namespace cel::well_known_types { namespace { using ::google::protobuf::Descriptor; using ::google::protobuf::DescriptorPool; using ::google::protobuf::EnumDescriptor; using ::google::protobuf::FieldDescriptor; using ::google::protobuf::OneofDescriptor; using ::google::protobuf::util::TimeUtil; using CppStringType = ::google::protobuf::FieldDescriptor::CppStringType; absl::string_view FlatStringValue( const StringValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { return absl::visit( absl::Overload( [](absl::string_view string) -> absl::string_view { return string; }, [&](const absl::Cord& cord) -> absl::string_view { if (auto flat = cord.TryFlat(); flat) { return *flat; } scratch = static_cast<std::string>(cord); return scratch; }), AsVariant(value)); } StringValue CopyStringValue(const StringValue& value, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { return absl::visit( absl::Overload( [&](absl::string_view string) -> StringValue { if (string.data() != scratch.data()) { scratch.assign(string.data(), string.size()); return scratch; } return string; }, [](const absl::Cord& cord) -> StringValue { return cord; }), AsVariant(value)); } BytesValue CopyBytesValue(const BytesValue& value, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { return absl::visit( absl::Overload( [&](absl::string_view string) -> BytesValue { if (string.data() != scratch.data()) { scratch.assign(string.data(), string.size()); return scratch; } return string; }, [](const absl::Cord& cord) -> BytesValue { return cord; }), AsVariant(value)); } google::protobuf::Reflection::ScratchSpace& GetScratchSpace() { static absl::NoDestructor<google::protobuf::Reflection::ScratchSpace> scratch_space; return *scratch_space; } template <typename Variant> Variant GetStringField(absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, CppStringType string_type, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { ABSL_DCHECK(field->cpp_string_type() == string_type); switch (string_type) { case CppStringType::kCord: return reflection->GetCord(message, field); case CppStringType::kView: ABSL_FALLTHROUGH_INTENDED; case CppStringType::kString: return reflection->GetStringView(message, field, GetScratchSpace()); default: return absl::string_view( reflection->GetStringReference(message, field, &scratch)); } } template <typename Variant> Variant GetStringField(const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, CppStringType string_type, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { return GetStringField<Variant>(message.GetReflection(), message, field, string_type, scratch); } template <typename Variant> Variant GetRepeatedStringField( absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, CppStringType string_type, int index, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { ABSL_DCHECK(field->cpp_string_type() == string_type); switch (string_type) { case CppStringType::kView: ABSL_FALLTHROUGH_INTENDED; case CppStringType::kString: return reflection->GetRepeatedStringView(message, field, index, GetScratchSpace()); default: return absl::string_view(reflection->GetRepeatedStringReference( message, field, index, &scratch)); } } template <typename Variant> Variant GetRepeatedStringField( const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, CppStringType string_type, int index, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { return GetRepeatedStringField<Variant>(message.GetReflection(), message, field, string_type, index, scratch); } absl::StatusOr<absl::Nonnull<const Descriptor*>> GetMessageTypeByName( absl::Nonnull<const DescriptorPool*> pool, absl::string_view name) { const auto* descriptor = pool->FindMessageTypeByName(name); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InvalidArgumentError(absl::StrCat( "descriptor missing for protocol buffer message well known type: ", name)); } return descriptor; } absl::StatusOr<absl::Nonnull<const EnumDescriptor*>> GetEnumTypeByName( absl::Nonnull<const DescriptorPool*> pool, absl::string_view name) { const auto* descriptor = pool->FindEnumTypeByName(name); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InvalidArgumentError(absl::StrCat( "descriptor missing for protocol buffer enum well known type: ", name)); } return descriptor; } absl::StatusOr<absl::Nonnull<const OneofDescriptor*>> GetOneofByName( absl::Nonnull<const Descriptor*> descriptor, absl::string_view name) { const auto* oneof = descriptor->FindOneofByName(name); if (ABSL_PREDICT_FALSE(oneof == nullptr)) { return absl::InvalidArgumentError(absl::StrCat( "oneof missing for protocol buffer message well known type: ", descriptor->full_name(), ".", name)); } return oneof; } absl::StatusOr<absl::Nonnull<const FieldDescriptor*>> GetFieldByNumber( absl::Nonnull<const Descriptor*> descriptor, int32_t number) { const auto* field = descriptor->FindFieldByNumber(number); if (ABSL_PREDICT_FALSE(field == nullptr)) { return absl::InvalidArgumentError(absl::StrCat( "field missing for protocol buffer message well known type: ", descriptor->full_name(), ".", number)); } return field; } absl::Status CheckFieldType(absl::Nonnull<const FieldDescriptor*> field, FieldDescriptor::Type type) { if (ABSL_PREDICT_FALSE(field->type() != type)) { return absl::InvalidArgumentError(absl::StrCat( "unexpected field type for protocol buffer message well known type: ", field->full_name(), " ", field->type_name())); } return absl::OkStatus(); } absl::Status CheckFieldCppType(absl::Nonnull<const FieldDescriptor*> field, FieldDescriptor::CppType cpp_type) { if (ABSL_PREDICT_FALSE(field->cpp_type() != cpp_type)) { return absl::InvalidArgumentError(absl::StrCat( "unexpected field type for protocol buffer message well known type: ", field->full_name(), " ", field->cpp_type_name())); } return absl::OkStatus(); } absl::string_view LabelToString(FieldDescriptor::Label label) { switch (label) { case FieldDescriptor::LABEL_REPEATED: return "REPEATED"; case FieldDescriptor::LABEL_REQUIRED: return "REQUIRED"; case FieldDescriptor::LABEL_OPTIONAL: return "OPTIONAL"; default: return "ERROR"; } } absl::Status CheckFieldCardinality(absl::Nonnull<const FieldDescriptor*> field, FieldDescriptor::Label label) { if (ABSL_PREDICT_FALSE(field->label() != label)) { return absl::InvalidArgumentError( absl::StrCat("unexpected field cardinality for protocol buffer message " "well known type: ", field->full_name(), " ", LabelToString(field->label()))); } return absl::OkStatus(); } absl::string_view WellKnownTypeToString( Descriptor::WellKnownType well_known_type) { switch (well_known_type) { case Descriptor::WELLKNOWNTYPE_BOOLVALUE: return "BOOLVALUE"; case Descriptor::WELLKNOWNTYPE_INT32VALUE: return "INT32VALUE"; case Descriptor::WELLKNOWNTYPE_INT64VALUE: return "INT64VALUE"; case Descriptor::WELLKNOWNTYPE_UINT32VALUE: return "UINT32VALUE"; case Descriptor::WELLKNOWNTYPE_UINT64VALUE: return "UINT64VALUE"; case Descriptor::WELLKNOWNTYPE_FLOATVALUE: return "FLOATVALUE"; case Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: return "DOUBLEVALUE"; case Descriptor::WELLKNOWNTYPE_BYTESVALUE: return "BYTESVALUE"; case Descriptor::WELLKNOWNTYPE_STRINGVALUE: return "STRINGVALUE"; case Descriptor::WELLKNOWNTYPE_ANY: return "ANY"; case Descriptor::WELLKNOWNTYPE_DURATION: return "DURATION"; case Descriptor::WELLKNOWNTYPE_TIMESTAMP: return "TIMESTAMP"; case Descriptor::WELLKNOWNTYPE_VALUE: return "VALUE"; case Descriptor::WELLKNOWNTYPE_LISTVALUE: return "LISTVALUE"; case Descriptor::WELLKNOWNTYPE_STRUCT: return "STRUCT"; case Descriptor::WELLKNOWNTYPE_FIELDMASK: return "FIELDMASK"; default: return "ERROR"; } } absl::Status CheckWellKnownType(absl::Nonnull<const Descriptor*> descriptor, Descriptor::WellKnownType well_known_type) { if (ABSL_PREDICT_FALSE(descriptor->well_known_type() != well_known_type)) { return absl::InvalidArgumentError(absl::StrCat( "expected message to be well known type: ", descriptor->full_name(), " ", WellKnownTypeToString(descriptor->well_known_type()))); } return absl::OkStatus(); } absl::Status CheckFieldWellKnownType( absl::Nonnull<const FieldDescriptor*> field, Descriptor::WellKnownType well_known_type) { ABSL_DCHECK_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_MESSAGE); if (ABSL_PREDICT_FALSE(field->message_type()->well_known_type() != well_known_type)) { return absl::InvalidArgumentError(absl::StrCat( "expected message field to be well known type for protocol buffer " "message well known type: ", field->full_name(), " ", WellKnownTypeToString(field->message_type()->well_known_type()))); } return absl::OkStatus(); } absl::Status CheckFieldOneof(absl::Nonnull<const FieldDescriptor*> field, absl::Nonnull<const OneofDescriptor*> oneof, int index) { if (ABSL_PREDICT_FALSE(field->containing_oneof() != oneof)) { return absl::InvalidArgumentError( absl::StrCat("expected field to be member of oneof for protocol buffer " "message well known type: ", field->full_name())); } if (ABSL_PREDICT_FALSE(field->index_in_oneof() != index)) { return absl::InvalidArgumentError(absl::StrCat( "expected field to have index in oneof of ", index, " for protocol buffer " "message well known type: ", field->full_name(), " oneof_index=", field->index_in_oneof())); } return absl::OkStatus(); } absl::Status CheckMapField(absl::Nonnull<const FieldDescriptor*> field) { if (ABSL_PREDICT_FALSE(!field->is_map())) { return absl::InvalidArgumentError( absl::StrCat("expected field to be map for protocol buffer " "message well known type: ", field->full_name())); } return absl::OkStatus(); } } bool StringValue::ConsumePrefix(absl::string_view prefix) { return absl::visit(absl::Overload( [&](absl::string_view& value) { return absl::ConsumePrefix(&value, prefix); }, [&](absl::Cord& cord) { if (cord.StartsWith(prefix)) { cord.RemovePrefix(prefix.size()); return true; } return false; }), AsVariant(*this)); } StringValue GetStringField(absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, std::string& scratch) { ABSL_DCHECK_EQ(reflection, message.GetReflection()); ABSL_DCHECK(!field->is_map() && !field->is_repeated()); ABSL_DCHECK_EQ(field->type(), FieldDescriptor::TYPE_STRING); ABSL_DCHECK_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_STRING); return GetStringField<StringValue>(reflection, message, field, field->cpp_string_type(), scratch); } BytesValue GetBytesField(absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, std::string& scratch) { ABSL_DCHECK_EQ(reflection, message.GetReflection()); ABSL_DCHECK(!field->is_map() && !field->is_repeated()); ABSL_DCHECK_EQ(field->type(), FieldDescriptor::TYPE_BYTES); ABSL_DCHECK_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_STRING); return GetStringField<BytesValue>(reflection, message, field, field->cpp_string_type(), scratch); } StringValue GetRepeatedStringField( absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, int index, std::string& scratch) { ABSL_DCHECK_EQ(reflection, message.GetReflection()); ABSL_DCHECK(!field->is_map() && field->is_repeated()); ABSL_DCHECK_EQ(field->type(), FieldDescriptor::TYPE_STRING); ABSL_DCHECK_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_STRING); return GetRepeatedStringField<StringValue>( reflection, message, field, field->cpp_string_type(), index, scratch); } BytesValue GetRepeatedBytesField( absl::Nonnull<const google::protobuf::Reflection*> reflection, const google::protobuf::Message& message, absl::Nonnull<const FieldDescriptor*> field, int index, std::string& scratch) { ABSL_DCHECK_EQ(reflection, message.GetReflection()); ABSL_DCHECK(!field->is_map() && field->is_repeated()); ABSL_DCHECK_EQ(field->type(), FieldDescriptor::TYPE_BYTES); ABSL_DCHECK_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_STRING); return GetRepeatedStringField<BytesValue>( reflection, message, field, field->cpp_string_type(), index, scratch); } absl::Status NullValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetEnumTypeByName(pool, "google.protobuf.NullValue")); return Initialize(descriptor); } absl::Status NullValueReflection::Initialize( absl::Nonnull<const EnumDescriptor*> descriptor) { if (descriptor_ != descriptor) { if (ABSL_PREDICT_FALSE(descriptor->full_name() != "google.protobuf.NullValue")) { return absl::InvalidArgumentError(absl::StrCat( "expected enum to be well known type: ", descriptor->full_name(), " google.protobuf.NullValue")); } descriptor_ = nullptr; value_ = descriptor->FindValueByNumber(0); if (ABSL_PREDICT_FALSE(value_ == nullptr)) { return absl::InvalidArgumentError( "well known protocol buffer enum missing value: " "google.protobuf.NullValue.NULL_VALUE"); } if (ABSL_PREDICT_FALSE(descriptor->value_count() != 1)) { std::vector<absl::string_view> values; values.reserve(static_cast<size_t>(descriptor->value_count())); for (int i = 0; i < descriptor->value_count(); ++i) { values.push_back(descriptor->value(i)->name()); } return absl::InvalidArgumentError( absl::StrCat("well known protocol buffer enum has multiple values: [", absl::StrJoin(values, ", "), "]")); } descriptor_ = descriptor; } return absl::OkStatus(); } absl::Status BoolValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.BoolValue")); return Initialize(descriptor); } absl::Status BoolValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_BOOL)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } bool BoolValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetBool(message, value_field_); } void BoolValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, bool value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetBool(message, value_field_, value); } absl::StatusOr<BoolValueReflection> GetBoolValueReflection( absl::Nonnull<const Descriptor*> descriptor) { BoolValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status Int32ValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Int32Value")); return Initialize(descriptor); } absl::Status Int32ValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_INT32)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } int32_t Int32ValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetInt32(message, value_field_); } void Int32ValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, int32_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetInt32(message, value_field_, value); } absl::StatusOr<Int32ValueReflection> GetInt32ValueReflection( absl::Nonnull<const Descriptor*> descriptor) { Int32ValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status Int64ValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Int64Value")); return Initialize(descriptor); } absl::Status Int64ValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_INT64)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } int64_t Int64ValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetInt64(message, value_field_); } void Int64ValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, int64_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetInt64(message, value_field_, value); } absl::StatusOr<Int64ValueReflection> GetInt64ValueReflection( absl::Nonnull<const Descriptor*> descriptor) { Int64ValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status UInt32ValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.UInt32Value")); return Initialize(descriptor); } absl::Status UInt32ValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_UINT32)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } uint32_t UInt32ValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetUInt32(message, value_field_); } void UInt32ValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, uint32_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetUInt32(message, value_field_, value); } absl::StatusOr<UInt32ValueReflection> GetUInt32ValueReflection( absl::Nonnull<const Descriptor*> descriptor) { UInt32ValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status UInt64ValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.UInt64Value")); return Initialize(descriptor); } absl::Status UInt64ValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_UINT64)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } uint64_t UInt64ValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetUInt64(message, value_field_); } void UInt64ValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, uint64_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetUInt64(message, value_field_, value); } absl::StatusOr<UInt64ValueReflection> GetUInt64ValueReflection( absl::Nonnull<const Descriptor*> descriptor) { UInt64ValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status FloatValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.FloatValue")); return Initialize(descriptor); } absl::Status FloatValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_FLOAT)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } float FloatValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetFloat(message, value_field_); } void FloatValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, float value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetFloat(message, value_field_, value); } absl::StatusOr<FloatValueReflection> GetFloatValueReflection( absl::Nonnull<const Descriptor*> descriptor) { FloatValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status DoubleValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.DoubleValue")); return Initialize(descriptor); } absl::Status DoubleValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(value_field_, FieldDescriptor::CPPTYPE_DOUBLE)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } double DoubleValueReflection::GetValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetDouble(message, value_field_); } void DoubleValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, double value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetDouble(message, value_field_, value); } absl::StatusOr<DoubleValueReflection> GetDoubleValueReflection( absl::Nonnull<const Descriptor*> descriptor) { DoubleValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status BytesValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.BytesValue")); return Initialize(descriptor); } absl::Status BytesValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldType(value_field_, FieldDescriptor::TYPE_BYTES)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); value_field_string_type_ = value_field_->cpp_string_type(); descriptor_ = descriptor; } return absl::OkStatus(); } BytesValue BytesValueReflection::GetValue(const google::protobuf::Message& message, std::string& scratch) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return GetStringField<BytesValue>(message, value_field_, value_field_string_type_, scratch); } void BytesValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, absl::string_view value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, value_field_, std::string(value)); } void BytesValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, const absl::Cord& value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, value_field_, value); } absl::StatusOr<BytesValueReflection> GetBytesValueReflection( absl::Nonnull<const Descriptor*> descriptor) { BytesValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status StringValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN( const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.StringValue")); return Initialize(descriptor); } absl::Status StringValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldType(value_field_, FieldDescriptor::TYPE_STRING)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); value_field_string_type_ = value_field_->cpp_string_type(); descriptor_ = descriptor; } return absl::OkStatus(); } StringValue StringValueReflection::GetValue(const google::protobuf::Message& message, std::string& scratch) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return GetStringField<StringValue>(message, value_field_, value_field_string_type_, scratch); } void StringValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, absl::string_view value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, value_field_, std::string(value)); } void StringValueReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, const absl::Cord& value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, value_field_, value); } absl::StatusOr<StringValueReflection> GetStringValueReflection( absl::Nonnull<const Descriptor*> descriptor) { StringValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status AnyReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Any")); return Initialize(descriptor); } absl::Status AnyReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(type_url_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldType(type_url_field_, FieldDescriptor::TYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(type_url_field_, FieldDescriptor::LABEL_OPTIONAL)); type_url_field_string_type_ = type_url_field_->cpp_string_type(); CEL_ASSIGN_OR_RETURN(value_field_, GetFieldByNumber(descriptor, 2)); CEL_RETURN_IF_ERROR( CheckFieldType(value_field_, FieldDescriptor::TYPE_BYTES)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(value_field_, FieldDescriptor::LABEL_OPTIONAL)); value_field_string_type_ = value_field_->cpp_string_type(); descriptor_ = descriptor; } return absl::OkStatus(); } void AnyReflection::SetTypeUrl(absl::Nonnull<google::protobuf::Message*> message, absl::string_view type_url) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, type_url_field_, std::string(type_url)); } void AnyReflection::SetValue(absl::Nonnull<google::protobuf::Message*> message, const absl::Cord& value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, value_field_, value); } StringValue AnyReflection::GetTypeUrl(const google::protobuf::Message& message, std::string& scratch) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return GetStringField<StringValue>(message, type_url_field_, type_url_field_string_type_, scratch); } BytesValue AnyReflection::GetValue(const google::protobuf::Message& message, std::string& scratch) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return GetStringField<BytesValue>(message, value_field_, value_field_string_type_, scratch); } absl::StatusOr<AnyReflection> GetAnyReflection( absl::Nonnull<const Descriptor*> descriptor) { AnyReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } AnyReflection GetAnyReflectionOrDie( absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { AnyReflection reflection; ABSL_CHECK_OK(reflection.Initialize(descriptor)); return reflection; } absl::Status DurationReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Duration")); return Initialize(descriptor); } absl::Status DurationReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(seconds_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(seconds_field_, FieldDescriptor::CPPTYPE_INT64)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(seconds_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_ASSIGN_OR_RETURN(nanos_field_, GetFieldByNumber(descriptor, 2)); CEL_RETURN_IF_ERROR( CheckFieldCppType(nanos_field_, FieldDescriptor::CPPTYPE_INT32)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(nanos_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } int64_t DurationReflection::GetSeconds(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetInt64(message, seconds_field_); } int32_t DurationReflection::GetNanos(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetInt32(message, nanos_field_); } void DurationReflection::SetSeconds(absl::Nonnull<google::protobuf::Message*> message, int64_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetInt64(message, seconds_field_, value); } void DurationReflection::SetNanos(absl::Nonnull<google::protobuf::Message*> message, int32_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetInt32(message, nanos_field_, value); } absl::StatusOr<absl::Duration> DurationReflection::ToAbslDuration( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); int64_t seconds = GetSeconds(message); if (ABSL_PREDICT_FALSE(seconds < TimeUtil::kDurationMinSeconds || seconds > TimeUtil::kDurationMaxSeconds)) { return absl::InvalidArgumentError( absl::StrCat("invalid duration seconds: ", seconds)); } int32_t nanos = GetNanos(message); if (ABSL_PREDICT_FALSE(nanos < TimeUtil::kDurationMinNanoseconds || nanos > TimeUtil::kDurationMaxNanoseconds)) { return absl::InvalidArgumentError( absl::StrCat("invalid duration nanoseconds: ", nanos)); } if ((seconds < 0 && nanos > 0) || (seconds > 0 && nanos < 0)) { return absl::InvalidArgumentError(absl::StrCat( "duration sign mismatch: seconds=", seconds, ", nanoseconds=", nanos)); } return absl::Seconds(seconds) + absl::Nanoseconds(nanos); } absl::StatusOr<DurationReflection> GetDurationReflection( absl::Nonnull<const Descriptor*> descriptor) { DurationReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status TimestampReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Timestamp")); return Initialize(descriptor); } absl::Status TimestampReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(seconds_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(seconds_field_, FieldDescriptor::CPPTYPE_INT64)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(seconds_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_ASSIGN_OR_RETURN(nanos_field_, GetFieldByNumber(descriptor, 2)); CEL_RETURN_IF_ERROR( CheckFieldCppType(nanos_field_, FieldDescriptor::CPPTYPE_INT32)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(nanos_field_, FieldDescriptor::LABEL_OPTIONAL)); descriptor_ = descriptor; } return absl::OkStatus(); } int64_t TimestampReflection::GetSeconds(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetInt64(message, seconds_field_); } int32_t TimestampReflection::GetNanos(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetInt32(message, nanos_field_); } void TimestampReflection::SetSeconds(absl::Nonnull<google::protobuf::Message*> message, int64_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetInt64(message, seconds_field_, value); } void TimestampReflection::SetNanos(absl::Nonnull<google::protobuf::Message*> message, int32_t value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetInt32(message, nanos_field_, value); } absl::StatusOr<absl::Time> TimestampReflection::ToAbslTime( const google::protobuf::Message& message) const { int64_t seconds = GetSeconds(message); if (ABSL_PREDICT_FALSE(seconds < TimeUtil::kTimestampMinSeconds || seconds > TimeUtil::kTimestampMaxSeconds)) { return absl::InvalidArgumentError( absl::StrCat("invalid timestamp seconds: ", seconds)); } int32_t nanos = GetNanos(message); if (ABSL_PREDICT_FALSE(nanos < TimeUtil::kTimestampMinNanoseconds || nanos > TimeUtil::kTimestampMaxNanoseconds)) { return absl::InvalidArgumentError( absl::StrCat("invalid timestamp nanoseconds: ", nanos)); } return absl::UnixEpoch() + absl::Seconds(seconds) + absl::Nanoseconds(nanos); } absl::StatusOr<TimestampReflection> GetTimestampReflection( absl::Nonnull<const Descriptor*> descriptor) { TimestampReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } void ValueReflection::SetNumberValue( absl::Nonnull<google::protobuf::Value*> message, int64_t value) { if (value < kJsonMinInt || value > kJsonMaxInt) { SetStringValue(message, absl::StrCat(value)); return; } SetNumberValue(message, static_cast<double>(value)); } void ValueReflection::SetNumberValue( absl::Nonnull<google::protobuf::Value*> message, uint64_t value) { if (value > kJsonMaxUint) { SetStringValue(message, absl::StrCat(value)); return; } SetNumberValue(message, static_cast<double>(value)); } absl::Status ValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Value")); return Initialize(descriptor); } absl::Status ValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(kind_field_, GetOneofByName(descriptor, "kind")); CEL_ASSIGN_OR_RETURN(null_value_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(null_value_field_, FieldDescriptor::CPPTYPE_ENUM)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(null_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldOneof(null_value_field_, kind_field_, 0)); CEL_ASSIGN_OR_RETURN(bool_value_field_, GetFieldByNumber(descriptor, 4)); CEL_RETURN_IF_ERROR( CheckFieldCppType(bool_value_field_, FieldDescriptor::CPPTYPE_BOOL)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(bool_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldOneof(bool_value_field_, kind_field_, 3)); CEL_ASSIGN_OR_RETURN(number_value_field_, GetFieldByNumber(descriptor, 2)); CEL_RETURN_IF_ERROR(CheckFieldCppType(number_value_field_, FieldDescriptor::CPPTYPE_DOUBLE)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(number_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldOneof(number_value_field_, kind_field_, 1)); CEL_ASSIGN_OR_RETURN(string_value_field_, GetFieldByNumber(descriptor, 3)); CEL_RETURN_IF_ERROR(CheckFieldCppType(string_value_field_, FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(string_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldOneof(string_value_field_, kind_field_, 2)); string_value_field_string_type_ = string_value_field_->cpp_string_type(); CEL_ASSIGN_OR_RETURN(list_value_field_, GetFieldByNumber(descriptor, 6)); CEL_RETURN_IF_ERROR( CheckFieldCppType(list_value_field_, FieldDescriptor::CPPTYPE_MESSAGE)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(list_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldOneof(list_value_field_, kind_field_, 5)); CEL_RETURN_IF_ERROR(CheckFieldWellKnownType( list_value_field_, Descriptor::WELLKNOWNTYPE_LISTVALUE)); CEL_ASSIGN_OR_RETURN(struct_value_field_, GetFieldByNumber(descriptor, 5)); CEL_RETURN_IF_ERROR(CheckFieldCppType(struct_value_field_, FieldDescriptor::CPPTYPE_MESSAGE)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(struct_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldOneof(struct_value_field_, kind_field_, 4)); CEL_RETURN_IF_ERROR(CheckFieldWellKnownType( struct_value_field_, Descriptor::WELLKNOWNTYPE_STRUCT)); descriptor_ = descriptor; } return absl::OkStatus(); } google::protobuf::Value::KindCase ValueReflection::GetKindCase( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); const auto* field = message.GetReflection()->GetOneofFieldDescriptor(message, kind_field_); return field != nullptr ? static_cast<google::protobuf::Value::KindCase>( field->index_in_oneof() + 1) : google::protobuf::Value::KIND_NOT_SET; } bool ValueReflection::GetBoolValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetBool(message, bool_value_field_); } double ValueReflection::GetNumberValue(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetDouble(message, number_value_field_); } StringValue ValueReflection::GetStringValue(const google::protobuf::Message& message, std::string& scratch) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return GetStringField<StringValue>(message, string_value_field_, string_value_field_string_type_, scratch); } const google::protobuf::Message& ValueReflection::GetListValue( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetMessage(message, list_value_field_); } const google::protobuf::Message& ValueReflection::GetStructValue( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetMessage(message, struct_value_field_); } void ValueReflection::SetNullValue( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetEnumValue(message, null_value_field_, 0); } void ValueReflection::SetBoolValue(absl::Nonnull<google::protobuf::Message*> message, bool value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetBool(message, bool_value_field_, value); } void ValueReflection::SetNumberValue(absl::Nonnull<google::protobuf::Message*> message, int64_t value) const { if (value < kJsonMinInt || value > kJsonMaxInt) { SetStringValue(message, absl::StrCat(value)); return; } SetNumberValue(message, static_cast<double>(value)); } void ValueReflection::SetNumberValue(absl::Nonnull<google::protobuf::Message*> message, uint64_t value) const { if (value > kJsonMaxUint) { SetStringValue(message, absl::StrCat(value)); return; } SetNumberValue(message, static_cast<double>(value)); } void ValueReflection::SetNumberValue(absl::Nonnull<google::protobuf::Message*> message, double value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetDouble(message, number_value_field_, value); } void ValueReflection::SetStringValue(absl::Nonnull<google::protobuf::Message*> message, absl::string_view value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, string_value_field_, std::string(value)); } void ValueReflection::SetStringValue(absl::Nonnull<google::protobuf::Message*> message, const absl::Cord& value) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); message->GetReflection()->SetString(message, string_value_field_, value); } absl::Nonnull<google::protobuf::Message*> ValueReflection::MutableListValue( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); return message->GetReflection()->MutableMessage(message, list_value_field_); } absl::Nonnull<google::protobuf::Message*> ValueReflection::MutableStructValue( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); return message->GetReflection()->MutableMessage(message, struct_value_field_); } Unique<google::protobuf::Message> ValueReflection::ReleaseListValue( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); const auto* reflection = message->GetReflection(); if (!reflection->HasField(*message, list_value_field_)) { reflection->MutableMessage(message, list_value_field_); } return WrapUnique( reflection->UnsafeArenaReleaseMessage(message, list_value_field_), message->GetArena()); } Unique<google::protobuf::Message> ValueReflection::ReleaseStructValue( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); const auto* reflection = message->GetReflection(); if (!reflection->HasField(*message, struct_value_field_)) { reflection->MutableMessage(message, struct_value_field_); } return WrapUnique( reflection->UnsafeArenaReleaseMessage(message, struct_value_field_), message->GetArena()); } absl::StatusOr<ValueReflection> GetValueReflection( absl::Nonnull<const Descriptor*> descriptor) { ValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } ValueReflection GetValueReflectionOrDie( absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { ValueReflection reflection; ABSL_CHECK_OK(reflection.Initialize(descriptor)); return reflection; } absl::Status ListValueReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.ListValue")); return Initialize(descriptor); } absl::Status ListValueReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(values_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(values_field_, FieldDescriptor::CPPTYPE_MESSAGE)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(values_field_, FieldDescriptor::LABEL_REPEATED)); CEL_RETURN_IF_ERROR(CheckFieldWellKnownType( values_field_, Descriptor::WELLKNOWNTYPE_VALUE)); descriptor_ = descriptor; } return absl::OkStatus(); } int ListValueReflection::ValuesSize(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->FieldSize(message, values_field_); } google::protobuf::RepeatedFieldRef<google::protobuf::Message> ListValueReflection::Values( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetRepeatedFieldRef<google::protobuf::Message>( message, values_field_); } const google::protobuf::Message& ListValueReflection::Values( const google::protobuf::Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND, int index) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->GetRepeatedMessage(message, values_field_, index); } google::protobuf::MutableRepeatedFieldRef<google::protobuf::Message> ListValueReflection::MutableValues( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); return message->GetReflection()->GetMutableRepeatedFieldRef<google::protobuf::Message>( message, values_field_); } absl::Nonnull<google::protobuf::Message*> ListValueReflection::AddValues( absl::Nonnull<google::protobuf::Message*> message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); return message->GetReflection()->AddMessage(message, values_field_); } void ListValueReflection::ReserveValues(absl::Nonnull<google::protobuf::Message*> message, int capacity) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); if (capacity > 0) { MutableValues(message).Reserve(capacity); } } absl::StatusOr<ListValueReflection> GetListValueReflection( absl::Nonnull<const Descriptor*> descriptor) { ListValueReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } ListValueReflection GetListValueReflectionOrDie( absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { ListValueReflection reflection; ABSL_CHECK_OK(reflection.Initialize(descriptor)); return reflection; } absl::Status StructReflection::Initialize( absl::Nonnull<const DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.Struct")); return Initialize(descriptor); } absl::Status StructReflection::Initialize( absl::Nonnull<const Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(fields_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR(CheckMapField(fields_field_)); fields_key_field_ = fields_field_->message_type()->map_key(); CEL_RETURN_IF_ERROR( CheckFieldCppType(fields_key_field_, FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(fields_key_field_, FieldDescriptor::LABEL_OPTIONAL)); fields_value_field_ = fields_field_->message_type()->map_value(); CEL_RETURN_IF_ERROR(CheckFieldCppType(fields_value_field_, FieldDescriptor::CPPTYPE_MESSAGE)); CEL_RETURN_IF_ERROR(CheckFieldCardinality(fields_value_field_, FieldDescriptor::LABEL_OPTIONAL)); CEL_RETURN_IF_ERROR(CheckFieldWellKnownType( fields_value_field_, Descriptor::WELLKNOWNTYPE_VALUE)); descriptor_ = descriptor; } return absl::OkStatus(); } int StructReflection::FieldsSize(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return cel::extensions::protobuf_internal::MapSize(*message.GetReflection(), message, *fields_field_); } google::protobuf::MapIterator StructReflection::BeginFields( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return cel::extensions::protobuf_internal::MapBegin(*message.GetReflection(), message, *fields_field_); } google::protobuf::MapIterator StructReflection::EndFields( const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return cel::extensions::protobuf_internal::MapEnd(*message.GetReflection(), message, *fields_field_); } bool StructReflection::ContainsField(const google::protobuf::Message& message, absl::string_view name) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); std::string key_scratch(name); google::protobuf::MapKey key; key.SetStringValue(key_scratch); return cel::extensions::protobuf_internal::ContainsMapKey( *message.GetReflection(), message, *fields_field_, key); } absl::Nullable<const google::protobuf::Message*> StructReflection::FindField( const google::protobuf::Message& message, absl::string_view name) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); std::string key_scratch(name); google::protobuf::MapKey key; key.SetStringValue(key_scratch); google::protobuf::MapValueConstRef value; if (cel::extensions::protobuf_internal::LookupMapValue( *message.GetReflection(), message, *fields_field_, key, &value)) { return &value.GetMessageValue(); } return nullptr; } absl::Nonnull<google::protobuf::Message*> StructReflection::InsertField( absl::Nonnull<google::protobuf::Message*> message, absl::string_view name) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); std::string key_scratch(name); google::protobuf::MapKey key; key.SetStringValue(key_scratch); google::protobuf::MapValueRef value; cel::extensions::protobuf_internal::InsertOrLookupMapValue( *message->GetReflection(), message, *fields_field_, key, &value); return value.MutableMessageValue(); } bool StructReflection::DeleteField(absl::Nonnull<google::protobuf::Message*> message, absl::string_view name) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message->GetDescriptor(), descriptor_); std::string key_scratch(name); google::protobuf::MapKey key; key.SetStringValue(key_scratch); return cel::extensions::protobuf_internal::DeleteMapValue( message->GetReflection(), message, fields_field_, key); } absl::StatusOr<StructReflection> GetStructReflection( absl::Nonnull<const Descriptor*> descriptor) { StructReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } StructReflection GetStructReflectionOrDie( absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { StructReflection reflection; ABSL_CHECK_OK(reflection.Initialize(descriptor)); return reflection; } absl::Status FieldMaskReflection::Initialize( absl::Nonnull<const google::protobuf::DescriptorPool*> pool) { CEL_ASSIGN_OR_RETURN(const auto* descriptor, GetMessageTypeByName(pool, "google.protobuf.FieldMask")); return Initialize(descriptor); } absl::Status FieldMaskReflection::Initialize( absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { if (descriptor_ != descriptor) { CEL_RETURN_IF_ERROR(CheckWellKnownType(descriptor, kWellKnownType)); descriptor_ = nullptr; CEL_ASSIGN_OR_RETURN(paths_field_, GetFieldByNumber(descriptor, 1)); CEL_RETURN_IF_ERROR( CheckFieldCppType(paths_field_, FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR( CheckFieldCardinality(paths_field_, FieldDescriptor::LABEL_REPEATED)); paths_field_string_type_ = paths_field_->cpp_string_type(); descriptor_ = descriptor; } return absl::OkStatus(); } int FieldMaskReflection::PathsSize(const google::protobuf::Message& message) const { ABSL_DCHECK(IsInitialized()); ABSL_DCHECK_EQ(message.GetDescriptor(), descriptor_); return message.GetReflection()->FieldSize(message, paths_field_); } StringValue FieldMaskReflection::Paths(const google::protobuf::Message& message, int index, std::string& scratch) const { return GetRepeatedStringField<StringValue>( message, paths_field_, paths_field_string_type_, index, scratch); } absl::StatusOr<FieldMaskReflection> GetFieldMaskReflection( absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { FieldMaskReflection reflection; CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); return reflection; } absl::Status Reflection::Initialize(absl::Nonnull<const DescriptorPool*> pool) { CEL_RETURN_IF_ERROR(NullValue().Initialize(pool)); CEL_RETURN_IF_ERROR(BoolValue().Initialize(pool)); CEL_RETURN_IF_ERROR(Int32Value().Initialize(pool)); CEL_RETURN_IF_ERROR(Int64Value().Initialize(pool)); CEL_RETURN_IF_ERROR(UInt32Value().Initialize(pool)); CEL_RETURN_IF_ERROR(UInt64Value().Initialize(pool)); CEL_RETURN_IF_ERROR(FloatValue().Initialize(pool)); CEL_RETURN_IF_ERROR(DoubleValue().Initialize(pool)); CEL_RETURN_IF_ERROR(BytesValue().Initialize(pool)); CEL_RETURN_IF_ERROR(StringValue().Initialize(pool)); CEL_RETURN_IF_ERROR(Any().Initialize(pool)); CEL_RETURN_IF_ERROR(Duration().Initialize(pool)); CEL_RETURN_IF_ERROR(Timestamp().Initialize(pool)); CEL_RETURN_IF_ERROR(Value().Initialize(pool)); CEL_RETURN_IF_ERROR(ListValue().Initialize(pool)); CEL_RETURN_IF_ERROR(Struct().Initialize(pool)); if (const auto* descriptor = pool->FindMessageTypeByName("google.protobuf.FieldMask"); descriptor != nullptr) { CEL_RETURN_IF_ERROR(FieldMask().Initialize(descriptor)); } return absl::OkStatus(); } namespace { absl::StatusOr<ListValue> AdaptListValue(absl::Nullable<google::protobuf::Arena*> arena, const google::protobuf::Message& message, Unique<google::protobuf::Message> adapted) { ABSL_DCHECK(!adapted || &message == cel::to_address(adapted)); const auto* descriptor = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InvalidArgumentError( absl::StrCat("missing descriptor for protocol buffer message: ", message.GetTypeName())); } CEL_RETURN_IF_ERROR(GetListValueReflection(descriptor).status()); if (adapted) { return ListValue(std::move(adapted)); } return ListValue(std::cref(message)); } absl::StatusOr<Struct> AdaptStruct(absl::Nullable<google::protobuf::Arena*> arena, const google::protobuf::Message& message, Unique<google::protobuf::Message> adapted) { ABSL_DCHECK(!adapted || &message == cel::to_address(adapted)); const auto* descriptor = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InvalidArgumentError( absl::StrCat("missing descriptor for protocol buffer message: ", message.GetTypeName())); } CEL_RETURN_IF_ERROR(GetStructReflection(descriptor).status()); if (adapted) { return Struct(std::move(adapted)); } return Struct(std::cref(message)); } absl::StatusOr<Unique<google::protobuf::Message>> AdaptAny( absl::Nullable<google::protobuf::Arena*> arena, AnyReflection& reflection, const google::protobuf::Message& message, absl::Nonnull<const Descriptor*> descriptor, absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, bool error_if_unresolveable) { ABSL_DCHECK_EQ(descriptor->well_known_type(), Descriptor::WELLKNOWNTYPE_ANY); absl::Nonnull<const google::protobuf::Message*> to_unwrap = &message; Unique<google::protobuf::Message> unwrapped; std::string type_url_scratch; std::string value_scratch; do { CEL_RETURN_IF_ERROR(reflection.Initialize(descriptor)); StringValue type_url = reflection.GetTypeUrl(*to_unwrap, type_url_scratch); absl::string_view type_url_view = FlatStringValue(type_url, type_url_scratch); if (!absl::ConsumePrefix(&type_url_view, "type.googleapis.com/") && !absl::ConsumePrefix(&type_url_view, "type.googleprod.com/")) { if (!error_if_unresolveable) { break; } return absl::InvalidArgumentError(absl::StrCat( "unable to find descriptor for type URL: ", type_url_view)); } const auto* packed_descriptor = pool->FindMessageTypeByName(type_url_view); if (packed_descriptor == nullptr) { if (!error_if_unresolveable) { break; } return absl::InvalidArgumentError(absl::StrCat( "unable to find descriptor for type name: ", type_url_view)); } const auto* prototype = factory->GetPrototype(packed_descriptor); if (prototype == nullptr) { return absl::InvalidArgumentError(absl::StrCat( "unable to build prototype for type name: ", type_url_view)); } BytesValue value = reflection.GetValue(*to_unwrap, value_scratch); Unique<google::protobuf::Message> unpacked = WrapUnique(prototype->New(arena), arena); const bool ok = absl::visit(absl::Overload( [&](absl::string_view string) -> bool { return unpacked->ParseFromString(string); }, [&](const absl::Cord& cord) -> bool { return unpacked->ParseFromCord(cord); }), AsVariant(value)); if (!ok) { return absl::InvalidArgumentError(absl::StrCat( "failed to unpack protocol buffer message: ", type_url_view)); } unwrapped = std::move(unpacked); to_unwrap = cel::to_address(unwrapped); descriptor = to_unwrap->GetDescriptor(); if (descriptor == nullptr) { return absl::InvalidArgumentError( absl::StrCat("missing descriptor for protocol buffer message: ", to_unwrap->GetTypeName())); } } while (descriptor->well_known_type() == Descriptor::WELLKNOWNTYPE_ANY); return unwrapped; } } absl::StatusOr<Unique<google::protobuf::Message>> UnpackAnyFrom( absl::Nullable<google::protobuf::Arena*> arena, AnyReflection& reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory) { ABSL_DCHECK_EQ(message.GetDescriptor()->well_known_type(), Descriptor::WELLKNOWNTYPE_ANY); return AdaptAny(arena, reflection, message, message.GetDescriptor(), pool, factory, true); } absl::StatusOr<Unique<google::protobuf::Message>> UnpackAnyIfResolveable( absl::Nullable<google::protobuf::Arena*> arena, AnyReflection& reflection, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory) { ABSL_DCHECK_EQ(message.GetDescriptor()->well_known_type(), Descriptor::WELLKNOWNTYPE_ANY); return AdaptAny(arena, reflection, message, message.GetDescriptor(), pool, factory, false); } absl::StatusOr<well_known_types::Value> AdaptFromMessage( absl::Nullable<google::protobuf::Arena*> arena, const google::protobuf::Message& message, absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, std::string& scratch) { const auto* descriptor = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(descriptor == nullptr)) { return absl::InvalidArgumentError( absl::StrCat("missing descriptor for protocol buffer message: ", message.GetTypeName())); } absl::Nonnull<const google::protobuf::Message*> to_adapt; Unique<google::protobuf::Message> adapted; Descriptor::WellKnownType well_known_type = descriptor->well_known_type(); if (well_known_type == Descriptor::WELLKNOWNTYPE_ANY) { AnyReflection reflection; CEL_ASSIGN_OR_RETURN( adapted, UnpackAnyFrom(arena, reflection, message, pool, factory)); to_adapt = cel::to_address(adapted); descriptor = to_adapt->GetDescriptor(); well_known_type = descriptor->well_known_type(); } else { to_adapt = &message; } switch (descriptor->well_known_type()) { case Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetDoubleValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_FLOATVALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetFloatValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_INT64VALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetInt64ValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_UINT64VALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetUInt64ValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_INT32VALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetInt32ValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_UINT32VALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetUInt32ValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_STRINGVALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetStringValueReflection(descriptor)); auto value = reflection.GetValue(*to_adapt, scratch); if (adapted) { value = CopyStringValue(value, scratch); } return value; } case Descriptor::WELLKNOWNTYPE_BYTESVALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetBytesValueReflection(descriptor)); auto value = reflection.GetValue(*to_adapt, scratch); if (adapted) { value = CopyBytesValue(value, scratch); } return value; } case Descriptor::WELLKNOWNTYPE_BOOLVALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetBoolValueReflection(descriptor)); return reflection.GetValue(*to_adapt); } case Descriptor::WELLKNOWNTYPE_ANY: ABSL_UNREACHABLE(); case Descriptor::WELLKNOWNTYPE_DURATION: { CEL_ASSIGN_OR_RETURN(auto reflection, GetDurationReflection(descriptor)); return reflection.ToAbslDuration(*to_adapt); } case Descriptor::WELLKNOWNTYPE_TIMESTAMP: { CEL_ASSIGN_OR_RETURN(auto reflection, GetTimestampReflection(descriptor)); return reflection.ToAbslTime(*to_adapt); } case Descriptor::WELLKNOWNTYPE_VALUE: { CEL_ASSIGN_OR_RETURN(auto reflection, GetValueReflection(descriptor)); const auto kind_case = reflection.GetKindCase(*to_adapt); switch (kind_case) { case google::protobuf::Value::KIND_NOT_SET: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Value::kNullValue: return nullptr; case google::protobuf::Value::kNumberValue: return reflection.GetNumberValue(*to_adapt); case google::protobuf::Value::kStringValue: { auto value = reflection.GetStringValue(*to_adapt, scratch); if (adapted) { value = CopyStringValue(value, scratch); } return value; } case google::protobuf::Value::kBoolValue: return reflection.GetBoolValue(*to_adapt); case google::protobuf::Value::kStructValue: { if (adapted) { adapted = reflection.ReleaseStructValue(cel::to_address(adapted)); to_adapt = cel::to_address(adapted); } else { to_adapt = &reflection.GetStructValue(*to_adapt); } return AdaptStruct(arena, *to_adapt, std::move(adapted)); } case google::protobuf::Value::kListValue: { if (adapted) { adapted = reflection.ReleaseListValue(cel::to_address(adapted)); to_adapt = cel::to_address(adapted); } else { to_adapt = &reflection.GetListValue(*to_adapt); } return AdaptListValue(arena, *to_adapt, std::move(adapted)); } default: return absl::InvalidArgumentError( absl::StrCat("unexpected value kind case: ", kind_case)); } } case Descriptor::WELLKNOWNTYPE_LISTVALUE: return AdaptListValue(arena, *to_adapt, std::move(adapted)); case Descriptor::WELLKNOWNTYPE_STRUCT: return AdaptStruct(arena, *to_adapt, std::move(adapted)); default: if (adapted) { return adapted; } return absl::monostate{}; } } }
#include "internal/well_known_types.h" #include <cstddef> #include <cstdint> #include <string> #include "google/protobuf/any.pb.h" #include "google/protobuf/duration.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 "google/protobuf/descriptor.pb.h" #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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/variant.h" #include "common/memory.h" #include "internal/message_type_name.h" #include "internal/minimal_descriptor_pool.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel::well_known_types { namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::internal::GetMinimalDescriptorPool; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::_; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::NotNull; using ::testing::Test; using ::testing::VariantWith; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ReflectionTest : public Test { public: absl::Nonnull<google::protobuf::Arena*> arena() ABSL_ATTRIBUTE_LIFETIME_BOUND { return &arena_; } std::string& scratch_space() ABSL_ATTRIBUTE_LIFETIME_BOUND { return scratch_space_; } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } template <typename T> absl::Nonnull<T*> MakeGenerated() { return google::protobuf::Arena::Create<T>(arena()); } template <typename T> absl::Nonnull<google::protobuf::Message*> MakeDynamic() { const auto* descriptor = ABSL_DIE_IF_NULL(descriptor_pool()->FindMessageTypeByName( internal::MessageTypeNameFor<T>())); const auto* prototype = ABSL_DIE_IF_NULL(message_factory()->GetPrototype(descriptor)); return prototype->New(arena()); } private: google::protobuf::Arena arena_; std::string scratch_space_; }; TEST_F(ReflectionTest, MinimalDescriptorPool) { EXPECT_THAT(Reflection().Initialize(GetMinimalDescriptorPool()), IsOk()); } TEST_F(ReflectionTest, TestingDescriptorPool) { EXPECT_THAT(Reflection().Initialize(GetTestingDescriptorPool()), IsOk()); } TEST_F(ReflectionTest, BoolValue_Generated) { auto* value = MakeGenerated<google::protobuf::BoolValue>(); EXPECT_EQ(BoolValueReflection::GetValue(*value), false); BoolValueReflection::SetValue(value, true); EXPECT_EQ(BoolValueReflection::GetValue(*value), true); } TEST_F(ReflectionTest, BoolValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::BoolValue>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetBoolValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), false); reflection.SetValue(value, true); EXPECT_EQ(reflection.GetValue(*value), true); } TEST_F(ReflectionTest, Int32Value_Generated) { auto* value = MakeGenerated<google::protobuf::Int32Value>(); EXPECT_EQ(Int32ValueReflection::GetValue(*value), 0); Int32ValueReflection::SetValue(value, 1); EXPECT_EQ(Int32ValueReflection::GetValue(*value), 1); } TEST_F(ReflectionTest, Int32Value_Dynamic) { auto* value = MakeDynamic<google::protobuf::Int32Value>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetInt32ValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), 0); reflection.SetValue(value, 1); EXPECT_EQ(reflection.GetValue(*value), 1); } TEST_F(ReflectionTest, Int64Value_Generated) { auto* value = MakeGenerated<google::protobuf::Int64Value>(); EXPECT_EQ(Int64ValueReflection::GetValue(*value), 0); Int64ValueReflection::SetValue(value, 1); EXPECT_EQ(Int64ValueReflection::GetValue(*value), 1); } TEST_F(ReflectionTest, Int64Value_Dynamic) { auto* value = MakeDynamic<google::protobuf::Int64Value>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetInt64ValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), 0); reflection.SetValue(value, 1); EXPECT_EQ(reflection.GetValue(*value), 1); } TEST_F(ReflectionTest, UInt32Value_Generated) { auto* value = MakeGenerated<google::protobuf::UInt32Value>(); EXPECT_EQ(UInt32ValueReflection::GetValue(*value), 0); UInt32ValueReflection::SetValue(value, 1); EXPECT_EQ(UInt32ValueReflection::GetValue(*value), 1); } TEST_F(ReflectionTest, UInt32Value_Dynamic) { auto* value = MakeDynamic<google::protobuf::UInt32Value>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetUInt32ValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), 0); reflection.SetValue(value, 1); EXPECT_EQ(reflection.GetValue(*value), 1); } TEST_F(ReflectionTest, UInt64Value_Generated) { auto* value = MakeGenerated<google::protobuf::UInt64Value>(); EXPECT_EQ(UInt64ValueReflection::GetValue(*value), 0); UInt64ValueReflection::SetValue(value, 1); EXPECT_EQ(UInt64ValueReflection::GetValue(*value), 1); } TEST_F(ReflectionTest, UInt64Value_Dynamic) { auto* value = MakeDynamic<google::protobuf::UInt64Value>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetUInt64ValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), 0); reflection.SetValue(value, 1); EXPECT_EQ(reflection.GetValue(*value), 1); } TEST_F(ReflectionTest, FloatValue_Generated) { auto* value = MakeGenerated<google::protobuf::FloatValue>(); EXPECT_EQ(FloatValueReflection::GetValue(*value), 0); FloatValueReflection::SetValue(value, 1); EXPECT_EQ(FloatValueReflection::GetValue(*value), 1); } TEST_F(ReflectionTest, FloatValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::FloatValue>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetFloatValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), 0); reflection.SetValue(value, 1); EXPECT_EQ(reflection.GetValue(*value), 1); } TEST_F(ReflectionTest, DoubleValue_Generated) { auto* value = MakeGenerated<google::protobuf::DoubleValue>(); EXPECT_EQ(DoubleValueReflection::GetValue(*value), 0); DoubleValueReflection::SetValue(value, 1); EXPECT_EQ(DoubleValueReflection::GetValue(*value), 1); } TEST_F(ReflectionTest, DoubleValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::DoubleValue>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetDoubleValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value), 0); reflection.SetValue(value, 1); EXPECT_EQ(reflection.GetValue(*value), 1); } TEST_F(ReflectionTest, BytesValue_Generated) { auto* value = MakeGenerated<google::protobuf::BytesValue>(); EXPECT_EQ(BytesValueReflection::GetValue(*value), ""); BytesValueReflection::SetValue(value, absl::Cord("Hello World!")); EXPECT_EQ(BytesValueReflection::GetValue(*value), "Hello World!"); } TEST_F(ReflectionTest, BytesValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::BytesValue>(); std::string scratch; ASSERT_OK_AND_ASSIGN( auto reflection, GetBytesValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value, scratch), ""); reflection.SetValue(value, "Hello World!"); EXPECT_EQ(reflection.GetValue(*value, scratch), "Hello World!"); reflection.SetValue(value, absl::Cord()); EXPECT_EQ(reflection.GetValue(*value, scratch), ""); } TEST_F(ReflectionTest, StringValue_Generated) { auto* value = MakeGenerated<google::protobuf::StringValue>(); EXPECT_EQ(StringValueReflection::GetValue(*value), ""); StringValueReflection::SetValue(value, "Hello World!"); EXPECT_EQ(StringValueReflection::GetValue(*value), "Hello World!"); } TEST_F(ReflectionTest, StringValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::StringValue>(); std::string scratch; ASSERT_OK_AND_ASSIGN( auto reflection, GetStringValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetValue(*value, scratch), ""); reflection.SetValue(value, "Hello World!"); EXPECT_EQ(reflection.GetValue(*value, scratch), "Hello World!"); reflection.SetValue(value, absl::Cord()); EXPECT_EQ(reflection.GetValue(*value, scratch), ""); } TEST_F(ReflectionTest, Any_Generated) { auto* value = MakeGenerated<google::protobuf::Any>(); EXPECT_EQ(AnyReflection::GetTypeUrl(*value), ""); AnyReflection::SetTypeUrl(value, "Hello World!"); EXPECT_EQ(AnyReflection::GetTypeUrl(*value), "Hello World!"); EXPECT_EQ(AnyReflection::GetValue(*value), ""); AnyReflection::SetValue(value, absl::Cord("Hello World!")); EXPECT_EQ(AnyReflection::GetValue(*value), "Hello World!"); } TEST_F(ReflectionTest, Any_Dynamic) { auto* value = MakeDynamic<google::protobuf::Any>(); std::string scratch; ASSERT_OK_AND_ASSIGN( auto reflection, GetAnyReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetTypeUrl(*value, scratch), ""); reflection.SetTypeUrl(value, "Hello World!"); EXPECT_EQ(reflection.GetTypeUrl(*value, scratch), "Hello World!"); EXPECT_EQ(reflection.GetValue(*value, scratch), ""); reflection.SetValue(value, absl::Cord("Hello World!")); EXPECT_EQ(reflection.GetValue(*value, scratch), "Hello World!"); } TEST_F(ReflectionTest, Duration_Generated) { auto* value = MakeGenerated<google::protobuf::Duration>(); EXPECT_EQ(DurationReflection::GetSeconds(*value), 0); DurationReflection::SetSeconds(value, 1); EXPECT_EQ(DurationReflection::GetSeconds(*value), 1); EXPECT_EQ(DurationReflection::GetNanos(*value), 0); DurationReflection::SetNanos(value, 1); EXPECT_EQ(DurationReflection::GetNanos(*value), 1); } TEST_F(ReflectionTest, Duration_Dynamic) { auto* value = MakeDynamic<google::protobuf::Duration>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetDurationReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetSeconds(*value), 0); reflection.SetSeconds(value, 1); EXPECT_EQ(reflection.GetSeconds(*value), 1); EXPECT_EQ(reflection.GetNanos(*value), 0); reflection.SetNanos(value, 1); EXPECT_EQ(reflection.GetNanos(*value), 1); } TEST_F(ReflectionTest, Timestamp_Generated) { auto* value = MakeGenerated<google::protobuf::Timestamp>(); EXPECT_EQ(TimestampReflection::GetSeconds(*value), 0); TimestampReflection::SetSeconds(value, 1); EXPECT_EQ(TimestampReflection::GetSeconds(*value), 1); EXPECT_EQ(TimestampReflection::GetNanos(*value), 0); TimestampReflection::SetNanos(value, 1); EXPECT_EQ(TimestampReflection::GetNanos(*value), 1); } TEST_F(ReflectionTest, Timestamp_Dynamic) { auto* value = MakeDynamic<google::protobuf::Timestamp>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetTimestampReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetSeconds(*value), 0); reflection.SetSeconds(value, 1); EXPECT_EQ(reflection.GetSeconds(*value), 1); EXPECT_EQ(reflection.GetNanos(*value), 0); reflection.SetNanos(value, 1); EXPECT_EQ(reflection.GetNanos(*value), 1); } TEST_F(ReflectionTest, Value_Generated) { auto* value = MakeGenerated<google::protobuf::Value>(); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::KIND_NOT_SET); ValueReflection::SetNullValue(value); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::kNullValue); ValueReflection::SetBoolValue(value, true); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::kBoolValue); EXPECT_EQ(ValueReflection::GetBoolValue(*value), true); ValueReflection::SetNumberValue(value, 1.0); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::kNumberValue); EXPECT_EQ(ValueReflection::GetNumberValue(*value), 1.0); ValueReflection::SetStringValue(value, "Hello World!"); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::kStringValue); EXPECT_EQ(ValueReflection::GetStringValue(*value), "Hello World!"); ValueReflection::MutableListValue(value); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::kListValue); EXPECT_EQ(ValueReflection::GetListValue(*value).ByteSizeLong(), 0); ValueReflection::MutableStructValue(value); EXPECT_EQ(ValueReflection::GetKindCase(*value), google::protobuf::Value::kStructValue); EXPECT_EQ(ValueReflection::GetStructValue(*value).ByteSizeLong(), 0); } TEST_F(ReflectionTest, Value_Dynamic) { auto* value = MakeDynamic<google::protobuf::Value>(); std::string scratch; ASSERT_OK_AND_ASSIGN( auto reflection, GetValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::KIND_NOT_SET); reflection.SetNullValue(value); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::kNullValue); reflection.SetBoolValue(value, true); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::kBoolValue); EXPECT_EQ(reflection.GetBoolValue(*value), true); reflection.SetNumberValue(value, 1.0); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::kNumberValue); EXPECT_EQ(reflection.GetNumberValue(*value), 1.0); reflection.SetStringValue(value, "Hello World!"); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::kStringValue); EXPECT_EQ(reflection.GetStringValue(*value, scratch), "Hello World!"); reflection.MutableListValue(value); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::kListValue); EXPECT_EQ(reflection.GetListValue(*value).ByteSizeLong(), 0); EXPECT_THAT(reflection.ReleaseListValue(value), NotNull()); reflection.MutableStructValue(value); EXPECT_EQ(reflection.GetKindCase(*value), google::protobuf::Value::kStructValue); EXPECT_EQ(reflection.GetStructValue(*value).ByteSizeLong(), 0); EXPECT_THAT(reflection.ReleaseStructValue(value), NotNull()); } TEST_F(ReflectionTest, ListValue_Generated) { auto* value = MakeGenerated<google::protobuf::ListValue>(); EXPECT_EQ(ListValueReflection::ValuesSize(*value), 0); EXPECT_EQ(ListValueReflection::Values(*value).size(), 0); EXPECT_EQ(ListValueReflection::MutableValues(value).size(), 0); } TEST_F(ReflectionTest, ListValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::ListValue>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetListValueReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.ValuesSize(*value), 0); EXPECT_EQ(reflection.Values(*value).size(), 0); EXPECT_EQ(reflection.MutableValues(value).size(), 0); } TEST_F(ReflectionTest, StructValue_Generated) { auto* value = MakeGenerated<google::protobuf::Struct>(); EXPECT_EQ(StructReflection::FieldsSize(*value), 0); EXPECT_EQ(StructReflection::BeginFields(*value), StructReflection::EndFields(*value)); EXPECT_FALSE(StructReflection::ContainsField(*value, "foo")); EXPECT_THAT(StructReflection::FindField(*value, "foo"), IsNull()); EXPECT_THAT(StructReflection::InsertField(value, "foo"), NotNull()); EXPECT_TRUE(StructReflection::DeleteField(value, "foo")); } TEST_F(ReflectionTest, StructValue_Dynamic) { auto* value = MakeDynamic<google::protobuf::Struct>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetStructReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.FieldsSize(*value), 0); EXPECT_EQ(reflection.BeginFields(*value), reflection.EndFields(*value)); EXPECT_FALSE(reflection.ContainsField(*value, "foo")); EXPECT_THAT(reflection.FindField(*value, "foo"), IsNull()); EXPECT_THAT(reflection.InsertField(value, "foo"), NotNull()); EXPECT_TRUE(reflection.DeleteField(value, "foo")); } TEST_F(ReflectionTest, FieldMask_Generated) { auto* value = MakeGenerated<google::protobuf::FieldMask>(); EXPECT_EQ(FieldMaskReflection::PathsSize(*value), 0); value->add_paths("foo"); EXPECT_EQ(FieldMaskReflection::PathsSize(*value), 1); EXPECT_EQ(FieldMaskReflection::Paths(*value, 0), "foo"); } TEST_F(ReflectionTest, FieldMask_Dynamic) { auto* value = MakeDynamic<google::protobuf::FieldMask>(); ASSERT_OK_AND_ASSIGN( auto reflection, GetFieldMaskReflection(ABSL_DIE_IF_NULL(value->GetDescriptor()))); EXPECT_EQ(reflection.PathsSize(*value), 0); value->GetReflection()->AddString( &*value, ABSL_DIE_IF_NULL(value->GetDescriptor()->FindFieldByName("paths")), "foo"); EXPECT_EQ(reflection.PathsSize(*value), 1); EXPECT_EQ(reflection.Paths(*value, 0, scratch_space()), "foo"); } TEST_F(ReflectionTest, NullValue_MissingValue) { google::protobuf::DescriptorPool descriptor_pool; { google::protobuf::FileDescriptorProto file_proto; file_proto.set_name("google/protobuf/struct.proto"); file_proto.set_syntax("editions"); file_proto.set_edition(google::protobuf::EDITION_2023); file_proto.set_package("google.protobuf"); auto* enum_proto = file_proto.add_enum_type(); enum_proto->set_name("NullValue"); auto* value_proto = enum_proto->add_value(); value_proto->set_number(1); value_proto->set_name("NULL_VALUE"); enum_proto->mutable_options()->mutable_features()->set_enum_type( google::protobuf::FeatureSet::CLOSED); ASSERT_THAT(descriptor_pool.BuildFile(file_proto), NotNull()); } EXPECT_THAT( NullValueReflection().Initialize(&descriptor_pool), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("well known protocol buffer enum missing value: "))); } TEST_F(ReflectionTest, NullValue_MultipleValues) { google::protobuf::DescriptorPool descriptor_pool; { google::protobuf::FileDescriptorProto file_proto; file_proto.set_name("google/protobuf/struct.proto"); file_proto.set_syntax("proto3"); file_proto.set_package("google.protobuf"); auto* enum_proto = file_proto.add_enum_type(); enum_proto->set_name("NullValue"); auto* value_proto = enum_proto->add_value(); value_proto->set_number(0); value_proto->set_name("NULL_VALUE"); value_proto = enum_proto->add_value(); value_proto->set_number(1); value_proto->set_name("NULL_VALUE2"); ASSERT_THAT(descriptor_pool.BuildFile(file_proto), NotNull()); } EXPECT_THAT( NullValueReflection().Initialize(&descriptor_pool), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("well known protocol buffer enum has multiple values: "))); } TEST_F(ReflectionTest, EnumDescriptorMissing) { google::protobuf::DescriptorPool descriptor_pool; EXPECT_THAT(NullValueReflection().Initialize(&descriptor_pool), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("descriptor missing for protocol buffer enum " "well known type: "))); } TEST_F(ReflectionTest, MessageDescriptorMissing) { google::protobuf::DescriptorPool descriptor_pool; EXPECT_THAT(BoolValueReflection().Initialize(&descriptor_pool), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("descriptor missing for protocol buffer " "message well known type: "))); } class AdaptFromMessageTest : public Test { public: absl::Nonnull<google::protobuf::Arena*> arena() ABSL_ATTRIBUTE_LIFETIME_BOUND { return &arena_; } std::string& scratch_space() ABSL_ATTRIBUTE_LIFETIME_BOUND { return scratch_space_; } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } template <typename T> absl::Nonnull<google::protobuf::Message*> MakeDynamic() { const auto* descriptor_pool = GetTestingDescriptorPool(); const auto* descriptor = ABSL_DIE_IF_NULL(descriptor_pool->FindMessageTypeByName( internal::MessageTypeNameFor<T>())); const auto* prototype = ABSL_DIE_IF_NULL(GetTestingMessageFactory()->GetPrototype(descriptor)); return prototype->New(arena()); } template <typename T> Owned<google::protobuf::Message> DynamicParseTextProto(absl::string_view text) { return ::cel::internal::DynamicParseTextProto<T>( arena(), text, descriptor_pool(), message_factory()); } absl::StatusOr<Value> AdaptFromMessage(const google::protobuf::Message& message) { return well_known_types::AdaptFromMessage( arena(), message, descriptor_pool(), message_factory(), scratch_space()); } private: google::protobuf::Arena arena_; std::string scratch_space_; }; TEST_F(AdaptFromMessageTest, BoolValue) { auto message = DynamicParseTextProto<google::protobuf::BoolValue>(R"pb(value: true)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<bool>(true))); } TEST_F(AdaptFromMessageTest, Int32Value) { auto message = DynamicParseTextProto<google::protobuf::Int32Value>(R"pb(value: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<int32_t>(1))); } TEST_F(AdaptFromMessageTest, Int64Value) { auto message = DynamicParseTextProto<google::protobuf::Int64Value>(R"pb(value: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<int64_t>(1))); } TEST_F(AdaptFromMessageTest, UInt32Value) { auto message = DynamicParseTextProto<google::protobuf::UInt32Value>(R"pb(value: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<uint32_t>(1))); } TEST_F(AdaptFromMessageTest, UInt64Value) { auto message = DynamicParseTextProto<google::protobuf::UInt64Value>(R"pb(value: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<uint64_t>(1))); } TEST_F(AdaptFromMessageTest, FloatValue) { auto message = DynamicParseTextProto<google::protobuf::FloatValue>(R"pb(value: 1.0)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<float>(1))); } TEST_F(AdaptFromMessageTest, DoubleValue) { auto message = DynamicParseTextProto<google::protobuf::DoubleValue>(R"pb(value: 1.0)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<double>(1))); } TEST_F(AdaptFromMessageTest, BytesValue) { auto message = DynamicParseTextProto<google::protobuf::BytesValue>( R"pb(value: "foo")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<BytesValue>(BytesValue("foo")))); } TEST_F(AdaptFromMessageTest, StringValue) { auto message = DynamicParseTextProto<google::protobuf::StringValue>( R"pb(value: "foo")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<StringValue>(StringValue("foo")))); } TEST_F(AdaptFromMessageTest, Duration) { auto message = DynamicParseTextProto<google::protobuf::Duration>( R"pb(seconds: 1 nanos: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<absl::Duration>(absl::Seconds(1) + absl::Nanoseconds(1)))); } TEST_F(AdaptFromMessageTest, Duration_SecondsOutOfRange) { auto message = DynamicParseTextProto<google::protobuf::Duration>( R"pb(seconds: 0x7fffffffffffffff nanos: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid duration seconds: "))); } TEST_F(AdaptFromMessageTest, Duration_NanosOutOfRange) { auto message = DynamicParseTextProto<google::protobuf::Duration>( R"pb(seconds: 1 nanos: 0x7fffffff)pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid duration nanoseconds: "))); } TEST_F(AdaptFromMessageTest, Duration_SignMismatch) { auto message = DynamicParseTextProto<google::protobuf::Duration>(R"pb(seconds: -1 nanos: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("duration sign mismatch: "))); } TEST_F(AdaptFromMessageTest, Timestamp) { auto message = DynamicParseTextProto<google::protobuf::Timestamp>(R"pb(seconds: 1 nanos: 1)pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<absl::Time>( absl::UnixEpoch() + absl::Seconds(1) + absl::Nanoseconds(1)))); } TEST_F(AdaptFromMessageTest, Timestamp_SecondsOutOfRange) { auto message = DynamicParseTextProto<google::protobuf::Timestamp>( R"pb(seconds: 0x7fffffffffffffff nanos: 1)pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid timestamp seconds: "))); } TEST_F(AdaptFromMessageTest, Timestamp_NanosOutOfRange) { auto message = DynamicParseTextProto<google::protobuf::Timestamp>( R"pb(seconds: 1 nanos: 0x7fffffff)pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid timestamp nanoseconds: "))); } TEST_F(AdaptFromMessageTest, Value_NullValue) { auto message = DynamicParseTextProto<google::protobuf::Value>( R"pb(null_value: NULL_VALUE)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<std::nullptr_t>(nullptr))); } TEST_F(AdaptFromMessageTest, Value_BoolValue) { auto message = DynamicParseTextProto<google::protobuf::Value>(R"pb(bool_value: true)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<bool>(true))); } TEST_F(AdaptFromMessageTest, Value_NumberValue) { auto message = DynamicParseTextProto<google::protobuf::Value>( R"pb(number_value: 1.0)pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<double>(1.0))); } TEST_F(AdaptFromMessageTest, Value_StringValue) { auto message = DynamicParseTextProto<google::protobuf::Value>( R"pb(string_value: "foo")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<StringValue>(StringValue("foo")))); } TEST_F(AdaptFromMessageTest, Value_ListValue) { auto message = DynamicParseTextProto<google::protobuf::Value>(R"pb(list_value: {})pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<ListValue>(VariantWith<ListValueConstRef>(_)))); } TEST_F(AdaptFromMessageTest, Value_StructValue) { auto message = DynamicParseTextProto<google::protobuf::Value>(R"pb(struct_value: {})pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<Struct>(VariantWith<StructConstRef>(_)))); } TEST_F(AdaptFromMessageTest, ListValue) { auto message = DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<ListValue>(VariantWith<ListValueConstRef>(_)))); } TEST_F(AdaptFromMessageTest, Struct) { auto message = DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<Struct>(VariantWith<StructConstRef>(_)))); } TEST_F(AdaptFromMessageTest, TestAllTypesProto3) { auto message = DynamicParseTextProto<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<absl::monostate>(absl::monostate()))); } TEST_F(AdaptFromMessageTest, Any_BoolValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.BoolValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<bool>(false))); } TEST_F(AdaptFromMessageTest, Any_Int32Value) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Int32Value")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<int32_t>(0))); } TEST_F(AdaptFromMessageTest, Any_Int64Value) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Int64Value")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<int64_t>(0))); } TEST_F(AdaptFromMessageTest, Any_UInt32Value) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.UInt32Value")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<uint32_t>(0))); } TEST_F(AdaptFromMessageTest, Any_UInt64Value) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.UInt64Value")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<uint64_t>(0))); } TEST_F(AdaptFromMessageTest, Any_FloatValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.FloatValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<float>(0))); } TEST_F(AdaptFromMessageTest, Any_DoubleValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.DoubleValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<double>(0))); } TEST_F(AdaptFromMessageTest, Any_BytesValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.BytesValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<BytesValue>(BytesValue()))); } TEST_F(AdaptFromMessageTest, Any_StringValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.StringValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<StringValue>(StringValue()))); } TEST_F(AdaptFromMessageTest, Any_Duration) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Duration")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<absl::Duration>(absl::ZeroDuration()))); } TEST_F(AdaptFromMessageTest, Any_Timestamp) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Timestamp")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<absl::Time>(absl::UnixEpoch()))); } TEST_F(AdaptFromMessageTest, Any_Value_NullValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Value")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<std::nullptr_t>(nullptr))); } TEST_F(AdaptFromMessageTest, Any_Value_BoolValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Value" value: "\x20\x01")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<bool>(true))); } TEST_F(AdaptFromMessageTest, Any_Value_NumberValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Value" value: "\x11\x00\x00\x00\x00\x00\x00\x00\x00")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<double>(0.0))); } TEST_F(AdaptFromMessageTest, Any_Value_StringValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Value" value: "\x1a\x03\x66\x6f\x6f")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<StringValue>(StringValue("foo")))); } TEST_F(AdaptFromMessageTest, Any_Value_ListValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Value" value: "\x32\x00")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<ListValue>( VariantWith<ListValuePtr>(NotNull())))); } TEST_F(AdaptFromMessageTest, Any_Value_StructValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Value" value: "\x2a\x00")pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<Struct>(VariantWith<StructPtr>(NotNull())))); } TEST_F(AdaptFromMessageTest, Any_ListValue) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.ListValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<ListValue>( VariantWith<ListValuePtr>(NotNull())))); } TEST_F(AdaptFromMessageTest, Any_Struct) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.protobuf.Struct")pb"); EXPECT_THAT( AdaptFromMessage(*message), IsOkAndHolds(VariantWith<Struct>(VariantWith<StructPtr>(NotNull())))); } TEST_F(AdaptFromMessageTest, Any_TestAllTypesProto3) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/google.api.expr.test.v1.proto3.TestAllTypes")pb"); EXPECT_THAT(AdaptFromMessage(*message), IsOkAndHolds(VariantWith<Unique<google::protobuf::Message>>(NotNull()))); } TEST_F(AdaptFromMessageTest, Any_BadTypeUrlDomain) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.example.com/google.protobuf.BoolValue")pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unable to find descriptor for type URL: "))); } TEST_F(AdaptFromMessageTest, Any_UnknownMessage) { auto message = DynamicParseTextProto<google::protobuf::Any>( R"pb(type_url: "type.googleapis.com/message.that.does.not.Exist")pb"); EXPECT_THAT(AdaptFromMessage(*message), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unable to find descriptor for type name: "))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/well_known_types.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/well_known_types_test.cc
4552db5798fb0853b131b783d8875794334fae7f
98b84864-4604-4f7e-9c73-6891124d7ebb
cpp
google/cel-cpp
time
internal/time.cc
internal/time_test.cc
#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 ::absl_testing::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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/time.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/time_test.cc
4552db5798fb0853b131b783d8875794334fae7f
537e74d1-0a16-4799-8d4c-63f815386099
cpp
google/cel-cpp
macro_expr_factory
parser/macro_expr_factory.cc
parser/macro_expr_factory_test.cc
#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"))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/parser/macro_expr_factory.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/parser/macro_expr_factory_test.cc
4552db5798fb0853b131b783d8875794334fae7f
8c0d3074-1316-4946-9977-f3d3c6a6b78b
cpp
google/cel-cpp
parser
parser/parser.cc
parser/parser_test.cc
#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 = tree; if (auto* ctx = tree_as<CelParser::StartContext>(tree)) { tree = ctx->expr(); } if (auto* ctx = tree_as<CelParser::ExprContext>(tree)) { if (ctx->op != nullptr) { return ctx; } tree = ctx->e; } if (auto* ctx = tree_as<CelParser::ConditionalOrContext>(tree)) { if (!ctx->ops.empty()) { return ctx; } tree = ctx->e; } if (auto* ctx = tree_as<CelParser::ConditionalAndContext>(tree)) { if (!ctx->ops.empty()) { return ctx; } tree = ctx->e; } if (auto* ctx = tree_as<CelParser::RelationContext>(tree)) { if (ctx->calc() == nullptr) { return ctx; } tree = ctx->calc(); } if (auto* ctx = tree_as<CelParser::CalcContext>(tree)) { if (ctx->unary() == nullptr) { return ctx; } tree = ctx->unary(); } if (auto* ctx = tree_as<CelParser::MemberExprContext>(tree)) { tree = ctx->member(); } if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(tree)) { if (auto* nested = tree_as<CelParser::NestedContext>(ctx->primary())) { tree = nested->e; } else { return ctx; } } } return tree; } std::any ParserVisitor::visitExpr(CelParser::ExprContext* ctx) { auto result = ExprFromAny(visit(ctx->e)); if (!ctx->op) { return ExprToAny(std::move(result)); } std::vector<Expr> arguments; arguments.reserve(3); arguments.push_back(std::move(result)); int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); arguments.push_back(ExprFromAny(visit(ctx->e1))); arguments.push_back(ExprFromAny(visit(ctx->e2))); return ExprToAny( factory_.NewCall(op_id, CelOperator::CONDITIONAL, std::move(arguments))); } std::any ParserVisitor::visitConditionalOr( CelParser::ConditionalOrContext* ctx) { auto result = ExprFromAny(visit(ctx->e)); if (ctx->ops.empty()) { return ExprToAny(std::move(result)); } ExpressionBalancer b(factory_, CelOperator::LOGICAL_OR, std::move(result)); for (size_t i = 0; i < ctx->ops.size(); ++i) { auto op = ctx->ops[i]; if (i >= ctx->e1.size()) { return ExprToAny( factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "unexpected character, wanted '||'")); } auto next = ExprFromAny(visit(ctx->e1[i])); int64_t op_id = factory_.NextId(SourceRangeFromToken(op)); b.AddTerm(op_id, std::move(next)); } return ExprToAny(b.Balance()); } std::any ParserVisitor::visitConditionalAnd( CelParser::ConditionalAndContext* ctx) { auto result = ExprFromAny(visit(ctx->e)); if (ctx->ops.empty()) { return ExprToAny(std::move(result)); } ExpressionBalancer b(factory_, CelOperator::LOGICAL_AND, std::move(result)); for (size_t i = 0; i < ctx->ops.size(); ++i) { auto op = ctx->ops[i]; if (i >= ctx->e1.size()) { return ExprToAny( factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "unexpected character, wanted '&&'")); } auto next = ExprFromAny(visit(ctx->e1[i])); int64_t op_id = factory_.NextId(SourceRangeFromToken(op)); b.AddTerm(op_id, std::move(next)); } return ExprToAny(b.Balance()); } std::any ParserVisitor::visitRelation(CelParser::RelationContext* ctx) { if (ctx->calc()) { return visit(ctx->calc()); } std::string op_text; if (ctx->op) { op_text = ctx->op->getText(); } auto op = ReverseLookupOperator(op_text); if (op) { auto lhs = ExprFromAny(visit(ctx->relation(0))); int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); auto rhs = ExprFromAny(visit(ctx->relation(1))); return ExprToAny( GlobalCallOrMacro(op_id, *op, std::move(lhs), std::move(rhs))); } return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "operator not found")); } std::any ParserVisitor::visitCalc(CelParser::CalcContext* ctx) { if (ctx->unary()) { return visit(ctx->unary()); } std::string op_text; if (ctx->op) { op_text = ctx->op->getText(); } auto op = ReverseLookupOperator(op_text); if (op) { auto lhs = ExprFromAny(visit(ctx->calc(0))); int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); auto rhs = ExprFromAny(visit(ctx->calc(1))); return ExprToAny( GlobalCallOrMacro(op_id, *op, std::move(lhs), std::move(rhs))); } return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "operator not found")); } std::any ParserVisitor::visitUnary(CelParser::UnaryContext* ctx) { return ExprToAny(factory_.NewStringConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), "<<error>>")); } std::any ParserVisitor::visitLogicalNot(CelParser::LogicalNotContext* ctx) { if (ctx->ops.size() % 2 == 0) { return visit(ctx->member()); } int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->ops[0])); auto target = ExprFromAny(visit(ctx->member())); return ExprToAny( GlobalCallOrMacro(op_id, CelOperator::LOGICAL_NOT, std::move(target))); } std::any ParserVisitor::visitNegate(CelParser::NegateContext* ctx) { if (ctx->ops.size() % 2 == 0) { return visit(ctx->member()); } int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->ops[0])); auto target = ExprFromAny(visit(ctx->member())); return ExprToAny( GlobalCallOrMacro(op_id, CelOperator::NEGATE, std::move(target))); } std::any ParserVisitor::visitSelect(CelParser::SelectContext* ctx) { auto operand = ExprFromAny(visit(ctx->member())); if (!ctx->id || !ctx->op) { return ExprToAny(factory_.NewUnspecified( factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); } auto id = ctx->id->getText(); if (ctx->opt != nullptr) { if (!enable_optional_syntax_) { return ExprToAny(factory_.ReportError( SourceRangeFromParserRuleContext(ctx), "unsupported syntax '.?'")); } auto op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); std::vector<Expr> arguments; arguments.reserve(2); arguments.push_back(std::move(operand)); arguments.push_back(factory_.NewStringConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), std::move(id))); return ExprToAny(factory_.NewCall(op_id, "_?._", std::move(arguments))); } return ExprToAny( factory_.NewSelect(factory_.NextId(SourceRangeFromToken(ctx->op)), std::move(operand), std::move(id))); } std::any ParserVisitor::visitMemberCall(CelParser::MemberCallContext* ctx) { auto operand = ExprFromAny(visit(ctx->member())); if (!ctx->id) { return ExprToAny(factory_.NewUnspecified( factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); } auto id = ctx->id->getText(); int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->open)); auto args = visitList(ctx->args); return ExprToAny( ReceiverCallOrMacroImpl(op_id, id, std::move(operand), std::move(args))); } std::any ParserVisitor::visitIndex(CelParser::IndexContext* ctx) { auto target = ExprFromAny(visit(ctx->member())); int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); auto index = ExprFromAny(visit(ctx->index)); if (!enable_optional_syntax_ && ctx->opt != nullptr) { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "unsupported syntax '.?'")); } return ExprToAny(GlobalCallOrMacro( op_id, ctx->opt != nullptr ? "_[?_]" : CelOperator::INDEX, std::move(target), std::move(index))); } std::any ParserVisitor::visitCreateMessage( CelParser::CreateMessageContext* ctx) { std::vector<std::string> parts; parts.reserve(ctx->ids.size()); for (const auto* id : ctx->ids) { parts.push_back(id->getText()); } std::string name; if (ctx->leadingDot) { name.push_back('.'); name.append(absl::StrJoin(parts, ".")); } else { name = absl::StrJoin(parts, "."); } int64_t obj_id = factory_.NextId(SourceRangeFromToken(ctx->op)); std::vector<StructExprField> fields; if (ctx->entries) { fields = visitFields(ctx->entries); } return ExprToAny( factory_.NewStruct(obj_id, std::move(name), std::move(fields))); } std::any ParserVisitor::visitFieldInitializerList( CelParser::FieldInitializerListContext* ctx) { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "<<unreachable>>")); } std::vector<StructExprField> ParserVisitor::visitFields( CelParser::FieldInitializerListContext* ctx) { std::vector<StructExprField> res; if (!ctx || ctx->fields.empty()) { return res; } res.reserve(ctx->fields.size()); for (size_t i = 0; i < ctx->fields.size(); ++i) { if (i >= ctx->cols.size() || i >= ctx->values.size()) { return res; } const auto* f = ctx->fields[i]; if (f->id == nullptr) { ABSL_DCHECK(HasErrored()); return res; } int64_t init_id = factory_.NextId(SourceRangeFromToken(ctx->cols[i])); if (!enable_optional_syntax_ && f->opt) { factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "unsupported syntax '?'"); continue; } auto value = ExprFromAny(visit(ctx->values[i])); res.push_back(factory_.NewStructField(init_id, f->id->getText(), std::move(value), f->opt != nullptr)); } return res; } std::any ParserVisitor::visitIdentOrGlobalCall( CelParser::IdentOrGlobalCallContext* ctx) { std::string ident_name; if (ctx->leadingDot) { ident_name = "."; } if (!ctx->id) { return ExprToAny(factory_.NewUnspecified( factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); } if (cel::internal::LexisIsReserved(ctx->id->getText())) { return ExprToAny(factory_.ReportError( SourceRangeFromParserRuleContext(ctx), absl::StrFormat("reserved identifier: %s", ctx->id->getText()))); } ident_name += ctx->id->getText(); if (ctx->op) { int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); auto args = visitList(ctx->args); return ExprToAny( GlobalCallOrMacroImpl(op_id, std::move(ident_name), std::move(args))); } return ExprToAny(factory_.NewIdent( factory_.NextId(SourceRangeFromToken(ctx->id)), std::move(ident_name))); } std::any ParserVisitor::visitNested(CelParser::NestedContext* ctx) { return visit(ctx->e); } std::any ParserVisitor::visitCreateList(CelParser::CreateListContext* ctx) { int64_t list_id = factory_.NextId(SourceRangeFromToken(ctx->op)); auto elems = visitList(ctx->elems); return ExprToAny(factory_.NewList(list_id, std::move(elems))); } std::vector<ListExprElement> ParserVisitor::visitList( CelParser::ListInitContext* ctx) { std::vector<ListExprElement> rv; if (!ctx) return rv; rv.reserve(ctx->elems.size()); for (size_t i = 0; i < ctx->elems.size(); ++i) { auto* expr_ctx = ctx->elems[i]; if (expr_ctx == nullptr) { return rv; } if (!enable_optional_syntax_ && expr_ctx->opt != nullptr) { factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "unsupported syntax '?'"); rv.push_back(factory_.NewListElement(factory_.NewUnspecified(0), false)); continue; } rv.push_back(factory_.NewListElement(ExprFromAny(visitExpr(expr_ctx->e)), expr_ctx->opt != nullptr)); } return rv; } std::vector<Expr> ParserVisitor::visitList(CelParser::ExprListContext* ctx) { std::vector<Expr> rv; if (!ctx) return rv; std::transform(ctx->e.begin(), ctx->e.end(), std::back_inserter(rv), [this](CelParser::ExprContext* expr_ctx) { return ExprFromAny(visitExpr(expr_ctx)); }); return rv; } std::any ParserVisitor::visitCreateStruct(CelParser::CreateStructContext* ctx) { int64_t struct_id = factory_.NextId(SourceRangeFromToken(ctx->op)); std::vector<MapExprEntry> entries; if (ctx->entries) { entries = visitEntries(ctx->entries); } return ExprToAny(factory_.NewMap(struct_id, std::move(entries))); } std::any ParserVisitor::visitConstantLiteral( CelParser::ConstantLiteralContext* clctx) { CelParser::LiteralContext* literal = clctx->literal(); if (auto* ctx = tree_as<CelParser::IntContext>(literal)) { return visitInt(ctx); } else if (auto* ctx = tree_as<CelParser::UintContext>(literal)) { return visitUint(ctx); } else if (auto* ctx = tree_as<CelParser::DoubleContext>(literal)) { return visitDouble(ctx); } else if (auto* ctx = tree_as<CelParser::StringContext>(literal)) { return visitString(ctx); } else if (auto* ctx = tree_as<CelParser::BytesContext>(literal)) { return visitBytes(ctx); } else if (auto* ctx = tree_as<CelParser::BoolFalseContext>(literal)) { return visitBoolFalse(ctx); } else if (auto* ctx = tree_as<CelParser::BoolTrueContext>(literal)) { return visitBoolTrue(ctx); } else if (auto* ctx = tree_as<CelParser::NullContext>(literal)) { return visitNull(ctx); } return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(clctx), "invalid constant literal expression")); } std::any ParserVisitor::visitMapInitializerList( CelParser::MapInitializerListContext* ctx) { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "<<unreachable>>")); } std::vector<MapExprEntry> ParserVisitor::visitEntries( CelParser::MapInitializerListContext* ctx) { std::vector<MapExprEntry> res; if (!ctx || ctx->keys.empty()) { return res; } res.reserve(ctx->cols.size()); for (size_t i = 0; i < ctx->cols.size(); ++i) { auto id = factory_.NextId(SourceRangeFromToken(ctx->cols[i])); if (!enable_optional_syntax_ && ctx->keys[i]->opt) { factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "unsupported syntax '?'"); res.push_back(factory_.NewMapEntry(0, factory_.NewUnspecified(0), factory_.NewUnspecified(0), false)); continue; } auto key = ExprFromAny(visit(ctx->keys[i]->e)); auto value = ExprFromAny(visit(ctx->values[i])); res.push_back(factory_.NewMapEntry(id, std::move(key), std::move(value), ctx->keys[i]->opt != nullptr)); } return res; } std::any ParserVisitor::visitInt(CelParser::IntContext* ctx) { std::string value; if (ctx->sign) { value = ctx->sign->getText(); } value += ctx->tok->getText(); int64_t int_value; if (absl::StartsWith(ctx->tok->getText(), "0x")) { if (absl::SimpleHexAtoi(value, &int_value)) { return ExprToAny(factory_.NewIntConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), int_value)); } else { return ExprToAny(factory_.ReportError( SourceRangeFromParserRuleContext(ctx), "invalid hex int literal")); } } if (absl::SimpleAtoi(value, &int_value)) { return ExprToAny(factory_.NewIntConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), int_value)); } else { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "invalid int literal")); } } std::any ParserVisitor::visitUint(CelParser::UintContext* ctx) { std::string value = ctx->tok->getText(); if (!value.empty()) { value.resize(value.size() - 1); } uint64_t uint_value; if (absl::StartsWith(ctx->tok->getText(), "0x")) { if (absl::SimpleHexAtoi(value, &uint_value)) { return ExprToAny(factory_.NewUintConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), uint_value)); } else { return ExprToAny(factory_.ReportError( SourceRangeFromParserRuleContext(ctx), "invalid hex uint literal")); } } if (absl::SimpleAtoi(value, &uint_value)) { return ExprToAny(factory_.NewUintConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), uint_value)); } else { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "invalid uint literal")); } } std::any ParserVisitor::visitDouble(CelParser::DoubleContext* ctx) { std::string value; if (ctx->sign) { value = ctx->sign->getText(); } value += ctx->tok->getText(); double double_value; if (absl::SimpleAtod(value, &double_value)) { return ExprToAny(factory_.NewDoubleConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), double_value)); } else { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), "invalid double literal")); } } std::any ParserVisitor::visitString(CelParser::StringContext* ctx) { auto status_or_value = cel::internal::ParseStringLiteral(ctx->tok->getText()); if (!status_or_value.ok()) { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), status_or_value.status().message())); } return ExprToAny(factory_.NewStringConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), std::move(status_or_value).value())); } std::any ParserVisitor::visitBytes(CelParser::BytesContext* ctx) { auto status_or_value = cel::internal::ParseBytesLiteral(ctx->tok->getText()); if (!status_or_value.ok()) { return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), status_or_value.status().message())); } return ExprToAny(factory_.NewBytesConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), std::move(status_or_value).value())); } std::any ParserVisitor::visitBoolTrue(CelParser::BoolTrueContext* ctx) { return ExprToAny(factory_.NewBoolConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), true)); } std::any ParserVisitor::visitBoolFalse(CelParser::BoolFalseContext* ctx) { return ExprToAny(factory_.NewBoolConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)), false)); } std::any ParserVisitor::visitNull(CelParser::NullContext* ctx) { return ExprToAny(factory_.NewNullConst( factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); } absl::Status ParserVisitor::GetSourceInfo( google::api::expr::v1alpha1::SourceInfo* source_info) const { source_info->set_location(source_.description()); for (const auto& positions : factory_.positions()) { source_info->mutable_positions()->insert( std::pair{positions.first, positions.second.begin}); } source_info->mutable_line_offsets()->Reserve(source_.line_offsets().size()); for (const auto& line_offset : source_.line_offsets()) { source_info->mutable_line_offsets()->Add(line_offset); } for (const auto& macro_call : factory_.macro_calls()) { google::api::expr::v1alpha1::Expr macro_call_proto; CEL_RETURN_IF_ERROR(cel::extensions::protobuf_internal::ExprToProto( macro_call.second, &macro_call_proto)); source_info->mutable_macro_calls()->insert( std::pair{macro_call.first, std::move(macro_call_proto)}); } return absl::OkStatus(); } EnrichedSourceInfo ParserVisitor::enriched_source_info() const { std::map<int64_t, std::pair<int32_t, int32_t>> offsets; for (const auto& positions : factory_.positions()) { offsets.insert( std::pair{positions.first, std::pair{positions.second.begin, positions.second.end - 1}}); } return EnrichedSourceInfo(std::move(offsets)); } void ParserVisitor::syntaxError(antlr4::Recognizer* recognizer, antlr4::Token* offending_symbol, size_t line, size_t col, const std::string& msg, std::exception_ptr e) { cel::SourceRange range; if (auto position = source_.GetPosition(cel::SourceLocation{ static_cast<int32_t>(line), static_cast<int32_t>(col)}); position) { range.begin = *position; } factory_.ReportError(range, absl::StrCat("Syntax error: ", msg)); } bool ParserVisitor::HasErrored() const { return factory_.HasErrors(); } std::string ParserVisitor::ErrorMessage() { return factory_.ErrorMessage(); } Expr ParserVisitor::GlobalCallOrMacroImpl(int64_t expr_id, absl::string_view function, std::vector<Expr> args) { if (auto macro = macro_registry_.FindMacro(function, args.size(), false); macro) { std::vector<Expr> macro_args; if (add_macro_calls_) { macro_args.reserve(args.size()); for (const auto& arg : args) { macro_args.push_back(factory_.BuildMacroCallArg(arg)); } } factory_.BeginMacro(factory_.GetSourceRange(expr_id)); auto expr = macro->Expand(factory_, absl::nullopt, absl::MakeSpan(args)); factory_.EndMacro(); if (expr) { if (add_macro_calls_) { factory_.AddMacroCall(expr->id(), function, absl::nullopt, std::move(macro_args)); } factory_.EraseId(expr_id); return std::move(*expr); } } return factory_.NewCall(expr_id, function, std::move(args)); } Expr ParserVisitor::ReceiverCallOrMacroImpl(int64_t expr_id, absl::string_view function, Expr target, std::vector<Expr> args) { if (auto macro = macro_registry_.FindMacro(function, args.size(), true); macro) { Expr macro_target; std::vector<Expr> macro_args; if (add_macro_calls_) { macro_args.reserve(args.size()); macro_target = factory_.BuildMacroCallArg(target); for (const auto& arg : args) { macro_args.push_back(factory_.BuildMacroCallArg(arg)); } } factory_.BeginMacro(factory_.GetSourceRange(expr_id)); auto expr = macro->Expand(factory_, std::ref(target), absl::MakeSpan(args)); factory_.EndMacro(); if (expr) { if (add_macro_calls_) { factory_.AddMacroCall(expr->id(), function, std::move(macro_target), std::move(macro_args)); } factory_.EraseId(expr_id); return std::move(*expr); } } return factory_.NewMemberCall(expr_id, function, std::move(target), std::move(args)); } std::string ParserVisitor::ExtractQualifiedName(antlr4::ParserRuleContext* ctx, const Expr& e) { if (e == Expr{}) { return ""; } if (const auto* ident_expr = absl::get_if<IdentExpr>(&e.kind()); ident_expr) { return ident_expr->name(); } if (const auto* select_expr = absl::get_if<SelectExpr>(&e.kind()); select_expr) { std::string prefix = ExtractQualifiedName(ctx, select_expr->operand()); if (!prefix.empty()) { return absl::StrCat(prefix, ".", select_expr->field()); } } factory_.ReportError(factory_.GetSourceRange(e.id()), "expected a qualified name"); return ""; } static constexpr auto kStandardReplacements = std::array<std::pair<absl::string_view, absl::string_view>, 3>{ std::make_pair("\n", "\\n"), std::make_pair("\r", "\\r"), std::make_pair("\t", "\\t"), }; static constexpr absl::string_view kSingleQuote = "'"; class ExprRecursionListener final : public ParseTreeListener { public: explicit ExprRecursionListener( const int max_recursion_depth = kDefaultMaxRecursionDepth) : max_recursion_depth_(max_recursion_depth), recursion_depth_(0) {} ~ExprRecursionListener() override {} void visitTerminal(TerminalNode* node) override {}; void visitErrorNode(ErrorNode* error) override {}; void enterEveryRule(ParserRuleContext* ctx) override; void exitEveryRule(ParserRuleContext* ctx) override; private: const int max_recursion_depth_; int recursion_depth_; }; void ExprRecursionListener::enterEveryRule(ParserRuleContext* ctx) { if (ctx->getRuleIndex() == CelParser::RuleExpr) { if (recursion_depth_ > max_recursion_depth_) { throw ParseCancellationException( absl::StrFormat("Expression recursion limit exceeded. limit: %d", max_recursion_depth_)); } recursion_depth_++; } } void ExprRecursionListener::exitEveryRule(ParserRuleContext* ctx) { if (ctx->getRuleIndex() == CelParser::RuleExpr) { recursion_depth_--; } } class RecoveryLimitErrorStrategy final : public DefaultErrorStrategy { public: explicit RecoveryLimitErrorStrategy( int recovery_limit = kDefaultErrorRecoveryLimit, int recovery_token_lookahead_limit = kDefaultErrorRecoveryTokenLookaheadLimit) : recovery_limit_(recovery_limit), recovery_attempts_(0), recovery_token_lookahead_limit_(recovery_token_lookahead_limit) {} void recover(Parser* recognizer, std::exception_ptr e) override { checkRecoveryLimit(recognizer); DefaultErrorStrategy::recover(recognizer, e); } Token* recoverInline(Parser* recognizer) override { checkRecoveryLimit(recognizer); return DefaultErrorStrategy::recoverInline(recognizer); } void consumeUntil(Parser* recognizer, const IntervalSet& set) override { size_t ttype = recognizer->getInputStream()->LA(1); int recovery_search_depth = 0; while (ttype != Token::EOF && !set.contains(ttype) && recovery_search_depth++ < recovery_token_lookahead_limit_) { recognizer->consume(); ttype = recognizer->getInputStream()->LA(1); } if (recovery_search_depth == recovery_token_lookahead_limit_) { throw ParseCancellationException("Unable to find a recovery token"); } } protected: std::string escapeWSAndQuote(const std::string& s) const override { std::string result; result.reserve(s.size() + 2); absl::StrAppend(&result, kSingleQuote, s, kSingleQuote); absl::StrReplaceAll(kStandardReplacements, &result); return result; } private: void checkRecoveryLimit(Parser* recognizer) { if (recovery_attempts_++ >= recovery_limit_) { std::string too_many_errors = absl::StrFormat("More than %d parse errors.", recovery_limit_); recognizer->notifyErrorListeners(too_many_errors); throw ParseCancellationException(too_many_errors); } } int recovery_limit_; int recovery_attempts_; int recovery_token_lookahead_limit_; }; } absl::StatusOr<ParsedExpr> Parse(absl::string_view expression, absl::string_view description, const ParserOptions& options) { std::vector<Macro> macros = Macro::AllMacros(); if (options.enable_optional_syntax) { macros.push_back(cel::OptMapMacro()); macros.push_back(cel::OptFlatMapMacro()); } return ParseWithMacros(expression, macros, description, options); } absl::StatusOr<ParsedExpr> ParseWithMacros(absl::string_view expression, const std::vector<Macro>& macros, absl::string_view description, const ParserOptions& options) { CEL_ASSIGN_OR_RETURN(auto verbose_parsed_expr, EnrichedParse(expression, macros, description, options)); return verbose_parsed_expr.parsed_expr(); } absl::StatusOr<VerboseParsedExpr> EnrichedParse( absl::string_view expression, const std::vector<Macro>& macros, absl::string_view description, const ParserOptions& options) { CEL_ASSIGN_OR_RETURN(auto source, cel::NewSource(expression, std::string(description))); cel::MacroRegistry macro_registry; CEL_RETURN_IF_ERROR(macro_registry.RegisterMacros(macros)); return EnrichedParse(*source, macro_registry, options); } absl::StatusOr<VerboseParsedExpr> EnrichedParse( const cel::Source& source, const cel::MacroRegistry& registry, const ParserOptions& options) { try { CodePointStream input(source.content(), source.description()); if (input.size() > options.expression_size_codepoint_limit) { return absl::InvalidArgumentError(absl::StrCat( "expression size exceeds codepoint limit.", " input size: ", input.size(), ", limit: ", options.expression_size_codepoint_limit)); } CelLexer lexer(&input); CommonTokenStream tokens(&lexer); CelParser parser(&tokens); ExprRecursionListener listener(options.max_recursion_depth); ParserVisitor visitor(source, options.max_recursion_depth, registry, options.add_macro_calls, options.enable_optional_syntax); lexer.removeErrorListeners(); parser.removeErrorListeners(); lexer.addErrorListener(&visitor); parser.addErrorListener(&visitor); parser.addParseListener(&listener); parser.setErrorHandler(std::make_shared<RecoveryLimitErrorStrategy>( options.error_recovery_limit, options.error_recovery_token_lookahead_limit)); Expr expr; try { expr = ExprFromAny(visitor.visit(parser.start())); } catch (const ParseCancellationException& e) { if (visitor.HasErrored()) { return absl::InvalidArgumentError(visitor.ErrorMessage()); } return absl::CancelledError(e.what()); } if (visitor.HasErrored()) { return absl::InvalidArgumentError(visitor.ErrorMessage()); } ParsedExpr parsed_expr; CEL_RETURN_IF_ERROR(cel::extensions::protobuf_internal::ExprToProto( expr, parsed_expr.mutable_expr())); CEL_RETURN_IF_ERROR( visitor.GetSourceInfo(parsed_expr.mutable_source_info())); auto enriched_source_info = visitor.enriched_source_info(); return VerboseParsedExpr(std::move(parsed_expr), std::move(enriched_source_info)); } catch (const std::exception& e) { return absl::AbortedError(e.what()); } catch (const char* what) { return absl::AbortedError(what); } catch (...) { return absl::UnknownError("An unknown exception occurred"); } } absl::StatusOr<google::api::expr::v1alpha1::ParsedExpr> Parse( const cel::Source& source, const cel::MacroRegistry& registry, const ParserOptions& options) { CEL_ASSIGN_OR_RETURN(auto verbose_expr, EnrichedParse(source, registry, options)); return verbose_expr.parsed_expr(); } }
#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 ::absl_testing::IsOk; using ::google::api::expr::v1alpha1::Expr; using ::testing::HasSubstr; using ::testing::Not; 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" " y^#3:Expr.Ident#\n" " ]^#38:Expr.CreateList#\n" " )^#39:Expr.Call#,\n" " __result__^#40:Expr.Ident#\n" " )^#41:Expr.Call#,\n" " " __result__^#42:Expr.Ident#)^#43:Expr.Comprehension#", "", "", "", "x^#1:Expr.Ident#.filter(\n" " y^#3:Expr.Ident#,\n" " _&&_(\n" " ^#18:exists#,\n" " ^#33:exists#\n" " )^#34:Expr.Call#\n" ")^#43:filter#,\n" "y^#19:Expr.Ident#.exists(\n" " z^#21:Expr.Ident#,\n" " ^#25:has#\n" ")^#33:exists#,\n" "has(\n" " z^#23:Expr.Ident#.b^#24:Expr.Select#\n" ")^#25:has#,\n" "y^#4:Expr.Ident#." "exists(\n" " z^#6:Expr.Ident#,\n" " ^#10:has#\n" ")^#18:exists#,\n" "has(\n" " z^#8:Expr.Ident#.a^#9:Expr.Select#\n" ")^#10:has"}, {"has(a.b).asList().exists(c, c)", "__comprehension__(\n" " " c,\n" " " a^#2:Expr.Ident#.b~test-only~^#4:Expr.Select#.asList()^#5:Expr.Call#,\n" " " __result__,\n" " " false^#9:bool#,\n" " " @not_strictly_false(\n" " !_(\n" " __result__^#10:Expr.Ident#\n" " )^#11:Expr.Call#\n" " )^#12:Expr.Call#,\n" " " _||_(\n" " __result__^#13:Expr.Ident#,\n" " c^#8:Expr.Ident#\n" " )^#14:Expr.Call#,\n" " " __result__^#15:Expr.Ident#)^#16:Expr.Comprehension#", "", "", "", "^#4:has#.asList()^#5:Expr.Call#.exists(\n" " c^#7:Expr.Ident#,\n" " c^#8:Expr.Ident#\n" ")^#16:exists#,\n" "has(\n" " a^#2:Expr.Ident#.b^#3:Expr.Select#\n" ")^#4:has"}, {"[has(a.b), has(c.d)].exists(e, e)", "__comprehension__(\n" " " e,\n" " " [\n" " a^#3:Expr.Ident#.b~test-only~^#5:Expr.Select#,\n" " c^#7:Expr.Ident#.d~test-only~^#9:Expr.Select#\n" " ]^#1:Expr.CreateList#,\n" " " __result__,\n" " " false^#13:bool#,\n" " " @not_strictly_false(\n" " !_(\n" " __result__^#14:Expr.Ident#\n" " )^#15:Expr.Call#\n" " )^#16:Expr.Call#,\n" " " _||_(\n" " __result__^#17:Expr.Ident#,\n" " e^#12:Expr.Ident#\n" " )^#18:Expr.Call#,\n" " " __result__^#19:Expr.Ident#)^#20:Expr.Comprehension#", "", "", "", "[\n" " ^#5:has#,\n" " ^#9:has#\n" "]^#1:Expr.CreateList#.exists(\n" " e^#11:Expr.Ident#,\n" " e^#12:Expr.Ident#\n" ")^#20:exists#,\n" "has(\n" " c^#7:Expr.Ident#.d^#8:Expr.Select#\n" ")^#9:has#,\n" "has(\n" " a^#3:Expr.Ident#.b^#4:Expr.Select#\n" ")^#5:has"}, {"b'\\UFFFFFFFF'", "", "ERROR: <input>:1:1: Invalid bytes literal: Illegal escape sequence: " "Unicode escape sequence \\U cannot be used in bytes literals\n | " "b'\\UFFFFFFFF'\n | ^"}, {"a.?b[?0] && a[?c]", "_&&_(\n _[?_](\n _?._(\n a^#1:Expr.Ident#,\n " "\"b\"^#3:string#\n )^#2:Expr.Call#,\n 0^#5:int64#\n " ")^#4:Expr.Call#,\n _[?_](\n a^#6:Expr.Ident#,\n " "c^#8:Expr.Ident#\n )^#7:Expr.Call#\n)^#9:Expr.Call#"}, {"{?'key': value}", "{\n " "?\"key\"^#3:string#:value^#4:Expr.Ident#^#2:Expr.CreateStruct.Entry#\n}^#" "1:Expr.CreateStruct#"}, {"[?a, ?b]", "[\n ?a^#2:Expr.Ident#,\n ?b^#3:Expr.Ident#\n]^#1:Expr.CreateList#"}, {"[?a[?b]]", "[\n ?_[?_](\n a^#2:Expr.Ident#,\n b^#4:Expr.Ident#\n " ")^#3:Expr.Call#\n]^#1:Expr.CreateList#"}, {"Msg{?field: value}", "Msg{\n " "?field:value^#3:Expr.Ident#^#2:Expr.CreateStruct.Entry#\n}^#1:Expr." "CreateStruct#"}, {"m.optMap(v, f)", "_?_:_(\n m^#1:Expr.Ident#.hasValue()^#6:Expr.Call#,\n optional.of(\n " " __comprehension__(\n "Target\n []^#7:Expr.CreateList#,\n " "LoopCondition\n false^#9:bool#,\n "v^#3:Expr.Ident#,\n "f^#4:Expr.Ident#)^#10:Expr.Comprehension#\n )^#11:Expr.Call#,\n " "optional.none()^#12:Expr.Call#\n)^#13:Expr.Call#"}, {"m.optFlatMap(v, f)", "_?_:_(\n m^#1:Expr.Ident#.hasValue()^#6:Expr.Call#,\n " "__comprehension__(\n "[]^#7:Expr.CreateList#,\n "m^#5:Expr.Ident#.value()^#8:Expr.Call#,\n "false^#9:bool#,\n " f^#4:Expr.Ident#)^#10:Expr.Comprehension#,\n " "optional.none()^#11:Expr.Call#\n)^#12:Expr.Call#"}}; class KindAndIdAdorner : public testutil::ExpressionAdorner { public: explicit KindAndIdAdorner( const google::api::expr::v1alpha1::SourceInfo& source_info = google::api::expr::v1alpha1::SourceInfo::default_instance()) : source_info_(source_info) {} std::string adorn(const Expr& e) const override { if (source_info_.macro_calls_size() != 0 && source_info_.macro_calls().contains(e.id())) { return absl::StrFormat( "^#%d:%s#", e.id(), source_info_.macro_calls().at(e.id()).call_expr().function()); } if (e.has_const_expr()) { auto& const_expr = e.const_expr(); auto reflection = const_expr.GetReflection(); auto oneof = const_expr.GetDescriptor()->FindOneofByName("constant_kind"); auto field_desc = reflection->GetOneofFieldDescriptor(const_expr, oneof); auto enum_desc = field_desc->enum_type(); if (enum_desc) { return absl::StrFormat("^#%d:%s#", e.id(), nameChain(enum_desc)); } else { return absl::StrFormat("^#%d:%s#", e.id(), field_desc->type_name()); } } else { auto reflection = e.GetReflection(); auto oneof = e.GetDescriptor()->FindOneofByName("expr_kind"); auto desc = reflection->GetOneofFieldDescriptor(e, oneof)->message_type(); return absl::StrFormat("^#%d:%s#", e.id(), nameChain(desc)); } } std::string adorn(const Expr::CreateStruct::Entry& e) const override { return absl::StrFormat("^#%d:Expr.CreateStruct.Entry#", e.id()); } private: template <class T> std::string nameChain(const T* descriptor) const { std::list<std::string> name_chain{descriptor->name()}; const google::protobuf::Descriptor* desc = descriptor->containing_type(); while (desc) { name_chain.push_front(desc->name()); desc = desc->containing_type(); } return absl::StrJoin(name_chain, "."); } const google::api::expr::v1alpha1::SourceInfo& source_info_; }; class LocationAdorner : public testutil::ExpressionAdorner { public: explicit LocationAdorner(const google::api::expr::v1alpha1::SourceInfo& source_info) : source_info_(source_info) {} absl::optional<std::pair<int32_t, int32_t>> getLocation(int64_t id) const { absl::optional<std::pair<int32_t, int32_t>> location; const auto& positions = source_info_.positions(); if (positions.find(id) == positions.end()) { return location; } int32_t pos = positions.at(id); int32_t line = 1; for (int i = 0; i < source_info_.line_offsets_size(); ++i) { if (source_info_.line_offsets(i) > pos) { break; } else { line += 1; } } int32_t col = pos; if (line > 1) { col = pos - source_info_.line_offsets(line - 2); } return std::make_pair(line, col); } std::string adorn(const Expr& e) const override { auto loc = getLocation(e.id()); if (loc) { return absl::StrFormat("^#%d[%d,%d]#", e.id(), loc->first, loc->second); } else { return absl::StrFormat("^#%d[NO_POS]#", e.id()); } } std::string adorn(const Expr::CreateStruct::Entry& e) const override { auto loc = getLocation(e.id()); if (loc) { return absl::StrFormat("^#%d[%d,%d]#", e.id(), loc->first, loc->second); } else { return absl::StrFormat("^#%d[NO_POS]#", e.id()); } } private: template <class T> std::string nameChain(const T* descriptor) const { std::list<std::string> name_chain{descriptor->name()}; const google::protobuf::Descriptor* desc = descriptor->containing_type(); while (desc) { name_chain.push_front(desc->name()); desc = desc->containing_type(); } return absl::StrJoin(name_chain, "."); } private: const google::api::expr::v1alpha1::SourceInfo& source_info_; }; std::string ConvertEnrichedSourceInfoToString( const EnrichedSourceInfo& enriched_source_info) { std::vector<std::string> offsets; for (const auto& offset : enriched_source_info.offsets()) { offsets.push_back(absl::StrFormat( "[%d,%d,%d]", offset.first, offset.second.first, offset.second.second)); } return absl::StrJoin(offsets, "^#"); } std::string ConvertMacroCallsToString( const google::api::expr::v1alpha1::SourceInfo& source_info) { KindAndIdAdorner macro_calls_adorner(source_info); testutil::ExprPrinter w(macro_calls_adorner); std::vector<std::pair<int64_t, google::api::expr::v1alpha1::Expr>> macro_calls; for (auto pair : source_info.macro_calls()) { pair.second.set_id(pair.first); macro_calls.push_back(pair); } absl::c_sort(macro_calls, [](const std::pair<int64_t, google::api::expr::v1alpha1::Expr>& p1, const std::pair<int64_t, google::api::expr::v1alpha1::Expr>& p2) { return p1.first > p2.first; }); std::string result = ""; for (const auto& pair : macro_calls) { result += w.print(pair.second) += ",\n"; } return result.substr(0, result.size() - 3); } class ExpressionTest : public testing::TestWithParam<TestInfo> {}; TEST_P(ExpressionTest, Parse) { const TestInfo& test_info = GetParam(); ParserOptions options; if (!test_info.M.empty()) { options.add_macro_calls = true; } options.enable_optional_syntax = true; std::vector<Macro> macros = Macro::AllMacros(); macros.push_back(cel::OptMapMacro()); macros.push_back(cel::OptFlatMapMacro()); auto result = EnrichedParse(test_info.I, macros, "<input>", options); if (test_info.E.empty()) { EXPECT_THAT(result, IsOk()); } else { EXPECT_THAT(result, Not(IsOk())); EXPECT_EQ(test_info.E, result.status().message()); } if (!test_info.P.empty()) { KindAndIdAdorner kind_and_id_adorner; testutil::ExprPrinter w(kind_and_id_adorner); std::string adorned_string = w.print(result->parsed_expr().expr()); EXPECT_EQ(test_info.P, adorned_string) << result->parsed_expr(); } if (!test_info.L.empty()) { LocationAdorner location_adorner(result->parsed_expr().source_info()); testutil::ExprPrinter w(location_adorner); std::string adorned_string = w.print(result->parsed_expr().expr()); EXPECT_EQ(test_info.L, adorned_string) << result->parsed_expr(); ; } if (!test_info.R.empty()) { EXPECT_EQ(test_info.R, ConvertEnrichedSourceInfoToString( result->enriched_source_info())); } if (!test_info.M.empty()) { EXPECT_EQ(test_info.M, ConvertMacroCallsToString( result.value().parsed_expr().source_info())) << result->parsed_expr(); ; } } TEST(ExpressionTest, TsanOom) { Parse( "[[a([[???[a[[??[a([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[???[" "a([[????") .IgnoreError(); } TEST(ExpressionTest, ErrorRecoveryLimits) { ParserOptions options; options.error_recovery_limit = 1; auto result = Parse("......", "", options); EXPECT_THAT(result, Not(IsOk())); EXPECT_EQ(result.status().message(), "ERROR: :1:1: Syntax error: More than 1 parse errors.\n | ......\n " "| ^\nERROR: :1:2: Syntax error: no viable alternative at input " "'..'\n | ......\n | .^"); } TEST(ExpressionTest, ExpressionSizeLimit) { ParserOptions options; options.expression_size_codepoint_limit = 10; auto result = Parse("...............", "", options); EXPECT_THAT(result, Not(IsOk())); EXPECT_EQ( result.status().message(), "expression size exceeds codepoint limit. input size: 15, limit: 10"); } TEST(ExpressionTest, RecursionDepthLongArgList) { ParserOptions options; options.max_recursion_depth = 16; EXPECT_THAT(Parse("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", "", options), IsOk()); } TEST(ExpressionTest, RecursionDepthExceeded) { ParserOptions options; options.max_recursion_depth = 6; auto result = Parse("1 + 2 + 3 + 4 + 5 + 6 + 7", "", options); EXPECT_THAT(result, Not(IsOk())); EXPECT_THAT(result.status().message(), HasSubstr("Exceeded max recursion depth of 6 when parsing.")); } TEST(ExpressionTest, RecursionDepthIgnoresParentheses) { ParserOptions options; options.max_recursion_depth = 6; auto result = Parse("(((1 + 2 + 3 + 4 + (5 + 6))))", "", options); EXPECT_THAT(result, IsOk()); } std::string TestName(const testing::TestParamInfo<TestInfo>& test_info) { std::string name = absl::StrCat(test_info.index, "-", test_info.param.I); absl::c_replace_if(name, [](char c) { return !absl::ascii_isalnum(c); }, '_'); return name; return name; } INSTANTIATE_TEST_SUITE_P(CelParserTest, ExpressionTest, testing::ValuesIn(test_cases), TestName); void BM_Parse(benchmark::State& state) { std::vector<Macro> macros = Macro::AllMacros(); for (auto s : state) { for (const auto& test_case : test_cases) { if (test_case.benchmark) { benchmark::DoNotOptimize(ParseWithMacros(test_case.I, macros)); } } } } BENCHMARK(BM_Parse)->ThreadRange(1, std::thread::hardware_concurrency()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/parser/parser.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/parser/parser_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e5b7ba67-593a-44d6-b196-01c568b6ef37
cpp
google/cel-cpp
macro_registry
parser/macro_registry.cc
parser/macro_registry_test.cc
#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 ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::testing::Eq; using ::testing::Ne; 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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/parser/macro_registry.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/parser/macro_registry_test.cc
4552db5798fb0853b131b783d8875794334fae7f
fe64423d-2070-423e-8f2c-0338e81ff7d7
cpp
google/cel-cpp
bindings_ext
extensions/bindings_ext.cc
extensions/bindings_ext_test.cc
#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 <cstdint> #include <memory> #include <string> #include <tuple> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.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 "eval/public/testing/matchers.h" #include "internal/testing.h" #include "parser/macro.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 ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::v1alpha1::SourceInfo; using ::google::api::expr::parser::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::runtime::test::IsCelInt64; using ::google::api::expr::test::v1::proto2::NestedTestAllTypes; using ::google::protobuf::Arena; using ::google::protobuf::TextFormat; using ::testing::Contains; using ::testing::HasSubstr; using ::testing::Pair; 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, Default) { 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); } TEST_P(BindingsExtTest, Tracing) { 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->Trace(activation, &arena, [](int64_t, const CelValue&, google::protobuf::Arena*) { return absl::OkStatus(); })); 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 kTraceExpr = R"pb( expr: { id: 11 comprehension_expr: { iter_var: "#unused" iter_range: { id: 8 list_expr: {} } accu_var: "x" accu_init: { id: 4 const_expr: { int64_value: 20 } } loop_condition: { id: 9 const_expr: { bool_value: false } } loop_step: { id: 10 ident_expr: { name: "x" } } result: { id: 6 call_expr: { function: "_*_" args: { id: 5 ident_expr: { name: "x" } } args: { id: 7 ident_expr: { name: "x" } } } } } })pb"; TEST(BindingsExtTest, TraceSupport) { ParsedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kTraceExpr, &expr)); InterpreterOptions options; options.enable_heterogeneous_equality = true; options.enable_empty_wrapper_null_unboxing = true; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN( auto plan, builder->CreateExpression(&expr.expr(), &expr.source_info())); Activation activation; google::protobuf::Arena arena; absl::flat_hash_map<int64_t, CelValue> ids; ASSERT_OK_AND_ASSIGN( auto result, plan->Trace(activation, &arena, [&](int64_t id, const CelValue& value, google::protobuf::Arena* arena) { ids[id] = value; return absl::OkStatus(); })); EXPECT_TRUE(result.IsInt64() && result.Int64OrDie() == 400) << result.DebugString(); EXPECT_THAT(ids, Contains(Pair(4, IsCelInt64(20)))); EXPECT_THAT(ids, Contains(Pair(7, IsCelInt64(20)))); } 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()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/bindings_ext.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/bindings_ext_test.cc
4552db5798fb0853b131b783d8875794334fae7f
3f6d82ef-f7d8-4ac5-a96a-0301c89d3a59
cpp
google/cel-cpp
math_ext
extensions/math_ext.cc
extensions/math_ext_test.cc
#include "extensions/math_ext.h" #include <cmath> #include <cstdint> #include <limits> #include "absl/base/casts.h" #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.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(const Value& value, absl::string_view function) { if (auto int_value = As<IntValue>(value); int_value) { return CelNumber::FromInt64(int_value->NativeValue()); } if (auto uint_value = As<UintValue>(value); uint_value) { return CelNumber::FromUint64(uint_value->NativeValue()); } if (auto double_value = As<DoubleValue>(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(); } double CeilDouble(ValueManager&, double value) { return std::ceil(value); } double FloorDouble(ValueManager&, double value) { return std::floor(value); } double RoundDouble(ValueManager&, double value) { return std::round(value); } double TruncDouble(ValueManager&, double value) { return std::trunc(value); } bool IsInfDouble(ValueManager&, double value) { return std::isinf(value); } bool IsNaNDouble(ValueManager&, double value) { return std::isnan(value); } bool IsFiniteDouble(ValueManager&, double value) { return std::isfinite(value); } double AbsDouble(ValueManager&, double value) { return std::fabs(value); } Value AbsInt(ValueManager& value_manager, int64_t value) { if (ABSL_PREDICT_FALSE(value == std::numeric_limits<int64_t>::min())) { return ErrorValue(absl::InvalidArgumentError("integer overflow")); } return IntValue(value < 0 ? -value : value); } uint64_t AbsUint(ValueManager&, uint64_t value) { return value; } double SignDouble(ValueManager&, double value) { if (std::isnan(value)) { return value; } if (value == 0.0) { return 0.0; } return std::signbit(value) ? -1.0 : 1.0; } int64_t SignInt(ValueManager&, int64_t value) { return value < 0 ? -1 : value > 0 ? 1 : 0; } uint64_t SignUint(ValueManager&, uint64_t value) { return value == 0 ? 0 : 1; } int64_t BitAndInt(ValueManager&, int64_t lhs, int64_t rhs) { return lhs & rhs; } uint64_t BitAndUint(ValueManager&, uint64_t lhs, uint64_t rhs) { return lhs & rhs; } int64_t BitOrInt(ValueManager&, int64_t lhs, int64_t rhs) { return lhs | rhs; } uint64_t BitOrUint(ValueManager&, uint64_t lhs, uint64_t rhs) { return lhs | rhs; } int64_t BitXorInt(ValueManager&, int64_t lhs, int64_t rhs) { return lhs ^ rhs; } uint64_t BitXorUint(ValueManager&, uint64_t lhs, uint64_t rhs) { return lhs ^ rhs; } int64_t BitNotInt(ValueManager&, int64_t value) { return ~value; } uint64_t BitNotUint(ValueManager&, uint64_t value) { return ~value; } Value BitShiftLeftInt(ValueManager&, int64_t lhs, int64_t rhs) { if (ABSL_PREDICT_FALSE(rhs < 0)) { return ErrorValue(absl::InvalidArgumentError( absl::StrCat("math.bitShiftLeft() invalid negative shift: ", rhs))); } if (rhs > 63) { return IntValue(0); } return IntValue(lhs << static_cast<int>(rhs)); } Value BitShiftLeftUint(ValueManager&, uint64_t lhs, int64_t rhs) { if (ABSL_PREDICT_FALSE(rhs < 0)) { return ErrorValue(absl::InvalidArgumentError( absl::StrCat("math.bitShiftLeft() invalid negative shift: ", rhs))); } if (rhs > 63) { return UintValue(0); } return UintValue(lhs << static_cast<int>(rhs)); } Value BitShiftRightInt(ValueManager&, int64_t lhs, int64_t rhs) { if (ABSL_PREDICT_FALSE(rhs < 0)) { return ErrorValue(absl::InvalidArgumentError( absl::StrCat("math.bitShiftRight() invalid negative shift: ", rhs))); } if (rhs > 63) { return IntValue(0); } return IntValue(absl::bit_cast<int64_t>(absl::bit_cast<uint64_t>(lhs) >> static_cast<int>(rhs))); } Value BitShiftRightUint(ValueManager&, uint64_t lhs, int64_t rhs) { if (ABSL_PREDICT_FALSE(rhs < 0)) { return ErrorValue(absl::InvalidArgumentError( absl::StrCat("math.bitShiftRight() invalid negative shift: ", rhs))); } if (rhs > 63) { return UintValue(0); } return UintValue(lhs >> static_cast<int>(rhs)); } } 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))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor( "math.ceil", false), UnaryFunctionAdapter<double, double>::WrapFunction(CeilDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor( "math.floor", false), UnaryFunctionAdapter<double, double>::WrapFunction(FloorDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor( "math.round", false), UnaryFunctionAdapter<double, double>::WrapFunction(RoundDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor( "math.trunc", false), UnaryFunctionAdapter<double, double>::WrapFunction(TruncDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<bool, double>::CreateDescriptor( "math.isInf", false), UnaryFunctionAdapter<bool, double>::WrapFunction(IsInfDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<bool, double>::CreateDescriptor( "math.isNaN", false), UnaryFunctionAdapter<bool, double>::WrapFunction(IsNaNDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<bool, double>::CreateDescriptor( "math.isFinite", false), UnaryFunctionAdapter<bool, double>::WrapFunction(IsFiniteDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor( "math.abs", false), UnaryFunctionAdapter<double, double>::WrapFunction(AbsDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, int64_t>::CreateDescriptor( "math.abs", false), UnaryFunctionAdapter<Value, int64_t>::WrapFunction(AbsInt))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<uint64_t, uint64_t>::CreateDescriptor( "math.abs", false), UnaryFunctionAdapter<uint64_t, uint64_t>::WrapFunction(AbsUint))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor( "math.sign", false), UnaryFunctionAdapter<double, double>::WrapFunction(SignDouble))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<int64_t, int64_t>::CreateDescriptor( "math.sign", false), UnaryFunctionAdapter<int64_t, int64_t>::WrapFunction(SignInt))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<uint64_t, uint64_t>::CreateDescriptor( "math.sign", false), UnaryFunctionAdapter<uint64_t, uint64_t>::WrapFunction(SignUint))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<int64_t, int64_t, int64_t>::CreateDescriptor( "math.bitAnd", false), BinaryFunctionAdapter<int64_t, int64_t, int64_t>::WrapFunction( BitAndInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<uint64_t, uint64_t, uint64_t>::CreateDescriptor( "math.bitAnd", false), BinaryFunctionAdapter<uint64_t, uint64_t, uint64_t>::WrapFunction( BitAndUint))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<int64_t, int64_t, int64_t>::CreateDescriptor( "math.bitOr", false), BinaryFunctionAdapter<int64_t, int64_t, int64_t>::WrapFunction( BitOrInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<uint64_t, uint64_t, uint64_t>::CreateDescriptor( "math.bitOr", false), BinaryFunctionAdapter<uint64_t, uint64_t, uint64_t>::WrapFunction( BitOrUint))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<int64_t, int64_t, int64_t>::CreateDescriptor( "math.bitXor", false), BinaryFunctionAdapter<int64_t, int64_t, int64_t>::WrapFunction( BitXorInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<uint64_t, uint64_t, uint64_t>::CreateDescriptor( "math.bitXor", false), BinaryFunctionAdapter<uint64_t, uint64_t, uint64_t>::WrapFunction( BitXorUint))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<int64_t, int64_t>::CreateDescriptor( "math.bitNot", false), UnaryFunctionAdapter<int64_t, int64_t>::WrapFunction(BitNotInt))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<uint64_t, uint64_t>::CreateDescriptor( "math.bitNot", false), UnaryFunctionAdapter<uint64_t, uint64_t>::WrapFunction(BitNotUint))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, int64_t, int64_t>::CreateDescriptor( "math.bitShiftLeft", false), BinaryFunctionAdapter<Value, int64_t, int64_t>::WrapFunction( BitShiftLeftInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, uint64_t, int64_t>::CreateDescriptor( "math.bitShiftLeft", false), BinaryFunctionAdapter<Value, uint64_t, int64_t>::WrapFunction( BitShiftLeftUint))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, int64_t, int64_t>::CreateDescriptor( "math.bitShiftRight", false), BinaryFunctionAdapter<Value, int64_t, int64_t>::WrapFunction( BitShiftRightInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, uint64_t, int64_t>::CreateDescriptor( "math.bitShiftRight", false), BinaryFunctionAdapter<Value, uint64_t, int64_t>::WrapFunction( BitShiftRightUint))); 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 ::absl_testing::StatusIs; 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; 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)", }, })); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/math_ext.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/math_ext_test.cc
4552db5798fb0853b131b783d8875794334fae7f
b9511aae-495e-4df9-8c02-e84d9e35edec
cpp
google/cel-cpp
sets_functions
extensions/sets_functions.cc
extensions/sets_functions_test.cc
#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](const Value& sublist_element) -> absl::StatusOr<bool> { CEL_ASSIGN_OR_RETURN(auto contains, list.Contains(value_factory, sublist_element)); any_missing = !contains->Is<BoolValue>() || !contains.GetBool().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](const Value& list_element) -> absl::StatusOr<bool> { CEL_ASSIGN_OR_RETURN(auto contains, sublist.Contains(value_factory, list_element)); exists = contains->Is<BoolValue>() && contains.GetBool().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.GetBool().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 ::absl_testing::IsOk; using ::google::protobuf::Arena; 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}])"}, })); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/sets_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/sets_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
f7d0dad8-0b4f-4a8e-b3dc-80d73139d3c7
cpp
google/cel-cpp
value
common/value.cc
common/value_test.cc
#include "common/value.h" #include <array> #include <cstddef> #include <cstdint> #include <memory> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/log/absl_log.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/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 "common/json.h" #include "common/optional_ref.h" #include "common/type.h" #include "common/value_kind.h" #include "common/values/values.h" #include "internal/status_macros.h" #include "runtime/runtime_options.h" #include "google/protobuf/descriptor.h" namespace cel { namespace { static constexpr std::array<ValueKind, 25> kValueToKindArray = { ValueKind::kError, ValueKind::kBool, ValueKind::kBytes, ValueKind::kDouble, ValueKind::kDuration, ValueKind::kError, ValueKind::kInt, ValueKind::kList, ValueKind::kList, ValueKind::kList, ValueKind::kList, ValueKind::kMap, ValueKind::kMap, ValueKind::kMap, ValueKind::kMap, ValueKind::kNull, ValueKind::kOpaque, ValueKind::kString, ValueKind::kStruct, ValueKind::kStruct, ValueKind::kStruct, ValueKind::kTimestamp, ValueKind::kType, ValueKind::kUint, ValueKind::kUnknown}; static_assert(kValueToKindArray.size() == absl::variant_size<common_internal::ValueVariant>(), "Kind indexer must match variant declaration for cel::Value."); } Type Value::GetRuntimeType() const { AssertIsValid(); switch (kind()) { case ValueKind::kNull: return NullType(); case ValueKind::kBool: return BoolType(); case ValueKind::kInt: return IntType(); case ValueKind::kUint: return UintType(); case ValueKind::kDouble: return DoubleType(); case ValueKind::kString: return StringType(); case ValueKind::kBytes: return BytesType(); case ValueKind::kStruct: return this->GetStruct().GetRuntimeType(); case ValueKind::kDuration: return DurationType(); case ValueKind::kTimestamp: return TimestampType(); case ValueKind::kList: return ListType(); case ValueKind::kMap: return MapType(); case ValueKind::kUnknown: return UnknownType(); case ValueKind::kType: return TypeType(); case ValueKind::kError: return ErrorType(); case ValueKind::kOpaque: return this->GetOpaque().GetRuntimeType(); default: return cel::Type(); } } ValueKind Value::kind() const { ABSL_DCHECK_NE(variant_.index(), 0) << "kind() called on uninitialized cel::Value."; return kValueToKindArray[variant_.index()]; } absl::string_view Value::GetTypeName() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> absl::string_view { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::string_view(); } else { return alternative.GetTypeName(); } }, variant_); } std::string Value::DebugString() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> std::string { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return std::string(); } else { return alternative.DebugString(); } }, variant_); } absl::Status Value::SerializeTo(AnyToJsonConverter& value_manager, absl::Cord& value) const { AssertIsValid(); return absl::visit( [&value_manager, &value](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid Value"); } else { return alternative.SerializeTo(value_manager, value); } }, variant_); } absl::StatusOr<Json> Value::ConvertToJson( AnyToJsonConverter& value_manager) const { AssertIsValid(); return absl::visit( [&value_manager](const auto& alternative) -> absl::StatusOr<Json> { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid Value"); } else { return alternative.ConvertToJson(value_manager); } }, variant_); } absl::Status Value::Equal(ValueManager& value_manager, const Value& other, Value& result) const { AssertIsValid(); return absl::visit( [&value_manager, &other, &result](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid Value"); } else { return alternative.Equal(value_manager, other, result); } }, variant_); } absl::StatusOr<Value> Value::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } bool Value::IsZeroValue() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> bool { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return false; } else { return alternative.IsZeroValue(); } }, variant_); } std::ostream& operator<<(std::ostream& out, const Value& value) { return absl::visit( [&out](const auto& alternative) -> std::ostream& { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return out << "default ctor Value"; } else { return out << alternative; } }, value.variant_); } absl::StatusOr<Value> BytesValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> ErrorValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> ListValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> MapValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> OpaqueValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> StringValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> StructValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> TypeValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::StatusOr<Value> UnknownValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::Status ListValue::Get(ValueManager& value_manager, size_t index, Value& result) const { return absl::visit( [&value_manager, index, &result](const auto& alternative) -> absl::Status { return alternative.Get(value_manager, index, result); }, variant_); } absl::StatusOr<Value> ListValue::Get(ValueManager& value_manager, size_t index) const { Value result; CEL_RETURN_IF_ERROR(Get(value_manager, index, result)); return result; } absl::Status ListValue::ForEach(ValueManager& value_manager, ForEachCallback callback) const { return absl::visit( [&value_manager, callback](const auto& alternative) -> absl::Status { return alternative.ForEach(value_manager, callback); }, variant_); } absl::Status ListValue::ForEach(ValueManager& value_manager, ForEachWithIndexCallback callback) const { return absl::visit( [&value_manager, callback](const auto& alternative) -> absl::Status { return alternative.ForEach(value_manager, callback); }, variant_); } absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> ListValue::NewIterator( ValueManager& value_manager) const { return absl::visit( [&value_manager](const auto& alternative) -> absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> { return alternative.NewIterator(value_manager); }, variant_); } absl::Status ListValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { return absl::visit( [&value_manager, &other, &result](const auto& alternative) -> absl::Status { return alternative.Equal(value_manager, other, result); }, variant_); } absl::Status ListValue::Contains(ValueManager& value_manager, const Value& other, Value& result) const { return absl::visit( [&value_manager, &other, &result](const auto& alternative) -> absl::Status { return alternative.Contains(value_manager, other, result); }, variant_); } absl::StatusOr<Value> ListValue::Contains(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Contains(value_manager, other, result)); return result; } absl::Status MapValue::Get(ValueManager& value_manager, const Value& key, Value& result) const { return absl::visit( [&value_manager, &key, &result](const auto& alternative) -> absl::Status { return alternative.Get(value_manager, key, result); }, variant_); } absl::StatusOr<Value> MapValue::Get(ValueManager& value_manager, const Value& key) const { Value result; CEL_RETURN_IF_ERROR(Get(value_manager, key, result)); return result; } absl::StatusOr<bool> MapValue::Find(ValueManager& value_manager, const Value& key, Value& result) const { return absl::visit( [&value_manager, &key, &result](const auto& alternative) -> absl::StatusOr<bool> { return alternative.Find(value_manager, key, result); }, variant_); } absl::StatusOr<std::pair<Value, bool>> MapValue::Find( ValueManager& value_manager, const Value& key) const { Value result; CEL_ASSIGN_OR_RETURN(auto ok, Find(value_manager, key, result)); return std::pair{std::move(result), ok}; } absl::Status MapValue::Has(ValueManager& value_manager, const Value& key, Value& result) const { return absl::visit( [&value_manager, &key, &result](const auto& alternative) -> absl::Status { return alternative.Has(value_manager, key, result); }, variant_); } absl::StatusOr<Value> MapValue::Has(ValueManager& value_manager, const Value& key) const { Value result; CEL_RETURN_IF_ERROR(Has(value_manager, key, result)); return result; } absl::Status MapValue::ListKeys(ValueManager& value_manager, ListValue& result) const { return absl::visit( [&value_manager, &result](const auto& alternative) -> absl::Status { return alternative.ListKeys(value_manager, result); }, variant_); } absl::StatusOr<ListValue> MapValue::ListKeys( ValueManager& value_manager) const { ListValue result; CEL_RETURN_IF_ERROR(ListKeys(value_manager, result)); return result; } absl::Status MapValue::ForEach(ValueManager& value_manager, ForEachCallback callback) const { return absl::visit( [&value_manager, callback](const auto& alternative) -> absl::Status { return alternative.ForEach(value_manager, callback); }, variant_); } absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> MapValue::NewIterator( ValueManager& value_manager) const { return absl::visit( [&value_manager](const auto& alternative) -> absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> { return alternative.NewIterator(value_manager); }, variant_); } absl::Status MapValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { return absl::visit( [&value_manager, &other, &result](const auto& alternative) -> absl::Status { return alternative.Equal(value_manager, other, result); }, variant_); } absl::Status StructValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options) const { AssertIsValid(); return absl::visit( [&value_manager, name, &result, unboxing_options](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.GetFieldByName(value_manager, name, result, unboxing_options); } }, variant_); } absl::StatusOr<Value> StructValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, ProtoWrapperTypeOptions unboxing_options) const { Value result; CEL_RETURN_IF_ERROR( GetFieldByName(value_manager, name, result, unboxing_options)); return result; } absl::Status StructValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options) const { AssertIsValid(); return absl::visit( [&value_manager, number, &result, unboxing_options](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.GetFieldByNumber(value_manager, number, result, unboxing_options); } }, variant_); } absl::StatusOr<Value> StructValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, ProtoWrapperTypeOptions unboxing_options) const { Value result; CEL_RETURN_IF_ERROR( GetFieldByNumber(value_manager, number, result, unboxing_options)); return result; } absl::Status StructValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { AssertIsValid(); return absl::visit( [&value_manager, &other, &result](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.Equal(value_manager, other, result); } }, variant_); } absl::Status StructValue::ForEachField(ValueManager& value_manager, ForEachFieldCallback callback) const { AssertIsValid(); return absl::visit( [&value_manager, callback](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.ForEachField(value_manager, callback); } }, variant_); } absl::StatusOr<int> StructValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const { AssertIsValid(); return absl::visit( [&value_manager, qualifiers, presence_test, &result](const auto& alternative) -> absl::StatusOr<int> { if constexpr (std::is_same_v< absl::remove_cvref_t<decltype(alternative)>, absl::monostate>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.Qualify(value_manager, qualifiers, presence_test, result); } }, variant_); } absl::StatusOr<std::pair<Value, int>> StructValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test) const { Value result; CEL_ASSIGN_OR_RETURN( auto count, Qualify(value_manager, qualifiers, presence_test, result)); return std::pair{std::move(result), count}; } Value Value::Enum(absl::Nonnull<const google::protobuf::EnumValueDescriptor*> value) { ABSL_DCHECK(value != nullptr); if (value->type()->full_name() == "google.protobuf.NullValue") { ABSL_DCHECK_EQ(value->number(), 0); return NullValue(); } return IntValue(value->number()); } Value Value::Enum(absl::Nonnull<const google::protobuf::EnumDescriptor*> type, int32_t number) { ABSL_DCHECK(type != nullptr); if (type->full_name() == "google.protobuf.NullValue") { ABSL_DCHECK_EQ(number, 0); return NullValue(); } if (type->is_closed()) { if (ABSL_PREDICT_FALSE(type->FindValueByNumber(number) == nullptr)) { return ErrorValue(absl::InvalidArgumentError(absl::StrCat( "closed enum has no such value: ", type->full_name(), ".", number))); } } return IntValue(number); } absl::optional<BoolValue> Value::AsBool() const { if (const auto* alternative = absl::get_if<BoolValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } optional_ref<const BytesValue> Value::AsBytes() const& { if (const auto* alternative = absl::get_if<BytesValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<BytesValue> Value::AsBytes() && { if (auto* alternative = absl::get_if<BytesValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<DoubleValue> Value::AsDouble() const { if (const auto* alternative = absl::get_if<DoubleValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<DurationValue> Value::AsDuration() const { if (const auto* alternative = absl::get_if<DurationValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } optional_ref<const ErrorValue> Value::AsError() const& { if (const auto* alternative = absl::get_if<ErrorValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ErrorValue> Value::AsError() && { if (auto* alternative = absl::get_if<ErrorValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<IntValue> Value::AsInt() const { if (const auto* alternative = absl::get_if<IntValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ListValue> Value::AsList() const& { if (const auto* alternative = absl::get_if<common_internal::LegacyListValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedListValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedRepeatedFieldValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedJsonListValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ListValue> Value::AsList() && { if (auto* alternative = absl::get_if<common_internal::LegacyListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedRepeatedFieldValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedJsonListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<MapValue> Value::AsMap() const& { if (const auto* alternative = absl::get_if<common_internal::LegacyMapValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedMapValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedMapFieldValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedJsonMapValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<MapValue> Value::AsMap() && { if (auto* alternative = absl::get_if<common_internal::LegacyMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedMapFieldValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedJsonMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<MessageValue> Value::AsMessage() const& { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<MessageValue> Value::AsMessage() && { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<NullValue> Value::AsNull() const { if (const auto* alternative = absl::get_if<NullValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } optional_ref<const OpaqueValue> Value::AsOpaque() const& { if (const auto* alternative = absl::get_if<OpaqueValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<OpaqueValue> Value::AsOpaque() && { if (auto* alternative = absl::get_if<OpaqueValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const OptionalValue> Value::AsOptional() const& { if (const auto* alternative = absl::get_if<OpaqueValue>(&variant_); alternative != nullptr && alternative->IsOptional()) { return static_cast<const OptionalValue&>(*alternative); } return absl::nullopt; } absl::optional<OptionalValue> Value::AsOptional() && { if (auto* alternative = absl::get_if<OpaqueValue>(&variant_); alternative != nullptr && alternative->IsOptional()) { return static_cast<OptionalValue&&>(*alternative); } return absl::nullopt; } optional_ref<const ParsedJsonListValue> Value::AsParsedJsonList() const& { if (const auto* alternative = absl::get_if<ParsedJsonListValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedJsonListValue> Value::AsParsedJsonList() && { if (auto* alternative = absl::get_if<ParsedJsonListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedJsonMapValue> Value::AsParsedJsonMap() const& { if (const auto* alternative = absl::get_if<ParsedJsonMapValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedJsonMapValue> Value::AsParsedJsonMap() && { if (auto* alternative = absl::get_if<ParsedJsonMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedListValue> Value::AsParsedList() const& { if (const auto* alternative = absl::get_if<ParsedListValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedListValue> Value::AsParsedList() && { if (auto* alternative = absl::get_if<ParsedListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedMapValue> Value::AsParsedMap() const& { if (const auto* alternative = absl::get_if<ParsedMapValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedMapValue> Value::AsParsedMap() && { if (auto* alternative = absl::get_if<ParsedMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedMapFieldValue> Value::AsParsedMapField() const& { if (const auto* alternative = absl::get_if<ParsedMapFieldValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedMapFieldValue> Value::AsParsedMapField() && { if (auto* alternative = absl::get_if<ParsedMapFieldValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedMessageValue> Value::AsParsedMessage() const& { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedMessageValue> Value::AsParsedMessage() && { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedRepeatedFieldValue> Value::AsParsedRepeatedField() const& { if (const auto* alternative = absl::get_if<ParsedRepeatedFieldValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedRepeatedFieldValue> Value::AsParsedRepeatedField() && { if (auto* alternative = absl::get_if<ParsedRepeatedFieldValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedStructValue> Value::AsParsedStruct() const& { if (const auto* alternative = absl::get_if<ParsedStructValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedStructValue> Value::AsParsedStruct() && { if (auto* alternative = absl::get_if<ParsedStructValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const StringValue> Value::AsString() const& { if (const auto* alternative = absl::get_if<StringValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<StringValue> Value::AsString() && { if (auto* alternative = absl::get_if<StringValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<StructValue> Value::AsStruct() const& { if (const auto* alternative = absl::get_if<common_internal::LegacyStructValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedStructValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<StructValue> Value::AsStruct() && { if (auto* alternative = absl::get_if<common_internal::LegacyStructValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedStructValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<TimestampValue> Value::AsTimestamp() const { if (const auto* alternative = absl::get_if<TimestampValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } optional_ref<const TypeValue> Value::AsType() const& { if (const auto* alternative = absl::get_if<TypeValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<TypeValue> Value::AsType() && { if (auto* alternative = absl::get_if<TypeValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<UintValue> Value::AsUint() const { if (const auto* alternative = absl::get_if<UintValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } optional_ref<const UnknownValue> Value::AsUnknown() const& { if (const auto* alternative = absl::get_if<UnknownValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<UnknownValue> Value::AsUnknown() && { if (auto* alternative = absl::get_if<UnknownValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } BoolValue Value::GetBool() const { ABSL_DCHECK(IsBool()) << *this; return absl::get<BoolValue>(variant_); } const BytesValue& Value::GetBytes() const& { ABSL_DCHECK(IsBytes()) << *this; return absl::get<BytesValue>(variant_); } BytesValue Value::GetBytes() && { ABSL_DCHECK(IsBytes()) << *this; return absl::get<BytesValue>(std::move(variant_)); } DoubleValue Value::GetDouble() const { ABSL_DCHECK(IsDouble()) << *this; return absl::get<DoubleValue>(variant_); } DurationValue Value::GetDuration() const { ABSL_DCHECK(IsDuration()) << *this; return absl::get<DurationValue>(variant_); } const ErrorValue& Value::GetError() const& { ABSL_DCHECK(IsError()) << *this; return absl::get<ErrorValue>(variant_); } ErrorValue Value::GetError() && { ABSL_DCHECK(IsError()) << *this; return absl::get<ErrorValue>(std::move(variant_)); } IntValue Value::GetInt() const { ABSL_DCHECK(IsInt()) << *this; return absl::get<IntValue>(variant_); } #ifdef ABSL_HAVE_EXCEPTIONS #define CEL_VALUE_THROW_BAD_VARIANT_ACCESS() throw absl::bad_variant_access() #else #define CEL_VALUE_THROW_BAD_VARIANT_ACCESS() \ ABSL_LOG(FATAL) << absl::bad_variant_access().what() #endif ListValue Value::GetList() const& { ABSL_DCHECK(IsList()) << *this; if (const auto* alternative = absl::get_if<common_internal::LegacyListValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedListValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedRepeatedFieldValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedJsonListValue>(&variant_); alternative != nullptr) { return *alternative; } CEL_VALUE_THROW_BAD_VARIANT_ACCESS(); } ListValue Value::GetList() && { ABSL_DCHECK(IsList()) << *this; if (auto* alternative = absl::get_if<common_internal::LegacyListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedRepeatedFieldValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedJsonListValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } CEL_VALUE_THROW_BAD_VARIANT_ACCESS(); } MapValue Value::GetMap() const& { ABSL_DCHECK(IsMap()) << *this; if (const auto* alternative = absl::get_if<common_internal::LegacyMapValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedMapValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedMapFieldValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedJsonMapValue>(&variant_); alternative != nullptr) { return *alternative; } CEL_VALUE_THROW_BAD_VARIANT_ACCESS(); } MapValue Value::GetMap() && { ABSL_DCHECK(IsMap()) << *this; if (auto* alternative = absl::get_if<common_internal::LegacyMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedMapFieldValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedJsonMapValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } CEL_VALUE_THROW_BAD_VARIANT_ACCESS(); } MessageValue Value::GetMessage() const& { ABSL_DCHECK(IsMessage()) << *this; return absl::get<ParsedMessageValue>(variant_); } MessageValue Value::GetMessage() && { ABSL_DCHECK(IsMessage()) << *this; return absl::get<ParsedMessageValue>(std::move(variant_)); } NullValue Value::GetNull() const { ABSL_DCHECK(IsNull()) << *this; return absl::get<NullValue>(variant_); } const OpaqueValue& Value::GetOpaque() const& { ABSL_DCHECK(IsOpaque()) << *this; return absl::get<OpaqueValue>(variant_); } OpaqueValue Value::GetOpaque() && { ABSL_DCHECK(IsOpaque()) << *this; return absl::get<OpaqueValue>(std::move(variant_)); } const OptionalValue& Value::GetOptional() const& { ABSL_DCHECK(IsOptional()) << *this; return static_cast<const OptionalValue&>(absl::get<OpaqueValue>(variant_)); } OptionalValue Value::GetOptional() && { ABSL_DCHECK(IsOptional()) << *this; return static_cast<OptionalValue&&>( absl::get<OpaqueValue>(std::move(variant_))); } const ParsedJsonListValue& Value::GetParsedJsonList() const& { ABSL_DCHECK(IsParsedJsonList()) << *this; return absl::get<ParsedJsonListValue>(variant_); } ParsedJsonListValue Value::GetParsedJsonList() && { ABSL_DCHECK(IsParsedJsonList()) << *this; return absl::get<ParsedJsonListValue>(std::move(variant_)); } const ParsedJsonMapValue& Value::GetParsedJsonMap() const& { ABSL_DCHECK(IsParsedJsonMap()) << *this; return absl::get<ParsedJsonMapValue>(variant_); } ParsedJsonMapValue Value::GetParsedJsonMap() && { ABSL_DCHECK(IsParsedJsonMap()) << *this; return absl::get<ParsedJsonMapValue>(std::move(variant_)); } const ParsedListValue& Value::GetParsedList() const& { ABSL_DCHECK(IsParsedList()) << *this; return absl::get<ParsedListValue>(variant_); } ParsedListValue Value::GetParsedList() && { ABSL_DCHECK(IsParsedList()) << *this; return absl::get<ParsedListValue>(std::move(variant_)); } const ParsedMapValue& Value::GetParsedMap() const& { ABSL_DCHECK(IsParsedMap()) << *this; return absl::get<ParsedMapValue>(variant_); } ParsedMapValue Value::GetParsedMap() && { ABSL_DCHECK(IsParsedMap()) << *this; return absl::get<ParsedMapValue>(std::move(variant_)); } const ParsedMapFieldValue& Value::GetParsedMapField() const& { ABSL_DCHECK(IsParsedMapField()) << *this; return absl::get<ParsedMapFieldValue>(variant_); } ParsedMapFieldValue Value::GetParsedMapField() && { ABSL_DCHECK(IsParsedMapField()) << *this; return absl::get<ParsedMapFieldValue>(std::move(variant_)); } const ParsedMessageValue& Value::GetParsedMessage() const& { ABSL_DCHECK(IsParsedMessage()) << *this; return absl::get<ParsedMessageValue>(variant_); } ParsedMessageValue Value::GetParsedMessage() && { ABSL_DCHECK(IsParsedMessage()) << *this; return absl::get<ParsedMessageValue>(std::move(variant_)); } const ParsedRepeatedFieldValue& Value::GetParsedRepeatedField() const& { ABSL_DCHECK(IsParsedRepeatedField()) << *this; return absl::get<ParsedRepeatedFieldValue>(variant_); } ParsedRepeatedFieldValue Value::GetParsedRepeatedField() && { ABSL_DCHECK(IsParsedRepeatedField()) << *this; return absl::get<ParsedRepeatedFieldValue>(std::move(variant_)); } const ParsedStructValue& Value::GetParsedStruct() const& { ABSL_DCHECK(IsParsedMap()) << *this; return absl::get<ParsedStructValue>(variant_); } ParsedStructValue Value::GetParsedStruct() && { ABSL_DCHECK(IsParsedMap()) << *this; return absl::get<ParsedStructValue>(std::move(variant_)); } const StringValue& Value::GetString() const& { ABSL_DCHECK(IsString()) << *this; return absl::get<StringValue>(variant_); } StringValue Value::GetString() && { ABSL_DCHECK(IsString()) << *this; return absl::get<StringValue>(std::move(variant_)); } StructValue Value::GetStruct() const& { ABSL_DCHECK(IsStruct()) << *this; if (const auto* alternative = absl::get_if<common_internal::LegacyStructValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedStructValue>(&variant_); alternative != nullptr) { return *alternative; } if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } CEL_VALUE_THROW_BAD_VARIANT_ACCESS(); } StructValue Value::GetStruct() && { ABSL_DCHECK(IsStruct()) << *this; if (auto* alternative = absl::get_if<common_internal::LegacyStructValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedStructValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } CEL_VALUE_THROW_BAD_VARIANT_ACCESS(); } TimestampValue Value::GetTimestamp() const { ABSL_DCHECK(IsTimestamp()) << *this; return absl::get<TimestampValue>(variant_); } const TypeValue& Value::GetType() const& { ABSL_DCHECK(IsType()) << *this; return absl::get<TypeValue>(variant_); } TypeValue Value::GetType() && { ABSL_DCHECK(IsType()) << *this; return absl::get<TypeValue>(std::move(variant_)); } UintValue Value::GetUint() const { ABSL_DCHECK(IsUint()) << *this; return absl::get<UintValue>(variant_); } const UnknownValue& Value::GetUnknown() const& { ABSL_DCHECK(IsUnknown()) << *this; return absl::get<UnknownValue>(variant_); } UnknownValue Value::GetUnknown() && { ABSL_DCHECK(IsUnknown()) << *this; return absl::get<UnknownValue>(std::move(variant_)); } namespace { class EmptyValueIterator final : public ValueIterator { public: bool HasNext() override { return false; } absl::Status Next(ValueManager&, Value&) override { return absl::FailedPreconditionError( "`ValueIterator::Next` called after `ValueIterator::HasNext` returned " "false"); } }; } absl::Nonnull<std::unique_ptr<ValueIterator>> NewEmptyValueIterator() { return std::make_unique<EmptyValueIterator>(); } }
#include "common/value.h" #include <sstream> #include "google/protobuf/struct.pb.h" #include "google/protobuf/type.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/base/attributes.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/types/optional.h" #include "common/native_type.h" #include "common/type.h" #include "common/value_testing.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.h" #include "proto/test/v1/proto3/test_all_types.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/generated_enum_reflection.h" namespace cel { namespace { using ::absl_testing::StatusIs; using ::cel::internal::DynamicParseTextProto; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::_; using ::testing::An; using ::testing::Eq; using ::testing::NotNull; using ::testing::Optional; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; TEST(Value, KindDebugDeath) { Value value; static_cast<void>(value); EXPECT_DEBUG_DEATH(static_cast<void>(value.kind()), _); } TEST(Value, GetTypeName) { Value value; static_cast<void>(value); EXPECT_DEBUG_DEATH(static_cast<void>(value.GetTypeName()), _); } TEST(Value, DebugStringUinitializedValue) { Value value; static_cast<void>(value); std::ostringstream out; out << value; EXPECT_EQ(out.str(), "default ctor Value"); } TEST(Value, NativeValueIdDebugDeath) { Value value; static_cast<void>(value); EXPECT_DEBUG_DEATH(static_cast<void>(NativeTypeId::Of(value)), _); } TEST(Value, GeneratedEnum) { EXPECT_EQ(Value::Enum(google::protobuf::NULL_VALUE), NullValue()); EXPECT_EQ(Value::Enum(google::protobuf::SYNTAX_EDITIONS), IntValue(2)); } TEST(Value, DynamicEnum) { EXPECT_THAT( Value::Enum(google::protobuf::GetEnumDescriptor<google::protobuf::NullValue>(), 0), test::IsNullValue()); EXPECT_THAT( Value::Enum(google::protobuf::GetEnumDescriptor<google::protobuf::NullValue>() ->FindValueByNumber(0)), test::IsNullValue()); EXPECT_THAT( Value::Enum(google::protobuf::GetEnumDescriptor<google::protobuf::Syntax>(), 2), test::IntValueIs(2)); EXPECT_THAT(Value::Enum(google::protobuf::GetEnumDescriptor<google::protobuf::Syntax>() ->FindValueByNumber(2)), test::IntValueIs(2)); } TEST(Value, DynamicClosedEnum) { google::protobuf::FileDescriptorProto file_descriptor; file_descriptor.set_name("test/closed_enum.proto"); file_descriptor.set_package("test"); file_descriptor.set_syntax("editions"); file_descriptor.set_edition(google::protobuf::EDITION_2023); { auto* enum_descriptor = file_descriptor.add_enum_type(); enum_descriptor->set_name("ClosedEnum"); enum_descriptor->mutable_options()->mutable_features()->set_enum_type( google::protobuf::FeatureSet::CLOSED); auto* enum_value_descriptor = enum_descriptor->add_value(); enum_value_descriptor->set_number(1); enum_value_descriptor->set_name("FOO"); enum_value_descriptor = enum_descriptor->add_value(); enum_value_descriptor->set_number(2); enum_value_descriptor->set_name("BAR"); } google::protobuf::DescriptorPool pool; ASSERT_THAT(pool.BuildFile(file_descriptor), NotNull()); const auto* enum_descriptor = pool.FindEnumTypeByName("test.ClosedEnum"); ASSERT_THAT(enum_descriptor, NotNull()); EXPECT_THAT(Value::Enum(enum_descriptor, 0), test::ErrorValueIs(StatusIs(absl::StatusCode::kInvalidArgument))); } TEST(Value, Is) { google::protobuf::Arena arena; EXPECT_TRUE(Value(BoolValue()).Is<BoolValue>()); EXPECT_TRUE(Value(BoolValue(true)).IsTrue()); EXPECT_TRUE(Value(BoolValue(false)).IsFalse()); EXPECT_TRUE(Value(BytesValue()).Is<BytesValue>()); EXPECT_TRUE(Value(DoubleValue()).Is<DoubleValue>()); EXPECT_TRUE(Value(DurationValue()).Is<DurationValue>()); EXPECT_TRUE(Value(ErrorValue()).Is<ErrorValue>()); EXPECT_TRUE(Value(IntValue()).Is<IntValue>()); EXPECT_TRUE(Value(ListValue()).Is<ListValue>()); EXPECT_TRUE(Value(ParsedListValue()).Is<ListValue>()); EXPECT_TRUE(Value(ParsedListValue()).Is<ParsedListValue>()); EXPECT_TRUE(Value(ParsedJsonListValue()).Is<ListValue>()); EXPECT_TRUE(Value(ParsedJsonListValue()).Is<ParsedJsonListValue>()); { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("repeated_int32")); EXPECT_TRUE( Value(ParsedRepeatedFieldValue(message, field)).Is<ListValue>()); EXPECT_TRUE(Value(ParsedRepeatedFieldValue(message, field)) .Is<ParsedRepeatedFieldValue>()); } EXPECT_TRUE(Value(MapValue()).Is<MapValue>()); EXPECT_TRUE(Value(ParsedMapValue()).Is<MapValue>()); EXPECT_TRUE(Value(ParsedMapValue()).Is<ParsedMapValue>()); EXPECT_TRUE(Value(ParsedJsonMapValue()).Is<MapValue>()); EXPECT_TRUE(Value(ParsedJsonMapValue()).Is<ParsedJsonMapValue>()); { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("map_int32_int32")); EXPECT_TRUE(Value(ParsedMapFieldValue(message, field)).Is<MapValue>()); EXPECT_TRUE( Value(ParsedMapFieldValue(message, field)).Is<ParsedMapFieldValue>()); } EXPECT_TRUE(Value(NullValue()).Is<NullValue>()); EXPECT_TRUE(Value(OptionalValue()).Is<OpaqueValue>()); EXPECT_TRUE(Value(OptionalValue()).Is<OptionalValue>()); EXPECT_TRUE(Value(ParsedMessageValue()).Is<StructValue>()); EXPECT_TRUE(Value(ParsedMessageValue()).Is<MessageValue>()); EXPECT_TRUE(Value(ParsedMessageValue()).Is<ParsedMessageValue>()); EXPECT_TRUE(Value(StringValue()).Is<StringValue>()); EXPECT_TRUE(Value(TimestampValue()).Is<TimestampValue>()); EXPECT_TRUE(Value(TypeValue(StringType())).Is<TypeValue>()); EXPECT_TRUE(Value(UintValue()).Is<UintValue>()); EXPECT_TRUE(Value(UnknownValue()).Is<UnknownValue>()); } template <typename T> constexpr T& AsLValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return t; } template <typename T> constexpr const T& AsConstLValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return t; } template <typename T> constexpr T&& AsRValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return static_cast<T&&>(t); } template <typename T> constexpr const T&& AsConstRValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return static_cast<const T&&>(t); } TEST(Value, As) { google::protobuf::Arena arena; EXPECT_THAT(Value(BoolValue()).As<BoolValue>(), Optional(An<BoolValue>())); EXPECT_THAT(Value(BoolValue()).As<ErrorValue>(), Eq(absl::nullopt)); { Value value(BytesValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<BytesValue>(), Optional(An<BytesValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<BytesValue>(), Optional(An<BytesValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<BytesValue>(), Optional(An<BytesValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<BytesValue>(), Optional(An<BytesValue>())); } EXPECT_THAT(Value(DoubleValue()).As<DoubleValue>(), Optional(An<DoubleValue>())); EXPECT_THAT(Value(DoubleValue()).As<ErrorValue>(), Eq(absl::nullopt)); EXPECT_THAT(Value(DurationValue()).As<DurationValue>(), Optional(An<DurationValue>())); EXPECT_THAT(Value(DurationValue()).As<ErrorValue>(), Eq(absl::nullopt)); { Value value(ErrorValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ErrorValue>(), Optional(An<ErrorValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ErrorValue>(), Optional(An<ErrorValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ErrorValue>(), Optional(An<ErrorValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ErrorValue>(), Optional(An<ErrorValue>())); EXPECT_THAT(Value(ErrorValue()).As<BoolValue>(), Eq(absl::nullopt)); } EXPECT_THAT(Value(IntValue()).As<IntValue>(), Optional(An<IntValue>())); EXPECT_THAT(Value(IntValue()).As<ErrorValue>(), Eq(absl::nullopt)); { Value value(ListValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(Value(ListValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedJsonListValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(Value(ListValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedJsonListValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedJsonListValue>(), Optional(An<ParsedJsonListValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedJsonListValue>(), Optional(An<ParsedJsonListValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedJsonListValue>(), Optional(An<ParsedJsonListValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ParsedJsonListValue>(), Optional(An<ParsedJsonListValue>())); } { Value value(ParsedListValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(Value(ListValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedListValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedListValue>(), Optional(An<ParsedListValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedListValue>(), Optional(An<ParsedListValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedListValue>(), Optional(An<ParsedListValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ParsedListValue>(), Optional(An<ParsedListValue>())); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("repeated_int32")); Value value(ParsedRepeatedFieldValue{message, field}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ListValue>(), Optional(An<ListValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ListValue>(), Optional(An<ListValue>())); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("repeated_int32")); Value value(ParsedRepeatedFieldValue{message, field}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedRepeatedFieldValue>(), Optional(An<ParsedRepeatedFieldValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedRepeatedFieldValue>(), Optional(An<ParsedRepeatedFieldValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedRepeatedFieldValue>(), Optional(An<ParsedRepeatedFieldValue>())); EXPECT_THAT( AsConstRValueRef<Value>(other_value).As<ParsedRepeatedFieldValue>(), Optional(An<ParsedRepeatedFieldValue>())); } { Value value(MapValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(Value(MapValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedJsonMapValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(Value(MapValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedJsonMapValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedJsonMapValue>(), Optional(An<ParsedJsonMapValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedJsonMapValue>(), Optional(An<ParsedJsonMapValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedJsonMapValue>(), Optional(An<ParsedJsonMapValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ParsedJsonMapValue>(), Optional(An<ParsedJsonMapValue>())); } { Value value(ParsedMapValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(Value(MapValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedMapValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedMapValue>(), Optional(An<ParsedMapValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedMapValue>(), Optional(An<ParsedMapValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedMapValue>(), Optional(An<ParsedMapValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ParsedMapValue>(), Optional(An<ParsedMapValue>())); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("map_int32_int32")); Value value(ParsedMapFieldValue{message, field}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<MapValue>(), Optional(An<MapValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<MapValue>(), Optional(An<MapValue>())); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("map_int32_int32")); Value value(ParsedMapFieldValue{message, field}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedMapFieldValue>(), Optional(An<ParsedMapFieldValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedMapFieldValue>(), Optional(An<ParsedMapFieldValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedMapFieldValue>(), Optional(An<ParsedMapFieldValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ParsedMapFieldValue>(), Optional(An<ParsedMapFieldValue>())); } { Value value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT( Value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}) .As<ErrorValue>(), Eq(absl::nullopt)); } EXPECT_THAT(Value(NullValue()).As<NullValue>(), Optional(An<NullValue>())); EXPECT_THAT(Value(NullValue()).As<ErrorValue>(), Eq(absl::nullopt)); { Value value(OptionalValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<OpaqueValue>(), Optional(An<OpaqueValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<OpaqueValue>(), Optional(An<OpaqueValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<OpaqueValue>(), Optional(An<OpaqueValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<OpaqueValue>(), Optional(An<OpaqueValue>())); EXPECT_THAT(Value(OpaqueValue(OptionalValue())).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(OptionalValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(Value(OptionalValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { OpaqueValue value(OptionalValue{}); OpaqueValue other_value = value; EXPECT_THAT(AsLValueRef<OpaqueValue>(value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(AsConstLValueRef<OpaqueValue>(value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(AsRValueRef<OpaqueValue>(value).As<OptionalValue>(), Optional(An<OptionalValue>())); EXPECT_THAT(AsConstRValueRef<OpaqueValue>(other_value).As<OptionalValue>(), Optional(An<OptionalValue>())); } { Value value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); } { Value value(StringValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<StringValue>(), Optional(An<StringValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<StringValue>(), Optional(An<StringValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<StringValue>(), Optional(An<StringValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<StringValue>(), Optional(An<StringValue>())); EXPECT_THAT(Value(StringValue()).As<ErrorValue>(), Eq(absl::nullopt)); } { Value value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<StructValue>(), Optional(An<StructValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<StructValue>(), Optional(An<StructValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<StructValue>(), Optional(An<StructValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<StructValue>(), Optional(An<StructValue>())); } EXPECT_THAT(Value(TimestampValue()).As<TimestampValue>(), Optional(An<TimestampValue>())); EXPECT_THAT(Value(TimestampValue()).As<ErrorValue>(), Eq(absl::nullopt)); { Value value(TypeValue(StringType{})); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<TypeValue>(), Optional(An<TypeValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<TypeValue>(), Optional(An<TypeValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<TypeValue>(), Optional(An<TypeValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<TypeValue>(), Optional(An<TypeValue>())); EXPECT_THAT(Value(TypeValue(StringType())).As<ErrorValue>(), Eq(absl::nullopt)); } EXPECT_THAT(Value(UintValue()).As<UintValue>(), Optional(An<UintValue>())); EXPECT_THAT(Value(UintValue()).As<ErrorValue>(), Eq(absl::nullopt)); { Value value(UnknownValue{}); Value other_value = value; EXPECT_THAT(AsLValueRef<Value>(value).As<UnknownValue>(), Optional(An<UnknownValue>())); EXPECT_THAT(AsConstLValueRef<Value>(value).As<UnknownValue>(), Optional(An<UnknownValue>())); EXPECT_THAT(AsRValueRef<Value>(value).As<UnknownValue>(), Optional(An<UnknownValue>())); EXPECT_THAT(AsConstRValueRef<Value>(other_value).As<UnknownValue>(), Optional(An<UnknownValue>())); EXPECT_THAT(Value(UnknownValue()).As<ErrorValue>(), Eq(absl::nullopt)); } } template <typename To, typename From> decltype(auto) DoGet(From&& from) { return std::forward<From>(from).template Get<To>(); } TEST(Value, Get) { google::protobuf::Arena arena; EXPECT_THAT(DoGet<BoolValue>(Value(BoolValue())), An<BoolValue>()); { Value value(BytesValue{}); Value other_value = value; EXPECT_THAT(DoGet<BytesValue>(AsLValueRef<Value>(value)), An<BytesValue>()); EXPECT_THAT(DoGet<BytesValue>(AsConstLValueRef<Value>(value)), An<BytesValue>()); EXPECT_THAT(DoGet<BytesValue>(AsRValueRef<Value>(value)), An<BytesValue>()); EXPECT_THAT(DoGet<BytesValue>(AsConstRValueRef<Value>(other_value)), An<BytesValue>()); } EXPECT_THAT(DoGet<DoubleValue>(Value(DoubleValue())), An<DoubleValue>()); EXPECT_THAT(DoGet<DurationValue>(Value(DurationValue())), An<DurationValue>()); { Value value(ErrorValue{}); Value other_value = value; EXPECT_THAT(DoGet<ErrorValue>(AsLValueRef<Value>(value)), An<ErrorValue>()); EXPECT_THAT(DoGet<ErrorValue>(AsConstLValueRef<Value>(value)), An<ErrorValue>()); EXPECT_THAT(DoGet<ErrorValue>(AsRValueRef<Value>(value)), An<ErrorValue>()); EXPECT_THAT(DoGet<ErrorValue>(AsConstRValueRef<Value>(other_value)), An<ErrorValue>()); } EXPECT_THAT(DoGet<IntValue>(Value(IntValue())), An<IntValue>()); { Value value(ListValue{}); Value other_value = value; EXPECT_THAT(DoGet<ListValue>(AsLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsRValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstRValueRef<Value>(other_value)), An<ListValue>()); } { Value value(ParsedJsonListValue{}); Value other_value = value; EXPECT_THAT(DoGet<ListValue>(AsLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsRValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstRValueRef<Value>(other_value)), An<ListValue>()); } { Value value(ParsedJsonListValue{}); Value other_value = value; EXPECT_THAT(DoGet<ParsedJsonListValue>(AsLValueRef<Value>(value)), An<ParsedJsonListValue>()); EXPECT_THAT(DoGet<ParsedJsonListValue>(AsConstLValueRef<Value>(value)), An<ParsedJsonListValue>()); EXPECT_THAT(DoGet<ParsedJsonListValue>(AsRValueRef<Value>(value)), An<ParsedJsonListValue>()); EXPECT_THAT( DoGet<ParsedJsonListValue>(AsConstRValueRef<Value>(other_value)), An<ParsedJsonListValue>()); } { Value value(ParsedListValue{}); Value other_value = value; EXPECT_THAT(DoGet<ListValue>(AsLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsRValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstRValueRef<Value>(other_value)), An<ListValue>()); } { Value value(ParsedListValue{}); Value other_value = value; EXPECT_THAT(DoGet<ParsedListValue>(AsLValueRef<Value>(value)), An<ParsedListValue>()); EXPECT_THAT(DoGet<ParsedListValue>(AsConstLValueRef<Value>(value)), An<ParsedListValue>()); EXPECT_THAT(DoGet<ParsedListValue>(AsRValueRef<Value>(value)), An<ParsedListValue>()); EXPECT_THAT(DoGet<ParsedListValue>(AsConstRValueRef<Value>(other_value)), An<ParsedListValue>()); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("repeated_int32")); Value value(ParsedRepeatedFieldValue{message, field}); Value other_value = value; EXPECT_THAT(DoGet<ListValue>(AsLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstLValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsRValueRef<Value>(value)), An<ListValue>()); EXPECT_THAT(DoGet<ListValue>(AsConstRValueRef<Value>(other_value)), An<ListValue>()); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("repeated_int32")); Value value(ParsedRepeatedFieldValue{message, field}); Value other_value = value; EXPECT_THAT(DoGet<ParsedRepeatedFieldValue>(AsLValueRef<Value>(value)), An<ParsedRepeatedFieldValue>()); EXPECT_THAT(DoGet<ParsedRepeatedFieldValue>(AsConstLValueRef<Value>(value)), An<ParsedRepeatedFieldValue>()); EXPECT_THAT(DoGet<ParsedRepeatedFieldValue>(AsRValueRef<Value>(value)), An<ParsedRepeatedFieldValue>()); EXPECT_THAT( DoGet<ParsedRepeatedFieldValue>(AsConstRValueRef<Value>(other_value)), An<ParsedRepeatedFieldValue>()); } { Value value(MapValue{}); Value other_value = value; EXPECT_THAT(DoGet<MapValue>(AsLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsRValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstRValueRef<Value>(other_value)), An<MapValue>()); } { Value value(ParsedJsonMapValue{}); Value other_value = value; EXPECT_THAT(DoGet<MapValue>(AsLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsRValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstRValueRef<Value>(other_value)), An<MapValue>()); } { Value value(ParsedJsonMapValue{}); Value other_value = value; EXPECT_THAT(DoGet<ParsedJsonMapValue>(AsLValueRef<Value>(value)), An<ParsedJsonMapValue>()); EXPECT_THAT(DoGet<ParsedJsonMapValue>(AsConstLValueRef<Value>(value)), An<ParsedJsonMapValue>()); EXPECT_THAT(DoGet<ParsedJsonMapValue>(AsRValueRef<Value>(value)), An<ParsedJsonMapValue>()); EXPECT_THAT(DoGet<ParsedJsonMapValue>(AsConstRValueRef<Value>(other_value)), An<ParsedJsonMapValue>()); } { Value value(ParsedMapValue{}); Value other_value = value; EXPECT_THAT(DoGet<MapValue>(AsLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsRValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstRValueRef<Value>(other_value)), An<MapValue>()); } { Value value(ParsedMapValue{}); Value other_value = value; EXPECT_THAT(DoGet<ParsedMapValue>(AsLValueRef<Value>(value)), An<ParsedMapValue>()); EXPECT_THAT(DoGet<ParsedMapValue>(AsConstLValueRef<Value>(value)), An<ParsedMapValue>()); EXPECT_THAT(DoGet<ParsedMapValue>(AsRValueRef<Value>(value)), An<ParsedMapValue>()); EXPECT_THAT(DoGet<ParsedMapValue>(AsConstRValueRef<Value>(other_value)), An<ParsedMapValue>()); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("map_int32_int32")); Value value(ParsedMapFieldValue{message, field}); Value other_value = value; EXPECT_THAT(DoGet<MapValue>(AsLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstLValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsRValueRef<Value>(value)), An<MapValue>()); EXPECT_THAT(DoGet<MapValue>(AsConstRValueRef<Value>(other_value)), An<MapValue>()); } { auto message = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory()); const auto* field = ABSL_DIE_IF_NULL( message->GetDescriptor()->FindFieldByName("map_int32_int32")); Value value(ParsedMapFieldValue{message, field}); Value other_value = value; EXPECT_THAT(DoGet<ParsedMapFieldValue>(AsLValueRef<Value>(value)), An<ParsedMapFieldValue>()); EXPECT_THAT(DoGet<ParsedMapFieldValue>(AsConstLValueRef<Value>(value)), An<ParsedMapFieldValue>()); EXPECT_THAT(DoGet<ParsedMapFieldValue>(AsRValueRef<Value>(value)), An<ParsedMapFieldValue>()); EXPECT_THAT( DoGet<ParsedMapFieldValue>(AsConstRValueRef<Value>(other_value)), An<ParsedMapFieldValue>()); } { Value value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); Value other_value = value; EXPECT_THAT(DoGet<MessageValue>(AsLValueRef<Value>(value)), An<MessageValue>()); EXPECT_THAT(DoGet<MessageValue>(AsConstLValueRef<Value>(value)), An<MessageValue>()); EXPECT_THAT(DoGet<MessageValue>(AsRValueRef<Value>(value)), An<MessageValue>()); EXPECT_THAT(DoGet<MessageValue>(AsConstRValueRef<Value>(other_value)), An<MessageValue>()); } EXPECT_THAT(DoGet<NullValue>(Value(NullValue())), An<NullValue>()); { Value value(OptionalValue{}); Value other_value = value; EXPECT_THAT(DoGet<OpaqueValue>(AsLValueRef<Value>(value)), An<OpaqueValue>()); EXPECT_THAT(DoGet<OpaqueValue>(AsConstLValueRef<Value>(value)), An<OpaqueValue>()); EXPECT_THAT(DoGet<OpaqueValue>(AsRValueRef<Value>(value)), An<OpaqueValue>()); EXPECT_THAT(DoGet<OpaqueValue>(AsConstRValueRef<Value>(other_value)), An<OpaqueValue>()); } { Value value(OptionalValue{}); Value other_value = value; EXPECT_THAT(DoGet<OptionalValue>(AsLValueRef<Value>(value)), An<OptionalValue>()); EXPECT_THAT(DoGet<OptionalValue>(AsConstLValueRef<Value>(value)), An<OptionalValue>()); EXPECT_THAT(DoGet<OptionalValue>(AsRValueRef<Value>(value)), An<OptionalValue>()); EXPECT_THAT(DoGet<OptionalValue>(AsConstRValueRef<Value>(other_value)), An<OptionalValue>()); } { OpaqueValue value(OptionalValue{}); OpaqueValue other_value = value; EXPECT_THAT(DoGet<OptionalValue>(AsLValueRef<OpaqueValue>(value)), An<OptionalValue>()); EXPECT_THAT(DoGet<OptionalValue>(AsConstLValueRef<OpaqueValue>(value)), An<OptionalValue>()); EXPECT_THAT(DoGet<OptionalValue>(AsRValueRef<OpaqueValue>(value)), An<OptionalValue>()); EXPECT_THAT( DoGet<OptionalValue>(AsConstRValueRef<OpaqueValue>(other_value)), An<OptionalValue>()); } { Value value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); Value other_value = value; EXPECT_THAT(DoGet<ParsedMessageValue>(AsLValueRef<Value>(value)), An<ParsedMessageValue>()); EXPECT_THAT(DoGet<ParsedMessageValue>(AsConstLValueRef<Value>(value)), An<ParsedMessageValue>()); EXPECT_THAT(DoGet<ParsedMessageValue>(AsRValueRef<Value>(value)), An<ParsedMessageValue>()); EXPECT_THAT(DoGet<ParsedMessageValue>(AsConstRValueRef<Value>(other_value)), An<ParsedMessageValue>()); } { Value value(StringValue{}); Value other_value = value; EXPECT_THAT(DoGet<StringValue>(AsLValueRef<Value>(value)), An<StringValue>()); EXPECT_THAT(DoGet<StringValue>(AsConstLValueRef<Value>(value)), An<StringValue>()); EXPECT_THAT(DoGet<StringValue>(AsRValueRef<Value>(value)), An<StringValue>()); EXPECT_THAT(DoGet<StringValue>(AsConstRValueRef<Value>(other_value)), An<StringValue>()); } { Value value(ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); Value other_value = value; EXPECT_THAT(DoGet<StructValue>(AsLValueRef<Value>(value)), An<StructValue>()); EXPECT_THAT(DoGet<StructValue>(AsConstLValueRef<Value>(value)), An<StructValue>()); EXPECT_THAT(DoGet<StructValue>(AsRValueRef<Value>(value)), An<StructValue>()); EXPECT_THAT(DoGet<StructValue>(AsConstRValueRef<Value>(other_value)), An<StructValue>()); } EXPECT_THAT(DoGet<TimestampValue>(Value(TimestampValue())), An<TimestampValue>()); { Value value(TypeValue(StringType{})); Value other_value = value; EXPECT_THAT(DoGet<TypeValue>(AsLValueRef<Value>(value)), An<TypeValue>()); EXPECT_THAT(DoGet<TypeValue>(AsConstLValueRef<Value>(value)), An<TypeValue>()); EXPECT_THAT(DoGet<TypeValue>(AsRValueRef<Value>(value)), An<TypeValue>()); EXPECT_THAT(DoGet<TypeValue>(AsConstRValueRef<Value>(other_value)), An<TypeValue>()); } EXPECT_THAT(DoGet<UintValue>(Value(UintValue())), An<UintValue>()); { Value value(UnknownValue{}); Value other_value = value; EXPECT_THAT(DoGet<UnknownValue>(AsLValueRef<Value>(value)), An<UnknownValue>()); EXPECT_THAT(DoGet<UnknownValue>(AsConstLValueRef<Value>(value)), An<UnknownValue>()); EXPECT_THAT(DoGet<UnknownValue>(AsRValueRef<Value>(value)), An<UnknownValue>()); EXPECT_THAT(DoGet<UnknownValue>(AsConstRValueRef<Value>(other_value)), An<UnknownValue>()); } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
64f7242a-e1e8-40ac-b18f-6192a82247a4
cpp
google/cel-cpp
type_reflector
common/type_reflector.cc
common/type_reflector_test.cc
#include "common/type_reflector.h" #include <cstdint> #include <string> #include <utility> #include "absl/base/no_destructor.h" #include "absl/container/flat_hash_map.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 "absl/strings/strip.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/memory.h" #include "common/type.h" #include "common/value.h" #include "common/value_factory.h" #include "common/values/piecewise_value_manager.h" #include "common/values/thread_compatible_type_reflector.h" #include "internal/deserialize.h" #include "internal/overflow.h" #include "internal/status_macros.h" namespace cel { namespace { class WellKnownValueBuilder : public ValueBuilder { public: virtual absl::Status Deserialize(const absl::Cord& serialized_value) = 0; }; class BoolValueBuilder final : public WellKnownValueBuilder { public: explicit BoolValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return BoolValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeBoolValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto bool_value = As<BoolValue>(value); bool_value.has_value()) { value_ = bool_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } bool value_ = false; }; class Int32ValueBuilder final : public WellKnownValueBuilder { public: explicit Int32ValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return IntValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeInt32Value(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto int_value = As<IntValue>(value); int_value.has_value()) { CEL_ASSIGN_OR_RETURN( value_, internal::CheckedInt64ToInt32(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } int64_t value_ = 0; }; class Int64ValueBuilder final : public WellKnownValueBuilder { public: explicit Int64ValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return IntValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeInt64Value(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto int_value = As<IntValue>(value); int_value.has_value()) { value_ = int_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } int64_t value_ = 0; }; class UInt32ValueBuilder final : public WellKnownValueBuilder { public: explicit UInt32ValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return UintValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeUInt32Value(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto uint_value = As<UintValue>(value); uint_value.has_value()) { CEL_ASSIGN_OR_RETURN( value_, internal::CheckedUint64ToUint32(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } uint64_t value_ = 0; }; class UInt64ValueBuilder final : public WellKnownValueBuilder { public: explicit UInt64ValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return UintValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeUInt64Value(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto uint_value = As<UintValue>(value); uint_value.has_value()) { value_ = uint_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } uint64_t value_ = 0; }; class FloatValueBuilder final : public WellKnownValueBuilder { public: explicit FloatValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return DoubleValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeFloatValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto double_value = As<DoubleValue>(value); double_value.has_value()) { value_ = static_cast<float>(double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } double value_ = 0; }; class DoubleValueBuilder final : public WellKnownValueBuilder { public: explicit DoubleValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return DoubleValue(value_); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeDoubleValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto double_value = As<DoubleValue>(value); double_value.has_value()) { value_ = double_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } double value_ = 0; }; class StringValueBuilder final : public WellKnownValueBuilder { public: explicit StringValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return StringValue(std::move(value_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeStringValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto string_value = As<StringValue>(value); string_value.has_value()) { value_ = string_value->NativeCord(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } absl::Cord value_; }; class BytesValueBuilder final : public WellKnownValueBuilder { public: explicit BytesValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name != "value") { return NoSuchFieldError(name).NativeValue(); } return SetValue(std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number != 1) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return SetValue(std::move(value)); } Value Build() && override { return BytesValue(std::move(value_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(value_, internal::DeserializeBytesValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValue(Value value) { if (auto bytes_value = As<BytesValue>(value); bytes_value.has_value()) { value_ = bytes_value->NativeCord(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bytes").NativeValue(); } absl::Cord value_; }; class DurationValueBuilder final : public WellKnownValueBuilder { public: explicit DurationValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name == "seconds") { return SetSeconds(std::move(value)); } if (name == "nanos") { return SetNanos(std::move(value)); } return NoSuchFieldError(name).NativeValue(); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number == 1) { return SetSeconds(std::move(value)); } if (number == 2) { return SetNanos(std::move(value)); } return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } Value Build() && override { return DurationValue(absl::Seconds(seconds_) + absl::Nanoseconds(nanos_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(auto value, internal::DeserializeDuration(serialized_value)); seconds_ = absl::IDivDuration(value, absl::Seconds(1), &value); nanos_ = static_cast<int32_t>( absl::IDivDuration(value, absl::Nanoseconds(1), &value)); return absl::OkStatus(); } private: absl::Status SetSeconds(Value value) { if (auto int_value = As<IntValue>(value); int_value.has_value()) { seconds_ = int_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status SetNanos(Value value) { if (auto int_value = As<IntValue>(value); int_value.has_value()) { CEL_ASSIGN_OR_RETURN( nanos_, internal::CheckedInt64ToInt32(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } int64_t seconds_ = 0; int32_t nanos_ = 0; }; class TimestampValueBuilder final : public WellKnownValueBuilder { public: explicit TimestampValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name == "seconds") { return SetSeconds(std::move(value)); } if (name == "nanos") { return SetNanos(std::move(value)); } return NoSuchFieldError(name).NativeValue(); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number == 1) { return SetSeconds(std::move(value)); } if (number == 2) { return SetNanos(std::move(value)); } return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } Value Build() && override { return TimestampValue(absl::UnixEpoch() + absl::Seconds(seconds_) + absl::Nanoseconds(nanos_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(auto value, internal::DeserializeTimestamp(serialized_value)); auto duration = value - absl::UnixEpoch(); seconds_ = absl::IDivDuration(duration, absl::Seconds(1), &duration); nanos_ = static_cast<int32_t>( absl::IDivDuration(duration, absl::Nanoseconds(1), &duration)); return absl::OkStatus(); } private: absl::Status SetSeconds(Value value) { if (auto int_value = As<IntValue>(value); int_value.has_value()) { seconds_ = int_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status SetNanos(Value value) { if (auto int_value = As<IntValue>(value); int_value.has_value()) { CEL_ASSIGN_OR_RETURN( nanos_, internal::CheckedInt64ToInt32(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } int64_t seconds_ = 0; int32_t nanos_ = 0; }; class JsonValueBuilder final : public WellKnownValueBuilder { public: explicit JsonValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) : type_reflector_(type_reflector), value_factory_(value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name == "null_value") { return SetNullValue(); } if (name == "number_value") { return SetNumberValue(std::move(value)); } if (name == "string_value") { return SetStringValue(std::move(value)); } if (name == "bool_value") { return SetBoolValue(std::move(value)); } if (name == "struct_value") { return SetStructValue(std::move(value)); } if (name == "list_value") { return SetListValue(std::move(value)); } return NoSuchFieldError(name).NativeValue(); } absl::Status SetFieldByNumber(int64_t number, Value value) override { switch (number) { case 1: return SetNullValue(); case 2: return SetNumberValue(std::move(value)); case 3: return SetStringValue(std::move(value)); case 4: return SetBoolValue(std::move(value)); case 5: return SetStructValue(std::move(value)); case 6: return SetListValue(std::move(value)); default: return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } } Value Build() && override { return value_factory_.CreateValueFromJson(std::move(json_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(json_, internal::DeserializeValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetNullValue() { json_ = kJsonNull; return absl::OkStatus(); } absl::Status SetNumberValue(Value value) { if (auto double_value = As<DoubleValue>(value); double_value.has_value()) { json_ = double_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status SetStringValue(Value value) { if (auto string_value = As<StringValue>(value); string_value.has_value()) { json_ = string_value->NativeCord(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } absl::Status SetBoolValue(Value value) { if (auto bool_value = As<BoolValue>(value); bool_value.has_value()) { json_ = bool_value->NativeValue(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } absl::Status SetStructValue(Value value) { if (auto map_value = As<MapValue>(value); map_value.has_value()) { common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_ASSIGN_OR_RETURN(json_, map_value->ConvertToJson(value_manager)); return absl::OkStatus(); } if (auto struct_value = As<StructValue>(value); struct_value.has_value()) { common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_ASSIGN_OR_RETURN(json_, struct_value->ConvertToJson(value_manager)); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "google.protobuf.Struct") .NativeValue(); } absl::Status SetListValue(Value value) { if (auto list_value = As<ListValue>(value); list_value.has_value()) { common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_ASSIGN_OR_RETURN(json_, list_value->ConvertToJson(value_manager)); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "google.protobuf.ListValue") .NativeValue(); } const TypeReflector& type_reflector_; ValueFactory& value_factory_; Json json_; }; class JsonArrayValueBuilder final : public WellKnownValueBuilder { public: explicit JsonArrayValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) : type_reflector_(type_reflector), value_factory_(value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name == "values") { return SetValues(std::move(value)); } return NoSuchFieldError(name).NativeValue(); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number == 1) { return SetValues(std::move(value)); } return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } Value Build() && override { return value_factory_.CreateListValueFromJsonArray(std::move(array_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(array_, internal::DeserializeListValue(serialized_value)); return absl::OkStatus(); } private: absl::Status SetValues(Value value) { if (auto list_value = As<ListValue>(value); list_value.has_value()) { common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_ASSIGN_OR_RETURN(array_, list_value->ConvertToJsonArray(value_manager)); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "list(dyn)").NativeValue(); } const TypeReflector& type_reflector_; ValueFactory& value_factory_; JsonArray array_; }; class JsonObjectValueBuilder final : public WellKnownValueBuilder { public: explicit JsonObjectValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) : type_reflector_(type_reflector), value_factory_(value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name == "fields") { return SetFields(std::move(value)); } return NoSuchFieldError(name).NativeValue(); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number == 1) { return SetFields(std::move(value)); } return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } Value Build() && override { return value_factory_.CreateMapValueFromJsonObject(std::move(object_)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(object_, internal::DeserializeStruct(serialized_value)); return absl::OkStatus(); } private: absl::Status SetFields(Value value) { if (auto map_value = As<MapValue>(value); map_value.has_value()) { common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_ASSIGN_OR_RETURN(object_, map_value->ConvertToJsonObject(value_manager)); return absl::OkStatus(); } if (auto struct_value = As<StructValue>(value); struct_value.has_value()) { common_internal::PiecewiseValueManager value_manager(type_reflector_, value_factory_); CEL_ASSIGN_OR_RETURN(auto json_value, struct_value->ConvertToJson(value_manager)); if (absl::holds_alternative<JsonObject>(json_value)) { object_ = absl::get<JsonObject>(std::move(json_value)); return absl::OkStatus(); } } return TypeConversionError(value.GetTypeName(), "map(string, dyn)") .NativeValue(); } const TypeReflector& type_reflector_; ValueFactory& value_factory_; JsonObject object_; }; class AnyValueBuilder final : public WellKnownValueBuilder { public: explicit AnyValueBuilder(const TypeReflector& type_reflector, ValueFactory& value_factory) : type_reflector_(type_reflector), value_factory_(value_factory) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { if (name == "type_url") { return SetTypeUrl(std::move(value)); } if (name == "value") { return SetValue(std::move(value)); } return NoSuchFieldError(name).NativeValue(); } absl::Status SetFieldByNumber(int64_t number, Value value) override { if (number == 1) { return SetTypeUrl(std::move(value)); } if (number == 2) { return SetValue(std::move(value)); } return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } Value Build() && override { auto status_or_value = type_reflector_.DeserializeValue(value_factory_, type_url_, value_); if (!status_or_value.ok()) { return ErrorValue(std::move(status_or_value).status()); } if (!(*status_or_value).has_value()) { return NoSuchTypeError(type_url_); } return std::move(*std::move(*status_or_value)); } absl::Status Deserialize(const absl::Cord& serialized_value) override { CEL_ASSIGN_OR_RETURN(auto any, internal::DeserializeAny(serialized_value)); type_url_ = any.type_url(); value_ = GetAnyValueAsCord(any); return absl::OkStatus(); } private: absl::Status SetTypeUrl(Value value) { if (auto string_value = As<StringValue>(value); string_value.has_value()) { type_url_ = string_value->NativeString(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } absl::Status SetValue(Value value) { if (auto bytes_value = As<BytesValue>(value); bytes_value.has_value()) { value_ = bytes_value->NativeCord(); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bytes").NativeValue(); } const TypeReflector& type_reflector_; ValueFactory& value_factory_; std::string type_url_; absl::Cord value_; }; using WellKnownValueBuilderProvider = Unique<WellKnownValueBuilder> (*)( MemoryManagerRef, const TypeReflector&, ValueFactory&); template <typename T> Unique<WellKnownValueBuilder> WellKnownValueBuilderProviderFor( MemoryManagerRef memory_manager, const TypeReflector& type_reflector, ValueFactory& value_factory) { return memory_manager.MakeUnique<T>(type_reflector, value_factory); } using WellKnownValueBuilderMap = absl::flat_hash_map<absl::string_view, WellKnownValueBuilderProvider>; const WellKnownValueBuilderMap& GetWellKnownValueBuilderMap() { static const WellKnownValueBuilderMap* builders = []() -> WellKnownValueBuilderMap* { WellKnownValueBuilderMap* builders = new WellKnownValueBuilderMap(); builders->insert_or_assign( "google.protobuf.BoolValue", &WellKnownValueBuilderProviderFor<BoolValueBuilder>); builders->insert_or_assign( "google.protobuf.Int32Value", &WellKnownValueBuilderProviderFor<Int32ValueBuilder>); builders->insert_or_assign( "google.protobuf.Int64Value", &WellKnownValueBuilderProviderFor<Int64ValueBuilder>); builders->insert_or_assign( "google.protobuf.UInt32Value", &WellKnownValueBuilderProviderFor<UInt32ValueBuilder>); builders->insert_or_assign( "google.protobuf.UInt64Value", &WellKnownValueBuilderProviderFor<UInt64ValueBuilder>); builders->insert_or_assign( "google.protobuf.FloatValue", &WellKnownValueBuilderProviderFor<FloatValueBuilder>); builders->insert_or_assign( "google.protobuf.DoubleValue", &WellKnownValueBuilderProviderFor<DoubleValueBuilder>); builders->insert_or_assign( "google.protobuf.StringValue", &WellKnownValueBuilderProviderFor<StringValueBuilder>); builders->insert_or_assign( "google.protobuf.BytesValue", &WellKnownValueBuilderProviderFor<BytesValueBuilder>); builders->insert_or_assign( "google.protobuf.Duration", &WellKnownValueBuilderProviderFor<DurationValueBuilder>); builders->insert_or_assign( "google.protobuf.Timestamp", &WellKnownValueBuilderProviderFor<TimestampValueBuilder>); builders->insert_or_assign( "google.protobuf.Value", &WellKnownValueBuilderProviderFor<JsonValueBuilder>); builders->insert_or_assign( "google.protobuf.ListValue", &WellKnownValueBuilderProviderFor<JsonArrayValueBuilder>); builders->insert_or_assign( "google.protobuf.Struct", &WellKnownValueBuilderProviderFor<JsonObjectValueBuilder>); builders->insert_or_assign( "google.protobuf.Any", &WellKnownValueBuilderProviderFor<AnyValueBuilder>); return builders; }(); return *builders; } class ValueBuilderForStruct final : public ValueBuilder { public: explicit ValueBuilderForStruct(Unique<StructValueBuilder> delegate) : delegate_(std::move(delegate)) {} absl::Status SetFieldByName(absl::string_view name, Value value) override { return delegate_->SetFieldByName(name, std::move(value)); } absl::Status SetFieldByNumber(int64_t number, Value value) override { return delegate_->SetFieldByNumber(number, std::move(value)); } Value Build() && override { auto status_or_value = std::move(*delegate_).Build(); if (!status_or_value.ok()) { return ErrorValue(status_or_value.status()); } return std::move(status_or_value).value(); } private: Unique<StructValueBuilder> delegate_; }; } absl::StatusOr<absl::optional<Unique<ValueBuilder>>> TypeReflector::NewValueBuilder(ValueFactory& value_factory, absl::string_view name) const { const auto& well_known_value_builders = GetWellKnownValueBuilderMap(); if (auto well_known_value_builder = well_known_value_builders.find(name); well_known_value_builder != well_known_value_builders.end()) { return (*well_known_value_builder->second)(value_factory.GetMemoryManager(), *this, value_factory); } CEL_ASSIGN_OR_RETURN( auto maybe_builder, NewStructValueBuilder(value_factory, common_internal::MakeBasicStructType(name))); if (maybe_builder.has_value()) { return value_factory.GetMemoryManager().MakeUnique<ValueBuilderForStruct>( std::move(*maybe_builder)); } return absl::nullopt; } absl::StatusOr<absl::optional<Value>> TypeReflector::DeserializeValue( ValueFactory& value_factory, absl::string_view type_url, const absl::Cord& value) const { if (absl::StartsWith(type_url, kTypeGoogleApisComPrefix)) { const auto& well_known_value_builders = GetWellKnownValueBuilderMap(); if (auto well_known_value_builder = well_known_value_builders.find( absl::StripPrefix(type_url, kTypeGoogleApisComPrefix)); well_known_value_builder != well_known_value_builders.end()) { auto deserializer = (*well_known_value_builder->second)( value_factory.GetMemoryManager(), *this, value_factory); CEL_RETURN_IF_ERROR(deserializer->Deserialize(value)); return std::move(*deserializer).Build(); } } return DeserializeValueImpl(value_factory, type_url, value); } absl::StatusOr<absl::optional<Value>> TypeReflector::DeserializeValueImpl( ValueFactory&, absl::string_view, const absl::Cord&) const { return absl::nullopt; } absl::StatusOr<absl::optional<Unique<StructValueBuilder>>> TypeReflector::NewStructValueBuilder(ValueFactory&, const StructType&) const { return absl::nullopt; } absl::StatusOr<bool> TypeReflector::FindValue(ValueFactory&, absl::string_view, Value&) const { return false; } TypeReflector& TypeReflector::LegacyBuiltin() { static absl::NoDestructor<common_internal::LegacyTypeReflector> instance; return *instance; } TypeReflector& TypeReflector::ModernBuiltin() { static absl::NoDestructor<TypeReflector> instance; return *instance; } Shared<TypeReflector> NewThreadCompatibleTypeReflector( MemoryManagerRef memory_manager) { return memory_manager .MakeShared<common_internal::ThreadCompatibleTypeReflector>(); } }
#include <cstdint> #include <limits> #include <utility> #include "absl/status/status.h" #include "absl/time/time.h" #include "common/casting.h" #include "common/json.h" #include "common/memory.h" #include "common/type.h" #include "common/value.h" #include "common/value_testing.h" #include "common/values/legacy_value_manager.h" #include "common/values/list_value.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Optional; using TypeReflectorTest = common_internal::ThreadCompatibleValueTest<>; #define TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(element_type) \ TEST_P(TypeReflectorTest, NewListValueBuilder_##element_type) { \ ASSERT_OK_AND_ASSIGN(auto list_value_builder, \ value_manager().NewListValueBuilder(ListType())); \ EXPECT_TRUE(list_value_builder->IsEmpty()); \ EXPECT_EQ(list_value_builder->Size(), 0); \ auto list_value = std::move(*list_value_builder).Build(); \ EXPECT_THAT(list_value.IsEmpty(), IsOkAndHolds(true)); \ EXPECT_THAT(list_value.Size(), IsOkAndHolds(0)); \ EXPECT_EQ(list_value.DebugString(), "[]"); \ } TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(BoolType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(BytesType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(DoubleType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(DurationType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(IntType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(ListType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(MapType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(NullType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(OptionalType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(StringType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(TimestampType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(TypeType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(UintType) TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST(DynType) #undef TYPE_REFLECTOR_NEW_LIST_VALUE_BUILDER_TEST #define TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(key_type, value_type) \ TEST_P(TypeReflectorTest, NewMapValueBuilder_##key_type##_##value_type) { \ ASSERT_OK_AND_ASSIGN(auto map_value_builder, \ value_manager().NewMapValueBuilder(MapType())); \ EXPECT_TRUE(map_value_builder->IsEmpty()); \ EXPECT_EQ(map_value_builder->Size(), 0); \ auto map_value = std::move(*map_value_builder).Build(); \ EXPECT_THAT(map_value.IsEmpty(), IsOkAndHolds(true)); \ EXPECT_THAT(map_value.Size(), IsOkAndHolds(0)); \ EXPECT_EQ(map_value.DebugString(), "{}"); \ } TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, BoolType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, BytesType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, DoubleType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, DurationType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, IntType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, ListType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, MapType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, NullType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, OptionalType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, StringType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, TimestampType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, TypeType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, UintType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(BoolType, DynType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, BoolType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, BytesType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, DoubleType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, DurationType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, IntType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, ListType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, MapType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, NullType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, OptionalType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, StringType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, TimestampType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, TypeType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, UintType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(IntType, DynType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, BoolType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, BytesType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, DoubleType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, DurationType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, IntType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, ListType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, MapType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, NullType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, OptionalType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, StringType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, TimestampType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, TypeType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, UintType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(UintType, DynType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, BoolType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, BytesType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, DoubleType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, DurationType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, IntType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, ListType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, MapType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, NullType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, OptionalType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, StringType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, TimestampType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, TypeType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, UintType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(StringType, DynType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, BoolType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, BytesType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, DoubleType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, DurationType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, IntType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, ListType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, MapType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, NullType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, OptionalType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, StringType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, TimestampType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, TypeType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, UintType) TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST(DynType, DynType) #undef TYPE_REFLECTOR_NEW_MAP_VALUE_BUILDER_TEST TEST_P(TypeReflectorTest, NewListValueBuilderCoverage_Dynamic) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewListValueBuilder( ListType(type_factory().GetDynListType()))); EXPECT_OK(builder->Add(IntValue(0))); EXPECT_OK(builder->Add(IntValue(1))); EXPECT_OK(builder->Add(IntValue(2))); EXPECT_EQ(builder->Size(), 3); EXPECT_FALSE(builder->IsEmpty()); auto value = std::move(*builder).Build(); EXPECT_EQ(value.DebugString(), "[0, 1, 2]"); } TEST_P(TypeReflectorTest, NewMapValueBuilderCoverage_DynamicDynamic) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewMapValueBuilder(MapType())); EXPECT_OK(builder->Put(BoolValue(false), IntValue(1))); EXPECT_OK(builder->Put(BoolValue(true), IntValue(2))); EXPECT_OK(builder->Put(IntValue(0), IntValue(3))); EXPECT_OK(builder->Put(IntValue(1), IntValue(4))); EXPECT_OK(builder->Put(UintValue(0), IntValue(5))); EXPECT_OK(builder->Put(UintValue(1), IntValue(6))); EXPECT_OK(builder->Put(StringValue("a"), IntValue(7))); EXPECT_OK(builder->Put(StringValue("b"), IntValue(8))); EXPECT_EQ(builder->Size(), 8); EXPECT_FALSE(builder->IsEmpty()); auto value = std::move(*builder).Build(); EXPECT_EQ( value.DebugString(), "{false: 1, true: 2, 0: 3, 1: 4, 0u: 5, 1u: 6, \"a\": 7, \"b\": 8}"); } TEST_P(TypeReflectorTest, NewMapValueBuilderCoverage_StaticDynamic) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewMapValueBuilder(MapType())); EXPECT_OK(builder->Put(BoolValue(true), IntValue(0))); EXPECT_EQ(builder->Size(), 1); EXPECT_FALSE(builder->IsEmpty()); auto value = std::move(*builder).Build(); EXPECT_EQ(value.DebugString(), "{true: 0}"); } TEST_P(TypeReflectorTest, NewMapValueBuilderCoverage_DynamicStatic) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewMapValueBuilder(MapType())); EXPECT_OK(builder->Put(BoolValue(true), IntValue(0))); EXPECT_EQ(builder->Size(), 1); EXPECT_FALSE(builder->IsEmpty()); auto value = std::move(*builder).Build(); EXPECT_EQ(value.DebugString(), "{true: 0}"); } TEST_P(TypeReflectorTest, JsonKeyCoverage) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewMapValueBuilder(MapType( type_factory().GetDynDynMapType()))); EXPECT_OK(builder->Put(BoolValue(true), IntValue(1))); EXPECT_OK(builder->Put(IntValue(1), IntValue(2))); EXPECT_OK(builder->Put(UintValue(2), IntValue(3))); EXPECT_OK(builder->Put(StringValue("a"), IntValue(4))); auto value = std::move(*builder).Build(); EXPECT_THAT(value.ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_P(TypeReflectorTest, NewValueBuilder_BoolValue) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.BoolValue")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", BoolValue(true)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", IntValue(1)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, BoolValue(true)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, IntValue(1)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<BoolValue>(value)); EXPECT_EQ(Cast<BoolValue>(value).NativeValue(), true); } TEST_P(TypeReflectorTest, NewValueBuilder_Int32Value) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.Int32Value")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName( "value", IntValue(std::numeric_limits<int64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); EXPECT_THAT((*builder)->SetFieldByNumber(1, IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber( 1, IntValue(std::numeric_limits<int64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<IntValue>(value)); EXPECT_EQ(Cast<IntValue>(value).NativeValue(), 1); } TEST_P(TypeReflectorTest, NewValueBuilder_Int64Value) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.Int64Value")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<IntValue>(value)); EXPECT_EQ(Cast<IntValue>(value).NativeValue(), 1); } TEST_P(TypeReflectorTest, NewValueBuilder_UInt32Value) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.UInt32Value")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", UintValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", UintValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName( "value", UintValue(std::numeric_limits<uint64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); EXPECT_THAT((*builder)->SetFieldByNumber(1, UintValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, UintValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber( 1, UintValue(std::numeric_limits<uint64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<UintValue>(value)); EXPECT_EQ(Cast<UintValue>(value).NativeValue(), 1); } TEST_P(TypeReflectorTest, NewValueBuilder_UInt64Value) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.UInt64Value")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", UintValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", UintValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, UintValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, UintValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<UintValue>(value)); EXPECT_EQ(Cast<UintValue>(value).NativeValue(), 1); } TEST_P(TypeReflectorTest, NewValueBuilder_FloatValue) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.FloatValue")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", DoubleValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", DoubleValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, DoubleValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, DoubleValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<DoubleValue>(value)); EXPECT_EQ(Cast<DoubleValue>(value).NativeValue(), 1); } TEST_P(TypeReflectorTest, NewValueBuilder_DoubleValue) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.DoubleValue")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", DoubleValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", DoubleValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, DoubleValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, DoubleValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<DoubleValue>(value)); EXPECT_EQ(Cast<DoubleValue>(value).NativeValue(), 1); } TEST_P(TypeReflectorTest, NewValueBuilder_StringValue) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.StringValue")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", StringValue("foo")), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", StringValue("foo")), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, StringValue("foo")), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, StringValue("foo")), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<StringValue>(value)); EXPECT_EQ(Cast<StringValue>(value).NativeString(), "foo"); } TEST_P(TypeReflectorTest, NewValueBuilder_BytesValue) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.BytesValue")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("value", BytesValue("foo")), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", BytesValue("foo")), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BytesValue("foo")), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, BytesValue("foo")), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<BytesValue>(value)); EXPECT_EQ(Cast<BytesValue>(value).NativeString(), "foo"); } TEST_P(TypeReflectorTest, NewValueBuilder_Duration) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.Duration")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("seconds", IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("seconds", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("nanos", IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName( "nanos", IntValue(std::numeric_limits<int64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); EXPECT_THAT((*builder)->SetFieldByName("nanos", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(3, IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(2, IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber( 2, IntValue(std::numeric_limits<int64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); EXPECT_THAT((*builder)->SetFieldByNumber(2, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<DurationValue>(value)); EXPECT_EQ(Cast<DurationValue>(value).NativeValue(), absl::Seconds(1) + absl::Nanoseconds(1)); } TEST_P(TypeReflectorTest, NewValueBuilder_Timestamp) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder( "google.protobuf.Timestamp")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName("seconds", IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("seconds", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("nanos", IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByName( "nanos", IntValue(std::numeric_limits<int64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); EXPECT_THAT((*builder)->SetFieldByName("nanos", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(1, IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(3, IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(2, IntValue(1)), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber( 2, IntValue(std::numeric_limits<int64_t>::max())), StatusIs(absl::StatusCode::kOutOfRange)); EXPECT_THAT((*builder)->SetFieldByNumber(2, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<TimestampValue>(value)); EXPECT_EQ(Cast<TimestampValue>(value).NativeValue(), absl::UnixEpoch() + absl::Seconds(1) + absl::Nanoseconds(1)); } TEST_P(TypeReflectorTest, NewValueBuilder_Any) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewValueBuilder("google.protobuf.Any")); ASSERT_TRUE(builder.has_value()); EXPECT_THAT((*builder)->SetFieldByName( "type_url", StringValue("type.googleapis.com/google.protobuf.BoolValue")), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("does_not_exist", IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByName("type_url", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByName("value", BytesValue()), IsOk()); EXPECT_THAT((*builder)->SetFieldByName("value", BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( (*builder)->SetFieldByNumber( 1, StringValue("type.googleapis.com/google.protobuf.BoolValue")), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(3, IntValue(1)), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT((*builder)->SetFieldByNumber(1, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT((*builder)->SetFieldByNumber(2, BytesValue()), IsOk()); EXPECT_THAT((*builder)->SetFieldByNumber(2, BoolValue(true)), StatusIs(absl::StatusCode::kInvalidArgument)); auto value = std::move(**builder).Build(); EXPECT_TRUE(InstanceOf<BoolValue>(value)); EXPECT_EQ(Cast<BoolValue>(value).NativeValue(), false); } INSTANTIATE_TEST_SUITE_P( TypeReflectorTest, TypeReflectorTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), TypeReflectorTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/type_reflector.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/type_reflector_test.cc
4552db5798fb0853b131b783d8875794334fae7f
d37b53b4-31a7-4b63-b4fa-2549c355aa9f
cpp
google/cel-cpp
type_introspector
common/type_introspector.cc
extensions/protobuf/type_introspector_test.cc
#include "common/type_introspector.h" #include <algorithm> #include <cstdint> #include <initializer_list> #include "absl/container/flat_hash_map.h" #include "absl/container/inlined_vector.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/memory.h" #include "common/type.h" #include "common/types/thread_compatible_type_introspector.h" namespace cel { namespace { common_internal::BasicStructTypeField MakeBasicStructTypeField( absl::string_view name, Type type, int32_t number) { return common_internal::BasicStructTypeField(name, number, type); } struct FieldNameComparer { using is_transparent = void; bool operator()(const common_internal::BasicStructTypeField& lhs, const common_internal::BasicStructTypeField& rhs) const { return (*this)(lhs.name(), rhs.name()); } bool operator()(const common_internal::BasicStructTypeField& lhs, absl::string_view rhs) const { return (*this)(lhs.name(), rhs); } bool operator()(absl::string_view lhs, const common_internal::BasicStructTypeField& rhs) const { return (*this)(lhs, rhs.name()); } bool operator()(absl::string_view lhs, absl::string_view rhs) const { return lhs < rhs; } }; struct FieldNumberComparer { using is_transparent = void; bool operator()(const common_internal::BasicStructTypeField& lhs, const common_internal::BasicStructTypeField& rhs) const { return (*this)(lhs.number(), rhs.number()); } bool operator()(const common_internal::BasicStructTypeField& lhs, int64_t rhs) const { return (*this)(lhs.number(), rhs); } bool operator()(int64_t lhs, const common_internal::BasicStructTypeField& rhs) const { return (*this)(lhs, rhs.number()); } bool operator()(int64_t lhs, int64_t rhs) const { return lhs < rhs; } }; struct WellKnownType { WellKnownType( const Type& type, std::initializer_list<common_internal::BasicStructTypeField> fields) : type(type), fields_by_name(fields), fields_by_number(fields) { std::sort(fields_by_name.begin(), fields_by_name.end(), FieldNameComparer{}); std::sort(fields_by_number.begin(), fields_by_number.end(), FieldNumberComparer{}); } explicit WellKnownType(const Type& type) : WellKnownType(type, {}) {} Type type; absl::InlinedVector<common_internal::BasicStructTypeField, 2> fields_by_name; absl::InlinedVector<common_internal::BasicStructTypeField, 2> fields_by_number; absl::optional<StructTypeField> FieldByName(absl::string_view name) const { auto it = std::lower_bound(fields_by_name.begin(), fields_by_name.end(), name, FieldNameComparer{}); if (it == fields_by_name.end() || it->name() != name) { return absl::nullopt; } return *it; } absl::optional<StructTypeField> FieldByNumber(int64_t number) const { auto it = std::lower_bound(fields_by_number.begin(), fields_by_number.end(), number, FieldNumberComparer{}); if (it == fields_by_number.end() || it->number() != number) { return absl::nullopt; } return *it; } }; using WellKnownTypesMap = absl::flat_hash_map<absl::string_view, WellKnownType>; const WellKnownTypesMap& GetWellKnownTypesMap() { static const WellKnownTypesMap* types = []() -> WellKnownTypesMap* { WellKnownTypesMap* types = new WellKnownTypesMap(); types->insert_or_assign( "google.protobuf.BoolValue", WellKnownType{BoolWrapperType{}, {MakeBasicStructTypeField("value", BoolType{}, 1)}}); types->insert_or_assign( "google.protobuf.Int32Value", WellKnownType{IntWrapperType{}, {MakeBasicStructTypeField("value", IntType{}, 1)}}); types->insert_or_assign( "google.protobuf.Int64Value", WellKnownType{IntWrapperType{}, {MakeBasicStructTypeField("value", IntType{}, 1)}}); types->insert_or_assign( "google.protobuf.UInt32Value", WellKnownType{UintWrapperType{}, {MakeBasicStructTypeField("value", UintType{}, 1)}}); types->insert_or_assign( "google.protobuf.UInt64Value", WellKnownType{UintWrapperType{}, {MakeBasicStructTypeField("value", UintType{}, 1)}}); types->insert_or_assign( "google.protobuf.FloatValue", WellKnownType{DoubleWrapperType{}, {MakeBasicStructTypeField("value", DoubleType{}, 1)}}); types->insert_or_assign( "google.protobuf.DoubleValue", WellKnownType{DoubleWrapperType{}, {MakeBasicStructTypeField("value", DoubleType{}, 1)}}); types->insert_or_assign( "google.protobuf.StringValue", WellKnownType{StringWrapperType{}, {MakeBasicStructTypeField("value", StringType{}, 1)}}); types->insert_or_assign( "google.protobuf.BytesValue", WellKnownType{BytesWrapperType{}, {MakeBasicStructTypeField("value", BytesType{}, 1)}}); types->insert_or_assign( "google.protobuf.Duration", WellKnownType{DurationType{}, {MakeBasicStructTypeField("seconds", IntType{}, 1), MakeBasicStructTypeField("nanos", IntType{}, 2)}}); types->insert_or_assign( "google.protobuf.Timestamp", WellKnownType{TimestampType{}, {MakeBasicStructTypeField("seconds", IntType{}, 1), MakeBasicStructTypeField("nanos", IntType{}, 2)}}); types->insert_or_assign( "google.protobuf.Value", WellKnownType{ DynType{}, {MakeBasicStructTypeField("null_value", NullType{}, 1), MakeBasicStructTypeField("number_value", DoubleType{}, 2), MakeBasicStructTypeField("string_value", StringType{}, 3), MakeBasicStructTypeField("bool_value", BoolType{}, 4), MakeBasicStructTypeField("struct_value", JsonMapType(), 5), MakeBasicStructTypeField("list_value", ListType{}, 6)}}); types->insert_or_assign( "google.protobuf.ListValue", WellKnownType{ListType{}, {MakeBasicStructTypeField("values", ListType{}, 1)}}); types->insert_or_assign( "google.protobuf.Struct", WellKnownType{JsonMapType(), {MakeBasicStructTypeField("fields", JsonMapType(), 1)}}); types->insert_or_assign( "google.protobuf.Any", WellKnownType{AnyType{}, {MakeBasicStructTypeField("type_url", StringType{}, 1), MakeBasicStructTypeField("value", BytesType{}, 2)}}); types->insert_or_assign("null_type", WellKnownType{NullType{}}); types->insert_or_assign("google.protobuf.NullValue", WellKnownType{NullType{}}); types->insert_or_assign("bool", WellKnownType{BoolType{}}); types->insert_or_assign("int", WellKnownType{IntType{}}); types->insert_or_assign("uint", WellKnownType{UintType{}}); types->insert_or_assign("double", WellKnownType{DoubleType{}}); types->insert_or_assign("bytes", WellKnownType{BytesType{}}); types->insert_or_assign("string", WellKnownType{StringType{}}); types->insert_or_assign("list", WellKnownType{ListType{}}); types->insert_or_assign("map", WellKnownType{MapType{}}); types->insert_or_assign("type", WellKnownType{TypeType{}}); return types; }(); return *types; } } absl::StatusOr<absl::optional<Type>> TypeIntrospector::FindType( TypeFactory& type_factory, absl::string_view name) const { const auto& well_known_types = GetWellKnownTypesMap(); if (auto it = well_known_types.find(name); it != well_known_types.end()) { return it->second.type; } return FindTypeImpl(type_factory, name); } absl::StatusOr<absl::optional<TypeIntrospector::EnumConstant>> TypeIntrospector::FindEnumConstant(TypeFactory& type_factory, absl::string_view type, absl::string_view value) const { if (type == "google.protobuf.NullValue" && value == "NULL_VALUE") { return EnumConstant{NullType{}, "google.protobuf.NullValue", "NULL_VALUE", 0}; } return FindEnumConstantImpl(type_factory, type, value); } absl::StatusOr<absl::optional<StructTypeField>> TypeIntrospector::FindStructTypeFieldByName(TypeFactory& type_factory, absl::string_view type, absl::string_view name) const { const auto& well_known_types = GetWellKnownTypesMap(); if (auto it = well_known_types.find(type); it != well_known_types.end()) { return it->second.FieldByName(name); } return FindStructTypeFieldByNameImpl(type_factory, type, name); } absl::StatusOr<absl::optional<Type>> TypeIntrospector::FindTypeImpl( TypeFactory&, absl::string_view) const { return absl::nullopt; } absl::StatusOr<absl::optional<TypeIntrospector::EnumConstant>> TypeIntrospector::FindEnumConstantImpl(TypeFactory&, absl::string_view, absl::string_view) const { return absl::nullopt; } absl::StatusOr<absl::optional<StructTypeField>> TypeIntrospector::FindStructTypeFieldByNameImpl(TypeFactory&, absl::string_view, absl::string_view) const { return absl::nullopt; } Shared<TypeIntrospector> NewThreadCompatibleTypeIntrospector( MemoryManagerRef memory_manager) { return memory_manager .MakeShared<common_internal::ThreadCompatibleTypeIntrospector>(); } }
#include "extensions/protobuf/type_introspector.h" #include "absl/types/optional.h" #include "common/type.h" #include "common/type_kind.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 ::absl_testing::IsOkAndHolds; using ::google::api::expr::test::v1::proto2::TestAllTypes; using ::testing::Eq; using ::testing::Optional; 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(MessageType(TestAllTypes::GetDescriptor()))))); 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( 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))); } TEST_P(ProtoTypeIntrospectorTest, FindEnumConstant) { ProtoTypeIntrospector introspector; const auto* enum_desc = TestAllTypes::NestedEnum_descriptor(); ASSERT_OK_AND_ASSIGN( auto enum_constant, introspector.FindEnumConstant( type_manager(), "google.api.expr.test.v1.proto2.TestAllTypes.NestedEnum", "BAZ")); ASSERT_TRUE(enum_constant.has_value()); EXPECT_EQ(enum_constant->type.kind(), TypeKind::kEnum); EXPECT_EQ(enum_constant->type_full_name, enum_desc->full_name()); EXPECT_EQ(enum_constant->value_name, "BAZ"); EXPECT_EQ(enum_constant->number, 2); } TEST_P(ProtoTypeIntrospectorTest, FindEnumConstantNull) { ProtoTypeIntrospector introspector; ASSERT_OK_AND_ASSIGN( auto enum_constant, introspector.FindEnumConstant(type_manager(), "google.protobuf.NullValue", "NULL_VALUE")); ASSERT_TRUE(enum_constant.has_value()); EXPECT_EQ(enum_constant->type.kind(), TypeKind::kNull); EXPECT_EQ(enum_constant->type_full_name, "google.protobuf.NullValue"); EXPECT_EQ(enum_constant->value_name, "NULL_VALUE"); EXPECT_EQ(enum_constant->number, 0); } TEST_P(ProtoTypeIntrospectorTest, FindEnumConstantUnknownEnum) { ProtoTypeIntrospector introspector; ASSERT_OK_AND_ASSIGN( auto enum_constant, introspector.FindEnumConstant(type_manager(), "NotARealEnum", "BAZ")); EXPECT_FALSE(enum_constant.has_value()); } TEST_P(ProtoTypeIntrospectorTest, FindEnumConstantUnknownValue) { ProtoTypeIntrospector introspector; ASSERT_OK_AND_ASSIGN( auto enum_constant, introspector.FindEnumConstant( type_manager(), "google.api.expr.test.v1.proto2.TestAllTypes.NestedEnum", "QUX")); ASSERT_FALSE(enum_constant.has_value()); } INSTANTIATE_TEST_SUITE_P( ProtoTypeIntrospectorTest, ProtoTypeIntrospectorTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ProtoTypeIntrospectorTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/type_introspector.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/type_introspector_test.cc
4552db5798fb0853b131b783d8875794334fae7f
9a58c4d0-27d9-4437-9d38-160904208ce5
cpp
google/cel-cpp
type
common/type.cc
common/type_test.cc
#include "common/type.h" #include <array> #include <cstdint> #include <cstring> #include <string> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.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 "common/type_kind.h" #include "common/types/types.h" #include "google/protobuf/descriptor.h" namespace cel { using ::google::protobuf::Descriptor; using ::google::protobuf::FieldDescriptor; Type Type::Message(absl::Nonnull<const Descriptor*> descriptor) { switch (descriptor->well_known_type()) { case Descriptor::WELLKNOWNTYPE_BOOLVALUE: return BoolWrapperType(); case Descriptor::WELLKNOWNTYPE_INT32VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_INT64VALUE: return IntWrapperType(); case Descriptor::WELLKNOWNTYPE_UINT32VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_UINT64VALUE: return UintWrapperType(); case Descriptor::WELLKNOWNTYPE_FLOATVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: return DoubleWrapperType(); case Descriptor::WELLKNOWNTYPE_BYTESVALUE: return BytesWrapperType(); case Descriptor::WELLKNOWNTYPE_STRINGVALUE: return StringWrapperType(); case Descriptor::WELLKNOWNTYPE_ANY: return AnyType(); case Descriptor::WELLKNOWNTYPE_DURATION: return DurationType(); case Descriptor::WELLKNOWNTYPE_TIMESTAMP: return TimestampType(); case Descriptor::WELLKNOWNTYPE_VALUE: return DynType(); case Descriptor::WELLKNOWNTYPE_LISTVALUE: return ListType(); case Descriptor::WELLKNOWNTYPE_STRUCT: return JsonMapType(); default: return MessageType(descriptor); } } Type Type::Enum(absl::Nonnull<const google::protobuf::EnumDescriptor*> descriptor) { if (descriptor->full_name() == "google.protobuf.NullValue") { return NullType(); } return EnumType(descriptor); } namespace { static constexpr std::array<TypeKind, 28> kTypeToKindArray = { TypeKind::kDyn, TypeKind::kAny, TypeKind::kBool, TypeKind::kBoolWrapper, TypeKind::kBytes, TypeKind::kBytesWrapper, TypeKind::kDouble, TypeKind::kDoubleWrapper, TypeKind::kDuration, TypeKind::kEnum, TypeKind::kError, TypeKind::kFunction, TypeKind::kInt, TypeKind::kIntWrapper, TypeKind::kList, TypeKind::kMap, TypeKind::kNull, TypeKind::kOpaque, TypeKind::kString, TypeKind::kStringWrapper, TypeKind::kStruct, TypeKind::kStruct, TypeKind::kTimestamp, TypeKind::kTypeParam, TypeKind::kType, TypeKind::kUint, TypeKind::kUintWrapper, TypeKind::kUnknown}; static_assert(kTypeToKindArray.size() == absl::variant_size<common_internal::TypeVariant>(), "Kind indexer must match variant declaration for cel::Type."); } TypeKind Type::kind() const { return kTypeToKindArray[variant_.index()]; } absl::string_view Type::name() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return absl::visit( [](const auto& alternative) -> absl::string_view { return alternative.name(); }, variant_); } std::string Type::DebugString() const { return absl::visit( [](const auto& alternative) -> std::string { return alternative.DebugString(); }, variant_); } TypeParameters Type::GetParameters() const { return absl::visit( [](const auto& alternative) -> TypeParameters { return alternative.GetParameters(); }, variant_); } bool operator==(const Type& lhs, const Type& rhs) { if (lhs.IsStruct() && rhs.IsStruct()) { return lhs.GetStruct() == rhs.GetStruct(); } else if (lhs.IsStruct() || rhs.IsStruct()) { return false; } else { return lhs.variant_ == rhs.variant_; } } common_internal::StructTypeVariant Type::ToStructTypeVariant() const { if (const auto* other = absl::get_if<MessageType>(&variant_); other != nullptr) { return common_internal::StructTypeVariant(*other); } if (const auto* other = absl::get_if<common_internal::BasicStructType>(&variant_); other != nullptr) { return common_internal::StructTypeVariant(*other); } return common_internal::StructTypeVariant(); } namespace { template <typename T> absl::optional<T> GetOrNullopt(const common_internal::TypeVariant& variant) { if (const auto* alt = absl::get_if<T>(&variant); alt != nullptr) { return *alt; } return absl::nullopt; } } absl::optional<AnyType> Type::AsAny() const { return GetOrNullopt<AnyType>(variant_); } absl::optional<BoolType> Type::AsBool() const { return GetOrNullopt<BoolType>(variant_); } absl::optional<BoolWrapperType> Type::AsBoolWrapper() const { return GetOrNullopt<BoolWrapperType>(variant_); } absl::optional<BytesType> Type::AsBytes() const { return GetOrNullopt<BytesType>(variant_); } absl::optional<BytesWrapperType> Type::AsBytesWrapper() const { return GetOrNullopt<BytesWrapperType>(variant_); } absl::optional<DoubleType> Type::AsDouble() const { return GetOrNullopt<DoubleType>(variant_); } absl::optional<DoubleWrapperType> Type::AsDoubleWrapper() const { return GetOrNullopt<DoubleWrapperType>(variant_); } absl::optional<DurationType> Type::AsDuration() const { return GetOrNullopt<DurationType>(variant_); } absl::optional<DynType> Type::AsDyn() const { return GetOrNullopt<DynType>(variant_); } absl::optional<EnumType> Type::AsEnum() const { return GetOrNullopt<EnumType>(variant_); } absl::optional<ErrorType> Type::AsError() const { return GetOrNullopt<ErrorType>(variant_); } absl::optional<FunctionType> Type::AsFunction() const { return GetOrNullopt<FunctionType>(variant_); } absl::optional<IntType> Type::AsInt() const { return GetOrNullopt<IntType>(variant_); } absl::optional<IntWrapperType> Type::AsIntWrapper() const { return GetOrNullopt<IntWrapperType>(variant_); } absl::optional<ListType> Type::AsList() const { return GetOrNullopt<ListType>(variant_); } absl::optional<MapType> Type::AsMap() const { return GetOrNullopt<MapType>(variant_); } absl::optional<MessageType> Type::AsMessage() const { return GetOrNullopt<MessageType>(variant_); } absl::optional<NullType> Type::AsNull() const { return GetOrNullopt<NullType>(variant_); } absl::optional<OpaqueType> Type::AsOpaque() const { return GetOrNullopt<OpaqueType>(variant_); } absl::optional<OptionalType> Type::AsOptional() const { if (auto maybe_opaque = AsOpaque(); maybe_opaque.has_value()) { return maybe_opaque->AsOptional(); } return absl::nullopt; } absl::optional<StringType> Type::AsString() const { return GetOrNullopt<StringType>(variant_); } absl::optional<StringWrapperType> Type::AsStringWrapper() const { return GetOrNullopt<StringWrapperType>(variant_); } absl::optional<StructType> Type::AsStruct() const { if (const auto* alt = absl::get_if<common_internal::BasicStructType>(&variant_); alt != nullptr) { return *alt; } if (const auto* alt = absl::get_if<MessageType>(&variant_); alt != nullptr) { return *alt; } return absl::nullopt; } absl::optional<TimestampType> Type::AsTimestamp() const { return GetOrNullopt<TimestampType>(variant_); } absl::optional<TypeParamType> Type::AsTypeParam() const { return GetOrNullopt<TypeParamType>(variant_); } absl::optional<TypeType> Type::AsType() const { return GetOrNullopt<TypeType>(variant_); } absl::optional<UintType> Type::AsUint() const { return GetOrNullopt<UintType>(variant_); } absl::optional<UintWrapperType> Type::AsUintWrapper() const { return GetOrNullopt<UintWrapperType>(variant_); } absl::optional<UnknownType> Type::AsUnknown() const { return GetOrNullopt<UnknownType>(variant_); } namespace { template <typename T> T GetOrDie(const common_internal::TypeVariant& variant) { return absl::get<T>(variant); } } AnyType Type::GetAny() const { ABSL_DCHECK(IsAny()) << DebugString(); return GetOrDie<AnyType>(variant_); } BoolType Type::GetBool() const { ABSL_DCHECK(IsBool()) << DebugString(); return GetOrDie<BoolType>(variant_); } BoolWrapperType Type::GetBoolWrapper() const { ABSL_DCHECK(IsBoolWrapper()) << DebugString(); return GetOrDie<BoolWrapperType>(variant_); } BytesType Type::GetBytes() const { ABSL_DCHECK(IsBytes()) << DebugString(); return GetOrDie<BytesType>(variant_); } BytesWrapperType Type::GetBytesWrapper() const { ABSL_DCHECK(IsBytesWrapper()) << DebugString(); return GetOrDie<BytesWrapperType>(variant_); } DoubleType Type::GetDouble() const { ABSL_DCHECK(IsDouble()) << DebugString(); return GetOrDie<DoubleType>(variant_); } DoubleWrapperType Type::GetDoubleWrapper() const { ABSL_DCHECK(IsDoubleWrapper()) << DebugString(); return GetOrDie<DoubleWrapperType>(variant_); } DurationType Type::GetDuration() const { ABSL_DCHECK(IsDuration()) << DebugString(); return GetOrDie<DurationType>(variant_); } DynType Type::GetDyn() const { ABSL_DCHECK(IsDyn()) << DebugString(); return GetOrDie<DynType>(variant_); } EnumType Type::GetEnum() const { ABSL_DCHECK(IsEnum()) << DebugString(); return GetOrDie<EnumType>(variant_); } ErrorType Type::GetError() const { ABSL_DCHECK(IsError()) << DebugString(); return GetOrDie<ErrorType>(variant_); } FunctionType Type::GetFunction() const { ABSL_DCHECK(IsFunction()) << DebugString(); return GetOrDie<FunctionType>(variant_); } IntType Type::GetInt() const { ABSL_DCHECK(IsInt()) << DebugString(); return GetOrDie<IntType>(variant_); } IntWrapperType Type::GetIntWrapper() const { ABSL_DCHECK(IsIntWrapper()) << DebugString(); return GetOrDie<IntWrapperType>(variant_); } ListType Type::GetList() const { ABSL_DCHECK(IsList()) << DebugString(); return GetOrDie<ListType>(variant_); } MapType Type::GetMap() const { ABSL_DCHECK(IsMap()) << DebugString(); return GetOrDie<MapType>(variant_); } MessageType Type::GetMessage() const { ABSL_DCHECK(IsMessage()) << DebugString(); return GetOrDie<MessageType>(variant_); } NullType Type::GetNull() const { ABSL_DCHECK(IsNull()) << DebugString(); return GetOrDie<NullType>(variant_); } OpaqueType Type::GetOpaque() const { ABSL_DCHECK(IsOpaque()) << DebugString(); return GetOrDie<OpaqueType>(variant_); } OptionalType Type::GetOptional() const { ABSL_DCHECK(IsOptional()) << DebugString(); return GetOrDie<OpaqueType>(variant_).GetOptional(); } StringType Type::GetString() const { ABSL_DCHECK(IsString()) << DebugString(); return GetOrDie<StringType>(variant_); } StringWrapperType Type::GetStringWrapper() const { ABSL_DCHECK(IsStringWrapper()) << DebugString(); return GetOrDie<StringWrapperType>(variant_); } StructType Type::GetStruct() const { ABSL_DCHECK(IsStruct()) << DebugString(); if (const auto* alt = absl::get_if<common_internal::BasicStructType>(&variant_); alt != nullptr) { return *alt; } if (const auto* alt = absl::get_if<MessageType>(&variant_); alt != nullptr) { return *alt; } return StructType(); } TimestampType Type::GetTimestamp() const { ABSL_DCHECK(IsTimestamp()) << DebugString(); return GetOrDie<TimestampType>(variant_); } TypeParamType Type::GetTypeParam() const { ABSL_DCHECK(IsTypeParam()) << DebugString(); return GetOrDie<TypeParamType>(variant_); } TypeType Type::GetType() const { ABSL_DCHECK(IsType()) << DebugString(); return GetOrDie<TypeType>(variant_); } UintType Type::GetUint() const { ABSL_DCHECK(IsUint()) << DebugString(); return GetOrDie<UintType>(variant_); } UintWrapperType Type::GetUintWrapper() const { ABSL_DCHECK(IsUintWrapper()) << DebugString(); return GetOrDie<UintWrapperType>(variant_); } UnknownType Type::GetUnknown() const { ABSL_DCHECK(IsUnknown()) << DebugString(); return GetOrDie<UnknownType>(variant_); } Type Type::Unwrap() const { switch (kind()) { case TypeKind::kBoolWrapper: return BoolType(); case TypeKind::kIntWrapper: return IntType(); case TypeKind::kUintWrapper: return UintType(); case TypeKind::kDoubleWrapper: return DoubleType(); case TypeKind::kBytesWrapper: return BytesType(); case TypeKind::kStringWrapper: return StringType(); default: return *this; } } Type Type::Wrap() const { switch (kind()) { case TypeKind::kBool: return BoolWrapperType(); case TypeKind::kInt: return IntWrapperType(); case TypeKind::kUint: return UintWrapperType(); case TypeKind::kDouble: return DoubleWrapperType(); case TypeKind::kBytes: return BytesWrapperType(); case TypeKind::kString: return StringWrapperType(); default: return *this; } } namespace common_internal { Type SingularMessageFieldType( absl::Nonnull<const google::protobuf::FieldDescriptor*> descriptor) { ABSL_DCHECK(!descriptor->is_map()); switch (descriptor->type()) { case FieldDescriptor::TYPE_BOOL: return BoolType(); case FieldDescriptor::TYPE_SFIXED32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_SINT32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_INT32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_SFIXED64: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_SINT64: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_INT64: return IntType(); case FieldDescriptor::TYPE_FIXED32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_UINT32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_FIXED64: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_UINT64: return UintType(); case FieldDescriptor::TYPE_FLOAT: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_DOUBLE: return DoubleType(); case FieldDescriptor::TYPE_BYTES: return BytesType(); case FieldDescriptor::TYPE_STRING: return StringType(); case FieldDescriptor::TYPE_GROUP: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::TYPE_MESSAGE: return Type::Message(descriptor->message_type()); case FieldDescriptor::TYPE_ENUM: return Type::Enum(descriptor->enum_type()); default: return Type(); } } std::string BasicStructTypeField::DebugString() const { if (!name().empty() && number() >= 1) { return absl::StrCat("[", number(), "]", name()); } if (!name().empty()) { return std::string(name()); } if (number() >= 1) { return absl::StrCat(number()); } return std::string(); } } Type Type::Field(absl::Nonnull<const google::protobuf::FieldDescriptor*> descriptor) { if (descriptor->is_map()) { return MapType(descriptor->message_type()); } if (descriptor->is_repeated()) { return ListType(descriptor); } return common_internal::SingularMessageFieldType(descriptor); } std::string StructTypeField::DebugString() const { return absl::visit( [](const auto& alternative) -> std::string { return alternative.DebugString(); }, variant_); } absl::string_view StructTypeField::name() const { return absl::visit( [](const auto& alternative) -> absl::string_view { return alternative.name(); }, variant_); } int32_t StructTypeField::number() const { return absl::visit( [](const auto& alternative) -> int32_t { return alternative.number(); }, variant_); } Type StructTypeField::GetType() const { return absl::visit( [](const auto& alternative) -> Type { return alternative.GetType(); }, variant_); } StructTypeField::operator bool() const { return absl::visit( [](const auto& alternative) -> bool { return static_cast<bool>(alternative); }, variant_); } absl::optional<MessageTypeField> StructTypeField::AsMessage() const { if (const auto* alternative = absl::get_if<MessageTypeField>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } StructTypeField::operator MessageTypeField() const { ABSL_DCHECK(IsMessage()); return absl::get<MessageTypeField>(variant_); } TypeParameters::TypeParameters(absl::Span<const Type> types) : size_(types.size()) { if (size_ <= 2) { std::memcpy(&internal_[0], types.data(), size_ * sizeof(Type)); } else { external_ = types.data(); } } TypeParameters::TypeParameters(const Type& element) : size_(1) { std::memcpy(&internal_[0], &element, sizeof(element)); } TypeParameters::TypeParameters(const Type& key, const Type& value) : size_(2) { std::memcpy(&internal_[0], &key, sizeof(key)); std::memcpy(&internal_[0] + sizeof(key), &value, sizeof(value)); } }
#include "common/type.h" #include "absl/hash/hash.h" #include "absl/hash/hash_testing.h" #include "absl/log/die_if_null.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::cel::internal::GetTestingDescriptorPool; using ::testing::An; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::Optional; TEST(Type, Default) { EXPECT_EQ(Type(), DynType()); EXPECT_TRUE(Type().IsDyn()); } TEST(Type, Enum) { EXPECT_EQ( Type::Enum( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum"))), EnumType(ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum")))); EXPECT_EQ(Type::Enum( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.protobuf.NullValue"))), NullType()); } TEST(Type, Field) { google::protobuf::Arena arena; const auto* descriptor = ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")); EXPECT_EQ( Type::Field(ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_bool"))), BoolType()); EXPECT_EQ( Type::Field(ABSL_DIE_IF_NULL(descriptor->FindFieldByName("null_value"))), NullType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_int32"))), IntType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_sint32"))), IntType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_sfixed32"))), IntType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_int64"))), IntType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_sint64"))), IntType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_sfixed64"))), IntType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_fixed32"))), UintType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_uint32"))), UintType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_fixed64"))), UintType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_uint64"))), UintType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_float"))), DoubleType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_double"))), DoubleType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_bytes"))), BytesType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_string"))), StringType()); EXPECT_EQ( Type::Field(ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_any"))), AnyType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_duration"))), DurationType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_timestamp"))), TimestampType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_struct"))), JsonMapType()); EXPECT_EQ( Type::Field(ABSL_DIE_IF_NULL(descriptor->FindFieldByName("list_value"))), JsonListType()); EXPECT_EQ(Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("single_value"))), JsonType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_bool_wrapper"))), BoolWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_int32_wrapper"))), IntWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_int64_wrapper"))), IntWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_uint32_wrapper"))), UintWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_uint64_wrapper"))), UintWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_float_wrapper"))), DoubleWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_double_wrapper"))), DoubleWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_bytes_wrapper"))), BytesWrapperType()); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("single_string_wrapper"))), StringWrapperType()); EXPECT_EQ( Type::Field( ABSL_DIE_IF_NULL(descriptor->FindFieldByName("standalone_enum"))), EnumType(ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum")))); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("repeated_int32"))), ListType(&arena, IntType())); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( descriptor->FindFieldByName("map_int32_int32"))), MapType(&arena, IntType(), IntType())); } TEST(Type, Kind) { google::protobuf::Arena arena; EXPECT_EQ(Type(AnyType()).kind(), AnyType::kKind); EXPECT_EQ(Type(BoolType()).kind(), BoolType::kKind); EXPECT_EQ(Type(BoolWrapperType()).kind(), BoolWrapperType::kKind); EXPECT_EQ(Type(BytesType()).kind(), BytesType::kKind); EXPECT_EQ(Type(BytesWrapperType()).kind(), BytesWrapperType::kKind); EXPECT_EQ(Type(DoubleType()).kind(), DoubleType::kKind); EXPECT_EQ(Type(DoubleWrapperType()).kind(), DoubleWrapperType::kKind); EXPECT_EQ(Type(DurationType()).kind(), DurationType::kKind); EXPECT_EQ(Type(DynType()).kind(), DynType::kKind); EXPECT_EQ( Type(EnumType( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum")))) .kind(), EnumType::kKind); EXPECT_EQ(Type(ErrorType()).kind(), ErrorType::kKind); EXPECT_EQ(Type(FunctionType(&arena, DynType(), {})).kind(), FunctionType::kKind); EXPECT_EQ(Type(IntType()).kind(), IntType::kKind); EXPECT_EQ(Type(IntWrapperType()).kind(), IntWrapperType::kKind); EXPECT_EQ(Type(ListType()).kind(), ListType::kKind); EXPECT_EQ(Type(MapType()).kind(), MapType::kKind); EXPECT_EQ(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .kind(), MessageType::kKind); EXPECT_EQ(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .kind(), MessageType::kKind); EXPECT_EQ(Type(NullType()).kind(), NullType::kKind); EXPECT_EQ(Type(OptionalType()).kind(), OpaqueType::kKind); EXPECT_EQ(Type(StringType()).kind(), StringType::kKind); EXPECT_EQ(Type(StringWrapperType()).kind(), StringWrapperType::kKind); EXPECT_EQ(Type(TimestampType()).kind(), TimestampType::kKind); EXPECT_EQ(Type(UintType()).kind(), UintType::kKind); EXPECT_EQ(Type(UintWrapperType()).kind(), UintWrapperType::kKind); EXPECT_EQ(Type(UnknownType()).kind(), UnknownType::kKind); } TEST(Type, GetParameters) { google::protobuf::Arena arena; EXPECT_THAT(Type(AnyType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(BoolType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(BoolWrapperType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(BytesType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(BytesWrapperType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(DoubleType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(DoubleWrapperType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(DurationType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(DynType()).GetParameters(), IsEmpty()); EXPECT_THAT( Type(EnumType( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum")))) .GetParameters(), IsEmpty()); EXPECT_THAT(Type(ErrorType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(FunctionType(&arena, DynType(), {IntType(), StringType(), DynType()})) .GetParameters(), ElementsAre(DynType(), IntType(), StringType(), DynType())); EXPECT_THAT(Type(IntType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(IntWrapperType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(ListType()).GetParameters(), ElementsAre(DynType())); EXPECT_THAT(Type(MapType()).GetParameters(), ElementsAre(DynType(), DynType())); EXPECT_THAT(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .GetParameters(), IsEmpty()); EXPECT_THAT(Type(NullType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(OptionalType()).GetParameters(), ElementsAre(DynType())); EXPECT_THAT(Type(StringType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(StringWrapperType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(TimestampType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(UintType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(UintWrapperType()).GetParameters(), IsEmpty()); EXPECT_THAT(Type(UnknownType()).GetParameters(), IsEmpty()); } TEST(Type, Is) { google::protobuf::Arena arena; EXPECT_TRUE(Type(AnyType()).Is<AnyType>()); EXPECT_TRUE(Type(BoolType()).Is<BoolType>()); EXPECT_TRUE(Type(BoolWrapperType()).Is<BoolWrapperType>()); EXPECT_TRUE(Type(BoolWrapperType()).IsWrapper()); EXPECT_TRUE(Type(BytesType()).Is<BytesType>()); EXPECT_TRUE(Type(BytesWrapperType()).Is<BytesWrapperType>()); EXPECT_TRUE(Type(BytesWrapperType()).IsWrapper()); EXPECT_TRUE(Type(DoubleType()).Is<DoubleType>()); EXPECT_TRUE(Type(DoubleWrapperType()).Is<DoubleWrapperType>()); EXPECT_TRUE(Type(DoubleWrapperType()).IsWrapper()); EXPECT_TRUE(Type(DurationType()).Is<DurationType>()); EXPECT_TRUE(Type(DynType()).Is<DynType>()); EXPECT_TRUE( Type(EnumType( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum")))) .Is<EnumType>()); EXPECT_TRUE(Type(ErrorType()).Is<ErrorType>()); EXPECT_TRUE(Type(FunctionType(&arena, DynType(), {})).Is<FunctionType>()); EXPECT_TRUE(Type(IntType()).Is<IntType>()); EXPECT_TRUE(Type(IntWrapperType()).Is<IntWrapperType>()); EXPECT_TRUE(Type(IntWrapperType()).IsWrapper()); EXPECT_TRUE(Type(ListType()).Is<ListType>()); EXPECT_TRUE(Type(MapType()).Is<MapType>()); EXPECT_TRUE(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .IsStruct()); EXPECT_TRUE(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .IsMessage()); EXPECT_TRUE(Type(NullType()).Is<NullType>()); EXPECT_TRUE(Type(OptionalType()).Is<OpaqueType>()); EXPECT_TRUE(Type(OptionalType()).Is<OptionalType>()); EXPECT_TRUE(Type(StringType()).Is<StringType>()); EXPECT_TRUE(Type(StringWrapperType()).Is<StringWrapperType>()); EXPECT_TRUE(Type(StringWrapperType()).IsWrapper()); EXPECT_TRUE(Type(TimestampType()).Is<TimestampType>()); EXPECT_TRUE(Type(TypeType()).Is<TypeType>()); EXPECT_TRUE(Type(TypeParamType("T")).Is<TypeParamType>()); EXPECT_TRUE(Type(UintType()).Is<UintType>()); EXPECT_TRUE(Type(UintWrapperType()).Is<UintWrapperType>()); EXPECT_TRUE(Type(UintWrapperType()).IsWrapper()); EXPECT_TRUE(Type(UnknownType()).Is<UnknownType>()); } TEST(Type, As) { google::protobuf::Arena arena; EXPECT_THAT(Type(AnyType()).As<AnyType>(), Optional(An<AnyType>())); EXPECT_THAT(Type(BoolType()).As<BoolType>(), Optional(An<BoolType>())); EXPECT_THAT(Type(BoolWrapperType()).As<BoolWrapperType>(), Optional(An<BoolWrapperType>())); EXPECT_THAT(Type(BytesType()).As<BytesType>(), Optional(An<BytesType>())); EXPECT_THAT(Type(BytesWrapperType()).As<BytesWrapperType>(), Optional(An<BytesWrapperType>())); EXPECT_THAT(Type(DoubleType()).As<DoubleType>(), Optional(An<DoubleType>())); EXPECT_THAT(Type(DoubleWrapperType()).As<DoubleWrapperType>(), Optional(An<DoubleWrapperType>())); EXPECT_THAT(Type(DurationType()).As<DurationType>(), Optional(An<DurationType>())); EXPECT_THAT(Type(DynType()).As<DynType>(), Optional(An<DynType>())); EXPECT_THAT( Type(EnumType( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum")))) .As<EnumType>(), Optional(An<EnumType>())); EXPECT_THAT(Type(ErrorType()).As<ErrorType>(), Optional(An<ErrorType>())); EXPECT_TRUE(Type(FunctionType(&arena, DynType(), {})).Is<FunctionType>()); EXPECT_THAT(Type(IntType()).As<IntType>(), Optional(An<IntType>())); EXPECT_THAT(Type(IntWrapperType()).As<IntWrapperType>(), Optional(An<IntWrapperType>())); EXPECT_THAT(Type(ListType()).As<ListType>(), Optional(An<ListType>())); EXPECT_THAT(Type(MapType()).As<MapType>(), Optional(An<MapType>())); EXPECT_THAT(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .As<StructType>(), Optional(An<StructType>())); EXPECT_THAT(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))) .As<MessageType>(), Optional(An<MessageType>())); EXPECT_THAT(Type(NullType()).As<NullType>(), Optional(An<NullType>())); EXPECT_THAT(Type(OptionalType()).As<OptionalType>(), Optional(An<OptionalType>())); EXPECT_THAT(Type(OptionalType()).As<OptionalType>(), Optional(An<OptionalType>())); EXPECT_THAT(Type(StringType()).As<StringType>(), Optional(An<StringType>())); EXPECT_THAT(Type(StringWrapperType()).As<StringWrapperType>(), Optional(An<StringWrapperType>())); EXPECT_THAT(Type(TimestampType()).As<TimestampType>(), Optional(An<TimestampType>())); EXPECT_THAT(Type(TypeType()).As<TypeType>(), Optional(An<TypeType>())); EXPECT_THAT(Type(TypeParamType("T")).As<TypeParamType>(), Optional(An<TypeParamType>())); EXPECT_THAT(Type(UintType()).As<UintType>(), Optional(An<UintType>())); EXPECT_THAT(Type(UintWrapperType()).As<UintWrapperType>(), Optional(An<UintWrapperType>())); EXPECT_THAT(Type(UnknownType()).As<UnknownType>(), Optional(An<UnknownType>())); } template <typename T> T DoGet(const Type& type) { return type.template Get<T>(); } TEST(Type, Get) { google::protobuf::Arena arena; EXPECT_THAT(DoGet<AnyType>(Type(AnyType())), An<AnyType>()); EXPECT_THAT(DoGet<BoolType>(Type(BoolType())), An<BoolType>()); EXPECT_THAT(DoGet<BoolWrapperType>(Type(BoolWrapperType())), An<BoolWrapperType>()); EXPECT_THAT(DoGet<BoolWrapperType>(Type(BoolWrapperType())), An<BoolWrapperType>()); EXPECT_THAT(DoGet<BytesType>(Type(BytesType())), An<BytesType>()); EXPECT_THAT(DoGet<BytesWrapperType>(Type(BytesWrapperType())), An<BytesWrapperType>()); EXPECT_THAT(DoGet<BytesWrapperType>(Type(BytesWrapperType())), An<BytesWrapperType>()); EXPECT_THAT(DoGet<DoubleType>(Type(DoubleType())), An<DoubleType>()); EXPECT_THAT(DoGet<DoubleWrapperType>(Type(DoubleWrapperType())), An<DoubleWrapperType>()); EXPECT_THAT(DoGet<DoubleWrapperType>(Type(DoubleWrapperType())), An<DoubleWrapperType>()); EXPECT_THAT(DoGet<DurationType>(Type(DurationType())), An<DurationType>()); EXPECT_THAT(DoGet<DynType>(Type(DynType())), An<DynType>()); EXPECT_THAT( DoGet<EnumType>(Type(EnumType( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindEnumTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum"))))), An<EnumType>()); EXPECT_THAT(DoGet<ErrorType>(Type(ErrorType())), An<ErrorType>()); EXPECT_THAT(DoGet<FunctionType>(Type(FunctionType(&arena, DynType(), {}))), An<FunctionType>()); EXPECT_THAT(DoGet<IntType>(Type(IntType())), An<IntType>()); EXPECT_THAT(DoGet<IntWrapperType>(Type(IntWrapperType())), An<IntWrapperType>()); EXPECT_THAT(DoGet<IntWrapperType>(Type(IntWrapperType())), An<IntWrapperType>()); EXPECT_THAT(DoGet<ListType>(Type(ListType())), An<ListType>()); EXPECT_THAT(DoGet<MapType>(Type(MapType())), An<MapType>()); EXPECT_THAT(DoGet<StructType>(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes"))))), An<StructType>()); EXPECT_THAT(DoGet<MessageType>(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes"))))), An<MessageType>()); EXPECT_THAT(DoGet<NullType>(Type(NullType())), An<NullType>()); EXPECT_THAT(DoGet<OptionalType>(Type(OptionalType())), An<OptionalType>()); EXPECT_THAT(DoGet<OptionalType>(Type(OptionalType())), An<OptionalType>()); EXPECT_THAT(DoGet<StringType>(Type(StringType())), An<StringType>()); EXPECT_THAT(DoGet<StringWrapperType>(Type(StringWrapperType())), An<StringWrapperType>()); EXPECT_THAT(DoGet<StringWrapperType>(Type(StringWrapperType())), An<StringWrapperType>()); EXPECT_THAT(DoGet<TimestampType>(Type(TimestampType())), An<TimestampType>()); EXPECT_THAT(DoGet<TypeType>(Type(TypeType())), An<TypeType>()); EXPECT_THAT(DoGet<TypeParamType>(Type(TypeParamType("T"))), An<TypeParamType>()); EXPECT_THAT(DoGet<UintType>(Type(UintType())), An<UintType>()); EXPECT_THAT(DoGet<UintWrapperType>(Type(UintWrapperType())), An<UintWrapperType>()); EXPECT_THAT(DoGet<UintWrapperType>(Type(UintWrapperType())), An<UintWrapperType>()); EXPECT_THAT(DoGet<UnknownType>(Type(UnknownType())), An<UnknownType>()); } TEST(Type, VerifyTypeImplementsAbslHashCorrectly) { google::protobuf::Arena arena; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {Type(AnyType()), Type(BoolType()), Type(BoolWrapperType()), Type(BytesType()), Type(BytesWrapperType()), Type(DoubleType()), Type(DoubleWrapperType()), Type(DurationType()), Type(DynType()), Type(ErrorType()), Type(FunctionType(&arena, DynType(), {DynType()})), Type(IntType()), Type(IntWrapperType()), Type(ListType(&arena, DynType())), Type(MapType(&arena, DynType(), DynType())), Type(NullType()), Type(OptionalType(&arena, DynType())), Type(StringType()), Type(StringWrapperType()), Type(StructType(common_internal::MakeBasicStructType("test.Struct"))), Type(TimestampType()), Type(TypeParamType("T")), Type(TypeType()), Type(UintType()), Type(UintWrapperType()), Type(UnknownType())})); EXPECT_EQ( absl::HashOf(Type::Field( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")) ->FindFieldByName("repeated_int64"))), absl::HashOf(Type(ListType(&arena, IntType())))); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")) ->FindFieldByName("repeated_int64")), Type(ListType(&arena, IntType()))); EXPECT_EQ( absl::HashOf(Type::Field( ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")) ->FindFieldByName("map_int64_int64"))), absl::HashOf(Type(MapType(&arena, IntType(), IntType())))); EXPECT_EQ(Type::Field(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")) ->FindFieldByName("map_int64_int64")), Type(MapType(&arena, IntType(), IntType()))); EXPECT_EQ(absl::HashOf(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes"))))), absl::HashOf(Type(StructType(common_internal::MakeBasicStructType( "google.api.expr.test.v1.proto3.TestAllTypes"))))); EXPECT_EQ(Type(MessageType(ABSL_DIE_IF_NULL( GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes")))), Type(StructType(common_internal::MakeBasicStructType( "google.api.expr.test.v1.proto3.TestAllTypes")))); } TEST(Type, Unwrap) { EXPECT_EQ(Type(BoolWrapperType()).Unwrap(), BoolType()); EXPECT_EQ(Type(IntWrapperType()).Unwrap(), IntType()); EXPECT_EQ(Type(UintWrapperType()).Unwrap(), UintType()); EXPECT_EQ(Type(DoubleWrapperType()).Unwrap(), DoubleType()); EXPECT_EQ(Type(BytesWrapperType()).Unwrap(), BytesType()); EXPECT_EQ(Type(StringWrapperType()).Unwrap(), StringType()); EXPECT_EQ(Type(AnyType()).Unwrap(), AnyType()); } TEST(Type, Wrap) { EXPECT_EQ(Type(BoolType()).Wrap(), BoolWrapperType()); EXPECT_EQ(Type(IntType()).Wrap(), IntWrapperType()); EXPECT_EQ(Type(UintType()).Wrap(), UintWrapperType()); EXPECT_EQ(Type(DoubleType()).Wrap(), DoubleWrapperType()); EXPECT_EQ(Type(BytesType()).Wrap(), BytesWrapperType()); EXPECT_EQ(Type(StringType()).Wrap(), StringWrapperType()); EXPECT_EQ(Type(AnyType()).Wrap(), AnyType()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
dc1dee63-2514-4493-8277-ec5ec028b543
cpp
google/cel-cpp
bind_proto_to_activation
extensions/protobuf/bind_proto_to_activation.cc
extensions/protobuf/bind_proto_to_activation_test.cc
#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 ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::test::IntValueIs; using ::google::api::expr::test::v1::proto2::TestAllTypes; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Optional; 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)); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/bind_proto_to_activation.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/bind_proto_to_activation_test.cc
4552db5798fb0853b131b783d8875794334fae7f
5596e95d-05d0-4549-a9d7-d039d691e49b
cpp
google/cel-cpp
ast_converters
extensions/protobuf/ast_converters.cc
extensions/protobuf/ast_converters_test.cc
#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::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 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<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; } } namespace { using ::cel::ast_internal::AbstractType; using ::cel::ast_internal::AstImpl; 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) { return CreateAstFromParsedExpr(parsed_expr.expr(), &parsed_expr.source_info()); } 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(Expr expr, internal::ConvertProtoExprToNative(checked_expr.expr())); CEL_ASSIGN_OR_RETURN( SourceInfo source_info, internal::ConvertProtoSourceInfoToNative(checked_expr.source_info())); AstImpl::ReferenceMap reference_map; for (const auto& pair : checked_expr.reference_map()) { auto native_reference = internal::ConvertProtoReferenceToNative(pair.second); if (!native_reference.ok()) { return native_reference.status(); } reference_map.emplace(pair.first, *(std::move(native_reference))); } AstImpl::TypeMap type_map; for (const auto& pair : checked_expr.type_map()) { auto native_type = internal::ConvertProtoTypeToNative(pair.second); if (!native_type.ok()) { return native_type.status(); } type_map.emplace(pair.first, *(std::move(native_type))); } return std::make_unique<AstImpl>( std::move(expr), std::move(source_info), std::move(reference_map), std::move(type_map), checked_expr.expr_version()); } 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 ::absl_testing::StatusIs; using ::cel::ast_internal::NullValue; using ::cel::ast_internal::PrimitiveType; using ::cel::ast_internal::WellKnownType; 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, 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()); } } } namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::internal::test::EqualsProto; using ::google::api::expr::parser::Parse; using ::testing::HasSubstr; 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::AstImpl ast; ast.root_expr().set_id(1); ast.root_expr().mutable_ident_expr().set_name("expr"); ast.source_info().set_syntax_version("version"); ast.source_info().set_location("location"); ast.source_info().mutable_line_offsets().push_back(1); ast.source_info().mutable_line_offsets().push_back(2); ast.source_info().mutable_positions().insert({1, 2}); ast.source_info().mutable_positions().insert({3, 4}); ast_internal::Expr macro; macro.mutable_ident_expr().set_name("name"); ast.source_info().mutable_macro_calls().insert({1, std::move(macro)}); ast_internal::AstImpl::TypeMap type_map; ast_internal::AstImpl::ReferenceMap 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.reference_map().insert({1, std::move(reference)}); ast.type_map().insert({1, std::move(type)}); ast.set_expr_version("version"); ast.set_is_checked(true); 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::AstImpl ast(std::move(expr), std::move(source_info)); 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))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/ast_converters.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/ast_converters_test.cc
4552db5798fb0853b131b783d8875794334fae7f
fe88a1a3-3336-4fb1-9fd3-55428cfbc69e
cpp
google/cel-cpp
memory_manager
extensions/protobuf/memory_manager.cc
extensions/protobuf/memory_manager_test.cc
#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()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/memory_manager.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/memory_manager_test.cc
4552db5798fb0853b131b783d8875794334fae7f
dce4203b-7007-428f-b60f-a239e8cc6927
cpp
google/cel-cpp
timestamp
extensions/protobuf/internal/timestamp.cc
extensions/protobuf/internal/timestamp_test.cc
#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/is_generated_message.h" #include "extensions/protobuf/internal/is_message_lite.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 constexpr (NotMessageLite<google::protobuf::Timestamp>) { if (IsGeneratedMessage(message)) { return UnwrapGeneratedTimestampProto( google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::Timestamp>) { if (IsGeneratedMessage(message)) { return WrapGeneratedTimestampProto( value, google::protobuf::DownCastMessage<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 ::absl_testing::IsOkAndHolds; using ::testing::Eq; 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); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/timestamp.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/timestamp_test.cc
4552db5798fb0853b131b783d8875794334fae7f
b88e1308-3599-460c-8a88-6e076d5b4ee0
cpp
google/cel-cpp
any
common/any.cc
common/any_test.cc
#include "common/any.h" #include "absl/base/nullability.h" #include "absl/strings/string_view.h" namespace cel { bool ParseTypeUrl(absl::string_view type_url, absl::Nullable<absl::string_view*> prefix, absl::Nullable<absl::string_view*> type_name) { auto pos = type_url.find_last_of('/'); if (pos == absl::string_view::npos || pos + 1 == type_url.size()) { return false; } if (prefix) { *prefix = type_url.substr(0, pos + 1); } if (type_name) { *type_name = type_url.substr(pos + 1); } return true; } }
#include "common/any.h" #include <string> #include "google/protobuf/any.pb.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "internal/testing.h" namespace cel { namespace { TEST(Any, Value) { google::protobuf::Any any; std::string scratch; SetAnyValueFromCord(&any, absl::Cord("Hello World!")); EXPECT_EQ(GetAnyValueAsCord(any), "Hello World!"); EXPECT_EQ(GetAnyValueAsString(any), "Hello World!"); EXPECT_EQ(GetAnyValueAsStringView(any, scratch), "Hello World!"); } TEST(MakeTypeUrlWithPrefix, Basic) { EXPECT_EQ(MakeTypeUrlWithPrefix("foo", "bar.Baz"), "foo/bar.Baz"); EXPECT_EQ(MakeTypeUrlWithPrefix("foo/", "bar.Baz"), "foo/bar.Baz"); } TEST(MakeTypeUrl, Basic) { EXPECT_EQ(MakeTypeUrl("bar.Baz"), "type.googleapis.com/bar.Baz"); } TEST(ParseTypeUrl, Valid) { EXPECT_TRUE(ParseTypeUrl("type.googleapis.com/bar.Baz")); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com")); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com/")); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com/foo/")); } TEST(ParseTypeUrl, TypeName) { absl::string_view type_name; EXPECT_TRUE(ParseTypeUrl("type.googleapis.com/bar.Baz", &type_name)); EXPECT_EQ(type_name, "bar.Baz"); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com", &type_name)); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com/", &type_name)); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com/foo/", &type_name)); } TEST(ParseTypeUrl, PrefixAndTypeName) { absl::string_view prefix; absl::string_view type_name; EXPECT_TRUE(ParseTypeUrl("type.googleapis.com/bar.Baz", &prefix, &type_name)); EXPECT_EQ(prefix, "type.googleapis.com/"); EXPECT_EQ(type_name, "bar.Baz"); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com", &prefix, &type_name)); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com/", &prefix, &type_name)); EXPECT_FALSE(ParseTypeUrl("type.googleapis.com/foo/", &prefix, &type_name)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/any.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/any_test.cc
4552db5798fb0853b131b783d8875794334fae7f
639f12ec-94cf-4ade-98fe-9223116f5cae
cpp
google/cel-cpp
constant
common/constant.cc
common/constant_test.cc
#include "common/constant.h" #include <cmath> #include <cstdint> #include <string> #include "absl/base/no_destructor.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "internal/strings.h" namespace cel { const BytesConstant& BytesConstant::default_instance() { static const absl::NoDestructor<BytesConstant> instance; return *instance; } const StringConstant& StringConstant::default_instance() { static const absl::NoDestructor<StringConstant> instance; return *instance; } const Constant& Constant::default_instance() { static const absl::NoDestructor<Constant> instance; return *instance; } std::string FormatNullConstant() { return "null"; } std::string FormatBoolConstant(bool value) { return value ? std::string("true") : std::string("false"); } std::string FormatIntConstant(int64_t value) { return absl::StrCat(value); } std::string FormatUintConstant(uint64_t value) { return absl::StrCat(value, "u"); } std::string FormatDoubleConstant(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"); } return stringified; } if (std::isnan(value)) { return "nan"; } if (std::signbit(value)) { return "-infinity"; } return "+infinity"; } std::string FormatBytesConstant(absl::string_view value) { return internal::FormatBytesLiteral(value); } std::string FormatStringConstant(absl::string_view value) { return internal::FormatStringLiteral(value); } std::string FormatDurationConstant(absl::Duration value) { return absl::StrCat("duration(\"", absl::FormatDuration(value), "\")"); } std::string FormatTimestampConstant(absl::Time value) { return absl::StrCat( "timestamp(\"", absl::FormatTime("%Y-%m-%d%ET%H:%M:%E*SZ", value, absl::UTCTimeZone()), "\")"); } }
#include "common/constant.h" #include <cmath> #include <cstddef> #include <cstdint> #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()); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<std::nullptr_t>()); } 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); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<bool>()); } 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); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<int64_t>()); } 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); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<uint64_t>()); } 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); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<double>()); } 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"); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<BytesConstant>()); } 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"); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<StringConstant>()); } 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()); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<absl::Duration>()); } 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()); EXPECT_EQ(const_expr.kind().index(), ConstantKindIndexOf<absl::Time>()); } 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\")"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/constant.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/constant_test.cc
4552db5798fb0853b131b783d8875794334fae7f
228440bd-1351-4db5-9e28-9f82e36e1b7b
cpp
google/cel-cpp
struct
extensions/protobuf/internal/struct.cc
extensions/protobuf/internal/struct_test.cc
#include "extensions/protobuf/internal/struct.h" #include <string> #include <type_traits> #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/is_generated_message.h" #include "extensions/protobuf/internal/is_message_lite.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 { template <typename T> std::enable_if_t<NotMessageLite<T>, google::protobuf::Message*> UpCastMessage( T* message) { return message; } template <typename T> std::enable_if_t<IsMessageLite<T>, google::protobuf::Message*> UpCastMessage(T* message); 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 constexpr (NotMessageLite<google::protobuf::Value>) { if (IsGeneratedMessage(message)) { return GeneratedValueProtoToJson( google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::ListValue>) { if (IsGeneratedMessage(message)) { return GeneratedListValueProtoToJson( google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::Struct>) { if (IsGeneratedMessage(message)) { return GeneratedStructProtoToJson( google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::Value>) { if (IsGeneratedMessage(message)) { return GeneratedValueProtoFromJson( json, google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::ListValue>) { if (IsGeneratedMessage(message)) { return GeneratedListValueProtoFromJson( json, google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::Struct>) { if (IsGeneratedMessage(message)) { return GeneratedStructProtoFromJson( json, google::protobuf::DownCastMessage<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) { std::string map_key_string = static_cast<std::string>(entry.first); google::protobuf::MapKey map_key; map_key.SetStringValue(map_key_string); 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(); } absl::Status DynamicValueProtoSetNullValue(google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Value>) { if (IsGeneratedMessage(*message)) { GeneratedValueProtoSetNullValue( google::protobuf::DownCastMessage<google::protobuf::Value>(message)); return absl::OkStatus(); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); 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(); } absl::Status DynamicValueProtoSetBoolValue(bool value, google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Value>) { if (IsGeneratedMessage(*message)) { GeneratedValueProtoSetBoolValue( value, google::protobuf::DownCastMessage<google::protobuf::Value>(message)); return absl::OkStatus(); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); 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(); } absl::Status DynamicValueProtoSetNumberValue(double value, google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Value>) { if (IsGeneratedMessage(*message)) { GeneratedValueProtoSetNumberValue( value, google::protobuf::DownCastMessage<google::protobuf::Value>(message)); return absl::OkStatus(); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); 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(); } absl::Status DynamicValueProtoSetStringValue(absl::string_view value, google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Value>) { if (IsGeneratedMessage(*message)) { GeneratedValueProtoSetStringValue( value, google::protobuf::DownCastMessage<google::protobuf::Value>(message)); return absl::OkStatus(); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); 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(); } absl::StatusOr<google::protobuf::Message*> DynamicValueProtoMutableListValue( google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Value> && NotMessageLite<google::protobuf::ListValue>) { if (IsGeneratedMessage(*message)) { return UpCastMessage(GeneratedValueProtoMutableListValue( google::protobuf::DownCastMessage<google::protobuf::Value>(message))); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); 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 reflection->MutableMessage(message, list_value_field); } absl::StatusOr<google::protobuf::Message*> DynamicValueProtoMutableStructValue( google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Value"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Value> && NotMessageLite<google::protobuf::Struct>) { if (IsGeneratedMessage(*message)) { return UpCastMessage(GeneratedValueProtoMutableStructValue( google::protobuf::DownCastMessage<google::protobuf::Value>(message))); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); 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 reflection->MutableMessage(message, struct_value_field); } absl::StatusOr<google::protobuf::Message*> DynamicListValueProtoAddElement( google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.ListValue"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::ListValue>) { if (IsGeneratedMessage(*message)) { return UpCastMessage(GeneratedListValueProtoAddElement( google::protobuf::DownCastMessage<google::protobuf::ListValue>(message))); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); CEL_ASSIGN_OR_RETURN( const auto* element_field, FindFieldByNumber(desc, google::protobuf::ListValue::kValuesFieldNumber)); CEL_RETURN_IF_ERROR( CheckFieldMessageType(element_field, "google.protobuf.Value")); CEL_RETURN_IF_ERROR(CheckFieldRepeated(element_field)); return reflection->AddMessage(message, element_field); } absl::StatusOr<google::protobuf::Message*> DynamicStructValueProtoAddField( absl::string_view name, google::protobuf::Message* message) { ABSL_DCHECK_EQ(message->GetTypeName(), "google.protobuf.Struct"); CEL_ASSIGN_OR_RETURN(const auto* desc, GetDescriptor(*message)); if constexpr (NotMessageLite<google::protobuf::Struct>) { if (IsGeneratedMessage(*message)) { return UpCastMessage(GeneratedStructValueProtoAddField( name, google::protobuf::DownCastMessage<google::protobuf::Struct>(message))); } } CEL_ASSIGN_OR_RETURN(const auto* reflection, GetReflection(*message)); CEL_ASSIGN_OR_RETURN( const auto* map_field, FindFieldByNumber(desc, google::protobuf::Struct::kFieldsFieldNumber)); CEL_RETURN_IF_ERROR(CheckFieldMap(map_field)); CEL_RETURN_IF_ERROR(CheckFieldType(map_field->message_type()->map_key(), google::protobuf::FieldDescriptor::CPPTYPE_STRING)); CEL_RETURN_IF_ERROR(CheckFieldMessageType( map_field->message_type()->map_value(), "google.protobuf.Value")); std::string key_string = std::string(name); google::protobuf::MapKey key; key.SetStringValue(key_string); google::protobuf::MapValueRef value; InsertOrLookupMapValue(*reflection, message, *map_field, key, &value); return value.MutableMessageValue(); } }
#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 ::absl_testing::IsOkAndHolds; using ::google::api::expr::testutil::EqualsProto; using ::testing::IsEmpty; using ::testing::VariantWith; 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))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/struct.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/struct_test.cc
4552db5798fb0853b131b783d8875794334fae7f
11b9ca7d-c6c5-4e38-9f83-784f153d6efd
cpp
google/cel-cpp
wrappers
extensions/protobuf/internal/wrappers.cc
extensions/protobuf/internal/wrappers_test.cc
#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/is_generated_message.h" #include "extensions/protobuf/internal/is_message_lite.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 constexpr (NotMessageLite<T>) { if (IsGeneratedMessage(message)) { 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 constexpr (NotMessageLite<T>) { if (IsGeneratedMessage(message)) { 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 ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; 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); } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/wrappers.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/wrappers_test.cc
4552db5798fb0853b131b783d8875794334fae7f
6e35bbc7-1b0a-42d5-8c5e-f0868b68394d
cpp
google/cel-cpp
ast
extensions/protobuf/internal/ast.cc
extensions/protobuf/internal/ast_test.cc
#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 ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::cel::internal::test::EqualsProto; 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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/ast.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/ast_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e1c22087-66df-40a5-a4bc-a00b88a25171
cpp
google/cel-cpp
field_mask
extensions/protobuf/internal/field_mask.cc
extensions/protobuf/internal/field_mask_test.cc
#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 "extensions/protobuf/internal/is_generated_message.h" #include "extensions/protobuf/internal/is_message_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 constexpr (NotMessageLite<google::protobuf::FieldMask>) { if (IsGeneratedMessage(message)) { return GeneratedFieldMaskProtoToJsonString( google::protobuf::DownCastMessage<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 ::absl_testing::IsOkAndHolds; using ::testing::Eq; 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")))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/field_mask.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/field_mask_test.cc
4552db5798fb0853b131b783d8875794334fae7f
22b80074-28d5-4dc2-b4e0-e438581af639
cpp
google/cel-cpp
duration
extensions/protobuf/internal/duration.cc
extensions/protobuf/internal/duration_test.cc
#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 "extensions/protobuf/internal/is_generated_message.h" #include "extensions/protobuf/internal/is_message_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 constexpr (NotMessageLite<google::protobuf::Duration>) { if (IsGeneratedMessage(message)) { return UnwrapGeneratedDurationProto( google::protobuf::DownCastMessage<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 constexpr (NotMessageLite<google::protobuf::Duration>) { if (IsGeneratedMessage(message)) { return WrapGeneratedDurationProto( value, google::protobuf::DownCastMessage<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 ::absl_testing::IsOkAndHolds; using ::testing::Eq; 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); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/duration.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/duration_test.cc
4552db5798fb0853b131b783d8875794334fae7f
3ecfa19f-269a-4559-ba6a-c352b92f1c18
cpp
google/cel-cpp
message
extensions/protobuf/internal/message.cc
extensions/protobuf/internal/message_test.cc
#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(const Value& value, google::protobuf::MapKey& key, std::string&) { if (auto bool_value = As<BoolValue>(value); bool_value) { key.SetBoolValue(bool_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } absl::Status ProtoInt32MapKeyFromValueConverter(const Value& value, google::protobuf::MapKey& key, std::string&) { 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"); } key.SetInt32Value(static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoInt64MapKeyFromValueConverter(const Value& value, google::protobuf::MapKey& key, std::string&) { if (auto int_value = As<IntValue>(value); int_value) { key.SetInt64Value(int_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoUInt32MapKeyFromValueConverter(const Value& value, google::protobuf::MapKey& key, std::string&) { 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"); } key.SetUInt32Value(static_cast<uint32_t>(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoUInt64MapKeyFromValueConverter(const Value& value, google::protobuf::MapKey& key, std::string&) { if (auto uint_value = As<UintValue>(value); uint_value) { key.SetUInt64Value(uint_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoStringMapKeyFromValueConverter(const Value& value, google::protobuf::MapKey& key, std::string& key_string) { if (auto string_value = As<StringValue>(value); string_value) { key_string = string_value->NativeString(); key.SetStringValue(key_string); 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::Status (*)(const google::protobuf::MapKey&, ValueManager&, Value&); absl::Status ProtoBoolMapKeyToValueConverter(const google::protobuf::MapKey& key, ValueManager&, Value& result) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_BOOL, key.type())); result = BoolValue{key.GetBoolValue()}; return absl::OkStatus(); } absl::Status ProtoInt32MapKeyToValueConverter(const google::protobuf::MapKey& key, ValueManager&, Value& result) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_INT32, key.type())); result = IntValue{key.GetInt32Value()}; return absl::OkStatus(); } absl::Status ProtoInt64MapKeyToValueConverter(const google::protobuf::MapKey& key, ValueManager&, Value& result) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_INT64, key.type())); result = IntValue{key.GetInt64Value()}; return absl::OkStatus(); } absl::Status ProtoUInt32MapKeyToValueConverter(const google::protobuf::MapKey& key, ValueManager&, Value& result) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_UINT32, key.type())); result = UintValue{key.GetUInt32Value()}; return absl::OkStatus(); } absl::Status ProtoUInt64MapKeyToValueConverter(const google::protobuf::MapKey& key, ValueManager&, Value& result) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_UINT64, key.type())); result = UintValue{key.GetUInt64Value()}; return absl::OkStatus(); } absl::Status ProtoStringMapKeyToValueConverter(const google::protobuf::MapKey& key, ValueManager& value_manager, Value& result) { CEL_RETURN_IF_ERROR(ProtoMapKeyTypeMismatch( google::protobuf::FieldDescriptor::CPPTYPE_STRING, key.type())); result = StringValue{key.GetStringValue()}; return absl::OkStatus(); } 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( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto bool_value = As<BoolValue>(value); bool_value) { value_ref.SetBoolValue(bool_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bool").NativeValue(); } absl::Status ProtoInt32MapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { 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"); } value_ref.SetInt32Value(static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoInt64MapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto int_value = As<IntValue>(value); int_value) { value_ref.SetInt64Value(int_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "int").NativeValue(); } absl::Status ProtoUInt32MapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { 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"); } value_ref.SetUInt32Value(static_cast<uint32_t>(uint_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoUInt64MapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto uint_value = As<UintValue>(value); uint_value) { value_ref.SetUInt64Value(uint_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "uint").NativeValue(); } absl::Status ProtoFloatMapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto double_value = As<DoubleValue>(value); double_value) { value_ref.SetFloatValue(double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status ProtoDoubleMapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto double_value = As<DoubleValue>(value); double_value) { value_ref.SetDoubleValue(double_value->NativeValue()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "double").NativeValue(); } absl::Status ProtoBytesMapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto bytes_value = As<BytesValue>(value); bytes_value) { value_ref.SetStringValue(bytes_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "bytes").NativeValue(); } absl::Status ProtoStringMapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (auto string_value = As<StringValue>(value); string_value) { value_ref.SetStringValue(string_value->NativeString()); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "string").NativeValue(); } absl::Status ProtoNullMapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*>, google::protobuf::MapValueRef& value_ref) { if (InstanceOf<NullValue>(value) || InstanceOf<IntValue>(value)) { value_ref.SetEnumValue(0); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "google.protobuf.NullValue") .NativeValue(); } absl::Status ProtoEnumMapValueFromValueConverter( const Value& value, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, google::protobuf::MapValueRef& value_ref) { 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"); } value_ref.SetEnumValue(static_cast<int32_t>(int_value->NativeValue())); return absl::OkStatus(); } return TypeConversionError(value.GetTypeName(), "enum").NativeValue(); } absl::Status ProtoMessageMapValueFromValueConverter( const Value& 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::Status (*)( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*>, const google::protobuf::MapValueConstRef&, ValueManager&, Value&); absl::Status ProtoBoolMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = BoolValue{value_ref.GetBoolValue()}; return absl::OkStatus(); } absl::Status ProtoInt32MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = IntValue{value_ref.GetInt32Value()}; return absl::OkStatus(); } absl::Status ProtoInt64MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = IntValue{value_ref.GetInt64Value()}; return absl::OkStatus(); } absl::Status ProtoUInt32MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = UintValue{value_ref.GetUInt32Value()}; return absl::OkStatus(); } absl::Status ProtoUInt64MapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = UintValue{value_ref.GetUInt64Value()}; return absl::OkStatus(); } absl::Status ProtoFloatMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = DoubleValue{value_ref.GetFloatValue()}; return absl::OkStatus(); } absl::Status ProtoDoubleMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = DoubleValue{value_ref.GetDoubleValue()}; return absl::OkStatus(); } absl::Status ProtoBytesMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = BytesValue{value_ref.GetStringValue()}; return absl::OkStatus(); } absl::Status ProtoStringMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = StringValue{value_ref.GetStringValue()}; return absl::OkStatus(); } absl::Status ProtoNullMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = NullValue{}; return absl::OkStatus(); } absl::Status ProtoEnumMapValueToValueConverter( SharedView<const void>, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { result = IntValue{value_ref.GetEnumValue()}; return absl::OkStatus(); } absl::Status ProtoMessageMapValueToValueConverter( SharedView<const void> alias, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, const google::protobuf::MapValueConstRef& value_ref, ValueManager& value_manager, Value& result) { CEL_ASSIGN_OR_RETURN( result, ProtoMessageToValueImpl(value_manager, Shared<const void>(alias), &value_ref.GetMessageValue())); return absl::OkStatus(); } absl::StatusOr<ProtoMapValueToValueConverter> GetProtoMapValueToValueConverter( 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 ProtoBoolMapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32MapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64MapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32MapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64MapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return ProtoFloatMapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return ProtoDoubleMapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (value_field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { return ProtoBytesMapValueToValueConverter; } return ProtoStringMapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: if (value_field->enum_type()->full_name() == "google.protobuf.NullValue") { return ProtoNullMapValueToValueConverter; } return ProtoEnumMapValueToValueConverter; case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageMapValueToValueConverter; default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer map value type: ", google::protobuf::FieldDescriptor::CppTypeName(value_field->cpp_type()))); } } using ProtoRepeatedFieldToValueAccessor = absl::Status (*)( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*>, absl::Nonnull<const google::protobuf::Reflection*>, absl::Nonnull<const google::protobuf::FieldDescriptor*>, int, ValueManager&, Value&); absl::Status ProtoBoolRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = BoolValue{reflection->GetRepeatedBool(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoInt32RepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = IntValue{reflection->GetRepeatedInt32(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoInt64RepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = IntValue{reflection->GetRepeatedInt64(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoUInt32RepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = UintValue{reflection->GetRepeatedUInt32(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoUInt64RepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = UintValue{reflection->GetRepeatedUInt64(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoFloatRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = DoubleValue{reflection->GetRepeatedFloat(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoDoubleRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager&, Value& result) { result = DoubleValue{reflection->GetRepeatedDouble(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoBytesRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager& value_manager, Value& result) { result = BytesValue{reflection->GetRepeatedString(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoStringRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager& value_manager, Value& result) { result = value_manager.CreateUncheckedStringValue( reflection->GetRepeatedString(*message, field, index)); return absl::OkStatus(); } absl::Status ProtoNullRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*>, absl::Nonnull<const google::protobuf::Reflection*>, absl::Nonnull<const google::protobuf::FieldDescriptor*>, int, ValueManager&, Value& result) { result = NullValue{}; return absl::OkStatus(); } absl::Status ProtoEnumRepeatedFieldToValueAccessor( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager& value_manager, Value& result) { result = IntValue{reflection->GetRepeatedEnumValue(*message, field, index)}; return absl::OkStatus(); } absl::Status ProtoMessageRepeatedFieldToValueAccessor( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, int index, ValueManager& value_manager, Value& result) { const auto& field_value = reflection->GetRepeatedMessage(*message, field, index); CEL_ASSIGN_OR_RETURN( result, ProtoMessageToValueImpl( value_manager, Shared<const void>(aliased), &field_value)); return absl::OkStatus(); } absl::StatusOr<ProtoRepeatedFieldToValueAccessor> GetProtoRepeatedFieldToValueAccessor( 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 ProtoBoolRepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32RepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64RepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32RepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64RepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return ProtoFloatRepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return ProtoDoubleRepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { return ProtoBytesRepeatedFieldToValueAccessor; } return ProtoStringRepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: if (field->enum_type()->full_name() == "google.protobuf.NullValue") { return ProtoNullRepeatedFieldToValueAccessor; } return ProtoEnumRepeatedFieldToValueAccessor; case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageRepeatedFieldToValueAccessor; default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer repeated field type: ", google::protobuf::FieldDescriptor::CppTypeName(field->cpp_type()))); } } absl::Status ProtoBoolFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = BoolValue{reflection->GetBool(*message, field)}; return absl::OkStatus(); } absl::Status ProtoInt32FieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = IntValue{reflection->GetInt32(*message, field)}; return absl::OkStatus(); } absl::Status ProtoInt64FieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = IntValue{reflection->GetInt64(*message, field)}; return absl::OkStatus(); } absl::Status ProtoUInt32FieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = UintValue{reflection->GetUInt32(*message, field)}; return absl::OkStatus(); } absl::Status ProtoUInt64FieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = UintValue{reflection->GetUInt64(*message, field)}; return absl::OkStatus(); } absl::Status ProtoFloatFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = DoubleValue{reflection->GetFloat(*message, field)}; return absl::OkStatus(); } absl::Status ProtoDoubleFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = DoubleValue{reflection->GetDouble(*message, field)}; return absl::OkStatus(); } absl::Status ProtoBytesFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& result) { result = BytesValue{reflection->GetString(*message, field)}; return absl::OkStatus(); } absl::Status ProtoStringFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& result) { result = StringValue{reflection->GetString(*message, field)}; return absl::OkStatus(); } absl::Status ProtoNullFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*>, absl::Nonnull<const google::protobuf::Reflection*>, absl::Nonnull<const google::protobuf::FieldDescriptor*>, ValueManager&, Value& result) { result = NullValue{}; return absl::OkStatus(); } absl::Status ProtoEnumFieldToValue( SharedView<const void>, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager&, Value& result) { result = IntValue{reflection->GetEnumValue(*message, field)}; return absl::OkStatus(); } bool IsWrapperType(absl::Nonnull<const google::protobuf::Descriptor*> descriptor) { switch (descriptor->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: return true; default: return false; } } absl::Status ProtoMessageFieldToValue( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& result, ProtoWrapperTypeOptions wrapper_type_options) { if (wrapper_type_options == ProtoWrapperTypeOptions::kUnsetNull && IsWrapperType(field->message_type()) && !reflection->HasField(*message, field)) { result = NullValue{}; return absl::OkStatus(); } const auto& field_value = reflection->GetMessage(*message, field); CEL_ASSIGN_OR_RETURN( result, ProtoMessageToValueImpl( value_manager, Shared<const void>(aliased), &field_value)); return absl::OkStatus(); } absl::Status ProtoMapFieldToValue( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& value); absl::Status ProtoRepeatedFieldToValue( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& value); absl::Status ProtoFieldToValue( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& result, ProtoWrapperTypeOptions wrapper_type_options) { if (field->is_map()) { return ProtoMapFieldToValue(aliased, message, reflection, field, value_manager, result); } if (field->is_repeated()) { return ProtoRepeatedFieldToValue(aliased, message, reflection, field, value_manager, result); } switch (field->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return ProtoBoolFieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return ProtoInt32FieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return ProtoInt64FieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return ProtoUInt32FieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return ProtoUInt64FieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: return ProtoFloatFieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: return ProtoDoubleFieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (field->type() == google::protobuf::FieldDescriptor::TYPE_BYTES) { return ProtoBytesFieldToValue(aliased, message, reflection, field, value_manager, result); } return ProtoStringFieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: if (field->enum_type()->full_name() == "google.protobuf.NullValue") { return ProtoNullFieldToValue(aliased, message, reflection, field, value_manager, result); } return ProtoEnumFieldToValue(aliased, message, reflection, field, value_manager, result); case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: return ProtoMessageFieldToValue(aliased, message, reflection, field, value_manager, result, wrapper_type_options); default: return absl::InvalidArgumentError(absl::StrCat( "unexpected protocol buffer repeated field type: ", google::protobuf::FieldDescriptor::CppTypeName(field->cpp_type()))); } } bool IsValidFieldNumber(int64_t number) { return ABSL_PREDICT_TRUE(number > 0 && number < std::numeric_limits<int32_t>::max()); } class ParsedProtoListElementIterator final : public ValueIterator { public: ParsedProtoListElementIterator( Shared<const void> aliasing, const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ProtoRepeatedFieldToValueAccessor field_to_value_accessor) : aliasing_(std::move(aliasing)), message_(message), field_(field), field_to_value_accessor_(field_to_value_accessor), size_(GetReflectionOrDie(message_)->FieldSize(message, field_)) {} bool HasNext() override { return index_ < size_; } absl::Status Next(ValueManager& value_manager, Value& result) override { Value scratch; CEL_RETURN_IF_ERROR(field_to_value_accessor_( aliasing_, &message_, GetReflectionOrDie(message_), field_, index_, value_manager, result)); ++index_; return absl::OkStatus(); } private: Shared<const void> aliasing_; const google::protobuf::Message& message_; absl::Nonnull<const google::protobuf::FieldDescriptor*> field_; ProtoRepeatedFieldToValueAccessor field_to_value_accessor_; const int size_; int index_ = 0; }; class ParsedProtoListValueInterface : public ParsedListValueInterface, public EnableSharedFromThis<ParsedProtoListValueInterface> { public: ParsedProtoListValueInterface( const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ProtoRepeatedFieldToValueAccessor field_to_value_accessor) : message_(message), field_(field), field_to_value_accessor_(field_to_value_accessor) {} std::string DebugString() const final { google::protobuf::TextFormat::Printer printer; printer.SetSingleLineMode(true); printer.SetUseUtf8StringEscaping(true); std::string buffer; buffer.push_back('['); std::string output; const int count = GetReflectionOrDie(message_)->FieldSize(message_, field_); for (int index = 0; index < count; ++index) { if (index != 0) { buffer.append(", "); } printer.PrintFieldValueToString(message_, field_, index, &output); buffer.append(output); } buffer.push_back(']'); return buffer; } absl::StatusOr<JsonArray> ConvertToJsonArray( AnyToJsonConverter& converter) const final { return ProtoRepeatedFieldToJsonArray( converter, GetReflectionOrDie(message_), message_, field_); } size_t Size() const final { return static_cast<size_t>( GetReflectionOrDie(message_)->FieldSize(message_, field_)); } absl::Status ForEach(ValueManager& value_manager, ForEachCallback callback) const final { const auto size = Size(); Value element; for (size_t index = 0; index < size; ++index) { CEL_RETURN_IF_ERROR(field_to_value_accessor_( shared_from_this(), &message_, GetReflectionOrDie(message_), field_, static_cast<int>(index), value_manager, element)); CEL_ASSIGN_OR_RETURN(auto ok, callback(element)); if (!ok) { break; } } return absl::OkStatus(); } absl::Status ForEach(ValueManager& value_manager, ForEachWithIndexCallback callback) const final { const auto size = Size(); Value element; for (size_t index = 0; index < size; ++index) { CEL_RETURN_IF_ERROR(field_to_value_accessor_( shared_from_this(), &message_, GetReflectionOrDie(message_), field_, static_cast<int>(index), value_manager, element)); CEL_ASSIGN_OR_RETURN(auto ok, callback(index, element)); if (!ok) { break; } } return absl::OkStatus(); } absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager& value_manager) const final { return std::make_unique<ParsedProtoListElementIterator>( shared_from_this(), message_, field_, field_to_value_accessor_); } private: absl::Status GetImpl(ValueManager& value_manager, size_t index, Value& result) const final { Value scratch; CEL_RETURN_IF_ERROR(field_to_value_accessor_( shared_from_this(), &message_, GetReflectionOrDie(message_), field_, static_cast<int>(index), value_manager, result)); return absl::OkStatus(); } NativeTypeId GetNativeTypeId() const final { return NativeTypeId::For<ParsedProtoListValueInterface>(); } const google::protobuf::Message& message_; absl::Nonnull<const google::protobuf::FieldDescriptor*> field_; ProtoRepeatedFieldToValueAccessor field_to_value_accessor_; }; class ParsedProtoMapKeyIterator final : public ValueIterator { public: ParsedProtoMapKeyIterator(const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ProtoMapKeyToValueConverter map_key_to_value) : begin_(MapBegin(*GetReflectionOrDie(message), message, *field)), end_(MapEnd(*GetReflectionOrDie(message), message, *field)), map_key_to_value_(map_key_to_value) {} bool HasNext() override { return begin_ != end_; } absl::Status Next(ValueManager& value_manager, Value& result) override { Value scratch; CEL_RETURN_IF_ERROR( map_key_to_value_(begin_.GetKey(), value_manager, result)); ++begin_; return absl::OkStatus(); } private: google::protobuf::MapIterator begin_; google::protobuf::MapIterator end_; ProtoMapKeyToValueConverter map_key_to_value_; }; class ParsedProtoMapValueInterface : public ParsedMapValueInterface, public EnableSharedFromThis<ParsedProtoMapValueInterface> { public: ParsedProtoMapValueInterface( const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ProtoMapKeyFromValueConverter map_key_from_value, ProtoMapKeyToValueConverter map_key_to_value, ProtoMapValueToValueConverter map_value_to_value) : message_(message), field_(field), map_key_from_value_(map_key_from_value), map_key_to_value_(map_key_to_value), map_value_to_value_(map_value_to_value) {} std::string DebugString() const final { google::protobuf::TextFormat::Printer printer; printer.SetSingleLineMode(true); printer.SetUseUtf8StringEscaping(true); std::string buffer; buffer.push_back('{'); std::string output; const auto* reflection = GetReflectionOrDie(message_); const auto* map_key = field_->message_type()->map_key(); const auto* map_value = field_->message_type()->map_value(); const int count = reflection->FieldSize(message_, field_); for (int index = 0; index < count; ++index) { if (index != 0) { buffer.append(", "); } const auto& entry = reflection->GetRepeatedMessage(message_, field_, index); printer.PrintFieldValueToString(entry, map_key, -1, &output); buffer.append(output); buffer.append(": "); printer.PrintFieldValueToString(entry, map_value, -1, &output); buffer.append(output); } buffer.push_back('}'); return buffer; } absl::StatusOr<JsonObject> ConvertToJsonObject( AnyToJsonConverter& converter) const final { return ProtoMapFieldToJsonObject(converter, GetReflectionOrDie(message_), message_, field_); } size_t Size() const final { return static_cast<size_t>(protobuf_internal::MapSize( *GetReflectionOrDie(message_), message_, *field_)); } absl::Status ListKeys(ValueManager& value_manager, ListValue& result) const final { CEL_ASSIGN_OR_RETURN(auto builder, value_manager.NewListValueBuilder(ListType{})); builder->Reserve(Size()); auto begin = MapBegin(*GetReflectionOrDie(message_), message_, *field_); auto end = MapEnd(*GetReflectionOrDie(message_), message_, *field_); Value key; while (begin != end) { CEL_RETURN_IF_ERROR( map_key_to_value_(begin.GetKey(), value_manager, key)); CEL_RETURN_IF_ERROR(builder->Add(std::move(key))); ++begin; } result = std::move(*builder).Build(); return absl::OkStatus(); } absl::Status ForEach(ValueManager& value_manager, ForEachCallback callback) const final { auto begin = MapBegin(*GetReflectionOrDie(message_), message_, *field_); auto end = MapEnd(*GetReflectionOrDie(message_), message_, *field_); Value key; Value value; while (begin != end) { CEL_RETURN_IF_ERROR( map_key_to_value_(begin.GetKey(), value_manager, key)); CEL_RETURN_IF_ERROR(map_value_to_value_(shared_from_this(), field_, begin.GetValueRef(), value_manager, value)); CEL_ASSIGN_OR_RETURN(auto ok, callback(key, value)); if (!ok) { break; } ++begin; } return absl::OkStatus(); } absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator( ValueManager& value_manager) const final { return std::make_unique<ParsedProtoMapKeyIterator>(message_, field_, map_key_to_value_); } private: absl::StatusOr<bool> FindImpl(ValueManager& value_manager, const Value& key, Value& result) const final { google::protobuf::MapKey map_key; std::string map_key_string; CEL_RETURN_IF_ERROR( map_key_from_value_(Value(key), map_key, map_key_string)); google::protobuf::MapValueConstRef map_value; if (!LookupMapValue(*GetReflectionOrDie(message_), message_, *field_, map_key, &map_value)) { return false; } Value scratch; CEL_RETURN_IF_ERROR(map_value_to_value_(shared_from_this(), field_->message_type()->map_value(), map_value, value_manager, result)); return true; } absl::StatusOr<bool> HasImpl(ValueManager& value_manager, const Value& key) const final { google::protobuf::MapKey map_key; std::string map_key_string; CEL_RETURN_IF_ERROR( map_key_from_value_(Value(key), map_key, map_key_string)); return ContainsMapKey(*GetReflectionOrDie(message_), message_, *field_, map_key); } NativeTypeId GetNativeTypeId() const final { return NativeTypeId::For<ParsedProtoMapValueInterface>(); } const google::protobuf::Message& message_; absl::Nonnull<const google::protobuf::FieldDescriptor*> field_; ProtoMapKeyFromValueConverter map_key_from_value_; ProtoMapKeyToValueConverter map_key_to_value_; ProtoMapValueToValueConverter map_value_to_value_; }; class ParsedProtoQualifyState final : public ProtoQualifyState { public: ParsedProtoQualifyState(const google::protobuf::Message* message, const google::protobuf::Descriptor* descriptor, const google::protobuf::Reflection* reflection, Shared<const void> alias, ValueManager& value_manager) : ProtoQualifyState(message, descriptor, reflection), alias_(std::move(alias)), value_manager_(value_manager) {} absl::optional<Value>& result() { return result_; } private: void SetResultFromError(absl::Status status, cel::MemoryManagerRef memory_manager) override { result_ = ErrorValue{std::move(status)}; } void SetResultFromBool(bool value) override { result_ = BoolValue{value}; } absl::Status SetResultFromField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) override { Value result; CEL_RETURN_IF_ERROR( ProtoFieldToValue(alias_, message, message->GetReflection(), field, value_manager_, result, unboxing_option)); result_ = std::move(result); return absl::OkStatus(); } absl::Status SetResultFromRepeatedField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, int index, cel::MemoryManagerRef memory_manager) override { Value result; CEL_ASSIGN_OR_RETURN(auto accessor, GetProtoRepeatedFieldToValueAccessor(field)); CEL_RETURN_IF_ERROR((*accessor)(alias_, message, message->GetReflection(), field, index, value_manager_, result)); result_ = std::move(result); return absl::OkStatus(); } absl::Status SetResultFromMapField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, const google::protobuf::MapValueConstRef& value, cel::MemoryManagerRef memory_manager) override { CEL_ASSIGN_OR_RETURN(auto converter, GetProtoMapValueToValueConverter(field)); Value result; CEL_RETURN_IF_ERROR( (*converter)(alias_, field, value, value_manager_, result)); result_ = std::move(result); return absl::OkStatus(); } Shared<const void> alias_; ValueManager& value_manager_; absl::optional<Value> result_; }; class ParsedProtoStructValueInterface; const ParsedProtoStructValueInterface* AsParsedProtoStructValue( const ParsedStructValue& value); const ParsedProtoStructValueInterface* AsParsedProtoStructValue( const Value& value) { if (auto parsed_struct_value = As<ParsedStructValue>(value); parsed_struct_value) { return AsParsedProtoStructValue(*parsed_struct_value); } return nullptr; } class ParsedProtoStructValueInterface : public ParsedStructValueInterface, public EnableSharedFromThis<ParsedProtoStructValueInterface> { public: absl::string_view GetTypeName() const final { return message().GetDescriptor()->full_name(); } std::string DebugString() const final { return message().DebugString(); } absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const final { if (!message().SerializePartialToCord(&value)) { return absl::InternalError( absl::StrCat("failed to serialize ", GetTypeName())); } return absl::OkStatus(); } absl::StatusOr<Json> ConvertToJson( AnyToJsonConverter& value_manager) const final { return ProtoMessageToJson(value_manager, message()); } bool IsZeroValue() const final { return message().ByteSizeLong() == 0; } absl::Status GetFieldByName( ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options) const final { const auto* desc = message().GetDescriptor(); const auto* field_desc = desc->FindFieldByName(name); if (ABSL_PREDICT_FALSE(field_desc == nullptr)) { field_desc = message().GetReflection()->FindKnownExtensionByName(name); if (ABSL_PREDICT_FALSE(field_desc == nullptr)) { result = NoSuchFieldError(name); return absl::OkStatus(); } } return GetField(value_manager, field_desc, result, unboxing_options); } absl::Status GetFieldByNumber( ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options) const final { if (!IsValidFieldNumber(number)) { result = NoSuchFieldError(absl::StrCat(number)); return absl::OkStatus(); } const auto* desc = message().GetDescriptor(); const auto* field_desc = desc->FindFieldByNumber(static_cast<int>(number)); if (ABSL_PREDICT_FALSE(field_desc == nullptr)) { result = NoSuchFieldError(absl::StrCat(number)); return absl::OkStatus(); } return GetField(value_manager, field_desc, result, unboxing_options); } absl::StatusOr<bool> HasFieldByName(absl::string_view name) const final { const auto* desc = message().GetDescriptor(); const auto* field_desc = desc->FindFieldByName(name); if (ABSL_PREDICT_FALSE(field_desc == nullptr)) { field_desc = message().GetReflection()->FindKnownExtensionByName(name); if (ABSL_PREDICT_FALSE(field_desc == nullptr)) { return NoSuchFieldError(name).NativeValue(); } } return HasField(field_desc); } absl::StatusOr<bool> HasFieldByNumber(int64_t number) const final { if (!IsValidFieldNumber(number)) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } const auto* desc = message().GetDescriptor(); const auto* field_desc = desc->FindFieldByNumber(static_cast<int>(number)); if (ABSL_PREDICT_FALSE(field_desc == nullptr)) { return NoSuchFieldError(absl::StrCat(number)).NativeValue(); } return HasField(field_desc); } absl::Status ForEachField(ValueManager& value_manager, ForEachFieldCallback callback) const final { std::vector<const google::protobuf::FieldDescriptor*> fields; const auto* reflection = message().GetReflection(); reflection->ListFields(message(), &fields); Value value; for (const auto* field : fields) { CEL_RETURN_IF_ERROR(ProtoFieldToValue( shared_from_this(), &message(), reflection, field, value_manager, value, ProtoWrapperTypeOptions::kUnsetProtoDefault)); CEL_ASSIGN_OR_RETURN(auto ok, callback(field->name(), value)); if (!ok) { break; } } return absl::OkStatus(); } absl::StatusOr<int> Qualify(ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const final { if (ABSL_PREDICT_FALSE(qualifiers.empty())) { return absl::InvalidArgumentError("invalid select qualifier path."); } auto memory_manager = value_manager.GetMemoryManager(); ParsedProtoQualifyState qualify_state(&message(), message().GetDescriptor(), message().GetReflection(), shared_from_this(), value_manager); for (int i = 0; i < qualifiers.size() - 1; i++) { const auto& qualifier = qualifiers[i]; CEL_RETURN_IF_ERROR( qualify_state.ApplySelectQualifier(qualifier, memory_manager)); if (qualify_state.result().has_value()) { result = std::move(qualify_state.result()).value(); return result.Is<ErrorValue>() ? -1 : i + 1; } } const auto& last_qualifier = qualifiers.back(); if (presence_test) { CEL_RETURN_IF_ERROR( qualify_state.ApplyLastQualifierHas(last_qualifier, memory_manager)); } else { CEL_RETURN_IF_ERROR( qualify_state.ApplyLastQualifierGet(last_qualifier, memory_manager)); } result = std::move(qualify_state.result()).value(); return -1; } virtual const google::protobuf::Message& message() const = 0; StructType GetRuntimeType() const final { return MessageType(message().GetDescriptor()); } private: absl::Status EqualImpl(ValueManager& value_manager, const ParsedStructValue& other, Value& result) const final { if (const auto* parsed_proto_struct_value = AsParsedProtoStructValue(other); parsed_proto_struct_value) { const auto& lhs_message = message(); const auto& rhs_message = parsed_proto_struct_value->message(); if (lhs_message.GetDescriptor() == rhs_message.GetDescriptor()) { result = BoolValue{ google::protobuf::util::MessageDifferencer::Equals(lhs_message, rhs_message)}; return absl::OkStatus(); } } return ParsedStructValueInterface::EqualImpl(value_manager, other, result); } NativeTypeId GetNativeTypeId() const final { return NativeTypeId::For<ParsedProtoStructValueInterface>(); } absl::StatusOr<bool> HasField( absl::Nonnull<const google::protobuf::FieldDescriptor*> field_desc) const { const auto* reflect = message().GetReflection(); if (field_desc->is_map() || field_desc->is_repeated()) { return reflect->FieldSize(message(), field_desc) > 0; } return reflect->HasField(message(), field_desc); } absl::Status GetField( ValueManager& value_manager, absl::Nonnull<const google::protobuf::FieldDescriptor*> field_desc, Value& result, ProtoWrapperTypeOptions unboxing_options) const { CEL_RETURN_IF_ERROR(ProtoFieldToValue( shared_from_this(), &message(), message().GetReflection(), field_desc, value_manager, result, unboxing_options)); return absl::OkStatus(); } }; const ParsedProtoStructValueInterface* AsParsedProtoStructValue( const ParsedStructValue& value) { return NativeTypeId::Of(value) == NativeTypeId::For<ParsedProtoStructValueInterface>() ? cel::internal::down_cast<const ParsedProtoStructValueInterface*>( value.operator->()) : nullptr; } class PooledParsedProtoStructValueInterface final : public ParsedProtoStructValueInterface { public: explicit PooledParsedProtoStructValueInterface( absl::Nonnull<const google::protobuf::Message*> message) : message_(message) {} const google::protobuf::Message& message() const override { return *message_; } private: absl::Nonnull<const google::protobuf::Message*> message_; }; class AliasingParsedProtoStructValueInterface final : public ParsedProtoStructValueInterface { public: explicit AliasingParsedProtoStructValueInterface( absl::Nonnull<const google::protobuf::Message*> message, Shared<const void> alias) : message_(message), alias_(std::move(alias)) {} const google::protobuf::Message& message() const override { return *message_; } private: absl::Nonnull<const google::protobuf::Message*> message_; Shared<const void> alias_; }; class ReffedStaticParsedProtoStructValueInterface final : public ParsedProtoStructValueInterface, public common_internal::ReferenceCount { public: explicit ReffedStaticParsedProtoStructValueInterface(size_t size) : size_(size) {} const google::protobuf::Message& message() const override { return *static_cast<const google::protobuf::Message*>( reinterpret_cast<const google::protobuf::MessageLite*>( reinterpret_cast<const char*>(this) + MessageOffset())); } static size_t MessageOffset() { return internal::AlignUp( sizeof(ReffedStaticParsedProtoStructValueInterface), __STDCPP_DEFAULT_NEW_ALIGNMENT__); } private: void Finalize() noexcept override { reinterpret_cast<google::protobuf::MessageLite*>(reinterpret_cast<char*>(this) + MessageOffset()) ->~MessageLite(); } void Delete() noexcept override { void* address = this; const auto size = MessageOffset() + size_; this->~ReffedStaticParsedProtoStructValueInterface(); internal::SizedDelete(address, size); } const size_t size_; }; class ReffedDynamicParsedProtoStructValueInterface final : public ParsedProtoStructValueInterface, public common_internal::ReferenceCount { public: explicit ReffedDynamicParsedProtoStructValueInterface( absl::Nonnull<const google::protobuf::Message*> message) : message_(message) {} const google::protobuf::Message& message() const override { return *message_; } private: void Finalize() noexcept override { delete message_; } void Delete() noexcept override { delete this; } absl::Nonnull<const google::protobuf::Message*> message_; }; void ProtoMessageDestruct(void* object) { static_cast<google::protobuf::Message*>(object)->~Message(); } absl::Status ProtoMapFieldToValue( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& value) { ABSL_DCHECK(field->is_map()); CEL_ASSIGN_OR_RETURN(auto map_key_from_value, GetProtoMapKeyFromValueConverter( field->message_type()->map_key()->cpp_type())); CEL_ASSIGN_OR_RETURN(auto map_key_to_value, GetProtoMapKeyToValueConverter(field)); CEL_ASSIGN_OR_RETURN(auto map_value_to_value, GetProtoMapValueToValueConverter(field)); if (!aliased) { value = ParsedMapValue{value_manager.GetMemoryManager() .MakeShared<ParsedProtoMapValueInterface>( *message, field, map_key_from_value, map_key_to_value, map_value_to_value)}; } else { value = ParsedMapValue{ value_manager.GetMemoryManager() .MakeShared<AliasingValue<ParsedProtoMapValueInterface>>( Shared<const void>(aliased), *message, field, map_key_from_value, map_key_to_value, map_value_to_value)}; } return absl::OkStatus(); } absl::Status ProtoRepeatedFieldToValue( SharedView<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message, absl::Nonnull<const google::protobuf::Reflection*> reflection, absl::Nonnull<const google::protobuf::FieldDescriptor*> field, ValueManager& value_manager, Value& value) { ABSL_DCHECK(!field->is_map()); ABSL_DCHECK(field->is_repeated()); CEL_ASSIGN_OR_RETURN(auto repeated_field_to_value, GetProtoRepeatedFieldToValueAccessor(field)); if (!aliased) { value = ParsedListValue{value_manager.GetMemoryManager() .MakeShared<ParsedProtoListValueInterface>( *message, field, repeated_field_to_value)}; } else { value = ParsedListValue{ value_manager.GetMemoryManager() .MakeShared<AliasingValue<ParsedProtoListValueInterface>>( Shared<const void>(aliased), *message, field, repeated_field_to_value)}; } return absl::OkStatus(); } absl::StatusOr<absl::optional<Value>> WellKnownProtoMessageToValue( ValueFactory& value_factory, const TypeReflector& type_reflector, absl::Nonnull<const google::protobuf::Message*> message) { const auto* desc = message->GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::nullopt; } switch (desc->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicFloatValueProto(*message)); return DoubleValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicDoubleValueProto(*message)); return DoubleValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicInt32ValueProto(*message)); return IntValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicInt64ValueProto(*message)); return IntValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicUInt32ValueProto(*message)); return UintValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicUInt64ValueProto(*message)); return UintValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicStringValueProto(*message)); return StringValue{std::move(value)}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicBytesValueProto(*message)); return BytesValue{std::move(value)}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicBoolValueProto(*message)); return BoolValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY: { CEL_ASSIGN_OR_RETURN(auto any, UnwrapDynamicAnyProto(*message)); CEL_ASSIGN_OR_RETURN(auto value, type_reflector.DeserializeValue( value_factory, any.type_url(), GetAnyValueAsCord(any))); if (!value) { return absl::NotFoundError( absl::StrCat("unable to find deserializer for ", any.type_url())); } return std::move(value).value(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicDurationProto(*message)); return DurationValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP: { CEL_ASSIGN_OR_RETURN(auto value, UnwrapDynamicTimestampProto(*message)); return TimestampValue{value}; } case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE: { CEL_ASSIGN_OR_RETURN(auto value, DynamicValueProtoToJson(*message)); return value_factory.CreateValueFromJson(std::move(value)); } case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE: { CEL_ASSIGN_OR_RETURN(auto value, DynamicListValueProtoToJson(*message)); return value_factory.CreateValueFromJson(std::move(value)); } case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT: { CEL_ASSIGN_OR_RETURN(auto value, DynamicStructProtoToJson(*message)); return value_factory.CreateValueFromJson(std::move(value)); } default: return absl::nullopt; } } absl::StatusOr<absl::optional<Value>> WellKnownProtoMessageToValue( ValueManager& value_manager, absl::Nonnull<const google::protobuf::Message*> message) { return WellKnownProtoMessageToValue(value_manager, value_manager.type_provider(), message); } absl::Status ProtoMessageCopyUsingSerialization( google::protobuf::MessageLite* to, const google::protobuf::MessageLite* from) { ABSL_DCHECK_EQ(to->GetTypeName(), from->GetTypeName()); absl::Cord serialized; if (!from->SerializePartialToCord(&serialized)) { return absl::UnknownError( absl::StrCat("failed to serialize `", from->GetTypeName(), "`")); } if (!to->ParsePartialFromCord(serialized)) { return absl::UnknownError( absl::StrCat("failed to parse `", to->GetTypeName(), "`")); } return absl::OkStatus(); } absl::Status ProtoMessageCopy( absl::Nonnull<google::protobuf::Message*> to_message, absl::Nonnull<const google::protobuf::Descriptor*> to_descriptor, absl::Nonnull<const google::protobuf::Message*> from_message) { CEL_ASSIGN_OR_RETURN(const auto* from_descriptor, GetDescriptor(*from_message)); if (to_descriptor == from_descriptor) { to_message->CopyFrom(*from_message); return absl::OkStatus(); } if (to_descriptor->full_name() == from_descriptor->full_name()) { return ProtoMessageCopyUsingSerialization(to_message, from_message); } return TypeConversionError(from_descriptor->full_name(), to_descriptor->full_name()) .NativeValue(); } absl::Status ProtoMessageCopy( absl::Nonnull<google::protobuf::Message*> to_message, absl::Nonnull<const google::protobuf::Descriptor*> to_descriptor, absl::Nonnull<const google::protobuf::MessageLite*> from_message) { const auto& from_type_name = from_message->GetTypeName(); if (from_type_name == to_descriptor->full_name()) { return ProtoMessageCopyUsingSerialization(to_message, from_message); } return TypeConversionError(from_type_name, to_descriptor->full_name()) .NativeValue(); } } absl::StatusOr<absl::Nonnull<const google::protobuf::Descriptor*>> GetDescriptor( const google::protobuf::Message& message) { const auto* desc = message.GetDescriptor(); if (ABSL_PREDICT_FALSE(desc == nullptr)) { return absl::InvalidArgumentError( absl::StrCat(message.GetTypeName(), " is missing descriptor")); } return desc; } absl::StatusOr<absl::Nonnull<const google::protobuf::Reflection*>> GetReflection( const google::protobuf::Message& message) { const auto* reflect = message.GetReflection(); if (ABSL_PREDICT_FALSE(reflect == nullptr)) { return absl::InvalidArgumentError( absl::StrCat(message.GetTypeName(), " is missing reflection")); } return reflect; } absl::Nonnull<const google::protobuf::Reflection*> GetReflectionOrDie( const google::protobuf::Message& message) { const auto* reflection = message.GetReflection(); ABSL_CHECK(reflection != nullptr) << message.GetTypeName() << " is missing reflection"; return reflection; } 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_DCHECK_GT(size, 0); ABSL_DCHECK(absl::has_single_bit(align)); { CEL_ASSIGN_OR_RETURN(auto well_known, WellKnownProtoMessageToValue(value_manager, message)); if (well_known) { return std::move(well_known).value(); } } auto memory_manager = value_manager.GetMemoryManager(); if (auto* arena = ProtoMemoryManagerArena(memory_manager); arena != nullptr) { auto* copied_message = (*arena_copy_construct)(arena, message); return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( copied_message)}; } switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: { auto* copied_message = (*copy_construct)(memory_manager.Allocate(size, align), message); memory_manager.OwnCustomDestructor(copied_message, &ProtoMessageDestruct); return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( copied_message)}; } case MemoryManagement::kReferenceCounting: { auto* block = static_cast<char*>(memory_manager.Allocate( ReffedStaticParsedProtoStructValueInterface::MessageOffset() + size, __STDCPP_DEFAULT_NEW_ALIGNMENT__)); auto* message_address = block + ReffedStaticParsedProtoStructValueInterface::MessageOffset(); auto* copied_message = (*copy_construct)(message_address, message); ABSL_DCHECK_EQ(reinterpret_cast<uintptr_t>(message_address), reinterpret_cast<uintptr_t>(copied_message)); auto* message_value = ::new (static_cast<void*>(block)) ReffedStaticParsedProtoStructValueInterface(size); common_internal::SetReferenceCountForThat(*message_value, message_value); return ParsedStructValue{common_internal::MakeShared( common_internal::kAdoptRef, message_value, message_value)}; } } } 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_DCHECK_GT(size, 0); ABSL_DCHECK(absl::has_single_bit(align)); { CEL_ASSIGN_OR_RETURN(auto well_known, WellKnownProtoMessageToValue(value_manager, message)); if (well_known) { return std::move(well_known).value(); } } auto memory_manager = value_manager.GetMemoryManager(); if (auto* arena = ProtoMemoryManagerArena(memory_manager); arena != nullptr) { auto* moved_message = (*arena_move_construct)(arena, message); return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( moved_message)}; } switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: { auto* moved_message = (*move_construct)(memory_manager.Allocate(size, align), message); memory_manager.OwnCustomDestructor(moved_message, &ProtoMessageDestruct); return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( moved_message)}; } case MemoryManagement::kReferenceCounting: { auto* block = static_cast<char*>(memory_manager.Allocate( ReffedStaticParsedProtoStructValueInterface::MessageOffset() + size, __STDCPP_DEFAULT_NEW_ALIGNMENT__)); auto* message_address = block + ReffedStaticParsedProtoStructValueInterface::MessageOffset(); auto* moved_message = (*move_construct)(message_address, message); ABSL_DCHECK_EQ(reinterpret_cast<uintptr_t>(message_address), reinterpret_cast<uintptr_t>(moved_message)); auto* message_value = ::new (static_cast<void*>(block)) ReffedStaticParsedProtoStructValueInterface(size); common_internal::SetReferenceCountForThat(*message_value, message_value); return ParsedStructValue{common_internal::MakeShared( common_internal::kAdoptRef, message_value, message_value)}; } } } absl::StatusOr<Value> ProtoMessageToValueImpl( ValueManager& value_manager, Shared<const void> aliased, absl::Nonnull<const google::protobuf::Message*> message) { { CEL_ASSIGN_OR_RETURN(auto well_known, WellKnownProtoMessageToValue(value_manager, message)); if (well_known) { return std::move(well_known).value(); } } auto memory_manager = value_manager.GetMemoryManager(); switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: { if (!aliased) { return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( message)}; } return ParsedStructValue{ memory_manager.MakeShared<AliasingParsedProtoStructValueInterface>( message, std::move(aliased))}; } case MemoryManagement::kReferenceCounting: { if (!aliased) { auto* copied_message = message->New(); copied_message->CopyFrom(*message); return ParsedStructValue{ memory_manager .MakeShared<ReffedDynamicParsedProtoStructValueInterface>( copied_message)}; } return ParsedStructValue{ memory_manager.MakeShared<AliasingParsedProtoStructValueInterface>( message, std::move(aliased))}; } } } absl::StatusOr<absl::Nonnull<google::protobuf::Message*>> ProtoMessageFromValueImpl( const Value& value, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, google::protobuf::Arena* arena) { switch (value.kind()) { case ValueKind::kNull: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.Value", arena)); CEL_RETURN_IF_ERROR(DynamicValueProtoFromJson(kJsonNull, *message)); return message.release(); } case ValueKind::kBool: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.BoolValue", arena)); CEL_RETURN_IF_ERROR(WrapDynamicBoolValueProto( Cast<BoolValue>(value).NativeValue(), *message)); return message.release(); } case ValueKind::kInt: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.Int64Value", arena)); CEL_RETURN_IF_ERROR(WrapDynamicInt64ValueProto( Cast<IntValue>(value).NativeValue(), *message)); return message.release(); } case ValueKind::kUint: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.UInt64Value", arena)); CEL_RETURN_IF_ERROR(WrapDynamicUInt64ValueProto( Cast<UintValue>(value).NativeValue(), *message)); return message.release(); } case ValueKind::kDouble: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.DoubleValue", arena)); CEL_RETURN_IF_ERROR(WrapDynamicDoubleValueProto( Cast<DoubleValue>(value).NativeValue(), *message)); return message.release(); } case ValueKind::kString: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.StringValue", arena)); CEL_RETURN_IF_ERROR(WrapDynamicStringValueProto( Cast<StringValue>(value).NativeCord(), *message)); return message.release(); } case ValueKind::kBytes: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.BytesValue", arena)); CEL_RETURN_IF_ERROR(WrapDynamicBytesValueProto( Cast<BytesValue>(value).NativeCord(), *message)); return message.release(); } case ValueKind::kStruct: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, value.GetTypeName(), arena)); ProtoAnyToJsonConverter converter(pool, factory); absl::Cord serialized; CEL_RETURN_IF_ERROR(value.SerializeTo(converter, serialized)); if (!message->ParsePartialFromCord(serialized)) { return absl::UnknownError( absl::StrCat("failed to parse `", message->GetTypeName(), "`")); } return message.release(); } case ValueKind::kDuration: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.Duration", arena)); CEL_RETURN_IF_ERROR(WrapDynamicDurationProto( Cast<DurationValue>(value).NativeValue(), *message)); return message.release(); } case ValueKind::kTimestamp: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.Timestamp", arena)); CEL_RETURN_IF_ERROR(WrapDynamicTimestampProto( Cast<TimestampValue>(value).NativeValue(), *message)); return message.release(); } case ValueKind::kList: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.ListValue", arena)); ProtoAnyToJsonConverter converter(pool, factory); CEL_ASSIGN_OR_RETURN( auto json, Cast<ListValue>(value).ConvertToJsonArray(converter)); CEL_RETURN_IF_ERROR(DynamicListValueProtoFromJson(json, *message)); return message.release(); } case ValueKind::kMap: { CEL_ASSIGN_OR_RETURN( auto message, NewProtoMessage(pool, factory, "google.protobuf.Struct", arena)); ProtoAnyToJsonConverter converter(pool, factory); CEL_ASSIGN_OR_RETURN( auto json, Cast<MapValue>(value).ConvertToJsonObject(converter)); CEL_RETURN_IF_ERROR(DynamicStructProtoFromJson(json, *message)); return message.release(); } default: break; } return TypeConversionError(value.GetTypeName(), "*message*").NativeValue(); } absl::Status ProtoMessageFromValueImpl( const Value& value, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory, absl::Nonnull<google::protobuf::Message*> message) { CEL_ASSIGN_OR_RETURN(const auto* to_desc, GetDescriptor(*message)); switch (to_desc->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: { if (auto double_value = As<DoubleValue>(value); double_value) { return WrapDynamicFloatValueProto( static_cast<float>(double_value->NativeValue()), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: { if (auto double_value = As<DoubleValue>(value); double_value) { return WrapDynamicDoubleValueProto( static_cast<float>(double_value->NativeValue()), *message); } return TypeConversionError(value.GetTypeName(), to_desc->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 WrapDynamicInt32ValueProto( static_cast<int32_t>(int_value->NativeValue()), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: { if (auto int_value = As<IntValue>(value); int_value) { return WrapDynamicInt64ValueProto(int_value->NativeValue(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->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 WrapDynamicUInt32ValueProto( static_cast<uint32_t>(uint_value->NativeValue()), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: { if (auto uint_value = As<UintValue>(value); uint_value) { return WrapDynamicUInt64ValueProto(uint_value->NativeValue(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: { if (auto string_value = As<StringValue>(value); string_value) { return WrapDynamicStringValueProto(string_value->NativeCord(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: { if (auto bytes_value = As<BytesValue>(value); bytes_value) { return WrapDynamicBytesValueProto(bytes_value->NativeCord(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: { if (auto bool_value = As<BoolValue>(value); bool_value) { return WrapDynamicBoolValueProto(bool_value->NativeValue(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY: { ProtoAnyToJsonConverter converter(pool, factory); absl::Cord serialized; CEL_RETURN_IF_ERROR(value.SerializeTo(converter, serialized)); std::string type_url; switch (value.kind()) { case ValueKind::kNull: type_url = MakeTypeUrl("google.protobuf.Value"); break; case ValueKind::kBool: type_url = MakeTypeUrl("google.protobuf.BoolValue"); break; case ValueKind::kInt: type_url = MakeTypeUrl("google.protobuf.Int64Value"); break; case ValueKind::kUint: type_url = MakeTypeUrl("google.protobuf.UInt64Value"); break; case ValueKind::kDouble: type_url = MakeTypeUrl("google.protobuf.DoubleValue"); break; case ValueKind::kBytes: type_url = MakeTypeUrl("google.protobuf.BytesValue"); break; case ValueKind::kString: type_url = MakeTypeUrl("google.protobuf.StringValue"); break; case ValueKind::kList: type_url = MakeTypeUrl("google.protobuf.ListValue"); break; case ValueKind::kMap: type_url = MakeTypeUrl("google.protobuf.Struct"); break; case ValueKind::kDuration: type_url = MakeTypeUrl("google.protobuf.Duration"); break; case ValueKind::kTimestamp: type_url = MakeTypeUrl("google.protobuf.Timestamp"); break; default: type_url = MakeTypeUrl(value.GetTypeName()); break; } return WrapDynamicAnyProto(type_url, serialized, *message); } case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION: { if (auto duration_value = As<DurationValue>(value); duration_value) { return WrapDynamicDurationProto(duration_value->NativeValue(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP: { if (auto timestamp_value = As<TimestampValue>(value); timestamp_value) { return WrapDynamicTimestampProto(timestamp_value->NativeValue(), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE: { ProtoAnyToJsonConverter converter(pool, factory); CEL_ASSIGN_OR_RETURN(auto json, value.ConvertToJson(converter)); return DynamicValueProtoFromJson(json, *message); } case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE: { ProtoAnyToJsonConverter converter(pool, factory); CEL_ASSIGN_OR_RETURN(auto json, value.ConvertToJson(converter)); if (absl::holds_alternative<JsonArray>(json)) { return DynamicListValueProtoFromJson(absl::get<JsonArray>(json), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT: { ProtoAnyToJsonConverter converter(pool, factory); CEL_ASSIGN_OR_RETURN(auto json, value.ConvertToJson(converter)); if (absl::holds_alternative<JsonObject>(json)) { return DynamicStructProtoFromJson(absl::get<JsonObject>(json), *message); } return TypeConversionError(value.GetTypeName(), to_desc->full_name()) .NativeValue(); } default: break; } if (auto legacy_value = common_internal::AsLegacyStructValue(value); legacy_value) { if ((legacy_value->message_ptr() & base_internal::kMessageWrapperTagMask) == base_internal::kMessageWrapperTagMessageValue) { const auto* from_message = reinterpret_cast<const google::protobuf::Message*>( legacy_value->message_ptr() & base_internal::kMessageWrapperPtrMask); return ProtoMessageCopy(message, to_desc, from_message); } else { const auto* from_message = reinterpret_cast<const google::protobuf::MessageLite*>( legacy_value->message_ptr() & base_internal::kMessageWrapperPtrMask); return ProtoMessageCopy(message, to_desc, from_message); } } if (const auto* parsed_proto_struct_value = AsParsedProtoStructValue(value); parsed_proto_struct_value) { return ProtoMessageCopy(message, to_desc, &parsed_proto_struct_value->message()); } return TypeConversionError(value.GetTypeName(), message->GetTypeName()) .NativeValue(); } absl::StatusOr<Value> ProtoMessageToValueImpl( ValueFactory& value_factory, const TypeReflector& type_reflector, absl::Nonnull<const google::protobuf::Message*> prototype, const absl::Cord& serialized) { auto memory_manager = value_factory.GetMemoryManager(); auto* arena = ProtoMemoryManagerArena(value_factory.GetMemoryManager()); auto message = ArenaUniquePtr<google::protobuf::Message>(prototype->New(arena), DefaultArenaDeleter{arena}); if (!message->ParsePartialFromCord(serialized)) { return absl::InvalidArgumentError( absl::StrCat("failed to parse `", prototype->GetTypeName(), "`")); } { CEL_ASSIGN_OR_RETURN(auto well_known, WellKnownProtoMessageToValue( value_factory, type_reflector, message.get())); if (well_known) { return std::move(well_known).value(); } } switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( message.release())}; case MemoryManagement::kReferenceCounting: return ParsedStructValue{ memory_manager .MakeShared<ReffedDynamicParsedProtoStructValueInterface>( message.release())}; } } StructValue ProtoMessageAsStructValueImpl( ValueFactory& value_factory, absl::Nonnull<google::protobuf::Message*> message) { auto memory_manager = value_factory.GetMemoryManager(); switch (memory_manager.memory_management()) { case MemoryManagement::kPooling: return ParsedStructValue{ memory_manager.MakeShared<PooledParsedProtoStructValueInterface>( message)}; case MemoryManagement::kReferenceCounting: return ParsedStructValue{ memory_manager .MakeShared<ReffedDynamicParsedProtoStructValueInterface>( message)}; } } } }
#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 ::absl_testing::IsOkAndHolds; using ::google::api::expr::test::v1::proto2::TestAllTypes; using ::testing::NotNull; 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()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/message.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/protobuf/internal/message_test.cc
4552db5798fb0853b131b783d8875794334fae7f
a39cbe50-8ba6-4da9-a383-ecfcfeb694fa
cpp
google/cel-cpp
operators
base/operators.cc
base/operators_test.cc
#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 } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/operators.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/operators_test.cc
4552db5798fb0853b131b783d8875794334fae7f
100048c8-17af-47ac-9db1-6fb5b3094ca7
cpp
google/cel-cpp
decl
common/decl.cc
common/decl_test.cc
#include "common/decl.h" #include <cstddef> #include <string> #include <utility> #include <vector> #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/type.h" #include "common/type_kind.h" namespace cel { namespace common_internal { bool TypeIsAssignable(const Type& to, const Type& 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(NullType{}, from) || TypeIsAssignable(BoolType{}, from); case TypeKind::kIntWrapper: return TypeIsAssignable(NullType{}, from) || TypeIsAssignable(IntType{}, from); case TypeKind::kUintWrapper: return TypeIsAssignable(NullType{}, from) || TypeIsAssignable(UintType{}, from); case TypeKind::kDoubleWrapper: return TypeIsAssignable(NullType{}, from) || TypeIsAssignable(DoubleType{}, from); case TypeKind::kBytesWrapper: return TypeIsAssignable(NullType{}, from) || TypeIsAssignable(BytesType{}, from); case TypeKind::kStringWrapper: return TypeIsAssignable(NullType{}, from) || TypeIsAssignable(StringType{}, from); default: break; } const auto from_kind = from.kind(); if (to_kind != from_kind || to.name() != from.name()) { return false; } auto to_params = to.GetParameters(); auto from_params = from.GetParameters(); 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(std::vector<OverloadDecl>& insertion_order, 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)); ABSL_DCHECK(inserted.second); insertion_order.push_back(*inserted.first); } void CollectTypeParams(absl::flat_hash_set<std::string>& type_params, const Type& type) { const auto kind = type.kind(); switch (kind) { case TypeKind::kList: { const auto& list_type = type.GetList(); CollectTypeParams(type_params, list_type.element()); } break; case TypeKind::kMap: { const auto& map_type = type.GetMap(); CollectTypeParams(type_params, map_type.key()); CollectTypeParams(type_params, map_type.value()); } break; case TypeKind::kOpaque: { const auto& opaque_type = type.GetOpaque(); for (const auto& param : opaque_type.GetParameters()) { CollectTypeParams(type_params, param); } } break; case TypeKind::kFunction: { const auto& function_type = type.GetFunction(); CollectTypeParams(type_params, function_type.result()); for (const auto& arg : function_type.args()) { CollectTypeParams(type_params, arg); } } break; case TypeKind::kTypeParam: type_params.emplace(type.GetTypeParam().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_.insertion_order, overloads_.set, overload, status); } void FunctionDecl::AddOverloadImpl(OverloadDecl&& overload, absl::Status& status) { AddOverloadInternal(overloads_.insertion_order, overloads_.set, std::move(overload), status); } }
#include "common/decl.h" #include "absl/status/status.h" #include "common/constant.h" #include "common/type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::Property; using ::testing::UnorderedElementsAre; 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) { google::protobuf::Arena arena; auto overload_decl = MakeOverloadDecl( "foo", ListType(&arena, TypeParamType("A")), MapType(&arena, TypeParamType("B"), TypeParamType("C")), OpaqueType(&arena, "bar", {FunctionType(&arena, TypeParamType("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{}), MakeOverloadDecl("baz", IntType{}, IntType{}))); EXPECT_THAT(function_decl.overloads(), ElementsAre(Property(&OverloadDecl::id, "foo"), Property(&OverloadDecl::id, "bar"), Property(&OverloadDecl::id, "baz"))); EXPECT_THAT(function_decl.AddOverload( MakeOverloadDecl("qux", DynType{}, StringType{})), StatusIs(absl::StatusCode::kInvalidArgument)); } using common_internal::TypeIsAssignable; TEST(TypeIsAssignable, BoolWrapper) { EXPECT_TRUE(TypeIsAssignable(BoolWrapperType{}, BoolWrapperType{})); EXPECT_TRUE(TypeIsAssignable(BoolWrapperType{}, NullType{})); EXPECT_TRUE(TypeIsAssignable(BoolWrapperType{}, BoolType{})); EXPECT_FALSE(TypeIsAssignable(BoolWrapperType{}, DurationType{})); } TEST(TypeIsAssignable, IntWrapper) { EXPECT_TRUE(TypeIsAssignable(IntWrapperType{}, IntWrapperType{})); EXPECT_TRUE(TypeIsAssignable(IntWrapperType{}, NullType{})); EXPECT_TRUE(TypeIsAssignable(IntWrapperType{}, IntType{})); EXPECT_FALSE(TypeIsAssignable(IntWrapperType{}, DurationType{})); } TEST(TypeIsAssignable, UintWrapper) { EXPECT_TRUE(TypeIsAssignable(UintWrapperType{}, UintWrapperType{})); EXPECT_TRUE(TypeIsAssignable(UintWrapperType{}, NullType{})); EXPECT_TRUE(TypeIsAssignable(UintWrapperType{}, UintType{})); EXPECT_FALSE(TypeIsAssignable(UintWrapperType{}, DurationType{})); } TEST(TypeIsAssignable, DoubleWrapper) { EXPECT_TRUE(TypeIsAssignable(DoubleWrapperType{}, DoubleWrapperType{})); EXPECT_TRUE(TypeIsAssignable(DoubleWrapperType{}, NullType{})); EXPECT_TRUE(TypeIsAssignable(DoubleWrapperType{}, DoubleType{})); EXPECT_FALSE(TypeIsAssignable(DoubleWrapperType{}, DurationType{})); } TEST(TypeIsAssignable, BytesWrapper) { EXPECT_TRUE(TypeIsAssignable(BytesWrapperType{}, BytesWrapperType{})); EXPECT_TRUE(TypeIsAssignable(BytesWrapperType{}, NullType{})); EXPECT_TRUE(TypeIsAssignable(BytesWrapperType{}, BytesType{})); EXPECT_FALSE(TypeIsAssignable(BytesWrapperType{}, DurationType{})); } TEST(TypeIsAssignable, StringWrapper) { EXPECT_TRUE(TypeIsAssignable(StringWrapperType{}, StringWrapperType{})); EXPECT_TRUE(TypeIsAssignable(StringWrapperType{}, NullType{})); EXPECT_TRUE(TypeIsAssignable(StringWrapperType{}, StringType{})); EXPECT_FALSE(TypeIsAssignable(StringWrapperType{}, DurationType{})); } TEST(TypeIsAssignable, Complex) { google::protobuf::Arena arena; EXPECT_TRUE(TypeIsAssignable(OptionalType(&arena, DynType{}), OptionalType(&arena, StringType{}))); EXPECT_FALSE(TypeIsAssignable(OptionalType(&arena, BoolType{}), OptionalType(&arena, StringType{}))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/decl.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/decl_test.cc
4552db5798fb0853b131b783d8875794334fae7f
335f1012-0c74-4c51-87eb-9de4ab987744
cpp
google/cel-cpp
expr
base/ast_internal/expr.cc
base/ast_internal/expr_test.cc
#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* value = absl::get_if<std::unique_ptr<Type>>(&type_kind_); if (value != nullptr) { if (*value != nullptr) return **value; } return default_type(); } Type::Type(const Type& other) : type_kind_(CopyImpl(other.type_kind_)) {} Type& Type::operator=(const Type& other) { type_kind_ = CopyImpl(other.type_kind_); return *this; } FunctionType::FunctionType(const FunctionType& other) : result_type_(std::make_unique<Type>(other.result_type())), arg_types_(other.arg_types()) {} FunctionType& FunctionType::operator=(const FunctionType& other) { result_type_ = std::make_unique<Type>(other.result_type()); arg_types_ = other.arg_types(); return *this; } }
#include "base/ast_internal/expr.h" #include <memory> #include <string> #include <utility> #include "absl/types/variant.h" #include "common/expr.h" #include "internal/testing.h" namespace cel { namespace ast_internal { namespace { 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, 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_TRUE(type == Type(std::make_unique<Type>(PrimitiveType::kBool))); EXPECT_FALSE(type == Type(PrimitiveType::kBool)); EXPECT_FALSE(type == Type(std::unique_ptr<Type>())); EXPECT_FALSE(type == Type(std::make_unique<Type>(PrimitiveType::kInt64))); } 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), {})); } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/ast_internal/expr.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/base/ast_internal/expr_test.cc
4552db5798fb0853b131b783d8875794334fae7f
0d24ce96-9a8f-48fc-a5df-5aaec4cdd83a
cpp
google/cel-cpp
source
common/source.cc
common/source_test.cc
#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 | ..^"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/source.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/source_test.cc
4552db5798fb0853b131b783d8875794334fae7f
5411c9c4-0335-4de2-af86-ce114032e1cb
cpp
google/cel-cpp
value_testing
common/value_testing.cc
common/value_testing_test.cc
#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 v.Is<Type>() && matcher_.Matches(v.template Get<Type>()); } 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 "common/value_testing.h" #include <utility> #include "gtest/gtest-spi.h" #include "absl/status/status.h" #include "absl/time/time.h" #include "common/memory.h" #include "common/value.h" #include "internal/testing.h" namespace cel::test { namespace { using ::absl_testing::StatusIs; using ::testing::_; using ::testing::ElementsAre; using ::testing::Truly; using ::testing::UnorderedElementsAre; TEST(BoolValueIs, Match) { EXPECT_THAT(BoolValue(true), BoolValueIs(true)); } TEST(BoolValueIs, NoMatch) { EXPECT_THAT(BoolValue(false), Not(BoolValueIs(true))); EXPECT_THAT(IntValue(2), Not(BoolValueIs(true))); } TEST(BoolValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), BoolValueIs(true)); }(), "kind is bool and is equal to true"); } TEST(IntValueIs, Match) { EXPECT_THAT(IntValue(42), IntValueIs(42)); } TEST(IntValueIs, NoMatch) { EXPECT_THAT(IntValue(-42), Not(IntValueIs(42))); EXPECT_THAT(UintValue(2), Not(IntValueIs(42))); } TEST(IntValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(UintValue(42), IntValueIs(42)); }(), "kind is int and is equal to 42"); } TEST(UintValueIs, Match) { EXPECT_THAT(UintValue(42), UintValueIs(42)); } TEST(UintValueIs, NoMatch) { EXPECT_THAT(UintValue(41), Not(UintValueIs(42))); EXPECT_THAT(IntValue(2), Not(UintValueIs(42))); } TEST(UintValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), UintValueIs(42)); }(), "kind is uint and is equal to 42"); } TEST(DoubleValueIs, Match) { EXPECT_THAT(DoubleValue(1.2), DoubleValueIs(1.2)); } TEST(DoubleValueIs, NoMatch) { EXPECT_THAT(DoubleValue(41), Not(DoubleValueIs(1.2))); EXPECT_THAT(IntValue(2), Not(DoubleValueIs(1.2))); } TEST(DoubleValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), DoubleValueIs(1.2)); }(), "kind is double and is equal to 1.2"); } TEST(DurationValueIs, Match) { EXPECT_THAT(DurationValue(absl::Minutes(2)), DurationValueIs(absl::Minutes(2))); } TEST(DurationValueIs, NoMatch) { EXPECT_THAT(DurationValue(absl::Minutes(5)), Not(DurationValueIs(absl::Minutes(2)))); EXPECT_THAT(IntValue(2), Not(DurationValueIs(absl::Minutes(2)))); } TEST(DurationValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), DurationValueIs(absl::Minutes(2))); }(), "kind is duration and is equal to 2m"); } TEST(TimestampValueIs, Match) { EXPECT_THAT(TimestampValue(absl::UnixEpoch() + absl::Minutes(2)), TimestampValueIs(absl::UnixEpoch() + absl::Minutes(2))); } TEST(TimestampValueIs, NoMatch) { EXPECT_THAT(TimestampValue(absl::UnixEpoch()), Not(TimestampValueIs(absl::UnixEpoch() + absl::Minutes(2)))); EXPECT_THAT(IntValue(2), Not(TimestampValueIs(absl::UnixEpoch() + absl::Minutes(2)))); } TEST(TimestampValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), TimestampValueIs(absl::UnixEpoch() + absl::Minutes(2))); }(), "kind is timestamp and is equal to 19"); } TEST(StringValueIs, Match) { EXPECT_THAT(StringValue("hello!"), StringValueIs("hello!")); } TEST(StringValueIs, NoMatch) { EXPECT_THAT(StringValue("hello!"), Not(StringValueIs("goodbye!"))); EXPECT_THAT(IntValue(2), Not(StringValueIs("goodbye!"))); } TEST(StringValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), StringValueIs("hello!")); }(), "kind is string and is equal to \"hello!\""); } TEST(BytesValueIs, Match) { EXPECT_THAT(BytesValue("hello!"), BytesValueIs("hello!")); } TEST(BytesValueIs, NoMatch) { EXPECT_THAT(BytesValue("hello!"), Not(BytesValueIs("goodbye!"))); EXPECT_THAT(IntValue(2), Not(BytesValueIs("goodbye!"))); } TEST(BytesValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), BytesValueIs("hello!")); }(), "kind is bytes and is equal to \"hello!\""); } TEST(ErrorValueIs, Match) { EXPECT_THAT(ErrorValue(absl::InternalError("test")), ErrorValueIs(StatusIs(absl::StatusCode::kInternal, "test"))); } TEST(ErrorValueIs, NoMatch) { EXPECT_THAT(ErrorValue(absl::UnknownError("test")), Not(ErrorValueIs(StatusIs(absl::StatusCode::kInternal, "test")))); EXPECT_THAT(IntValue(2), Not(ErrorValueIs(_))); } TEST(ErrorValueIs, NonMatchMessage) { EXPECT_NONFATAL_FAILURE( []() { EXPECT_THAT(IntValue(42), ErrorValueIs(StatusIs( absl::StatusCode::kInternal, "test"))); }(), "kind is *error* and"); } using ValueMatcherTest = common_internal::ThreadCompatibleValueTest<>; TEST_P(ValueMatcherTest, OptionalValueIsMatch) { EXPECT_THAT( OptionalValue::Of(value_manager().GetMemoryManager(), IntValue(42)), OptionalValueIs(IntValueIs(42))); } TEST_P(ValueMatcherTest, OptionalValueIsHeldValueDifferent) { EXPECT_NONFATAL_FAILURE( [&]() { EXPECT_THAT(OptionalValue::Of(value_manager().GetMemoryManager(), IntValue(-42)), OptionalValueIs(IntValueIs(42))); }(), "is OptionalValue that is engaged with value whose kind is int and is " "equal to 42"); } TEST_P(ValueMatcherTest, OptionalValueIsNotEngaged) { EXPECT_NONFATAL_FAILURE( [&]() { EXPECT_THAT(OptionalValue::None(), OptionalValueIs(IntValueIs(42))); }(), "is not engaged"); } TEST_P(ValueMatcherTest, OptionalValueIsNotAnOptional) { EXPECT_NONFATAL_FAILURE( [&]() { EXPECT_THAT(IntValue(42), OptionalValueIs(IntValueIs(42))); }(), "wanted OptionalValue, got int"); } TEST_P(ValueMatcherTest, OptionalValueIsEmptyMatch) { EXPECT_THAT(OptionalValue::None(), OptionalValueIsEmpty()); } TEST_P(ValueMatcherTest, OptionalValueIsEmptyNotEmpty) { EXPECT_NONFATAL_FAILURE( [&]() { EXPECT_THAT( OptionalValue::Of(value_manager().GetMemoryManager(), IntValue(42)), OptionalValueIsEmpty()); }(), "is not empty"); } TEST_P(ValueMatcherTest, OptionalValueIsEmptyNotOptional) { EXPECT_NONFATAL_FAILURE( [&]() { EXPECT_THAT(IntValue(42), OptionalValueIsEmpty()); }(), "wanted OptionalValue, got int"); } TEST_P(ValueMatcherTest, ListMatcherBasic) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewListValueBuilder( value_manager().GetDynListType())); ASSERT_OK(builder->Add(IntValue(42))); Value list_value = std::move(*builder).Build(); EXPECT_THAT(list_value, ListValueIs(Truly([](const ListValue& v) { auto size = v.Size(); return size.ok() && *size == 1; }))); } TEST_P(ValueMatcherTest, ListMatcherMatchesElements) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewListValueBuilder( value_manager().GetDynListType())); ASSERT_OK(builder->Add(IntValue(42))); ASSERT_OK(builder->Add(IntValue(1337))); ASSERT_OK(builder->Add(IntValue(42))); ASSERT_OK(builder->Add(IntValue(100))); EXPECT_THAT( std::move(*builder).Build(), ListValueIs(ListValueElements( &value_manager(), ElementsAre(IntValueIs(42), IntValueIs(1337), IntValueIs(42), IntValueIs(100))))); } TEST_P(ValueMatcherTest, MapMatcherBasic) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewMapValueBuilder( value_manager().GetDynDynMapType())); ASSERT_OK(builder->Put(IntValue(42), IntValue(42))); Value map_value = std::move(*builder).Build(); EXPECT_THAT(map_value, MapValueIs(Truly([](const MapValue& v) { auto size = v.Size(); return size.ok() && *size == 1; }))); } TEST_P(ValueMatcherTest, MapMatcherMatchesElements) { ASSERT_OK_AND_ASSIGN(auto builder, value_manager().NewMapValueBuilder( value_manager().GetDynDynMapType())); ASSERT_OK(builder->Put(IntValue(42), StringValue("answer"))); ASSERT_OK(builder->Put(IntValue(1337), StringValue("leet"))); EXPECT_THAT(std::move(*builder).Build(), MapValueIs(MapValueElements( &value_manager(), UnorderedElementsAre( Pair(IntValueIs(42), StringValueIs("answer")), Pair(IntValueIs(1337), StringValueIs("leet")))))); } INSTANTIATE_TEST_SUITE_P( MemoryManagerStrategy, ValueMatcherTest, testing::Values(cel::MemoryManagement::kPooling, cel::MemoryManagement::kReferenceCounting)); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/value_testing.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/value_testing_test.cc
4552db5798fb0853b131b783d8875794334fae7f
86609310-a524-4f89-81c7-b0a7611ba42f
cpp
google/cel-cpp
ast_traverse
eval/public/ast_traverse.cc
eval/public/ast_traverse_test.cc
#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); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/ast_traverse.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/ast_traverse_test.cc
4552db5798fb0853b131b783d8875794334fae7f
91deb376-7ef7-42c4-bc88-4a85799d766c
cpp
google/cel-cpp
reference
common/reference.cc
common/reference_test.cc
#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"})); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/reference.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/reference_test.cc
4552db5798fb0853b131b783d8875794334fae7f
1b4ec663-8290-45e4-8883-8a08002c6f9c
cpp
google/cel-cpp
ast_rewrite
eval/public/ast_rewrite.cc
eval/public/ast_rewrite_test.cc
#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")); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/ast_rewrite.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/ast_rewrite_test.cc
4552db5798fb0853b131b783d8875794334fae7f
67162720-7b91-4e49-9f0d-59f369b55439
cpp
google/cel-cpp
kind
common/kind.cc
common/kind_test.cc
#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"; case Kind::kEnum: return "enum"; 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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/kind.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/kind_test.cc
4552db5798fb0853b131b783d8875794334fae7f
d5aa5d03-9969-4c67-b9de-22138d23dbba
cpp
google/cel-cpp
value_factory
common/value_factory.cc
common/value_factory_test.cc
#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 "internal/status_macros.h" #include "internal/time.h" #include "internal/utf8.h" namespace cel { namespace { 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(StringValue(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(NullValue().DebugString()); }, [&out](JsonBool value) -> void { out.append(BoolValue(value).DebugString()); }, [&out](JsonNumber value) -> void { out.append(DoubleValue(value).DebugString()); }, [&out](const JsonString& value) -> void { out.append(StringValue(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: 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, const Value& key, Value& result) const override { return Cast<StringValue>(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&, const Value& key) const override { return Cast<StringValue>(key).NativeValue(absl::Overload( [this](absl::string_view value) -> bool { return object_.contains(value); }, [this](const absl::Cord& value) -> bool { return object_.contains(value); })); } 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::GetZeroDynListValue() { return ListValue(); } MapValue ValueFactory::GetZeroDynDynMapValue() { return MapValue(); } MapValue ValueFactory::GetZeroStringDynMapValue() { return MapValue(); } OptionalValue ValueFactory::GetZeroDynOptionalValue() { return OptionalValue(); } 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/value.h" #include "common/value_manager.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::IsOkAndHolds; using ::testing::TestParamInfo; using ::testing::UnorderedElementsAreArray; class ValueFactoryTest : public common_internal::ThreadCompatibleMemoryTest<> { public: void SetUp() override { value_manager_ = NewThreadCompatibleValueManager( memory_manager(), NewThreadCompatibleTypeReflector(memory_manager())); } 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_; } static std::string ToString( TestParamInfo<std::tuple<MemoryManagement>> param) { std::ostringstream out; out << std::get<0>(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(Type(value.GetRuntimeType()), 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)); 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({StringValue("a"), StringValue("b"), StringValue("c"), StringValue("d"), StringValue("e"), StringValue("f")})); ASSERT_OK_AND_ASSIGN(auto has, map_value.Has(value_manager(), StringValue("a"))); ASSERT_TRUE(InstanceOf<BoolValue>(has)); EXPECT_TRUE(Cast<BoolValue>(has).NativeValue()); ASSERT_OK_AND_ASSIGN( has, map_value.Has(value_manager(), StringValue(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(), StringValue("a"))); ASSERT_TRUE(InstanceOf<NullValue>(get)); ASSERT_OK_AND_ASSIGN( get, map_value.Get(value_manager(), StringValue(absl::Cord("a")))); ASSERT_TRUE(InstanceOf<NullValue>(get)); } INSTANTIATE_TEST_SUITE_P( ValueFactoryTest, ValueFactoryTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), ValueFactoryTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/value_factory.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/value_factory_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e9e402c9-9be5-442f-9be4-e0ed14971680
cpp
google/cel-cpp
memory
common/memory.cc
common/memory_test.cc
#include "common/memory.h" #include <cstddef> #include <cstring> #include <new> #include <ostream> #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/numeric/bits.h" #include "google/protobuf/arena.h" namespace cel { std::ostream& operator<<(std::ostream& out, MemoryManagement memory_management) { switch (memory_management) { case MemoryManagement::kPooling: return out << "POOLING"; case MemoryManagement::kReferenceCounting: return out << "REFERENCE_COUNTING"; } } void* ReferenceCountingMemoryManager::Allocate(size_t size, size_t alignment) { ABSL_DCHECK(absl::has_single_bit(alignment)) << "alignment must be a power of 2: " << alignment; if (size == 0) { return nullptr; } if (alignment <= __STDCPP_DEFAULT_NEW_ALIGNMENT__) { return ::operator new(size); } return ::operator new(size, static_cast<std::align_val_t>(alignment)); } bool ReferenceCountingMemoryManager::Deallocate(void* ptr, size_t size, size_t alignment) noexcept { ABSL_DCHECK(absl::has_single_bit(alignment)) << "alignment must be a power of 2: " << alignment; if (ptr == nullptr) { ABSL_DCHECK_EQ(size, 0); return false; } ABSL_DCHECK_GT(size, 0); if (alignment <= __STDCPP_DEFAULT_NEW_ALIGNMENT__) { #if defined(__cpp_sized_deallocation) && __cpp_sized_deallocation >= 201309L ::operator delete(ptr, size); #else ::operator delete(ptr); #endif } else { #if defined(__cpp_sized_deallocation) && __cpp_sized_deallocation >= 201309L ::operator delete(ptr, size, static_cast<std::align_val_t>(alignment)); #else ::operator delete(ptr, static_cast<std::align_val_t>(alignment)); #endif } return true; } MemoryManager MemoryManager::Unmanaged() { static absl::NoDestructor<google::protobuf::Arena> arena; return MemoryManager::Pooling(&*arena); } }
#include "common/memory.h" #include <cstddef> #include <memory> #include <sstream> #include <string> #include <utility> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/debugging/leak_check.h" #include "absl/log/absl_check.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/data.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->()); } class OwnedTest : public TestWithParam<MemoryManagement> { public: Allocator<> GetAllocator() { switch (GetParam()) { case MemoryManagement::kPooling: return ArenaAllocator(&arena_); case MemoryManagement::kReferenceCounting: return NewDeleteAllocator(); } } private: google::protobuf::Arena arena_; }; TEST_P(OwnedTest, Default) { Owned<Data> owned; EXPECT_FALSE(owned); EXPECT_EQ(cel::to_address(owned), nullptr); EXPECT_FALSE(owned != nullptr); EXPECT_FALSE(nullptr != owned); } class TestData final : public Data { public: using InternalArenaConstructable_ = void; using DestructorSkippable_ = void; TestData() noexcept : Data() {} explicit TestData(absl::Nullable<google::protobuf::Arena*> arena) noexcept : Data(arena) {} }; TEST_P(OwnedTest, AllocateSharedData) { auto owned = AllocateShared<TestData>(GetAllocator()); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_EQ(Owner(owned).arena(), GetAllocator().arena()); EXPECT_EQ(Borrower(owned).arena(), GetAllocator().arena()); } TEST_P(OwnedTest, AllocateSharedMessageLite) { auto owned = AllocateShared<google::protobuf::Value>(GetAllocator()); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_EQ(Owner(owned).arena(), GetAllocator().arena()); EXPECT_EQ(Borrower(owned).arena(), GetAllocator().arena()); } TEST_P(OwnedTest, WrapSharedData) { auto owned = WrapShared(google::protobuf::Arena::Create<TestData>(GetAllocator().arena())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_EQ(Owner(owned).arena(), GetAllocator().arena()); EXPECT_EQ(Borrower(owned).arena(), GetAllocator().arena()); } TEST_P(OwnedTest, WrapSharedMessageLite) { auto owned = WrapShared( google::protobuf::Arena::Create<google::protobuf::Value>(GetAllocator().arena())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_EQ(Owner(owned).arena(), GetAllocator().arena()); EXPECT_EQ(Borrower(owned).arena(), GetAllocator().arena()); } TEST_P(OwnedTest, SharedFromUniqueData) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_EQ(Owner(owned).arena(), GetAllocator().arena()); EXPECT_EQ(Borrower(owned).arena(), GetAllocator().arena()); } TEST_P(OwnedTest, SharedFromUniqueMessageLite) { auto owned = Owned(AllocateUnique<google::protobuf::Value>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_EQ(Owner(owned).arena(), GetAllocator().arena()); EXPECT_EQ(Borrower(owned).arena(), GetAllocator().arena()); } TEST_P(OwnedTest, CopyConstruct) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> copied_owned(owned); EXPECT_EQ(copied_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, MoveConstruct) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> moved_owned(std::move(owned)); EXPECT_EQ(moved_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, CopyConstructOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<Data> copied_owned(owned); EXPECT_EQ(copied_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, MoveConstructOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<Data> moved_owned(std::move(owned)); EXPECT_EQ(moved_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, ConstructBorrowed) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> borrowed_owned(Borrowed<TestData>{owned}); EXPECT_EQ(borrowed_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, ConstructOwner) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> owner_owned(Owner(owned), cel::to_address(owned)); EXPECT_EQ(owner_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, ConstructNullPtr) { Owned<Data> owned(nullptr); EXPECT_EQ(owned, nullptr); } TEST_P(OwnedTest, CopyAssign) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> copied_owned; copied_owned = owned; EXPECT_EQ(copied_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, MoveAssign) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> moved_owned; moved_owned = std::move(owned); EXPECT_EQ(moved_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, CopyAssignOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<Data> copied_owned; copied_owned = owned; EXPECT_EQ(copied_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, MoveAssignOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<Data> moved_owned; moved_owned = std::move(owned); EXPECT_EQ(moved_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, AssignBorrowed) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Owned<TestData> borrowed_owned; borrowed_owned = Borrowed<TestData>{owned}; EXPECT_EQ(borrowed_owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, AssignUnique) { Owned<TestData> owned; owned = AllocateUnique<TestData>(GetAllocator()); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); } TEST_P(OwnedTest, AssignNullPtr) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); EXPECT_TRUE(owned); owned = nullptr; EXPECT_FALSE(owned); } INSTANTIATE_TEST_SUITE_P( OwnedTest, OwnedTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)); class BorrowedTest : public TestWithParam<MemoryManagement> { public: Allocator<> GetAllocator() { switch (GetParam()) { case MemoryManagement::kPooling: return ArenaAllocator(&arena_); case MemoryManagement::kReferenceCounting: return NewDeleteAllocator(); } } private: google::protobuf::Arena arena_; }; TEST_P(BorrowedTest, Default) { Borrowed<Data> borrowed; EXPECT_FALSE(borrowed); EXPECT_EQ(cel::to_address(borrowed), nullptr); EXPECT_FALSE(borrowed != nullptr); EXPECT_FALSE(nullptr != borrowed); } TEST_P(BorrowedTest, CopyConstruct) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<TestData> copied_borrowed(borrowed); EXPECT_EQ(copied_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, MoveConstruct) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<TestData> moved_borrowed(std::move(borrowed)); EXPECT_EQ(moved_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, CopyConstructOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<Data> copied_borrowed(borrowed); EXPECT_EQ(copied_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, MoveConstructOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<Data> moved_borrowed(std::move(borrowed)); EXPECT_EQ(moved_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, ConstructNullPtr) { Borrowed<TestData> borrowed(nullptr); EXPECT_FALSE(borrowed); } TEST_P(BorrowedTest, CopyAssign) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<TestData> copied_borrowed; copied_borrowed = borrowed; EXPECT_EQ(copied_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, MoveAssign) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<TestData> moved_borrowed; moved_borrowed = std::move(borrowed); EXPECT_EQ(moved_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, CopyAssignOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<Data> copied_borrowed; copied_borrowed = borrowed; EXPECT_EQ(copied_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, MoveAssignOther) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); auto borrowed = Borrowed(owned); EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); Borrowed<Data> moved_borrowed; moved_borrowed = std::move(borrowed); EXPECT_EQ(moved_borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, AssignOwned) { auto owned = Owned(AllocateUnique<TestData>(GetAllocator())); EXPECT_EQ(owned->GetArena(), GetAllocator().arena()); Borrowed<Data> borrowed = owned; EXPECT_EQ(borrowed->GetArena(), GetAllocator().arena()); } TEST_P(BorrowedTest, AssignNullPtr) { Borrowed<TestData> borrowed; borrowed = nullptr; EXPECT_FALSE(borrowed); } INSTANTIATE_TEST_SUITE_P( BorrowedTest, BorrowedTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/memory.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/memory_test.cc
4552db5798fb0853b131b783d8875794334fae7f
8c6606ee-28ef-4e3b-be17-ef3a8e2c4e7f
cpp
google/cel-cpp
native_type
common/native_type.cc
common/native_type_test.cc
#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{})); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/native_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/native_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
2478c4a4-5745-42fe-abaf-6b65cb3276c5
cpp
google/cel-cpp
list_type
common/types/list_type.cc
common/types/list_type_test.cc
#include <string> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "common/type.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" namespace cel { namespace common_internal { namespace { ABSL_CONST_INIT const ListTypeData kDynListTypeData; } absl::Nonnull<ListTypeData*> ListTypeData::Create( absl::Nonnull<google::protobuf::Arena*> arena, const Type& element) { return ::new (arena->AllocateAligned( sizeof(ListTypeData), alignof(ListTypeData))) ListTypeData(element); } ListTypeData::ListTypeData(const Type& element) : element(element) {} } ListType::ListType() : ListType(&common_internal::kDynListTypeData) {} ListType::ListType(absl::Nonnull<google::protobuf::Arena*> arena, const Type& element) : ListType(element.IsDyn() ? &common_internal::kDynListTypeData : common_internal::ListTypeData::Create(arena, element)) {} std::string ListType::DebugString() const { return absl::StrCat("list<", element().DebugString(), ">"); } TypeParameters ListType::GetParameters() const { return TypeParameters(GetElement()); } Type ListType::GetElement() const { ABSL_DCHECK_NE(data_, 0); if ((data_ & kBasicBit) == kBasicBit) { return reinterpret_cast<const common_internal::ListTypeData*>(data_ & kPointerMask) ->element; } if ((data_ & kProtoBit) == kProtoBit) { return common_internal::SingularMessageFieldType( reinterpret_cast<const google::protobuf::FieldDescriptor*>(data_ & kPointerMask)); } return Type(); } Type ListType::element() const { return GetElement(); } }
#include <sstream> #include "absl/hash/hash.h" #include "common/type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel { namespace { TEST(ListType, Default) { ListType list_type; EXPECT_EQ(list_type.element(), DynType()); } TEST(ListType, Kind) { google::protobuf::Arena arena; EXPECT_EQ(ListType(&arena, BoolType()).kind(), ListType::kKind); EXPECT_EQ(Type(ListType(&arena, BoolType())).kind(), ListType::kKind); } TEST(ListType, Name) { google::protobuf::Arena arena; EXPECT_EQ(ListType(&arena, BoolType()).name(), ListType::kName); EXPECT_EQ(Type(ListType(&arena, BoolType())).name(), ListType::kName); } TEST(ListType, DebugString) { google::protobuf::Arena arena; { std::ostringstream out; out << ListType(&arena, BoolType()); EXPECT_EQ(out.str(), "list<bool>"); } { std::ostringstream out; out << Type(ListType(&arena, BoolType())); EXPECT_EQ(out.str(), "list<bool>"); } } TEST(ListType, Hash) { google::protobuf::Arena arena; EXPECT_EQ(absl::HashOf(ListType(&arena, BoolType())), absl::HashOf(ListType(&arena, BoolType()))); } TEST(ListType, Equal) { google::protobuf::Arena arena; EXPECT_EQ(ListType(&arena, BoolType()), ListType(&arena, BoolType())); EXPECT_EQ(Type(ListType(&arena, BoolType())), ListType(&arena, BoolType())); EXPECT_EQ(ListType(&arena, BoolType()), Type(ListType(&arena, BoolType()))); EXPECT_EQ(Type(ListType(&arena, BoolType())), Type(ListType(&arena, BoolType()))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/list_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/list_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e114bc94-ba21-4c16-9d98-227c026a9002
cpp
google/cel-cpp
optional_type
common/types/optional_type.cc
common/types/optional_type_test.cc
#include <cstddef> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "common/type.h" namespace cel { namespace common_internal { namespace { struct OptionalTypeData final { const absl::string_view name; const size_t parameters_size; const Type parameter; }; union DynOptionalTypeData final { OptionalTypeData optional; OpaqueTypeData opaque; }; static_assert(offsetof(OptionalTypeData, name) == offsetof(OpaqueTypeData, name)); static_assert(offsetof(OptionalTypeData, parameters_size) == offsetof(OpaqueTypeData, parameters_size)); static_assert(offsetof(OptionalTypeData, parameter) == offsetof(OpaqueTypeData, parameters)); ABSL_CONST_INIT const DynOptionalTypeData kDynOptionalTypeData = { .optional = { .name = OptionalType::kName, .parameters_size = 1, .parameter = DynType(), }, }; } } OptionalType::OptionalType() : opaque_(&common_internal::kDynOptionalTypeData.opaque) {} Type OptionalType::GetParameter() const { return GetParameters().front(); } }
#include <sstream> #include "absl/hash/hash.h" #include "common/type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel { namespace { TEST(OptionalType, Default) { OptionalType optional_type; EXPECT_EQ(optional_type.GetParameter(), DynType()); } TEST(OptionalType, Kind) { google::protobuf::Arena arena; EXPECT_EQ(OptionalType(&arena, BoolType()).kind(), OptionalType::kKind); EXPECT_EQ(Type(OptionalType(&arena, BoolType())).kind(), OptionalType::kKind); } TEST(OptionalType, Name) { google::protobuf::Arena arena; EXPECT_EQ(OptionalType(&arena, BoolType()).name(), OptionalType::kName); EXPECT_EQ(Type(OptionalType(&arena, BoolType())).name(), OptionalType::kName); } TEST(OptionalType, DebugString) { google::protobuf::Arena arena; { std::ostringstream out; out << OptionalType(&arena, BoolType()); EXPECT_EQ(out.str(), "optional_type<bool>"); } { std::ostringstream out; out << Type(OptionalType(&arena, BoolType())); EXPECT_EQ(out.str(), "optional_type<bool>"); } } TEST(OptionalType, Parameter) { google::protobuf::Arena arena; EXPECT_EQ(OptionalType(&arena, BoolType()).GetParameter(), BoolType()); } TEST(OptionalType, Hash) { google::protobuf::Arena arena; EXPECT_EQ(absl::HashOf(OptionalType(&arena, BoolType())), absl::HashOf(OptionalType(&arena, BoolType()))); } TEST(OptionalType, Equal) { google::protobuf::Arena arena; EXPECT_EQ(OptionalType(&arena, BoolType()), OptionalType(&arena, BoolType())); EXPECT_EQ(Type(OptionalType(&arena, BoolType())), OptionalType(&arena, BoolType())); EXPECT_EQ(OptionalType(&arena, BoolType()), Type(OptionalType(&arena, BoolType()))); EXPECT_EQ(Type(OptionalType(&arena, BoolType())), Type(OptionalType(&arena, BoolType()))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/optional_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/optional_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
671484fe-b9bf-495f-ba88-1dec3ba87779
cpp
google/cel-cpp
map_type
common/types/map_type.cc
common/types/map_type_test.cc
#include <string> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "common/type.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" namespace cel { namespace common_internal { namespace { ABSL_CONST_INIT const MapTypeData kDynDynMapTypeData = { .key_and_value = {DynType(), DynType()}, }; ABSL_CONST_INIT const MapTypeData kStringDynMapTypeData = { .key_and_value = {StringType(), DynType()}, }; } absl::Nonnull<MapTypeData*> MapTypeData::Create( absl::Nonnull<google::protobuf::Arena*> arena, const Type& key, const Type& value) { MapTypeData* data = ::new (arena->AllocateAligned(sizeof(MapTypeData), alignof(MapTypeData))) MapTypeData; data->key_and_value[0] = key; data->key_and_value[1] = value; return data; } } MapType::MapType() : MapType(&common_internal::kDynDynMapTypeData) {} MapType::MapType(absl::Nonnull<google::protobuf::Arena*> arena, const Type& key, const Type& value) : MapType(key.IsDyn() && value.IsDyn() ? &common_internal::kDynDynMapTypeData : common_internal::MapTypeData::Create(arena, key, value)) {} std::string MapType::DebugString() const { return absl::StrCat("map<", key().DebugString(), ", ", value().DebugString(), ">"); } TypeParameters MapType::GetParameters() const { ABSL_DCHECK_NE(data_, 0); if ((data_ & kBasicBit) == kBasicBit) { const auto* data = reinterpret_cast<const common_internal::MapTypeData*>( data_ & kPointerMask); return TypeParameters(data->key_and_value[0], data->key_and_value[1]); } if ((data_ & kProtoBit) == kProtoBit) { const auto* descriptor = reinterpret_cast<const google::protobuf::Descriptor*>(data_ & kPointerMask); return TypeParameters(Type::Field(descriptor->map_key()), Type::Field(descriptor->map_value())); } return TypeParameters(Type(), Type()); } Type MapType::GetKey() const { ABSL_DCHECK_NE(data_, 0); if ((data_ & kBasicBit) == kBasicBit) { return reinterpret_cast<const common_internal::MapTypeData*>(data_ & kPointerMask) ->key_and_value[0]; } if ((data_ & kProtoBit) == kProtoBit) { return Type::Field( reinterpret_cast<const google::protobuf::Descriptor*>(data_ & kPointerMask) ->map_key()); } return Type(); } Type MapType::key() const { return GetKey(); } Type MapType::GetValue() const { ABSL_DCHECK_NE(data_, 0); if ((data_ & kBasicBit) == kBasicBit) { return reinterpret_cast<const common_internal::MapTypeData*>(data_ & kPointerMask) ->key_and_value[1]; } if ((data_ & kProtoBit) == kProtoBit) { return Type::Field( reinterpret_cast<const google::protobuf::Descriptor*>(data_ & kPointerMask) ->map_value()); } return Type(); } Type MapType::value() const { return GetValue(); } MapType JsonMapType() { return MapType(&common_internal::kStringDynMapTypeData); } }
#include <sstream> #include "absl/hash/hash.h" #include "common/type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel { namespace { TEST(MapType, Default) { MapType map_type; EXPECT_EQ(map_type.key(), DynType()); EXPECT_EQ(map_type.value(), DynType()); } TEST(MapType, Kind) { google::protobuf::Arena arena; EXPECT_EQ(MapType(&arena, StringType(), BytesType()).kind(), MapType::kKind); EXPECT_EQ(Type(MapType(&arena, StringType(), BytesType())).kind(), MapType::kKind); } TEST(MapType, Name) { google::protobuf::Arena arena; EXPECT_EQ(MapType(&arena, StringType(), BytesType()).name(), MapType::kName); EXPECT_EQ(Type(MapType(&arena, StringType(), BytesType())).name(), MapType::kName); } TEST(MapType, DebugString) { google::protobuf::Arena arena; { std::ostringstream out; out << MapType(&arena, StringType(), BytesType()); EXPECT_EQ(out.str(), "map<string, bytes>"); } { std::ostringstream out; out << Type(MapType(&arena, StringType(), BytesType())); EXPECT_EQ(out.str(), "map<string, bytes>"); } } TEST(MapType, Hash) { google::protobuf::Arena arena; EXPECT_EQ(absl::HashOf(MapType(&arena, StringType(), BytesType())), absl::HashOf(MapType(&arena, StringType(), BytesType()))); } TEST(MapType, Equal) { google::protobuf::Arena arena; EXPECT_EQ(MapType(&arena, StringType(), BytesType()), MapType(&arena, StringType(), BytesType())); EXPECT_EQ(Type(MapType(&arena, StringType(), BytesType())), MapType(&arena, StringType(), BytesType())); EXPECT_EQ(MapType(&arena, StringType(), BytesType()), Type(MapType(&arena, StringType(), BytesType()))); EXPECT_EQ(Type(MapType(&arena, StringType(), BytesType())), Type(MapType(&arena, StringType(), BytesType()))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/map_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/map_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
f5f16c60-4ca6-4bc5-b57b-52af2ce349be
cpp
google/cel-cpp
opaque_type
common/types/opaque_type.cc
common/types/opaque_type_test.cc
#include <cstddef> #include <cstring> #include <string> #include <type_traits> #include "absl/base/nullability.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/optional.h" #include "absl/types/span.h" #include "absl/utility/utility.h" #include "common/type.h" #include "google/protobuf/arena.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()), ">"); } } namespace common_internal { absl::Nonnull<OpaqueTypeData*> OpaqueTypeData::Create( absl::Nonnull<google::protobuf::Arena*> arena, absl::string_view name, absl::Span<const Type> parameters) { return ::new (arena->AllocateAligned( offsetof(OpaqueTypeData, parameters) + (parameters.size() * sizeof(Type)), alignof(OpaqueTypeData))) OpaqueTypeData(name, parameters); } OpaqueTypeData::OpaqueTypeData(absl::string_view name, absl::Span<const Type> parameters) : name(name), parameters_size(parameters.size()) { std::memcpy(this->parameters, parameters.data(), parameters_size * sizeof(Type)); } } OpaqueType::OpaqueType(absl::Nonnull<google::protobuf::Arena*> arena, absl::string_view name, absl::Span<const Type> parameters) : OpaqueType( common_internal::OpaqueTypeData::Create(arena, name, parameters)) {} std::string OpaqueType::DebugString() const { ABSL_DCHECK(*this); return OpaqueDebugString(name(), GetParameters()); } absl::string_view OpaqueType::name() const { ABSL_DCHECK(*this); return data_->name; } TypeParameters OpaqueType::GetParameters() const { ABSL_DCHECK(*this); return TypeParameters( absl::MakeConstSpan(data_->parameters, data_->parameters_size)); } bool OpaqueType::IsOptional() const { return name() == OptionalType::kName && GetParameters().size() == 1; } absl::optional<OptionalType> OpaqueType::AsOptional() const { if (IsOptional()) { return OptionalType(absl::in_place, *this); } return absl::nullopt; } OptionalType OpaqueType::GetOptional() const { ABSL_DCHECK(IsOptional()) << DebugString(); return OptionalType(absl::in_place, *this); } }
#include <sstream> #include "absl/hash/hash.h" #include "common/type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel { namespace { TEST(OpaqueType, Kind) { google::protobuf::Arena arena; EXPECT_EQ(OpaqueType(&arena, "test.Opaque", {BytesType()}).kind(), OpaqueType::kKind); EXPECT_EQ(Type(OpaqueType(&arena, "test.Opaque", {BytesType()})).kind(), OpaqueType::kKind); } TEST(OpaqueType, Name) { google::protobuf::Arena arena; EXPECT_EQ(OpaqueType(&arena, "test.Opaque", {BytesType()}).name(), "test.Opaque"); EXPECT_EQ(Type(OpaqueType(&arena, "test.Opaque", {BytesType()})).name(), "test.Opaque"); } TEST(OpaqueType, DebugString) { google::protobuf::Arena arena; { std::ostringstream out; out << OpaqueType(&arena, "test.Opaque", {BytesType()}); EXPECT_EQ(out.str(), "test.Opaque<bytes>"); } { std::ostringstream out; out << Type(OpaqueType(&arena, "test.Opaque", {BytesType()})); EXPECT_EQ(out.str(), "test.Opaque<bytes>"); } { std::ostringstream out; out << OpaqueType(&arena, "test.Opaque", {}); EXPECT_EQ(out.str(), "test.Opaque"); } } TEST(OpaqueType, Hash) { google::protobuf::Arena arena; EXPECT_EQ(absl::HashOf(OpaqueType(&arena, "test.Opaque", {BytesType()})), absl::HashOf(OpaqueType(&arena, "test.Opaque", {BytesType()}))); } TEST(OpaqueType, Equal) { google::protobuf::Arena arena; EXPECT_EQ(OpaqueType(&arena, "test.Opaque", {BytesType()}), OpaqueType(&arena, "test.Opaque", {BytesType()})); EXPECT_EQ(Type(OpaqueType(&arena, "test.Opaque", {BytesType()})), OpaqueType(&arena, "test.Opaque", {BytesType()})); EXPECT_EQ(OpaqueType(&arena, "test.Opaque", {BytesType()}), Type(OpaqueType(&arena, "test.Opaque", {BytesType()}))); EXPECT_EQ(Type(OpaqueType(&arena, "test.Opaque", {BytesType()})), Type(OpaqueType(&arena, "test.Opaque", {BytesType()}))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/opaque_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/opaque_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
800c1f91-fb75-4e4d-b139-9a34c49d661b
cpp
google/cel-cpp
type_type
common/types/type_type.cc
common/types/type_type_test.cc
#include "common/type.h" #include "absl/base/nullability.h" #include "absl/types/span.h" #include "google/protobuf/arena.h" namespace cel { namespace common_internal { struct TypeTypeData final { static TypeTypeData* Create(absl::Nonnull<google::protobuf::Arena*> arena, const Type& type) { return google::protobuf::Arena::Create<TypeTypeData>(arena, type); } explicit TypeTypeData(const Type& type) : type(type) {} TypeTypeData() = delete; TypeTypeData(const TypeTypeData&) = delete; TypeTypeData(TypeTypeData&&) = delete; TypeTypeData& operator=(const TypeTypeData&) = delete; TypeTypeData& operator=(TypeTypeData&&) = delete; const Type type; }; } TypeType::TypeType(absl::Nonnull<google::protobuf::Arena*> arena, const Type& parameter) : TypeType(common_internal::TypeTypeData::Create(arena, parameter)) {} TypeParameters TypeType::GetParameters() const { if (data_) { return TypeParameters(absl::MakeConstSpan(&data_->type, 1)); } return {}; } Type TypeType::GetType() const { if (data_) { return data_->type; } return Type(); } }
#include "common/type.h" #include <sstream> #include "absl/hash/hash.h" #include "internal/testing.h" namespace cel { namespace { TEST(TypeType, Kind) { EXPECT_EQ(TypeType().kind(), TypeType::kKind); EXPECT_EQ(Type(TypeType()).kind(), TypeType::kKind); } TEST(TypeType, Name) { EXPECT_EQ(TypeType().name(), TypeType::kName); EXPECT_EQ(Type(TypeType()).name(), TypeType::kName); } TEST(TypeType, DebugString) { { std::ostringstream out; out << TypeType(); EXPECT_EQ(out.str(), TypeType::kName); } { std::ostringstream out; out << Type(TypeType()); EXPECT_EQ(out.str(), TypeType::kName); } } TEST(TypeType, Hash) { EXPECT_EQ(absl::HashOf(TypeType()), absl::HashOf(TypeType())); } TEST(TypeType, Equal) { EXPECT_EQ(TypeType(), TypeType()); EXPECT_EQ(Type(TypeType()), TypeType()); EXPECT_EQ(TypeType(), Type(TypeType())); EXPECT_EQ(Type(TypeType()), Type(TypeType())); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/type_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/type_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
8f4948f3-55a4-4823-8e3a-94744b33e635
cpp
google/cel-cpp
enum_type
common/types/enum_type.cc
common/types/enum_type_test.cc
#include <string> #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "common/type.h" #include "google/protobuf/descriptor.h" namespace cel { using google::protobuf::EnumDescriptor; bool IsWellKnownEnumType(absl::Nonnull<const EnumDescriptor*> descriptor) { return descriptor->full_name() == "google.protobuf.NullValue"; } std::string EnumType::DebugString() const { if (ABSL_PREDICT_TRUE(static_cast<bool>(*this))) { static_assert(sizeof(descriptor_) == 8 || sizeof(descriptor_) == 4, "sizeof(void*) is neither 8 nor 4"); return absl::StrCat(name(), "@0x", absl::Hex(descriptor_, sizeof(descriptor_) == 8 ? absl::PadSpec::kZeroPad16 : absl::PadSpec::kZeroPad8)); } return std::string(); } }
#include "google/protobuf/descriptor.pb.h" #include "common/memory.h" #include "common/type.h" #include "common/type_kind.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" namespace cel { namespace { using ::testing::Eq; using ::testing::IsEmpty; using ::testing::NotNull; using ::testing::StartsWith; TEST(EnumType, Kind) { EXPECT_EQ(EnumType::kind(), TypeKind::kEnum); } TEST(EnumType, Default) { EnumType type; EXPECT_FALSE(type); EXPECT_THAT(type.DebugString(), Eq("")); EXPECT_EQ(type, EnumType()); } TEST(EnumType, Descriptor) { google::protobuf::DescriptorPool pool; { google::protobuf::FileDescriptorProto file_desc_proto; file_desc_proto.set_syntax("proto3"); file_desc_proto.set_package("test"); file_desc_proto.set_name("test/enum.proto"); auto* enum_desc = file_desc_proto.add_enum_type(); enum_desc->set_name("Enum"); auto* enum_value_desc = enum_desc->add_value(); enum_value_desc->set_number(0); enum_value_desc->set_name("VALUE"); ASSERT_THAT(pool.BuildFile(file_desc_proto), NotNull()); } const google::protobuf::EnumDescriptor* desc = pool.FindEnumTypeByName("test.Enum"); ASSERT_THAT(desc, NotNull()); EnumType type(desc); EXPECT_TRUE(type); EXPECT_THAT(type.name(), Eq("test.Enum")); EXPECT_THAT(type.DebugString(), StartsWith("test.Enum@0x")); EXPECT_THAT(type.GetParameters(), IsEmpty()); EXPECT_NE(type, EnumType()); EXPECT_NE(EnumType(), type); EXPECT_EQ(cel::to_address(type), desc); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/enum_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/enum_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
b7ffdda7-6fd5-418d-bc6a-e72a47e2948e
cpp
google/cel-cpp
basic_struct_type
common/types/basic_struct_type.cc
common/types/basic_struct_type_test.cc
#include <array> #include "absl/algorithm/container.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "common/type.h" namespace cel { bool IsWellKnownMessageType(absl::string_view name) { static constexpr absl::string_view kPrefix = "google.protobuf."; static constexpr std::array<absl::string_view, 15> kNames = { "Any", "BoolValue", "BytesValue", "DoubleValue", "Duration", "FloatValue", "Int32Value", "Int64Value", "ListValue", "StringValue", "Struct", "Timestamp", "UInt32Value", "UInt64Value", "Value", }; if (!absl::ConsumePrefix(&name, kPrefix)) { return false; } return absl::c_binary_search(kNames, name); } }
#include "common/type.h" #include "common/type_kind.h" #include "internal/testing.h" namespace cel::common_internal { namespace { using ::testing::Eq; using ::testing::IsEmpty; TEST(BasicStructType, Kind) { EXPECT_EQ(BasicStructType::kind(), TypeKind::kStruct); } TEST(BasicStructType, Default) { BasicStructType type; EXPECT_FALSE(type); EXPECT_THAT(type.DebugString(), Eq("")); EXPECT_EQ(type, BasicStructType()); } TEST(BasicStructType, Name) { BasicStructType type = MakeBasicStructType("test.Struct"); EXPECT_TRUE(type); EXPECT_THAT(type.name(), Eq("test.Struct")); EXPECT_THAT(type.DebugString(), Eq("test.Struct")); EXPECT_THAT(type.GetParameters(), IsEmpty()); EXPECT_NE(type, BasicStructType()); EXPECT_NE(BasicStructType(), type); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/basic_struct_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/basic_struct_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
6ed72d99-79f6-4ec1-983d-ef0e978b28cc
cpp
google/cel-cpp
message_type
common/types/message_type.cc
common/types/message_type_test.cc
#include <string> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "common/type.h" #include "google/protobuf/descriptor.h" namespace cel { using google::protobuf::Descriptor; bool IsWellKnownMessageType(absl::Nonnull<const Descriptor*> descriptor) { switch (descriptor->well_known_type()) { case Descriptor::WELLKNOWNTYPE_BOOLVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_INT32VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_INT64VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_UINT32VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_UINT64VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_FLOATVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_BYTESVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_STRINGVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_ANY: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_DURATION: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_TIMESTAMP: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_LISTVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_STRUCT: return true; default: return false; } } std::string MessageType::DebugString() const { if (ABSL_PREDICT_TRUE(static_cast<bool>(*this))) { static_assert(sizeof(descriptor_) == 8 || sizeof(descriptor_) == 4, "sizeof(void*) is neither 8 nor 4"); return absl::StrCat(name(), "@0x", absl::Hex(descriptor_, sizeof(descriptor_) == 8 ? absl::PadSpec::kZeroPad16 : absl::PadSpec::kZeroPad8)); } return std::string(); } std::string MessageTypeField::DebugString() const { if (ABSL_PREDICT_TRUE(static_cast<bool>(*this))) { static_assert(sizeof(descriptor_) == 8 || sizeof(descriptor_) == 4, "sizeof(void*) is neither 8 nor 4"); return absl::StrCat("[", (*this)->number(), "]", (*this)->name(), "@0x", absl::Hex(descriptor_, sizeof(descriptor_) == 8 ? absl::PadSpec::kZeroPad16 : absl::PadSpec::kZeroPad8)); } return std::string(); } Type MessageTypeField::GetType() const { ABSL_DCHECK(*this); return Type::Field(descriptor_); } }
#include "google/protobuf/descriptor.pb.h" #include "common/memory.h" #include "common/type.h" #include "common/type_kind.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" namespace cel { namespace { using ::testing::An; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::NotNull; using ::testing::Optional; using ::testing::StartsWith; TEST(MessageType, Kind) { EXPECT_EQ(MessageType::kind(), TypeKind::kStruct); } TEST(MessageType, Default) { MessageType type; EXPECT_FALSE(type); EXPECT_THAT(type.DebugString(), Eq("")); EXPECT_EQ(type, MessageType()); } TEST(MessageType, Descriptor) { google::protobuf::DescriptorPool pool; { google::protobuf::FileDescriptorProto file_desc_proto; file_desc_proto.set_syntax("proto3"); file_desc_proto.set_package("test"); file_desc_proto.set_name("test/struct.proto"); file_desc_proto.add_message_type()->set_name("Struct"); ASSERT_THAT(pool.BuildFile(file_desc_proto), NotNull()); } const google::protobuf::Descriptor* desc = pool.FindMessageTypeByName("test.Struct"); ASSERT_THAT(desc, NotNull()); MessageType type(desc); EXPECT_TRUE(type); EXPECT_THAT(type.name(), Eq("test.Struct")); EXPECT_THAT(type.DebugString(), StartsWith("test.Struct@0x")); EXPECT_THAT(type.GetParameters(), IsEmpty()); EXPECT_NE(type, MessageType()); EXPECT_NE(MessageType(), type); EXPECT_EQ(cel::to_address(type), desc); } TEST(MessageTypeField, Descriptor) { google::protobuf::DescriptorPool pool; { google::protobuf::FileDescriptorProto file_desc_proto; file_desc_proto.set_syntax("proto3"); file_desc_proto.set_package("test"); file_desc_proto.set_name("test/struct.proto"); auto* message_type = file_desc_proto.add_message_type(); message_type->set_name("Struct"); auto* field = message_type->add_field(); field->set_name("foo"); field->set_json_name("foo"); field->set_number(1); field->set_type(google::protobuf::FieldDescriptorProto::TYPE_INT64); field->set_label(google::protobuf::FieldDescriptorProto::LABEL_OPTIONAL); ASSERT_THAT(pool.BuildFile(file_desc_proto), NotNull()); } const google::protobuf::Descriptor* desc = pool.FindMessageTypeByName("test.Struct"); ASSERT_THAT(desc, NotNull()); const google::protobuf::FieldDescriptor* field_desc = desc->FindFieldByName("foo"); ASSERT_THAT(desc, NotNull()); MessageTypeField message_type_field(field_desc); EXPECT_TRUE(message_type_field); EXPECT_THAT(message_type_field.name(), Eq("foo")); EXPECT_THAT(message_type_field.DebugString(), StartsWith("[1]foo@0x")); EXPECT_THAT(message_type_field.number(), Eq(1)); EXPECT_THAT(message_type_field.GetType(), IntType()); EXPECT_EQ(cel::to_address(message_type_field), field_desc); StructTypeField struct_type_field = message_type_field; EXPECT_TRUE(struct_type_field.IsMessage()); EXPECT_THAT(struct_type_field.AsMessage(), Optional(An<MessageTypeField>())); EXPECT_THAT(static_cast<MessageTypeField>(struct_type_field), An<MessageTypeField>()); EXPECT_EQ(struct_type_field.name(), message_type_field.name()); EXPECT_EQ(struct_type_field.number(), message_type_field.number()); EXPECT_EQ(struct_type_field.GetType(), message_type_field.GetType()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/message_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/message_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
29996d35-ce48-4b53-83ed-d3e904ae45e0
cpp
google/cel-cpp
struct_type
common/types/struct_type.cc
common/types/struct_type_test.cc
#include <string> #include "absl/functional/overload.h" #include "absl/log/absl_check.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "common/type.h" #include "common/types/types.h" namespace cel { absl::string_view StructType::name() const { ABSL_DCHECK(*this); return absl::visit( absl::Overload([](absl::monostate) { return absl::string_view(); }, [](const common_internal::BasicStructType& alt) { return alt.name(); }, [](const MessageType& alt) { return alt.name(); }), variant_); } TypeParameters StructType::GetParameters() const { ABSL_DCHECK(*this); return absl::visit( absl::Overload( [](absl::monostate) { return TypeParameters(); }, [](const common_internal::BasicStructType& alt) { return alt.GetParameters(); }, [](const MessageType& alt) { return alt.GetParameters(); }), variant_); } std::string StructType::DebugString() const { return absl::visit( absl::Overload([](absl::monostate) { return std::string(); }, [](common_internal::BasicStructType alt) { return alt.DebugString(); }, [](MessageType alt) { return alt.DebugString(); }), variant_); } absl::optional<MessageType> StructType::AsMessage() const { if (const auto* alt = absl::get_if<MessageType>(&variant_); alt != nullptr) { return *alt; } return absl::nullopt; } MessageType StructType::GetMessage() const { ABSL_DCHECK(IsMessage()) << DebugString(); return absl::get<MessageType>(variant_); } common_internal::TypeVariant StructType::ToTypeVariant() const { return absl::visit( absl::Overload( [](absl::monostate) { return common_internal::TypeVariant(); }, [](common_internal::BasicStructType alt) { return static_cast<bool>(alt) ? common_internal::TypeVariant(alt) : common_internal::TypeVariant(); }, [](MessageType alt) { return static_cast<bool>(alt) ? common_internal::TypeVariant(alt) : common_internal::TypeVariant(); }), variant_); } }
#include "google/protobuf/descriptor.pb.h" #include "absl/base/nullability.h" #include "absl/hash/hash.h" #include "absl/log/absl_check.h" #include "absl/log/die_if_null.h" #include "common/type.h" #include "common/type_kind.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" namespace cel { namespace { using ::testing::Test; class StructTypeTest : public Test { public: void SetUp() override { { google::protobuf::FileDescriptorProto file_desc_proto; file_desc_proto.set_syntax("proto3"); file_desc_proto.set_package("test"); file_desc_proto.set_name("test/struct.proto"); file_desc_proto.add_message_type()->set_name("Struct"); ABSL_CHECK(pool_.BuildFile(file_desc_proto) != nullptr); } } absl::Nonnull<const google::protobuf::Descriptor*> GetDescriptor() const { return ABSL_DIE_IF_NULL(pool_.FindMessageTypeByName("test.Struct")); } MessageType GetMessageType() const { return MessageType(GetDescriptor()); } common_internal::BasicStructType GetBasicStructType() const { return common_internal::MakeBasicStructType("test.Struct"); } private: google::protobuf::DescriptorPool pool_; }; TEST(StructType, Kind) { EXPECT_EQ(StructType::kind(), TypeKind::kStruct); } TEST_F(StructTypeTest, Name) { EXPECT_EQ(StructType(GetMessageType()).name(), GetMessageType().name()); EXPECT_EQ(StructType(GetBasicStructType()).name(), GetBasicStructType().name()); } TEST_F(StructTypeTest, DebugString) { EXPECT_EQ(StructType(GetMessageType()).DebugString(), GetMessageType().DebugString()); EXPECT_EQ(StructType(GetBasicStructType()).DebugString(), GetBasicStructType().DebugString()); } TEST_F(StructTypeTest, Hash) { EXPECT_EQ(absl::HashOf(StructType(GetMessageType())), absl::HashOf(StructType(GetBasicStructType()))); } TEST_F(StructTypeTest, Equal) { EXPECT_EQ(StructType(GetMessageType()), StructType(GetBasicStructType())); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/struct_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/struct_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
96e128d6-eefa-45ae-800e-f8e8117dd875
cpp
google/cel-cpp
function_type
common/types/function_type.cc
common/types/function_type_test.cc
#include <cstddef> #include <cstring> #include <string> #include "absl/base/nullability.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/type.h" #include "google/protobuf/arena.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()); } } namespace common_internal { absl::Nonnull<FunctionTypeData*> FunctionTypeData::Create( absl::Nonnull<google::protobuf::Arena*> arena, const Type& result, absl::Span<const Type> args) { return ::new (arena->AllocateAligned( offsetof(FunctionTypeData, args) + ((1 + args.size()) * sizeof(Type)), alignof(FunctionTypeData))) FunctionTypeData(result, args); } FunctionTypeData::FunctionTypeData(const Type& result, absl::Span<const Type> args) : args_size(1 + args.size()) { this->args[0] = result; std::memcpy(this->args + 1, args.data(), args.size() * sizeof(Type)); } } FunctionType::FunctionType(absl::Nonnull<google::protobuf::Arena*> arena, const Type& result, absl::Span<const Type> args) : FunctionType( common_internal::FunctionTypeData::Create(arena, result, args)) {} std::string FunctionType::DebugString() const { return FunctionDebugString(result(), args()); } TypeParameters FunctionType::GetParameters() const { ABSL_DCHECK(*this); return TypeParameters(absl::MakeConstSpan(data_->args, data_->args_size)); } const Type& FunctionType::result() const { ABSL_DCHECK(*this); return data_->args[0]; } absl::Span<const Type> FunctionType::args() const { ABSL_DCHECK(*this); return absl::MakeConstSpan(data_->args + 1, data_->args_size - 1); } }
#include <sstream> #include "absl/hash/hash.h" #include "common/type.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel { namespace { TEST(FunctionType, Kind) { google::protobuf::Arena arena; EXPECT_EQ(FunctionType(&arena, DynType{}, {BytesType()}).kind(), FunctionType::kKind); EXPECT_EQ(Type(FunctionType(&arena, DynType{}, {BytesType()})).kind(), FunctionType::kKind); } TEST(FunctionType, Name) { google::protobuf::Arena arena; EXPECT_EQ(FunctionType(&arena, DynType{}, {BytesType()}).name(), "function"); EXPECT_EQ(Type(FunctionType(&arena, DynType{}, {BytesType()})).name(), "function"); } TEST(FunctionType, DebugString) { google::protobuf::Arena arena; { std::ostringstream out; out << FunctionType(&arena, DynType{}, {BytesType()}); EXPECT_EQ(out.str(), "(bytes) -> dyn"); } { std::ostringstream out; out << Type(FunctionType(&arena, DynType{}, {BytesType()})); EXPECT_EQ(out.str(), "(bytes) -> dyn"); } } TEST(FunctionType, Hash) { google::protobuf::Arena arena; EXPECT_EQ(absl::HashOf(FunctionType(&arena, DynType{}, {BytesType()})), absl::HashOf(FunctionType(&arena, DynType{}, {BytesType()}))); } TEST(FunctionType, Equal) { google::protobuf::Arena arena; EXPECT_EQ(FunctionType(&arena, DynType{}, {BytesType()}), FunctionType(&arena, DynType{}, {BytesType()})); EXPECT_EQ(Type(FunctionType(&arena, DynType{}, {BytesType()})), FunctionType(&arena, DynType{}, {BytesType()})); EXPECT_EQ(FunctionType(&arena, DynType{}, {BytesType()}), Type(FunctionType(&arena, DynType{}, {BytesType()}))); EXPECT_EQ(Type(FunctionType(&arena, DynType{}, {BytesType()})), Type(FunctionType(&arena, DynType{}, {BytesType()}))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/function_type.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/function_type_test.cc
4552db5798fb0853b131b783d8875794334fae7f
8605120a-7d6a-41a7-8cb7-70a7ce52e7d8
cpp
google/cel-cpp
type_pool
common/types/type_pool.cc
common/types/type_pool_test.cc
#include "common/types/type_pool.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "common/type.h" namespace cel::common_internal { StructType TypePool::MakeStructType(absl::string_view name) { ABSL_DCHECK(!IsWellKnownMessageType(name)) << name; if (ABSL_PREDICT_FALSE(name.empty())) { return StructType(); } if (const auto* descriptor = descriptors_->FindMessageTypeByName(name); descriptor != nullptr) { return MessageType(descriptor); } return MakeBasicStructType(InternString(name)); } FunctionType TypePool::MakeFunctionType(const Type& result, absl::Span<const Type> args) { absl::MutexLock lock(&functions_mutex_); return functions_.InternFunctionType(result, args); } ListType TypePool::MakeListType(const Type& element) { if (element.IsDyn()) { return ListType(); } absl::MutexLock lock(&lists_mutex_); return lists_.InternListType(element); } MapType TypePool::MakeMapType(const Type& key, const Type& value) { if (key.IsDyn() && value.IsDyn()) { return MapType(); } if (key.IsString() && value.IsDyn()) { return JsonMapType(); } absl::MutexLock lock(&maps_mutex_); return maps_.InternMapType(key, value); } OpaqueType TypePool::MakeOpaqueType(absl::string_view name, absl::Span<const Type> parameters) { if (name == OptionalType::kName) { if (parameters.size() == 1 && parameters.front().IsDyn()) { return OptionalType(); } name = OptionalType::kName; } else { name = InternString(name); } absl::MutexLock lock(&opaques_mutex_); return opaques_.InternOpaqueType(name, parameters); } OptionalType TypePool::MakeOptionalType(const Type& parameter) { return MakeOpaqueType(OptionalType::kName, absl::MakeConstSpan(&parameter, 1)) .GetOptional(); } TypeParamType TypePool::MakeTypeParamType(absl::string_view name) { return TypeParamType(InternString(name)); } TypeType TypePool::MakeTypeType(const Type& type) { absl::MutexLock lock(&types_mutex_); return types_.InternTypeType(type); } absl::string_view TypePool::InternString(absl::string_view string) { absl::MutexLock lock(&strings_mutex_); return strings_.InternString(string); } }
#include "common/types/type_pool.h" #include "common/type.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "google/protobuf/arena.h" namespace cel::common_internal { namespace { using ::cel::internal::GetTestingDescriptorPool; using ::testing::_; TEST(TypePool, MakeStructType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeStructType("foo.Bar"), MakeBasicStructType("foo.Bar")); EXPECT_TRUE( type_pool.MakeStructType("google.api.expr.test.v1.proto3.TestAllTypes") .IsMessage()); EXPECT_DEBUG_DEATH( static_cast<void>(type_pool.MakeStructType("google.protobuf.BoolValue")), _); } TEST(TypePool, MakeFunctionType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeFunctionType(BoolType(), {IntType(), IntType()}), FunctionType(&arena, BoolType(), {IntType(), IntType()})); } TEST(TypePool, MakeListType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeListType(DynType()), ListType()); EXPECT_EQ(type_pool.MakeListType(DynType()), JsonListType()); EXPECT_EQ(type_pool.MakeListType(StringType()), ListType(&arena, StringType())); } TEST(TypePool, MakeMapType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeMapType(DynType(), DynType()), MapType()); EXPECT_EQ(type_pool.MakeMapType(StringType(), DynType()), JsonMapType()); EXPECT_EQ(type_pool.MakeMapType(StringType(), StringType()), MapType(&arena, StringType(), StringType())); } TEST(TypePool, MakeOpaqueType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeOpaqueType("custom_type", {DynType(), DynType()}), OpaqueType(&arena, "custom_type", {DynType(), DynType()})); } TEST(TypePool, MakeOptionalType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeOptionalType(DynType()), OptionalType()); EXPECT_EQ(type_pool.MakeOptionalType(StringType()), OptionalType(&arena, StringType())); } TEST(TypePool, MakeTypeParamType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeTypeParamType("T"), TypeParamType("T")); } TEST(TypePool, MakeTypeType) { google::protobuf::Arena arena; TypePool type_pool(GetTestingDescriptorPool(), &arena); EXPECT_EQ(type_pool.MakeTypeType(BoolType()), TypeType(&arena, BoolType())); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/type_pool.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/type_pool_test.cc
4552db5798fb0853b131b783d8875794334fae7f
847a8838-d796-4ef7-b972-f55b4b1524ad
cpp
google/cel-cpp
parsed_json_value
common/values/parsed_json_value.cc
common/values/parsed_json_value_test.cc
#include "common/values/parsed_json_value.h" #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/functional/overload.h" #include "absl/status/status.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/allocator.h" #include "common/memory.h" #include "common/value.h" #include "internal/well_known_types.h" #include "google/protobuf/message.h" namespace cel::common_internal { namespace { using ::cel::well_known_types::AsVariant; using ::cel::well_known_types::GetValueReflectionOrDie; } Value ParsedJsonValue(Allocator<> allocator, Borrowed<const google::protobuf::Message> message) { const auto reflection = GetValueReflectionOrDie(message->GetDescriptor()); const auto kind_case = reflection.GetKindCase(*message); switch (kind_case) { case google::protobuf::Value::KIND_NOT_SET: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Value::kNullValue: return NullValue(); case google::protobuf::Value::kBoolValue: return BoolValue(reflection.GetBoolValue(*message)); case google::protobuf::Value::kNumberValue: return DoubleValue(reflection.GetNumberValue(*message)); case google::protobuf::Value::kStringValue: { std::string scratch; return absl::visit( absl::Overload( [&](absl::string_view string) -> StringValue { if (string.empty()) { return StringValue(); } if (string.data() == scratch.data() && string.size() == scratch.size()) { return StringValue(allocator, std::move(scratch)); } else { return StringValue(message, string); } }, [&](absl::Cord&& cord) -> StringValue { if (cord.empty()) { return StringValue(); } return StringValue(std::move(cord)); }), AsVariant(reflection.GetStringValue(*message, scratch))); } case google::protobuf::Value::kListValue: return ParsedJsonListValue(Owned<const google::protobuf::Message>( Owner(message), &reflection.GetListValue(*message))); case google::protobuf::Value::kStructValue: return ParsedJsonMapValue(Owned<const google::protobuf::Message>( Owner(message), &reflection.GetStructValue(*message))); default: return ErrorValue(absl::InvalidArgumentError( absl::StrCat("unexpected value kind case: ", kind_case))); } } }
#include "common/values/parsed_json_value.h" #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/memory.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_manager.h" #include "common/value_testing.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel::common_internal { namespace { using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::cel::test::BoolValueIs; using ::cel::test::DoubleValueIs; using ::cel::test::IsNullValue; using ::cel::test::ListValueElements; using ::cel::test::ListValueIs; using ::cel::test::MapValueElements; using ::cel::test::MapValueIs; using ::cel::test::StringValueIs; using ::testing::ElementsAre; using ::testing::Pair; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using ::testing::UnorderedElementsAre; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ParsedJsonValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); value_manager_ = NewThreadCompatibleValueManager( MemoryManager::Pooling(arena()), NewThreadCompatibleTypeReflector(MemoryManager::Pooling(arena()))); break; case AllocatorKind::kNewDelete: value_manager_ = NewThreadCompatibleValueManager( MemoryManager::ReferenceCounting(), NewThreadCompatibleTypeReflector( MemoryManager::ReferenceCounting())); break; } } void TearDown() override { value_manager_.reset(); arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } ValueManager& value_manager() { return **value_manager_; } template <typename T> auto GeneratedParseTextProto(absl::string_view text) { return ::cel::internal::GeneratedParseTextProto<T>( allocator(), text, descriptor_pool(), message_factory()); } template <typename T> auto DynamicParseTextProto(absl::string_view text) { return ::cel::internal::DynamicParseTextProto<T>( allocator(), text, descriptor_pool(), message_factory()); } private: absl::optional<google::protobuf::Arena> arena_; absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ParsedJsonValueTest, Null_Dynamic) { EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(null_value: NULL_VALUE)pb")), IsNullValue()); EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(null_value: NULL_VALUE)pb")), IsNullValue()); } TEST_P(ParsedJsonValueTest, Bool_Dynamic) { EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(bool_value: true)pb")), BoolValueIs(true)); } TEST_P(ParsedJsonValueTest, Double_Dynamic) { EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(number_value: 1.0)pb")), DoubleValueIs(1.0)); } TEST_P(ParsedJsonValueTest, String_Dynamic) { EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(string_value: "foo")pb")), StringValueIs("foo")); } TEST_P(ParsedJsonValueTest, List_Dynamic) { EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(list_value: { values {} values { bool_value: true } })pb")), ListValueIs(ListValueElements( &value_manager(), ElementsAre(IsNullValue(), BoolValueIs(true))))); } TEST_P(ParsedJsonValueTest, Map_Dynamic) { EXPECT_THAT( ParsedJsonValue(arena(), DynamicParseTextProto<google::protobuf::Value>( R"pb(struct_value: { fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } } })pb")), MapValueIs(MapValueElements( &value_manager(), UnorderedElementsAre( Pair(StringValueIs("foo"), IsNullValue()), Pair(StringValueIs("bar"), BoolValueIs(true)))))); } INSTANTIATE_TEST_SUITE_P(ParsedJsonValueTest, ParsedJsonValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_json_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_json_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
7b33fe13-c650-4a7d-9230-9d844a52e739
cpp
google/cel-cpp
string_value
common/values/string_value.cc
common/values/string_value_test.cc
#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::Status StringValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return NativeValue([&value](const auto& bytes) -> absl::Status { return internal::SerializeStringValue(bytes, value); }); } absl::StatusOr<Json> StringValue::ConvertToJson(AnyToJsonConverter&) const { return NativeCord(); } absl::Status StringValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<StringValue>(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 = BoolValue{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(const StringValue& 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(const StringValue& 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/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/string_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/string_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
0b8a4b1c-0153-4d36-9ce3-49d6b157c049
cpp
google/cel-cpp
bool_value
common/values/bool_value.cc
common/values/bool_value_test.cc
#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 { namespace { std::string BoolDebugString(bool value) { return value ? "true" : "false"; } } std::string BoolValue::DebugString() const { return BoolDebugString(NativeValue()); } absl::StatusOr<Json> BoolValue::ConvertToJson(AnyToJsonConverter&) const { return NativeValue(); } absl::Status BoolValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeBoolValue(NativeValue(), value); } absl::Status BoolValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<BoolValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValue{false}; return absl::OkStatus(); } absl::StatusOr<Value> BoolValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/bool_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/bool_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
56270ad0-5a98-4e37-aeac-328c5d28bdf9
cpp
google/cel-cpp
double_value
common/values/double_value.cc
common/values/double_value_test.cc
#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 { 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 DoubleValue::DebugString() const { return DoubleDebugString(NativeValue()); } absl::Status DoubleValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeDoubleValue(NativeValue(), value); } absl::StatusOr<Json> DoubleValue::ConvertToJson(AnyToJsonConverter&) const { return NativeValue(); } absl::Status DoubleValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<DoubleValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } if (auto other_value = As<IntValue>(other); other_value.has_value()) { result = BoolValue{internal::Number::FromDouble(NativeValue()) == internal::Number::FromInt64(other_value->NativeValue())}; return absl::OkStatus(); } if (auto other_value = As<UintValue>(other); other_value.has_value()) { result = BoolValue{internal::Number::FromDouble(NativeValue()) == internal::Number::FromUint64(other_value->NativeValue())}; return absl::OkStatus(); } result = BoolValue{false}; return absl::OkStatus(); } absl::StatusOr<Value> DoubleValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/double_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/double_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
3b0b5c9a-b9f3-4305-a773-0ced3e5c0dfb
cpp
google/cel-cpp
struct_value
common/values/struct_value.cc
common/values/struct_value_test.cc
#include <cstddef> #include <string> #include <utility> #include "absl/container/flat_hash_map.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/types/optional.h" #include "absl/types/variant.h" #include "common/casting.h" #include "common/optional_ref.h" #include "common/type.h" #include "common/value.h" #include "internal/status_macros.h" namespace cel { StructType StructValue::GetRuntimeType() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> StructType { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { ABSL_UNREACHABLE(); } else { return alternative.GetRuntimeType(); } }, variant_); } absl::string_view StructValue::GetTypeName() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> absl::string_view { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return absl::string_view{}; } else { return alternative.GetTypeName(); } }, variant_); } std::string StructValue::DebugString() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> std::string { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return std::string{}; } else { return alternative.DebugString(); } }, variant_); } absl::Status StructValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { AssertIsValid(); return absl::visit( [&converter, &value](const auto& alternative) -> absl::Status { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.SerializeTo(converter, value); } }, variant_); } absl::StatusOr<Json> StructValue::ConvertToJson( AnyToJsonConverter& converter) const { AssertIsValid(); return absl::visit( [&converter](const auto& alternative) -> absl::StatusOr<Json> { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.ConvertToJson(converter); } }, variant_); } bool StructValue::IsZeroValue() const { AssertIsValid(); return absl::visit( [](const auto& alternative) -> bool { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return false; } else { return alternative.IsZeroValue(); } }, variant_); } absl::StatusOr<bool> StructValue::HasFieldByName(absl::string_view name) const { AssertIsValid(); return absl::visit( [name](const auto& alternative) -> absl::StatusOr<bool> { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.HasFieldByName(name); } }, variant_); } absl::StatusOr<bool> StructValue::HasFieldByNumber(int64_t number) const { AssertIsValid(); return absl::visit( [number](const auto& alternative) -> absl::StatusOr<bool> { if constexpr (std::is_same_v< absl::monostate, absl::remove_cvref_t<decltype(alternative)>>) { return absl::InternalError("use of invalid StructValue"); } else { return alternative.HasFieldByNumber(number); } }, variant_); } namespace common_internal { absl::Status StructValueEqual(ValueManager& value_manager, const StructValue& lhs, const StructValue& rhs, Value& result) { if (lhs.GetTypeName() != rhs.GetTypeName()) { result = BoolValue{false}; return absl::OkStatus(); } absl::flat_hash_map<std::string, Value> lhs_fields; CEL_RETURN_IF_ERROR(lhs.ForEachField( value_manager, [&lhs_fields](absl::string_view name, const Value& lhs_value) -> absl::StatusOr<bool> { lhs_fields.insert_or_assign(std::string(name), Value(lhs_value)); return true; })); bool equal = true; size_t rhs_fields_count = 0; CEL_RETURN_IF_ERROR(rhs.ForEachField( value_manager, [&value_manager, &result, &lhs_fields, &equal, &rhs_fields_count]( absl::string_view name, const Value& rhs_value) -> absl::StatusOr<bool> { auto lhs_field = lhs_fields.find(name); if (lhs_field == lhs_fields.end()) { equal = false; return false; } CEL_RETURN_IF_ERROR( lhs_field->second.Equal(value_manager, rhs_value, result)); if (auto bool_value = As<BoolValue>(result); bool_value.has_value() && !bool_value->NativeValue()) { equal = false; return false; } ++rhs_fields_count; return true; })); if (!equal || rhs_fields_count != lhs_fields.size()) { result = BoolValue{false}; return absl::OkStatus(); } result = BoolValue{true}; return absl::OkStatus(); } absl::Status StructValueEqual(ValueManager& value_manager, const ParsedStructValueInterface& lhs, const StructValue& rhs, Value& result) { if (lhs.GetTypeName() != rhs.GetTypeName()) { result = BoolValue{false}; return absl::OkStatus(); } absl::flat_hash_map<std::string, Value> lhs_fields; CEL_RETURN_IF_ERROR(lhs.ForEachField( value_manager, [&lhs_fields](absl::string_view name, const Value& lhs_value) -> absl::StatusOr<bool> { lhs_fields.insert_or_assign(std::string(name), Value(lhs_value)); return true; })); bool equal = true; size_t rhs_fields_count = 0; CEL_RETURN_IF_ERROR(rhs.ForEachField( value_manager, [&value_manager, &result, &lhs_fields, &equal, &rhs_fields_count]( absl::string_view name, const Value& rhs_value) -> absl::StatusOr<bool> { auto lhs_field = lhs_fields.find(name); if (lhs_field == lhs_fields.end()) { equal = false; return false; } CEL_RETURN_IF_ERROR( lhs_field->second.Equal(value_manager, rhs_value, result)); if (auto bool_value = As<BoolValue>(result); bool_value.has_value() && !bool_value->NativeValue()) { equal = false; return false; } ++rhs_fields_count; return true; })); if (!equal || rhs_fields_count != lhs_fields.size()) { result = BoolValue{false}; return absl::OkStatus(); } result = BoolValue{true}; return absl::OkStatus(); } } absl::optional<MessageValue> StructValue::AsMessage() & { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<MessageValue> StructValue::AsMessage() const& { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<MessageValue> StructValue::AsMessage() && { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<MessageValue> StructValue::AsMessage() const&& { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } optional_ref<const ParsedMessageValue> StructValue::AsParsedMessage() & { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } optional_ref<const ParsedMessageValue> StructValue::AsParsedMessage() const& { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedMessageValue> StructValue::AsParsedMessage() && { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } absl::optional<ParsedMessageValue> StructValue::AsParsedMessage() const&& { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } StructValue::operator MessageValue() & { ABSL_DCHECK(IsMessage()) << *this; return absl::get<ParsedMessageValue>(variant_); } StructValue::operator MessageValue() const& { ABSL_DCHECK(IsMessage()) << *this; return absl::get<ParsedMessageValue>(variant_); } StructValue::operator MessageValue() && { ABSL_DCHECK(IsMessage()) << *this; return absl::get<ParsedMessageValue>(std::move(variant_)); } StructValue::operator MessageValue() const&& { ABSL_DCHECK(IsMessage()) << *this; return absl::get<ParsedMessageValue>(std::move(variant_)); } StructValue::operator const ParsedMessageValue&() & { ABSL_DCHECK(IsParsedMessage()) << *this; return absl::get<ParsedMessageValue>(variant_); } StructValue::operator const ParsedMessageValue&() const& { ABSL_DCHECK(IsParsedMessage()) << *this; return absl::get<ParsedMessageValue>(variant_); } StructValue::operator ParsedMessageValue() && { ABSL_DCHECK(IsParsedMessage()) << *this; return absl::get<ParsedMessageValue>(std::move(variant_)); } StructValue::operator ParsedMessageValue() const&& { ABSL_DCHECK(IsParsedMessage()) << *this; return absl::get<ParsedMessageValue>(std::move(variant_)); } common_internal::ValueVariant StructValue::ToValueVariant() const& { return absl::visit( [](const auto& alternative) -> common_internal::ValueVariant { return alternative; }, variant_); } common_internal::ValueVariant StructValue::ToValueVariant() && { return absl::visit( [](auto&& alternative) -> common_internal::ValueVariant { return std::move(alternative); }, std::move(variant_)); } }
#include "absl/base/attributes.h" #include "common/value.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.h" #include "proto/test/v1/proto3/test_all_types.pb.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::cel::internal::DynamicParseTextProto; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::An; using ::testing::Optional; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; TEST(StructValue, Is) { EXPECT_TRUE(StructValue(ParsedMessageValue()).Is<MessageValue>()); EXPECT_TRUE(StructValue(ParsedMessageValue()).Is<ParsedMessageValue>()); } template <typename T> constexpr T& AsLValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return t; } template <typename T> constexpr const T& AsConstLValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return t; } template <typename T> constexpr T&& AsRValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return static_cast<T&&>(t); } template <typename T> constexpr const T&& AsConstRValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return static_cast<const T&&>(t); } TEST(StructValue, As) { google::protobuf::Arena arena; { StructValue value( ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); StructValue other_value = value; EXPECT_THAT(AsLValueRef<StructValue>(value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT(AsConstLValueRef<StructValue>(value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT(AsRValueRef<StructValue>(value).As<MessageValue>(), Optional(An<MessageValue>())); EXPECT_THAT(AsConstRValueRef<StructValue>(other_value).As<MessageValue>(), Optional(An<MessageValue>())); } { StructValue value( ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); StructValue other_value = value; EXPECT_THAT(AsLValueRef<StructValue>(value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT(AsConstLValueRef<StructValue>(value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT(AsRValueRef<StructValue>(value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT( AsConstRValueRef<StructValue>(other_value).As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); } } TEST(StructValue, Cast) { google::protobuf::Arena arena; { StructValue value( ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); StructValue other_value = value; EXPECT_THAT(static_cast<MessageValue>(AsLValueRef<StructValue>(value)), An<MessageValue>()); EXPECT_THAT(static_cast<MessageValue>(AsConstLValueRef<StructValue>(value)), An<MessageValue>()); EXPECT_THAT(static_cast<MessageValue>(AsRValueRef<StructValue>(value)), An<MessageValue>()); EXPECT_THAT( static_cast<MessageValue>(AsConstRValueRef<StructValue>(other_value)), An<MessageValue>()); } { StructValue value( ParsedMessageValue{DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb()pb", GetTestingDescriptorPool(), GetTestingMessageFactory())}); StructValue other_value = value; EXPECT_THAT( static_cast<ParsedMessageValue>(AsLValueRef<StructValue>(value)), An<ParsedMessageValue>()); EXPECT_THAT( static_cast<ParsedMessageValue>(AsConstLValueRef<StructValue>(value)), An<ParsedMessageValue>()); EXPECT_THAT( static_cast<ParsedMessageValue>(AsRValueRef<StructValue>(value)), An<ParsedMessageValue>()); EXPECT_THAT(static_cast<ParsedMessageValue>( AsConstRValueRef<StructValue>(other_value)), An<ParsedMessageValue>()); } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/struct_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/struct_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
142e80f4-e36b-41d7-9010-10ab919d054d
cpp
google/cel-cpp
map_value
common/values/map_value.cc
common/values/map_value_test.cc
#include <cstddef> #include <utility> #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/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), "'")); } } 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::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<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_); } namespace common_internal { absl::Status MapValueEqual(ValueManager& value_manager, const MapValue& lhs, const MapValue& rhs, Value& result) { if (Is(lhs, rhs)) { result = BoolValue{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 = BoolValue{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 = BoolValue{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 = BoolValue{true}; return absl::OkStatus(); } absl::Status MapValueEqual(ValueManager& value_manager, const ParsedMapValueInterface& lhs, const MapValue& rhs, Value& result) { auto lhs_size = lhs.Size(); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { result = BoolValue{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 = BoolValue{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 = BoolValue{true}; return absl::OkStatus(); } } absl::Status CheckMapKey(const Value& 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()); } } common_internal::ValueVariant MapValue::ToValueVariant() const& { return absl::visit( [](const auto& alternative) -> common_internal::ValueVariant { return alternative; }, variant_); } common_internal::ValueVariant MapValue::ToValueVariant() && { return absl::visit( [](auto&& alternative) -> common_internal::ValueVariant { return std::move(alternative); }, std::move(variant_)); } }
#include <cstdint> #include <memory> #include <sstream> #include <tuple> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.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 ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::TestParamInfo; using ::testing::UnorderedElementsAreArray; TEST(MapValue, CheckKey) { EXPECT_THAT(CheckMapKey(BoolValue()), IsOk()); EXPECT_THAT(CheckMapKey(IntValue()), IsOk()); EXPECT_THAT(CheckMapKey(UintValue()), IsOk()); EXPECT_THAT(CheckMapKey(StringValue()), IsOk()); EXPECT_THAT(CheckMapKey(BytesValue()), 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(MapType())); (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(JsonMapType())); (static_cast<void>(builder->Put(std::forward<Args>(args).first, std::forward<Args>(args).second)), ...); return std::move(*builder).Build(); } }; 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(), "{}"); 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(), "[]"); 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, 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(), IntValue(0))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 3.0); ASSERT_OK_AND_ASSIGN(value, map_value.Get(value_manager(), IntValue(1))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 4.0); ASSERT_OK_AND_ASSIGN(value, map_value.Get(value_manager(), IntValue(2))); ASSERT_TRUE(InstanceOf<DoubleValue>(value)); ASSERT_EQ(Cast<DoubleValue>(value).NativeValue(), 5.0); EXPECT_THAT(map_value.Get(value_manager(), IntValue(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(), IntValue(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(), IntValue(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(), IntValue(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(), IntValue(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(), IntValue(0))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN(value, map_value.Has(value_manager(), IntValue(1))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN(value, map_value.Has(value_manager(), IntValue(2))); ASSERT_TRUE(InstanceOf<BoolValue>(value)); ASSERT_TRUE(Cast<BoolValue>(value).NativeValue()); ASSERT_OK_AND_ASSIGN(value, map_value.Has(value_manager(), IntValue(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](const Value& element) -> bool { keys.push_back(Cast<IntValue>(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](const Value& key, const Value& value) { entries.push_back(std::pair{Cast<IntValue>(key).NativeValue(), Cast<DoubleValue>(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, 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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/map_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/map_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
de101ed3-e456-4c60-85ce-bf326ecce6b6
cpp
google/cel-cpp
parsed_repeated_field_value
common/values/parsed_repeated_field_value.cc
common/values/parsed_repeated_field_value_test.cc
#include "common/values/parsed_repeated_field_value.h" #include <cstddef> #include <memory> #include <string> #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "common/json.h" #include "common/value.h" #include "internal/status_macros.h" #include "google/protobuf/message.h" namespace cel { std::string ParsedRepeatedFieldValue::DebugString() const { if (ABSL_PREDICT_FALSE(field_ == nullptr)) { return "INVALID"; } return "VALID"; } absl::Status ParsedRepeatedFieldValue::SerializeTo( AnyToJsonConverter& converter, absl::Cord& value) const { return absl::UnimplementedError("SerializeTo is not yet implemented"); } absl::StatusOr<Json> ParsedRepeatedFieldValue::ConvertToJson( AnyToJsonConverter& converter) const { return absl::UnimplementedError("ConvertToJson is not yet implemented"); } absl::StatusOr<JsonArray> ParsedRepeatedFieldValue::ConvertToJsonArray( AnyToJsonConverter& converter) const { return absl::UnimplementedError("ConvertToJsonArray is not yet implemented"); } absl::Status ParsedRepeatedFieldValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { return absl::UnimplementedError("Equal is not yet implemented"); } absl::StatusOr<Value> ParsedRepeatedFieldValue::Equal( ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } bool ParsedRepeatedFieldValue::IsZeroValue() const { return IsEmpty(); } bool ParsedRepeatedFieldValue::IsEmpty() const { return Size() == 0; } size_t ParsedRepeatedFieldValue::Size() const { ABSL_DCHECK(*this); if (ABSL_PREDICT_FALSE(field_ == nullptr)) { return 0; } return static_cast<size_t>( GetReflectionOrDie()->FieldSize(*message_, field_)); } absl::Status ParsedRepeatedFieldValue::Get(ValueManager& value_manager, size_t index, Value& result) const { return absl::UnimplementedError("Get is not yet implemented"); } absl::StatusOr<Value> ParsedRepeatedFieldValue::Get(ValueManager& value_manager, size_t index) const { Value result; CEL_RETURN_IF_ERROR(Get(value_manager, index, result)); return result; } absl::Status ParsedRepeatedFieldValue::ForEach(ValueManager& value_manager, ForEachCallback callback) const { return absl::UnimplementedError("ForEach is not yet implemented"); } absl::Status ParsedRepeatedFieldValue::ForEach( ValueManager& value_manager, ForEachWithIndexCallback callback) const { return absl::UnimplementedError("ForEach is not yet implemented"); } absl::StatusOr<absl::Nonnull<std::unique_ptr<ValueIterator>>> ParsedRepeatedFieldValue::NewIterator(ValueManager& value_manager) const { return absl::UnimplementedError("NewIterator is not yet implemented"); } absl::Status ParsedRepeatedFieldValue::Contains(ValueManager& value_manager, const Value& other, Value& result) const { return absl::UnimplementedError("Contains is not yet implemented"); } absl::StatusOr<Value> ParsedRepeatedFieldValue::Contains( ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Contains(value_manager, other, result)); return result; } absl::Nonnull<const google::protobuf::Reflection*> ParsedRepeatedFieldValue::GetReflectionOrDie() const { return ABSL_DIE_IF_NULL(message_->GetReflection()); } }
#include <cstddef> #include "absl/base/nullability.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_manager.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel { namespace { using ::absl_testing::StatusIs; using ::cel::internal::DynamicParseTextProto; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::_; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ParsedRepeatedFieldValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); value_manager_ = NewThreadCompatibleValueManager( MemoryManager::Pooling(arena()), NewThreadCompatibleTypeReflector(MemoryManager::Pooling(arena()))); break; case AllocatorKind::kNewDelete: value_manager_ = NewThreadCompatibleValueManager( MemoryManager::ReferenceCounting(), NewThreadCompatibleTypeReflector( MemoryManager::ReferenceCounting())); break; } } void TearDown() override { value_manager_.reset(); arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } ValueManager& value_manager() { return **value_manager_; } private: absl::optional<google::protobuf::Arena> arena_; absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ParsedRepeatedFieldValueTest, Default) { ParsedRepeatedFieldValue value; EXPECT_FALSE(value); } TEST_P(ParsedRepeatedFieldValueTest, Field) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_TRUE(value); } TEST_P(ParsedRepeatedFieldValueTest, Kind) { ParsedRepeatedFieldValue value; EXPECT_EQ(value.kind(), ParsedRepeatedFieldValue::kKind); EXPECT_EQ(value.kind(), ValueKind::kList); } TEST_P(ParsedRepeatedFieldValueTest, GetTypeName) { ParsedRepeatedFieldValue value; EXPECT_EQ(value.GetTypeName(), ParsedRepeatedFieldValue::kName); EXPECT_EQ(value.GetTypeName(), "list"); } TEST_P(ParsedRepeatedFieldValueTest, GetRuntimeType) { ParsedRepeatedFieldValue value; EXPECT_EQ(value.GetRuntimeType(), ListType()); } TEST_P(ParsedRepeatedFieldValueTest, DebugString) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.DebugString(), _); } TEST_P(ParsedRepeatedFieldValueTest, IsZeroValue) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_TRUE(valid_value.IsZeroValue()); } TEST_P(ParsedRepeatedFieldValueTest, SerializeTo) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); absl::Cord serialized; EXPECT_THAT(valid_value.SerializeTo(value_manager(), serialized), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedRepeatedFieldValueTest, ConvertToJson) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedRepeatedFieldValueTest, Equal) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.Equal(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedRepeatedFieldValueTest, Empty) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_TRUE(valid_value.IsEmpty()); } TEST_P(ParsedRepeatedFieldValueTest, Size) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_EQ(valid_value.Size(), 0); } TEST_P(ParsedRepeatedFieldValueTest, Get) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.Get(value_manager(), 0), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedRepeatedFieldValueTest, ForEach) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.ForEach( value_manager(), [](const Value&) -> absl::StatusOr<bool> { return true; }), StatusIs(absl::StatusCode::kUnimplemented)); EXPECT_THAT( valid_value.ForEach( value_manager(), [](size_t, const Value&) -> absl::StatusOr<bool> { return true; }), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedRepeatedFieldValueTest, NewIterator) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.NewIterator(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedRepeatedFieldValueTest, Contains) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedRepeatedFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "repeated_int64"))); EXPECT_THAT(valid_value.Contains(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } INSTANTIATE_TEST_SUITE_P(ParsedRepeatedFieldValueTest, ParsedRepeatedFieldValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_repeated_field_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_repeated_field_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
2b3d12ac-68d3-49d6-91a9-b5472a2b113e
cpp
google/cel-cpp
duration_value
common/values/duration_value.cc
common/values/duration_value_test.cc
#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 { namespace { std::string DurationDebugString(absl::Duration value) { return internal::DebugStringDuration(value); } } std::string DurationValue::DebugString() const { return DurationDebugString(NativeValue()); } absl::Status DurationValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeDuration(NativeValue(), value); } absl::StatusOr<Json> DurationValue::ConvertToJson(AnyToJsonConverter&) const { CEL_ASSIGN_OR_RETURN(auto json, internal::EncodeDurationToJson(NativeValue())); return JsonString(std::move(json)); } absl::Status DurationValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<DurationValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValue{false}; return absl::OkStatus(); } absl::StatusOr<Value> DurationValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/duration_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/duration_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e4045a8e-3e5b-4bed-9a33-db22c266c48c
cpp
google/cel-cpp
unknown_value
common/values/unknown_value.cc
common/values/unknown_value_test.cc
#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/json.h" #include "common/value.h" namespace cel { absl::Status UnknownValue::SerializeTo(AnyToJsonConverter&, absl::Cord&) 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&, const Value&, Value& result) const { result = BoolValue{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/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::StatusIs; using ::testing::An; using ::testing::Ne; 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, SerializeTo) { absl::Cord value; EXPECT_THAT(UnknownValue().SerializeTo(value_manager(), value), 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>(Value(UnknownValue())), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( UnknownValueTest, UnknownValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), UnknownValueTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/unknown_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/unknown_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
92a675e2-12a2-4cc7-94b8-6b41dd74b6c4
cpp
google/cel-cpp
uint_value
common/values/uint_value.cc
common/values/uint_value_test.cc
#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 { namespace { std::string UintDebugString(int64_t value) { return absl::StrCat(value, "u"); } } std::string UintValue::DebugString() const { return UintDebugString(NativeValue()); } absl::Status UintValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeUInt64Value(NativeValue(), value); } absl::StatusOr<Json> UintValue::ConvertToJson(AnyToJsonConverter&) const { return JsonUint(NativeValue()); } absl::Status UintValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<UintValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } if (auto other_value = As<DoubleValue>(other); other_value.has_value()) { result = BoolValue{internal::Number::FromUint64(NativeValue()) == internal::Number::FromDouble(other_value->NativeValue())}; return absl::OkStatus(); } if (auto other_value = As<IntValue>(other); other_value.has_value()) { result = BoolValue{internal::Number::FromUint64(NativeValue()) == internal::Number::FromInt64(other_value->NativeValue())}; return absl::OkStatus(); } result = BoolValue{false}; return absl::OkStatus(); } absl::StatusOr<Value> UintValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/uint_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/uint_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
1b9b18b5-5623-4596-a97b-1e51ff9ed9ac
cpp
google/cel-cpp
parsed_message_value
common/values/parsed_message_value.cc
common/values/parsed_message_value_test.cc
#include "common/values/parsed_message_value.h" #include <cstdint> #include <string> #include <utility> #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 "absl/types/span.h" #include "base/attribute.h" #include "common/json.h" #include "common/value.h" #include "internal/status_macros.h" #include "runtime/runtime_options.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel { bool ParsedMessageValue::IsZeroValue() const { ABSL_DCHECK(*this); return ABSL_PREDICT_TRUE(value_ != nullptr) ? value_->ByteSizeLong() == 0 : true; } std::string ParsedMessageValue::DebugString() const { if (ABSL_PREDICT_FALSE(value_ == nullptr)) { return "INVALID"; } return absl::StrCat(*value_); } absl::Status ParsedMessageValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::UnimplementedError("SerializeTo is not yet implemented"); } absl::StatusOr<Json> ParsedMessageValue::ConvertToJson( AnyToJsonConverter& converter) const { return absl::UnimplementedError("ConvertToJson is not yet implemented"); } absl::Status ParsedMessageValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { return absl::UnimplementedError("Equal is not yet implemented"); } absl::StatusOr<Value> ParsedMessageValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } absl::Status ParsedMessageValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options) const { return absl::UnimplementedError("GetFieldByName is not yet implemented"); } absl::StatusOr<Value> ParsedMessageValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, ProtoWrapperTypeOptions unboxing_options) const { Value result; CEL_RETURN_IF_ERROR( GetFieldByName(value_manager, name, result, unboxing_options)); return result; } absl::Status ParsedMessageValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options) const { return absl::UnimplementedError("GetFieldByNumber is not yet implemented"); } absl::StatusOr<Value> ParsedMessageValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, ProtoWrapperTypeOptions unboxing_options) const { Value result; CEL_RETURN_IF_ERROR( GetFieldByNumber(value_manager, number, result, unboxing_options)); return result; } absl::StatusOr<bool> ParsedMessageValue::HasFieldByName( absl::string_view name) const { return absl::UnimplementedError("HasFieldByName is not yet implemented"); } absl::StatusOr<bool> ParsedMessageValue::HasFieldByNumber( int64_t number) const { return absl::UnimplementedError("HasFieldByNumber is not yet implemented"); } absl::Status ParsedMessageValue::ForEachField( ValueManager& value_manager, ForEachFieldCallback callback) const { return absl::UnimplementedError("ForEachField is not yet implemented"); } absl::StatusOr<int> ParsedMessageValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const { return absl::UnimplementedError("Qualify is not yet implemented"); } absl::StatusOr<std::pair<Value, int>> ParsedMessageValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test) const { Value result; CEL_ASSIGN_OR_RETURN( auto count, Qualify(value_manager, qualifiers, presence_test, result)); return std::pair{std::move(result), count}; } }
#include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_manager.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel { namespace { using ::absl_testing::StatusIs; using ::cel::internal::DynamicParseTextProto; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::_; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ParsedMessageValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); value_manager_ = NewThreadCompatibleValueManager( MemoryManager::Pooling(arena()), NewThreadCompatibleTypeReflector(MemoryManager::Pooling(arena()))); break; case AllocatorKind::kNewDelete: value_manager_ = NewThreadCompatibleValueManager( MemoryManager::ReferenceCounting(), NewThreadCompatibleTypeReflector( MemoryManager::ReferenceCounting())); break; } } void TearDown() override { value_manager_.reset(); arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } ValueManager& value_manager() { return **value_manager_; } template <typename T> ParsedMessageValue MakeParsedMessage(absl::string_view text) { return ParsedMessageValue(DynamicParseTextProto<T>( allocator(), R"pb()pb", descriptor_pool(), message_factory())); } private: absl::optional<google::protobuf::Arena> arena_; absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ParsedMessageValueTest, Default) { ParsedMessageValue value; EXPECT_FALSE(value); } TEST_P(ParsedMessageValueTest, Field) { ParsedMessageValue value(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory())); EXPECT_TRUE(value); } TEST_P(ParsedMessageValueTest, Kind) { ParsedMessageValue value(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory())); EXPECT_EQ(value.kind(), ParsedMessageValue::kKind); EXPECT_EQ(value.kind(), ValueKind::kStruct); } TEST_P(ParsedMessageValueTest, GetTypeName) { ParsedMessageValue value(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory())); EXPECT_EQ(value.GetTypeName(), "google.api.expr.test.v1.proto3.TestAllTypes"); } TEST_P(ParsedMessageValueTest, GetRuntimeType) { ParsedMessageValue value(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory())); EXPECT_EQ(value.GetRuntimeType(), MessageType(value.GetDescriptor())); } TEST_P(ParsedMessageValueTest, DebugString) { ParsedMessageValue valid_value(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory())); EXPECT_THAT(valid_value.DebugString(), _); } TEST_P(ParsedMessageValueTest, IsZeroValue) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_TRUE(valid_value.IsZeroValue()); } TEST_P(ParsedMessageValueTest, SerializeTo) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); absl::Cord serialized; EXPECT_THAT(valid_value.SerializeTo(value_manager(), serialized), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMessageValueTest, ConvertToJson) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(valid_value.ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMessageValueTest, Equal) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(valid_value.Equal(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMessageValueTest, GetFieldByName) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(valid_value.GetFieldByName(value_manager(), "does_not_exist"), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMessageValueTest, GetFieldByNumber) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(valid_value.GetFieldByNumber(value_manager(), 1), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMessageValueTest, ForEachField) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(valid_value.ForEachField( value_manager(), [](absl::string_view, const Value&) -> absl::StatusOr<bool> { return true; }), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMessageValueTest, Qualify) { MessageValue valid_value = MakeParsedMessage<TestAllTypesProto3>(R"pb()pb"); EXPECT_THAT(valid_value.Qualify(value_manager(), {}, false), StatusIs(absl::StatusCode::kUnimplemented)); } INSTANTIATE_TEST_SUITE_P(ParsedMessageValueTest, ParsedMessageValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_message_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_message_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
7c566eab-5a0b-48f5-8314-6b7a47a159d1
cpp
google/cel-cpp
optional_value
common/values/optional_value.cc
common/values/optional_value_test.cc
#include <string> #include <utility> #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "common/casting.h" #include "common/memory.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_kind.h" namespace cel { namespace { class EmptyOptionalValue final : public OptionalValueInterface { public: EmptyOptionalValue() = default; bool HasValue() const override { return false; } void Value(cel::Value& result) const override { result = ErrorValue( absl::FailedPreconditionError("optional.none() dereference")); } }; 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>; 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))); } OptionalValue OptionalValue::None() { static const absl::NoDestructor<EmptyOptionalValue> empty; return OptionalValue(common_internal::MakeShared(&*empty, nullptr)); } absl::Status OptionalValueInterface::Equal(ValueManager& value_manager, const cel::Value& other, cel::Value& result) const { if (auto other_value = As<OptionalValue>(other); other_value.has_value()) { if (HasValue() != other_value->HasValue()) { result = BoolValue{false}; return absl::OkStatus(); } if (!HasValue()) { result = BoolValue{true}; return absl::OkStatus(); } return Value().Equal(value_manager, other_value->Value(), result); return absl::OkStatus(); } result = BoolValue{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 ::absl_testing::StatusIs; using ::testing::An; using ::testing::Ne; using ::testing::TestParamInfo; 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.GetRuntimeType(), 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, SerializeTo) { absl::Cord value; EXPECT_THAT(OptionalValue().SerializeTo(value_manager(), value), 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/optional_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/optional_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e0f4dcb8-c860-4741-8d6b-fcd45186e83e
cpp
google/cel-cpp
null_value
common/values/null_value.cc
common/values/null_value_test.cc
#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 { absl::Status NullValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeValue(kJsonNull, value); } absl::Status NullValue::Equal(ValueManager&, const Value& other, Value& result) const { result = BoolValue{InstanceOf<NullValue>(other)}; return absl::OkStatus(); } absl::StatusOr<Value> NullValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(Value(NullValue())), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( NullValueTest, NullValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), NullValueTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/null_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/null_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
4e7ca27a-1390-4e21-9568-d86ddbbb79ad
cpp
google/cel-cpp
message_value
common/values/message_value.cc
common/values/message_value_test.cc
#include "common/values/message_value.h" #include <cstdint> #include <string> #include <utility> #include "absl/base/nullability.h" #include "absl/base/optimization.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/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "base/attribute.h" #include "common/json.h" #include "common/optional_ref.h" #include "common/value.h" #include "common/values/parsed_message_value.h" #include "runtime/runtime_options.h" #include "google/protobuf/descriptor.h" namespace cel { absl::Nonnull<const google::protobuf::Descriptor*> MessageValue::GetDescriptor() const { ABSL_CHECK(*this); return absl::visit( absl::Overload( [](absl::monostate) -> absl::Nonnull<const google::protobuf::Descriptor*> { ABSL_UNREACHABLE(); }, [](const ParsedMessageValue& alternative) -> absl::Nonnull<const google::protobuf::Descriptor*> { return alternative.GetDescriptor(); }), variant_); } std::string MessageValue::DebugString() const { return absl::visit( absl::Overload([](absl::monostate) -> std::string { return "INVALID"; }, [](const ParsedMessageValue& alternative) -> std::string { return alternative.DebugString(); }), variant_); } bool MessageValue::IsZeroValue() const { ABSL_DCHECK(*this); return absl::visit( absl::Overload([](absl::monostate) -> bool { return true; }, [](const ParsedMessageValue& alternative) -> bool { return alternative.IsZeroValue(); }), variant_); } absl::Status MessageValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::Status { return absl::InternalError( "unexpected attempt to invoke `ConvertToJson` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::Status { return alternative.SerializeTo(converter, value); }), variant_); } absl::StatusOr<Json> MessageValue::ConvertToJson( AnyToJsonConverter& converter) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<Json> { return absl::InternalError( "unexpected attempt to invoke `ConvertToJson` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<Json> { return alternative.ConvertToJson(converter); }), variant_); } absl::Status MessageValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::Status { return absl::InternalError( "unexpected attempt to invoke `Equal` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::Status { return alternative.Equal(value_manager, other, result); }), variant_); } absl::StatusOr<Value> MessageValue::Equal(ValueManager& value_manager, const Value& other) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<Value> { return absl::InternalError( "unexpected attempt to invoke `Equal` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<Value> { return alternative.Equal(value_manager, other); }), variant_); } absl::Status MessageValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, Value& result, ProtoWrapperTypeOptions unboxing_options) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::Status { return absl::InternalError( "unexpected attempt to invoke `GetFieldByName` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::Status { return alternative.GetFieldByName(value_manager, name, result, unboxing_options); }), variant_); } absl::StatusOr<Value> MessageValue::GetFieldByName( ValueManager& value_manager, absl::string_view name, ProtoWrapperTypeOptions unboxing_options) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<Value> { return absl::InternalError( "unexpected attempt to invoke `GetFieldByName` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<Value> { return alternative.GetFieldByName(value_manager, name, unboxing_options); }), variant_); } absl::Status MessageValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, Value& result, ProtoWrapperTypeOptions unboxing_options) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::Status { return absl::InternalError( "unexpected attempt to invoke `GetFieldByNumber` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::Status { return alternative.GetFieldByNumber(value_manager, number, result, unboxing_options); }), variant_); } absl::StatusOr<Value> MessageValue::GetFieldByNumber( ValueManager& value_manager, int64_t number, ProtoWrapperTypeOptions unboxing_options) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<Value> { return absl::InternalError( "unexpected attempt to invoke `GetFieldByNumber` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<Value> { return alternative.GetFieldByNumber(value_manager, number, unboxing_options); }), variant_); } absl::StatusOr<bool> MessageValue::HasFieldByName( absl::string_view name) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<bool> { return absl::InternalError( "unexpected attempt to invoke `HasFieldByName` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<bool> { return alternative.HasFieldByName(name); }), variant_); } absl::StatusOr<bool> MessageValue::HasFieldByNumber(int64_t number) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<bool> { return absl::InternalError( "unexpected attempt to invoke `HasFieldByNumber` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<bool> { return alternative.HasFieldByNumber(number); }), variant_); } absl::Status MessageValue::ForEachField(ValueManager& value_manager, ForEachFieldCallback callback) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::Status { return absl::InternalError( "unexpected attempt to invoke `ForEachField` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::Status { return alternative.ForEachField(value_manager, callback); }), variant_); } absl::StatusOr<int> MessageValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test, Value& result) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<int> { return absl::InternalError( "unexpected attempt to invoke `Qualify` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<int> { return alternative.Qualify(value_manager, qualifiers, presence_test, result); }), variant_); } absl::StatusOr<std::pair<Value, int>> MessageValue::Qualify( ValueManager& value_manager, absl::Span<const SelectQualifier> qualifiers, bool presence_test) const { return absl::visit( absl::Overload( [](absl::monostate) -> absl::StatusOr<std::pair<Value, int>> { return absl::InternalError( "unexpected attempt to invoke `Qualify` on " "an invalid `MessageValue`"); }, [&](const ParsedMessageValue& alternative) -> absl::StatusOr<std::pair<Value, int>> { return alternative.Qualify(value_manager, qualifiers, presence_test); }), variant_); } cel::optional_ref<const ParsedMessageValue> MessageValue::AsParsed() const& { if (const auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return *alternative; } return absl::nullopt; } absl::optional<ParsedMessageValue> MessageValue::AsParsed() && { if (auto* alternative = absl::get_if<ParsedMessageValue>(&variant_); alternative != nullptr) { return std::move(*alternative); } return absl::nullopt; } const ParsedMessageValue& MessageValue::GetParsed() const& { ABSL_DCHECK(IsParsed()); return absl::get<ParsedMessageValue>(variant_); } ParsedMessageValue MessageValue::GetParsed() && { ABSL_DCHECK(IsParsed()); return absl::get<ParsedMessageValue>(std::move(variant_)); } common_internal::ValueVariant MessageValue::ToValueVariant() const& { return absl::get<ParsedMessageValue>(variant_); } common_internal::ValueVariant MessageValue::ToValueVariant() && { return absl::get<ParsedMessageValue>(std::move(variant_)); } common_internal::StructValueVariant MessageValue::ToStructValueVariant() const& { return absl::get<ParsedMessageValue>(variant_); } common_internal::StructValueVariant MessageValue::ToStructValueVariant() && { return absl::get<ParsedMessageValue>(std::move(variant_)); } }
#include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/type.h" #include "common/value.h" #include "common/value_kind.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel { namespace { using ::cel::internal::DynamicParseTextProto; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::An; using ::testing::Optional; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class MessageValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); break; case AllocatorKind::kNewDelete: break; } } void TearDown() override { arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } private: absl::optional<google::protobuf::Arena> arena_; }; TEST_P(MessageValueTest, Default) { MessageValue value; EXPECT_FALSE(value); } template <typename T> constexpr T& AsLValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return t; } template <typename T> constexpr const T& AsConstLValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return t; } template <typename T> constexpr T&& AsRValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return static_cast<T&&>(t); } template <typename T> constexpr const T&& AsConstRValueRef(T& t ABSL_ATTRIBUTE_LIFETIME_BOUND) { return static_cast<const T&&>(t); } TEST_P(MessageValueTest, Parsed) { MessageValue value( ParsedMessageValue(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()))); MessageValue other_value = value; EXPECT_TRUE(value); EXPECT_TRUE(value.Is<ParsedMessageValue>()); EXPECT_THAT(value.As<ParsedMessageValue>(), Optional(An<ParsedMessageValue>())); EXPECT_THAT(AsLValueRef<MessageValue>(value).Get<ParsedMessageValue>(), An<ParsedMessageValue>()); EXPECT_THAT(AsConstLValueRef<MessageValue>(value).Get<ParsedMessageValue>(), An<ParsedMessageValue>()); EXPECT_THAT(AsRValueRef<MessageValue>(value).Get<ParsedMessageValue>(), An<ParsedMessageValue>()); EXPECT_THAT( AsConstRValueRef<MessageValue>(other_value).Get<ParsedMessageValue>(), An<ParsedMessageValue>()); } TEST_P(MessageValueTest, Kind) { MessageValue value; EXPECT_EQ(value.kind(), ParsedMessageValue::kKind); EXPECT_EQ(value.kind(), ValueKind::kStruct); } TEST_P(MessageValueTest, GetTypeName) { MessageValue value( ParsedMessageValue(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()))); EXPECT_EQ(value.GetTypeName(), "google.api.expr.test.v1.proto3.TestAllTypes"); } TEST_P(MessageValueTest, GetRuntimeType) { MessageValue value( ParsedMessageValue(DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()))); EXPECT_EQ(value.GetRuntimeType(), MessageType(value.GetDescriptor())); } INSTANTIATE_TEST_SUITE_P(MessageValueTest, MessageValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/message_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/message_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
af364550-5955-4c94-a193-5b2803f102e2
cpp
google/cel-cpp
parsed_json_map_value
common/values/parsed_json_map_value.cc
common/values/parsed_json_map_value_test.cc
#include "common/values/parsed_json_map_value.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/base/optimization.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/json.h" #include "common/memory.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/parsed_json_value.h" #include "internal/json.h" #include "internal/status_macros.h" #include "internal/strings.h" #include "internal/well_known_types.h" #include "google/protobuf/arena.h" #include "google/protobuf/map.h" #include "google/protobuf/map_field.h" #include "google/protobuf/message.h" #include "google/protobuf/message_lite.h" namespace cel { namespace common_internal { absl::Status CheckWellKnownStructMessage(const google::protobuf::Message& message) { return internal::CheckJsonMap(message); } } std::string ParsedJsonMapValue::DebugString() const { if (value_ == nullptr) { return "{}"; } return internal::JsonMapDebugString(*value_); } absl::Status ParsedJsonMapValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { if (value_ == nullptr) { value.Clear(); return absl::OkStatus(); } if (!value_->SerializePartialToCord(&value)) { return absl::UnknownError("failed to serialize protocol buffer message"); } return absl::OkStatus(); } absl::StatusOr<Json> ParsedJsonMapValue::ConvertToJson( AnyToJsonConverter& converter) const { if (value_ == nullptr) { return JsonObject(); } return internal::ProtoJsonMapToNativeJsonMap(*value_); } absl::Status ParsedJsonMapValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { if (auto other_value = other.AsParsedJsonMap(); other_value) { result = BoolValue(*this == *other_value); return absl::OkStatus(); } if (auto other_value = other.AsMap(); other_value) { return common_internal::MapValueEqual(value_manager, MapValue(*this), *other_value, result); } result = BoolValue(false); return absl::OkStatus(); } absl::StatusOr<Value> ParsedJsonMapValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } size_t ParsedJsonMapValue::Size() const { if (value_ == nullptr) { return 0; } return static_cast<size_t>( well_known_types::GetStructReflectionOrDie(value_->GetDescriptor()) .FieldsSize(*value_)); } absl::Status ParsedJsonMapValue::Get(ValueManager& value_manager, const Value& key, Value& result) const { CEL_ASSIGN_OR_RETURN(bool ok, Find(value_manager, key, result)); if (ABSL_PREDICT_FALSE(!ok) && !(result.IsError() || result.IsUnknown())) { return absl::NotFoundError( absl::StrCat("Key not found in map : ", key.DebugString())); } return absl::OkStatus(); } absl::StatusOr<Value> ParsedJsonMapValue::Get(ValueManager& value_manager, const Value& key) const { Value result; CEL_RETURN_IF_ERROR(Get(value_manager, key, result)); return result; } absl::StatusOr<bool> ParsedJsonMapValue::Find(ValueManager& value_manager, const Value& key, Value& result) const { if (key.IsError() || key.IsUnknown()) { result = key; return false; } if (value_ != nullptr) { if (auto string_key = key.AsString(); string_key) { if (ABSL_PREDICT_FALSE(value_ == nullptr)) { result = NullValue(); return false; } std::string key_scratch; if (const auto* value = well_known_types::GetStructReflectionOrDie( value_->GetDescriptor()) .FindField(*value_, string_key->NativeString(key_scratch)); value != nullptr) { result = common_internal::ParsedJsonValue( value_manager.GetMemoryManager().arena(), Borrowed(value_, value)); return true; } result = NullValue(); return false; } } result = NullValue(); return false; } absl::StatusOr<std::pair<Value, bool>> ParsedJsonMapValue::Find( ValueManager& value_manager, const Value& key) const { Value result; CEL_ASSIGN_OR_RETURN(auto found, Find(value_manager, key, result)); if (found) { return std::pair{std::move(result), found}; } return std::pair{NullValue(), found}; } absl::Status ParsedJsonMapValue::Has(ValueManager& value_manager, const Value& key, Value& result) const { if (key.IsError() || key.IsUnknown()) { result = key; return absl::OkStatus(); } if (value_ != nullptr) { if (auto string_key = key.AsString(); string_key) { if (ABSL_PREDICT_FALSE(value_ == nullptr)) { result = BoolValue(false); return absl::OkStatus(); } std::string key_scratch; if (const auto* value = well_known_types::GetStructReflectionOrDie( value_->GetDescriptor()) .FindField(*value_, string_key->NativeString(key_scratch)); value != nullptr) { result = BoolValue(true); } else { result = BoolValue(false); } return absl::OkStatus(); } } result = BoolValue(false); return absl::OkStatus(); } absl::StatusOr<Value> ParsedJsonMapValue::Has(ValueManager& value_manager, const Value& key) const { Value result; CEL_RETURN_IF_ERROR(Has(value_manager, key, result)); return result; } namespace { class ParsedJsonMapValueKeysList final : public ParsedListValueInterface, public EnableSharedFromThis<ParsedJsonMapValueKeysList> { public: ParsedJsonMapValueKeysList(Owned<const google::protobuf::MessageLite> message, absl::Nullable<google::protobuf::Arena*> keys_arena, std::string* keys, size_t keys_size) : message_(std::move(message)), keys_arena_(keys_arena), keys_(keys), keys_size_(keys_size) {} ~ParsedJsonMapValueKeysList() override { if (keys_arena_ == nullptr) { delete[] keys_; } } std::string DebugString() const override { std::string result; result.push_back('['); for (size_t i = 0; i < keys_size_; ++i) { if (i > 0) { result.append(", "); } result.append(internal::FormatStringLiteral(keys_[i])); } result.push_back(']'); return result; } size_t Size() const override { return keys_size_; } absl::Status Contains(ValueManager& value_manager, const Value& other, Value& result) const override { if (ABSL_PREDICT_FALSE(other.IsError() || other.IsUnknown())) { result = other; return absl::OkStatus(); } if (const auto other_string = other.AsString(); other_string) { for (size_t i = 0; i < keys_size_; ++i) { if (keys_[i] == *other_string) { result = BoolValue(true); return absl::OkStatus(); } } } result = BoolValue(false); return absl::OkStatus(); } absl::StatusOr<JsonArray> ConvertToJsonArray( AnyToJsonConverter&) const override { JsonArrayBuilder builder; builder.reserve(keys_size_); for (size_t i = 0; i < keys_size_; ++i) { builder.push_back(JsonString(keys_[i])); } return std::move(builder).Build(); } protected: absl::Status GetImpl(ValueManager& value_manager, size_t index, Value& result) const override { result = StringValue(value_manager.GetMemoryManager().arena(), keys_[index]); return absl::OkStatus(); } private: friend struct cel::NativeTypeTraits<ParsedJsonMapValueKeysList>; NativeTypeId GetNativeTypeId() const noexcept override { return NativeTypeId::For<ParsedJsonMapValueKeysList>(); } const Owned<const google::protobuf::MessageLite> message_; const absl::Nullable<google::protobuf::Arena*> keys_arena_; std::string* const keys_; const size_t keys_size_; }; struct ArenaStringArray { absl::Nullable<std::string*> data; size_t size; }; void DestroyArenaStringArray(void* strings) { std::destroy_n(reinterpret_cast<ArenaStringArray*>(strings)->data, reinterpret_cast<ArenaStringArray*>(strings)->size); } } template <> struct NativeTypeTraits<ParsedJsonMapValueKeysList> final { static NativeTypeId Id(const ParsedJsonMapValueKeysList& type) { return type.GetNativeTypeId(); } static bool SkipDestructor(const ParsedJsonMapValueKeysList& type) { return NativeType::SkipDestructor(type.message_) && type.keys_arena_ != nullptr; } }; absl::Status ParsedJsonMapValue::ListKeys(ValueManager& value_manager, ListValue& result) const { if (value_ == nullptr) { result = ListValue(); return absl::OkStatus(); } google::protobuf::Arena* arena = value_manager.GetMemoryManager().arena(); size_t keys_size; std::string* keys; const auto reflection = well_known_types::GetStructReflectionOrDie(value_->GetDescriptor()); keys_size = static_cast<size_t>(reflection.FieldsSize(*value_)); auto keys_it = reflection.BeginFields(*value_); if (arena != nullptr) { keys = reinterpret_cast<std::string*>(arena->AllocateAligned( keys_size * sizeof(std::string), alignof(std::string))); for (size_t i = 0; i < keys_size; ++i, ++keys_it) { ::new (static_cast<void*>(keys + i)) std::string(keys_it.GetKey().GetStringValue()); } } else { keys = new std::string[keys_size]; for (size_t i = 0; i < keys_size; ++i, ++keys_it) { const auto& key = keys_it.GetKey().GetStringValue(); (keys + i)->assign(key.data(), key.size()); } } if (arena != nullptr) { ArenaStringArray* array = google::protobuf::Arena::Create<ArenaStringArray>(arena); array->data = keys; array->size = keys_size; arena->OwnCustomDestructor(array, &DestroyArenaStringArray); } result = ParsedListValue( value_manager.GetMemoryManager().MakeShared<ParsedJsonMapValueKeysList>( value_, arena, keys, keys_size)); return absl::OkStatus(); } absl::StatusOr<ListValue> ParsedJsonMapValue::ListKeys( ValueManager& value_manager) const { ListValue result; CEL_RETURN_IF_ERROR(ListKeys(value_manager, result)); return result; } absl::Status ParsedJsonMapValue::ForEach(ValueManager& value_manager, ForEachCallback callback) const { if (value_ == nullptr) { return absl::OkStatus(); } const auto reflection = well_known_types::GetStructReflectionOrDie(value_->GetDescriptor()); Value key_scratch; Value value_scratch; auto map_begin = reflection.BeginFields(*value_); const auto map_end = reflection.EndFields(*value_); for (; map_begin != map_end; ++map_begin) { key_scratch = StringValue(value_manager.GetMemoryManager().arena(), map_begin.GetKey().GetStringValue()); value_scratch = common_internal::ParsedJsonValue( value_manager.GetMemoryManager().arena(), Borrowed(value_, &map_begin.GetValueRef().GetMessageValue())); CEL_ASSIGN_OR_RETURN(auto ok, callback(key_scratch, value_scratch)); if (!ok) { break; } } return absl::OkStatus(); } namespace { class ParsedJsonMapValueIterator final : public ValueIterator { public: explicit ParsedJsonMapValueIterator(Owned<const google::protobuf::Message> message) : message_(std::move(message)), reflection_(well_known_types::GetStructReflectionOrDie( message_->GetDescriptor())), begin_(reflection_.BeginFields(*message_)), end_(reflection_.EndFields(*message_)) {} bool HasNext() override { return begin_ != end_; } absl::Status Next(ValueManager& value_manager, Value& result) override { if (ABSL_PREDICT_FALSE(begin_ == end_)) { return absl::FailedPreconditionError( "`ValueIterator::Next` called after `ValueIterator::HasNext` " "returned false"); } std::string scratch = static_cast<std::string>(begin_.GetKey().GetStringValue()); result = StringValue(value_manager.GetMemoryManager().arena(), std::move(scratch)); ++begin_; return absl::OkStatus(); } private: const Owned<const google::protobuf::Message> message_; const well_known_types::StructReflection reflection_; google::protobuf::MapIterator begin_; const google::protobuf::MapIterator end_; std::string scratch_; }; } absl::StatusOr<absl::Nonnull<std::unique_ptr<ValueIterator>>> ParsedJsonMapValue::NewIterator(ValueManager& value_manager) const { if (value_ == nullptr) { return NewEmptyValueIterator(); } return std::make_unique<ParsedJsonMapValueIterator>(value_); } bool operator==(const ParsedJsonMapValue& lhs, const ParsedJsonMapValue& rhs) { if (cel::to_address(lhs.value_) == cel::to_address(rhs.value_)) { return true; } if (cel::to_address(lhs.value_) == nullptr) { return rhs.IsEmpty(); } if (cel::to_address(rhs.value_) == nullptr) { return lhs.IsEmpty(); } return internal::JsonMapEquals(*lhs.value_, *rhs.value_); } }
#include <utility> #include <vector> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/json.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_manager.h" #include "common/value_testing.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::cel::test::BoolValueIs; using ::cel::test::IsNullValue; using ::cel::test::StringValueIs; using ::testing::AnyOf; using ::testing::IsEmpty; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::Pair; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using ::testing::UnorderedElementsAre; using ::testing::VariantWith; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ParsedJsonMapValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); value_manager_ = NewThreadCompatibleValueManager( MemoryManager::Pooling(arena()), NewThreadCompatibleTypeReflector(MemoryManager::Pooling(arena()))); break; case AllocatorKind::kNewDelete: value_manager_ = NewThreadCompatibleValueManager( MemoryManager::ReferenceCounting(), NewThreadCompatibleTypeReflector( MemoryManager::ReferenceCounting())); break; } } void TearDown() override { value_manager_.reset(); arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } ValueManager& value_manager() { return **value_manager_; } template <typename T> auto GeneratedParseTextProto(absl::string_view text) { return ::cel::internal::GeneratedParseTextProto<T>( allocator(), text, descriptor_pool(), message_factory()); } template <typename T> auto DynamicParseTextProto(absl::string_view text) { return ::cel::internal::DynamicParseTextProto<T>( allocator(), text, descriptor_pool(), message_factory()); } private: absl::optional<google::protobuf::Arena> arena_; absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ParsedJsonMapValueTest, Kind) { EXPECT_EQ(ParsedJsonMapValue::kind(), ParsedJsonMapValue::kKind); EXPECT_EQ(ParsedJsonMapValue::kind(), ValueKind::kMap); } TEST_P(ParsedJsonMapValueTest, GetTypeName) { EXPECT_EQ(ParsedJsonMapValue::GetTypeName(), ParsedJsonMapValue::kName); EXPECT_EQ(ParsedJsonMapValue::GetTypeName(), "google.protobuf.Struct"); } TEST_P(ParsedJsonMapValueTest, GetRuntimeType) { ParsedJsonMapValue value; EXPECT_EQ(ParsedJsonMapValue::GetRuntimeType(), JsonMapType()); } TEST_P(ParsedJsonMapValueTest, DebugString_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); EXPECT_EQ(valid_value.DebugString(), "{}"); } TEST_P(ParsedJsonMapValueTest, IsZeroValue_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); EXPECT_TRUE(valid_value.IsZeroValue()); } TEST_P(ParsedJsonMapValueTest, SerializeTo_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); absl::Cord serialized; EXPECT_THAT(valid_value.SerializeTo(value_manager(), serialized), IsOk()); EXPECT_THAT(serialized, IsEmpty()); } TEST_P(ParsedJsonMapValueTest, ConvertToJson_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); EXPECT_THAT(valid_value.ConvertToJson(value_manager()), IsOkAndHolds(VariantWith<JsonObject>(JsonObject()))); } TEST_P(ParsedJsonMapValueTest, Equal_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); EXPECT_THAT(valid_value.Equal(value_manager(), BoolValue()), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT( valid_value.Equal( value_manager(), ParsedJsonMapValue( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb"))), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Equal(value_manager(), MapValue()), IsOkAndHolds(BoolValueIs(true))); } TEST_P(ParsedJsonMapValueTest, Empty_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); EXPECT_TRUE(valid_value.IsEmpty()); } TEST_P(ParsedJsonMapValueTest, Size_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>(R"pb()pb")); EXPECT_EQ(valid_value.Size(), 0); } TEST_P(ParsedJsonMapValueTest, Get_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } })pb")); EXPECT_THAT(valid_value.Get(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT(valid_value.Get(value_manager(), StringValue("foo")), IsOkAndHolds(IsNullValue())); EXPECT_THAT(valid_value.Get(value_manager(), StringValue("bar")), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Get(value_manager(), StringValue("baz")), StatusIs(absl::StatusCode::kNotFound)); } TEST_P(ParsedJsonMapValueTest, Find_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } })pb")); EXPECT_THAT(valid_value.Find(value_manager(), BoolValue()), IsOkAndHolds(Pair(IsNullValue(), IsFalse()))); EXPECT_THAT(valid_value.Find(value_manager(), StringValue("foo")), IsOkAndHolds(Pair(IsNullValue(), IsTrue()))); EXPECT_THAT(valid_value.Find(value_manager(), StringValue("bar")), IsOkAndHolds(Pair(BoolValueIs(true), IsTrue()))); EXPECT_THAT(valid_value.Find(value_manager(), StringValue("baz")), IsOkAndHolds(Pair(IsNullValue(), IsFalse()))); } TEST_P(ParsedJsonMapValueTest, Has_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } })pb")); EXPECT_THAT(valid_value.Has(value_manager(), BoolValue()), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Has(value_manager(), StringValue("foo")), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Has(value_manager(), StringValue("bar")), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Has(value_manager(), StringValue("baz")), IsOkAndHolds(BoolValueIs(false))); } TEST_P(ParsedJsonMapValueTest, ListKeys_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } })pb")); ASSERT_OK_AND_ASSIGN(auto keys, valid_value.ListKeys(value_manager())); EXPECT_THAT(keys.Size(), IsOkAndHolds(2)); EXPECT_THAT(keys.DebugString(), AnyOf("[\"foo\", \"bar\"]", "[\"bar\", \"foo\"]")); EXPECT_THAT(keys.Contains(value_manager(), BoolValue()), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(keys.Contains(value_manager(), StringValue("bar")), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(keys.Get(value_manager(), 0), IsOkAndHolds(AnyOf(StringValueIs("foo"), StringValueIs("bar")))); EXPECT_THAT(keys.Get(value_manager(), 1), IsOkAndHolds(AnyOf(StringValueIs("foo"), StringValueIs("bar")))); EXPECT_THAT( keys.ConvertToJson(value_manager()), IsOkAndHolds(AnyOf(VariantWith<JsonArray>(MakeJsonArray( {JsonString("foo"), JsonString("bar")})), VariantWith<JsonArray>(MakeJsonArray( {JsonString("bar"), JsonString("foo")}))))); } TEST_P(ParsedJsonMapValueTest, ForEach_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } })pb")); std::vector<std::pair<Value, Value>> entries; EXPECT_THAT( valid_value.ForEach( value_manager(), [&](const Value& key, const Value& value) -> absl::StatusOr<bool> { entries.push_back(std::pair{std::move(key), std::move(value)}); return true; }), IsOk()); EXPECT_THAT(entries, UnorderedElementsAre( Pair(StringValueIs("foo"), IsNullValue()), Pair(StringValueIs("bar"), BoolValueIs(true)))); } TEST_P(ParsedJsonMapValueTest, NewIterator_Dynamic) { ParsedJsonMapValue valid_value( DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: {} } fields { key: "bar" value: { bool_value: true } })pb")); ASSERT_OK_AND_ASSIGN(auto iterator, valid_value.NewIterator(value_manager())); ASSERT_TRUE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), IsOkAndHolds(AnyOf(StringValueIs("foo"), StringValueIs("bar")))); ASSERT_TRUE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), IsOkAndHolds(AnyOf(StringValueIs("foo"), StringValueIs("bar")))); ASSERT_FALSE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } INSTANTIATE_TEST_SUITE_P(ParsedJsonMapValueTest, ParsedJsonMapValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_json_map_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_json_map_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
e4f7969a-884d-459f-a3f8-7c48d3440123
cpp
google/cel-cpp
error_value
common/values/error_value.cc
common/values/error_value_test.cc
#include <string> #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.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); } const absl::Status& DefaultErrorValue() { static const absl::NoDestructor<absl::Status> value( absl::UnknownError("unknown error")); return *value; } } ErrorValue::ErrorValue() : ErrorValue(DefaultErrorValue()) {} 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(const Type& from, const Type& to) { return TypeConversionError(from.DebugString(), to.DebugString()); } bool IsNoSuchField(const ErrorValue& value) { return absl::IsNotFound(value.NativeValue()) && absl::StartsWith(value.NativeValue().message(), "no_such_field"); } bool IsNoSuchKey(const ErrorValue& 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::Status ErrorValue::SerializeTo(AnyToJsonConverter&, absl::Cord&) 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&, const Value&, Value& result) const { result = BoolValue{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/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::StatusIs; using ::testing::_; using ::testing::An; using ::testing::IsEmpty; using ::testing::Ne; using ::testing::Not; 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, SerializeTo) { absl::Cord value; EXPECT_THAT(ErrorValue().SerializeTo(value_manager(), value), 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>(Value(ErrorValue(absl::CancelledError()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( ErrorValueTest, ErrorValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), ErrorValueTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/error_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/error_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
f7da06ba-53b8-4515-bc96-3129eeae5a96
cpp
google/cel-cpp
bytes_value
common/values/bytes_value.cc
common/values/bytes_value_test.cc
#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::Status BytesValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return NativeValue([&value](const auto& bytes) -> absl::Status { return internal::SerializeBytesValue(bytes, value); }); } absl::StatusOr<Json> BytesValue::ConvertToJson(AnyToJsonConverter&) const { return NativeValue( [](const auto& value) -> Json { return JsonBytes(value); }); } absl::Status BytesValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<BytesValue>(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 = BoolValue{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(const BytesValue& 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(const BytesValue& 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/value.h" #include "common/value_testing.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/bytes_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/bytes_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
6f3f95cf-f163-4ace-87a5-f25a38f093e7
cpp
google/cel-cpp
list_value
common/values/list_value.cc
common/values/list_value_test.cc
#include <cstddef> #include <utility> #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/variant.h" #include "common/casting.h" #include "common/value.h" #include "internal/status_macros.h" namespace cel { 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::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<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_); } namespace common_internal { absl::Status ListValueEqual(ValueManager& value_manager, const ListValue& lhs, const ListValue& rhs, Value& result) { if (Is(lhs, rhs)) { result = BoolValue{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 = BoolValue{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 = BoolValue{true}; return absl::OkStatus(); } absl::Status ListValueEqual(ValueManager& value_manager, const ParsedListValueInterface& lhs, const ListValue& rhs, Value& result) { auto lhs_size = lhs.Size(); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { result = BoolValue{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 = BoolValue{true}; return absl::OkStatus(); } } common_internal::ValueVariant ListValue::ToValueVariant() const& { return absl::visit( [](const auto& alternative) -> common_internal::ValueVariant { return alternative; }, variant_); } common_internal::ValueVariant ListValue::ToValueVariant() && { return absl::visit( [](auto&& alternative) -> common_internal::ValueVariant { return std::move(alternative); }, std::move(variant_)); } }
#include <cstdint> #include <memory> #include <sstream> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.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 ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAreArray; using ::testing::TestParamInfo; 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(ListType())); (static_cast<void>(builder->Add(std::forward<Args>(args))), ...); return std::move(*builder).Build(); } }; TEST_P(ListValueTest, Default) { ListValue value; EXPECT_THAT(value.IsEmpty(), IsOkAndHolds(true)); EXPECT_THAT(value.Size(), IsOkAndHolds(0)); EXPECT_EQ(value.DebugString(), "[]"); } 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))); } 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](const Value& element) { elements.push_back(Cast<IntValue>(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(), IntValue(2))); ASSERT_TRUE(InstanceOf<BoolValue>(contained)); EXPECT_TRUE(Cast<BoolValue>(contained).NativeValue()); ASSERT_OK_AND_ASSIGN(contained, value.Contains(value_manager(), IntValue(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, 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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/list_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/list_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
73f81048-c2c7-4461-8373-1ea5fef53afb
cpp
google/cel-cpp
legacy_struct_value
common/values/legacy_struct_value.cc
common/values/legacy_struct_value_test.cc
#include <cstddef> #include <cstdint> #include <string> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/log/absl_check.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/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "base/internal/message_wrapper.h" #include "common/json.h" #include "common/type.h" #include "common/value.h" #include "internal/dynamic_loader.h" #include "runtime/runtime_options.h" #include "google/protobuf/message.h" #include "google/protobuf/message_lite.h" #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" #endif 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&, const Value&, 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, const Value& 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::GetRuntimeType() const { InitializeLegacyStructValue(); if ((message_ptr_ & ::cel::base_internal::kMessageWrapperTagMask) == ::cel::base_internal::kMessageWrapperTagMessageValue) { return MessageType( google::protobuf::DownCastMessage<google::protobuf::Message>( reinterpret_cast<const google::protobuf::MessageLite*>( message_ptr_ & ::cel::base_internal::kMessageWrapperPtrMask)) ->GetDescriptor()); } return common_internal::MakeBasicStructType(GetTypeName()); } 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::Status LegacyStructValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { InitializeLegacyStructValue(); return (*legacy_struct_value_vtable.serialize_to)(message_ptr_, type_info_, 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, const Value& 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); } bool IsLegacyStructValue(const Value& value) { return absl::holds_alternative<LegacyStructValue>(value.variant_); } LegacyStructValue GetLegacyStructValue(const Value& value) { ABSL_DCHECK(IsLegacyStructValue(value)); return absl::get<LegacyStructValue>(value.variant_); } absl::optional<LegacyStructValue> AsLegacyStructValue(const Value& value) { if (IsLegacyStructValue(value)) { return GetLegacyStructValue(value); } return absl::nullopt; } } #if defined(__GNUC__) #pragma GCC diagnostic pop #endif
#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, 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, SerializeTo) { absl::Cord serialize_value; EXPECT_DEATH(static_cast<void>(LegacyStructValue(0, 0).SerializeTo( value_manager(), serialize_value)), _); } 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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/legacy_struct_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/legacy_struct_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
d19434c1-ac20-4e52-9b0a-725424f6da46
cpp
google/cel-cpp
parsed_json_list_value
common/values/parsed_json_list_value.cc
common/values/parsed_json_list_value_test.cc
#include "common/values/parsed_json_list_value.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "common/json.h" #include "common/memory.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/parsed_json_value.h" #include "internal/json.h" #include "internal/number.h" #include "internal/status_macros.h" #include "internal/well_known_types.h" #include "google/protobuf/message.h" namespace cel { namespace common_internal { absl::Status CheckWellKnownListValueMessage(const google::protobuf::Message& message) { return internal::CheckJsonList(message); } } std::string ParsedJsonListValue::DebugString() const { if (value_ == nullptr) { return "[]"; } return internal::JsonListDebugString(*value_); } absl::Status ParsedJsonListValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { if (value_ == nullptr) { value.Clear(); return absl::OkStatus(); } if (!value_->SerializePartialToCord(&value)) { return absl::UnknownError("failed to serialize protocol buffer message"); } return absl::OkStatus(); } absl::StatusOr<Json> ParsedJsonListValue::ConvertToJson( AnyToJsonConverter& converter) const { if (value_ == nullptr) { return JsonArray(); } return internal::ProtoJsonListToNativeJsonList(*value_); } absl::Status ParsedJsonListValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { if (auto other_value = other.AsParsedJsonList(); other_value) { result = BoolValue(*this == *other_value); return absl::OkStatus(); } if (auto other_value = other.AsList(); other_value) { return common_internal::ListValueEqual(value_manager, ListValue(*this), *other_value, result); } result = BoolValue(false); return absl::OkStatus(); } absl::StatusOr<Value> ParsedJsonListValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } size_t ParsedJsonListValue::Size() const { if (value_ == nullptr) { return 0; } return static_cast<size_t>( well_known_types::GetListValueReflectionOrDie(value_->GetDescriptor()) .ValuesSize(*value_)); } absl::Status ParsedJsonListValue::Get(ValueManager& value_manager, size_t index, Value& result) const { if (value_ == nullptr) { return absl::InvalidArgumentError("index out of bounds"); } const auto reflection = well_known_types::GetListValueReflectionOrDie(value_->GetDescriptor()); if (ABSL_PREDICT_FALSE(index >= static_cast<size_t>(reflection.ValuesSize(*value_)))) { return absl::InvalidArgumentError("index out of bounds"); } result = common_internal::ParsedJsonValue( value_manager.GetMemoryManager().arena(), Borrowed(value_, &reflection.Values(*value_, static_cast<int>(index)))); return absl::OkStatus(); } absl::StatusOr<Value> ParsedJsonListValue::Get(ValueManager& value_manager, size_t index) const { Value result; CEL_RETURN_IF_ERROR(Get(value_manager, index, result)); return result; } absl::Status ParsedJsonListValue::ForEach(ValueManager& value_manager, ForEachCallback callback) const { return ForEach(value_manager, [callback = std::move(callback)](size_t, const Value& value) -> absl::StatusOr<bool> { return callback(value); }); } absl::Status ParsedJsonListValue::ForEach( ValueManager& value_manager, ForEachWithIndexCallback callback) const { if (value_ == nullptr) { return absl::OkStatus(); } Value scratch; const auto reflection = well_known_types::GetListValueReflectionOrDie(value_->GetDescriptor()); const int size = reflection.ValuesSize(*value_); for (int i = 0; i < size; ++i) { scratch = common_internal::ParsedJsonValue( value_manager.GetMemoryManager().arena(), Borrowed(value_, &reflection.Values(*value_, i))); CEL_ASSIGN_OR_RETURN(auto ok, callback(static_cast<size_t>(i), scratch)); if (!ok) { break; } } return absl::OkStatus(); } namespace { class ParsedJsonListValueIterator final : public ValueIterator { public: explicit ParsedJsonListValueIterator(Owned<const google::protobuf::Message> message) : message_(std::move(message)), reflection_(well_known_types::GetListValueReflectionOrDie( message_->GetDescriptor())), size_(reflection_.ValuesSize(*message_)) {} bool HasNext() override { return index_ < size_; } absl::Status Next(ValueManager& value_manager, Value& result) override { if (ABSL_PREDICT_FALSE(index_ >= size_)) { return absl::FailedPreconditionError( "`ValueIterator::Next` called after `ValueIterator::HasNext` " "returned false"); } result = common_internal::ParsedJsonValue( value_manager.GetMemoryManager().arena(), Borrowed(message_, &reflection_.Values(*message_, index_))); ++index_; return absl::OkStatus(); } private: const Owned<const google::protobuf::Message> message_; const well_known_types::ListValueReflection reflection_; const int size_; int index_ = 0; }; } absl::StatusOr<absl::Nonnull<std::unique_ptr<ValueIterator>>> ParsedJsonListValue::NewIterator(ValueManager& value_manager) const { if (value_ == nullptr) { return NewEmptyValueIterator(); } return std::make_unique<ParsedJsonListValueIterator>(value_); } namespace { absl::optional<internal::Number> AsNumber(const Value& value) { if (auto int_value = value.AsInt(); int_value) { return internal::Number::FromInt64(*int_value); } if (auto uint_value = value.AsUint(); uint_value) { return internal::Number::FromUint64(*uint_value); } if (auto double_value = value.AsDouble(); double_value) { return internal::Number::FromDouble(*double_value); } return absl::nullopt; } } absl::Status ParsedJsonListValue::Contains(ValueManager& value_manager, const Value& other, Value& result) const { if (value_ == nullptr) { result = BoolValue(false); return absl::OkStatus(); } if (ABSL_PREDICT_FALSE(other.IsError() || other.IsUnknown())) { result = other; return absl::OkStatus(); } const auto reflection = well_known_types::GetListValueReflectionOrDie(value_->GetDescriptor()); if (reflection.ValuesSize(*value_) > 0) { const auto value_reflection = well_known_types::GetValueReflectionOrDie( reflection.GetValueDescriptor()); if (other.IsNull()) { for (const auto& element : reflection.Values(*value_)) { const auto element_kind_case = value_reflection.GetKindCase(element); if (element_kind_case == google::protobuf::Value::KIND_NOT_SET || element_kind_case == google::protobuf::Value::kNullValue) { result = BoolValue(true); return absl::OkStatus(); } } } else if (const auto other_value = other.AsBool(); other_value) { for (const auto& element : reflection.Values(*value_)) { if (value_reflection.GetKindCase(element) == google::protobuf::Value::kBoolValue && value_reflection.GetBoolValue(element) == *other_value) { result = BoolValue(true); return absl::OkStatus(); } } } else if (const auto other_value = AsNumber(other); other_value) { for (const auto& element : reflection.Values(*value_)) { if (value_reflection.GetKindCase(element) == google::protobuf::Value::kNumberValue && internal::Number::FromDouble( value_reflection.GetNumberValue(element)) == *other_value) { result = BoolValue(true); return absl::OkStatus(); } } } else if (const auto other_value = other.AsString(); other_value) { std::string scratch; for (const auto& element : reflection.Values(*value_)) { if (value_reflection.GetKindCase(element) == google::protobuf::Value::kStringValue && absl::visit( [&](const auto& alternative) -> bool { return *other_value == alternative; }, well_known_types::AsVariant( value_reflection.GetStringValue(element, scratch)))) { result = BoolValue(true); return absl::OkStatus(); } } } else if (const auto other_value = other.AsList(); other_value) { for (const auto& element : reflection.Values(*value_)) { if (value_reflection.GetKindCase(element) == google::protobuf::Value::kListValue) { CEL_RETURN_IF_ERROR(other_value->Equal( value_manager, ParsedJsonListValue(Owned( Owner(value_), &value_reflection.GetListValue(element))), result)); if (result.IsTrue()) { return absl::OkStatus(); } } } } else if (const auto other_value = other.AsMap(); other_value) { for (const auto& element : reflection.Values(*value_)) { if (value_reflection.GetKindCase(element) == google::protobuf::Value::kStructValue) { CEL_RETURN_IF_ERROR(other_value->Equal( value_manager, ParsedJsonMapValue(Owned( Owner(value_), &value_reflection.GetStructValue(element))), result)); if (result.IsTrue()) { return absl::OkStatus(); } } } } } result = BoolValue(false); return absl::OkStatus(); } absl::StatusOr<Value> ParsedJsonListValue::Contains(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Contains(value_manager, other, result)); return result; } bool operator==(const ParsedJsonListValue& lhs, const ParsedJsonListValue& rhs) { if (cel::to_address(lhs.value_) == cel::to_address(rhs.value_)) { return true; } if (cel::to_address(lhs.value_) == nullptr) { return rhs.IsEmpty(); } if (cel::to_address(rhs.value_) == nullptr) { return lhs.IsEmpty(); } return internal::JsonListEquals(*lhs.value_, *rhs.value_); } }
#include <cstddef> #include <vector> #include "google/protobuf/struct.pb.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/json.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_manager.h" #include "common/value_testing.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::cel::test::BoolValueIs; using ::cel::test::IsNullValue; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using ::testing::VariantWith; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ParsedJsonListValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); value_manager_ = NewThreadCompatibleValueManager( MemoryManager::Pooling(arena()), NewThreadCompatibleTypeReflector(MemoryManager::Pooling(arena()))); break; case AllocatorKind::kNewDelete: value_manager_ = NewThreadCompatibleValueManager( MemoryManager::ReferenceCounting(), NewThreadCompatibleTypeReflector( MemoryManager::ReferenceCounting())); break; } } void TearDown() override { value_manager_.reset(); arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } ValueManager& value_manager() { return **value_manager_; } template <typename T> auto GeneratedParseTextProto(absl::string_view text) { return ::cel::internal::GeneratedParseTextProto<T>( allocator(), text, descriptor_pool(), message_factory()); } template <typename T> auto DynamicParseTextProto(absl::string_view text) { return ::cel::internal::DynamicParseTextProto<T>( allocator(), text, descriptor_pool(), message_factory()); } private: absl::optional<google::protobuf::Arena> arena_; absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ParsedJsonListValueTest, Kind) { EXPECT_EQ(ParsedJsonListValue::kind(), ParsedJsonListValue::kKind); EXPECT_EQ(ParsedJsonListValue::kind(), ValueKind::kList); } TEST_P(ParsedJsonListValueTest, GetTypeName) { EXPECT_EQ(ParsedJsonListValue::GetTypeName(), ParsedJsonListValue::kName); EXPECT_EQ(ParsedJsonListValue::GetTypeName(), "google.protobuf.ListValue"); } TEST_P(ParsedJsonListValueTest, GetRuntimeType) { EXPECT_EQ(ParsedJsonListValue::GetRuntimeType(), JsonListType()); } TEST_P(ParsedJsonListValueTest, DebugString_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); EXPECT_EQ(valid_value.DebugString(), "[]"); } TEST_P(ParsedJsonListValueTest, IsZeroValue_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); EXPECT_TRUE(valid_value.IsZeroValue()); } TEST_P(ParsedJsonListValueTest, SerializeTo_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); absl::Cord serialized; EXPECT_THAT(valid_value.SerializeTo(value_manager(), serialized), IsOk()); EXPECT_THAT(serialized, IsEmpty()); } TEST_P(ParsedJsonListValueTest, ConvertToJson_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); EXPECT_THAT(valid_value.ConvertToJson(value_manager()), IsOkAndHolds(VariantWith<JsonArray>(JsonArray()))); } TEST_P(ParsedJsonListValueTest, Equal_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); EXPECT_THAT(valid_value.Equal(value_manager(), BoolValue()), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT( valid_value.Equal( value_manager(), ParsedJsonListValue( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb"))), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Equal(value_manager(), ListValue()), IsOkAndHolds(BoolValueIs(true))); } TEST_P(ParsedJsonListValueTest, Empty_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); EXPECT_TRUE(valid_value.IsEmpty()); } TEST_P(ParsedJsonListValueTest, Size_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>(R"pb()pb")); EXPECT_EQ(valid_value.Size(), 0); } TEST_P(ParsedJsonListValueTest, Get_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>( R"pb(values {} values { bool_value: true })pb")); EXPECT_THAT(valid_value.Get(value_manager(), 0), IsOkAndHolds(IsNullValue())); EXPECT_THAT(valid_value.Get(value_manager(), 1), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Get(value_manager(), 2), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_P(ParsedJsonListValueTest, ForEach_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>( R"pb(values {} values { bool_value: true })pb")); { std::vector<Value> values; EXPECT_THAT( valid_value.ForEach(value_manager(), [&](const Value& element) -> absl::StatusOr<bool> { values.push_back(element); return true; }), IsOk()); EXPECT_THAT(values, ElementsAre(IsNullValue(), BoolValueIs(true))); } { std::vector<Value> values; EXPECT_THAT(valid_value.ForEach( value_manager(), [&](size_t, const Value& element) -> absl::StatusOr<bool> { values.push_back(element); return true; }), IsOk()); EXPECT_THAT(values, ElementsAre(IsNullValue(), BoolValueIs(true))); } } TEST_P(ParsedJsonListValueTest, NewIterator_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>( R"pb(values {} values { bool_value: true })pb")); ASSERT_OK_AND_ASSIGN(auto iterator, valid_value.NewIterator(value_manager())); ASSERT_TRUE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), IsOkAndHolds(IsNullValue())); ASSERT_TRUE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), IsOkAndHolds(BoolValueIs(true))); ASSERT_FALSE(iterator->HasNext()); EXPECT_THAT(iterator->Next(value_manager()), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST_P(ParsedJsonListValueTest, Contains_Dynamic) { ParsedJsonListValue valid_value( DynamicParseTextProto<google::protobuf::ListValue>( R"pb(values {} values { bool_value: true } values { number_value: 1.0 } values { string_value: "foo" } values { list_value: {} } values { struct_value: {} })pb")); EXPECT_THAT(valid_value.Contains(value_manager(), BytesValue()), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Contains(value_manager(), NullValue()), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Contains(value_manager(), BoolValue(false)), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Contains(value_manager(), BoolValue(true)), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Contains(value_manager(), DoubleValue(0.0)), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Contains(value_manager(), DoubleValue(1.0)), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Contains(value_manager(), StringValue("bar")), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Contains(value_manager(), StringValue("foo")), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT(valid_value.Contains( value_manager(), ParsedJsonListValue( DynamicParseTextProto<google::protobuf::ListValue>( R"pb(values {} values { bool_value: true } values { number_value: 1.0 } values { string_value: "foo" } values { list_value: {} } values { struct_value: {} })pb"))), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Contains(value_manager(), ListValue()), IsOkAndHolds(BoolValueIs(true))); EXPECT_THAT( valid_value.Contains( value_manager(), ParsedJsonMapValue(DynamicParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: { bool_value: true } })pb"))), IsOkAndHolds(BoolValueIs(false))); EXPECT_THAT(valid_value.Contains(value_manager(), MapValue()), IsOkAndHolds(BoolValueIs(true))); } INSTANTIATE_TEST_SUITE_P(ParsedJsonListValueTest, ParsedJsonListValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_json_list_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_json_list_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
64b34c8c-6eb0-45a4-a04c-18182e61973a
cpp
google/cel-cpp
timestamp_value
common/values/timestamp_value.cc
common/values/timestamp_value_test.cc
#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 { namespace { std::string TimestampDebugString(absl::Time value) { return internal::DebugStringTimestamp(value); } } std::string TimestampValue::DebugString() const { return TimestampDebugString(NativeValue()); } absl::Status TimestampValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeTimestamp(NativeValue(), value); } absl::StatusOr<Json> TimestampValue::ConvertToJson(AnyToJsonConverter&) const { CEL_ASSIGN_OR_RETURN(auto json, internal::EncodeTimestampToJson(NativeValue())); return JsonString(std::move(json)); } absl::Status TimestampValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<TimestampValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValue{false}; return absl::OkStatus(); } absl::StatusOr<Value> TimestampValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>( 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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/timestamp_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/timestamp_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
9fd7364f-8a9c-4b58-8fa0-dcea8e48c78a
cpp
google/cel-cpp
type_value
common/values/type_value.cc
common/values/type_value_test.cc
#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::Status TypeValue::SerializeTo(AnyToJsonConverter&, absl::Cord&) 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&, const Value& other, Value& result) const { if (auto other_value = As<TypeValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } result = BoolValue{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 ::absl_testing::StatusIs; using ::testing::An; using ::testing::Ne; 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, SerializeTo) { absl::Cord value; EXPECT_THAT(TypeValue(AnyType()).SerializeTo(value_manager(), value), 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>(Value(TypeValue(AnyType()))), Ne(absl::nullopt)); } INSTANTIATE_TEST_SUITE_P( TypeValueTest, TypeValueTest, ::testing::Combine(::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)), TypeValueTest::ToString); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/type_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/type_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
18bfc23a-196f-4d42-a64d-c968866588d8
cpp
google/cel-cpp
int_value
common/values/int_value.cc
common/values/int_value_test.cc
#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 { namespace { std::string IntDebugString(int64_t value) { return absl::StrCat(value); } } std::string IntValue::DebugString() const { return IntDebugString(NativeValue()); } absl::Status IntValue::SerializeTo(AnyToJsonConverter&, absl::Cord& value) const { return internal::SerializeInt64Value(NativeValue(), value); } absl::StatusOr<Json> IntValue::ConvertToJson(AnyToJsonConverter&) const { return JsonInt(NativeValue()); } absl::Status IntValue::Equal(ValueManager&, const Value& other, Value& result) const { if (auto other_value = As<IntValue>(other); other_value.has_value()) { result = BoolValue{NativeValue() == other_value->NativeValue()}; return absl::OkStatus(); } if (auto other_value = As<DoubleValue>(other); other_value.has_value()) { result = BoolValue{internal::Number::FromInt64(NativeValue()) == internal::Number::FromDouble(other_value->NativeValue())}; return absl::OkStatus(); } if (auto other_value = As<UintValue>(other); other_value.has_value()) { result = BoolValue{internal::Number::FromInt64(NativeValue()) == internal::Number::FromUint64(other_value->NativeValue())}; return absl::OkStatus(); } result = BoolValue{false}; return absl::OkStatus(); } absl::StatusOr<Value> IntValue::Equal(ValueManager& value_manager, const Value& 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 ::absl_testing::IsOkAndHolds; using ::testing::An; using ::testing::Ne; 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, 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>(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); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/int_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/int_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
7cb8f19e-77cd-4976-a55e-25bc52421108
cpp
google/cel-cpp
parsed_map_field_value
common/values/parsed_map_field_value.cc
common/values/parsed_map_field_value_test.cc
#include "common/values/parsed_map_field_value.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "common/json.h" #include "common/value.h" #include "internal/status_macros.h" #include "google/protobuf/message.h" namespace cel { std::string ParsedMapFieldValue::DebugString() const { if (ABSL_PREDICT_FALSE(field_ == nullptr)) { return "INVALID"; } return "VALID"; } absl::Status ParsedMapFieldValue::SerializeTo(AnyToJsonConverter& converter, absl::Cord& value) const { return absl::UnimplementedError("SerializeTo is not yet implemented"); } absl::StatusOr<Json> ParsedMapFieldValue::ConvertToJson( AnyToJsonConverter& converter) const { return absl::UnimplementedError("ConvertToJson is not yet implemented"); } absl::StatusOr<JsonObject> ParsedMapFieldValue::ConvertToJsonObject( AnyToJsonConverter& converter) const { return absl::UnimplementedError("ConvertToJsonObject is not yet implemented"); } absl::Status ParsedMapFieldValue::Equal(ValueManager& value_manager, const Value& other, Value& result) const { return absl::UnimplementedError("Equal is not yet implemented"); } absl::StatusOr<Value> ParsedMapFieldValue::Equal(ValueManager& value_manager, const Value& other) const { Value result; CEL_RETURN_IF_ERROR(Equal(value_manager, other, result)); return result; } bool ParsedMapFieldValue::IsZeroValue() const { return IsEmpty(); } bool ParsedMapFieldValue::IsEmpty() const { return Size() == 0; } size_t ParsedMapFieldValue::Size() const { ABSL_DCHECK(*this); if (ABSL_PREDICT_FALSE(field_ == nullptr)) { return 0; } return static_cast<size_t>( GetReflectionOrDie()->FieldSize(*message_, field_)); } absl::Status ParsedMapFieldValue::Get(ValueManager& value_manager, const Value& key, Value& result) const { return absl::UnimplementedError("Get is not yet implemented"); } absl::StatusOr<Value> ParsedMapFieldValue::Get(ValueManager& value_manager, const Value& key) const { Value result; CEL_RETURN_IF_ERROR(Get(value_manager, key, result)); return result; } absl::StatusOr<bool> ParsedMapFieldValue::Find(ValueManager& value_manager, const Value& key, Value& result) const { return absl::UnimplementedError("Find is not yet implemented"); } absl::StatusOr<std::pair<Value, bool>> ParsedMapFieldValue::Find( ValueManager& value_manager, const Value& key) const { Value result; CEL_ASSIGN_OR_RETURN(auto found, Find(value_manager, key, result)); if (found) { return std::pair{std::move(result), found}; } return std::pair{NullValue(), found}; } absl::Status ParsedMapFieldValue::Has(ValueManager& value_manager, const Value& key, Value& result) const { return absl::UnimplementedError("Has is not yet implemented"); } absl::StatusOr<Value> ParsedMapFieldValue::Has(ValueManager& value_manager, const Value& key) const { Value result; CEL_RETURN_IF_ERROR(Has(value_manager, key, result)); return result; } absl::Status ParsedMapFieldValue::ListKeys(ValueManager& value_manager, ListValue& result) const { return absl::UnimplementedError("ListKeys is not yet implemented"); } absl::StatusOr<ListValue> ParsedMapFieldValue::ListKeys( ValueManager& value_manager) const { ListValue result; CEL_RETURN_IF_ERROR(ListKeys(value_manager, result)); return result; } absl::Status ParsedMapFieldValue::ForEach(ValueManager& value_manager, ForEachCallback callback) const { return absl::UnimplementedError("ForEach is not yet implemented"); } absl::StatusOr<absl::Nonnull<std::unique_ptr<ValueIterator>>> ParsedMapFieldValue::NewIterator(ValueManager& value_manager) const { return absl::UnimplementedError("NewIterator is not yet implemented"); } absl::Nonnull<const google::protobuf::Reflection*> ParsedMapFieldValue::GetReflectionOrDie() const { return ABSL_DIE_IF_NULL(message_->GetReflection()); } }
#include "absl/base/nullability.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_manager.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.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 cel { namespace { using ::absl_testing::StatusIs; using ::cel::internal::DynamicParseTextProto; using ::cel::internal::GetTestingDescriptorPool; using ::cel::internal::GetTestingMessageFactory; using ::testing::_; using ::testing::PrintToStringParamName; using ::testing::TestWithParam; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; class ParsedMapFieldValueTest : public TestWithParam<AllocatorKind> { public: void SetUp() override { switch (GetParam()) { case AllocatorKind::kArena: arena_.emplace(); value_manager_ = NewThreadCompatibleValueManager( MemoryManager::Pooling(arena()), NewThreadCompatibleTypeReflector(MemoryManager::Pooling(arena()))); break; case AllocatorKind::kNewDelete: value_manager_ = NewThreadCompatibleValueManager( MemoryManager::ReferenceCounting(), NewThreadCompatibleTypeReflector( MemoryManager::ReferenceCounting())); break; } } void TearDown() override { value_manager_.reset(); arena_.reset(); } Allocator<> allocator() { return arena_ ? ArenaAllocator(&*arena_) : NewDeleteAllocator(); } absl::Nullable<google::protobuf::Arena*> arena() { return allocator().arena(); } absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() { return GetTestingDescriptorPool(); } absl::Nonnull<google::protobuf::MessageFactory*> message_factory() { return GetTestingMessageFactory(); } ValueManager& value_manager() { return **value_manager_; } private: absl::optional<google::protobuf::Arena> arena_; absl::optional<Shared<ValueManager>> value_manager_; }; TEST_P(ParsedMapFieldValueTest, Default) { ParsedMapFieldValue value; EXPECT_FALSE(value); } TEST_P(ParsedMapFieldValueTest, Field) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_TRUE(value); } TEST_P(ParsedMapFieldValueTest, Kind) { ParsedMapFieldValue value; EXPECT_EQ(value.kind(), ParsedMapFieldValue::kKind); EXPECT_EQ(value.kind(), ValueKind::kMap); } TEST_P(ParsedMapFieldValueTest, GetTypeName) { ParsedMapFieldValue value; EXPECT_EQ(value.GetTypeName(), ParsedMapFieldValue::kName); EXPECT_EQ(value.GetTypeName(), "map"); } TEST_P(ParsedMapFieldValueTest, GetRuntimeType) { ParsedMapFieldValue value; EXPECT_EQ(value.GetRuntimeType(), MapType()); } TEST_P(ParsedMapFieldValueTest, DebugString) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.DebugString(), _); } TEST_P(ParsedMapFieldValueTest, IsZeroValue) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_TRUE(valid_value.IsZeroValue()); } TEST_P(ParsedMapFieldValueTest, SerializeTo) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); absl::Cord serialized; EXPECT_THAT(valid_value.SerializeTo(value_manager(), serialized), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, ConvertToJson) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.ConvertToJson(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, Equal) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.Equal(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, Empty) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_TRUE(valid_value.IsEmpty()); } TEST_P(ParsedMapFieldValueTest, Size) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_EQ(valid_value.Size(), 0); } TEST_P(ParsedMapFieldValueTest, Get) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.Get(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, Find) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.Find(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, Has) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.Has(value_manager(), BoolValue()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, ListKeys) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.ListKeys(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, ForEach) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.ForEach(value_manager(), [](const Value&, const Value&) -> absl::StatusOr<bool> { return true; }), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_P(ParsedMapFieldValueTest, NewIterator) { auto message = DynamicParseTextProto<TestAllTypesProto3>( allocator(), R"pb()pb", descriptor_pool(), message_factory()); ParsedMapFieldValue valid_value( message, ABSL_DIE_IF_NULL(message->GetDescriptor()->FindFieldByName( "map_int64_int64"))); EXPECT_THAT(valid_value.NewIterator(value_manager()), StatusIs(absl::StatusCode::kUnimplemented)); } INSTANTIATE_TEST_SUITE_P(ParsedMapFieldValueTest, ParsedMapFieldValueTest, ::testing::Values(AllocatorKind::kArena, AllocatorKind::kNewDelete), PrintToStringParamName()); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_map_field_value.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/values/parsed_map_field_value_test.cc
4552db5798fb0853b131b783d8875794334fae7f
d6217abe-0e96-4cc3-9106-a8417b7ceeda
cpp
google/cel-cpp
shared_byte_string
common/internal/shared_byte_string.cc
common/internal/shared_byte_string_test.cc
#include "common/internal/shared_byte_string.h" #include <cstdint> #include <string> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/allocator.h" #include "common/internal/reference_count.h" #include "google/protobuf/arena.h" namespace cel::common_internal { SharedByteString::SharedByteString(Allocator<> allocator, absl::string_view value) : header_(false, value.size()) { if (value.empty()) { content_.string.data = ""; content_.string.refcount = 0; } else { if (auto* arena = allocator.arena(); arena != nullptr) { content_.string.data = google::protobuf::Arena::Create<std::string>(arena, value)->data(); content_.string.refcount = 0; return; } auto pair = MakeReferenceCountedString(value); content_.string.data = pair.second.data(); content_.string.refcount = reinterpret_cast<uintptr_t>(pair.first); } } SharedByteString::SharedByteString(Allocator<> allocator, const absl::Cord& value) : header_(allocator.arena() == nullptr, allocator.arena() == nullptr ? 0 : value.size()) { if (header_.is_cord) { ::new (static_cast<void*>(cord_ptr())) absl::Cord(value); } else { if (value.empty()) { content_.string.data = ""; } else { auto* string = google::protobuf::Arena::Create<std::string>(allocator.arena()); absl::CopyCordToString(value, string); content_.string.data = string->data(); } content_.string.refcount = 0; } } }
#include "common/internal/shared_byte_string.h" #include <string> #include <utility> #include "absl/hash/hash.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/internal/reference_count.h" #include "internal/testing.h" namespace cel::common_internal { namespace { using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Ne; using ::testing::Not; class OwningObject final : public ReferenceCounted { public: explicit OwningObject(std::string string) : string_(std::move(string)) {} absl::string_view owned_string() const { return string_; } private: void Finalize() noexcept override { std::string().swap(string_); } std::string string_; }; TEST(SharedByteString, DefaultConstructor) { SharedByteString byte_string; std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), IsEmpty()); EXPECT_THAT(byte_string.ToCord(), IsEmpty()); } TEST(SharedByteString, StringView) { absl::string_view string_view = "foo"; SharedByteString byte_string(string_view); std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), Not(IsEmpty())); EXPECT_THAT(byte_string.ToString(scratch).data(), Eq(string_view.data())); auto cord = byte_string.ToCord(); EXPECT_THAT(cord, Eq("foo")); EXPECT_THAT(cord.Flatten().data(), Ne(string_view.data())); } TEST(SharedByteString, OwnedStringView) { auto* const owner = new OwningObject("----------------------------------------"); { SharedByteString byte_string1(owner, owner->owned_string()); SharedByteStringView byte_string2(byte_string1); SharedByteString byte_string3(byte_string2); std::string scratch; EXPECT_THAT(byte_string3.ToString(scratch), Not(IsEmpty())); EXPECT_THAT(byte_string3.ToString(scratch).data(), Eq(owner->owned_string().data())); auto cord = byte_string3.ToCord(); EXPECT_THAT(cord, Eq(owner->owned_string())); EXPECT_THAT(cord.Flatten().data(), Eq(owner->owned_string().data())); } StrongUnref(owner); } TEST(SharedByteString, String) { SharedByteString byte_string(std::string("foo")); std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), Eq("foo")); EXPECT_THAT(byte_string.ToCord(), Eq("foo")); } TEST(SharedByteString, Cord) { SharedByteString byte_string(absl::Cord("foo")); std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), Eq("foo")); EXPECT_THAT(byte_string.ToCord(), Eq("foo")); } TEST(SharedByteString, CopyConstruct) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(std::string("bar")); SharedByteString byte_string3(absl::Cord("baz")); EXPECT_THAT(SharedByteString(byte_string1).ToString(), byte_string1.ToString()); EXPECT_THAT(SharedByteString(byte_string2).ToString(), byte_string2.ToString()); EXPECT_THAT(SharedByteString(byte_string3).ToString(), byte_string3.ToString()); } TEST(SharedByteString, MoveConstruct) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(std::string("bar")); SharedByteString byte_string3(absl::Cord("baz")); EXPECT_THAT(SharedByteString(std::move(byte_string1)).ToString(), Eq("foo")); EXPECT_THAT(SharedByteString(std::move(byte_string2)).ToString(), Eq("bar")); EXPECT_THAT(SharedByteString(std::move(byte_string3)).ToString(), Eq("baz")); } TEST(SharedByteString, CopyAssign) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(std::string("bar")); SharedByteString byte_string3(absl::Cord("baz")); SharedByteString byte_string; EXPECT_THAT((byte_string = byte_string1).ToString(), byte_string1.ToString()); EXPECT_THAT((byte_string = byte_string2).ToString(), byte_string2.ToString()); EXPECT_THAT((byte_string = byte_string3).ToString(), byte_string3.ToString()); } TEST(SharedByteString, MoveAssign) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(std::string("bar")); SharedByteString byte_string3(absl::Cord("baz")); SharedByteString byte_string; EXPECT_THAT((byte_string = std::move(byte_string1)).ToString(), Eq("foo")); EXPECT_THAT((byte_string = std::move(byte_string2)).ToString(), Eq("bar")); EXPECT_THAT((byte_string = std::move(byte_string3)).ToString(), Eq("baz")); } TEST(SharedByteString, Swap) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(std::string("bar")); SharedByteString byte_string3(absl::Cord("baz")); SharedByteString byte_string4; byte_string1.swap(byte_string2); byte_string2.swap(byte_string3); byte_string2.swap(byte_string3); byte_string2.swap(byte_string3); byte_string4 = byte_string1; byte_string1.swap(byte_string4); byte_string4 = byte_string2; byte_string2.swap(byte_string4); byte_string4 = byte_string3; byte_string3.swap(byte_string4); EXPECT_THAT(byte_string1.ToString(), Eq("bar")); EXPECT_THAT(byte_string2.ToString(), Eq("baz")); EXPECT_THAT(byte_string3.ToString(), Eq("foo")); } TEST(SharedByteString, HashValue) { EXPECT_EQ(absl::HashOf(SharedByteString(absl::string_view("foo"))), absl::HashOf(absl::string_view("foo"))); EXPECT_EQ(absl::HashOf(SharedByteString(absl::Cord("foo"))), absl::HashOf(absl::Cord("foo"))); } TEST(SharedByteString, Equality) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(absl::string_view("bar")); SharedByteString byte_string3(absl::Cord("baz")); SharedByteString byte_string4(absl::Cord("qux")); EXPECT_NE(byte_string1, byte_string2); EXPECT_NE(byte_string2, byte_string1); EXPECT_NE(byte_string1, byte_string3); EXPECT_NE(byte_string3, byte_string1); EXPECT_NE(byte_string1, byte_string4); EXPECT_NE(byte_string4, byte_string1); EXPECT_NE(byte_string2, byte_string3); EXPECT_NE(byte_string3, byte_string2); EXPECT_NE(byte_string3, byte_string4); EXPECT_NE(byte_string4, byte_string3); } TEST(SharedByteString, LessThan) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(absl::string_view("baz")); SharedByteString byte_string3(absl::Cord("bar")); SharedByteString byte_string4(absl::Cord("qux")); EXPECT_LT(byte_string2, byte_string1); EXPECT_LT(byte_string1, byte_string4); EXPECT_LT(byte_string3, byte_string4); EXPECT_LT(byte_string3, byte_string2); } TEST(SharedByteString, SharedByteStringView) { SharedByteString byte_string1(absl::string_view("foo")); SharedByteString byte_string2(std::string("bar")); SharedByteString byte_string3(absl::Cord("baz")); EXPECT_THAT(SharedByteStringView(byte_string1).ToString(), Eq("foo")); EXPECT_THAT(SharedByteStringView(byte_string2).ToString(), Eq("bar")); EXPECT_THAT(SharedByteStringView(byte_string3).ToString(), Eq("baz")); } TEST(SharedByteStringView, DefaultConstructor) { SharedByteStringView byte_string; std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), IsEmpty()); EXPECT_THAT(byte_string.ToCord(), IsEmpty()); } TEST(SharedByteStringView, StringView) { absl::string_view string_view = "foo"; SharedByteStringView byte_string(string_view); std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), Not(IsEmpty())); EXPECT_THAT(byte_string.ToString(scratch).data(), Eq(string_view.data())); auto cord = byte_string.ToCord(); EXPECT_THAT(cord, Eq("foo")); EXPECT_THAT(cord.Flatten().data(), Ne(string_view.data())); } TEST(SharedByteStringView, OwnedStringView) { auto* const owner = new OwningObject("----------------------------------------"); { SharedByteString byte_string1(owner, owner->owned_string()); SharedByteStringView byte_string2(byte_string1); std::string scratch; EXPECT_THAT(byte_string2.ToString(scratch), Not(IsEmpty())); EXPECT_THAT(byte_string2.ToString(scratch).data(), Eq(owner->owned_string().data())); auto cord = byte_string2.ToCord(); EXPECT_THAT(cord, Eq(owner->owned_string())); EXPECT_THAT(cord.Flatten().data(), Eq(owner->owned_string().data())); } StrongUnref(owner); } TEST(SharedByteStringView, String) { std::string string("foo"); SharedByteStringView byte_string(string); std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), Eq("foo")); EXPECT_THAT(byte_string.ToCord(), Eq("foo")); } TEST(SharedByteStringView, Cord) { absl::Cord cord("foo"); SharedByteStringView byte_string(cord); std::string scratch; EXPECT_THAT(byte_string.ToString(scratch), Eq("foo")); EXPECT_THAT(byte_string.ToCord(), Eq("foo")); } TEST(SharedByteStringView, CopyConstruct) { std::string string("bar"); absl::Cord cord("baz"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(string); SharedByteStringView byte_string3(cord); EXPECT_THAT(SharedByteString(byte_string1).ToString(), byte_string1.ToString()); EXPECT_THAT(SharedByteString(byte_string2).ToString(), byte_string2.ToString()); EXPECT_THAT(SharedByteString(byte_string3).ToString(), byte_string3.ToString()); } TEST(SharedByteStringView, MoveConstruct) { std::string string("bar"); absl::Cord cord("baz"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(string); SharedByteStringView byte_string3(cord); EXPECT_THAT(SharedByteString(std::move(byte_string1)).ToString(), Eq("foo")); EXPECT_THAT(SharedByteString(std::move(byte_string2)).ToString(), Eq("bar")); EXPECT_THAT(SharedByteString(std::move(byte_string3)).ToString(), Eq("baz")); } TEST(SharedByteStringView, CopyAssign) { std::string string("bar"); absl::Cord cord("baz"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(string); SharedByteStringView byte_string3(cord); SharedByteStringView byte_string; EXPECT_THAT((byte_string = byte_string1).ToString(), byte_string1.ToString()); EXPECT_THAT((byte_string = byte_string2).ToString(), byte_string2.ToString()); EXPECT_THAT((byte_string = byte_string3).ToString(), byte_string3.ToString()); } TEST(SharedByteStringView, MoveAssign) { std::string string("bar"); absl::Cord cord("baz"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(string); SharedByteStringView byte_string3(cord); SharedByteStringView byte_string; EXPECT_THAT((byte_string = std::move(byte_string1)).ToString(), Eq("foo")); EXPECT_THAT((byte_string = std::move(byte_string2)).ToString(), Eq("bar")); EXPECT_THAT((byte_string = std::move(byte_string3)).ToString(), Eq("baz")); } TEST(SharedByteStringView, Swap) { std::string string("bar"); absl::Cord cord("baz"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(string); SharedByteStringView byte_string3(cord); byte_string1.swap(byte_string2); byte_string2.swap(byte_string3); EXPECT_THAT(byte_string1.ToString(), Eq("bar")); EXPECT_THAT(byte_string2.ToString(), Eq("baz")); EXPECT_THAT(byte_string3.ToString(), Eq("foo")); } TEST(SharedByteStringView, HashValue) { absl::Cord cord("foo"); EXPECT_EQ(absl::HashOf(SharedByteStringView(absl::string_view("foo"))), absl::HashOf(absl::string_view("foo"))); EXPECT_EQ(absl::HashOf(SharedByteStringView(cord)), absl::HashOf(cord)); } TEST(SharedByteStringView, Equality) { absl::Cord cord1("baz"); absl::Cord cord2("qux"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(absl::string_view("bar")); SharedByteStringView byte_string3(cord1); SharedByteStringView byte_string4(cord2); EXPECT_NE(byte_string1, byte_string2); EXPECT_NE(byte_string2, byte_string1); EXPECT_NE(byte_string1, byte_string3); EXPECT_NE(byte_string3, byte_string1); EXPECT_NE(byte_string1, byte_string4); EXPECT_NE(byte_string4, byte_string1); EXPECT_NE(byte_string2, byte_string3); EXPECT_NE(byte_string3, byte_string2); EXPECT_NE(byte_string3, byte_string4); EXPECT_NE(byte_string4, byte_string3); } TEST(SharedByteStringView, LessThan) { absl::Cord cord1("bar"); absl::Cord cord2("qux"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(absl::string_view("baz")); SharedByteStringView byte_string3(cord1); SharedByteStringView byte_string4(cord2); EXPECT_LT(byte_string2, byte_string1); EXPECT_LT(byte_string1, byte_string4); EXPECT_LT(byte_string3, byte_string4); EXPECT_LT(byte_string3, byte_string2); } TEST(SharedByteStringView, SharedByteString) { std::string string("bar"); absl::Cord cord("baz"); SharedByteStringView byte_string1(absl::string_view("foo")); SharedByteStringView byte_string2(string); SharedByteStringView byte_string3(cord); EXPECT_THAT(SharedByteString(byte_string1).ToString(), Eq("foo")); EXPECT_THAT(SharedByteString(byte_string2).ToString(), Eq("bar")); EXPECT_THAT(SharedByteString(byte_string3).ToString(), Eq("baz")); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/shared_byte_string.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/shared_byte_string_test.cc
4552db5798fb0853b131b783d8875794334fae7f
6406a445-254d-4325-a6b3-b18337092254
cpp
google/cel-cpp
byte_string
common/internal/byte_string.cc
common/internal/byte_string_test.cc
#include "common/internal/byte_string.h" #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include <tuple> #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 "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; } 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(std::move(owner)); if (refcount == nullptr) { std::tie(refcount, string) = MakeReferenceCountedString(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 GetSmall(); case ByteStringKind::kMedium: return GetMedium(); case ByteStringKind::kLarge: { const auto& large = GetLarge(); if (auto flat = large.TryFlat(); flat) { return *flat; } scratch = static_cast<std::string>(large); return scratch; } } } void ByteString::RemovePrefix(size_t n) { ABSL_DCHECK_LE(n, size()); if (n == 0) { return; } switch (GetKind()) { case ByteStringKind::kSmall: std::memmove(rep_.small.data, rep_.small.data + n, rep_.small.size - n); rep_.small.size -= n; break; case ByteStringKind::kMedium: rep_.medium.data += n; rep_.medium.size -= n; if (rep_.medium.size <= kSmallByteStringCapacity) { const auto* refcount = GetMediumReferenceCount(); SetSmall(GetMediumArena(), GetMedium()); StrongUnref(refcount); } break; case ByteStringKind::kLarge: { auto& large = GetLarge(); const auto large_size = large.size(); const auto new_large_pos = n; const auto new_large_size = large_size - n; large = large.Subcord(new_large_pos, new_large_size); if (new_large_size <= kSmallByteStringCapacity) { auto large_copy = std::move(large); DestroyLarge(); SetSmall(nullptr, large_copy); } } break; } } void ByteString::RemoveSuffix(size_t n) { ABSL_DCHECK_LE(n, size()); if (n == 0) { return; } switch (GetKind()) { case ByteStringKind::kSmall: rep_.small.size -= n; break; case ByteStringKind::kMedium: rep_.medium.size -= n; if (rep_.medium.size <= kSmallByteStringCapacity) { const auto* refcount = GetMediumReferenceCount(); SetSmall(GetMediumArena(), GetMedium()); StrongUnref(refcount); } break; case ByteStringKind::kLarge: { auto& large = GetLarge(); const auto large_size = large.size(); const auto new_large_pos = 0; const auto new_large_size = large_size - n; large = large.Subcord(new_large_pos, new_large_size); if (new_large_size <= kSmallByteStringCapacity) { auto large_copy = std::move(large); DestroyLarge(); SetSmall(nullptr, large_copy); } } break; } } std::string ByteString::ToString() const { switch (GetKind()) { case ByteStringKind::kSmall: return std::string(GetSmall()); case ByteStringKind::kMedium: return std::string(GetMedium()); case ByteStringKind::kLarge: return static_cast<std::string>(GetLarge()); } } namespace { struct ReferenceCountReleaser { absl::Nonnull<const ReferenceCount*> refcount; void operator()() const noexcept { StrongUnref(*refcount); } }; } absl::Cord ByteString::ToCord() const& { switch (GetKind()) { case ByteStringKind::kSmall: return absl::Cord(GetSmall()); case ByteStringKind::kMedium: { const auto* refcount = GetMediumReferenceCount(); if (refcount != nullptr) { StrongRef(*refcount); return absl::MakeCordFromExternal(GetMedium(), ReferenceCountReleaser{refcount}); } return absl::Cord(GetMedium()); } case ByteStringKind::kLarge: return GetLarge(); } } absl::Cord ByteString::ToCord() && { switch (GetKind()) { case ByteStringKind::kSmall: return absl::Cord(GetSmall()); case ByteStringKind::kMedium: { const auto* refcount = GetMediumReferenceCount(); if (refcount != nullptr) { auto medium = GetMedium(); SetSmallEmpty(nullptr); return absl::MakeCordFromExternal(medium, ReferenceCountReleaser{refcount}); } return absl::Cord(GetMedium()); } case ByteStringKind::kLarge: return GetLarge(); } } absl::Nullable<google::protobuf::Arena*> ByteString::GetMediumArena( const MediumByteStringRep& rep) noexcept { if ((rep.owner & kMetadataOwnerBits) == kMetadataOwnerArenaBit) { return reinterpret_cast<google::protobuf::Arena*>(rep.owner & kMetadataOwnerPointerMask); } return nullptr; } absl::Nullable<const ReferenceCount*> ByteString::GetMediumReferenceCount( const MediumByteStringRep& rep) noexcept { if ((rep.owner & kMetadataOwnerBits) == kMetadataOwnerReferenceCountBit) { return reinterpret_cast<const ReferenceCount*>(rep.owner & kMetadataOwnerPointerMask); } return nullptr; } void ByteString::CopyFrom(const ByteString& other) { const auto kind = GetKind(); const auto other_kind = other.GetKind(); switch (kind) { case ByteStringKind::kSmall: switch (other_kind) { case ByteStringKind::kSmall: CopyFromSmallSmall(other); break; case ByteStringKind::kMedium: CopyFromSmallMedium(other); break; case ByteStringKind::kLarge: CopyFromSmallLarge(other); break; } break; case ByteStringKind::kMedium: switch (other_kind) { case ByteStringKind::kSmall: CopyFromMediumSmall(other); break; case ByteStringKind::kMedium: CopyFromMediumMedium(other); break; case ByteStringKind::kLarge: CopyFromMediumLarge(other); break; } break; case ByteStringKind::kLarge: switch (other_kind) { case ByteStringKind::kSmall: CopyFromLargeSmall(other); break; case ByteStringKind::kMedium: CopyFromLargeMedium(other); break; case ByteStringKind::kLarge: CopyFromLargeLarge(other); break; } break; } } void ByteString::CopyFromSmallSmall(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kSmall); rep_.small.size = other.rep_.small.size; std::memcpy(rep_.small.data, other.rep_.small.data, rep_.small.size); } void ByteString::CopyFromSmallMedium(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kMedium); SetMedium(GetSmallArena(), other.GetMedium()); } void ByteString::CopyFromSmallLarge(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kLarge); SetMediumOrLarge(GetSmallArena(), other.GetLarge()); } void ByteString::CopyFromMediumSmall(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kSmall); auto* arena = GetMediumArena(); if (arena == nullptr) { DestroyMedium(); } SetSmall(arena, other.GetSmall()); } void ByteString::CopyFromMediumMedium(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kMedium); auto* arena = GetMediumArena(); auto* other_arena = other.GetMediumArena(); if (arena == other_arena) { if (other_arena == nullptr) { StrongRef(other.GetMediumReferenceCount()); } if (arena == nullptr) { StrongUnref(GetMediumReferenceCount()); } SetMedium(other.GetMedium(), other.GetMediumOwner()); } else { DestroyMedium(); SetMedium(arena, other.GetMedium()); } } void ByteString::CopyFromMediumLarge(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kLarge); auto* arena = GetMediumArena(); if (arena == nullptr) { DestroyMedium(); SetLarge(std::move(other.GetLarge())); } else { SetMedium(arena, other.GetLarge()); } } void ByteString::CopyFromLargeSmall(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kSmall); DestroyLarge(); SetSmall(nullptr, other.GetSmall()); } void ByteString::CopyFromLargeMedium(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kMedium); const auto* refcount = other.GetMediumReferenceCount(); if (refcount != nullptr) { StrongRef(*refcount); DestroyLarge(); SetMedium(other.GetMedium(), other.GetMediumOwner()); } else { GetLarge() = other.GetMedium(); } } void ByteString::CopyFromLargeLarge(const ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kLarge); GetLarge() = std::move(other.GetLarge()); } void ByteString::CopyFrom(ByteStringView other) { const auto kind = GetKind(); const auto other_kind = other.GetKind(); switch (kind) { case ByteStringKind::kSmall: switch (other_kind) { case ByteStringViewKind::kString: CopyFromSmallString(other); break; case ByteStringViewKind::kCord: CopyFromSmallCord(other); break; } break; case ByteStringKind::kMedium: switch (other_kind) { case ByteStringViewKind::kString: CopyFromMediumString(other); break; case ByteStringViewKind::kCord: CopyFromMediumCord(other); break; } break; case ByteStringKind::kLarge: switch (other_kind) { case ByteStringViewKind::kString: CopyFromLargeString(other); break; case ByteStringViewKind::kCord: CopyFromLargeCord(other); break; } break; } } void ByteString::CopyFromSmallString(ByteStringView other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringViewKind::kString); auto* arena = GetSmallArena(); const auto other_string = other.GetString(); if (other_string.size() <= kSmallByteStringCapacity) { SetSmall(arena, other_string); } else { SetMedium(arena, other_string); } } void ByteString::CopyFromSmallCord(ByteStringView other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringViewKind::kCord); auto* arena = GetSmallArena(); auto other_cord = other.GetSubcord(); if (other_cord.size() <= kSmallByteStringCapacity) { SetSmall(arena, other_cord); } else { SetMediumOrLarge(arena, std::move(other_cord)); } } void ByteString::CopyFromMediumString(ByteStringView other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringViewKind::kString); auto* arena = GetMediumArena(); const auto other_string = other.GetString(); if (other_string.size() <= kSmallByteStringCapacity) { DestroyMedium(); SetSmall(arena, other_string); return; } auto* other_arena = other.GetStringArena(); if (arena == other_arena) { if (other_arena == nullptr) { StrongRef(other.GetStringReferenceCount()); } if (arena == nullptr) { StrongUnref(GetMediumReferenceCount()); } SetMedium(other_string, other.GetStringOwner()); } else { DestroyMedium(); SetMedium(arena, other_string); } } void ByteString::CopyFromMediumCord(ByteStringView other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringViewKind::kCord); auto* arena = GetMediumArena(); auto other_cord = other.GetSubcord(); DestroyMedium(); if (other_cord.size() <= kSmallByteStringCapacity) { SetSmall(arena, other_cord); } else { SetMediumOrLarge(arena, std::move(other_cord)); } } void ByteString::CopyFromLargeString(ByteStringView other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringViewKind::kString); const auto other_string = other.GetString(); if (other_string.size() <= kSmallByteStringCapacity) { DestroyLarge(); SetSmall(nullptr, other_string); return; } auto* other_arena = other.GetStringArena(); if (other_arena == nullptr) { const auto* refcount = other.GetStringReferenceCount(); if (refcount != nullptr) { StrongRef(*refcount); DestroyLarge(); SetMedium(other_string, other.GetStringOwner()); return; } } GetLarge() = other_string; } void ByteString::CopyFromLargeCord(ByteStringView other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringViewKind::kCord); auto cord = other.GetSubcord(); if (cord.size() <= kSmallByteStringCapacity) { DestroyLarge(); SetSmall(nullptr, cord); } else { GetLarge() = std::move(cord); } } void ByteString::MoveFrom(ByteString& other) { const auto kind = GetKind(); const auto other_kind = other.GetKind(); switch (kind) { case ByteStringKind::kSmall: switch (other_kind) { case ByteStringKind::kSmall: MoveFromSmallSmall(other); break; case ByteStringKind::kMedium: MoveFromSmallMedium(other); break; case ByteStringKind::kLarge: MoveFromSmallLarge(other); break; } break; case ByteStringKind::kMedium: switch (other_kind) { case ByteStringKind::kSmall: MoveFromMediumSmall(other); break; case ByteStringKind::kMedium: MoveFromMediumMedium(other); break; case ByteStringKind::kLarge: MoveFromMediumLarge(other); break; } break; case ByteStringKind::kLarge: switch (other_kind) { case ByteStringKind::kSmall: MoveFromLargeSmall(other); break; case ByteStringKind::kMedium: MoveFromLargeMedium(other); break; case ByteStringKind::kLarge: MoveFromLargeLarge(other); break; } break; } } void ByteString::MoveFromSmallSmall(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kSmall); rep_.small.size = other.rep_.small.size; std::memcpy(rep_.small.data, other.rep_.small.data, rep_.small.size); other.SetSmallEmpty(other.GetSmallArena()); } void ByteString::MoveFromSmallMedium(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kMedium); auto* arena = GetSmallArena(); auto* other_arena = other.GetMediumArena(); if (arena == other_arena) { SetMedium(other.GetMedium(), other.GetMediumOwner()); } else { SetMedium(arena, other.GetMedium()); other.DestroyMedium(); } other.SetSmallEmpty(other_arena); } void ByteString::MoveFromSmallLarge(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kLarge); auto* arena = GetSmallArena(); if (arena == nullptr) { SetLarge(std::move(other.GetLarge())); } else { SetMediumOrLarge(arena, other.GetLarge()); } other.DestroyLarge(); other.SetSmallEmpty(nullptr); } void ByteString::MoveFromMediumSmall(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kSmall); auto* arena = GetMediumArena(); auto* other_arena = other.GetSmallArena(); if (arena == nullptr) { DestroyMedium(); } SetSmall(arena, other.GetSmall()); other.SetSmallEmpty(other_arena); } void ByteString::MoveFromMediumMedium(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kMedium); auto* arena = GetMediumArena(); auto* other_arena = other.GetMediumArena(); DestroyMedium(); if (arena == other_arena) { SetMedium(other.GetMedium(), other.GetMediumOwner()); } else { SetMedium(arena, other.GetMedium()); other.DestroyMedium(); } other.SetSmallEmpty(other_arena); } void ByteString::MoveFromMediumLarge(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kLarge); auto* arena = GetMediumArena(); DestroyMedium(); SetMediumOrLarge(arena, std::move(other.GetLarge())); other.DestroyLarge(); other.SetSmallEmpty(nullptr); } void ByteString::MoveFromLargeSmall(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kSmall); auto* other_arena = other.GetSmallArena(); DestroyLarge(); SetSmall(nullptr, other.GetSmall()); other.SetSmallEmpty(other_arena); } void ByteString::MoveFromLargeMedium(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kMedium); auto* other_arena = other.GetMediumArena(); if (other_arena == nullptr) { DestroyLarge(); SetMedium(other.GetMedium(), other.GetMediumOwner()); } else { GetLarge() = other.GetMedium(); other.DestroyMedium(); } other.SetSmallEmpty(other_arena); } void ByteString::MoveFromLargeLarge(ByteString& other) { ABSL_DCHECK_EQ(GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(other.GetKind(), ByteStringKind::kLarge); GetLarge() = ConsumeAndDestroy(other.GetLarge()); other.SetSmallEmpty(nullptr); } void ByteString::HashValue(absl::HashState state) const { Visit(absl::Overload( [&state](absl::string_view string) { absl::HashState::combine(std::move(state), string); }, [&state](const absl::Cord& cord) { absl::HashState::combine(std::move(state), cord); })); } void ByteString::Swap(ByteString& other) { const auto kind = GetKind(); const auto other_kind = other.GetKind(); switch (kind) { case ByteStringKind::kSmall: switch (other_kind) { case ByteStringKind::kSmall: SwapSmallSmall(*this, other); break; case ByteStringKind::kMedium: SwapSmallMedium(*this, other); break; case ByteStringKind::kLarge: SwapSmallLarge(*this, other); break; } break; case ByteStringKind::kMedium: switch (other_kind) { case ByteStringKind::kSmall: SwapSmallMedium(other, *this); break; case ByteStringKind::kMedium: SwapMediumMedium(*this, other); break; case ByteStringKind::kLarge: SwapMediumLarge(*this, other); break; } break; case ByteStringKind::kLarge: switch (other_kind) { case ByteStringKind::kSmall: SwapSmallLarge(other, *this); break; case ByteStringKind::kMedium: SwapMediumLarge(other, *this); break; case ByteStringKind::kLarge: SwapLargeLarge(*this, other); break; } break; } } void ByteString::Destroy() noexcept { switch (GetKind()) { case ByteStringKind::kSmall: break; case ByteStringKind::kMedium: DestroyMedium(); break; case ByteStringKind::kLarge: DestroyLarge(); break; } } void ByteString::SetSmallEmpty(absl::Nullable<google::protobuf::Arena*> arena) { rep_.header.kind = ByteStringKind::kSmall; rep_.small.size = 0; rep_.small.arena = arena; } void ByteString::SetSmall(absl::Nullable<google::protobuf::Arena*> arena, absl::string_view string) { ABSL_DCHECK_LE(string.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kSmall; rep_.small.size = string.size(); rep_.small.arena = arena; std::memcpy(rep_.small.data, string.data(), rep_.small.size); } void ByteString::SetSmall(absl::Nullable<google::protobuf::Arena*> arena, const absl::Cord& cord) { ABSL_DCHECK_LE(cord.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kSmall; rep_.small.size = cord.size(); rep_.small.arena = arena; (CopyCordToArray)(cord, rep_.small.data); } void ByteString::SetMedium(absl::Nullable<google::protobuf::Arena*> arena, absl::string_view string) { ABSL_DCHECK_GT(string.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kMedium; rep_.medium.size = string.size(); if (arena != nullptr) { char* data = static_cast<char*>( arena->AllocateAligned(rep_.medium.size, alignof(char))); std::memcpy(data, string.data(), rep_.medium.size); rep_.medium.data = data; rep_.medium.owner = reinterpret_cast<uintptr_t>(arena) | kMetadataOwnerArenaBit; } else { auto pair = MakeReferenceCountedString(string); rep_.medium.data = pair.second.data(); rep_.medium.owner = reinterpret_cast<uintptr_t>(pair.first) | kMetadataOwnerReferenceCountBit; } } void ByteString::SetMedium(absl::Nullable<google::protobuf::Arena*> arena, std::string&& string) { ABSL_DCHECK_GT(string.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kMedium; rep_.medium.size = string.size(); if (arena != nullptr) { auto* data = google::protobuf::Arena::Create<std::string>(arena, std::move(string)); rep_.medium.data = data->data(); rep_.medium.owner = reinterpret_cast<uintptr_t>(arena) | kMetadataOwnerArenaBit; } else { auto pair = MakeReferenceCountedString(std::move(string)); rep_.medium.data = pair.second.data(); rep_.medium.owner = reinterpret_cast<uintptr_t>(pair.first) | kMetadataOwnerReferenceCountBit; } } void ByteString::SetMedium(absl::Nonnull<google::protobuf::Arena*> arena, const absl::Cord& cord) { ABSL_DCHECK_GT(cord.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kMedium; rep_.medium.size = cord.size(); char* data = static_cast<char*>( arena->AllocateAligned(rep_.medium.size, alignof(char))); (CopyCordToArray)(cord, data); rep_.medium.data = data; rep_.medium.owner = reinterpret_cast<uintptr_t>(arena) | kMetadataOwnerArenaBit; } void ByteString::SetMedium(absl::string_view string, uintptr_t owner) { ABSL_DCHECK_GT(string.size(), kSmallByteStringCapacity); ABSL_DCHECK_NE(owner, 0); rep_.header.kind = ByteStringKind::kMedium; rep_.medium.size = string.size(); rep_.medium.data = string.data(); rep_.medium.owner = owner; } void ByteString::SetMediumOrLarge(absl::Nullable<google::protobuf::Arena*> arena, const absl::Cord& cord) { if (arena != nullptr) { SetMedium(arena, cord); } else { SetLarge(cord); } } void ByteString::SetMediumOrLarge(absl::Nullable<google::protobuf::Arena*> arena, absl::Cord&& cord) { if (arena != nullptr) { SetMedium(arena, cord); } else { SetLarge(std::move(cord)); } } void ByteString::SetLarge(const absl::Cord& cord) { ABSL_DCHECK_GT(cord.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kLarge; ::new (static_cast<void*>(&rep_.large.data[0])) absl::Cord(cord); } void ByteString::SetLarge(absl::Cord&& cord) { ABSL_DCHECK_GT(cord.size(), kSmallByteStringCapacity); rep_.header.kind = ByteStringKind::kLarge; ::new (static_cast<void*>(&rep_.large.data[0])) absl::Cord(std::move(cord)); } void ByteString::SwapSmallSmall(ByteString& lhs, ByteString& rhs) { using std::swap; ABSL_DCHECK_EQ(lhs.GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(rhs.GetKind(), ByteStringKind::kSmall); const auto size = lhs.rep_.small.size; lhs.rep_.small.size = rhs.rep_.small.size; rhs.rep_.small.size = size; swap(lhs.rep_.small.data, rhs.rep_.small.data); } void ByteString::SwapSmallMedium(ByteString& lhs, ByteString& rhs) { ABSL_DCHECK_EQ(lhs.GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(rhs.GetKind(), ByteStringKind::kMedium); auto* lhs_arena = lhs.GetSmallArena(); auto* rhs_arena = rhs.GetMediumArena(); if (lhs_arena == rhs_arena) { SmallByteStringRep lhs_rep = lhs.rep_.small; lhs.rep_.medium = rhs.rep_.medium; rhs.rep_.small = lhs_rep; } else { SmallByteStringRep small = lhs.rep_.small; lhs.SetMedium(lhs_arena, rhs.GetMedium()); rhs.DestroyMedium(); rhs.SetSmall(rhs_arena, GetSmall(small)); } } void ByteString::SwapSmallLarge(ByteString& lhs, ByteString& rhs) { ABSL_DCHECK_EQ(lhs.GetKind(), ByteStringKind::kSmall); ABSL_DCHECK_EQ(rhs.GetKind(), ByteStringKind::kLarge); auto* lhs_arena = lhs.GetSmallArena(); absl::Cord large = std::move(rhs.GetLarge()); rhs.DestroyLarge(); rhs.rep_.small = lhs.rep_.small; if (lhs_arena == nullptr) { lhs.SetLarge(std::move(large)); } else { rhs.rep_.small.arena = nullptr; lhs.SetMedium(lhs_arena, large); } } void ByteString::SwapMediumMedium(ByteString& lhs, ByteString& rhs) { using std::swap; ABSL_DCHECK_EQ(lhs.GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(rhs.GetKind(), ByteStringKind::kMedium); auto* lhs_arena = lhs.GetMediumArena(); auto* rhs_arena = rhs.GetMediumArena(); if (lhs_arena == rhs_arena) { swap(lhs.rep_.medium, rhs.rep_.medium); } else { MediumByteStringRep medium = lhs.rep_.medium; lhs.SetMedium(lhs_arena, rhs.GetMedium()); rhs.DestroyMedium(); rhs.SetMedium(rhs_arena, GetMedium(medium)); DestroyMedium(medium); } } void ByteString::SwapMediumLarge(ByteString& lhs, ByteString& rhs) { ABSL_DCHECK_EQ(lhs.GetKind(), ByteStringKind::kMedium); ABSL_DCHECK_EQ(rhs.GetKind(), ByteStringKind::kLarge); auto* lhs_arena = lhs.GetMediumArena(); absl::Cord large = std::move(rhs.GetLarge()); rhs.DestroyLarge(); if (lhs_arena == nullptr) { rhs.rep_.medium = lhs.rep_.medium; lhs.SetLarge(std::move(large)); } else { rhs.SetMedium(nullptr, lhs.GetMedium()); lhs.SetMedium(lhs_arena, std::move(large)); } } void ByteString::SwapLargeLarge(ByteString& lhs, ByteString& rhs) { using std::swap; ABSL_DCHECK_EQ(lhs.GetKind(), ByteStringKind::kLarge); ABSL_DCHECK_EQ(rhs.GetKind(), ByteStringKind::kLarge); swap(lhs.GetLarge(), rhs.GetLarge()); } ByteStringView::ByteStringView(const ByteString& other) noexcept { switch (other.GetKind()) { case ByteStringKind::kSmall: { auto* other_arena = other.GetSmallArena(); const auto string = other.GetSmall(); rep_.header.kind = ByteStringViewKind::kString; rep_.string.size = string.size(); rep_.string.data = string.data(); if (other_arena != nullptr) { rep_.string.owner = reinterpret_cast<uintptr_t>(other_arena) | kMetadataOwnerArenaBit; } else { rep_.string.owner = 0; } } break; case ByteStringKind::kMedium: { const auto string = other.GetMedium(); rep_.header.kind = ByteStringViewKind::kString; rep_.string.size = string.size(); rep_.string.data = string.data(); rep_.string.owner = other.GetMediumOwner(); } break; case ByteStringKind::kLarge: { const auto& cord = other.GetLarge(); rep_.header.kind = ByteStringViewKind::kCord; rep_.cord.size = cord.size(); rep_.cord.data = &cord; rep_.cord.pos = 0; } break; } } bool ByteStringView::empty() const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: return rep_.string.size == 0; case ByteStringViewKind::kCord: return rep_.cord.size == 0; } } size_t ByteStringView::size() const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: return rep_.string.size; case ByteStringViewKind::kCord: return rep_.cord.size; } } absl::optional<absl::string_view> ByteStringView::TryFlat() const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: return GetString(); case ByteStringViewKind::kCord: if (auto flat = GetCord().TryFlat(); flat) { return flat->substr(rep_.cord.pos, rep_.cord.size); } return absl::nullopt; } } absl::string_view ByteStringView::GetFlat(std::string& scratch) const { switch (GetKind()) { case ByteStringViewKind::kString: return GetString(); case ByteStringViewKind::kCord: { if (auto flat = GetCord().TryFlat(); flat) { return flat->substr(rep_.cord.pos, rep_.cord.size); } scratch = static_cast<std::string>(GetSubcord()); return scratch; } } } bool ByteStringView::Equals(ByteStringView rhs) const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return GetString() == rhs.GetString(); case ByteStringViewKind::kCord: return GetString() == rhs.GetSubcord(); } case ByteStringViewKind::kCord: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return GetSubcord() == rhs.GetString(); case ByteStringViewKind::kCord: return GetSubcord() == rhs.GetSubcord(); } } } int ByteStringView::Compare(ByteStringView rhs) const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return GetString().compare(rhs.GetString()); case ByteStringViewKind::kCord: return -rhs.GetSubcord().Compare(GetString()); } case ByteStringViewKind::kCord: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return GetSubcord().Compare(rhs.GetString()); case ByteStringViewKind::kCord: return GetSubcord().Compare(rhs.GetSubcord()); } } } bool ByteStringView::StartsWith(ByteStringView rhs) const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return absl::StartsWith(GetString(), rhs.GetString()); case ByteStringViewKind::kCord: { const auto string = GetString(); const auto& cord = rhs.GetSubcord(); const auto cord_size = cord.size(); return string.size() >= cord_size && string.substr(0, cord_size) == cord; } } case ByteStringViewKind::kCord: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return GetSubcord().StartsWith(rhs.GetString()); case ByteStringViewKind::kCord: return GetSubcord().StartsWith(rhs.GetSubcord()); } } } bool ByteStringView::EndsWith(ByteStringView rhs) const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return absl::EndsWith(GetString(), rhs.GetString()); case ByteStringViewKind::kCord: { const auto string = GetString(); const auto& cord = rhs.GetSubcord(); const auto string_size = string.size(); const auto cord_size = cord.size(); return string_size >= cord_size && string.substr(string_size - cord_size) == cord; } } case ByteStringViewKind::kCord: switch (rhs.GetKind()) { case ByteStringViewKind::kString: return GetSubcord().EndsWith(rhs.GetString()); case ByteStringViewKind::kCord: return GetSubcord().EndsWith(rhs.GetSubcord()); } } } void ByteStringView::RemovePrefix(size_t n) { ABSL_DCHECK_LE(n, size()); switch (GetKind()) { case ByteStringViewKind::kString: rep_.string.data += n; break; case ByteStringViewKind::kCord: rep_.cord.pos += n; break; } rep_.header.size -= n; } void ByteStringView::RemoveSuffix(size_t n) { ABSL_DCHECK_LE(n, size()); rep_.header.size -= n; } std::string ByteStringView::ToString() const { switch (GetKind()) { case ByteStringViewKind::kString: return std::string(GetString()); case ByteStringViewKind::kCord: return static_cast<std::string>(GetSubcord()); } } absl::Cord ByteStringView::ToCord() const { switch (GetKind()) { case ByteStringViewKind::kString: { const auto* refcount = GetStringReferenceCount(); if (refcount != nullptr) { StrongRef(*refcount); return absl::MakeCordFromExternal(GetString(), ReferenceCountReleaser{refcount}); } return absl::Cord(GetString()); } case ByteStringViewKind::kCord: return GetSubcord(); } } absl::Nullable<google::protobuf::Arena*> ByteStringView::GetArena() const noexcept { switch (GetKind()) { case ByteStringViewKind::kString: return GetStringArena(); case ByteStringViewKind::kCord: return nullptr; } } void ByteStringView::HashValue(absl::HashState state) const { Visit(absl::Overload( [&state](absl::string_view string) { absl::HashState::combine(std::move(state), string); }, [&state](const absl::Cord& cord) { absl::HashState::combine(std::move(state), cord); })); } }
#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 = ByteString::Owned(GetAllocator(), GetMediumOrLargeFragmentedCord()); std::string scratch; EXPECT_EQ(byte_string.GetFlat(scratch), GetMediumStringView()); } TEST_P(ByteStringTest, Equals) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_TRUE(byte_string.Equals(GetMediumStringView())); } TEST_P(ByteStringTest, Compare) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_EQ(byte_string.Compare(GetMediumStringView()), 0); EXPECT_EQ(byte_string.Compare(GetMediumOrLargeCord()), 0); } TEST_P(ByteStringTest, StartsWith) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_TRUE(byte_string.StartsWith( GetMediumStringView().substr(0, kSmallByteStringCapacity))); EXPECT_TRUE(byte_string.StartsWith( GetMediumOrLargeCord().Subcord(0, kSmallByteStringCapacity))); } TEST_P(ByteStringTest, EndsWith) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_TRUE(byte_string.EndsWith( GetMediumStringView().substr(kSmallByteStringCapacity))); EXPECT_TRUE(byte_string.EndsWith(GetMediumOrLargeCord().Subcord( kSmallByteStringCapacity, GetMediumOrLargeCord().size() - kSmallByteStringCapacity))); } TEST_P(ByteStringTest, RemovePrefixSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); byte_string.RemovePrefix(1); EXPECT_EQ(byte_string, GetSmallStringView().substr(1)); } TEST_P(ByteStringTest, RemovePrefixMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); byte_string.RemovePrefix(byte_string.size() - kSmallByteStringCapacity); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string, GetMediumStringView().substr(GetMediumStringView().size() - kSmallByteStringCapacity)); } TEST_P(ByteStringTest, RemovePrefixMediumOrLarge) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); byte_string.RemovePrefix(byte_string.size() - kSmallByteStringCapacity); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string, GetMediumStringView().substr(GetMediumStringView().size() - kSmallByteStringCapacity)); } TEST_P(ByteStringTest, RemoveSuffixSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); byte_string.RemoveSuffix(1); EXPECT_EQ(byte_string, GetSmallStringView().substr(0, GetSmallStringView().size() - 1)); } TEST_P(ByteStringTest, RemoveSuffixMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kMedium); byte_string.RemoveSuffix(byte_string.size() - kSmallByteStringCapacity); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string, GetMediumStringView().substr(0, kSmallByteStringCapacity)); } TEST_P(ByteStringTest, RemoveSuffixMediumOrLarge) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); byte_string.RemoveSuffix(byte_string.size() - kSmallByteStringCapacity); EXPECT_EQ(GetKind(byte_string), ByteStringKind::kSmall); EXPECT_EQ(byte_string, GetMediumStringView().substr(0, kSmallByteStringCapacity)); } TEST_P(ByteStringTest, ToStringSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); EXPECT_EQ(byte_string.ToString(), byte_string); } TEST_P(ByteStringTest, ToStringMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); EXPECT_EQ(byte_string.ToString(), byte_string); } TEST_P(ByteStringTest, ToStringLarge) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_EQ(byte_string.ToString(), byte_string); } TEST_P(ByteStringTest, ToCordSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); EXPECT_EQ(byte_string.ToCord(), byte_string); EXPECT_EQ(std::move(byte_string).ToCord(), GetSmallStringView()); } TEST_P(ByteStringTest, ToCordMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); EXPECT_EQ(byte_string.ToCord(), byte_string); EXPECT_EQ(std::move(byte_string).ToCord(), GetMediumStringView()); } TEST_P(ByteStringTest, ToCordLarge) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); EXPECT_EQ(byte_string.ToCord(), byte_string); EXPECT_EQ(std::move(byte_string).ToCord(), GetMediumOrLargeCord()); } TEST_P(ByteStringTest, HashValue) { EXPECT_EQ( absl::HashOf(ByteString::Owned(GetAllocator(), GetSmallStringView())), absl::HashOf(GetSmallStringView())); EXPECT_EQ( absl::HashOf(ByteString::Owned(GetAllocator(), GetMediumStringView())), absl::HashOf(GetMediumStringView())); EXPECT_EQ( absl::HashOf(ByteString::Owned(GetAllocator(), GetMediumOrLargeCord())), absl::HashOf(GetMediumOrLargeCord())); } INSTANTIATE_TEST_SUITE_P( ByteStringTest, ByteStringTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)); class ByteStringViewTest : public TestWithParam<MemoryManagement>, public ByteStringViewTestFriend { public: Allocator<> GetAllocator() { switch (GetParam()) { case MemoryManagement::kPooling: return ArenaAllocator(&arena_); case MemoryManagement::kReferenceCounting: return NewDeleteAllocator(); } } private: google::protobuf::Arena arena_; }; TEST_P(ByteStringViewTest, Default) { ByteStringView byte_String_view; EXPECT_THAT(byte_String_view, SizeIs(0)); EXPECT_THAT(byte_String_view, IsEmpty()); EXPECT_EQ(GetKind(byte_String_view), ByteStringViewKind::kString); } TEST_P(ByteStringViewTest, String) { ByteStringView byte_string_view(GetSmallStringView()); EXPECT_THAT(byte_string_view, SizeIs(GetSmallStringView().size())); EXPECT_THAT(byte_string_view, Not(IsEmpty())); EXPECT_EQ(byte_string_view, GetSmallStringView()); EXPECT_EQ(GetKind(byte_string_view), ByteStringViewKind::kString); EXPECT_EQ(byte_string_view.GetArena(), nullptr); } TEST_P(ByteStringViewTest, Cord) { ByteStringView byte_string_view(GetMediumOrLargeCord()); EXPECT_THAT(byte_string_view, SizeIs(GetMediumOrLargeCord().size())); EXPECT_THAT(byte_string_view, Not(IsEmpty())); EXPECT_EQ(byte_string_view, GetMediumOrLargeCord()); EXPECT_EQ(GetKind(byte_string_view), ByteStringViewKind::kCord); EXPECT_EQ(byte_string_view.GetArena(), nullptr); } TEST_P(ByteStringViewTest, ByteStringSmall) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); ByteStringView byte_string_view(byte_string); EXPECT_THAT(byte_string_view, SizeIs(GetSmallStringView().size())); EXPECT_THAT(byte_string_view, Not(IsEmpty())); EXPECT_EQ(byte_string_view, GetSmallStringView()); EXPECT_EQ(GetKind(byte_string_view), ByteStringViewKind::kString); EXPECT_EQ(byte_string_view.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringViewTest, ByteStringMedium) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumStringView()); ByteStringView byte_string_view(byte_string); EXPECT_THAT(byte_string_view, SizeIs(GetMediumStringView().size())); EXPECT_THAT(byte_string_view, Not(IsEmpty())); EXPECT_EQ(byte_string_view, GetMediumStringView()); EXPECT_EQ(GetKind(byte_string_view), ByteStringViewKind::kString); EXPECT_EQ(byte_string_view.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringViewTest, ByteStringLarge) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); ByteStringView byte_string_view(byte_string); EXPECT_THAT(byte_string_view, SizeIs(GetMediumOrLargeCord().size())); EXPECT_THAT(byte_string_view, Not(IsEmpty())); EXPECT_EQ(byte_string_view, GetMediumOrLargeCord()); EXPECT_EQ(byte_string_view.ToCord(), byte_string_view); if (GetAllocator().arena() == nullptr) { EXPECT_EQ(GetKind(byte_string_view), ByteStringViewKind::kCord); } else { EXPECT_EQ(GetKind(byte_string_view), ByteStringViewKind::kString); } EXPECT_EQ(byte_string_view.GetArena(), GetAllocator().arena()); } TEST_P(ByteStringViewTest, TryFlatString) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); ByteStringView byte_string_view(byte_string); EXPECT_THAT(byte_string_view.TryFlat(), Optional(GetSmallStringView())); } TEST_P(ByteStringViewTest, TryFlatCord) { if (GetAllocator().arena() != nullptr) { GTEST_SKIP(); } ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeFragmentedCord()); ByteStringView byte_string_view(byte_string); EXPECT_THAT(byte_string_view.TryFlat(), Eq(absl::nullopt)); } TEST_P(ByteStringViewTest, GetFlatString) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetSmallStringView()); ByteStringView byte_string_view(byte_string); std::string scratch; EXPECT_EQ(byte_string_view.GetFlat(scratch), GetSmallStringView()); } TEST_P(ByteStringViewTest, GetFlatCord) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeCord()); ByteStringView byte_string_view(byte_string); std::string scratch; EXPECT_EQ(byte_string_view.GetFlat(scratch), GetMediumStringView()); } TEST_P(ByteStringViewTest, GetFlatLargeFragmented) { ByteString byte_string = ByteString::Owned(GetAllocator(), GetMediumOrLargeFragmentedCord()); ByteStringView byte_string_view(byte_string); std::string scratch; EXPECT_EQ(byte_string_view.GetFlat(scratch), GetMediumStringView()); } TEST_P(ByteStringViewTest, RemovePrefixString) { ByteStringView byte_string_view(GetSmallStringView()); byte_string_view.RemovePrefix(1); EXPECT_EQ(byte_string_view, GetSmallStringView().substr(1)); } TEST_P(ByteStringViewTest, RemovePrefixCord) { ByteStringView byte_string_view(GetMediumOrLargeCord()); byte_string_view.RemovePrefix(1); EXPECT_EQ(byte_string_view, GetMediumOrLargeCord().Subcord( 1, GetMediumOrLargeCord().size() - 1)); } TEST_P(ByteStringViewTest, RemoveSuffixString) { ByteStringView byte_string_view(GetSmallStringView()); byte_string_view.RemoveSuffix(1); EXPECT_EQ(byte_string_view, GetSmallStringView().substr(0, GetSmallStringView().size() - 1)); } TEST_P(ByteStringViewTest, RemoveSuffixCord) { ByteStringView byte_string_view(GetMediumOrLargeCord()); byte_string_view.RemoveSuffix(1); EXPECT_EQ(byte_string_view, GetMediumOrLargeCord().Subcord( 0, GetMediumOrLargeCord().size() - 1)); } TEST_P(ByteStringViewTest, ToStringString) { ByteStringView byte_string_view(GetSmallStringView()); EXPECT_EQ(byte_string_view.ToString(), byte_string_view); } TEST_P(ByteStringViewTest, ToStringCord) { ByteStringView byte_string_view(GetMediumOrLargeCord()); EXPECT_EQ(byte_string_view.ToString(), byte_string_view); } TEST_P(ByteStringViewTest, ToCordString) { ByteString byte_string(GetAllocator(), GetMediumStringView()); ByteStringView byte_string_view(byte_string); EXPECT_EQ(byte_string_view.ToCord(), byte_string_view); } TEST_P(ByteStringViewTest, ToCordCord) { ByteStringView byte_string_view(GetMediumOrLargeCord()); EXPECT_EQ(byte_string_view.ToCord(), byte_string_view); } TEST_P(ByteStringViewTest, HashValue) { EXPECT_EQ(absl::HashOf(ByteStringView(GetSmallStringView())), absl::HashOf(GetSmallStringView())); EXPECT_EQ(absl::HashOf(ByteStringView(GetMediumStringView())), absl::HashOf(GetMediumStringView())); EXPECT_EQ(absl::HashOf(ByteStringView(GetMediumOrLargeCord())), absl::HashOf(GetMediumOrLargeCord())); } INSTANTIATE_TEST_SUITE_P( ByteStringViewTest, ByteStringViewTest, ::testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting)); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/byte_string.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/byte_string_test.cc
4552db5798fb0853b131b783d8875794334fae7f
12c45c0c-e7ad-4ffe-8d32-372737070ce5
cpp
google/cel-cpp
reference_count
common/internal/reference_count.cc
common/internal/reference_count_test.cc
#include "common/internal/reference_count.h" #include <cstddef> #include <cstring> #include <memory> #include <new> #include <string> #include <utility> #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/strings/string_view.h" #include "common/data.h" #include "internal/new.h" #include "google/protobuf/message_lite.h" namespace cel::common_internal { template class DeletingReferenceCount<google::protobuf::MessageLite>; template class DeletingReferenceCount<Data>; namespace { class ReferenceCountedStdString final : public ReferenceCounted { public: explicit ReferenceCountedStdString(std::string&& string) { (::new (static_cast<void*>(&string_[0])) std::string(std::move(string))) ->shrink_to_fit(); } 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) { return ::new (internal::New(offsetof(ReferenceCountedString, data_) + size)) ReferenceCountedString(size, data); } const char* data() const noexcept { return 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_[]; }; } std::pair<absl::Nonnull<const ReferenceCount*>, absl::string_view> MakeReferenceCountedString(absl::string_view value) { ABSL_DCHECK(!value.empty()); const auto* refcount = ReferenceCountedString::New(value.data(), value.size()); return std::pair{refcount, absl::string_view(refcount->data(), refcount->size())}; } std::pair<absl::Nonnull<const ReferenceCount*>, absl::string_view> MakeReferenceCountedString(std::string&& value) { ABSL_DCHECK(!value.empty()); const auto* refcount = new ReferenceCountedStdString(std::move(value)); return std::pair{refcount, absl::string_view(refcount->data(), refcount->size())}; } }
#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); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/reference_count.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/internal/reference_count_test.cc
4552db5798fb0853b131b783d8875794334fae7f
f45d9aec-4168-4cdc-9d17-b4e43a86edd1
cpp
google/cel-cpp
cel_value_equal
eval/internal/cel_value_equal.cc
eval/internal/cel_value_equal_test.cc
#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)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/internal/cel_value_equal.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/internal/cel_value_equal_test.cc
4552db5798fb0853b131b783d8875794334fae7f
56045f28-85a8-4780-80eb-1f1726626053
cpp
google/cel-cpp
string_extension_func_registrar
eval/public/string_extension_func_registrar.cc
eval/public/string_extension_func_registrar_test.cc
#include "eval/public/string_extension_func_registrar.h" #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "extensions/strings.h" namespace google::api::expr::runtime { absl::Status RegisterStringExtensionFunctions( CelFunctionRegistry* registry, const InterpreterOptions& options) { return cel::extensions::RegisterStringsFunctions(registry, options); } }
#include "eval/public/string_extension_func_registrar.h" #include <cstdint> #include <string> #include <vector> #include "google/api/expr/v1alpha1/checked.pb.h" #include "absl/types/span.h" #include "eval/public/builtin_func_registrar.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using google::protobuf::Arena; class StringExtensionTest : public ::testing::Test { protected: StringExtensionTest() = default; void SetUp() override { ASSERT_OK(RegisterBuiltinFunctions(&registry_)); ASSERT_OK(RegisterStringExtensionFunctions(&registry_)); } void PerformSplitStringTest(Arena* arena, std::string* value, std::string* delimiter, CelValue* result) { auto function = registry_.FindOverloads( "split", true, {CelValue::Type::kString, CelValue::Type::kString}); ASSERT_EQ(function.size(), 1); auto func = function[0]; std::vector<CelValue> args = {CelValue::CreateString(value), CelValue::CreateString(delimiter)}; absl::Span<CelValue> arg_span(&args[0], args.size()); auto status = func->Evaluate(arg_span, result, arena); ASSERT_OK(status); } void PerformSplitStringWithLimitTest(Arena* arena, std::string* value, std::string* delimiter, int64_t limit, CelValue* result) { auto function = registry_.FindOverloads( "split", true, {CelValue::Type::kString, CelValue::Type::kString, CelValue::Type::kInt64}); ASSERT_EQ(function.size(), 1); auto func = function[0]; std::vector<CelValue> args = {CelValue::CreateString(value), CelValue::CreateString(delimiter), CelValue::CreateInt64(limit)}; absl::Span<CelValue> arg_span(&args[0], args.size()); auto status = func->Evaluate(arg_span, result, arena); ASSERT_OK(status); } void PerformJoinStringTest(Arena* arena, std::vector<std::string>& values, CelValue* result) { auto function = registry_.FindOverloads("join", true, {CelValue::Type::kList}); ASSERT_EQ(function.size(), 1); auto func = function[0]; std::vector<CelValue> cel_list; cel_list.reserve(values.size()); for (const std::string& value : values) { cel_list.push_back( CelValue::CreateString(Arena::Create<std::string>(arena, value))); } std::vector<CelValue> args = {CelValue::CreateList( Arena::Create<ContainerBackedListImpl>(arena, cel_list))}; absl::Span<CelValue> arg_span(&args[0], args.size()); auto status = func->Evaluate(arg_span, result, arena); ASSERT_OK(status); } void PerformJoinStringWithSeparatorTest(Arena* arena, std::vector<std::string>& values, std::string* separator, CelValue* result) { auto function = registry_.FindOverloads( "join", true, {CelValue::Type::kList, CelValue::Type::kString}); ASSERT_EQ(function.size(), 1); auto func = function[0]; std::vector<CelValue> cel_list; cel_list.reserve(values.size()); for (const std::string& value : values) { cel_list.push_back( CelValue::CreateString(Arena::Create<std::string>(arena, value))); } std::vector<CelValue> args = { CelValue::CreateList( Arena::Create<ContainerBackedListImpl>(arena, cel_list)), CelValue::CreateString(separator)}; absl::Span<CelValue> arg_span(&args[0], args.size()); auto status = func->Evaluate(arg_span, result, arena); ASSERT_OK(status); } void PerformLowerAsciiTest(Arena* arena, std::string* value, CelValue* result) { auto function = registry_.FindOverloads("lowerAscii", true, {CelValue::Type::kString}); ASSERT_EQ(function.size(), 1); auto func = function[0]; std::vector<CelValue> args = {CelValue::CreateString(value)}; absl::Span<CelValue> arg_span(&args[0], args.size()); auto status = func->Evaluate(arg_span, result, arena); ASSERT_OK(status); } CelFunctionRegistry registry_; Arena arena_; }; TEST_F(StringExtensionTest, TestStringSplit) { Arena arena; CelValue result; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; std::vector<std::string> expected = {"This", "Is", "Test"}; ASSERT_NO_FATAL_FAILURE( PerformSplitStringTest(&arena, &value, &delimiter, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 3); for (int i = 0; i < expected.size(); ++i) { EXPECT_EQ(result.ListOrDie()->Get(&arena, i).StringOrDie().value(), expected[i]); } } TEST_F(StringExtensionTest, TestStringSplitEmptyDelimiter) { Arena arena; CelValue result; std::string value = "TEST"; std::string delimiter = ""; std::vector<std::string> expected = {"T", "E", "S", "T"}; ASSERT_NO_FATAL_FAILURE( PerformSplitStringTest(&arena, &value, &delimiter, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 4); for (int i = 0; i < expected.size(); ++i) { EXPECT_EQ(result.ListOrDie()->Get(&arena, i).StringOrDie().value(), expected[i]); } } TEST_F(StringExtensionTest, TestStringSplitWithLimitTwo) { Arena arena; CelValue result; int64_t limit = 2; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; std::vector<std::string> expected = {"This", "Is!!Test"}; ASSERT_NO_FATAL_FAILURE(PerformSplitStringWithLimitTest( &arena, &value, &delimiter, limit, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 2); for (int i = 0; i < expected.size(); ++i) { EXPECT_EQ(result.ListOrDie()->Get(&arena, i).StringOrDie().value(), expected[i]); } } TEST_F(StringExtensionTest, TestStringSplitWithLimitOne) { Arena arena; CelValue result; int64_t limit = 1; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; ASSERT_NO_FATAL_FAILURE(PerformSplitStringWithLimitTest( &arena, &value, &delimiter, limit, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 1); EXPECT_EQ(result.ListOrDie()->Get(&arena, 0).StringOrDie().value(), value); } TEST_F(StringExtensionTest, TestStringSplitWithLimitZero) { Arena arena; CelValue result; int64_t limit = 0; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; ASSERT_NO_FATAL_FAILURE(PerformSplitStringWithLimitTest( &arena, &value, &delimiter, limit, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 0); } TEST_F(StringExtensionTest, TestStringSplitWithLimitNegative) { Arena arena; CelValue result; int64_t limit = -1; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; std::vector<std::string> expected = {"This", "Is", "Test"}; ASSERT_NO_FATAL_FAILURE(PerformSplitStringWithLimitTest( &arena, &value, &delimiter, limit, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 3); for (int i = 0; i < expected.size(); ++i) { EXPECT_EQ(result.ListOrDie()->Get(&arena, i).StringOrDie().value(), expected[i]); } } TEST_F(StringExtensionTest, TestStringSplitWithLimitAsMaxPossibleSplits) { Arena arena; CelValue result; int64_t limit = 3; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; std::vector<std::string> expected = {"This", "Is", "Test"}; ASSERT_NO_FATAL_FAILURE(PerformSplitStringWithLimitTest( &arena, &value, &delimiter, limit, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 3); for (int i = 0; i < expected.size(); ++i) { EXPECT_EQ(result.ListOrDie()->Get(&arena, i).StringOrDie().value(), expected[i]); } } TEST_F(StringExtensionTest, TestStringSplitWithLimitGreaterThanMaxPossibleSplits) { Arena arena; CelValue result; int64_t limit = 4; std::string value = "This!!Is!!Test"; std::string delimiter = "!!"; std::vector<std::string> expected = {"This", "Is", "Test"}; ASSERT_NO_FATAL_FAILURE(PerformSplitStringWithLimitTest( &arena, &value, &delimiter, limit, &result)); ASSERT_EQ(result.type(), CelValue::Type::kList); EXPECT_EQ(result.ListOrDie()->size(), 3); for (int i = 0; i < expected.size(); ++i) { EXPECT_EQ(result.ListOrDie()->Get(&arena, i).StringOrDie().value(), expected[i]); } } TEST_F(StringExtensionTest, TestStringJoin) { Arena arena; CelValue result; std::vector<std::string> value = {"This", "Is", "Test"}; std::string expected = "ThisIsTest"; ASSERT_NO_FATAL_FAILURE(PerformJoinStringTest(&arena, value, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestStringJoinEmptyInput) { Arena arena; CelValue result; std::vector<std::string> value = {}; std::string expected = ""; ASSERT_NO_FATAL_FAILURE(PerformJoinStringTest(&arena, value, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestStringJoinWithSeparator) { Arena arena; CelValue result; std::vector<std::string> value = {"This", "Is", "Test"}; std::string separator = "-"; std::string expected = "This-Is-Test"; ASSERT_NO_FATAL_FAILURE( PerformJoinStringWithSeparatorTest(&arena, value, &separator, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestStringJoinWithMultiCharSeparator) { Arena arena; CelValue result; std::vector<std::string> value = {"This", "Is", "Test"}; std::string separator = "--"; std::string expected = "This--Is--Test"; ASSERT_NO_FATAL_FAILURE( PerformJoinStringWithSeparatorTest(&arena, value, &separator, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestStringJoinWithEmptySeparator) { Arena arena; CelValue result; std::vector<std::string> value = {"This", "Is", "Test"}; std::string separator = ""; std::string expected = "ThisIsTest"; ASSERT_NO_FATAL_FAILURE( PerformJoinStringWithSeparatorTest(&arena, value, &separator, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestStringJoinWithSeparatorEmptyInput) { Arena arena; CelValue result; std::vector<std::string> value = {}; std::string separator = "-"; std::string expected = ""; ASSERT_NO_FATAL_FAILURE( PerformJoinStringWithSeparatorTest(&arena, value, &separator, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestLowerAscii) { Arena arena; CelValue result; std::string value = "ThisIs@Test!-5"; std::string expected = "thisis@test!-5"; ASSERT_NO_FATAL_FAILURE(PerformLowerAsciiTest(&arena, &value, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestLowerAsciiWithEmptyInput) { Arena arena; CelValue result; std::string value = ""; std::string expected = ""; ASSERT_NO_FATAL_FAILURE(PerformLowerAsciiTest(&arena, &value, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } TEST_F(StringExtensionTest, TestLowerAsciiWithNonAsciiCharacter) { Arena arena; CelValue result; std::string value = "TacoCÆt"; std::string expected = "tacocÆt"; ASSERT_NO_FATAL_FAILURE(PerformLowerAsciiTest(&arena, &value, &result)); ASSERT_EQ(result.type(), CelValue::Type::kString); EXPECT_EQ(result.StringOrDie().value(), expected); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/string_extension_func_registrar.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/string_extension_func_registrar_test.cc
4552db5798fb0853b131b783d8875794334fae7f
71095631-8d89-4e7e-a68e-81746c3d2f37
cpp
google/cel-cpp
equality_function_registrar
eval/public/equality_function_registrar.cc
eval/public/equality_function_registrar_test.cc
#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 ::absl_testing::StatusIs; 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; 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}}), testing::Values<bool>(true))); INSTANTIATE_TEST_SUITE_P( NullEquality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>({ {"null == null", true}, {"true == null", false}, {"null == false", false}, {"1 == null", false}, {"null == 1", false}, {"-2 == null", false}, {"null == -2", false}, {"1.1 == null", false}, {"null == 1.1", false}, {"'a' == null", false}, {"lhs == null", false, CelValue::CreateBytesView("a")}, {"lhs == null", false, CelValue::CreateDuration(absl::Seconds(1))}, {"google.api.expr.runtime.TestMessage{} == null", false}, {"google.api.expr.runtime.TestMessage{}.string_wrapper_value" " == null", true}, {"google.api.expr.runtime.TestMessage{string_wrapper_value: " "google.protobuf.StringValue{}}.string_wrapper_value == null", false}, {"{} == null", false}, {"[] == null", false}, }), testing::Values<bool>(true))); INSTANTIATE_TEST_SUITE_P( ProtoEquality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>({ {"google.api.expr.runtime.TestMessage{} == null", false}, {"google.api.expr.runtime.TestMessage{string_wrapper_value: " "google.protobuf.StringValue{}}.string_wrapper_value == ''", true}, {"google.api.expr.runtime.TestMessage{" "int64_wrapper_value: " "google.protobuf.Int64Value{value: 1}," "double_value: 1.1} == " "google.api.expr.runtime.TestMessage{" "int64_wrapper_value: " "google.protobuf.Int64Value{value: 1}," "double_value: 1.1}", true}, {"google.api.expr.runtime.TestMessage{" "string_wrapper_value: google.protobuf.StringValue{}} == " "google.api.expr.runtime.TestMessage{}", false}, {"google.api.expr.runtime.TestMessage{} == " "google.rpc.context.AttributeContext{}", false}, }), testing::Values<bool>(true))); void RunBenchmark(absl::string_view expr, benchmark::State& benchmark) { InterpreterOptions opts; auto builder = CreateCelExpressionBuilder(opts); ASSERT_OK(RegisterEqualityFunctions(builder->GetRegistry(), opts)); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse(expr)); google::protobuf::Arena arena; Activation activation; ASSERT_OK_AND_ASSIGN(auto plan, builder->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); for (auto _ : benchmark) { ASSERT_OK_AND_ASSIGN(auto result, plan->Evaluate(activation, &arena)); ASSERT_TRUE(result.IsBool()); } } void RunIdentBenchmark(const CelValue& lhs, const CelValue& rhs, benchmark::State& benchmark) { InterpreterOptions opts; auto builder = CreateCelExpressionBuilder(opts); ASSERT_OK(RegisterEqualityFunctions(builder->GetRegistry(), opts)); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, parser::Parse("lhs == rhs")); google::protobuf::Arena arena; Activation activation; activation.InsertValue("lhs", lhs); activation.InsertValue("rhs", rhs); ASSERT_OK_AND_ASSIGN(auto plan, builder->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); for (auto _ : benchmark) { ASSERT_OK_AND_ASSIGN(auto result, plan->Evaluate(activation, &arena)); ASSERT_TRUE(result.IsBool()); } } void BM_EqualsInt(benchmark::State& s) { RunBenchmark("42 == 43", s); } BENCHMARK(BM_EqualsInt); void BM_EqualsString(benchmark::State& s) { RunBenchmark("'1234' == '1235'", s); } BENCHMARK(BM_EqualsString); void BM_EqualsCreatedList(benchmark::State& s) { RunBenchmark("[1, 2, 3, 4, 5] == [1, 2, 3, 4, 6]", s); } BENCHMARK(BM_EqualsCreatedList); void BM_EqualsBoundLegacyList(benchmark::State& s) { ContainerBackedListImpl lhs( {CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3), CelValue::CreateInt64(4), CelValue::CreateInt64(5)}); ContainerBackedListImpl rhs( {CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3), CelValue::CreateInt64(4), CelValue::CreateInt64(6)}); RunIdentBenchmark(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs), s); } BENCHMARK(BM_EqualsBoundLegacyList); void BM_EqualsCreatedMap(benchmark::State& s) { RunBenchmark("{1: 2, 2: 3, 3: 6} == {1: 2, 2: 3, 3: 6}", s); } BENCHMARK(BM_EqualsCreatedMap); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/equality_function_registrar.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/equality_function_registrar_test.cc
4552db5798fb0853b131b783d8875794334fae7f
5931df01-9e29-4dc2-bc74-b7a25d558adc
cpp
google/cel-cpp
cel_type_registry
eval/public/cel_type_registry.cc
eval/public/cel_type_registry_test.cc
#include "eval/public/cel_type_registry.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/type_provider.h" #include "common/type.h" #include "common/type_factory.h" #include "common/value.h" #include "eval/internal/interop.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 "google/protobuf/descriptor.h" namespace google::api::expr::runtime { namespace { using cel::Type; using cel::TypeFactory; class LegacyToModernTypeProviderAdapter : public LegacyTypeProvider { public: explicit LegacyToModernTypeProviderAdapter(const LegacyTypeProvider& provider) : provider_(provider) {} absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const override { return provider_.ProvideLegacyType(name); } absl::optional<const LegacyTypeInfoApis*> ProvideLegacyTypeInfo( absl::string_view name) const override { return provider_.ProvideLegacyTypeInfo(name); } private: const LegacyTypeProvider& provider_; }; void AddEnumFromDescriptor(const google::protobuf::EnumDescriptor* desc, CelTypeRegistry& registry) { std::vector<CelTypeRegistry::Enumerator> enumerators; enumerators.reserve(desc->value_count()); for (int i = 0; i < desc->value_count(); i++) { enumerators.push_back( {std::string(desc->value(i)->name()), desc->value(i)->number()}); } registry.RegisterEnum(desc->full_name(), std::move(enumerators)); } } CelTypeRegistry::CelTypeRegistry() = default; void CelTypeRegistry::Register(const google::protobuf::EnumDescriptor* enum_descriptor) { AddEnumFromDescriptor(enum_descriptor, *this); } void CelTypeRegistry::RegisterEnum(absl::string_view enum_name, std::vector<Enumerator> enumerators) { modern_type_registry_.RegisterEnum(enum_name, std::move(enumerators)); } void CelTypeRegistry::RegisterTypeProvider( std::unique_ptr<LegacyTypeProvider> provider) { legacy_type_providers_.push_back( std::shared_ptr<const LegacyTypeProvider>(std::move(provider))); modern_type_registry_.AddTypeProvider( std::make_unique<LegacyToModernTypeProviderAdapter>( *legacy_type_providers_.back())); } std::shared_ptr<const LegacyTypeProvider> CelTypeRegistry::GetFirstTypeProvider() const { if (legacy_type_providers_.empty()) { return nullptr; } return legacy_type_providers_[0]; } absl::optional<LegacyTypeAdapter> CelTypeRegistry::FindTypeAdapter( absl::string_view fully_qualified_type_name) const { for (const auto& provider : legacy_type_providers_) { auto maybe_adapter = provider->ProvideLegacyType(fully_qualified_type_name); if (maybe_adapter.has_value()) { return maybe_adapter; } } return absl::nullopt; } }
#include "eval/public/cel_type_registry.h" #include <cstddef> #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/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/type_provider.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "eval/public/structs/legacy_type_adapter.h" #include "eval/public/structs/legacy_type_provider.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::MemoryManagerRef; using ::cel::Type; using ::cel::TypeFactory; using ::cel::TypeManager; using ::cel::TypeProvider; using ::cel::ValueManager; using ::testing::Contains; using ::testing::Eq; using ::testing::Key; using ::testing::Optional; using ::testing::Pair; using ::testing::Truly; using ::testing::UnorderedElementsAre; class TestTypeProvider : public LegacyTypeProvider { public: explicit TestTypeProvider(std::vector<std::string> types) : types_(std::move(types)) {} absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const override { for (const auto& type : types_) { if (name == type) { return LegacyTypeAdapter(nullptr, nullptr); } } return absl::nullopt; } private: std::vector<std::string> types_; }; TEST(CelTypeRegistryTest, RegisterEnum) { CelTypeRegistry registry; registry.RegisterEnum("google.api.expr.runtime.TestMessage.TestEnum", { {"TEST_ENUM_UNSPECIFIED", 0}, {"TEST_ENUM_1", 10}, {"TEST_ENUM_2", 20}, {"TEST_ENUM_3", 30}, }); EXPECT_THAT(registry.resolveable_enums(), Contains(Key("google.api.expr.runtime.TestMessage.TestEnum"))); } TEST(CelTypeRegistryTest, TestRegisterBuiltInEnum) { CelTypeRegistry registry; ASSERT_THAT(registry.resolveable_enums(), Contains(Key("google.protobuf.NullValue"))); } TEST(CelTypeRegistryTest, TestGetFirstTypeProviderSuccess) { CelTypeRegistry registry; registry.RegisterTypeProvider(std::make_unique<TestTypeProvider>( std::vector<std::string>{"google.protobuf.Int64"})); registry.RegisterTypeProvider(std::make_unique<TestTypeProvider>( std::vector<std::string>{"google.protobuf.Any"})); auto type_provider = registry.GetFirstTypeProvider(); ASSERT_NE(type_provider, nullptr); ASSERT_TRUE( type_provider->ProvideLegacyType("google.protobuf.Int64").has_value()); ASSERT_FALSE( type_provider->ProvideLegacyType("google.protobuf.Any").has_value()); } TEST(CelTypeRegistryTest, TestGetFirstTypeProviderFailureOnEmpty) { CelTypeRegistry registry; auto type_provider = registry.GetFirstTypeProvider(); ASSERT_EQ(type_provider, nullptr); } TEST(CelTypeRegistryTest, TestFindTypeAdapterFound) { CelTypeRegistry registry; registry.RegisterTypeProvider(std::make_unique<TestTypeProvider>( std::vector<std::string>{"google.protobuf.Any"})); auto desc = registry.FindTypeAdapter("google.protobuf.Any"); ASSERT_TRUE(desc.has_value()); } TEST(CelTypeRegistryTest, TestFindTypeAdapterFoundMultipleProviders) { CelTypeRegistry registry; registry.RegisterTypeProvider(std::make_unique<TestTypeProvider>( std::vector<std::string>{"google.protobuf.Int64"})); registry.RegisterTypeProvider(std::make_unique<TestTypeProvider>( std::vector<std::string>{"google.protobuf.Any"})); auto desc = registry.FindTypeAdapter("google.protobuf.Any"); ASSERT_TRUE(desc.has_value()); } TEST(CelTypeRegistryTest, TestFindTypeAdapterNotFound) { CelTypeRegistry registry; auto desc = registry.FindTypeAdapter("missing.MessageType"); EXPECT_FALSE(desc.has_value()); } MATCHER_P(TypeNameIs, name, "") { const Type& type = arg; *result_listener << "got typename: " << type.name(); return type.name() == name; } TEST(CelTypeRegistryTypeProviderTest, Builtins) { CelTypeRegistry registry; cel::common_internal::LegacyValueManager value_factory( MemoryManagerRef::ReferenceCounting(), registry.GetTypeProvider()); ASSERT_OK_AND_ASSIGN(absl::optional<Type> bool_type, value_factory.FindType("bool")); EXPECT_THAT(bool_type, Optional(TypeNameIs("bool"))); ASSERT_OK_AND_ASSIGN(absl::optional<Type> timestamp_type, value_factory.FindType("google.protobuf.Timestamp")); EXPECT_THAT(timestamp_type, Optional(TypeNameIs("google.protobuf.Timestamp"))); ASSERT_OK_AND_ASSIGN(absl::optional<Type> int_wrapper_type, value_factory.FindType("google.protobuf.Int64Value")); EXPECT_THAT(int_wrapper_type, Optional(TypeNameIs("google.protobuf.Int64Value"))); ASSERT_OK_AND_ASSIGN(absl::optional<Type> json_struct_type, value_factory.FindType("google.protobuf.Struct")); EXPECT_THAT(json_struct_type, Optional(TypeNameIs("map"))); ASSERT_OK_AND_ASSIGN(absl::optional<Type> any_type, value_factory.FindType("google.protobuf.Any")); EXPECT_THAT(any_type, Optional(TypeNameIs("google.protobuf.Any"))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_type_registry.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_type_registry_test.cc
4552db5798fb0853b131b783d8875794334fae7f
7681854c-90d0-4abf-9fa0-5e36c5c9fe1f
cpp
google/cel-cpp
activation_bind_helper
eval/public/activation_bind_helper.cc
eval/public/activation_bind_helper_test.cc
#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.")); } } } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/activation_bind_helper.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/activation_bind_helper_test.cc
4552db5798fb0853b131b783d8875794334fae7f
2349c720-6615-482b-b85d-847d3c18aa94
cpp
google/cel-cpp
set_util
eval/public/set_util.cc
eval/public/set_util_test.cc
#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)); } } } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/set_util.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/set_util_test.cc
4552db5798fb0853b131b783d8875794334fae7f
527075f5-bbd8-447e-a0d4-2a0ebffb9cbf
cpp
google/cel-cpp
cel_attribute
eval/public/cel_attribute.cc
eval/public/cel_attribute_test.cc
#include "eval/public/cel_attribute.h" #include <algorithm> #include <string> #include <utility> #include <variant> #include <vector> #include "absl/strings/string_view.h" #include "eval/public/cel_value.h" namespace google::api::expr::runtime { namespace { struct QualifierVisitor { CelAttributeQualifierPattern operator()(absl::string_view v) { if (v == "*") { return CelAttributeQualifierPattern::CreateWildcard(); } return CelAttributeQualifierPattern::OfString(std::string(v)); } CelAttributeQualifierPattern operator()(int64_t v) { return CelAttributeQualifierPattern::OfInt(v); } CelAttributeQualifierPattern operator()(uint64_t v) { return CelAttributeQualifierPattern::OfUint(v); } CelAttributeQualifierPattern operator()(bool v) { return CelAttributeQualifierPattern::OfBool(v); } CelAttributeQualifierPattern operator()(CelAttributeQualifierPattern v) { return v; } }; } CelAttributeQualifierPattern CreateCelAttributeQualifierPattern( const CelValue& value) { switch (value.type()) { case cel::Kind::kInt64: return CelAttributeQualifierPattern::OfInt(value.Int64OrDie()); case cel::Kind::kUint64: return CelAttributeQualifierPattern::OfUint(value.Uint64OrDie()); case cel::Kind::kString: return CelAttributeQualifierPattern::OfString( std::string(value.StringOrDie().value())); case cel::Kind::kBool: return CelAttributeQualifierPattern::OfBool(value.BoolOrDie()); default: return CelAttributeQualifierPattern(CelAttributeQualifier()); } } CelAttributeQualifier CreateCelAttributeQualifier(const CelValue& value) { switch (value.type()) { case cel::Kind::kInt64: return CelAttributeQualifier::OfInt(value.Int64OrDie()); case cel::Kind::kUint64: return CelAttributeQualifier::OfUint(value.Uint64OrDie()); case cel::Kind::kString: return CelAttributeQualifier::OfString( std::string(value.StringOrDie().value())); case cel::Kind::kBool: return CelAttributeQualifier::OfBool(value.BoolOrDie()); default: return CelAttributeQualifier(); } } CelAttributePattern CreateCelAttributePattern( absl::string_view variable, std::initializer_list<absl::variant<absl::string_view, int64_t, uint64_t, bool, CelAttributeQualifierPattern>> path_spec) { std::vector<CelAttributeQualifierPattern> path; path.reserve(path_spec.size()); for (const auto& spec_elem : path_spec) { path.emplace_back(absl::visit(QualifierVisitor(), spec_elem)); } return CelAttributePattern(std::string(variable), std::move(path)); } }
#include "eval/public/cel_attribute.h" #include <string> #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "eval/public/cel_value.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "internal/status_macros.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using google::api::expr::v1alpha1::Expr; using ::absl_testing::StatusIs; using ::google::protobuf::Duration; using ::google::protobuf::Timestamp; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::SizeIs; 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(CelAttributeQualifierTest, TestBoolAccess) { auto qualifier = CreateCelAttributeQualifier(CelValue::CreateBool(true)); EXPECT_FALSE(qualifier.GetStringKey().has_value()); EXPECT_FALSE(qualifier.GetInt64Key().has_value()); EXPECT_FALSE(qualifier.GetUint64Key().has_value()); EXPECT_TRUE(qualifier.GetBoolKey().has_value()); EXPECT_THAT(qualifier.GetBoolKey().value(), Eq(true)); } TEST(CelAttributeQualifierTest, TestInt64Access) { auto qualifier = CreateCelAttributeQualifier(CelValue::CreateInt64(1)); EXPECT_FALSE(qualifier.GetBoolKey().has_value()); EXPECT_FALSE(qualifier.GetStringKey().has_value()); EXPECT_FALSE(qualifier.GetUint64Key().has_value()); EXPECT_TRUE(qualifier.GetInt64Key().has_value()); EXPECT_THAT(qualifier.GetInt64Key().value(), Eq(1)); } TEST(CelAttributeQualifierTest, TestUint64Access) { auto qualifier = CreateCelAttributeQualifier(CelValue::CreateUint64(1)); EXPECT_FALSE(qualifier.GetBoolKey().has_value()); EXPECT_FALSE(qualifier.GetStringKey().has_value()); EXPECT_FALSE(qualifier.GetInt64Key().has_value()); EXPECT_TRUE(qualifier.GetUint64Key().has_value()); EXPECT_THAT(qualifier.GetUint64Key().value(), Eq(1UL)); } TEST(CelAttributeQualifierTest, TestStringAccess) { const std::string test = "test"; auto qualifier = CreateCelAttributeQualifier(CelValue::CreateString(&test)); EXPECT_FALSE(qualifier.GetBoolKey().has_value()); EXPECT_FALSE(qualifier.GetInt64Key().has_value()); EXPECT_FALSE(qualifier.GetUint64Key().has_value()); EXPECT_TRUE(qualifier.GetStringKey().has_value()); EXPECT_THAT(qualifier.GetStringKey().value(), Eq("test")); } void TestAllInequalities(const CelAttributeQualifier& qualifier) { EXPECT_FALSE(qualifier == CreateCelAttributeQualifier(CelValue::CreateBool(false))); EXPECT_FALSE(qualifier == CreateCelAttributeQualifier(CelValue::CreateInt64(0))); EXPECT_FALSE(qualifier == CreateCelAttributeQualifier(CelValue::CreateUint64(0))); const std::string test = "Those are not the droids you are looking for."; EXPECT_FALSE(qualifier == CreateCelAttributeQualifier(CelValue::CreateString(&test))); } TEST(CelAttributeQualifierTest, TestBoolComparison) { auto qualifier = CreateCelAttributeQualifier(CelValue::CreateBool(true)); TestAllInequalities(qualifier); EXPECT_TRUE(qualifier == CreateCelAttributeQualifier(CelValue::CreateBool(true))); } TEST(CelAttributeQualifierTest, TestInt64Comparison) { auto qualifier = CreateCelAttributeQualifier(CelValue::CreateInt64(true)); TestAllInequalities(qualifier); EXPECT_TRUE(qualifier == CreateCelAttributeQualifier(CelValue::CreateInt64(true))); } TEST(CelAttributeQualifierTest, TestUint64Comparison) { auto qualifier = CreateCelAttributeQualifier(CelValue::CreateUint64(true)); TestAllInequalities(qualifier); EXPECT_TRUE(qualifier == CreateCelAttributeQualifier(CelValue::CreateUint64(true))); } TEST(CelAttributeQualifierTest, TestStringComparison) { const std::string kTest = "test"; auto qualifier = CreateCelAttributeQualifier(CelValue::CreateString(&kTest)); TestAllInequalities(qualifier); EXPECT_TRUE(qualifier == CreateCelAttributeQualifier(CelValue::CreateString(&kTest))); } void TestAllQualifierMismatches(const CelAttributeQualifierPattern& qualifier) { const std::string test = "Those are not the droids you are looking for."; EXPECT_FALSE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateBool(false)))); EXPECT_FALSE( qualifier.IsMatch(CreateCelAttributeQualifier(CelValue::CreateInt64(0)))); EXPECT_FALSE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateUint64(0)))); EXPECT_FALSE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateString(&test)))); } TEST(CelAttributeQualifierPatternTest, TestQualifierBoolMatch) { auto qualifier = CreateCelAttributeQualifierPattern(CelValue::CreateBool(true)); TestAllQualifierMismatches(qualifier); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateBool(true)))); } TEST(CelAttributeQualifierPatternTest, TestQualifierInt64Match) { auto qualifier = CreateCelAttributeQualifierPattern(CelValue::CreateInt64(1)); TestAllQualifierMismatches(qualifier); EXPECT_TRUE( qualifier.IsMatch(CreateCelAttributeQualifier(CelValue::CreateInt64(1)))); } TEST(CelAttributeQualifierPatternTest, TestQualifierUint64Match) { auto qualifier = CreateCelAttributeQualifierPattern(CelValue::CreateUint64(1)); TestAllQualifierMismatches(qualifier); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateUint64(1)))); } TEST(CelAttributeQualifierPatternTest, TestQualifierStringMatch) { const std::string test = "test"; auto qualifier = CreateCelAttributeQualifierPattern(CelValue::CreateString(&test)); TestAllQualifierMismatches(qualifier); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateString(&test)))); } TEST(CelAttributeQualifierPatternTest, TestQualifierWildcardMatch) { auto qualifier = CelAttributeQualifierPattern::CreateWildcard(); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateBool(false)))); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateBool(true)))); EXPECT_TRUE( qualifier.IsMatch(CreateCelAttributeQualifier(CelValue::CreateInt64(0)))); EXPECT_TRUE( qualifier.IsMatch(CreateCelAttributeQualifier(CelValue::CreateInt64(1)))); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateUint64(0)))); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateUint64(1)))); const std::string kTest1 = "test1"; const std::string kTest2 = "test2"; EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateString(&kTest1)))); EXPECT_TRUE(qualifier.IsMatch( CreateCelAttributeQualifier(CelValue::CreateString(&kTest2)))); } TEST(CreateCelAttributePattern, Basic) { const std::string kTest = "def"; CelAttributePattern pattern = CreateCelAttributePattern( "abc", {kTest, static_cast<uint64_t>(1), static_cast<int64_t>(-1), false, CelAttributeQualifierPattern::CreateWildcard()}); EXPECT_THAT(pattern.variable(), Eq("abc")); ASSERT_THAT(pattern.qualifier_path(), SizeIs(5)); EXPECT_TRUE(pattern.qualifier_path()[4].IsWildcard()); } TEST(CreateCelAttributePattern, EmptyPath) { CelAttributePattern pattern = CreateCelAttributePattern("abc"); EXPECT_THAT(pattern.variable(), Eq("abc")); EXPECT_THAT(pattern.qualifier_path(), IsEmpty()); } TEST(CreateCelAttributePattern, Wildcards) { const std::string kTest = "*"; CelAttributePattern pattern = CreateCelAttributePattern( "abc", {kTest, "false", CelAttributeQualifierPattern::CreateWildcard()}); EXPECT_THAT(pattern.variable(), Eq("abc")); ASSERT_THAT(pattern.qualifier_path(), SizeIs(3)); EXPECT_TRUE(pattern.qualifier_path()[0].IsWildcard()); EXPECT_FALSE(pattern.qualifier_path()[1].IsWildcard()); EXPECT_TRUE(pattern.qualifier_path()[2].IsWildcard()); } TEST(CelAttribute, AsStringBasic) { CelAttribute attr( "var", { CreateCelAttributeQualifier(CelValue::CreateStringView("qual1")), CreateCelAttributeQualifier(CelValue::CreateStringView("qual2")), CreateCelAttributeQualifier(CelValue::CreateStringView("qual3")), }); ASSERT_OK_AND_ASSIGN(std::string string_format, attr.AsString()); EXPECT_EQ(string_format, "var.qual1.qual2.qual3"); } TEST(CelAttribute, AsStringInvalidRoot) { CelAttribute attr( "", { CreateCelAttributeQualifier(CelValue::CreateStringView("qual1")), CreateCelAttributeQualifier(CelValue::CreateStringView("qual2")), CreateCelAttributeQualifier(CelValue::CreateStringView("qual3")), }); EXPECT_EQ(attr.AsString().status().code(), absl::StatusCode::kInvalidArgument); } TEST(CelAttribute, InvalidQualifiers) { Expr expr; expr.mutable_ident_expr()->set_name("var"); google::protobuf::Arena arena; CelAttribute attr1("var", { CreateCelAttributeQualifier( CelValue::CreateDuration(absl::Minutes(2))), }); CelAttribute attr2("var", { CreateCelAttributeQualifier( CelProtoWrapper::CreateMessage(&expr, &arena)), }); CelAttribute attr3( "var", { CreateCelAttributeQualifier(CelValue::CreateBool(false)), }); EXPECT_FALSE(attr1 == attr2); EXPECT_FALSE(attr2 == attr1); EXPECT_FALSE(attr2 == attr2); EXPECT_FALSE(attr1 == attr3); EXPECT_FALSE(attr3 == attr1); EXPECT_FALSE(attr2 == attr3); EXPECT_FALSE(attr3 == attr2); EXPECT_THAT(attr1.AsString(), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(attr2.AsString(), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(CelAttribute, AsStringQualiferTypes) { CelAttribute attr( "var", { CreateCelAttributeQualifier(CelValue::CreateStringView("qual1")), CreateCelAttributeQualifier(CelValue::CreateUint64(1)), CreateCelAttributeQualifier(CelValue::CreateInt64(-1)), CreateCelAttributeQualifier(CelValue::CreateBool(false)), }); ASSERT_OK_AND_ASSIGN(std::string string_format, attr.AsString()); EXPECT_EQ(string_format, "var.qual1[1][-1][false]"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_attribute.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_attribute_test.cc
4552db5798fb0853b131b783d8875794334fae7f
0edc4c8a-f0c9-41bf-9ec3-d20068361023
cpp
google/cel-cpp
logical_function_registrar
eval/public/logical_function_registrar.cc
eval/public/logical_function_registrar_test.cc
#include "eval/public/logical_function_registrar.h" #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "runtime/standard/logical_functions.h" namespace google::api::expr::runtime { absl::Status RegisterLogicalFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { return cel::RegisterLogicalFunctions(registry->InternalGetRegistry(), ConvertToRuntimeOptions(options)); } }
#include "eval/public/logical_function_registrar.h" #include <memory> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/base/no_destructor.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "eval/public/activation.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/portable_cel_function_adapter.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 ::absl_testing::StatusIs; using ::testing::HasSubstr; struct TestCase { std::string test_name; std::string expr; absl::StatusOr<CelValue> result = CelValue::CreateBool(true); }; const CelError* ExampleError() { static absl::NoDestructor<absl::Status> error( absl::InternalError("test example error")); return &*error; } 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.short_circuiting = true; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterLogicalFunctions(builder->GetRegistry(), options)); ASSERT_OK(builder->GetRegistry()->Register( PortableUnaryFunctionAdapter<CelValue, CelValue::StringHolder>::Create( "toBool", false, [](google::protobuf::Arena*, CelValue::StringHolder holder) -> CelValue { if (holder.value() == "true") { return CelValue::CreateBool(true); } else if (holder.value() == "false") { return CelValue::CreateBool(false); } return CelValue::CreateError(ExampleError()); }))); 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)); if (!test_case.result.ok()) { EXPECT_TRUE(value.IsError()); EXPECT_THAT(*value.ErrorOrDie(), StatusIs(test_case.result.status().code(), HasSubstr(test_case.result.status().message()))); return; } EXPECT_THAT(value, test::EqualsCelValue(*test_case.result)); } using BuiltinFuncParamsTest = testing::TestWithParam<TestCase>; TEST_P(BuiltinFuncParamsTest, StandardFunctions) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( BuiltinFuncParamsTest, BuiltinFuncParamsTest, testing::ValuesIn<TestCase>({ {"LogicalNotOfTrue", "!true", CelValue::CreateBool(false)}, {"LogicalNotOfFalse", "!false", CelValue::CreateBool(true)}, {"NotStrictlyFalseTrue", "[true, true, true].all(x, x)", CelValue::CreateBool(true)}, {"NotStrictlyFalseErrorShortcircuit", "['true', 'false', 'error'].all(x, toBool(x))", CelValue::CreateBool(false)}, {"NotStrictlyFalseError", "['true', 'true', 'error'].all(x, toBool(x))", CelValue::CreateError(ExampleError())}, {"NotStrictlyFalseFalse", "[false, false, false].all(x, x)", CelValue::CreateBool(false)}, }), [](const testing::TestParamInfo<BuiltinFuncParamsTest::ParamType>& info) { return info.param.test_name; }); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/logical_function_registrar.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/logical_function_registrar_test.cc
4552db5798fb0853b131b783d8875794334fae7f
5f4bdf13-5af9-4796-999f-d114acc952de
cpp
google/cel-cpp
container_function_registrar
eval/public/container_function_registrar.cc
eval/public/container_function_registrar_test.cc
#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; }); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/container_function_registrar.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/container_function_registrar_test.cc
4552db5798fb0853b131b783d8875794334fae7f
cf9b2799-79ea-4943-97f3-dcb00a0256b4
cpp
google/cel-cpp
builtin_func_registrar
eval/public/builtin_func_registrar.cc
eval/public/builtin_func_registrar_test.cc
#include "eval/public/builtin_func_registrar.h" #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" #include "runtime/standard/arithmetic_functions.h" #include "runtime/standard/comparison_functions.h" #include "runtime/standard/container_functions.h" #include "runtime/standard/container_membership_functions.h" #include "runtime/standard/equality_functions.h" #include "runtime/standard/logical_functions.h" #include "runtime/standard/regex_functions.h" #include "runtime/standard/string_functions.h" #include "runtime/standard/time_functions.h" #include "runtime/standard/type_conversion_functions.h" namespace google::api::expr::runtime { absl::Status RegisterBuiltinFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { cel::FunctionRegistry& modern_registry = registry->InternalGetRegistry(); cel::RuntimeOptions runtime_options = ConvertToRuntimeOptions(options); CEL_RETURN_IF_ERROR( cel::RegisterLogicalFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterComparisonFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterContainerFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR(cel::RegisterContainerMembershipFunctions( modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterTypeConversionFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterArithmeticFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterTimeFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterStringFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterRegexFunctions(modern_registry, runtime_options)); CEL_RETURN_IF_ERROR( cel::RegisterEqualityFunctions(modern_registry, runtime_options)); return absl::OkStatus(); } }
#include "eval/public/builtin_func_registrar.h" #include <memory> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "eval/public/activation.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/testing/matchers.h" #include "internal/testing.h" #include "internal/time.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using google::api::expr::v1alpha1::Expr; using google::api::expr::v1alpha1::SourceInfo; using ::absl_testing::StatusIs; using ::cel::internal::MaxDuration; using ::cel::internal::MinDuration; using ::testing::HasSubstr; struct TestCase { std::string test_name; std::string expr; absl::flat_hash_map<std::string, CelValue> vars; absl::StatusOr<CelValue> result = CelValue::CreateBool(true); InterpreterOptions options; }; InterpreterOptions OverflowChecksEnabled() { static InterpreterOptions options; options.enable_timestamp_duration_overflow_errors = true; return options; } 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(); std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(test_case.options); ASSERT_OK( RegisterBuiltinFunctions(builder->GetRegistry(), test_case.options)); ASSERT_OK_AND_ASSIGN(auto cel_expression, builder->CreateExpression(&expr_ast, &source_info)); Activation activation; for (auto var : test_case.vars) { activation.InsertValue(var.first, var.second); } google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(auto value, cel_expression->Evaluate(activation, &arena)); if (!test_case.result.ok()) { EXPECT_TRUE(value.IsError()) << value.DebugString(); EXPECT_THAT(*value.ErrorOrDie(), StatusIs(test_case.result.status().code(), HasSubstr(test_case.result.status().message()))); return; } EXPECT_THAT(value, test::EqualsCelValue(*test_case.result)); } using BuiltinFuncParamsTest = testing::TestWithParam<TestCase>; TEST_P(BuiltinFuncParamsTest, StandardFunctions) { ExpectResult(GetParam()); } INSTANTIATE_TEST_SUITE_P( BuiltinFuncParamsTest, BuiltinFuncParamsTest, testing::ValuesIn<TestCase>({ {"TimeSubTimeLegacy", "t0 - t1 == duration('90s90ns')", { {"t0", CelValue::CreateTimestamp(absl::FromUnixSeconds(100) + absl::Nanoseconds(100))}, {"t1", CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}, }}, {"TimeSubDurationLegacy", "t0 - duration('90s90ns')", { {"t0", CelValue::CreateTimestamp(absl::FromUnixSeconds(100) + absl::Nanoseconds(100))}, }, CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}, {"TimeAddDurationLegacy", "t + duration('90s90ns')", {{"t", CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}}, CelValue::CreateTimestamp(absl::FromUnixSeconds(100) + absl::Nanoseconds(100))}, {"DurationAddTimeLegacy", "duration('90s90ns') + t == t + duration('90s90ns')", {{"t", CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}}}, {"DurationAddDurationLegacy", "duration('80s80ns') + duration('10s10ns') == duration('90s90ns')"}, {"DurationSubDurationLegacy", "duration('90s90ns') - duration('80s80ns') == duration('10s10ns')"}, {"MinDurationSubDurationLegacy", "min - duration('1ns') < duration('-87660000h')", {{"min", CelValue::CreateDuration(MinDuration())}}}, {"MaxDurationAddDurationLegacy", "max + duration('1ns') > duration('87660000h')", {{"max", CelValue::CreateDuration(MaxDuration())}}}, {"TimestampConversionFromStringLegacy", "timestamp('10000-01-02T00:00:00Z') > " "timestamp('9999-01-01T00:00:00Z')"}, {"TimestampFromUnixEpochSeconds", "timestamp(123) > timestamp('1970-01-01T00:02:02.999999999Z') && " "timestamp(123) == timestamp('1970-01-01T00:02:03Z') && " "timestamp(123) < timestamp('1970-01-01T00:02:03.000000001Z')"}, {"TimeSubTime", "t0 - t1 == duration('90s90ns')", { {"t0", CelValue::CreateTimestamp(absl::FromUnixSeconds(100) + absl::Nanoseconds(100))}, {"t1", CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}, }, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"TimeSubDuration", "t0 - duration('90s90ns')", { {"t0", CelValue::CreateTimestamp(absl::FromUnixSeconds(100) + absl::Nanoseconds(100))}, }, CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10)), OverflowChecksEnabled()}, {"TimeSubtractDurationOverflow", "timestamp('0001-01-01T00:00:00Z') - duration('1ns')", {}, absl::OutOfRangeError("timestamp overflow"), OverflowChecksEnabled()}, {"TimeAddDuration", "t + duration('90s90ns')", {{"t", CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}}, CelValue::CreateTimestamp(absl::FromUnixSeconds(100) + absl::Nanoseconds(100)), OverflowChecksEnabled()}, {"TimeAddDurationOverflow", "timestamp('9999-12-31T23:59:59.999999999Z') + duration('1ns')", {}, absl::OutOfRangeError("timestamp overflow"), OverflowChecksEnabled()}, {"DurationAddTime", "duration('90s90ns') + t == t + duration('90s90ns')", {{"t", CelValue::CreateTimestamp(absl::FromUnixSeconds(10) + absl::Nanoseconds(10))}}, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"DurationAddTimeOverflow", "duration('1ns') + timestamp('9999-12-31T23:59:59.999999999Z')", {}, absl::OutOfRangeError("timestamp overflow"), OverflowChecksEnabled()}, {"DurationAddDuration", "duration('80s80ns') + duration('10s10ns') == duration('90s90ns')", {}, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"DurationSubDuration", "duration('90s90ns') - duration('80s80ns') == duration('10s10ns')", {}, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"MinDurationSubDuration", "min - duration('1ns')", {{"min", CelValue::CreateDuration(MinDuration())}}, absl::OutOfRangeError("overflow"), OverflowChecksEnabled()}, {"MaxDurationAddDuration", "max + duration('1ns')", {{"max", CelValue::CreateDuration(MaxDuration())}}, absl::OutOfRangeError("overflow"), OverflowChecksEnabled()}, {"TimestampConversionFromStringOverflow", "timestamp('10000-01-02T00:00:00Z')", {}, absl::OutOfRangeError("timestamp overflow"), OverflowChecksEnabled()}, {"TimestampConversionFromStringUnderflow", "timestamp('0000-01-01T00:00:00Z')", {}, absl::OutOfRangeError("timestamp overflow"), OverflowChecksEnabled()}, {"ListConcatEmptyInputs", "[] + [] == []", {}, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"ListConcatRightEmpty", "[1] + [] == [1]", {}, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"ListConcatLeftEmpty", "[] + [1] == [1]", {}, CelValue::CreateBool(true), OverflowChecksEnabled()}, {"ListConcat", "[2] + [1] == [2, 1]", {}, CelValue::CreateBool(true), OverflowChecksEnabled()}, }), [](const testing::TestParamInfo<BuiltinFuncParamsTest::ParamType>& info) { return info.param.test_name; }); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/builtin_func_registrar.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/builtin_func_registrar_test.cc
4552db5798fb0853b131b783d8875794334fae7f
da860396-918a-45e7-8b9f-5a4861646232
cpp
google/cel-cpp
value_export_util
eval/public/value_export_util.cc
eval/public/value_export_util_test.cc
#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); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/value_export_util.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/value_export_util_test.cc
4552db5798fb0853b131b783d8875794334fae7f
05232ffb-1c4d-4174-b2a9-2e9bb1d48464
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
#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 "absl/strings/string_view.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 std::string(GetTypename(wrapped_message)); } absl::string_view GetTypename( const MessageWrapper& wrapped_message) const override { return "google.protobuf.Timestamp"; } 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; absl::string_view 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 std::string(GetTypename(wrapped_message)); } absl::string_view GetTypename( const MessageWrapper& wrapped_message) const override { return "google.api.expr.runtime.TestMessage"; } 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(); } absl::string_view 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"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/portable_cel_expr_builder_factory.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/portable_cel_expr_builder_factory_test.cc
4552db5798fb0853b131b783d8875794334fae7f
a9e0d084-df21-48ff-913e-7966d428b431
cpp
google/cel-cpp
cel_function_registry
eval/public/cel_function_registry.cc
eval/public/cel_function_registry_test.cc
#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 ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Property; using ::testing::SizeIs; using ::testing::Truly; 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())); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_function_registry.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_function_registry_test.cc
4552db5798fb0853b131b783d8875794334fae7f
40b79121-1cc3-4d60-a259-4ce6eb1ab4f0
cpp
google/cel-cpp
unknown_function_result_set
eval/public/unknown_function_result_set.cc
eval/public/unknown_function_result_set_test.cc
#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); } } } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/unknown_function_result_set.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/unknown_function_result_set_test.cc
4552db5798fb0853b131b783d8875794334fae7f