ID
int64
0
2.65k
Language
stringclasses
1 value
Repository Name
stringclasses
14 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
16
116
Code
stringlengths
411
31.4k
Unit Test - (Ground Truth)
stringlengths
40
32.1k
100
cpp
google/cel-cpp
builtin_func_registrar
eval/public/builtin_func_registrar.cc
eval/public/builtin_func_registrar_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_BUILTIN_FUNC_REGISTRAR_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_BUILTIN_FUNC_REGISTRAR_H_ #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" namespace google::api::expr::runtime { absl::Status RegisterBuiltinFunctions( CelFunctionRegistry* registry, const InterpreterOptions& options = InterpreterOptions()); } #endif #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 ::cel::internal::MaxDuration; using ::cel::internal::MinDuration; using testing::HasSubstr; using cel::internal::StatusIs; 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; }); } }
101
cpp
google/cel-cpp
cel_attribute
eval/public/cel_attribute.cc
eval/public/cel_attribute_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_ATTRIBUTE_PATTERN_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_ATTRIBUTE_PATTERN_H_ #include <sys/types.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <initializer_list> #include <memory> #include <optional> #include <string> #include <utility> #include <variant> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "base/attribute.h" #include "eval/public/cel_value.h" namespace google::api::expr::runtime { using CelAttributeQualifier = ::cel::AttributeQualifier; using CelAttribute = ::cel::Attribute; using CelAttributeQualifierPattern = ::cel::AttributeQualifierPattern; using CelAttributePattern = ::cel::AttributePattern; CelAttributeQualifierPattern CreateCelAttributeQualifierPattern( const CelValue& value); CelAttributeQualifier CreateCelAttributeQualifier(const CelValue& value); CelAttributePattern CreateCelAttributePattern( absl::string_view variable, std::initializer_list<absl::variant<absl::string_view, int64_t, uint64_t, bool, CelAttributeQualifierPattern>> path_spec = {}); } #endif #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 ::google::protobuf::Duration; using ::google::protobuf::Timestamp; using testing::Eq; using testing::IsEmpty; using testing::SizeIs; using cel::internal::StatusIs; class DummyMap : public CelMap { public: absl::optional<CelValue> operator[](CelValue value) const override { return CelValue::CreateNull(); } absl::StatusOr<const CelList*> ListKeys() const override { return absl::UnimplementedError("CelMap::ListKeys is not implemented"); } int size() const override { return 0; } }; class DummyList : public CelList { public: int size() const override { return 0; } CelValue operator[](int index) const override { return CelValue::CreateNull(); } }; TEST(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]"); } } }
102
cpp
google/cel-cpp
string_extension_func_registrar
eval/public/string_extension_func_registrar.cc
eval/public/string_extension_func_registrar_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRING_EXTENSION_FUNC_REGISTRAR_H_ #define THIRD_PARTY_CEL_CPP_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" namespace google::api::expr::runtime { absl::Status RegisterStringExtensionFunctions( CelFunctionRegistry* registry, const InterpreterOptions& options = InterpreterOptions()); } #endif #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); } } }
103
cpp
google/cel-cpp
logical_function_registrar
eval/public/logical_function_registrar.cc
eval/public/logical_function_registrar_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_LOGICAL_FUNCTION_REGISTRAR_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_LOGICAL_FUNCTION_REGISTRAR_H_ #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" namespace google::api::expr::runtime { absl::Status RegisterLogicalFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options); } #endif #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 testing::HasSubstr; using cel::internal::StatusIs; 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; }); } }
104
cpp
google/cel-cpp
cel_type_registry
eval/public/cel_type_registry.cc
eval/public/cel_type_registry_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_TYPE_REGISTRY_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_TYPE_REGISTRY_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "eval/public/structs/legacy_type_provider.h" #include "runtime/internal/composed_type_provider.h" #include "runtime/type_registry.h" namespace google::api::expr::runtime { class CelTypeRegistry { public: using Enumerator = cel::TypeRegistry::Enumerator; using Enumeration = cel::TypeRegistry::Enumeration; CelTypeRegistry(); ~CelTypeRegistry() = default; void Register(const google::protobuf::EnumDescriptor* enum_descriptor); void RegisterEnum(absl::string_view name, std::vector<Enumerator> enumerators); void RegisterTypeProvider(std::unique_ptr<LegacyTypeProvider> provider); std::shared_ptr<const LegacyTypeProvider> GetFirstTypeProvider() const; const cel::TypeProvider& GetTypeProvider() const { return modern_type_registry_.GetComposedTypeProvider(); } void RegisterModernTypeProvider(std::unique_ptr<cel::TypeProvider> provider) { return modern_type_registry_.AddTypeProvider(std::move(provider)); } absl::optional<LegacyTypeAdapter> FindTypeAdapter( absl::string_view fully_qualified_type_name) const; const absl::flat_hash_map<std::string, Enumeration>& resolveable_enums() const { return modern_type_registry_.resolveable_enums(); } absl::flat_hash_set<absl::string_view> ListResolveableEnums() const { const auto& enums = resolveable_enums(); absl::flat_hash_set<absl::string_view> result; result.reserve(enums.size()); for (const auto& entry : enums) { result.insert(entry.first); } return result; } cel::TypeRegistry& InternalGetModernRegistry() { return modern_type_registry_; } const cel::TypeRegistry& InternalGetModernRegistry() const { return modern_type_registry_; } private: cel::TypeRegistry modern_type_registry_; std::vector<std::shared_ptr<const LegacyTypeProvider>> legacy_type_providers_; }; } #endif #include "eval/public/cel_type_registry.h" #include <memory> #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); } absl::optional<const LegacyAnyPackingApis*> ProvideLegacyAnyPackingApis( absl::string_view name) const override { return provider_.ProvideLegacyAnyPackingApis(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({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 ::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; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; 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"))); } } }
105
cpp
google/cel-cpp
matchers
eval/public/testing/matchers.cc
eval/public/testing/matchers_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_TESTING_MATCHERS_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_TESTING_MATCHERS_H_ #include <ostream> #include "google/protobuf/message.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "eval/public/cel_value.h" #include "eval/public/set_util.h" #include "eval/public/unknown_set.h" namespace google { namespace api { namespace expr { namespace runtime { void PrintTo(const CelValue& value, std::ostream* os); namespace test { using CelValueMatcher = testing::Matcher<CelValue>; CelValueMatcher EqualsCelValue(const CelValue& v); CelValueMatcher IsCelNull(); CelValueMatcher IsCelBool(testing::Matcher<bool> m); CelValueMatcher IsCelInt64(testing::Matcher<int64_t> m); CelValueMatcher IsCelUint64(testing::Matcher<uint64_t> m); CelValueMatcher IsCelDouble(testing::Matcher<double> m); CelValueMatcher IsCelString(testing::Matcher<absl::string_view> m); CelValueMatcher IsCelBytes(testing::Matcher<absl::string_view> m); CelValueMatcher IsCelMessage(testing::Matcher<const google::protobuf::Message*> m); CelValueMatcher IsCelDuration(testing::Matcher<absl::Duration> m); CelValueMatcher IsCelTimestamp(testing::Matcher<absl::Time> m); CelValueMatcher IsCelError(testing::Matcher<absl::Status> m); template <typename ContainerMatcher> class CelListMatcher : public testing::MatcherInterface<const CelValue&> { public: explicit CelListMatcher(ContainerMatcher m) : container_matcher_(m) {} bool MatchAndExplain(const CelValue& v, testing::MatchResultListener* listener) const override { const CelList* cel_list; if (!v.GetValue(&cel_list) || cel_list == nullptr) return false; std::vector<CelValue> cel_vector; cel_vector.reserve(cel_list->size()); for (int i = 0; i < cel_list->size(); ++i) { cel_vector.push_back((*cel_list)[i]); } return container_matcher_.Matches(cel_vector); } void DescribeTo(std::ostream* os) const override { CelValue::Type type = static_cast<CelValue::Type>(CelValue::IndexOf<const CelList*>::value); *os << absl::StrCat("type is ", CelValue::TypeName(type), " and "); container_matcher_.DescribeTo(os); } private: const testing::Matcher<std::vector<CelValue>> container_matcher_; }; template <typename ContainerMatcher> CelValueMatcher IsCelList(ContainerMatcher m) { return CelValueMatcher(new CelListMatcher(m)); } } } } } } #endif #include "eval/public/testing/matchers.h" #include <ostream> #include <utility> #include "google/protobuf/message.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "eval/public/set_util.h" #include "internal/casts.h" namespace google::api::expr::runtime { void PrintTo(const CelValue& value, std::ostream* os) { *os << value.DebugString(); } namespace test { namespace { using testing::_; using testing::MatcherInterface; using testing::MatchResultListener; class CelValueEqualImpl : public MatcherInterface<CelValue> { public: explicit CelValueEqualImpl(const CelValue& v) : value_(v) {} bool MatchAndExplain(CelValue arg, MatchResultListener* listener) const override { return CelValueEqual(arg, value_); } void DescribeTo(std::ostream* os) const override { *os << value_.DebugString(); } private: const CelValue& value_; }; template <typename UnderlyingType> class CelValueMatcherImpl : public testing::MatcherInterface<const CelValue&> { public: explicit CelValueMatcherImpl(testing::Matcher<UnderlyingType> m) : underlying_type_matcher_(std::move(m)) {} bool MatchAndExplain(const CelValue& v, testing::MatchResultListener* listener) const override { UnderlyingType arg; return v.GetValue(&arg) && underlying_type_matcher_.Matches(arg); } void DescribeTo(std::ostream* os) const override { CelValue::Type type = static_cast<CelValue::Type>(CelValue::IndexOf<UnderlyingType>::value); *os << absl::StrCat("type is ", CelValue::TypeName(type), " and "); underlying_type_matcher_.DescribeTo(os); } private: const testing::Matcher<UnderlyingType> underlying_type_matcher_; }; template <> class CelValueMatcherImpl<const google::protobuf::Message*> : public testing::MatcherInterface<const CelValue&> { public: explicit CelValueMatcherImpl(testing::Matcher<const google::protobuf::Message*> m) : underlying_type_matcher_(std::move(m)) {} bool MatchAndExplain(const CelValue& v, testing::MatchResultListener* listener) const override { CelValue::MessageWrapper arg; return v.GetValue(&arg) && arg.HasFullProto() && underlying_type_matcher_.Matches( cel::internal::down_cast<const google::protobuf::Message*>( arg.message_ptr())); } void DescribeTo(std::ostream* os) const override { *os << absl::StrCat("type is ", CelValue::TypeName(CelValue::Type::kMessage), " and "); underlying_type_matcher_.DescribeTo(os); } private: const testing::Matcher<const google::protobuf::Message*> underlying_type_matcher_; }; } CelValueMatcher EqualsCelValue(const CelValue& v) { return CelValueMatcher(new CelValueEqualImpl(v)); } CelValueMatcher IsCelNull() { return CelValueMatcher(new CelValueMatcherImpl<CelValue::NullType>(_)); } CelValueMatcher IsCelBool(testing::Matcher<bool> m) { return CelValueMatcher(new CelValueMatcherImpl<bool>(std::move(m))); } CelValueMatcher IsCelInt64(testing::Matcher<int64_t> m) { return CelValueMatcher(new CelValueMatcherImpl<int64_t>(std::move(m))); } CelValueMatcher IsCelUint64(testing::Matcher<uint64_t> m) { return CelValueMatcher(new CelValueMatcherImpl<uint64_t>(std::move(m))); } CelValueMatcher IsCelDouble(testing::Matcher<double> m) { return CelValueMatcher(new CelValueMatcherImpl<double>(std::move(m))); } CelValueMatcher IsCelString(testing::Matcher<absl::string_view> m) { return CelValueMatcher(new CelValueMatcherImpl<CelValue::StringHolder>( testing::Property(&CelValue::StringHolder::value, m))); } CelValueMatcher IsCelBytes(testing::Matcher<absl::string_view> m) { return CelValueMatcher(new CelValueMatcherImpl<CelValue::BytesHolder>( testing::Property(&CelValue::BytesHolder::value, m))); } CelValueMatcher IsCelMessage(testing::Matcher<const google::protobuf::Message*> m) { return CelValueMatcher( new CelValueMatcherImpl<const google::protobuf::Message*>(std::move(m))); } CelValueMatcher IsCelDuration(testing::Matcher<absl::Duration> m) { return CelValueMatcher(new CelValueMatcherImpl<absl::Duration>(std::move(m))); } CelValueMatcher IsCelTimestamp(testing::Matcher<absl::Time> m) { return CelValueMatcher(new CelValueMatcherImpl<absl::Time>(std::move(m))); } CelValueMatcher IsCelError(testing::Matcher<absl::Status> m) { return CelValueMatcher( new CelValueMatcherImpl<const google::api::expr::runtime::CelError*>( testing::AllOf(testing::NotNull(), testing::Pointee(m)))); } } }
#include "eval/public/testing/matchers.h" #include "absl/status/status.h" #include "absl/time/time.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" #include "testutil/util.h" namespace google::api::expr::runtime::test { namespace { using testing::Contains; using testing::DoubleEq; using testing::DoubleNear; using testing::ElementsAre; using testing::Gt; using testing::Lt; using testing::Not; using testing::UnorderedElementsAre; using testutil::EqualsProto; TEST(IsCelValue, EqualitySmoketest) { EXPECT_THAT(CelValue::CreateBool(true), EqualsCelValue(CelValue::CreateBool(true))); EXPECT_THAT(CelValue::CreateInt64(-1), EqualsCelValue(CelValue::CreateInt64(-1))); EXPECT_THAT(CelValue::CreateUint64(2), EqualsCelValue(CelValue::CreateUint64(2))); EXPECT_THAT(CelValue::CreateDouble(1.25), EqualsCelValue(CelValue::CreateDouble(1.25))); EXPECT_THAT(CelValue::CreateStringView("abc"), EqualsCelValue(CelValue::CreateStringView("abc"))); EXPECT_THAT(CelValue::CreateBytesView("def"), EqualsCelValue(CelValue::CreateBytesView("def"))); EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)), EqualsCelValue(CelValue::CreateDuration(absl::Seconds(2)))); EXPECT_THAT( CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), EqualsCelValue(CelValue::CreateTimestamp(absl::FromUnixSeconds(1)))); EXPECT_THAT(CelValue::CreateInt64(-1), Not(EqualsCelValue(CelValue::CreateBool(true)))); EXPECT_THAT(CelValue::CreateUint64(2), Not(EqualsCelValue(CelValue::CreateInt64(-1)))); EXPECT_THAT(CelValue::CreateDouble(1.25), Not(EqualsCelValue(CelValue::CreateUint64(2)))); EXPECT_THAT(CelValue::CreateStringView("abc"), Not(EqualsCelValue(CelValue::CreateDouble(1.25)))); EXPECT_THAT(CelValue::CreateBytesView("def"), Not(EqualsCelValue(CelValue::CreateStringView("abc")))); EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)), Not(EqualsCelValue(CelValue::CreateBytesView("def")))); EXPECT_THAT(CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), Not(EqualsCelValue(CelValue::CreateDuration(absl::Seconds(2))))); EXPECT_THAT( CelValue::CreateBool(true), Not(EqualsCelValue(CelValue::CreateTimestamp(absl::FromUnixSeconds(1))))); } TEST(PrimitiveMatchers, Smoketest) { EXPECT_THAT(CelValue::CreateNull(), IsCelNull()); EXPECT_THAT(CelValue::CreateBool(false), Not(IsCelNull())); EXPECT_THAT(CelValue::CreateBool(true), IsCelBool(true)); EXPECT_THAT(CelValue::CreateBool(false), IsCelBool(Not(true))); EXPECT_THAT(CelValue::CreateInt64(1), IsCelInt64(1)); EXPECT_THAT(CelValue::CreateInt64(-1), IsCelInt64(Not(Gt(0)))); EXPECT_THAT(CelValue::CreateUint64(1), IsCelUint64(1)); EXPECT_THAT(CelValue::CreateUint64(2), IsCelUint64(Not(Lt(2)))); EXPECT_THAT(CelValue::CreateDouble(1.5), IsCelDouble(DoubleEq(1.5))); EXPECT_THAT(CelValue::CreateDouble(1.0 + 0.8), IsCelDouble(DoubleNear(1.8, 1e-5))); EXPECT_THAT(CelValue::CreateStringView("abc"), IsCelString("abc")); EXPECT_THAT(CelValue::CreateStringView("abcdef"), IsCelString(testing::HasSubstr("def"))); EXPECT_THAT(CelValue::CreateBytesView("abc"), IsCelBytes("abc")); EXPECT_THAT(CelValue::CreateBytesView("abcdef"), IsCelBytes(testing::HasSubstr("def"))); EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)), IsCelDuration(Lt(absl::Minutes(1)))); EXPECT_THAT(CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), IsCelTimestamp(Lt(absl::FromUnixSeconds(30)))); } TEST(PrimitiveMatchers, WrongType) { EXPECT_THAT(CelValue::CreateBool(true), Not(IsCelInt64(1))); EXPECT_THAT(CelValue::CreateInt64(1), Not(IsCelUint64(1))); EXPECT_THAT(CelValue::CreateUint64(1), Not(IsCelDouble(1.0))); EXPECT_THAT(CelValue::CreateDouble(1.5), Not(IsCelString("abc"))); EXPECT_THAT(CelValue::CreateStringView("abc"), Not(IsCelBytes("abc"))); EXPECT_THAT(CelValue::CreateBytesView("abc"), Not(IsCelDuration(Lt(absl::Minutes(1))))); EXPECT_THAT(CelValue::CreateDuration(absl::Seconds(2)), Not(IsCelTimestamp(Lt(absl::FromUnixSeconds(30))))); EXPECT_THAT(CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), Not(IsCelBool(true))); } TEST(SpecialMatchers, SmokeTest) { auto status = absl::InternalError("error"); CelValue error = CelValue::CreateError(&status); EXPECT_THAT(error, IsCelError(testing::Eq( absl::Status(absl::StatusCode::kInternal, "error")))); TestMessage proto_message; proto_message.add_bool_list(true); proto_message.add_bool_list(false); proto_message.add_int64_list(1); proto_message.add_int64_list(-1); CelValue message = CelProtoWrapper::CreateMessage(&proto_message, nullptr); EXPECT_THAT(message, IsCelMessage(EqualsProto(proto_message))); } TEST(ListMatchers, NotList) { EXPECT_THAT(CelValue::CreateInt64(1), Not(IsCelList(Contains(IsCelInt64(1))))); } TEST(ListMatchers, All) { ContainerBackedListImpl list({ CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3), CelValue::CreateInt64(4), }); CelValue cel_list = CelValue::CreateList(&list); EXPECT_THAT(cel_list, IsCelList(Contains(IsCelInt64(3)))); EXPECT_THAT(cel_list, IsCelList(Not(Contains(IsCelInt64(0))))); EXPECT_THAT(cel_list, IsCelList(ElementsAre(IsCelInt64(1), IsCelInt64(2), IsCelInt64(3), IsCelInt64(4)))); EXPECT_THAT(cel_list, IsCelList(Not(ElementsAre(IsCelInt64(2), IsCelInt64(1), IsCelInt64(3), IsCelInt64(4))))); EXPECT_THAT(cel_list, IsCelList(UnorderedElementsAre(IsCelInt64(2), IsCelInt64(1), IsCelInt64(4), IsCelInt64(3)))); EXPECT_THAT( cel_list, IsCelList(Not(UnorderedElementsAre(IsCelInt64(2), IsCelInt64(1), IsCelInt64(4), IsCelInt64(0))))); } } }
106
cpp
google/cel-cpp
cel_proto_wrap_util
eval/public/structs/cel_proto_wrap_util.cc
eval/public/structs/cel_proto_wrap_util_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_WRAP_UTIL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_WRAP_UTIL_H_ #include "eval/public/cel_value.h" #include "eval/public/structs/protobuf_value_factory.h" namespace google::api::expr::runtime::internal { CelValue UnwrapMessageToValue(const google::protobuf::Message* value, const ProtobufValueFactory& factory, google::protobuf::Arena* arena); const google::protobuf::Message* MaybeWrapValueToMessage( const google::protobuf::Descriptor* descriptor, const CelValue& value, google::protobuf::Arena* arena); } #endif #include "eval/public/structs/cel_proto_wrap_util.h" #include <math.h> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/message.h" #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "eval/public/cel_value.h" #include "eval/public/structs/protobuf_value_factory.h" #include "eval/testutil/test_message.pb.h" #include "internal/overflow.h" #include "internal/proto_time_encoding.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace google::api::expr::runtime::internal { namespace { using cel::internal::DecodeDuration; using cel::internal::DecodeTime; using cel::internal::EncodeTime; using google::protobuf::Any; using google::protobuf::BoolValue; using google::protobuf::BytesValue; using google::protobuf::DoubleValue; using google::protobuf::Duration; using google::protobuf::FloatValue; using google::protobuf::Int32Value; using google::protobuf::Int64Value; using google::protobuf::ListValue; using google::protobuf::StringValue; using google::protobuf::Struct; using google::protobuf::Timestamp; using google::protobuf::UInt32Value; using google::protobuf::UInt64Value; using google::protobuf::Value; using google::protobuf::Arena; using google::protobuf::Descriptor; using google::protobuf::DescriptorPool; using google::protobuf::Message; using google::protobuf::MessageFactory; constexpr int64_t kMaxIntJSON = (1ll << 53) - 1; constexpr int64_t kMinIntJSON = -kMaxIntJSON; google::protobuf::Message* MessageFromValue(const CelValue& value, Value* json, google::protobuf::Arena* arena); static bool IsJSONSafe(int64_t i) { return i >= kMinIntJSON && i <= kMaxIntJSON; } static bool IsJSONSafe(uint64_t i) { return i <= static_cast<uint64_t>(kMaxIntJSON); } class DynamicList : public CelList { public: DynamicList(const ListValue* values, ProtobufValueFactory factory, Arena* arena) : arena_(arena), factory_(std::move(factory)), values_(values) {} CelValue operator[](int index) const override; int size() const override { return values_->values_size(); } private: Arena* arena_; ProtobufValueFactory factory_; const ListValue* values_; }; class DynamicMap : public CelMap { public: DynamicMap(const Struct* values, ProtobufValueFactory factory, Arena* arena) : arena_(arena), factory_(std::move(factory)), values_(values), key_list_(values) {} absl::StatusOr<bool> Has(const CelValue& key) const override { CelValue::StringHolder str_key; if (!key.GetValue(&str_key)) { return absl::InvalidArgumentError(absl::StrCat( "Invalid map key type: '", CelValue::TypeName(key.type()), "'")); } return values_->fields().contains(std::string(str_key.value())); } absl::optional<CelValue> operator[](CelValue key) const override; int size() const override { return values_->fields_size(); } absl::StatusOr<const CelList*> ListKeys() const override { return &key_list_; } private: class DynamicMapKeyList : public CelList { public: explicit DynamicMapKeyList(const Struct* values) : values_(values), keys_(), initialized_(false) {} CelValue operator[](int index) const override { CheckInit(); return keys_[index]; } int size() const override { CheckInit(); return values_->fields_size(); } private: void CheckInit() const { absl::MutexLock lock(&mutex_); if (!initialized_) { for (const auto& it : values_->fields()) { keys_.push_back(CelValue::CreateString(&it.first)); } initialized_ = true; } } const Struct* values_; mutable absl::Mutex mutex_; mutable std::vector<CelValue> keys_; mutable bool initialized_; }; Arena* arena_; ProtobufValueFactory factory_; const Struct* values_; const DynamicMapKeyList key_list_; }; class ValueManager { public: ValueManager(const ProtobufValueFactory& value_factory, const google::protobuf::DescriptorPool* descriptor_pool, google::protobuf::Arena* arena, google::protobuf::MessageFactory* message_factory) : value_factory_(value_factory), descriptor_pool_(descriptor_pool), arena_(arena), message_factory_(message_factory) {} ValueManager(const ProtobufValueFactory& value_factory, google::protobuf::Arena* arena) : value_factory_(value_factory), descriptor_pool_(DescriptorPool::generated_pool()), arena_(arena), message_factory_(MessageFactory::generated_factory()) {} CelValue ValueFromMessage(const Duration* duration) { return CelValue::CreateDuration(DecodeDuration(*duration)); } CelValue ValueFromMessage(const Timestamp* timestamp) { return CelValue::CreateTimestamp(DecodeTime(*timestamp)); } CelValue ValueFromMessage(const ListValue* list_values) { return CelValue::CreateList(Arena::Create<DynamicList>( arena_, list_values, value_factory_, arena_)); } CelValue ValueFromMessage(const Struct* struct_value) { return CelValue::CreateMap(Arena::Create<DynamicMap>( arena_, struct_value, value_factory_, arena_)); } CelValue ValueFromMessage(const Any* any_value, const DescriptorPool* descriptor_pool, MessageFactory* message_factory) { auto type_url = any_value->type_url(); auto pos = type_url.find_last_of('/'); if (pos == absl::string_view::npos) { return CreateErrorValue(arena_, "Malformed type_url string"); } std::string full_name = std::string(type_url.substr(pos + 1)); const Descriptor* nested_descriptor = descriptor_pool->FindMessageTypeByName(full_name); if (nested_descriptor == nullptr) { return CreateErrorValue(arena_, "Descriptor not found"); } const Message* prototype = message_factory->GetPrototype(nested_descriptor); if (prototype == nullptr) { return CreateErrorValue(arena_, "Prototype not found"); } Message* nested_message = prototype->New(arena_); if (!any_value->UnpackTo(nested_message)) { return CreateErrorValue(arena_, "Failed to unpack Any into message"); } return UnwrapMessageToValue(nested_message, value_factory_, arena_); } CelValue ValueFromMessage(const Any* any_value) { return ValueFromMessage(any_value, descriptor_pool_, message_factory_); } CelValue ValueFromMessage(const BoolValue* wrapper) { return CelValue::CreateBool(wrapper->value()); } CelValue ValueFromMessage(const Int32Value* wrapper) { return CelValue::CreateInt64(wrapper->value()); } CelValue ValueFromMessage(const UInt32Value* wrapper) { return CelValue::CreateUint64(wrapper->value()); } CelValue ValueFromMessage(const Int64Value* wrapper) { return CelValue::CreateInt64(wrapper->value()); } CelValue ValueFromMessage(const UInt64Value* wrapper) { return CelValue::CreateUint64(wrapper->value()); } CelValue ValueFromMessage(const FloatValue* wrapper) { return CelValue::CreateDouble(wrapper->value()); } CelValue ValueFromMessage(const DoubleValue* wrapper) { return CelValue::CreateDouble(wrapper->value()); } CelValue ValueFromMessage(const StringValue* wrapper) { return CelValue::CreateString(&wrapper->value()); } CelValue ValueFromMessage(const BytesValue* wrapper) { return CelValue::CreateBytes( Arena::Create<std::string>(arena_, std::string(wrapper->value()))); } CelValue ValueFromMessage(const Value* value) { switch (value->kind_case()) { case Value::KindCase::kNullValue: return CelValue::CreateNull(); case Value::KindCase::kNumberValue: return CelValue::CreateDouble(value->number_value()); case Value::KindCase::kStringValue: return CelValue::CreateString(&value->string_value()); case Value::KindCase::kBoolValue: return CelValue::CreateBool(value->bool_value()); case Value::KindCase::kStructValue: return UnwrapMessageToValue(&value->struct_value(), value_factory_, arena_); case Value::KindCase::kListValue: return UnwrapMessageToValue(&value->list_value(), value_factory_, arena_); default: return CelValue::CreateNull(); } } private: const ProtobufValueFactory& value_factory_; const google::protobuf::DescriptorPool* descriptor_pool_; google::protobuf::Arena* arena_; MessageFactory* message_factory_; }; class ValueFromMessageMaker { public: template <class MessageType> static CelValue CreateWellknownTypeValue(const google::protobuf::Message* msg, const ProtobufValueFactory& factory, Arena* arena) { const MessageType* message = google::protobuf::DynamicCastToGenerated<const MessageType>(msg); google::protobuf::MessageFactory* message_factory = msg->GetReflection()->GetMessageFactory(); const google::protobuf::DescriptorPool* pool = msg->GetDescriptor()->file()->pool(); if (message == nullptr) { auto message_copy = Arena::Create<MessageType>(arena); if (MessageType::descriptor() == msg->GetDescriptor()) { message_copy->CopyFrom(*msg); message = message_copy; } else { std::string serialized_msg; if (msg->SerializeToString(&serialized_msg) && message_copy->ParseFromString(serialized_msg)) { message = message_copy; } } } return ValueManager(factory, pool, arena, message_factory) .ValueFromMessage(message); } static absl::optional<CelValue> CreateValue( const google::protobuf::Message* message, const ProtobufValueFactory& factory, Arena* arena) { switch (message->GetDescriptor()->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: return CreateWellknownTypeValue<DoubleValue>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: return CreateWellknownTypeValue<FloatValue>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: return CreateWellknownTypeValue<Int64Value>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: return CreateWellknownTypeValue<UInt64Value>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: return CreateWellknownTypeValue<Int32Value>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: return CreateWellknownTypeValue<UInt32Value>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: return CreateWellknownTypeValue<StringValue>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: return CreateWellknownTypeValue<BytesValue>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: return CreateWellknownTypeValue<BoolValue>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY: return CreateWellknownTypeValue<Any>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION: return CreateWellknownTypeValue<Duration>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP: return CreateWellknownTypeValue<Timestamp>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE: return CreateWellknownTypeValue<Value>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE: return CreateWellknownTypeValue<ListValue>(message, factory, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT: return CreateWellknownTypeValue<Struct>(message, factory, arena); default: return absl::nullopt; } } ValueFromMessageMaker(const ValueFromMessageMaker&) = delete; ValueFromMessageMaker& operator=(const ValueFromMessageMaker&) = delete; }; CelValue DynamicList::operator[](int index) const { return ValueManager(factory_, arena_) .ValueFromMessage(&values_->values(index)); } absl::optional<CelValue> DynamicMap::operator[](CelValue key) const { CelValue::StringHolder str_key; if (!key.GetValue(&str_key)) { return CreateErrorValue(arena_, absl::InvalidArgumentError(absl::StrCat( "Invalid map key type: '", CelValue::TypeName(key.type()), "'"))); } auto it = values_->fields().find(std::string(str_key.value())); if (it == values_->fields().end()) { return absl::nullopt; } return ValueManager(factory_, arena_).ValueFromMessage(&it->second); } google::protobuf::Message* MessageFromValue( const CelValue& value, Duration* duration, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { absl::Duration val; if (!value.GetValue(&val)) { return nullptr; } auto status = cel::internal::EncodeDuration(val, duration); if (!status.ok()) { return nullptr; } return duration; } google::protobuf::Message* MessageFromValue( const CelValue& value, BoolValue* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { bool val; if (!value.GetValue(&val)) { return nullptr; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, BytesValue* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { CelValue::BytesHolder view_val; if (!value.GetValue(&view_val)) { return nullptr; } wrapper->set_value(view_val.value()); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, DoubleValue* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { double val; if (!value.GetValue(&val)) { return nullptr; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, FloatValue* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { double val; if (!value.GetValue(&val)) { return nullptr; } if (val > std::numeric_limits<float>::max()) { wrapper->set_value(std::numeric_limits<float>::infinity()); return wrapper; } if (val < std::numeric_limits<float>::lowest()) { wrapper->set_value(-std::numeric_limits<float>::infinity()); return wrapper; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, Int32Value* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { int64_t val; if (!value.GetValue(&val)) { return nullptr; } if (!cel::internal::CheckedInt64ToInt32(val).ok()) { return nullptr; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, Int64Value* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { int64_t val; if (!value.GetValue(&val)) { return nullptr; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, StringValue* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { CelValue::StringHolder view_val; if (!value.GetValue(&view_val)) { return nullptr; } wrapper->set_value(view_val.value()); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, Timestamp* timestamp, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { absl::Time val; if (!value.GetValue(&val)) { return nullptr; } auto status = EncodeTime(val, timestamp); if (!status.ok()) { return nullptr; } return timestamp; } google::protobuf::Message* MessageFromValue( const CelValue& value, UInt32Value* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { uint64_t val; if (!value.GetValue(&val)) { return nullptr; } if (!cel::internal::CheckedUint64ToUint32(val).ok()) { return nullptr; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue( const CelValue& value, UInt64Value* wrapper, google::protobuf::Arena* arena ABSL_ATTRIBUTE_UNUSED = nullptr) { uint64_t val; if (!value.GetValue(&val)) { return nullptr; } wrapper->set_value(val); return wrapper; } google::protobuf::Message* MessageFromValue(const CelValue& value, ListValue* json_list, google::protobuf::Arena* arena) { if (!value.IsList()) { return nullptr; } const CelList& list = *value.ListOrDie(); for (int i = 0; i < list.size(); i++) { auto e = list.Get(arena, i); Value* elem = json_list->add_values(); auto result = MessageFromValue(e, elem, arena); if (result == nullptr) { return nullptr; } } return json_list; } google::protobuf::Message* MessageFromValue(const CelValue& value, Struct* json_struct, google::protobuf::Arena* arena) { if (!value.IsMap()) { return nullptr; } const CelMap& map = *value.MapOrDie(); absl::StatusOr<const CelList*> keys_or = map.ListKeys(arena); if (!keys_or.ok()) { return nullptr; } const CelList& keys = **keys_or; auto fields = json_struct->mutable_fields(); for (int i = 0; i < keys.size(); i++) { auto k = keys.Get(arena, i); if (!k.IsString()) { return nullptr; } absl::string_view key = k.StringOrDie().value(); auto v = map.Get(arena, k); if (!v.has_value()) { return nullptr; } Value field_value; auto result = MessageFromValue(*v, &field_value, arena); if (result == nullptr) { return nullptr; } (*fields)[std::string(key)] = field_value; } return json_struct; } google::protobuf::Message* MessageFromValue(const CelValue& value, Value* json, google::protobuf::Arena* arena) { switch (value.type()) { case CelValue::Type::kBool: { bool val; if (value.GetValue(&val)) { json->set_bool_value(val); return json; } } break; case CelValue::Type::kBytes: { CelValue::BytesHolder val; if (value.GetValue(&val)) { json->set_string_value(absl::Base64Escape(val.value())); return json; } } break; case CelValue::Type::kDouble: { double val; if (value.GetValue(&val)) { json->set_number_value(val); return json; } } break; case CelValue::Type::kDuration: { absl::Duration val; if (value.GetValue(&val)) { auto encode = cel::internal::EncodeDurationToString(val); if (!encode.ok()) { return nullptr; } json->set_string_value(*encode); return json; } } break; case CelValue::Type::kInt64: { int64_t val; if (value.GetValue(&val)) { if (IsJSONSafe(val)) { json->set_number_value(val); } else { json->set_string_value(absl::StrCat(val)); } return json; } } break; case CelValue::Type::kString: { CelValue::StringHolder val; if (value.GetValue(&val)) { json->set_string_value(val.value()); return json; } } break; case CelValue::Type::kTimestamp: { absl::Time val; if (value.GetValue(&val)) { auto encode = cel::internal::EncodeTimeToString(val); if (!encode.ok()) { return nullptr; } json->set_string_value(*encode); return json; } } break; case CelValue::Type::kUint64: { uint64_t val; if (value.GetValue(&val)) { if (IsJSONSafe(val)) { json->set_number_value(val); } else { json->set_string_value(absl::StrCat(val)); } return json; } } break; case CelValue::Type::kList: { auto lv = MessageFromValue(value, json->mutable_list_value(), arena); if (lv != nullptr) { return json; } } break; case CelValue::Type::kMap: { auto sv = MessageFromValue(value, json->mutable_struct_value(), arena); if (sv != nullptr) { return json; } } break; case CelValue::Type::kNullType: json->set_null_value(protobuf::NULL_VALUE); return json; default: return nullptr; } return nullptr; } google::protobuf::Message* MessageFromValue(const CelValue& value, Any* any, google::protobuf::Arena* arena) { switch (value.type()) { case CelValue::Type::kBool: { BoolValue v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kBytes: { BytesValue v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kDouble: { DoubleValue v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kDuration: { Duration v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kInt64: { Int64Value v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kString: { StringValue v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kTimestamp: { Timestamp v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kUint64: { UInt64Value v; auto msg = MessageFromValue(value, &v); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kList: { ListValue v; auto msg = MessageFromValue(value, &v, arena); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kMap: { Struct v; auto msg = MessageFromValue(value, &v, arena); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kNullType: { Value v; auto msg = MessageFromValue(value, &v, arena); if (msg != nullptr) { any->PackFrom(*msg); return any; } } break; case CelValue::Type::kMessage: { any->PackFrom(*(value.MessageOrDie())); return any; } break; default: break; } return nullptr; } class MessageFromValueFactory { public: virtual ~MessageFromValueFactory() {} virtual const google::protobuf::Descriptor* GetDescriptor() const = 0; virtual absl::optional<const google::protobuf::Message*> WrapMessage( const CelValue& value, Arena* arena) const = 0; }; class MessageFromValueMaker { public: MessageFromValueMaker(const MessageFromValueMaker&) = delete; MessageFromValueMaker& operator=(const MessageFromValueMaker&) = delete; template <class MessageType> static google::protobuf::Message* WrapWellknownTypeMessage(const CelValue& value, Arena* arena) { if (value.IsMessage()) { const auto* msg = value.MessageOrDie(); if (MessageType::descriptor()->well_known_type() == msg->GetDescriptor()->well_known_type()) { return nullptr; } } auto* msg_buffer = Arena::Create<MessageType>(arena); return MessageFromValue(value, msg_buffer, arena); } static google::protobuf::Message* MaybeWrapMessage(const google::protobuf::Descriptor* descriptor, const CelValue& value, Arena* arena) { switch (descriptor->well_known_type()) { case google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: return WrapWellknownTypeMessage<DoubleValue>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE: return WrapWellknownTypeMessage<FloatValue>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE: return WrapWellknownTypeMessage<Int64Value>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE: return WrapWellknownTypeMessage<UInt64Value>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE: return WrapWellknownTypeMessage<Int32Value>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE: return WrapWellknownTypeMessage<UInt32Value>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE: return WrapWellknownTypeMessage<StringValue>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE: return WrapWellknownTypeMessage<BytesValue>(value, arena); case google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE: return WrapWellknownTypeMessage<BoolValue>(value, arena); case google::
#include "eval/public/structs/cel_proto_wrap_util.h" #include <cassert> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/empty.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/message.h" #include "absl/base/no_destructor.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/message_wrapper.h" #include "eval/public/structs/protobuf_value_factory.h" #include "eval/public/structs/trivial_legacy_type_info.h" #include "eval/testutil/test_message.pb.h" #include "internal/proto_time_encoding.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "testutil/util.h" namespace google::api::expr::runtime::internal { namespace { using testing::Eq; using testing::UnorderedPointwise; using google::protobuf::Duration; using google::protobuf::ListValue; using google::protobuf::Struct; using google::protobuf::Timestamp; using google::protobuf::Value; using google::protobuf::Any; using google::protobuf::BoolValue; using google::protobuf::BytesValue; using google::protobuf::DoubleValue; using google::protobuf::FloatValue; using google::protobuf::Int32Value; using google::protobuf::Int64Value; using google::protobuf::StringValue; using google::protobuf::UInt32Value; using google::protobuf::UInt64Value; using google::protobuf::Arena; CelValue ProtobufValueFactoryImpl(const google::protobuf::Message* m) { return CelValue::CreateMessageWrapper( CelValue::MessageWrapper(m, TrivialTypeInfo::GetInstance())); } class CelProtoWrapperTest : public ::testing::Test { protected: CelProtoWrapperTest() {} void ExpectWrappedMessage(const CelValue& value, const google::protobuf::Message& message) { auto* result = MaybeWrapValueToMessage(message.GetDescriptor(), value, arena()); EXPECT_TRUE(result != nullptr); EXPECT_THAT(result, testutil::EqualsProto(message)); auto* identity = MaybeWrapValueToMessage( message.GetDescriptor(), ProtobufValueFactoryImpl(result), arena()); EXPECT_TRUE(identity == nullptr); result = MaybeWrapValueToMessage(ReflectedCopy(message)->GetDescriptor(), value, arena()); EXPECT_TRUE(result != nullptr); EXPECT_THAT(result, testutil::EqualsProto(message)); } void ExpectNotWrapped(const CelValue& value, const google::protobuf::Message& message) { auto result = MaybeWrapValueToMessage(message.GetDescriptor(), value, arena()); EXPECT_TRUE(result == nullptr); } template <class T> void ExpectUnwrappedPrimitive(const google::protobuf::Message& message, T result) { CelValue cel_value = UnwrapMessageToValue(&message, &ProtobufValueFactoryImpl, arena()); T value; EXPECT_TRUE(cel_value.GetValue(&value)); EXPECT_THAT(value, Eq(result)); T dyn_value; CelValue cel_dyn_value = UnwrapMessageToValue( ReflectedCopy(message).get(), &ProtobufValueFactoryImpl, arena()); EXPECT_THAT(cel_dyn_value.type(), Eq(cel_value.type())); EXPECT_TRUE(cel_dyn_value.GetValue(&dyn_value)); EXPECT_THAT(value, Eq(dyn_value)); } void ExpectUnwrappedMessage(const google::protobuf::Message& message, google::protobuf::Message* result) { CelValue cel_value = UnwrapMessageToValue(&message, &ProtobufValueFactoryImpl, arena()); if (result == nullptr) { EXPECT_TRUE(cel_value.IsNull()); return; } EXPECT_TRUE(cel_value.IsMessage()); EXPECT_THAT(cel_value.MessageOrDie(), testutil::EqualsProto(*result)); } std::unique_ptr<google::protobuf::Message> ReflectedCopy( const google::protobuf::Message& message) { std::unique_ptr<google::protobuf::Message> dynamic_value( factory_.GetPrototype(message.GetDescriptor())->New()); dynamic_value->CopyFrom(message); return dynamic_value; } Arena* arena() { return &arena_; } private: Arena arena_; google::protobuf::DynamicMessageFactory factory_; }; TEST_F(CelProtoWrapperTest, TestType) { Duration msg_duration; msg_duration.set_seconds(2); msg_duration.set_nanos(3); CelValue value_duration2 = UnwrapMessageToValue(&msg_duration, &ProtobufValueFactoryImpl, arena()); EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration)); Timestamp msg_timestamp; msg_timestamp.set_seconds(2); msg_timestamp.set_nanos(3); CelValue value_timestamp2 = UnwrapMessageToValue(&msg_timestamp, &ProtobufValueFactoryImpl, arena()); EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp)); } TEST_F(CelProtoWrapperTest, TestDuration) { Duration msg_duration; msg_duration.set_seconds(2); msg_duration.set_nanos(3); CelValue value = UnwrapMessageToValue(&msg_duration, &ProtobufValueFactoryImpl, arena()); EXPECT_THAT(value.type(), Eq(CelValue::Type::kDuration)); Duration out; auto status = cel::internal::EncodeDuration(value.DurationOrDie(), &out); EXPECT_TRUE(status.ok()); EXPECT_THAT(out, testutil::EqualsProto(msg_duration)); } TEST_F(CelProtoWrapperTest, TestTimestamp) { Timestamp msg_timestamp; msg_timestamp.set_seconds(2); msg_timestamp.set_nanos(3); CelValue value = UnwrapMessageToValue(&msg_timestamp, &ProtobufValueFactoryImpl, arena()); EXPECT_TRUE(value.IsTimestamp()); Timestamp out; auto status = cel::internal::EncodeTime(value.TimestampOrDie(), &out); EXPECT_TRUE(status.ok()); EXPECT_THAT(out, testutil::EqualsProto(msg_timestamp)); } TEST_F(CelProtoWrapperTest, UnwrapMessageToValueNull) { Value json; json.set_null_value(google::protobuf::NullValue::NULL_VALUE); ExpectUnwrappedMessage(json, nullptr); } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueNull) { Value value_msg; value_msg.set_null_value(protobuf::NULL_VALUE); CelValue value = UnwrapMessageToValue(ReflectedCopy(value_msg).get(), &ProtobufValueFactoryImpl, arena()); EXPECT_TRUE(value.IsNull()); } TEST_F(CelProtoWrapperTest, UnwrapMessageToValueBool) { bool value = true; Value json; json.set_bool_value(true); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, UnwrapMessageToValueNumber) { double value = 1.0; Value json; json.set_number_value(value); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, UnwrapMessageToValueString) { const std::string test = "test"; auto value = CelValue::StringHolder(&test); Value json; json.set_string_value(test); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, UnwrapMessageToValueStruct) { const std::vector<std::string> kFields = {"field1", "field2", "field3"}; Struct value_struct; auto& value1 = (*value_struct.mutable_fields())[kFields[0]]; value1.set_bool_value(true); auto& value2 = (*value_struct.mutable_fields())[kFields[1]]; value2.set_number_value(1.0); auto& value3 = (*value_struct.mutable_fields())[kFields[2]]; value3.set_string_value("test"); CelValue value = UnwrapMessageToValue(&value_struct, &ProtobufValueFactoryImpl, arena()); ASSERT_TRUE(value.IsMap()); const CelMap* cel_map = value.MapOrDie(); CelValue field1 = CelValue::CreateString(&kFields[0]); auto field1_presence = cel_map->Has(field1); ASSERT_OK(field1_presence); EXPECT_TRUE(*field1_presence); auto lookup1 = (*cel_map)[field1]; ASSERT_TRUE(lookup1.has_value()); ASSERT_TRUE(lookup1->IsBool()); EXPECT_EQ(lookup1->BoolOrDie(), true); CelValue field2 = CelValue::CreateString(&kFields[1]); auto field2_presence = cel_map->Has(field2); ASSERT_OK(field2_presence); EXPECT_TRUE(*field2_presence); auto lookup2 = (*cel_map)[field2]; ASSERT_TRUE(lookup2.has_value()); ASSERT_TRUE(lookup2->IsDouble()); EXPECT_DOUBLE_EQ(lookup2->DoubleOrDie(), 1.0); CelValue field3 = CelValue::CreateString(&kFields[2]); auto field3_presence = cel_map->Has(field3); ASSERT_OK(field3_presence); EXPECT_TRUE(*field3_presence); auto lookup3 = (*cel_map)[field3]; ASSERT_TRUE(lookup3.has_value()); ASSERT_TRUE(lookup3->IsString()); EXPECT_EQ(lookup3->StringOrDie().value(), "test"); std::string missing = "missing_field"; CelValue missing_field = CelValue::CreateString(&missing); auto missing_field_presence = cel_map->Has(missing_field); ASSERT_OK(missing_field_presence); EXPECT_FALSE(*missing_field_presence); const CelList* key_list = cel_map->ListKeys().value(); ASSERT_EQ(key_list->size(), kFields.size()); std::vector<std::string> result_keys; for (int i = 0; i < key_list->size(); i++) { CelValue key = (*key_list)[i]; ASSERT_TRUE(key.IsString()); result_keys.push_back(std::string(key.StringOrDie().value())); } EXPECT_THAT(result_keys, UnorderedPointwise(Eq(), kFields)); } TEST_F(CelProtoWrapperTest, UnwrapDynamicStruct) { Struct struct_msg; const std::string kFieldInt = "field_int"; const std::string kFieldBool = "field_bool"; (*struct_msg.mutable_fields())[kFieldInt].set_number_value(1.); (*struct_msg.mutable_fields())[kFieldBool].set_bool_value(true); CelValue value = UnwrapMessageToValue(ReflectedCopy(struct_msg).get(), &ProtobufValueFactoryImpl, arena()); EXPECT_TRUE(value.IsMap()); const CelMap* cel_map = value.MapOrDie(); ASSERT_TRUE(cel_map != nullptr); { auto lookup = (*cel_map)[CelValue::CreateString(&kFieldInt)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsDouble()); EXPECT_THAT(v.DoubleOrDie(), testing::DoubleEq(1.)); } { auto lookup = (*cel_map)[CelValue::CreateString(&kFieldBool)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsBool()); EXPECT_EQ(v.BoolOrDie(), true); } { auto presence = cel_map->Has(CelValue::CreateBool(true)); ASSERT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); auto lookup = (*cel_map)[CelValue::CreateBool(true)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsError()); } } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueStruct) { const std::string kField1 = "field1"; const std::string kField2 = "field2"; Value value_msg; (*value_msg.mutable_struct_value()->mutable_fields())[kField1] .set_number_value(1); (*value_msg.mutable_struct_value()->mutable_fields())[kField2] .set_number_value(2); CelValue value = UnwrapMessageToValue(ReflectedCopy(value_msg).get(), &ProtobufValueFactoryImpl, arena()); EXPECT_TRUE(value.IsMap()); EXPECT_TRUE( (*value.MapOrDie())[CelValue::CreateString(&kField1)].has_value()); EXPECT_TRUE( (*value.MapOrDie())[CelValue::CreateString(&kField2)].has_value()); } TEST_F(CelProtoWrapperTest, UnwrapMessageToValueList) { const std::vector<std::string> kFields = {"field1", "field2", "field3"}; ListValue list_value; list_value.add_values()->set_bool_value(true); list_value.add_values()->set_number_value(1.0); list_value.add_values()->set_string_value("test"); CelValue value = UnwrapMessageToValue(&list_value, &ProtobufValueFactoryImpl, arena()); ASSERT_TRUE(value.IsList()); const CelList* cel_list = value.ListOrDie(); ASSERT_EQ(cel_list->size(), 3); CelValue value1 = (*cel_list)[0]; ASSERT_TRUE(value1.IsBool()); EXPECT_EQ(value1.BoolOrDie(), true); auto value2 = (*cel_list)[1]; ASSERT_TRUE(value2.IsDouble()); EXPECT_DOUBLE_EQ(value2.DoubleOrDie(), 1.0); auto value3 = (*cel_list)[2]; ASSERT_TRUE(value3.IsString()); EXPECT_EQ(value3.StringOrDie().value(), "test"); } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueListValue) { Value value_msg; value_msg.mutable_list_value()->add_values()->set_number_value(1.); value_msg.mutable_list_value()->add_values()->set_number_value(2.); CelValue value = UnwrapMessageToValue(ReflectedCopy(value_msg).get(), &ProtobufValueFactoryImpl, arena()); EXPECT_TRUE(value.IsList()); EXPECT_THAT((*value.ListOrDie())[0].DoubleOrDie(), testing::DoubleEq(1)); EXPECT_THAT((*value.ListOrDie())[1].DoubleOrDie(), testing::DoubleEq(2)); } TEST_F(CelProtoWrapperTest, UnwrapAnyValue) { TestMessage test_message; test_message.set_string_value("test"); Any any; any.PackFrom(test_message); ExpectUnwrappedMessage(any, &test_message); } TEST_F(CelProtoWrapperTest, UnwrapInvalidAny) { Any any; CelValue value = UnwrapMessageToValue(&any, &ProtobufValueFactoryImpl, arena()); ASSERT_TRUE(value.IsError()); any.set_type_url("/"); ASSERT_TRUE( UnwrapMessageToValue(&any, &ProtobufValueFactoryImpl, arena()).IsError()); any.set_type_url("/invalid.proto.name"); ASSERT_TRUE( UnwrapMessageToValue(&any, &ProtobufValueFactoryImpl, arena()).IsError()); } TEST_F(CelProtoWrapperTest, UnwrapBoolWrapper) { bool value = true; BoolValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapInt32Wrapper) { int64_t value = 12; Int32Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapUInt32Wrapper) { uint64_t value = 12; UInt32Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapInt64Wrapper) { int64_t value = 12; Int64Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapUInt64Wrapper) { uint64_t value = 12; UInt64Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapFloatWrapper) { double value = 42.5; FloatValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapDoubleWrapper) { double value = 42.5; DoubleValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapStringWrapper) { std::string text = "42"; auto value = CelValue::StringHolder(&text); StringValue wrapper; wrapper.set_value(text); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapBytesWrapper) { std::string text = "42"; auto value = CelValue::BytesHolder(&text); BytesValue wrapper; wrapper.set_value("42"); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, WrapNull) { auto cel_value = CelValue::CreateNull(); Value json; json.set_null_value(protobuf::NULL_VALUE); ExpectWrappedMessage(cel_value, json); Any any; any.PackFrom(json); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBool) { auto cel_value = CelValue::CreateBool(true); Value json; json.set_bool_value(true); ExpectWrappedMessage(cel_value, json); BoolValue wrapper; wrapper.set_value(true); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBytes) { std::string str = "hello world"; auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str)); BytesValue wrapper; wrapper.set_value(str); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBytesToValue) { std::string str = "hello world"; auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str)); Value json; json.set_string_value("aGVsbG8gd29ybGQ="); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapDuration) { auto cel_value = CelValue::CreateDuration(absl::Seconds(300)); Duration d; d.set_seconds(300); ExpectWrappedMessage(cel_value, d); Any any; any.PackFrom(d); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapDurationToValue) { auto cel_value = CelValue::CreateDuration(absl::Seconds(300)); Value json; json.set_string_value("300s"); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapDouble) { double num = 1.5; auto cel_value = CelValue::CreateDouble(num); Value json; json.set_number_value(num); ExpectWrappedMessage(cel_value, json); DoubleValue wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapDoubleToFloatValue) { double num = 1.5; auto cel_value = CelValue::CreateDouble(num); FloatValue wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); double small_num = -9.9e-100; wrapper.set_value(small_num); cel_value = CelValue::CreateDouble(small_num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapDoubleOverflow) { double lowest_double = std::numeric_limits<double>::lowest(); auto cel_value = CelValue::CreateDouble(lowest_double); FloatValue wrapper; wrapper.set_value(-std::numeric_limits<float>::infinity()); ExpectWrappedMessage(cel_value, wrapper); double max_double = std::numeric_limits<double>::max(); cel_value = CelValue::CreateDouble(max_double); wrapper.set_value(std::numeric_limits<float>::infinity()); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapInt64) { int32_t num = std::numeric_limits<int32_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Value json; json.set_number_value(static_cast<double>(num)); ExpectWrappedMessage(cel_value, json); Int64Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapInt64ToInt32Value) { int32_t num = std::numeric_limits<int32_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Int32Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapFailureInt64ToInt32Value) { int64_t num = std::numeric_limits<int64_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Int32Value wrapper; ExpectNotWrapped(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapInt64ToValue) { int64_t max = std::numeric_limits<int64_t>::max(); auto cel_value = CelValue::CreateInt64(max); Value json; json.set_string_value(absl::StrCat(max)); ExpectWrappedMessage(cel_value, json); int64_t min = std::numeric_limits<int64_t>::min(); cel_value = CelValue::CreateInt64(min); json.set_string_value(absl::StrCat(min)); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapUint64) { uint32_t num = std::numeric_limits<uint32_t>::max(); auto cel_value = CelValue::CreateUint64(num); Value json; json.set_number_value(static_cast<double>(num)); ExpectWrappedMessage(cel_value, json); UInt64Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapUint64ToUint32Value) { uint32_t num = std::numeric_limits<uint32_t>::max(); auto cel_value = CelValue::CreateUint64(num); UInt32Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapUint64ToValue) { uint64_t num = std::numeric_limits<uint64_t>::max(); auto cel_value = CelValue::CreateUint64(num); Value json; json.set_string_value(absl::StrCat(num)); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureUint64ToUint32Value) { uint64_t num = std::numeric_limits<uint64_t>::max(); auto cel_value = CelValue::CreateUint64(num); UInt32Value wrapper; ExpectNotWrapped(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapString) { std::string str = "test"; auto cel_value = CelValue::CreateString(CelValue::StringHolder(&str)); Value json; json.set_string_value(str); ExpectWrappedMessage(cel_value, json); StringValue wrapper; wrapper.set_value(str); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapTimestamp) { absl::Time ts = absl::FromUnixSeconds(1615852799); auto cel_value = CelValue::CreateTimestamp(ts); Timestamp t; t.set_seconds(1615852799); ExpectWrappedMessage(cel_value, t); Any any; any.PackFrom(t); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapTimestampToValue) { absl::Time ts = absl::FromUnixSeconds(1615852799); auto cel_value = CelValue::CreateTimestamp(ts); Value json; json.set_string_value("2021-03-15T23:59:59Z"); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapList) { std::vector<CelValue> list_elems = { CelValue::CreateDouble(1.5), CelValue::CreateInt64(-2L), }; ContainerBackedListImpl list(std::move(list_elems)); auto cel_value = CelValue::CreateList(&list); Value json; json.mutable_list_value()->add_values()->set_number_value(1.5); json.mutable_list_value()->add_values()->set_number_value(-2.); ExpectWrappedMessage(cel_value, json); ExpectWrappedMessage(cel_value, json.list_value()); Any any; any.PackFrom(json.list_value()); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapFailureListValueBadJSON) { TestMessage message; std::vector<CelValue> list_elems = { CelValue::CreateDouble(1.5), UnwrapMessageToValue(&message, &ProtobufValueFactoryImpl, arena()), }; ContainerBackedListImpl list(std::move(list_elems)); auto cel_value = CelValue::CreateList(&list); Value json; ExpectNotWrapped(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapStruct) { const std::string kField1 = "field1"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(CelValue::StringHolder(&kField1)), CelValue::CreateBool(true)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); auto cel_value = CelValue::CreateMap(cel_map.get()); Value json; (*json.mutable_struct_value()->mutable_fields())[kField1].set_bool_value( true); ExpectWrappedMessage(cel_value, json); ExpectWrappedMessage(cel_value, json.struct_value()); Any any; any.PackFrom(json.struct_value()); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapFailureStructBadKeyType) { std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateInt64(1L), CelValue::CreateBool(true)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); auto cel_value = CelValue::CreateMap(cel_map.get()); Value json; ExpectNotWrapped(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureStructBadValueType) { const std::string kField1 = "field1"; TestMessage bad_value; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(CelValue::StringHolder(&kField1)), UnwrapMessageToValue(&bad_value, &ProtobufValueFactoryImpl, arena())}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); auto cel_value = CelValue::CreateMap(cel_map.get()); Value json; ExpectNotWrapped(cel_value, json); } class TestMap : public CelMapBuilder { public: absl::StatusOr<const CelList*> ListKeys() const override { return absl::UnimplementedError("test"); } }; TEST_F(CelProtoWrapperTest, WrapFailureStructListKeysUnimplemented) { const std::string kField1 = "field1"; TestMap map; ASSERT_OK(map.Add(CelValue::CreateString(CelValue::StringHolder(&kField1)), CelValue::CreateString(CelValue::StringHolder(&kField1)))); auto cel_value = CelValue::CreateMap(&map); Value json; ExpectNotWrapped(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureWrongType) { auto cel_value = CelValue::CreateNull(); std::vector<const google::protobuf::Message*> wrong_types = { &BoolValue::default_instance(), &BytesValue::default_instance(), &DoubleValue::default_instance(), &Duration::default_instance(), &FloatValue::default_instance(), &Int32Value::default_instance(), &Int64Value::default_instance(), &ListValue::default_instance(), &StringValue::default_instance(), &Struct::default_instance(), &Timestamp::default_instance(), &UInt32Value::default_instance(), &UInt64Value::default_instance(), }; for (const auto* wrong_type : wrong_types) { ExpectNotWrapped(cel_value, *wrong_type); } } TEST_F(CelProtoWrapperTest, WrapFailureErrorToAny) { auto cel_value = CreateNoSuchFieldError(arena(), "error_field"); ExpectNotWrapped(cel_value, Any::default_instance()); } TEST_F(CelProtoWrapperTest, DebugString) { google::protobuf::Empty e; EXPECT_EQ(UnwrapMessageToValue(&e, &ProtobufValueFactoryImpl, arena()) .DebugString(), "Message: opaque"); ListValue list_value; list_value.add_values()->set_bool_value(true); list_value.add_values()->set_number_value(1.0); list_value.add_values()->set_string_value("test"); CelValue value = UnwrapMessageToValue(&list_value, &ProtobufValueFactoryImpl, arena()); EXPECT_EQ(value.DebugString(), "CelList: [bool: 1, double: 1.000000, string: test]"); Struct value_struct; auto& value1 = (*value_struct.mutable_fields())["a"]; value1.set_bool_value(true); auto& value2 = (*value_struct.mutable_fields())["b"]; value2.set_number_value(1.0); auto& value3 = (*value_struct.mutable_fields())["c"]; value3.set_string_value("test"); value = UnwrapMessageToValue(&value_struct, &ProtobufValueFactoryImpl, arena()); EXPECT_THAT( value.DebugString(), testing::AllOf(testing::StartsWith("CelMap: {"), testing::HasSubstr("<string: a>: <bool: 1>"), testing::HasSubstr("<string: b>: <double: 1.0"), testing::HasSubstr("<string: c>: <string: test>"))); } } }
107
cpp
google/cel-cpp
cel_proto_lite_wrap_util
eval/public/structs/cel_proto_lite_wrap_util.cc
eval/public/structs/cel_proto_lite_wrap_util_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_LITE_WRAP_UTIL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_LITE_WRAP_UTIL_H_ #include <optional> #include <string> #include <string_view> #include <type_traits> #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/arena.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "eval/public/cel_value.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "eval/public/structs/legacy_type_provider.h" namespace google::api::expr::runtime::internal { CelValue CreateCelValue(bool value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(int32_t value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(int64_t value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(uint32_t value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(uint64_t value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(float value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(double value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const std::string& value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const absl::Cord& value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::BoolValue& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Duration& duration, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Timestamp& timestamp, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const std::string& value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Int32Value& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Int64Value& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::UInt32Value& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::UInt64Value& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::FloatValue& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::DoubleValue& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Value& value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::ListValue& list_value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Struct& struct_value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::StringValue& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::BytesValue& wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const google::protobuf::Any& any_value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); CelValue CreateCelValue(const std::string_view string_value, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); template <typename T> inline CelValue CreateCelValue(const T& message, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena) { static_assert(!std::is_base_of_v<google::protobuf::MessageLite, T*>, "Call to templated version of CreateCelValue with " "non-MessageLite derived type name. Please specialize the " "implementation to support this new type."); std::optional<const LegacyTypeInfoApis*> maybe_type_info = type_provider->ProvideLegacyTypeInfo(message.GetTypeName()); return CelValue::CreateMessageWrapper( CelValue::MessageWrapper(&message, maybe_type_info.value_or(nullptr))); } template <typename T> inline CelValue CreateCelValue(const T* message_pointer, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena) { static_assert( !std::is_base_of_v<google::protobuf::MessageLite, T> && !std::is_same_v<google::protobuf::MessageLite, T>, "Call to CreateCelValue with MessageLite pointer is not allowed. Please " "call this function with a reference to the object."); static_assert( std::is_base_of_v<google::protobuf::MessageLite, T>, "Call to CreateCelValue with a pointer is not " "allowed. Try calling this function with a reference to the object."); return CreateErrorValue(arena, "Unintended call to CreateCelValue " "with a pointer."); } absl::StatusOr<CelValue> UnwrapFromWellKnownType( const google::protobuf::MessageLite* message, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::DoubleValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::DoubleValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::FloatValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::FloatValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Int32Value*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Int32Value* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::UInt32Value*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::UInt32Value* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Int64Value*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Int64Value* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::UInt64Value*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::UInt64Value* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::StringValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::StringValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::BytesValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::BytesValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::BoolValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::BoolValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Any*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Any* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Duration*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Duration* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<::google::protobuf::Timestamp*> CreateMessageFromValue( const CelValue& cel_value, ::google::protobuf::Timestamp* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Value*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Value* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::ListValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::ListValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Struct*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Struct* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::StringValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::StringValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::BytesValue*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::BytesValue* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); absl::StatusOr<google::protobuf::Any*> CreateMessageFromValue( const CelValue& cel_value, google::protobuf::Any* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena); template <typename T> inline absl::StatusOr<T*> CreateMessageFromValue( const CelValue& cel_value, T* wrapper, const LegacyTypeProvider* type_provider, google::protobuf::Arena* arena) { return absl::UnimplementedError("Not implemented"); } } #endif #include "eval/public/structs/cel_proto_lite_wrap_util.h" #include <math.h> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <string_view> #include <utility> #include <vector> #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/message.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "eval/public/cel_value.h" #include "eval/public/structs/legacy_any_packing.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "eval/testutil/test_message.pb.h" #include "internal/casts.h" #include "internal/overflow.h" #include "internal/proto_time_encoding.h" namespace google::api::expr::runtime::internal { namespace { using cel::internal::DecodeDuration; using cel::internal::DecodeTime; using cel::internal::EncodeTime; using google::protobuf::Any; using google::protobuf::BoolValue; using google::protobuf::BytesValue; using google::protobuf::DoubleValue; using google::protobuf::Duration; using google::protobuf::FloatValue; using google::protobuf::Int32Value; using google::protobuf::Int64Value; using google::protobuf::ListValue; using google::protobuf::StringValue; using google::protobuf::Struct; using google::protobuf::Timestamp; using google::protobuf::UInt32Value; using google::protobuf::UInt64Value; using google::protobuf::Value; using google::protobuf::Arena; constexpr int64_t kMaxIntJSON = (1ll << 53) - 1; constexpr int64_t kMinIntJSON = -kMaxIntJSON; typedef enum { kUnknown, kBoolValue, kDoubleValue, kFloatValue, kInt32Value, kInt64Value, kUInt32Value, kUInt64Value, kDuration, kTimestamp, kStruct, kListValue, kValue, kStringValue, kBytesValue, kAny } WellKnownType; WellKnownType GetWellKnownType(absl::string_view type_name) { static auto* well_known_types_map = new absl::flat_hash_map<std::string, WellKnownType>( {{"google.protobuf.BoolValue", kBoolValue}, {"google.protobuf.DoubleValue", kDoubleValue}, {"google.protobuf.FloatValue", kFloatValue}, {"google.protobuf.Int32Value", kInt32Value}, {"google.protobuf.Int64Value", kInt64Value}, {"google.protobuf.UInt32Value", kUInt32Value}, {"google.protobuf.UInt64Value", kUInt64Value}, {"google.protobuf.Duration", kDuration}, {"google.protobuf.Timestamp", kTimestamp}, {"google.protobuf.Struct", kStruct}, {"google.protobuf.ListValue", kListValue}, {"google.protobuf.Value", kValue}, {"google.protobuf.StringValue", kStringValue}, {"google.protobuf.BytesValue", kBytesValue}, {"google.protobuf.Any", kAny}}); if (!well_known_types_map->contains(type_name)) { return kUnknown; } return well_known_types_map->at(type_name); } static bool IsJSONSafe(int64_t i) { return i >= kMinIntJSON && i <= kMaxIntJSON; } static bool IsJSONSafe(uint64_t i) { return i <= static_cast<uint64_t>(kMaxIntJSON); } class DynamicList : public CelList { public: DynamicList(const ListValue* values, const LegacyTypeProvider* type_provider, Arena* arena) : arena_(arena), type_provider_(type_provider), values_(values) {} CelValue operator[](int index) const override; int size() const override { return values_->values_size(); } private: Arena* arena_; const LegacyTypeProvider* type_provider_; const ListValue* values_; }; class DynamicMap : public CelMap { public: DynamicMap(const Struct* values, const LegacyTypeProvider* type_provider, Arena* arena) : arena_(arena), values_(values), type_provider_(type_provider), key_list_(values) {} absl::StatusOr<bool> Has(const CelValue& key) const override { CelValue::StringHolder str_key; if (!key.GetValue(&str_key)) { return absl::InvalidArgumentError(absl::StrCat( "Invalid map key type: '", CelValue::TypeName(key.type()), "'")); } return values_->fields().contains(std::string(str_key.value())); } absl::optional<CelValue> operator[](CelValue key) const override; int size() const override { return values_->fields_size(); } absl::StatusOr<const CelList*> ListKeys() const override { return &key_list_; } private: class DynamicMapKeyList : public CelList { public: explicit DynamicMapKeyList(const Struct* values) : values_(values), keys_(), initialized_(false) {} CelValue operator[](int index) const override { CheckInit(); return keys_[index]; } int size() const override { CheckInit(); return values_->fields_size(); } private: void CheckInit() const { absl::MutexLock lock(&mutex_); if (!initialized_) { for (const auto& it : values_->fields()) { keys_.push_back(CelValue::CreateString(&it.first)); } initialized_ = true; } } const Struct* values_; mutable absl::Mutex mutex_; mutable std::vector<CelValue> keys_; mutable bool initialized_; }; Arena* arena_; const Struct* values_; const LegacyTypeProvider* type_provider_; const DynamicMapKeyList key_list_; }; } CelValue CreateCelValue(const Duration& duration, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateDuration(DecodeDuration(duration)); } CelValue CreateCelValue(const Timestamp& timestamp, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateTimestamp(DecodeTime(timestamp)); } CelValue CreateCelValue(const ListValue& list_values, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateList( Arena::Create<DynamicList>(arena, &list_values, type_provider, arena)); } CelValue CreateCelValue(const Struct& struct_value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateMap( Arena::Create<DynamicMap>(arena, &struct_value, type_provider, arena)); } CelValue CreateCelValue(const Any& any_value, const LegacyTypeProvider* type_provider, Arena* arena) { auto type_url = any_value.type_url(); auto pos = type_url.find_last_of('/'); if (pos == absl::string_view::npos) { return CreateErrorValue(arena, "Malformed type_url string"); } std::string full_name = std::string(type_url.substr(pos + 1)); WellKnownType type = GetWellKnownType(full_name); switch (type) { case kDoubleValue: { DoubleValue* nested_message = Arena::Create<DoubleValue>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into DoubleValue"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kFloatValue: { FloatValue* nested_message = Arena::Create<FloatValue>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into FloatValue"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kInt32Value: { Int32Value* nested_message = Arena::Create<Int32Value>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Int32Value"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kInt64Value: { Int64Value* nested_message = Arena::Create<Int64Value>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Int64Value"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kUInt32Value: { UInt32Value* nested_message = Arena::Create<UInt32Value>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into UInt32Value"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kUInt64Value: { UInt64Value* nested_message = Arena::Create<UInt64Value>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into UInt64Value"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kBoolValue: { BoolValue* nested_message = Arena::Create<BoolValue>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into BoolValue"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kTimestamp: { Timestamp* nested_message = Arena::Create<Timestamp>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Timestamp"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kDuration: { Duration* nested_message = Arena::Create<Duration>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Duration"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kStringValue: { StringValue* nested_message = Arena::Create<StringValue>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into StringValue"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kBytesValue: { BytesValue* nested_message = Arena::Create<BytesValue>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into BytesValue"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kListValue: { ListValue* nested_message = Arena::Create<ListValue>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into ListValue"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kStruct: { Struct* nested_message = Arena::Create<Struct>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Struct"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kValue: { Value* nested_message = Arena::Create<Value>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Value"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kAny: { Any* nested_message = Arena::Create<Any>(arena); if (!any_value.UnpackTo(nested_message)) { return CreateErrorValue(arena, "Failed to unpack Any into Any"); } return CreateCelValue(*nested_message, type_provider, arena); } break; case kUnknown: if (type_provider == nullptr) { return CreateErrorValue(arena, "Provided LegacyTypeProvider is nullptr"); } std::optional<const LegacyAnyPackingApis*> any_apis = type_provider->ProvideLegacyAnyPackingApis(full_name); if (!any_apis.has_value()) { return CreateErrorValue( arena, "Failed to get AnyPackingApis for " + full_name); } std::optional<const LegacyTypeInfoApis*> type_info = type_provider->ProvideLegacyTypeInfo(full_name); if (!type_info.has_value()) { return CreateErrorValue(arena, "Failed to get TypeInfo for " + full_name); } absl::StatusOr<google::protobuf::MessageLite*> nested_message = (*any_apis)->Unpack(any_value, arena); if (!nested_message.ok()) { return CreateErrorValue(arena, "Failed to unpack Any into " + full_name); } return CelValue::CreateMessageWrapper( CelValue::MessageWrapper(*nested_message, *type_info)); } } CelValue CreateCelValue(bool value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateBool(value); } CelValue CreateCelValue(int32_t value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateInt64(value); } CelValue CreateCelValue(int64_t value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateInt64(value); } CelValue CreateCelValue(uint32_t value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateUint64(value); } CelValue CreateCelValue(uint64_t value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateUint64(value); } CelValue CreateCelValue(float value, const LegacyTypeProvider* type_provider, Arena* arena) { return CelValue::CreateDouble(value); } CelValue CreateCelValue(double value, const LegacyTypeProvider* type_provider,
#include "eval/public/structs/cel_proto_lite_wrap_util.h" #include <cassert> #include <limits> #include <memory> #include <optional> #include <string> #include <string_view> #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/wrappers.pb.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/message.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/structs/legacy_any_packing.h" #include "eval/public/structs/protobuf_descriptor_type_provider.h" #include "eval/testutil/test_message.pb.h" #include "internal/proto_time_encoding.h" #include "internal/testing.h" #include "testutil/util.h" namespace google::api::expr::runtime::internal { namespace { using testing::Eq; using testing::UnorderedPointwise; using cel::internal::StatusIs; using testutil::EqualsProto; using google::protobuf::Duration; using google::protobuf::ListValue; using google::protobuf::Struct; using google::protobuf::Timestamp; using google::protobuf::Value; using google::protobuf::Any; using google::protobuf::BoolValue; using google::protobuf::BytesValue; using google::protobuf::DoubleValue; using google::protobuf::FloatValue; using google::protobuf::Int32Value; using google::protobuf::Int64Value; using google::protobuf::StringValue; using google::protobuf::UInt32Value; using google::protobuf::UInt64Value; using google::protobuf::Arena; class ProtobufDescriptorAnyPackingApis : public LegacyAnyPackingApis { public: ProtobufDescriptorAnyPackingApis(const google::protobuf::DescriptorPool* pool, google::protobuf::MessageFactory* factory) : descriptor_pool_(pool), message_factory_(factory) {} absl::StatusOr<google::protobuf::MessageLite*> Unpack( const google::protobuf::Any& any_message, google::protobuf::Arena* arena) const override { auto type_url = any_message.type_url(); auto pos = type_url.find_last_of('/'); if (pos == absl::string_view::npos) { return absl::InternalError("Malformed type_url string"); } std::string full_name = std::string(type_url.substr(pos + 1)); const google::protobuf::Descriptor* nested_descriptor = descriptor_pool_->FindMessageTypeByName(full_name); if (nested_descriptor == nullptr) { return absl::InternalError("Descriptor not found"); } const google::protobuf::Message* prototype = message_factory_->GetPrototype(nested_descriptor); if (prototype == nullptr) { return absl::InternalError("Prototype not found"); } google::protobuf::Message* nested_message = prototype->New(arena); if (!any_message.UnpackTo(nested_message)) { return absl::InternalError("Failed to unpack Any into message"); } return nested_message; } absl::Status Pack(const google::protobuf::MessageLite* message, google::protobuf::Any& any_message) const override { const google::protobuf::Message* message_ptr = cel::internal::down_cast<const google::protobuf::Message*>(message); any_message.PackFrom(*message_ptr); return absl::OkStatus(); } private: const google::protobuf::DescriptorPool* descriptor_pool_; google::protobuf::MessageFactory* message_factory_; }; class ProtobufDescriptorProviderWithAny : public ProtobufDescriptorProvider { public: ProtobufDescriptorProviderWithAny(const google::protobuf::DescriptorPool* pool, google::protobuf::MessageFactory* factory) : ProtobufDescriptorProvider(pool, factory), any_packing_apis_(std::make_unique<ProtobufDescriptorAnyPackingApis>( pool, factory)) {} absl::optional<const LegacyAnyPackingApis*> ProvideLegacyAnyPackingApis( absl::string_view name) const override { return any_packing_apis_.get(); } private: std::unique_ptr<ProtobufDescriptorAnyPackingApis> any_packing_apis_; }; class ProtobufDescriptorProviderWithoutAny : public ProtobufDescriptorProvider { public: ProtobufDescriptorProviderWithoutAny(const google::protobuf::DescriptorPool* pool, google::protobuf::MessageFactory* factory) : ProtobufDescriptorProvider(pool, factory) {} absl::optional<const LegacyAnyPackingApis*> ProvideLegacyAnyPackingApis( absl::string_view name) const override { return std::nullopt; } }; class CelProtoWrapperTest : public ::testing::Test { protected: CelProtoWrapperTest() : type_provider_(std::make_unique<ProtobufDescriptorProviderWithAny>( google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory())) { factory_.SetDelegateToGeneratedFactory(true); } template <class MessageType> void ExpectWrappedMessage(const CelValue& value, const MessageType& message) { MessageType* tested_message = nullptr; absl::StatusOr<MessageType*> result = CreateMessageFromValue(value, tested_message, type_provider(), arena()); EXPECT_OK(result); tested_message = *result; EXPECT_TRUE(tested_message != nullptr); EXPECT_THAT(*tested_message, EqualsProto(message)); MessageType* created_message = Arena::Create<MessageType>(arena()); result = CreateMessageFromValue(value, created_message, type_provider(), arena()); EXPECT_EQ(created_message, *result); created_message = *result; EXPECT_TRUE(created_message != nullptr); EXPECT_THAT(*created_message, EqualsProto(message)); } template <class MessageType, class T> void ExpectUnwrappedPrimitive(const MessageType& message, T result) { CelValue cel_value = CreateCelValue(message, type_provider(), arena()); T value; EXPECT_TRUE(cel_value.GetValue(&value)); EXPECT_THAT(value, Eq(result)); T dyn_value; auto reflected_copy = ReflectedCopy(message); absl::StatusOr<CelValue> cel_dyn_value = UnwrapFromWellKnownType(reflected_copy.get(), type_provider(), arena()); EXPECT_OK(cel_dyn_value.status()); EXPECT_THAT(cel_dyn_value->type(), Eq(cel_value.type())); EXPECT_TRUE(cel_dyn_value->GetValue(&dyn_value)); EXPECT_THAT(value, Eq(dyn_value)); Any any; any.PackFrom(message); CelValue any_cel_value = CreateCelValue(any, type_provider(), arena()); T any_value; EXPECT_TRUE(any_cel_value.GetValue(&any_value)); EXPECT_THAT(any_value, Eq(result)); } template <class MessageType> void ExpectUnwrappedMessage(const MessageType& message, google::protobuf::Message* result) { CelValue cel_value = CreateCelValue(message, type_provider(), arena()); if (result == nullptr) { EXPECT_TRUE(cel_value.IsNull()); return; } EXPECT_TRUE(cel_value.IsMessage()); EXPECT_THAT(cel_value.MessageOrDie(), EqualsProto(*result)); } std::unique_ptr<google::protobuf::Message> ReflectedCopy( const google::protobuf::Message& message) { std::unique_ptr<google::protobuf::Message> dynamic_value( factory_.GetPrototype(message.GetDescriptor())->New()); dynamic_value->CopyFrom(message); return dynamic_value; } Arena* arena() { return &arena_; } const LegacyTypeProvider* type_provider() const { return type_provider_.get(); } private: Arena arena_; std::unique_ptr<LegacyTypeProvider> type_provider_; google::protobuf::DynamicMessageFactory factory_; }; TEST_F(CelProtoWrapperTest, TestType) { Duration msg_duration; msg_duration.set_seconds(2); msg_duration.set_nanos(3); CelValue value_duration2 = CreateCelValue(msg_duration, type_provider(), arena()); EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration)); Timestamp msg_timestamp; msg_timestamp.set_seconds(2); msg_timestamp.set_nanos(3); CelValue value_timestamp2 = CreateCelValue(msg_timestamp, type_provider(), arena()); EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp)); } TEST_F(CelProtoWrapperTest, TestDuration) { Duration msg_duration; msg_duration.set_seconds(2); msg_duration.set_nanos(3); CelValue value = CreateCelValue(msg_duration, type_provider(), arena()); EXPECT_THAT(value.type(), Eq(CelValue::Type::kDuration)); Duration out; auto status = cel::internal::EncodeDuration(value.DurationOrDie(), &out); EXPECT_TRUE(status.ok()); EXPECT_THAT(out, EqualsProto(msg_duration)); } TEST_F(CelProtoWrapperTest, TestTimestamp) { Timestamp msg_timestamp; msg_timestamp.set_seconds(2); msg_timestamp.set_nanos(3); CelValue value = CreateCelValue(msg_timestamp, type_provider(), arena()); EXPECT_TRUE(value.IsTimestamp()); Timestamp out; auto status = cel::internal::EncodeTime(value.TimestampOrDie(), &out); EXPECT_TRUE(status.ok()); EXPECT_THAT(out, EqualsProto(msg_timestamp)); } TEST_F(CelProtoWrapperTest, CreateCelValueNull) { Value json; json.set_null_value(google::protobuf::NullValue::NULL_VALUE); ExpectUnwrappedMessage(json, nullptr); } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueNull) { Value value_msg; value_msg.set_null_value(google::protobuf::NullValue::NULL_VALUE); ASSERT_OK_AND_ASSIGN(CelValue value, UnwrapFromWellKnownType(ReflectedCopy(value_msg).get(), type_provider(), arena())); EXPECT_TRUE(value.IsNull()); } TEST_F(CelProtoWrapperTest, CreateCelValueBool) { bool value = true; CelValue cel_value = CreateCelValue(value, type_provider(), arena()); EXPECT_TRUE(cel_value.IsBool()); EXPECT_EQ(cel_value.BoolOrDie(), value); Value json; json.set_bool_value(true); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, CreateCelValueDouble) { double value = 1.0; CelValue cel_value = CreateCelValue(value, type_provider(), arena()); EXPECT_TRUE(cel_value.IsDouble()); EXPECT_DOUBLE_EQ(cel_value.DoubleOrDie(), value); cel_value = CreateCelValue(static_cast<float>(value), type_provider(), arena()); EXPECT_TRUE(cel_value.IsDouble()); EXPECT_DOUBLE_EQ(cel_value.DoubleOrDie(), value); Value json; json.set_number_value(value); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, CreateCelValueInt) { int64_t value = 10; CelValue cel_value = CreateCelValue(value, type_provider(), arena()); EXPECT_TRUE(cel_value.IsInt64()); EXPECT_EQ(cel_value.Int64OrDie(), value); cel_value = CreateCelValue(static_cast<int32_t>(value), type_provider(), arena()); EXPECT_TRUE(cel_value.IsInt64()); EXPECT_EQ(cel_value.Int64OrDie(), value); } TEST_F(CelProtoWrapperTest, CreateCelValueUint) { uint64_t value = 10; CelValue cel_value = CreateCelValue(value, type_provider(), arena()); EXPECT_TRUE(cel_value.IsUint64()); EXPECT_EQ(cel_value.Uint64OrDie(), value); cel_value = CreateCelValue(static_cast<uint32_t>(value), type_provider(), arena()); EXPECT_TRUE(cel_value.IsUint64()); EXPECT_EQ(cel_value.Uint64OrDie(), value); } TEST_F(CelProtoWrapperTest, CreateCelValueString) { const std::string test = "test"; auto value = CelValue::StringHolder(&test); CelValue cel_value = CreateCelValue(test, type_provider(), arena()); EXPECT_TRUE(cel_value.IsString()); EXPECT_EQ(cel_value.StringOrDie().value(), test); Value json; json.set_string_value(test); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, CreateCelValueStringView) { const std::string test = "test"; const std::string_view test_view(test); CelValue cel_value = CreateCelValue(test_view, type_provider(), arena()); EXPECT_TRUE(cel_value.IsString()); EXPECT_EQ(cel_value.StringOrDie().value(), test); } TEST_F(CelProtoWrapperTest, CreateCelValueCord) { const std::string test1 = "test1"; const std::string test2 = "test2"; absl::Cord value; value.Append(test1); value.Append(test2); CelValue cel_value = CreateCelValue(value, type_provider(), arena()); EXPECT_TRUE(cel_value.IsBytes()); EXPECT_EQ(cel_value.BytesOrDie().value(), test1 + test2); } TEST_F(CelProtoWrapperTest, CreateCelValueStruct) { const std::vector<std::string> kFields = {"field1", "field2", "field3"}; Struct value_struct; auto& value1 = (*value_struct.mutable_fields())[kFields[0]]; value1.set_bool_value(true); auto& value2 = (*value_struct.mutable_fields())[kFields[1]]; value2.set_number_value(1.0); auto& value3 = (*value_struct.mutable_fields())[kFields[2]]; value3.set_string_value("test"); CelValue value = CreateCelValue(value_struct, type_provider(), arena()); ASSERT_TRUE(value.IsMap()); const CelMap* cel_map = value.MapOrDie(); EXPECT_EQ(cel_map->size(), 3); CelValue field1 = CelValue::CreateString(&kFields[0]); auto field1_presence = cel_map->Has(field1); ASSERT_OK(field1_presence); EXPECT_TRUE(*field1_presence); auto lookup1 = (*cel_map)[field1]; ASSERT_TRUE(lookup1.has_value()); ASSERT_TRUE(lookup1->IsBool()); EXPECT_EQ(lookup1->BoolOrDie(), true); CelValue field2 = CelValue::CreateString(&kFields[1]); auto field2_presence = cel_map->Has(field2); ASSERT_OK(field2_presence); EXPECT_TRUE(*field2_presence); auto lookup2 = (*cel_map)[field2]; ASSERT_TRUE(lookup2.has_value()); ASSERT_TRUE(lookup2->IsDouble()); EXPECT_DOUBLE_EQ(lookup2->DoubleOrDie(), 1.0); CelValue field3 = CelValue::CreateString(&kFields[2]); auto field3_presence = cel_map->Has(field3); ASSERT_OK(field3_presence); EXPECT_TRUE(*field3_presence); auto lookup3 = (*cel_map)[field3]; ASSERT_TRUE(lookup3.has_value()); ASSERT_TRUE(lookup3->IsString()); EXPECT_EQ(lookup3->StringOrDie().value(), "test"); CelValue wrong_key = CelValue::CreateBool(true); EXPECT_THAT(cel_map->Has(wrong_key), StatusIs(absl::StatusCode::kInvalidArgument)); absl::optional<CelValue> lockup_wrong_key = (*cel_map)[wrong_key]; ASSERT_TRUE(lockup_wrong_key.has_value()); EXPECT_TRUE((*lockup_wrong_key).IsError()); std::string missing = "missing_field"; CelValue missing_field = CelValue::CreateString(&missing); auto missing_field_presence = cel_map->Has(missing_field); ASSERT_OK(missing_field_presence); EXPECT_FALSE(*missing_field_presence); EXPECT_EQ((*cel_map)[missing_field], absl::nullopt); const CelList* key_list = cel_map->ListKeys().value(); ASSERT_EQ(key_list->size(), kFields.size()); std::vector<std::string> result_keys; for (int i = 0; i < key_list->size(); i++) { CelValue key = (*key_list)[i]; ASSERT_TRUE(key.IsString()); result_keys.push_back(std::string(key.StringOrDie().value())); } EXPECT_THAT(result_keys, UnorderedPointwise(Eq(), kFields)); } TEST_F(CelProtoWrapperTest, UnwrapDynamicStruct) { Struct struct_msg; const std::string kFieldInt = "field_int"; const std::string kFieldBool = "field_bool"; (*struct_msg.mutable_fields())[kFieldInt].set_number_value(1.); (*struct_msg.mutable_fields())[kFieldBool].set_bool_value(true); auto reflected_copy = ReflectedCopy(struct_msg); ASSERT_OK_AND_ASSIGN( CelValue value, UnwrapFromWellKnownType(reflected_copy.get(), type_provider(), arena())); EXPECT_TRUE(value.IsMap()); const CelMap* cel_map = value.MapOrDie(); ASSERT_TRUE(cel_map != nullptr); { auto lookup = (*cel_map)[CelValue::CreateString(&kFieldInt)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsDouble()); EXPECT_THAT(v.DoubleOrDie(), testing::DoubleEq(1.)); } { auto lookup = (*cel_map)[CelValue::CreateString(&kFieldBool)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsBool()); EXPECT_EQ(v.BoolOrDie(), true); } { auto presence = cel_map->Has(CelValue::CreateBool(true)); ASSERT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); auto lookup = (*cel_map)[CelValue::CreateBool(true)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsError()); } } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueStruct) { const std::string kField1 = "field1"; const std::string kField2 = "field2"; Value value_msg; (*value_msg.mutable_struct_value()->mutable_fields())[kField1] .set_number_value(1); (*value_msg.mutable_struct_value()->mutable_fields())[kField2] .set_number_value(2); auto reflected_copy = ReflectedCopy(value_msg); ASSERT_OK_AND_ASSIGN( CelValue value, UnwrapFromWellKnownType(reflected_copy.get(), type_provider(), arena())); EXPECT_TRUE(value.IsMap()); EXPECT_TRUE( (*value.MapOrDie())[CelValue::CreateString(&kField1)].has_value()); EXPECT_TRUE( (*value.MapOrDie())[CelValue::CreateString(&kField2)].has_value()); } TEST_F(CelProtoWrapperTest, CreateCelValueList) { const std::vector<std::string> kFields = {"field1", "field2", "field3"}; ListValue list_value; list_value.add_values()->set_bool_value(true); list_value.add_values()->set_number_value(1.0); list_value.add_values()->set_string_value("test"); CelValue value = CreateCelValue(list_value, type_provider(), arena()); ASSERT_TRUE(value.IsList()); const CelList* cel_list = value.ListOrDie(); ASSERT_EQ(cel_list->size(), 3); CelValue value1 = (*cel_list)[0]; ASSERT_TRUE(value1.IsBool()); EXPECT_EQ(value1.BoolOrDie(), true); auto value2 = (*cel_list)[1]; ASSERT_TRUE(value2.IsDouble()); EXPECT_DOUBLE_EQ(value2.DoubleOrDie(), 1.0); auto value3 = (*cel_list)[2]; ASSERT_TRUE(value3.IsString()); EXPECT_EQ(value3.StringOrDie().value(), "test"); Value proto_value; *proto_value.mutable_list_value() = list_value; CelValue cel_value = CreateCelValue(list_value, type_provider(), arena()); ASSERT_TRUE(cel_value.IsList()); } TEST_F(CelProtoWrapperTest, UnwrapListValue) { Value value_msg; value_msg.mutable_list_value()->add_values()->set_number_value(1.); value_msg.mutable_list_value()->add_values()->set_number_value(2.); ASSERT_OK_AND_ASSIGN(CelValue value, UnwrapFromWellKnownType(&value_msg.list_value(), type_provider(), arena())); EXPECT_TRUE(value.IsList()); EXPECT_THAT((*value.ListOrDie())[0].DoubleOrDie(), testing::DoubleEq(1)); EXPECT_THAT((*value.ListOrDie())[1].DoubleOrDie(), testing::DoubleEq(2)); } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueListValue) { Value value_msg; value_msg.mutable_list_value()->add_values()->set_number_value(1.); value_msg.mutable_list_value()->add_values()->set_number_value(2.); auto reflected_copy = ReflectedCopy(value_msg); ASSERT_OK_AND_ASSIGN( CelValue value, UnwrapFromWellKnownType(reflected_copy.get(), type_provider(), arena())); EXPECT_TRUE(value.IsList()); EXPECT_THAT((*value.ListOrDie())[0].DoubleOrDie(), testing::DoubleEq(1)); EXPECT_THAT((*value.ListOrDie())[1].DoubleOrDie(), testing::DoubleEq(2)); } TEST_F(CelProtoWrapperTest, UnwrapNullptr) { google::protobuf::MessageLite* msg = nullptr; ASSERT_OK_AND_ASSIGN(CelValue value, UnwrapFromWellKnownType(msg, type_provider(), arena())); EXPECT_TRUE(value.IsNull()); } TEST_F(CelProtoWrapperTest, UnwrapDuration) { Duration duration; duration.set_seconds(10); ASSERT_OK_AND_ASSIGN( CelValue value, UnwrapFromWellKnownType(&duration, type_provider(), arena())); EXPECT_TRUE(value.IsDuration()); EXPECT_EQ(value.DurationOrDie() / absl::Seconds(1), 10); } TEST_F(CelProtoWrapperTest, UnwrapTimestamp) { Timestamp t; t.set_seconds(1615852799); ASSERT_OK_AND_ASSIGN(CelValue value, UnwrapFromWellKnownType(&t, type_provider(), arena())); EXPECT_TRUE(value.IsTimestamp()); EXPECT_EQ(value.TimestampOrDie(), absl::FromUnixSeconds(1615852799)); } TEST_F(CelProtoWrapperTest, UnwrapUnknown) { TestMessage msg; EXPECT_THAT(UnwrapFromWellKnownType(&msg, type_provider(), arena()), StatusIs(absl::StatusCode::kNotFound)); } TEST_F(CelProtoWrapperTest, UnwrapAnyValue) { const std::string test = "test"; auto string_value = CelValue::StringHolder(&test); Value json; json.set_string_value(test); Any any; any.PackFrom(json); ExpectUnwrappedPrimitive(any, string_value); } TEST_F(CelProtoWrapperTest, UnwrapAnyOfNonWellKnownType) { TestMessage test_message; test_message.set_string_value("test"); Any any; any.PackFrom(test_message); CelValue cel_value = CreateCelValue(any, type_provider(), arena()); ASSERT_TRUE(cel_value.IsMessage()); EXPECT_THAT(cel_value.MessageWrapperOrDie().message_ptr(), EqualsProto(test_message)); } TEST_F(CelProtoWrapperTest, UnwrapNestedAny) { TestMessage test_message; test_message.set_string_value("test"); Any any1; any1.PackFrom(test_message); Any any2; any2.PackFrom(any1); CelValue cel_value = CreateCelValue(any2, type_provider(), arena()); ASSERT_TRUE(cel_value.IsMessage()); EXPECT_THAT(cel_value.MessageWrapperOrDie().message_ptr(), EqualsProto(test_message)); } TEST_F(CelProtoWrapperTest, UnwrapInvalidAny) { Any any; CelValue value = CreateCelValue(any, type_provider(), arena()); ASSERT_TRUE(value.IsError()); any.set_type_url("/"); ASSERT_TRUE(CreateCelValue(any, type_provider(), arena()).IsError()); any.set_type_url("/invalid.proto.name"); ASSERT_TRUE(CreateCelValue(any, type_provider(), arena()).IsError()); } TEST_F(CelProtoWrapperTest, UnwrapAnyWithMissingTypeProvider) { TestMessage test_message; test_message.set_string_value("test"); Any any1; any1.PackFrom(test_message); CelValue value1 = CreateCelValue(any1, nullptr, arena()); ASSERT_TRUE(value1.IsError()); Int32Value test_int; test_int.set_value(12); Any any2; any2.PackFrom(test_int); CelValue value2 = CreateCelValue(any2, nullptr, arena()); ASSERT_TRUE(value2.IsInt64()); EXPECT_EQ(value2.Int64OrDie(), 12); } TEST_F(CelProtoWrapperTest, UnwrapBoolWrapper) { bool value = true; BoolValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapInt32Wrapper) { int64_t value = 12; Int32Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapUInt32Wrapper) { uint64_t value = 12; UInt32Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapInt64Wrapper) { int64_t value = 12; Int64Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapUInt64Wrapper) { uint64_t value = 12; UInt64Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapFloatWrapper) { double value = 42.5; FloatValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapDoubleWrapper) { double value = 42.5; DoubleValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapStringWrapper) { std::string text = "42"; auto value = CelValue::StringHolder(&text); StringValue wrapper; wrapper.set_value(text); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapBytesWrapper) { std::string text = "42"; auto value = CelValue::BytesHolder(&text); BytesValue wrapper; wrapper.set_value("42"); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, WrapNull) { auto cel_value = CelValue::CreateNull(); Value json; json.set_null_value(protobuf::NULL_VALUE); ExpectWrappedMessage(cel_value, json); Any any; any.PackFrom(json); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBool) { auto cel_value = CelValue::CreateBool(true); Value json; json.set_bool_value(true); ExpectWrappedMessage(cel_value, json); BoolValue wrapper; wrapper.set_value(true); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBytes) { std::string str = "hello world"; auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str)); BytesValue wrapper; wrapper.set_value(str); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBytesToValue) { std::string str = "hello world"; auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str)); Value json; json.set_string_value("aGVsbG8gd29ybGQ="); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapDuration) { auto cel_value = CelValue::CreateDuration(absl::Seconds(300)); Duration d; d.set_seconds(300); ExpectWrappedMessage(cel_value, d); Any any; any.PackFrom(d); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapDurationToValue) { auto cel_value = CelValue::CreateDuration(absl::Seconds(300)); Value json; json.set_string_value("300s"); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapDouble) { double num = 1.5; auto cel_value = CelValue::CreateDouble(num); Value json; json.set_number_value(num); ExpectWrappedMessage(cel_value, json); DoubleValue wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapDoubleToFloatValue) { double num = 1.5; auto cel_value = CelValue::CreateDouble(num); FloatValue wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); double small_num = -9.9e-100; wrapper.set_value(small_num); cel_value = CelValue::CreateDouble(small_num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapDoubleOverflow) { double lowest_double = std::numeric_limits<double>::lowest(); auto cel_value = CelValue::CreateDouble(lowest_double); FloatValue wrapper; wrapper.set_value(-std::numeric_limits<float>::infinity()); ExpectWrappedMessage(cel_value, wrapper); double max_double = std::numeric_limits<double>::max(); cel_value = CelValue::CreateDouble(max_double); wrapper.set_value(std::numeric_limits<float>::infinity()); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapInt64) { int32_t num = std::numeric_limits<int32_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Value json; json.set_number_value(static_cast<double>(num)); ExpectWrappedMessage(cel_value, json); Int64Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapInt64ToInt32Value) { int32_t num = std::numeric_limits<int32_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Int32Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapFailureInt64ToInt32Value) { int64_t num = std::numeric_limits<int64_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Int32Value* result = nullptr; EXPECT_THAT( CreateMessageFromValue(cel_value, result, type_provider(), arena()), StatusIs(absl::StatusCode::kInternal)); } TEST_F(CelProtoWrapperTest, WrapInt64ToValue) { int64_t max = std::numeric_limits<int64_t>::max(); auto cel_value = CelValue::CreateInt64(max); Value json; json.set_string_value(absl::StrCat(max)); ExpectWrappedMessage(cel_value, json); int64_t min = std::numeric_limits<int64_t>::min(); cel_value = CelValue::CreateInt64(min); json.set_string_value(absl::StrCat(min)); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapUint64) { uint32_t num = std::numeric_limits<uint32_t>::max(); auto cel_value = CelValue::CreateUint64(num); Value json; json.set_number_value(static_cast<double>(num)); ExpectWrappedMessage(cel_value, json); UInt64Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapUint64ToUint32Value) { uint32_t num = std::numeric_limits<uint32_t>::max(); auto cel_value = CelValue::CreateUint64(num); UInt32Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapUint64ToValue) { uint64_t num = std::numeric_limits<uint64_t>::max(); auto cel_value = CelValue::CreateUint64(num); Value json; json.set_string_value(absl::StrCat(num)); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureUint64ToUint32Value) { uint64_t num = std::numeric_limits<uint64_t>::max(); auto cel_value = CelValue::CreateUint64(num); UInt32Value* result = nullptr; EXPECT_THAT( CreateMessageFromValue(cel_value, result, type_provider(), arena()), StatusIs(absl::StatusCode::kInternal)); } TEST_F(CelProtoWrapperTest, WrapString) { std::string str = "test"; auto cel_value = CelValue::CreateString(CelValue::StringHolder(&str)); Value json; json.set_string_value(str); ExpectWrappedMessage(cel_value, json); StringValue wrapper; wrapper.set_value(str); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapTimestamp) { absl::Time ts = absl::FromUnixSeconds(1615852799); auto cel_value = CelValue::CreateTimestamp(ts); Timestamp t; t.set_seconds(1615852799); ExpectWrappedMessage(cel_value, t); Any any; any.PackFrom(t); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapTimestampToValue) { absl::Time ts = absl::FromUnixSeconds(1615852799); auto cel_value = CelValue::CreateTimestamp(ts); Value json; json.set_string_value("2021-03-15T23:59:59Z"); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapList) { std::vector<CelValue> list_elems = { CelValue::CreateDouble(1.5), CelValue::CreateInt64(-2L), }; ContainerBackedListImpl list(std::move(list_elems)); auto cel_value = CelValue::CreateList(&list); Value json; json.mutable_list_value()->add_values()->set_number_value(1.5); json.mutable_list_value()->add_values()->set_number_value(-2.); ExpectWrappedMessage(cel_value, json); ExpectWrappedMessage(cel_value, json.list_value()); Any any; any.PackFrom(json.list_value()); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapFailureListValueBadJSON) { TestMessage message; std::vector<CelValue> list_elems = { CelValue::CreateDouble(1.5), CreateCelValue(message, type_provider(), arena()), }; ContainerBackedListImpl list(std::move(list_elems)); auto cel_value = CelValue::CreateList(&list); Value* json = nullptr; EXPECT_THAT(CreateMessageFromValue(ce
108
cpp
google/cel-cpp
protobuf_descriptor_type_provider
eval/public/structs/protobuf_descriptor_type_provider.cc
eval/public/structs/protobuf_descriptor_type_provider_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_PROTOBUF_DESCRIPTOR_TYPE_PROVIDER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_PROTOBUF_DESCRIPTOR_TYPE_PROVIDER_H_ #include <memory> #include <string> #include <utility> #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "eval/public/structs/legacy_type_provider.h" #include "eval/public/structs/proto_message_type_adapter.h" namespace google::api::expr::runtime { class ProtobufDescriptorProvider : public LegacyTypeProvider { public: ProtobufDescriptorProvider(const google::protobuf::DescriptorPool* pool, google::protobuf::MessageFactory* factory) : descriptor_pool_(pool), message_factory_(factory) {} absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const override; absl::optional<const LegacyTypeInfoApis*> ProvideLegacyTypeInfo( absl::string_view name) const override; private: std::unique_ptr<ProtoMessageTypeAdapter> CreateTypeAdapter( absl::string_view name) const; const ProtoMessageTypeAdapter* GetTypeAdapter(absl::string_view name) const; const google::protobuf::DescriptorPool* descriptor_pool_; google::protobuf::MessageFactory* message_factory_; mutable absl::flat_hash_map<std::string, std::unique_ptr<ProtoMessageTypeAdapter>> type_cache_ ABSL_GUARDED_BY(mu_); mutable absl::Mutex mu_; }; } #endif #include "eval/public/structs/protobuf_descriptor_type_provider.h" #include <memory> #include <utility> #include "google/protobuf/descriptor.h" #include "absl/synchronization/mutex.h" #include "eval/public/structs/proto_message_type_adapter.h" namespace google::api::expr::runtime { absl::optional<LegacyTypeAdapter> ProtobufDescriptorProvider::ProvideLegacyType( absl::string_view name) const { const ProtoMessageTypeAdapter* result = GetTypeAdapter(name); if (result == nullptr) { return absl::nullopt; } return LegacyTypeAdapter(result, result); } absl::optional<const LegacyTypeInfoApis*> ProtobufDescriptorProvider::ProvideLegacyTypeInfo( absl::string_view name) const { const ProtoMessageTypeAdapter* result = GetTypeAdapter(name); if (result == nullptr) { return absl::nullopt; } return result; } std::unique_ptr<ProtoMessageTypeAdapter> ProtobufDescriptorProvider::CreateTypeAdapter(absl::string_view name) const { const google::protobuf::Descriptor* descriptor = descriptor_pool_->FindMessageTypeByName(name); if (descriptor == nullptr) { return nullptr; } return std::make_unique<ProtoMessageTypeAdapter>(descriptor, message_factory_); } const ProtoMessageTypeAdapter* ProtobufDescriptorProvider::GetTypeAdapter( absl::string_view name) const { absl::MutexLock lock(&mu_); auto it = type_cache_.find(name); if (it != type_cache_.end()) { return it->second.get(); } auto type_provider = CreateTypeAdapter(name); const ProtoMessageTypeAdapter* result = type_provider.get(); type_cache_[name] = std::move(type_provider); return result; } }
#include "eval/public/structs/protobuf_descriptor_type_provider.h" #include <optional> #include "google/protobuf/wrappers.pb.h" #include "eval/public/cel_value.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "eval/public/testing/matchers.h" #include "extensions/protobuf/memory_manager.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::extensions::ProtoMemoryManager; TEST(ProtobufDescriptorProvider, Basic) { ProtobufDescriptorProvider provider( google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory()); google::protobuf::Arena arena; auto manager = ProtoMemoryManager(&arena); auto type_adapter = provider.ProvideLegacyType("google.protobuf.Int64Value"); absl::optional<const LegacyTypeInfoApis*> type_info = provider.ProvideLegacyTypeInfo("google.protobuf.Int64Value"); ASSERT_TRUE(type_adapter.has_value()); ASSERT_TRUE(type_adapter->mutation_apis() != nullptr); ASSERT_TRUE(type_info.has_value()); ASSERT_TRUE(type_info != nullptr); google::protobuf::Int64Value int64_value; CelValue::MessageWrapper int64_cel_value(&int64_value, *type_info); EXPECT_EQ((*type_info)->GetTypename(int64_cel_value), "google.protobuf.Int64Value"); ASSERT_TRUE(type_adapter->mutation_apis()->DefinesField("value")); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder value, type_adapter->mutation_apis()->NewInstance(manager)); ASSERT_OK(type_adapter->mutation_apis()->SetField( "value", CelValue::CreateInt64(10), manager, value)); ASSERT_OK_AND_ASSIGN( CelValue adapted, type_adapter->mutation_apis()->AdaptFromWellKnownType(manager, value)); EXPECT_THAT(adapted, test::IsCelInt64(10)); } TEST(ProtobufDescriptorProvider, MemoizesAdapters) { ProtobufDescriptorProvider provider( google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory()); auto type_adapter = provider.ProvideLegacyType("google.protobuf.Int64Value"); ASSERT_TRUE(type_adapter.has_value()); ASSERT_TRUE(type_adapter->mutation_apis() != nullptr); auto type_adapter2 = provider.ProvideLegacyType("google.protobuf.Int64Value"); ASSERT_TRUE(type_adapter2.has_value()); EXPECT_EQ(type_adapter->mutation_apis(), type_adapter2->mutation_apis()); EXPECT_EQ(type_adapter->access_apis(), type_adapter2->access_apis()); } TEST(ProtobufDescriptorProvider, NotFound) { ProtobufDescriptorProvider provider( google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory()); auto type_adapter = provider.ProvideLegacyType("UnknownType"); auto type_info = provider.ProvideLegacyTypeInfo("UnknownType"); ASSERT_FALSE(type_adapter.has_value()); ASSERT_FALSE(type_info.has_value()); } } }
109
cpp
google/cel-cpp
cel_proto_descriptor_pool_builder
eval/public/structs/cel_proto_descriptor_pool_builder.cc
eval/public/structs/cel_proto_descriptor_pool_builder_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_DESCRIPTOR_POOL_BUILDER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_DESCRIPTOR_POOL_BUILDER_H_ #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/descriptor.h" #include "absl/status/status.h" namespace google::api::expr::runtime { absl::Status AddStandardMessageTypesToDescriptorPool( google::protobuf::DescriptorPool& descriptor_pool); google::protobuf::FileDescriptorSet GetStandardMessageTypesFileDescriptorSet(); } #endif #include "eval/public/structs/cel_proto_descriptor_pool_builder.h" #include <string> #include "google/protobuf/any.pb.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/empty.pb.h" #include "google/protobuf/field_mask.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/wrappers.pb.h" #include "absl/container/flat_hash_map.h" #include "internal/proto_util.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { template <class MessageType> absl::Status AddOrValidateMessageType(google::protobuf::DescriptorPool& descriptor_pool) { const google::protobuf::Descriptor* descriptor = MessageType::descriptor(); if (descriptor_pool.FindMessageTypeByName(descriptor->full_name()) != nullptr) { return internal::ValidateStandardMessageType<MessageType>(descriptor_pool); } google::protobuf::FileDescriptorProto file_descriptor_proto; descriptor->file()->CopyTo(&file_descriptor_proto); if (descriptor_pool.BuildFile(file_descriptor_proto) == nullptr) { return absl::InternalError( absl::StrFormat("Failed to add descriptor '%s' to descriptor pool", descriptor->full_name())); } return absl::OkStatus(); } template <class MessageType> void AddStandardMessageTypeToMap( absl::flat_hash_map<std::string, google::protobuf::FileDescriptorProto>& fdmap) { const google::protobuf::Descriptor* descriptor = MessageType::descriptor(); if (fdmap.contains(descriptor->file()->name())) return; descriptor->file()->CopyTo(&fdmap[descriptor->file()->name()]); } } absl::Status AddStandardMessageTypesToDescriptorPool( google::protobuf::DescriptorPool& descriptor_pool) { CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Any>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::BoolValue>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::BytesValue>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::DoubleValue>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Duration>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::FloatValue>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Int32Value>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Int64Value>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::ListValue>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::StringValue>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Struct>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Timestamp>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::UInt32Value>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::UInt64Value>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Value>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::FieldMask>(descriptor_pool)); CEL_RETURN_IF_ERROR( AddOrValidateMessageType<google::protobuf::Empty>(descriptor_pool)); return absl::OkStatus(); } google::protobuf::FileDescriptorSet GetStandardMessageTypesFileDescriptorSet() { absl::flat_hash_map<std::string, google::protobuf::FileDescriptorProto> files; AddStandardMessageTypeToMap<google::protobuf::Any>(files); AddStandardMessageTypeToMap<google::protobuf::BoolValue>(files); AddStandardMessageTypeToMap<google::protobuf::BytesValue>(files); AddStandardMessageTypeToMap<google::protobuf::DoubleValue>(files); AddStandardMessageTypeToMap<google::protobuf::Duration>(files); AddStandardMessageTypeToMap<google::protobuf::FloatValue>(files); AddStandardMessageTypeToMap<google::protobuf::Int32Value>(files); AddStandardMessageTypeToMap<google::protobuf::Int64Value>(files); AddStandardMessageTypeToMap<google::protobuf::ListValue>(files); AddStandardMessageTypeToMap<google::protobuf::StringValue>(files); AddStandardMessageTypeToMap<google::protobuf::Struct>(files); AddStandardMessageTypeToMap<google::protobuf::Timestamp>(files); AddStandardMessageTypeToMap<google::protobuf::UInt32Value>(files); AddStandardMessageTypeToMap<google::protobuf::UInt64Value>(files); AddStandardMessageTypeToMap<google::protobuf::Value>(files); AddStandardMessageTypeToMap<google::protobuf::FieldMask>(files); AddStandardMessageTypeToMap<google::protobuf::Empty>(files); google::protobuf::FileDescriptorSet fdset; for (const auto& [name, fdproto] : files) { *fdset.add_file() = fdproto; } return fdset; } }
#include "eval/public/structs/cel_proto_descriptor_pool_builder.h" #include <string> #include <vector> #include "google/protobuf/any.pb.h" #include "absl/container/flat_hash_map.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using testing::HasSubstr; using testing::UnorderedElementsAre; using cel::internal::StatusIs; TEST(DescriptorPoolUtilsTest, PopulatesEmptyDescriptorPool) { google::protobuf::DescriptorPool descriptor_pool; ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Any"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.BoolValue"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.BytesValue"), nullptr); ASSERT_EQ( descriptor_pool.FindMessageTypeByName("google.protobuf.DoubleValue"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Duration"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.FloatValue"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Int32Value"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Int64Value"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.ListValue"), nullptr); ASSERT_EQ( descriptor_pool.FindMessageTypeByName("google.protobuf.StringValue"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Struct"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Timestamp"), nullptr); ASSERT_EQ( descriptor_pool.FindMessageTypeByName("google.protobuf.UInt32Value"), nullptr); ASSERT_EQ( descriptor_pool.FindMessageTypeByName("google.protobuf.UInt64Value"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Value"), nullptr); ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.FieldMask"), nullptr); ASSERT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool)); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Any"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.BoolValue"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.BytesValue"), nullptr); EXPECT_NE( descriptor_pool.FindMessageTypeByName("google.protobuf.DoubleValue"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Duration"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.FloatValue"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Int32Value"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Int64Value"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.ListValue"), nullptr); EXPECT_NE( descriptor_pool.FindMessageTypeByName("google.protobuf.StringValue"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Struct"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Timestamp"), nullptr); EXPECT_NE( descriptor_pool.FindMessageTypeByName("google.protobuf.UInt32Value"), nullptr); EXPECT_NE( descriptor_pool.FindMessageTypeByName("google.protobuf.UInt64Value"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Value"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.FieldMask"), nullptr); EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Empty"), nullptr); } TEST(DescriptorPoolUtilsTest, AcceptsPreAddedStandardTypes) { google::protobuf::DescriptorPool descriptor_pool; for (auto proto_name : std::vector<std::string>{ "google.protobuf.Any", "google.protobuf.BoolValue", "google.protobuf.BytesValue", "google.protobuf.DoubleValue", "google.protobuf.Duration", "google.protobuf.FloatValue", "google.protobuf.Int32Value", "google.protobuf.Int64Value", "google.protobuf.ListValue", "google.protobuf.StringValue", "google.protobuf.Struct", "google.protobuf.Timestamp", "google.protobuf.UInt32Value", "google.protobuf.UInt64Value", "google.protobuf.Value", "google.protobuf.FieldMask", "google.protobuf.Empty"}) { const google::protobuf::Descriptor* descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( proto_name); ASSERT_NE(descriptor, nullptr); google::protobuf::FileDescriptorProto file_descriptor_proto; descriptor->file()->CopyTo(&file_descriptor_proto); ASSERT_NE(descriptor_pool.BuildFile(file_descriptor_proto), nullptr); } EXPECT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool)); } TEST(DescriptorPoolUtilsTest, RejectsModifiedStandardType) { google::protobuf::DescriptorPool descriptor_pool; const google::protobuf::Descriptor* descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.protobuf.Duration"); ASSERT_NE(descriptor, nullptr); google::protobuf::FileDescriptorProto file_descriptor_proto; descriptor->file()->CopyTo(&file_descriptor_proto); google::protobuf::FieldDescriptorProto seconds_desc_proto; google::protobuf::FieldDescriptorProto nanos_desc_proto; descriptor->FindFieldByName("seconds")->CopyTo(&seconds_desc_proto); descriptor->FindFieldByName("nanos")->CopyTo(&nanos_desc_proto); nanos_desc_proto.set_name("millis"); file_descriptor_proto.mutable_message_type(0)->clear_field(); *file_descriptor_proto.mutable_message_type(0)->add_field() = seconds_desc_proto; *file_descriptor_proto.mutable_message_type(0)->add_field() = nanos_desc_proto; descriptor_pool.BuildFile(file_descriptor_proto); EXPECT_THAT( AddStandardMessageTypesToDescriptorPool(descriptor_pool), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("differs"))); } TEST(DescriptorPoolUtilsTest, GetStandardMessageTypesFileDescriptorSet) { google::protobuf::FileDescriptorSet fdset = GetStandardMessageTypesFileDescriptorSet(); std::vector<std::string> file_names; for (int i = 0; i < fdset.file_size(); ++i) { file_names.push_back(fdset.file(i).name()); } EXPECT_THAT( file_names, UnorderedElementsAre( "google/protobuf/any.proto", "google/protobuf/struct.proto", "google/protobuf/wrappers.proto", "google/protobuf/timestamp.proto", "google/protobuf/duration.proto", "google/protobuf/field_mask.proto", "google/protobuf/empty.proto")); } } }
110
cpp
google/cel-cpp
field_access_impl
eval/public/structs/field_access_impl.cc
eval/public/structs/field_access_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_FIELD_ACCESS_IMPL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_FIELD_ACCESS_IMPL_H_ #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/structs/protobuf_value_factory.h" namespace google::api::expr::runtime::internal { absl::StatusOr<CelValue> CreateValueFromSingleField( const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, ProtoWrapperTypeOptions options, const ProtobufValueFactory& factory, google::protobuf::Arena* arena); absl::StatusOr<CelValue> CreateValueFromRepeatedField( const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, int index, const ProtobufValueFactory& factory, google::protobuf::Arena* arena); absl::StatusOr<CelValue> CreateValueFromMapValue( const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, const google::protobuf::MapValueConstRef* value_ref, const ProtobufValueFactory& factory, google::protobuf::Arena* arena); absl::Status SetValueToSingleField(const CelValue& value, const google::protobuf::FieldDescriptor* desc, google::protobuf::Message* msg, google::protobuf::Arena* arena); absl::Status AddValueToRepeatedField(const CelValue& value, const google::protobuf::FieldDescriptor* desc, google::protobuf::Message* msg, google::protobuf::Arena* arena); } #endif #include "eval/public/structs/field_access_impl.h" #include <cstdint> #include <string> #include <type_traits> #include <utility> #include "google/protobuf/any.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/map_field.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "eval/public/structs/cel_proto_wrap_util.h" #include "internal/casts.h" #include "internal/overflow.h" namespace google::api::expr::runtime::internal { namespace { using ::google::protobuf::Arena; using ::google::protobuf::FieldDescriptor; using ::google::protobuf::MapValueConstRef; using ::google::protobuf::Message; using ::google::protobuf::Reflection; template <class Derived> class FieldAccessor { public: bool GetBool() const { return static_cast<const Derived*>(this)->GetBool(); } int64_t GetInt32() const { return static_cast<const Derived*>(this)->GetInt32(); } uint64_t GetUInt32() const { return static_cast<const Derived*>(this)->GetUInt32(); } int64_t GetInt64() const { return static_cast<const Derived*>(this)->GetInt64(); } uint64_t GetUInt64() const { return static_cast<const Derived*>(this)->GetUInt64(); } double GetFloat() const { return static_cast<const Derived*>(this)->GetFloat(); } double GetDouble() const { return static_cast<const Derived*>(this)->GetDouble(); } const std::string* GetString(std::string* buffer) const { return static_cast<const Derived*>(this)->GetString(buffer); } const Message* GetMessage() const { return static_cast<const Derived*>(this)->GetMessage(); } int64_t GetEnumValue() const { return static_cast<const Derived*>(this)->GetEnumValue(); } absl::StatusOr<CelValue> CreateValueFromFieldAccessor(Arena* arena) { switch (field_desc_->cpp_type()) { case FieldDescriptor::CPPTYPE_BOOL: { bool value = GetBool(); return CelValue::CreateBool(value); } case FieldDescriptor::CPPTYPE_INT32: { int64_t value = GetInt32(); return CelValue::CreateInt64(value); } case FieldDescriptor::CPPTYPE_INT64: { int64_t value = GetInt64(); return CelValue::CreateInt64(value); } case FieldDescriptor::CPPTYPE_UINT32: { uint64_t value = GetUInt32(); return CelValue::CreateUint64(value); } case FieldDescriptor::CPPTYPE_UINT64: { uint64_t value = GetUInt64(); return CelValue::CreateUint64(value); } case FieldDescriptor::CPPTYPE_FLOAT: { double value = GetFloat(); return CelValue::CreateDouble(value); } case FieldDescriptor::CPPTYPE_DOUBLE: { double value = GetDouble(); return CelValue::CreateDouble(value); } case FieldDescriptor::CPPTYPE_STRING: { std::string buffer; const std::string* value = GetString(&buffer); if (value == &buffer) { value = google::protobuf::Arena::Create<std::string>(arena, std::move(buffer)); } switch (field_desc_->type()) { case FieldDescriptor::TYPE_STRING: return CelValue::CreateString(value); case FieldDescriptor::TYPE_BYTES: return CelValue::CreateBytes(value); default: return absl::Status(absl::StatusCode::kInvalidArgument, "Error handling C++ string conversion"); } break; } case FieldDescriptor::CPPTYPE_MESSAGE: { const google::protobuf::Message* msg_value = GetMessage(); return UnwrapMessageToValue(msg_value, protobuf_value_factory_, arena); } case FieldDescriptor::CPPTYPE_ENUM: { int enum_value = GetEnumValue(); return CelValue::CreateInt64(enum_value); } default: return absl::Status(absl::StatusCode::kInvalidArgument, "Unhandled C++ type conversion"); } return absl::Status(absl::StatusCode::kInvalidArgument, "Unhandled C++ type conversion"); } protected: FieldAccessor(const Message* msg, const FieldDescriptor* field_desc, const ProtobufValueFactory& protobuf_value_factory) : msg_(msg), field_desc_(field_desc), protobuf_value_factory_(protobuf_value_factory) {} const Message* msg_; const FieldDescriptor* field_desc_; const ProtobufValueFactory& protobuf_value_factory_; }; const absl::flat_hash_set<std::string>& WellKnownWrapperTypes() { static auto* wrapper_types = new absl::flat_hash_set<std::string>{ "google.protobuf.BoolValue", "google.protobuf.DoubleValue", "google.protobuf.FloatValue", "google.protobuf.Int64Value", "google.protobuf.Int32Value", "google.protobuf.UInt64Value", "google.protobuf.UInt32Value", "google.protobuf.StringValue", "google.protobuf.BytesValue", }; return *wrapper_types; } bool IsWrapperType(const FieldDescriptor* field_descriptor) { return WellKnownWrapperTypes().find( field_descriptor->message_type()->full_name()) != WellKnownWrapperTypes().end(); } class ScalarFieldAccessor : public FieldAccessor<ScalarFieldAccessor> { public: ScalarFieldAccessor(const Message* msg, const FieldDescriptor* field_desc, bool unset_wrapper_as_null, const ProtobufValueFactory& factory) : FieldAccessor(msg, field_desc, factory), unset_wrapper_as_null_(unset_wrapper_as_null) {} bool GetBool() const { return GetReflection()->GetBool(*msg_, field_desc_); } int64_t GetInt32() const { return GetReflection()->GetInt32(*msg_, field_desc_); } uint64_t GetUInt32() const { return GetReflection()->GetUInt32(*msg_, field_desc_); } int64_t GetInt64() const { return GetReflection()->GetInt64(*msg_, field_desc_); } uint64_t GetUInt64() const { return GetReflection()->GetUInt64(*msg_, field_desc_); } double GetFloat() const { return GetReflection()->GetFloat(*msg_, field_desc_); } double GetDouble() const { return GetReflection()->GetDouble(*msg_, field_desc_); } const std::string* GetString(std::string* buffer) const { return &GetReflection()->GetStringReference(*msg_, field_desc_, buffer); } const Message* GetMessage() const { if (unset_wrapper_as_null_ && !GetReflection()->HasField(*msg_, field_desc_) && IsWrapperType(field_desc_)) { return nullptr; } return &GetReflection()->GetMessage(*msg_, field_desc_); } int64_t GetEnumValue() const { return GetReflection()->GetEnumValue(*msg_, field_desc_); } const Reflection* GetReflection() const { return msg_->GetReflection(); } private: bool unset_wrapper_as_null_; }; class RepeatedFieldAccessor : public FieldAccessor<RepeatedFieldAccessor> { public: RepeatedFieldAccessor(const Message* msg, const FieldDescriptor* field_desc, int index, const ProtobufValueFactory& factory) : FieldAccessor(msg, field_desc, factory), index_(index) {} bool GetBool() const { return GetReflection()->GetRepeatedBool(*msg_, field_desc_, index_); } int64_t GetInt32() const { return GetReflection()->GetRepeatedInt32(*msg_, field_desc_, index_); } uint64_t GetUInt32() const { return GetReflection()->GetRepeatedUInt32(*msg_, field_desc_, index_); } int64_t GetInt64() const { return GetReflection()->GetRepeatedInt64(*msg_, field_desc_, index_); } uint64_t GetUInt64() const { return GetReflection()->GetRepeatedUInt64(*msg_, field_desc_, index_); } double GetFloat() const { return GetReflection()->GetRepeatedFloat(*msg_, field_desc_, index_); } double GetDouble() const { return GetReflection()->GetRepeatedDouble(*msg_, field_desc_, index_); } const std::string* GetString(std::string* buffer) const { return &GetReflection()->GetRepeatedStringReference(*msg_, field_desc_, index_, buffer); } const Message* GetMessage() const { return &GetReflection()->GetRepeatedMessage(*msg_, field_desc_, index_); } int64_t GetEnumValue() const { return GetReflection()->GetRepeatedEnumValue(*msg_, field_desc_, index_); } const Reflection* GetReflection() const { return msg_->GetReflection(); } private: int index_; }; class MapValueAccessor : public FieldAccessor<MapValueAccessor> { public: MapValueAccessor(const Message* msg, const FieldDescriptor* field_desc, const MapValueConstRef* value_ref, const ProtobufValueFactory& factory) : FieldAccessor(msg, field_desc, factory), value_ref_(value_ref) {} bool GetBool() const { return value_ref_->GetBoolValue(); } int64_t GetInt32() const { return value_ref_->GetInt32Value(); } uint64_t GetUInt32() const { return value_ref_->GetUInt32Value(); } int64_t GetInt64() const { return value_ref_->GetInt64Value(); } uint64_t GetUInt64() const { return value_ref_->GetUInt64Value(); } double GetFloat() const { return value_ref_->GetFloatValue(); } double GetDouble() const { return value_ref_->GetDoubleValue(); } const std::string* GetString(std::string* ) const { return &value_ref_->GetStringValue(); } const Message* GetMessage() const { return &value_ref_->GetMessageValue(); } int64_t GetEnumValue() const { return value_ref_->GetEnumValue(); } const Reflection* GetReflection() const { return msg_->GetReflection(); } private: const MapValueConstRef* value_ref_; }; template <class Derived> class FieldSetter { public: bool AssignBool(const CelValue& cel_value) const { bool value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetBool(value); return true; } bool AssignInt32(const CelValue& cel_value) const { int64_t value; if (!cel_value.GetValue(&value)) { return false; } absl::StatusOr<int32_t> checked_cast = cel::internal::CheckedInt64ToInt32(value); if (!checked_cast.ok()) { return false; } static_cast<const Derived*>(this)->SetInt32(*checked_cast); return true; } bool AssignUInt32(const CelValue& cel_value) const { uint64_t value; if (!cel_value.GetValue(&value)) { return false; } if (!cel::internal::CheckedUint64ToUint32(value).ok()) { return false; } static_cast<const Derived*>(this)->SetUInt32(value); return true; } bool AssignInt64(const CelValue& cel_value) const { int64_t value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetInt64(value); return true; } bool AssignUInt64(const CelValue& cel_value) const { uint64_t value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetUInt64(value); return true; } bool AssignFloat(const CelValue& cel_value) const { double value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetFloat(value); return true; } bool AssignDouble(const CelValue& cel_value) const { double value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetDouble(value); return true; } bool AssignString(const CelValue& cel_value) const { CelValue::StringHolder value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetString(value); return true; } bool AssignBytes(const CelValue& cel_value) const { CelValue::BytesHolder value; if (!cel_value.GetValue(&value)) { return false; } static_cast<const Derived*>(this)->SetBytes(value); return true; } bool AssignEnum(const CelValue& cel_value) const { int64_t value; if (!cel_value.GetValue(&value)) { return false; } if (!cel::internal::CheckedInt64ToInt32(value).ok()) { return false; } static_cast<const Derived*>(this)->SetEnum(value); return true; } bool AssignMessage(const google::protobuf::Message* message) const { return static_cast<const Derived*>(this)->SetMessage(message); } bool SetFieldFromCelValue(const CelValue& value) { switch (field_desc_->cpp_type()) { case FieldDescriptor::CPPTYPE_BOOL: { return AssignBool(value); } case FieldDescriptor::CPPTYPE_INT32: { return AssignInt32(value); } case FieldDescriptor::CPPTYPE_INT64: { return AssignInt64(value); } case FieldDescriptor::CPPTYPE_UINT32: { return AssignUInt32(value); } case FieldDescriptor::CPPTYPE_UINT64: { return AssignUInt64(value); } case FieldDescriptor::CPPTYPE_FLOAT: { return AssignFloat(value); } case FieldDescriptor::CPPTYPE_DOUBLE: { return AssignDouble(value); } case FieldDescriptor::CPPTYPE_STRING: { switch (field_desc_->type()) { case FieldDescriptor::TYPE_STRING: return AssignString(value); case FieldDescriptor::TYPE_BYTES: return AssignBytes(value); default: return false; } break; } case FieldDescriptor::CPPTYPE_MESSAGE: { const google::protobuf::Message* wrapped_value = MaybeWrapValueToMessage(field_desc_->message_type(), value, arena_); if (wrapped_value == nullptr) { if (value.IsNull()) { return true; } if (CelValue::MessageWrapper wrapper; value.GetValue(&wrapper) && wrapper.HasFullProto()) { wrapped_value = static_cast<const google::protobuf::Message*>(wrapper.message_ptr()); } else { return false; } } return AssignMessage(wrapped_value); } case FieldDescriptor::CPPTYPE_ENUM: { return AssignEnum(value); } default: return false; } return true; } protected: FieldSetter(Message* msg, const FieldDescriptor* field_desc, Arena* arena) : msg_(msg), field_desc_(field_desc), arena_(arena) {} Message* msg_; const FieldDescriptor* field_desc_; Arena* arena_; }; bool MergeFromWithSerializeFallback(const google::protobuf::Message& value, google::protobuf::Message& field) { if (field.GetDescriptor() == value.GetDescriptor()) { field.MergeFrom(value); return true; } return field.MergeFromString(value.SerializeAsString()); } class ScalarFieldSetter : public FieldSetter<ScalarFieldSetter> { public: ScalarFieldSetter(Message* msg, const FieldDescriptor* field_desc, Arena* arena) : FieldSetter(msg, field_desc, arena) {} bool SetBool(bool value) const { GetReflection()->SetBool(msg_, field_desc_, value); return true; } bool SetInt32(int32_t value) const { GetReflection()->SetInt32(msg_, field_desc_, value); return true; } bool SetUInt32(uint32_t value) const { GetReflection()->SetUInt32(msg_, field_desc_, value); return true; } bool SetInt64(int64_t value) const { GetReflection()->SetInt64(msg_, field_desc_, value); return true; } bool SetUInt64(uint64_t value) const { GetReflection()->SetUInt64(msg_, field_desc_, value); return true; } bool SetFloat(float value) const { GetReflection()->SetFloat(msg_, field_desc_, value); return true; } bool SetDouble(double value) const { GetReflection()->SetDouble(msg_, field_desc_, value); return true; } bool SetString(CelValue::StringHolder value) const { GetReflection()->SetString(msg_, field_desc_, std::string(value.value())); return true; } bool SetBytes(CelValue::BytesHolder value) const { GetReflection()->SetString(msg_, field_desc_, std::string(value.value())); return true; } bool SetMessage(const Message* value) const { if (!value) { ABSL_LOG(ERROR) << "Message is NULL"; return true; } if (value->GetDescriptor()->full_name() == field_desc_->message_type()->full_name()) { auto* assignable_field_msg = GetReflection()->MutableMessage(msg_, field_desc_); return MergeFromWithSerializeFallback(*value, *assignable_field_msg); } return false; } bool SetEnum(const int64_t value) const { GetReflection()->SetEnumValue(msg_, field_desc_, value); return true; } const Reflection* GetReflection() const { return msg_->GetReflection(); } }; class RepeatedFieldSetter : public FieldSetter<RepeatedFieldSetter> { public: RepeatedFieldSetter(Message* msg, const FieldDescriptor* field_desc, Arena* arena) : FieldSetter(msg, field_desc, arena) {} bool SetBool(bool value) const { GetReflection()->AddBool(msg_, field_desc_, value); return true; } bool SetInt32(int32_t value) const { GetReflection()->AddInt32(msg_, field_desc_, value); return true; } bool SetUInt32(uint32_t value) const { GetReflection()->AddUInt32(msg_, field_desc_, value); return true; } bool SetInt64(int64_t value) const { GetReflection()->AddInt64(msg_, field_desc_, value); return true; } bool SetUInt64(uint64_t value) const { GetReflection()->AddUInt64(msg_, field_desc_, value); return true; } bool SetFloat(float value) const { GetReflection()->AddFloat(msg_, field_desc_, value); return true; } bool SetDouble(double value) const { GetReflection()->AddDouble(msg_, field_desc_, value); return true; } bool SetString(CelValue::StringHolder value) const { GetReflection()->AddString(msg_, field_desc_, std::string(value.value())); return true; } bool SetBytes(CelValue::BytesHolder value) const { GetReflection()->AddString(msg_, field_desc_, std::string(value.value())); return true; } bool SetMessage(const Message* value) const { if (!value) return true; if (value->GetDescriptor()->full_name() != field_desc_->message_type()->full_name()) { return false; } auto* assignable_message = GetReflection()->AddMessage(msg_, field_desc_); return MergeFromWithSerializeFallback(*value, *assignable_message); } bool SetEnum(const int64_t value) const { GetReflection()->AddEnumValue(msg_, field_desc_, value); return true; } private: const Reflection* GetReflection() const { return msg_->GetReflection(); } }; } absl::StatusOr<CelValue> CreateValueFromSingleField( const google::protobuf::Message* msg, const FieldDescriptor* desc, ProtoWrapperTypeOptions options, const ProtobufValueFactory& factory, google::protobuf::Arena* arena) { ScalarFieldAccessor accessor( msg, desc, (options == ProtoWrapperTypeOptions::kUnsetNull), factory); return accessor.CreateValueFromFieldAccessor(arena); } absl::StatusOr<CelValue> CreateValueFromRepeatedField( const google::protobuf::Message* msg, const FieldDescriptor* desc, int index, const ProtobufValueFactory& factory, google::protobuf::Arena* arena) { RepeatedFieldAccessor accessor(msg, desc, index, factory); return accessor.CreateValueFromFieldAccessor(arena); } absl::StatusOr<CelValue> CreateValueFromMapValue( const google::protobuf::Message* msg, const FieldDescriptor* desc, const MapValueConstRef* value_ref, const ProtobufValueFactory& factory, google::protobuf::Arena* arena) { MapValueAccessor accessor(msg, desc, value_ref, factory); return accessor.CreateValueFromFieldAccessor(arena); } absl::Status SetValueToSingleField(const CelValue& value, const FieldDescriptor* desc, Message* msg, Arena* arena) { ScalarFieldSetter setter(msg, desc, arena); return (setter.SetFieldFromCelValue(value)) ? absl::OkStatus() : absl::InvalidArgumentError(absl::Substitute( "Could not assign supplied argument to message \"$0\" field " "\"$1\" of type $2: value type \"$3\"", msg->GetDescriptor()->name(), desc->name(), desc->type_name(), CelValue::TypeName(value.type()))); } absl::Status AddValueToRepeatedField(const CelValue& value, const FieldDescriptor* desc, Message* msg, Arena* arena) { RepeatedFieldSetter setter(msg, desc, arena); return (setter.SetFieldFromCelValue(value)) ? absl::OkStatus() : absl::InvalidArgumentError(absl::Substitute( "Could not add supplied argument to message \"$0\" field " "\"$1\" of type $2: value type \"$3\"", msg->GetDescriptor()->name(), desc->name(), desc->type_name(), CelValue::TypeName(value.type()))); } }
#include "eval/public/structs/field_access_impl.h" #include <array> #include <limits> #include <string> #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "eval/public/cel_value.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" #include "internal/time.h" #include "testutil/util.h" #include "proto/test/v1/proto3/test_all_types.pb.h" namespace google::api::expr::runtime::internal { namespace { using ::cel::internal::MaxDuration; using ::cel::internal::MaxTimestamp; using ::google::api::expr::test::v1::proto3::TestAllTypes; using ::google::protobuf::Arena; using ::google::protobuf::FieldDescriptor; using testing::HasSubstr; using cel::internal::StatusIs; using testutil::EqualsProto; TEST(FieldAccessTest, SetDuration) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_duration"); auto status = SetValueToSingleField(CelValue::CreateDuration(MaxDuration()), field, &msg, &arena); EXPECT_TRUE(status.ok()); } TEST(FieldAccessTest, SetDurationBadDuration) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_duration"); auto status = SetValueToSingleField( CelValue::CreateDuration(MaxDuration() + absl::Seconds(1)), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetDurationBadInputType) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_duration"); auto status = SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetTimestamp) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_timestamp"); auto status = SetValueToSingleField(CelValue::CreateTimestamp(MaxTimestamp()), field, &msg, &arena); EXPECT_TRUE(status.ok()); } TEST(FieldAccessTest, SetTimestampBadTime) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_timestamp"); auto status = SetValueToSingleField( CelValue::CreateTimestamp(MaxTimestamp() + absl::Seconds(1)), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetTimestampBadInputType) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_timestamp"); auto status = SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetInt32Overflow) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_int32"); EXPECT_THAT( SetValueToSingleField( CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L), field, &msg, &arena), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Could not assign"))); } TEST(FieldAccessTest, SetUint32Overflow) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_uint32"); EXPECT_THAT( SetValueToSingleField( CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1L), field, &msg, &arena), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Could not assign"))); } TEST(FieldAccessTest, SetMessage) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("standalone_message"); TestAllTypes::NestedMessage* nested_msg = google::protobuf::Arena::Create<TestAllTypes::NestedMessage>(&arena); nested_msg->set_bb(1); auto status = SetValueToSingleField( CelProtoWrapper::CreateMessage(nested_msg, &arena), field, &msg, &arena); EXPECT_TRUE(status.ok()); } TEST(FieldAccessTest, SetMessageWithNull) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("standalone_message"); auto status = SetValueToSingleField(CelValue::CreateNull(), field, &msg, &arena); EXPECT_TRUE(status.ok()); } struct AccessFieldTestParam { absl::string_view field_name; absl::string_view message_textproto; CelValue cel_value; }; std::string GetTestName( const testing::TestParamInfo<AccessFieldTestParam>& info) { return std::string(info.param.field_name); } class SingleFieldTest : public testing::TestWithParam<AccessFieldTestParam> { public: absl::string_view field_name() const { return GetParam().field_name; } absl::string_view message_textproto() const { return GetParam().message_textproto; } CelValue cel_value() const { return GetParam().cel_value; } }; TEST_P(SingleFieldTest, Getter) { TestAllTypes test_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(message_textproto(), &test_message)); google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN( CelValue accessed_value, CreateValueFromSingleField( &test_message, test_message.GetDescriptor()->FindFieldByName(field_name()), ProtoWrapperTypeOptions::kUnsetProtoDefault, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(accessed_value, test::EqualsCelValue(cel_value())); } TEST_P(SingleFieldTest, Setter) { TestAllTypes test_message; CelValue to_set = cel_value(); google::protobuf::Arena arena; ASSERT_OK(SetValueToSingleField( to_set, test_message.GetDescriptor()->FindFieldByName(field_name()), &test_message, &arena)); EXPECT_THAT(test_message, EqualsProto(message_textproto())); } INSTANTIATE_TEST_SUITE_P( AllTypes, SingleFieldTest, testing::ValuesIn<AccessFieldTestParam>({ {"single_int32", "single_int32: 1", CelValue::CreateInt64(1)}, {"single_int64", "single_int64: 1", CelValue::CreateInt64(1)}, {"single_uint32", "single_uint32: 1", CelValue::CreateUint64(1)}, {"single_uint64", "single_uint64: 1", CelValue::CreateUint64(1)}, {"single_sint32", "single_sint32: 1", CelValue::CreateInt64(1)}, {"single_sint64", "single_sint64: 1", CelValue::CreateInt64(1)}, {"single_fixed32", "single_fixed32: 1", CelValue::CreateUint64(1)}, {"single_fixed64", "single_fixed64: 1", CelValue::CreateUint64(1)}, {"single_sfixed32", "single_sfixed32: 1", CelValue::CreateInt64(1)}, {"single_sfixed64", "single_sfixed64: 1", CelValue::CreateInt64(1)}, {"single_float", "single_float: 1.0", CelValue::CreateDouble(1.0)}, {"single_double", "single_double: 1.0", CelValue::CreateDouble(1.0)}, {"single_bool", "single_bool: true", CelValue::CreateBool(true)}, {"single_string", "single_string: 'abcd'", CelValue::CreateStringView("abcd")}, {"single_bytes", "single_bytes: 'asdf'", CelValue::CreateBytesView("asdf")}, {"standalone_enum", "standalone_enum: BAZ", CelValue::CreateInt64(2)}, {"single_int64_wrapper", "single_int64_wrapper { value: 20 }", CelValue::CreateInt64(20)}, {"single_value", "single_value { null_value: NULL_VALUE }", CelValue::CreateNull()}, }), &GetTestName); TEST(CreateValueFromSingleFieldTest, GetMessage) { TestAllTypes test_message; google::protobuf::Arena arena; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( "standalone_message { bb: 10 }", &test_message)); ASSERT_OK_AND_ASSIGN( CelValue accessed_value, CreateValueFromSingleField( &test_message, test_message.GetDescriptor()->FindFieldByName("standalone_message"), ProtoWrapperTypeOptions::kUnsetProtoDefault, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(accessed_value, test::IsCelMessage(EqualsProto("bb: 10"))); } TEST(SetValueToSingleFieldTest, WrongType) { TestAllTypes test_message; google::protobuf::Arena arena; EXPECT_THAT(SetValueToSingleField( CelValue::CreateDouble(1.0), test_message.GetDescriptor()->FindFieldByName("single_int32"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(SetValueToSingleFieldTest, IntOutOfRange) { CelValue out_of_range = CelValue::CreateInt64(1LL << 31); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); google::protobuf::Arena arena; EXPECT_THAT(SetValueToSingleField(out_of_range, descriptor->FindFieldByName("single_int32"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(SetValueToSingleField( out_of_range, descriptor->FindFieldByName("standalone_enum"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(SetValueToSingleFieldTest, UintOutOfRange) { CelValue out_of_range = CelValue::CreateUint64(1LL << 32); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); google::protobuf::Arena arena; EXPECT_THAT(SetValueToSingleField( out_of_range, descriptor->FindFieldByName("single_uint32"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(SetValueToSingleFieldTest, SetMessage) { TestAllTypes::NestedMessage nested_message; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( bb: 42 )", &nested_message)); google::protobuf::Arena arena; CelValue nested_value = CelProtoWrapper::CreateMessage(&nested_message, &arena); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); ASSERT_OK(SetValueToSingleField( nested_value, descriptor->FindFieldByName("standalone_message"), &test_message, &arena)); EXPECT_THAT(test_message, EqualsProto("standalone_message { bb: 42 }")); } TEST(SetValueToSingleFieldTest, SetAnyMessage) { TestAllTypes::NestedMessage nested_message; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( bb: 42 )", &nested_message)); google::protobuf::Arena arena; CelValue nested_value = CelProtoWrapper::CreateMessage(&nested_message, &arena); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); ASSERT_OK(SetValueToSingleField(nested_value, descriptor->FindFieldByName("single_any"), &test_message, &arena)); TestAllTypes::NestedMessage unpacked; test_message.single_any().UnpackTo(&unpacked); EXPECT_THAT(unpacked, EqualsProto("bb: 42")); } TEST(SetValueToSingleFieldTest, SetMessageToNullNoop) { google::protobuf::Arena arena; TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); ASSERT_OK(SetValueToSingleField( CelValue::CreateNull(), descriptor->FindFieldByName("standalone_message"), &test_message, &arena)); EXPECT_THAT(test_message, EqualsProto(test_message.default_instance())); } class RepeatedFieldTest : public testing::TestWithParam<AccessFieldTestParam> { public: absl::string_view field_name() const { return GetParam().field_name; } absl::string_view message_textproto() const { return GetParam().message_textproto; } CelValue cel_value() const { return GetParam().cel_value; } }; TEST_P(RepeatedFieldTest, GetFirstElem) { TestAllTypes test_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(message_textproto(), &test_message)); google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN( CelValue accessed_value, CreateValueFromRepeatedField( &test_message, test_message.GetDescriptor()->FindFieldByName(field_name()), 0, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(accessed_value, test::EqualsCelValue(cel_value())); } TEST_P(RepeatedFieldTest, AppendElem) { TestAllTypes test_message; CelValue to_add = cel_value(); google::protobuf::Arena arena; ASSERT_OK(AddValueToRepeatedField( to_add, test_message.GetDescriptor()->FindFieldByName(field_name()), &test_message, &arena)); EXPECT_THAT(test_message, EqualsProto(message_textproto())); } INSTANTIATE_TEST_SUITE_P( AllTypes, RepeatedFieldTest, testing::ValuesIn<AccessFieldTestParam>( {{"repeated_int32", "repeated_int32: 1", CelValue::CreateInt64(1)}, {"repeated_int64", "repeated_int64: 1", CelValue::CreateInt64(1)}, {"repeated_uint32", "repeated_uint32: 1", CelValue::CreateUint64(1)}, {"repeated_uint64", "repeated_uint64: 1", CelValue::CreateUint64(1)}, {"repeated_sint32", "repeated_sint32: 1", CelValue::CreateInt64(1)}, {"repeated_sint64", "repeated_sint64: 1", CelValue::CreateInt64(1)}, {"repeated_fixed32", "repeated_fixed32: 1", CelValue::CreateUint64(1)}, {"repeated_fixed64", "repeated_fixed64: 1", CelValue::CreateUint64(1)}, {"repeated_sfixed32", "repeated_sfixed32: 1", CelValue::CreateInt64(1)}, {"repeated_sfixed64", "repeated_sfixed64: 1", CelValue::CreateInt64(1)}, {"repeated_float", "repeated_float: 1.0", CelValue::CreateDouble(1.0)}, {"repeated_double", "repeated_double: 1.0", CelValue::CreateDouble(1.0)}, {"repeated_bool", "repeated_bool: true", CelValue::CreateBool(true)}, {"repeated_string", "repeated_string: 'abcd'", CelValue::CreateStringView("abcd")}, {"repeated_bytes", "repeated_bytes: 'asdf'", CelValue::CreateBytesView("asdf")}, {"repeated_nested_enum", "repeated_nested_enum: BAZ", CelValue::CreateInt64(2)}}), &GetTestName); TEST(RepeatedFieldTest, GetMessage) { TestAllTypes test_message; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( "repeated_nested_message { bb: 30 }", &test_message)); google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue accessed_value, CreateValueFromRepeatedField( &test_message, test_message.GetDescriptor()->FindFieldByName( "repeated_nested_message"), 0, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(accessed_value, test::IsCelMessage(EqualsProto("bb: 30"))); } TEST(AddValueToRepeatedFieldTest, WrongType) { TestAllTypes test_message; google::protobuf::Arena arena; EXPECT_THAT( AddValueToRepeatedField( CelValue::CreateDouble(1.0), test_message.GetDescriptor()->FindFieldByName("repeated_int32"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(AddValueToRepeatedFieldTest, IntOutOfRange) { CelValue out_of_range = CelValue::CreateInt64(1LL << 31); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); google::protobuf::Arena arena; EXPECT_THAT(AddValueToRepeatedField( out_of_range, descriptor->FindFieldByName("repeated_int32"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( AddValueToRepeatedField( out_of_range, descriptor->FindFieldByName("repeated_nested_enum"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(AddValueToRepeatedFieldTest, UintOutOfRange) { CelValue out_of_range = CelValue::CreateUint64(1LL << 32); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); google::protobuf::Arena arena; EXPECT_THAT(AddValueToRepeatedField( out_of_range, descriptor->FindFieldByName("repeated_uint32"), &test_message, &arena), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(AddValueToRepeatedFieldTest, AddMessage) { TestAllTypes::NestedMessage nested_message; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( bb: 42 )", &nested_message)); google::protobuf::Arena arena; CelValue nested_value = CelProtoWrapper::CreateMessage(&nested_message, &arena); TestAllTypes test_message; const google::protobuf::Descriptor* descriptor = test_message.GetDescriptor(); ASSERT_OK(AddValueToRepeatedField( nested_value, descriptor->FindFieldByName("repeated_nested_message"), &test_message, &arena)); EXPECT_THAT(test_message, EqualsProto("repeated_nested_message { bb: 42 }")); } constexpr std::array<const char*, 9> kWrapperFieldNames = { "single_bool_wrapper", "single_int64_wrapper", "single_int32_wrapper", "single_uint64_wrapper", "single_uint32_wrapper", "single_double_wrapper", "single_float_wrapper", "single_string_wrapper", "single_bytes_wrapper"}; TEST(CreateValueFromFieldTest, UnsetWrapperTypesNullIfEnabled) { CelValue result; TestAllTypes test_message; google::protobuf::Arena arena; for (const auto& field : kWrapperFieldNames) { ASSERT_OK_AND_ASSIGN( result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName(field), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); ASSERT_TRUE(result.IsNull()) << field << ": " << result.DebugString(); } } TEST(CreateValueFromFieldTest, UnsetWrapperTypesDefaultValueIfDisabled) { CelValue result; TestAllTypes test_message; google::protobuf::Arena arena; for (const auto& field : kWrapperFieldNames) { ASSERT_OK_AND_ASSIGN( result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName(field), ProtoWrapperTypeOptions::kUnsetProtoDefault, &CelProtoWrapper::InternalWrapMessage, &arena)); ASSERT_FALSE(result.IsNull()) << field << ": " << result.DebugString(); } } TEST(CreateValueFromFieldTest, SetWrapperTypesDefaultValue) { CelValue result; TestAllTypes test_message; google::protobuf::Arena arena; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( single_bool_wrapper {} single_int64_wrapper {} single_int32_wrapper {} single_uint64_wrapper {} single_uint32_wrapper {} single_double_wrapper {} single_float_wrapper {} single_string_wrapper {} single_bytes_wrapper {} )pb", &test_message)); ASSERT_OK_AND_ASSIGN( result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_bool_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelBool(false)); ASSERT_OK_AND_ASSIGN(result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_int64_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelInt64(0)); ASSERT_OK_AND_ASSIGN(result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_int32_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelInt64(0)); ASSERT_OK_AND_ASSIGN( result, CreateValueFromSingleField(&test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_uint64_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelUint64(0)); ASSERT_OK_AND_ASSIGN( result, CreateValueFromSingleField(&test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_uint32_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelUint64(0)); ASSERT_OK_AND_ASSIGN(result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_double_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelDouble(0.0f)); ASSERT_OK_AND_ASSIGN(result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_float_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelDouble(0.0f)); ASSERT_OK_AND_ASSIGN(result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_string_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelString("")); ASSERT_OK_AND_ASSIGN(result, CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName( "single_bytes_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &CelProtoWrapper::InternalWrapMessage, &arena)); EXPECT_THAT(result, test::IsCelBytes("")); } } }
111
cpp
google/cel-cpp
proto_message_type_adapter
eval/public/structs/proto_message_type_adapter.cc
eval/public/structs/proto_message_type_adapter_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_PROTO_MESSAGE_TYPE_ADAPTER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_PROTO_MESSAGE_TYPE_ADAPTER_H_ #include <string> #include <vector> #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "common/memory.h" #include "common/value.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" namespace google::api::expr::runtime { class ProtoMessageTypeAdapter : public LegacyTypeInfoApis, public LegacyTypeAccessApis, public LegacyTypeMutationApis { public: ProtoMessageTypeAdapter(const google::protobuf::Descriptor* descriptor, google::protobuf::MessageFactory* message_factory) : message_factory_(message_factory), descriptor_(descriptor) {} ~ProtoMessageTypeAdapter() override = default; std::string DebugString(const MessageWrapper& wrapped_message) const override; const std::string& GetTypename( const MessageWrapper& wrapped_message) const override; const LegacyTypeAccessApis* GetAccessApis( const MessageWrapper& wrapped_message) const override; const LegacyTypeMutationApis* GetMutationApis( const MessageWrapper& wrapped_message) const override; absl::optional<LegacyTypeInfoApis::FieldDescription> FindFieldByName( absl::string_view field_name) const override; absl::StatusOr<CelValue::MessageWrapper::Builder> NewInstance( cel::MemoryManagerRef memory_manager) const override; bool DefinesField(absl::string_view field_name) const override; absl::Status SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const override; absl::Status SetFieldByNumber( int64_t field_number, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const override; absl::StatusOr<CelValue> AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const override; absl::StatusOr<CelValue> GetField( absl::string_view field_name, const CelValue::MessageWrapper& instance, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) const override; absl::StatusOr<bool> HasField( absl::string_view field_name, const CelValue::MessageWrapper& value) const override; absl::StatusOr<LegacyTypeAccessApis::LegacyQualifyResult> Qualify( absl::Span<const cel::SelectQualifier> qualifiers, const CelValue::MessageWrapper& instance, bool presence_test, cel::MemoryManagerRef memory_manager) const override; bool IsEqualTo(const CelValue::MessageWrapper& instance, const CelValue::MessageWrapper& other_instance) const override; std::vector<absl::string_view> ListFields( const CelValue::MessageWrapper& instance) const override; private: absl::Status ValidateSetFieldOp(bool assertion, absl::string_view field, absl::string_view detail) const; absl::Status SetField(const google::protobuf::FieldDescriptor* field, const CelValue& value, google::protobuf::Arena* arena, google::protobuf::Message* message) const; google::protobuf::MessageFactory* message_factory_; const google::protobuf::Descriptor* descriptor_; }; const LegacyTypeInfoApis& GetGenericProtoTypeInfoInstance(); } #endif #include "eval/public/structs/proto_message_type_adapter.h" #include <cstdint> #include <limits> #include <string> #include <utility> #include <vector> #include "google/protobuf/util/message_differencer.h" #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/attribute.h" #include "common/memory.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/containers/internal_field_backed_list_impl.h" #include "eval/public/containers/internal_field_backed_map_impl.h" #include "eval/public/message_wrapper.h" #include "eval/public/structs/cel_proto_wrap_util.h" #include "eval/public/structs/field_access_impl.h" #include "eval/public/structs/legacy_type_adapter.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "extensions/protobuf/internal/qualify.h" #include "extensions/protobuf/memory_manager.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/map_field.h" #include "google/protobuf/message.h" namespace google::api::expr::runtime { namespace { using ::cel::extensions::ProtoMemoryManagerArena; using ::cel::extensions::ProtoMemoryManagerRef; using ::google::protobuf::FieldDescriptor; using ::google::protobuf::Message; using ::google::protobuf::Reflection; using LegacyQualifyResult = LegacyTypeAccessApis::LegacyQualifyResult; const std::string& UnsupportedTypeName() { static absl::NoDestructor<std::string> kUnsupportedTypeName( "<unknown message>"); return *kUnsupportedTypeName; } CelValue MessageCelValueFactory(const google::protobuf::Message* message); inline absl::StatusOr<const google::protobuf::Message*> UnwrapMessage( const MessageWrapper& value, absl::string_view op) { if (!value.HasFullProto() || value.message_ptr() == nullptr) { return absl::InternalError( absl::StrCat(op, " called on non-message type.")); } return static_cast<const google::protobuf::Message*>(value.message_ptr()); } inline absl::StatusOr<google::protobuf::Message*> UnwrapMessage( const MessageWrapper::Builder& value, absl::string_view op) { if (!value.HasFullProto() || value.message_ptr() == nullptr) { return absl::InternalError( absl::StrCat(op, " called on non-message type.")); } return static_cast<google::protobuf::Message*>(value.message_ptr()); } bool ProtoEquals(const google::protobuf::Message& m1, const google::protobuf::Message& m2) { if (m1.GetDescriptor() != m2.GetDescriptor()) { return false; } return google::protobuf::util::MessageDifferencer::Equals(m1, m2); } bool CelFieldIsPresent(const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_desc, const google::protobuf::Reflection* reflection) { if (field_desc->is_map()) { return reflection->FieldSize(*message, field_desc) != 0; } if (field_desc->is_repeated()) { return reflection->FieldSize(*message, field_desc) != 0; } return reflection->HasField(*message, field_desc); } absl::StatusOr<bool> HasFieldImpl(const google::protobuf::Message* message, const google::protobuf::Descriptor* descriptor, absl::string_view field_name) { ABSL_ASSERT(descriptor == message->GetDescriptor()); const Reflection* reflection = message->GetReflection(); const FieldDescriptor* field_desc = descriptor->FindFieldByName(field_name); if (field_desc == nullptr && reflection != nullptr) { field_desc = reflection->FindKnownExtensionByName(field_name); } if (field_desc == nullptr) { return absl::NotFoundError(absl::StrCat("no_such_field : ", field_name)); } if (reflection == nullptr) { return absl::FailedPreconditionError( "google::protobuf::Reflection unavailble in CEL field access."); } return CelFieldIsPresent(message, field_desc, reflection); } absl::StatusOr<CelValue> CreateCelValueFromField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_desc, ProtoWrapperTypeOptions unboxing_option, google::protobuf::Arena* arena) { if (field_desc->is_map()) { auto* map = google::protobuf::Arena::Create<internal::FieldBackedMapImpl>( arena, message, field_desc, &MessageCelValueFactory, arena); return CelValue::CreateMap(map); } if (field_desc->is_repeated()) { auto* list = google::protobuf::Arena::Create<internal::FieldBackedListImpl>( arena, message, field_desc, &MessageCelValueFactory, arena); return CelValue::CreateList(list); } CEL_ASSIGN_OR_RETURN( CelValue result, internal::CreateValueFromSingleField(message, field_desc, unboxing_option, &MessageCelValueFactory, arena)); return result; } absl::StatusOr<CelValue> GetFieldImpl(const google::protobuf::Message* message, const google::protobuf::Descriptor* descriptor, absl::string_view field_name, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) { ABSL_ASSERT(descriptor == message->GetDescriptor()); const Reflection* reflection = message->GetReflection(); const FieldDescriptor* field_desc = descriptor->FindFieldByName(field_name); if (field_desc == nullptr && reflection != nullptr) { std::string ext_name(field_name); field_desc = reflection->FindKnownExtensionByName(ext_name); } if (field_desc == nullptr) { return CreateNoSuchFieldError(memory_manager, field_name); } google::protobuf::Arena* arena = ProtoMemoryManagerArena(memory_manager); return CreateCelValueFromField(message, field_desc, unboxing_option, arena); } class LegacyQualifyState final : public cel::extensions::protobuf_internal::ProtoQualifyState { public: using ProtoQualifyState::ProtoQualifyState; LegacyQualifyState(const LegacyQualifyState&) = delete; LegacyQualifyState& operator=(const LegacyQualifyState&) = delete; absl::optional<CelValue>& result() { return result_; } private: void SetResultFromError(absl::Status status, cel::MemoryManagerRef memory_manager) override { result_ = CreateErrorValue(memory_manager, status); } void SetResultFromBool(bool value) override { result_ = CelValue::CreateBool(value); } absl::Status SetResultFromField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) override { CEL_ASSIGN_OR_RETURN(result_, CreateCelValueFromField( message, field, unboxing_option, ProtoMemoryManagerArena(memory_manager))); return absl::OkStatus(); } absl::Status SetResultFromRepeatedField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, int index, cel::MemoryManagerRef memory_manager) override { CEL_ASSIGN_OR_RETURN(result_, internal::CreateValueFromRepeatedField( message, field, index, &MessageCelValueFactory, ProtoMemoryManagerArena(memory_manager))); return absl::OkStatus(); } absl::Status SetResultFromMapField( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field, const google::protobuf::MapValueConstRef& value, cel::MemoryManagerRef memory_manager) override { CEL_ASSIGN_OR_RETURN(result_, internal::CreateValueFromMapValue( message, field, &value, &MessageCelValueFactory, ProtoMemoryManagerArena(memory_manager))); return absl::OkStatus(); } absl::optional<CelValue> result_; }; absl::StatusOr<LegacyQualifyResult> QualifyImpl( const google::protobuf::Message* message, const google::protobuf::Descriptor* descriptor, absl::Span<const cel::SelectQualifier> path, bool presence_test, cel::MemoryManagerRef memory_manager) { google::protobuf::Arena* arena = ProtoMemoryManagerArena(memory_manager); ABSL_DCHECK(descriptor == message->GetDescriptor()); LegacyQualifyState qualify_state(message, descriptor, message->GetReflection()); for (int i = 0; i < path.size() - 1; i++) { const auto& qualifier = path.at(i); CEL_RETURN_IF_ERROR(qualify_state.ApplySelectQualifier( qualifier, ProtoMemoryManagerRef(arena))); if (qualify_state.result().has_value()) { LegacyQualifyResult result; result.value = std::move(qualify_state.result()).value(); result.qualifier_count = result.value.IsError() ? -1 : i + 1; return result; } } const auto& last_qualifier = path.back(); LegacyQualifyResult result; result.qualifier_count = -1; if (presence_test) { CEL_RETURN_IF_ERROR(qualify_state.ApplyLastQualifierHas( last_qualifier, ProtoMemoryManagerRef(arena))); } else { CEL_RETURN_IF_ERROR(qualify_state.ApplyLastQualifierGet( last_qualifier, ProtoMemoryManagerRef(arena))); } result.value = *qualify_state.result(); return result; } std::vector<absl::string_view> ListFieldsImpl( const CelValue::MessageWrapper& instance) { if (instance.message_ptr() == nullptr) { return std::vector<absl::string_view>(); } ABSL_ASSERT(instance.HasFullProto()); const auto* message = static_cast<const google::protobuf::Message*>(instance.message_ptr()); const auto* reflect = message->GetReflection(); std::vector<const google::protobuf::FieldDescriptor*> fields; reflect->ListFields(*message, &fields); std::vector<absl::string_view> field_names; field_names.reserve(fields.size()); for (const auto* field : fields) { field_names.emplace_back(field->name()); } return field_names; } class DucktypedMessageAdapter : public LegacyTypeAccessApis, public LegacyTypeMutationApis, public LegacyTypeInfoApis { public: absl::StatusOr<bool> HasField( absl::string_view field_name, const CelValue::MessageWrapper& value) const override { CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message, UnwrapMessage(value, "HasField")); return HasFieldImpl(message, message->GetDescriptor(), field_name); } absl::StatusOr<CelValue> GetField( absl::string_view field_name, const CelValue::MessageWrapper& instance, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) const override { CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message, UnwrapMessage(instance, "GetField")); return GetFieldImpl(message, message->GetDescriptor(), field_name, unboxing_option, memory_manager); } absl::StatusOr<LegacyTypeAccessApis::LegacyQualifyResult> Qualify( absl::Span<const cel::SelectQualifier> qualifiers, const CelValue::MessageWrapper& instance, bool presence_test, cel::MemoryManagerRef memory_manager) const override { CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message, UnwrapMessage(instance, "Qualify")); return QualifyImpl(message, message->GetDescriptor(), qualifiers, presence_test, memory_manager); } bool IsEqualTo( const CelValue::MessageWrapper& instance, const CelValue::MessageWrapper& other_instance) const override { absl::StatusOr<const google::protobuf::Message*> lhs = UnwrapMessage(instance, "IsEqualTo"); absl::StatusOr<const google::protobuf::Message*> rhs = UnwrapMessage(other_instance, "IsEqualTo"); if (!lhs.ok() || !rhs.ok()) { return false; } return ProtoEquals(**lhs, **rhs); } const std::string& GetTypename( const MessageWrapper& wrapped_message) const override { if (!wrapped_message.HasFullProto() || wrapped_message.message_ptr() == nullptr) { return UnsupportedTypeName(); } auto* message = static_cast<const google::protobuf::Message*>(wrapped_message.message_ptr()); return message->GetDescriptor()->full_name(); } std::string DebugString( const MessageWrapper& wrapped_message) const override { if (!wrapped_message.HasFullProto() || wrapped_message.message_ptr() == nullptr) { return UnsupportedTypeName(); } auto* message = static_cast<const google::protobuf::Message*>(wrapped_message.message_ptr()); return message->ShortDebugString(); } bool DefinesField(absl::string_view field_name) const override { return true; } absl::StatusOr<CelValue::MessageWrapper::Builder> NewInstance( cel::MemoryManagerRef memory_manager) const override { return absl::UnimplementedError("NewInstance is not implemented"); } absl::StatusOr<CelValue> AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const override { if (!instance.HasFullProto() || instance.message_ptr() == nullptr) { return absl::UnimplementedError( "MessageLite is not supported, descriptor is required"); } return ProtoMessageTypeAdapter( static_cast<const google::protobuf::Message*>(instance.message_ptr()) ->GetDescriptor(), nullptr) .AdaptFromWellKnownType(memory_manager, instance); } absl::Status SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const override { if (!instance.HasFullProto() || instance.message_ptr() == nullptr) { return absl::UnimplementedError( "MessageLite is not supported, descriptor is required"); } return ProtoMessageTypeAdapter( static_cast<const google::protobuf::Message*>(instance.message_ptr()) ->GetDescriptor(), nullptr) .SetField(field_name, value, memory_manager, instance); } std::vector<absl::string_view> ListFields( const CelValue::MessageWrapper& instance) const override { return ListFieldsImpl(instance); } const LegacyTypeAccessApis* GetAccessApis( const MessageWrapper& wrapped_message) const override { return this; } const LegacyTypeMutationApis* GetMutationApis( const MessageWrapper& wrapped_message) const override { return this; } static const DucktypedMessageAdapter& GetSingleton() { static absl::NoDestructor<DucktypedMessageAdapter> instance; return *instance; } }; CelValue MessageCelValueFactory(const google::protobuf::Message* message) { return CelValue::CreateMessageWrapper( MessageWrapper(message, &DucktypedMessageAdapter::GetSingleton())); } } std::string ProtoMessageTypeAdapter::DebugString( const MessageWrapper& wrapped_message) const { if (!wrapped_message.HasFullProto() || wrapped_message.message_ptr() == nullptr) { return UnsupportedTypeName(); } auto* message = static_cast<const google::protobuf::Message*>(wrapped_message.message_ptr()); return message->ShortDebugString(); } const std::string& ProtoMessageTypeAdapter::GetTypename( const MessageWrapper& wrapped_message) const { return descriptor_->full_name(); } const LegacyTypeMutationApis* ProtoMessageTypeAdapter::GetMutationApis( const MessageWrapper& wrapped_message) const { return this; } const LegacyTypeAccessApis* ProtoMessageTypeAdapter::GetAccessApis( const MessageWrapper& wrapped_message) const { return this; } absl::optional<LegacyTypeInfoApis::FieldDescription> ProtoMessageTypeAdapter::FindFieldByName(absl::string_view field_name) const { if (descriptor_ == nullptr) { return absl::nullopt; } const google::protobuf::FieldDescriptor* field_descriptor = descriptor_->FindFieldByName(field_name); if (field_descriptor == nullptr) { return absl::nullopt; } return LegacyTypeInfoApis::FieldDescription{field_descriptor->number(), field_descriptor->name()}; } absl::Status ProtoMessageTypeAdapter::ValidateSetFieldOp( bool assertion, absl::string_view field, absl::string_view detail) const { if (!assertion) { return absl::InvalidArgumentError( absl::Substitute("SetField failed on message $0, field '$1': $2", descriptor_->full_name(), field, detail)); } return absl::OkStatus(); } absl::StatusOr<CelValue::MessageWrapper::Builder> ProtoMessageTypeAdapter::NewInstance( cel::MemoryManagerRef memory_manager) const { if (message_factory_ == nullptr) { return absl::UnimplementedError( absl::StrCat("Cannot create message ", descriptor_->name())); } google::protobuf::Arena* arena = ProtoMemoryManagerArena(memory_manager); const Message* prototype = message_factory_->GetPrototype(descriptor_); Message* msg = (prototype != nullptr) ? prototype->New(arena) : nullptr; if (msg == nullptr) { return absl::InvalidArgumentError( absl::StrCat("Failed to create message ", descriptor_->name())); } return MessageWrapper::Builder(msg); } bool ProtoMessageTypeAdapter::DefinesField(absl::string_view field_name) const { return descriptor_->FindFieldByName(field_name) != nullptr; } absl::StatusOr<bool> ProtoMessageTypeAdapter::HasField( absl::string_view field_name, const CelValue::MessageWrapper& value) const { CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message, UnwrapMessage(value, "HasField")); return HasFieldImpl(message, descriptor_, field_name); } absl::StatusOr<CelValue> ProtoMessageTypeAdapter::GetField( absl::string_view field_name, const CelValue::MessageWrapper& instance, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager) const { CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message, UnwrapMessage(instance, "GetField")); return GetFieldImpl(message, descriptor_, field_name, unboxing_option, memory_manager); } absl::StatusOr<LegacyTypeAccessApis::LegacyQualifyResult> ProtoMessageTypeAdapter::Qualify( absl::Span<const cel::SelectQualifier> qualifiers, const CelValue::MessageWrapper& instance, bool presence_test, cel::MemoryManagerRef memory_manager) const { CEL_ASSIGN_OR_RETURN(const google::protobuf::Message* message, UnwrapMessage(instance, "Qualify")); return QualifyImpl(message, descriptor_, qualifiers, presence_test, memory_manager); } absl::Status ProtoMessageTypeAdapter::SetField( const google::protobuf::FieldDescriptor* field, const CelValue& value, google::protobuf::Arena* arena, google::protobuf::Message* message) const { if (field->is_map()) { constexpr int kKeyField = 1; constexpr int kValueField = 2; const CelMap* cel_map; CEL_RETURN_IF_ERROR(ValidateSetFieldOp( value.GetValue<const CelMap*>(&cel_map) && cel_map != nullptr, field->name(), "value is not CelMap")); auto entry_descriptor = field->message_type(); CEL_RETURN_IF_ERROR( ValidateSetFieldOp(entry_descriptor != nullptr, field->name(), "failed to find map entry descriptor")); auto key_field_descriptor = entry_descriptor->FindFieldByNumber(kKeyField); auto value_field_descriptor = entry_descriptor->FindFieldByNumber(kValueField); CEL_RETURN_IF_ERROR( ValidateSetFieldOp(key_field_descriptor != nullptr, field->name(), "failed to find key field descriptor")); CEL_RETURN_IF_ERROR( ValidateSetFieldOp(value_field_descriptor != nullptr, field->name(), "failed to find value field descriptor")); CEL_ASSIGN_OR_RETURN(const CelList* key_list, cel_map->ListKeys(arena)); for (int i = 0; i < key_list->size(); i++) { CelValue key = (*key_list).Get(arena, i); auto value = (*cel_map).Get(arena, key); CEL_RETURN_IF_ERROR(ValidateSetFieldOp(value.has_value(), field->name(), "error serializing CelMap")); Message* entry_msg = message->GetReflection()->AddMessage(message, field); CEL_RETURN_IF_ERROR(internal::SetValueToSingleField( key, key_field_descriptor, entry_msg, arena)); CEL_RETURN_IF_ERROR(internal::SetValueToSingleField( value.value(), value_field_descriptor, entry_msg, arena)); } } else if (field->is_repeated()) { const CelList* cel_list; CEL_RETURN_IF_ERROR(ValidateSetFieldOp( value.GetValue<const CelList*>(&cel_list) && cel_list != nullptr, field->name(), "expected CelList value")); for (int i = 0; i < cel_list->size(); i++) { CEL_RETURN_IF_ERROR(internal::AddValueToRepeatedField( (*cel_list).Get(arena, i), field, message, arena)); } } else { CEL_RETURN_IF_ERROR( internal::SetValueToSingleField(value, field, message, arena)); } return absl::OkStatus(); } absl::Status ProtoMessageTypeAdapter::SetField( absl::string_view field_name, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const { google::protobuf::Arena* arena = cel::extensions::ProtoMemoryManagerArena(memory_manager); CEL_ASSIGN_OR_RETURN(google::protobuf::Message * mutable_message, UnwrapMessage(instance, "SetField")); const google::protobuf::FieldDescriptor* field_descriptor = descriptor_->FindFieldByName(field_name); CEL_RETURN_IF_ERROR( ValidateSetFieldOp(field_descriptor != nullptr, field_name, "not found")); return SetField(field_descriptor, value, arena, mutable_message); } absl::Status ProtoMessageTypeAdapter::SetFieldByNumber( int64_t field_number, const CelValue& value, cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder& instance) const { google::protobuf::Arena* arena = cel::extensions::ProtoMemoryManagerArena(memory_manager); CEL_ASSIGN_OR_RETURN(google::protobuf::Message * mutable_message, UnwrapMessage(instance, "SetField")); const google::protobuf::FieldDescriptor* field_descriptor = descriptor_->FindFieldByNumber(field_number); CEL_RETURN_IF_ERROR(ValidateSetFieldOp( field_descriptor != nullptr, absl::StrCat(field_number), "not found")); return SetField(field_descriptor, value, arena, mutable_message); } absl::StatusOr<CelValue> ProtoMessageTypeAdapter::AdaptFromWellKnownType( cel::MemoryManagerRef memory_manager, CelValue::MessageWrapper::Builder instance) const { google::protobuf::Arena* arena = cel::extensions::ProtoMemoryManagerArena(memory_manager); CEL_ASSIGN_OR_RETURN(google::protobuf::Message * message, UnwrapMessage(instance, "AdaptFromWellKnownType")); return internal::UnwrapMessageToValue(message, &MessageCelValueFactory, arena); } bool ProtoMessageTypeAdapter::IsEqualTo( const CelValue::MessageWrapper& instance, const CelValue::MessageWrapper& other_instance) const { absl::StatusOr<const google::protobuf::Message*> lhs = UnwrapMessage(instance, "IsEqualTo"); absl::StatusOr<const google::protobuf::Message*> rhs = UnwrapMessage(other_instance, "IsEqualTo"); if (!lhs.ok() || !rhs.ok()) { return false; } return ProtoEquals(**lhs, **rhs); } std::vector<absl::string_view> ProtoMessageTypeAdapter::ListFields( const CelValue::MessageWrapper& instance) const { return ListFieldsImpl(instance); } const LegacyTypeInfoApis& GetGenericProtoTypeInfoInstance() { return DucktypedMessageAdapter::GetSingleton(); } }
#include "eval/public/structs/proto_message_type_adapter.h" #include <vector> #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/descriptor.pb.h" #include "absl/status/status.h" #include "base/attribute.h" #include "common/value.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/message_wrapper.h" #include "eval/public/structs/legacy_type_adapter.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_message.pb.h" #include "extensions/protobuf/memory_manager.h" #include "internal/proto_matchers.h" #include "internal/testing.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace google::api::expr::runtime { namespace { using ::cel::ProtoWrapperTypeOptions; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::internal::test::EqualsProto; using ::google::protobuf::Int64Value; using testing::_; using testing::AllOf; using testing::ElementsAre; using testing::Eq; using testing::Field; using testing::HasSubstr; using testing::Optional; using testing::Truly; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; using LegacyQualifyResult = LegacyTypeAccessApis::LegacyQualifyResult; class ProtoMessageTypeAccessorTest : public testing::TestWithParam<bool> { public: ProtoMessageTypeAccessorTest() : type_specific_instance_( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()) {} const LegacyTypeAccessApis& GetAccessApis() { bool use_generic_instance = GetParam(); if (use_generic_instance) { return *GetGenericProtoTypeInfoInstance().GetAccessApis(dummy_); } else { return type_specific_instance_; } } private: ProtoMessageTypeAdapter type_specific_instance_; CelValue::MessageWrapper dummy_; }; TEST_P(ProtoMessageTypeAccessorTest, HasFieldSingular) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.HasField("int64_value", value), IsOkAndHolds(false)); example.set_int64_value(10); EXPECT_THAT(accessor.HasField("int64_value", value), IsOkAndHolds(true)); } TEST_P(ProtoMessageTypeAccessorTest, HasFieldRepeated) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.HasField("int64_list", value), IsOkAndHolds(false)); example.add_int64_list(10); EXPECT_THAT(accessor.HasField("int64_list", value), IsOkAndHolds(true)); } TEST_P(ProtoMessageTypeAccessorTest, HasFieldMap) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; example.set_int64_value(10); MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.HasField("int64_int32_map", value), IsOkAndHolds(false)); (*example.mutable_int64_int32_map())[2] = 3; EXPECT_THAT(accessor.HasField("int64_int32_map", value), IsOkAndHolds(true)); } TEST_P(ProtoMessageTypeAccessorTest, HasFieldUnknownField) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; example.set_int64_value(10); MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.HasField("unknown_field", value), StatusIs(absl::StatusCode::kNotFound)); } TEST_P(ProtoMessageTypeAccessorTest, HasFieldNonMessageType) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); MessageWrapper value(static_cast<const google::protobuf::MessageLite*>(nullptr), nullptr); EXPECT_THAT(accessor.HasField("unknown_field", value), StatusIs(absl::StatusCode::kInternal)); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldSingular) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; example.set_int64_value(10); MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.GetField("int64_value", value, ProtoWrapperTypeOptions::kUnsetNull, manager), IsOkAndHolds(test::IsCelInt64(10))); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldNoSuchField) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; example.set_int64_value(10); MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.GetField("unknown_field", value, ProtoWrapperTypeOptions::kUnsetNull, manager), IsOkAndHolds(test::IsCelError(StatusIs( absl::StatusCode::kNotFound, HasSubstr("unknown_field"))))); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldNotAMessage) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); MessageWrapper value(static_cast<const google::protobuf::MessageLite*>(nullptr), nullptr); EXPECT_THAT(accessor.GetField("int64_value", value, ProtoWrapperTypeOptions::kUnsetNull, manager), StatusIs(absl::StatusCode::kInternal)); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldRepeated) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; example.add_int64_list(10); example.add_int64_list(20); MessageWrapper value(&example, nullptr); ASSERT_OK_AND_ASSIGN( CelValue result, accessor.GetField("int64_list", value, ProtoWrapperTypeOptions::kUnsetNull, manager)); const CelList* held_value; ASSERT_TRUE(result.GetValue(&held_value)) << result.DebugString(); EXPECT_EQ(held_value->size(), 2); EXPECT_THAT((*held_value)[0], test::IsCelInt64(10)); EXPECT_THAT((*held_value)[1], test::IsCelInt64(20)); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldMap) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; (*example.mutable_int64_int32_map())[10] = 20; MessageWrapper value(&example, nullptr); ASSERT_OK_AND_ASSIGN( CelValue result, accessor.GetField("int64_int32_map", value, ProtoWrapperTypeOptions::kUnsetNull, manager)); const CelMap* held_value; ASSERT_TRUE(result.GetValue(&held_value)) << result.DebugString(); EXPECT_EQ(held_value->size(), 1); EXPECT_THAT((*held_value)[CelValue::CreateInt64(10)], Optional(test::IsCelInt64(20))); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldWrapperType) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; example.mutable_int64_wrapper_value()->set_value(10); MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.GetField("int64_wrapper_value", value, ProtoWrapperTypeOptions::kUnsetNull, manager), IsOkAndHolds(test::IsCelInt64(10))); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldWrapperTypeUnsetNullUnbox) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; MessageWrapper value(&example, nullptr); EXPECT_THAT(accessor.GetField("int64_wrapper_value", value, ProtoWrapperTypeOptions::kUnsetNull, manager), IsOkAndHolds(test::IsCelNull())); example.mutable_int64_wrapper_value()->clear_value(); EXPECT_THAT(accessor.GetField("int64_wrapper_value", value, ProtoWrapperTypeOptions::kUnsetNull, manager), IsOkAndHolds(test::IsCelInt64(_))); } TEST_P(ProtoMessageTypeAccessorTest, GetFieldWrapperTypeUnsetDefaultValueUnbox) { google::protobuf::Arena arena; const LegacyTypeAccessApis& accessor = GetAccessApis(); auto manager = ProtoMemoryManagerRef(&arena); TestMessage example; MessageWrapper value(&example, nullptr); EXPECT_THAT( accessor.GetField("int64_wrapper_value", value, ProtoWrapperTypeOptions::kUnsetProtoDefault, manager), IsOkAndHolds(test::IsCelInt64(_))); example.mutable_int64_wrapper_value()->clear_value(); EXPECT_THAT( accessor.GetField("int64_wrapper_value", value, ProtoWrapperTypeOptions::kUnsetProtoDefault, manager), IsOkAndHolds(test::IsCelInt64(_))); } TEST_P(ProtoMessageTypeAccessorTest, IsEqualTo) { const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; example.mutable_int64_wrapper_value()->set_value(10); TestMessage example2; example2.mutable_int64_wrapper_value()->set_value(10); MessageWrapper value(&example, nullptr); MessageWrapper value2(&example2, nullptr); EXPECT_TRUE(accessor.IsEqualTo(value, value2)); EXPECT_TRUE(accessor.IsEqualTo(value2, value)); } TEST_P(ProtoMessageTypeAccessorTest, IsEqualToSameTypeInequal) { const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; example.mutable_int64_wrapper_value()->set_value(10); TestMessage example2; example2.mutable_int64_wrapper_value()->set_value(12); MessageWrapper value(&example, nullptr); MessageWrapper value2(&example2, nullptr); EXPECT_FALSE(accessor.IsEqualTo(value, value2)); EXPECT_FALSE(accessor.IsEqualTo(value2, value)); } TEST_P(ProtoMessageTypeAccessorTest, IsEqualToDifferentTypeInequal) { const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; example.mutable_int64_wrapper_value()->set_value(10); Int64Value example2; example2.set_value(10); MessageWrapper value(&example, nullptr); MessageWrapper value2(&example2, nullptr); EXPECT_FALSE(accessor.IsEqualTo(value, value2)); EXPECT_FALSE(accessor.IsEqualTo(value2, value)); } TEST_P(ProtoMessageTypeAccessorTest, IsEqualToNonMessageInequal) { const LegacyTypeAccessApis& accessor = GetAccessApis(); TestMessage example; example.mutable_int64_wrapper_value()->set_value(10); TestMessage example2; example2.mutable_int64_wrapper_value()->set_value(10); MessageWrapper value(&example, nullptr); MessageWrapper value2(static_cast<const google::protobuf::MessageLite*>(&example2), nullptr); EXPECT_FALSE(accessor.IsEqualTo(value, value2)); EXPECT_FALSE(accessor.IsEqualTo(value2, value)); } INSTANTIATE_TEST_SUITE_P(GenericAndSpecific, ProtoMessageTypeAccessorTest, testing::Bool()); TEST(GetGenericProtoTypeInfoInstance, GetTypeName) { const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance(); TestMessage test_message; CelValue::MessageWrapper wrapped_message(&test_message, nullptr); EXPECT_EQ(info_api.GetTypename(wrapped_message), test_message.GetTypeName()); } TEST(GetGenericProtoTypeInfoInstance, DebugString) { const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance(); TestMessage test_message; test_message.set_string_value("abcd"); CelValue::MessageWrapper wrapped_message(&test_message, nullptr); EXPECT_EQ(info_api.DebugString(wrapped_message), test_message.ShortDebugString()); } TEST(GetGenericProtoTypeInfoInstance, GetAccessApis) { const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance(); TestMessage test_message; test_message.set_string_value("abcd"); CelValue::MessageWrapper wrapped_message(&test_message, nullptr); auto* accessor = info_api.GetAccessApis(wrapped_message); google::protobuf::Arena arena; auto manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN( CelValue result, accessor->GetField("string_value", wrapped_message, ProtoWrapperTypeOptions::kUnsetNull, manager)); EXPECT_THAT(result, test::IsCelString("abcd")); } TEST(GetGenericProtoTypeInfoInstance, FallbackForNonMessage) { const LegacyTypeInfoApis& info_api = GetGenericProtoTypeInfoInstance(); TestMessage test_message; test_message.set_string_value("abcd"); CelValue::MessageWrapper wrapped_message( static_cast<const google::protobuf::MessageLite*>(&test_message), nullptr); EXPECT_EQ(info_api.GetTypename(wrapped_message), "<unknown message>"); EXPECT_EQ(info_api.DebugString(wrapped_message), "<unknown message>"); CelValue::MessageWrapper null_message( static_cast<const google::protobuf::Message*>(nullptr), nullptr); EXPECT_EQ(info_api.GetTypename(null_message), "<unknown message>"); EXPECT_EQ(info_api.DebugString(null_message), "<unknown message>"); } TEST(ProtoMessageTypeAdapter, NewInstance) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder result, adapter.NewInstance(manager)); EXPECT_EQ(result.message_ptr()->SerializeAsString(), ""); } TEST(ProtoMessageTypeAdapter, NewInstanceUnsupportedDescriptor) { google::protobuf::Arena arena; google::protobuf::DescriptorPool pool; google::protobuf::FileDescriptorProto faked_file; faked_file.set_name("faked.proto"); faked_file.set_syntax("proto3"); faked_file.set_package("google.api.expr.runtime"); auto msg_descriptor = faked_file.add_message_type(); msg_descriptor->set_name("FakeMessage"); pool.BuildFile(faked_file); ProtoMessageTypeAdapter adapter( pool.FindMessageTypeByName("google.api.expr.runtime.FakeMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); EXPECT_THAT( adapter.NewInstance(manager), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("FakeMessage"))); } TEST(ProtoMessageTypeAdapter, DefinesField) { ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); EXPECT_TRUE(adapter.DefinesField("int64_value")); EXPECT_FALSE(adapter.DefinesField("not_a_field")); } TEST(ProtoMessageTypeAdapter, SetFieldSingular) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder value, adapter.NewInstance(manager)); ASSERT_OK(adapter.SetField("int64_value", CelValue::CreateInt64(10), manager, value)); TestMessage message; message.set_int64_value(10); EXPECT_EQ(value.message_ptr()->SerializeAsString(), message.SerializeAsString()); ASSERT_THAT(adapter.SetField("not_a_field", CelValue::CreateInt64(10), manager, value), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("field 'not_a_field': not found"))); } TEST(ProtoMessageTypeAdapter, SetFieldRepeated) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ContainerBackedListImpl list( {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}); CelValue value_to_set = CelValue::CreateList(&list); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance, adapter.NewInstance(manager)); ASSERT_OK(adapter.SetField("int64_list", value_to_set, manager, instance)); TestMessage message; message.add_int64_list(1); message.add_int64_list(2); EXPECT_EQ(instance.message_ptr()->SerializeAsString(), message.SerializeAsString()); } TEST(ProtoMessageTypeAdapter, SetFieldNotAField) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance, adapter.NewInstance(manager)); ASSERT_THAT(adapter.SetField("not_a_field", CelValue::CreateInt64(10), manager, instance), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("field 'not_a_field': not found"))); } TEST(ProtoMesssageTypeAdapter, SetFieldWrongType) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ContainerBackedListImpl list( {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}); CelValue list_value = CelValue::CreateList(&list); CelMapBuilder builder; ASSERT_OK(builder.Add(CelValue::CreateInt64(1), CelValue::CreateInt64(2))); ASSERT_OK(builder.Add(CelValue::CreateInt64(2), CelValue::CreateInt64(4))); CelValue map_value = CelValue::CreateMap(&builder); CelValue int_value = CelValue::CreateInt64(42); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance, adapter.NewInstance(manager)); EXPECT_THAT(adapter.SetField("int64_value", map_value, manager, instance), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(adapter.SetField("int64_value", list_value, manager, instance), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( adapter.SetField("int64_int32_map", list_value, manager, instance), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(adapter.SetField("int64_int32_map", int_value, manager, instance), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(adapter.SetField("int64_list", int_value, manager, instance), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(adapter.SetField("int64_list", map_value, manager, instance), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ProtoMesssageTypeAdapter, SetFieldNotAMessage) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); CelValue int_value = CelValue::CreateInt64(42); CelValue::MessageWrapper::Builder instance( static_cast<google::protobuf::MessageLite*>(nullptr)); EXPECT_THAT(adapter.SetField("int64_value", int_value, manager, instance), StatusIs(absl::StatusCode::kInternal)); } TEST(ProtoMesssageTypeAdapter, SetFieldNullMessage) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); CelValue int_value = CelValue::CreateInt64(42); CelValue::MessageWrapper::Builder instance( static_cast<google::protobuf::Message*>(nullptr)); EXPECT_THAT(adapter.SetField("int64_value", int_value, manager, instance), StatusIs(absl::StatusCode::kInternal)); } TEST(ProtoMessageTypeAdapter, AdaptFromWellKnownType) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.protobuf.Int64Value"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance, adapter.NewInstance(manager)); ASSERT_OK( adapter.SetField("value", CelValue::CreateInt64(42), manager, instance)); ASSERT_OK_AND_ASSIGN(CelValue value, adapter.AdaptFromWellKnownType(manager, instance)); EXPECT_THAT(value, test::IsCelInt64(42)); } TEST(ProtoMessageTypeAdapter, AdaptFromWellKnownTypeUnspecial) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(CelValue::MessageWrapper::Builder instance, adapter.NewInstance(manager)); ASSERT_OK(adapter.SetField("int64_value", CelValue::CreateInt64(42), manager, instance)); ASSERT_OK_AND_ASSIGN(CelValue value, adapter.AdaptFromWellKnownType(manager, instance)); EXPECT_THAT(value, test::IsCelMessage(EqualsProto("int64_value: 42"))); } TEST(ProtoMessageTypeAdapter, AdaptFromWellKnownTypeNotAMessageError) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); CelValue::MessageWrapper::Builder instance( static_cast<google::protobuf::MessageLite*>(nullptr)); EXPECT_THAT(adapter.AdaptFromWellKnownType(manager, instance), StatusIs(absl::StatusCode::kInternal)); } TEST(ProtoMesssageTypeAdapter, TypeInfoDebug) { ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); TestMessage message; message.set_int64_value(42); EXPECT_THAT(adapter.DebugString(MessageWrapper(&message, &adapter)), HasSubstr(message.ShortDebugString())); EXPECT_THAT(adapter.DebugString(MessageWrapper()), HasSubstr("<unknown message>")); } TEST(ProtoMesssageTypeAdapter, TypeInfoName) { ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); EXPECT_EQ(adapter.GetTypename(MessageWrapper()), "google.api.expr.runtime.TestMessage"); } TEST(ProtoMesssageTypeAdapter, FindFieldFound) { ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); EXPECT_THAT( adapter.FindFieldByName("int64_value"), Optional(Truly([](const LegacyTypeInfoApis::FieldDescription& desc) { return desc.name == "int64_value" && desc.number == 2; }))) << "expected field int64_value: 2"; } TEST(ProtoMesssageTypeAdapter, FindFieldNotFound) { ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); EXPECT_EQ(adapter.FindFieldByName("foo_not_a_field"), absl::nullopt); } TEST(ProtoMesssageTypeAdapter, TypeInfoMutator) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); const LegacyTypeMutationApis* api = adapter.GetMutationApis(MessageWrapper()); ASSERT_NE(api, nullptr); ASSERT_OK_AND_ASSIGN(MessageWrapper::Builder builder, api->NewInstance(manager)); EXPECT_NE(dynamic_cast<TestMessage*>(builder.message_ptr()), nullptr); } TEST(ProtoMesssageTypeAdapter, TypeInfoAccesor) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); TestMessage message; message.set_int64_value(42); CelValue::MessageWrapper wrapped(&message, &adapter); const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper()); ASSERT_NE(api, nullptr); EXPECT_THAT(api->GetField("int64_value", wrapped, ProtoWrapperTypeOptions::kUnsetNull, manager), IsOkAndHolds(test::IsCelInt64(42))); } TEST(ProtoMesssageTypeAdapter, Qualify) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); TestMessage message; message.mutable_message_value()->set_int64_value(42); CelValue::MessageWrapper wrapped(&message, &adapter); const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper()); ASSERT_NE(api, nullptr); std::vector<cel::SelectQualifier> qualfiers{ cel::FieldSpecifier{12, "message_value"}, cel::FieldSpecifier{2, "int64_value"}}; EXPECT_THAT( api->Qualify(qualfiers, wrapped, false, manager), IsOkAndHolds(Field(&LegacyQualifyResult::value, test::IsCelInt64(42)))); } TEST(ProtoMesssageTypeAdapter, QualifyDynamicFieldAccessUnsupported) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); TestMessage message; message.mutable_message_value()->set_int64_value(42); CelValue::MessageWrapper wrapped(&message, &adapter); const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper()); ASSERT_NE(api, nullptr); std::vector<cel::SelectQualifier> qualfiers{ cel::FieldSpecifier{12, "message_value"}, cel::AttributeQualifier::OfString("int64_value")}; EXPECT_THAT(api->Qualify(qualfiers, wrapped, false, manager), StatusIs(absl::StatusCode::kUnimplemented)); } TEST(ProtoMesssageTypeAdapter, QualifyNoSuchField) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); TestMessage message; message.mutable_message_value()->set_int64_value(42); CelValue::MessageWrapper wrapped(&message, &adapter); const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper()); ASSERT_NE(api, nullptr); std::vector<cel::SelectQualifier> qualfiers{ cel::FieldSpecifier{12, "message_value"}, cel::FieldSpecifier{99, "not_a_field"}, cel::FieldSpecifier{2, "int64_value"}}; EXPECT_THAT(api->Qualify(qualfiers, wrapped, false, manager), IsOkAndHolds(Field( &LegacyQualifyResult::value, test::IsCelError(StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field")))))); } TEST(ProtoMesssageTypeAdapter, QualifyHasNoSuchField) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); TestMessage message; message.mutable_message_value()->set_int64_value(42); CelValue::MessageWrapper wrapped(&message, &adapter); const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper()); ASSERT_NE(api, nullptr); std::vector<cel::SelectQualifier> qualfiers{ cel::FieldSpecifier{12, "message_value"}, cel::FieldSpecifier{99, "not_a_field"}}; EXPECT_THAT(api->Qualify(qualfiers, wrapped, true, manager), IsOkAndHolds(Field( &LegacyQualifyResult::value, test::IsCelError(StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_field")))))); } TEST(ProtoMesssageTypeAdapter, QualifyNoSuchFieldLeaf) { google::protobuf::Arena arena; ProtoMessageTypeAdapter adapter( google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName( "google.api.expr.runtime.TestMessage"), google::protobuf::MessageFactory::generated_factory()); auto manager = ProtoMemoryManagerRef(&arena); TestMessage message; message.mutable_message_value()->set_int64_value(42); CelValue::MessageWrapper wrapped(&message, &adapter); const LegacyTypeAccessApis* api = adapter.GetAccessApis(MessageWrapper()); ASSERT_NE(api, nullptr); std::vector<cel::SelectQualifier> qualfiers{ cel::FieldSpecifier{12, "message_value"}, cel::FieldSpecifier{99, "not_a_field"}}; EXPECT_THAT(api->Qualify(qualfiers, wrapped, false, manager), IsOkAndHolds(Field( &LegacyQualifyResult::value, test::IsCelError(StatusIs(absl::StatusCode::kNotFound, HasSubstr("no_such_f
112
cpp
google/cel-cpp
cel_proto_wrapper
eval/public/structs/cel_proto_wrapper.cc
eval/public/structs/cel_proto_wrapper_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_WRAPPER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_WRAPPER_H_ #include "google/protobuf/duration.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/descriptor.h" #include "eval/public/cel_value.h" #include "internal/proto_time_encoding.h" namespace google::api::expr::runtime { class CelProtoWrapper { public: static CelValue CreateMessage(const google::protobuf::Message* value, google::protobuf::Arena* arena); static CelValue InternalWrapMessage(const google::protobuf::Message* message); static CelValue CreateDuration(const google::protobuf::Duration* value) { return CelValue(cel::internal::DecodeDuration(*value)); } static CelValue CreateTimestamp(const google::protobuf::Timestamp* value) { return CelValue(cel::internal::DecodeTime(*value)); } static absl::optional<CelValue> MaybeWrapValue( const google::protobuf::Descriptor* descriptor, const CelValue& value, google::protobuf::Arena* arena); }; } #endif #include "eval/public/structs/cel_proto_wrapper.h" #include "google/protobuf/message.h" #include "absl/types/optional.h" #include "eval/public/cel_value.h" #include "eval/public/message_wrapper.h" #include "eval/public/structs/cel_proto_wrap_util.h" #include "eval/public/structs/proto_message_type_adapter.h" namespace google::api::expr::runtime { namespace { using ::google::protobuf::Arena; using ::google::protobuf::Descriptor; using ::google::protobuf::Message; } CelValue CelProtoWrapper::InternalWrapMessage(const Message* message) { return CelValue::CreateMessageWrapper( MessageWrapper(message, &GetGenericProtoTypeInfoInstance())); } CelValue CelProtoWrapper::CreateMessage(const Message* value, Arena* arena) { return internal::UnwrapMessageToValue(value, &InternalWrapMessage, arena); } absl::optional<CelValue> CelProtoWrapper::MaybeWrapValue( const Descriptor* descriptor, const CelValue& value, Arena* arena) { const Message* msg = internal::MaybeWrapValueToMessage(descriptor, value, arena); if (msg != nullptr) { return InternalWrapMessage(msg); } else { return absl::nullopt; } } }
#include "eval/public/structs/cel_proto_wrapper.h" #include <cassert> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/empty.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/wrappers.pb.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/message.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/testutil/test_message.pb.h" #include "internal/proto_time_encoding.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "testutil/util.h" namespace google::api::expr::runtime { namespace { using testing::Eq; using testing::UnorderedPointwise; using google::protobuf::Duration; using google::protobuf::ListValue; using google::protobuf::Struct; using google::protobuf::Timestamp; using google::protobuf::Value; using google::protobuf::Any; using google::protobuf::BoolValue; using google::protobuf::BytesValue; using google::protobuf::DoubleValue; using google::protobuf::FloatValue; using google::protobuf::Int32Value; using google::protobuf::Int64Value; using google::protobuf::StringValue; using google::protobuf::UInt32Value; using google::protobuf::UInt64Value; using google::protobuf::Arena; class CelProtoWrapperTest : public ::testing::Test { protected: CelProtoWrapperTest() {} void ExpectWrappedMessage(const CelValue& value, const google::protobuf::Message& message) { auto result = CelProtoWrapper::MaybeWrapValue(message.GetDescriptor(), value, arena()); EXPECT_TRUE(result.has_value()); EXPECT_TRUE((*result).IsMessage()); EXPECT_THAT((*result).MessageOrDie(), testutil::EqualsProto(message)); auto identity = CelProtoWrapper::MaybeWrapValue(message.GetDescriptor(), *result, arena()); EXPECT_FALSE(identity.has_value()); result = CelProtoWrapper::MaybeWrapValue( ReflectedCopy(message)->GetDescriptor(), value, arena()); EXPECT_TRUE(result.has_value()); EXPECT_TRUE((*result).IsMessage()); EXPECT_THAT((*result).MessageOrDie(), testutil::EqualsProto(message)); } void ExpectNotWrapped(const CelValue& value, const google::protobuf::Message& message) { auto result = CelProtoWrapper::MaybeWrapValue(message.GetDescriptor(), value, arena()); EXPECT_FALSE(result.has_value()); } template <class T> void ExpectUnwrappedPrimitive(const google::protobuf::Message& message, T result) { CelValue cel_value = CelProtoWrapper::CreateMessage(&message, arena()); T value; EXPECT_TRUE(cel_value.GetValue(&value)); EXPECT_THAT(value, Eq(result)); T dyn_value; CelValue cel_dyn_value = CelProtoWrapper::CreateMessage(ReflectedCopy(message).get(), arena()); EXPECT_THAT(cel_dyn_value.type(), Eq(cel_value.type())); EXPECT_TRUE(cel_dyn_value.GetValue(&dyn_value)); EXPECT_THAT(value, Eq(dyn_value)); } void ExpectUnwrappedMessage(const google::protobuf::Message& message, google::protobuf::Message* result) { CelValue cel_value = CelProtoWrapper::CreateMessage(&message, arena()); if (result == nullptr) { EXPECT_TRUE(cel_value.IsNull()); return; } EXPECT_TRUE(cel_value.IsMessage()); EXPECT_THAT(cel_value.MessageOrDie(), testutil::EqualsProto(*result)); } std::unique_ptr<google::protobuf::Message> ReflectedCopy( const google::protobuf::Message& message) { std::unique_ptr<google::protobuf::Message> dynamic_value( factory_.GetPrototype(message.GetDescriptor())->New()); dynamic_value->CopyFrom(message); return dynamic_value; } Arena* arena() { return &arena_; } private: Arena arena_; google::protobuf::DynamicMessageFactory factory_; }; TEST_F(CelProtoWrapperTest, TestType) { Duration msg_duration; msg_duration.set_seconds(2); msg_duration.set_nanos(3); CelValue value_duration1 = CelProtoWrapper::CreateDuration(&msg_duration); EXPECT_THAT(value_duration1.type(), Eq(CelValue::Type::kDuration)); CelValue value_duration2 = CelProtoWrapper::CreateMessage(&msg_duration, arena()); EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration)); Timestamp msg_timestamp; msg_timestamp.set_seconds(2); msg_timestamp.set_nanos(3); CelValue value_timestamp1 = CelProtoWrapper::CreateTimestamp(&msg_timestamp); EXPECT_THAT(value_timestamp1.type(), Eq(CelValue::Type::kTimestamp)); CelValue value_timestamp2 = CelProtoWrapper::CreateMessage(&msg_timestamp, arena()); EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp)); } TEST_F(CelProtoWrapperTest, TestDuration) { Duration msg_duration; msg_duration.set_seconds(2); msg_duration.set_nanos(3); CelValue value_duration1 = CelProtoWrapper::CreateDuration(&msg_duration); EXPECT_THAT(value_duration1.type(), Eq(CelValue::Type::kDuration)); CelValue value_duration2 = CelProtoWrapper::CreateMessage(&msg_duration, arena()); EXPECT_THAT(value_duration2.type(), Eq(CelValue::Type::kDuration)); CelValue value = CelProtoWrapper::CreateDuration(&msg_duration); EXPECT_TRUE(value.IsDuration()); Duration out; auto status = cel::internal::EncodeDuration(value.DurationOrDie(), &out); EXPECT_TRUE(status.ok()); EXPECT_THAT(out, testutil::EqualsProto(msg_duration)); } TEST_F(CelProtoWrapperTest, TestTimestamp) { Timestamp msg_timestamp; msg_timestamp.set_seconds(2); msg_timestamp.set_nanos(3); CelValue value_timestamp1 = CelProtoWrapper::CreateTimestamp(&msg_timestamp); EXPECT_THAT(value_timestamp1.type(), Eq(CelValue::Type::kTimestamp)); CelValue value_timestamp2 = CelProtoWrapper::CreateMessage(&msg_timestamp, arena()); EXPECT_THAT(value_timestamp2.type(), Eq(CelValue::Type::kTimestamp)); CelValue value = CelProtoWrapper::CreateTimestamp(&msg_timestamp); EXPECT_TRUE(value.IsTimestamp()); Timestamp out; auto status = cel::internal::EncodeTime(value.TimestampOrDie(), &out); EXPECT_TRUE(status.ok()); EXPECT_THAT(out, testutil::EqualsProto(msg_timestamp)); } TEST_F(CelProtoWrapperTest, UnwrapValueNull) { Value json; json.set_null_value(google::protobuf::NullValue::NULL_VALUE); ExpectUnwrappedMessage(json, nullptr); } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueNull) { Value value_msg; value_msg.set_null_value(protobuf::NULL_VALUE); CelValue value = CelProtoWrapper::CreateMessage(ReflectedCopy(value_msg).get(), arena()); EXPECT_TRUE(value.IsNull()); } TEST_F(CelProtoWrapperTest, UnwrapValueBool) { bool value = true; Value json; json.set_bool_value(true); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, UnwrapValueNumber) { double value = 1.0; Value json; json.set_number_value(value); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, UnwrapValueString) { const std::string test = "test"; auto value = CelValue::StringHolder(&test); Value json; json.set_string_value(test); ExpectUnwrappedPrimitive(json, value); } TEST_F(CelProtoWrapperTest, UnwrapValueStruct) { const std::vector<std::string> kFields = {"field1", "field2", "field3"}; Struct value_struct; auto& value1 = (*value_struct.mutable_fields())[kFields[0]]; value1.set_bool_value(true); auto& value2 = (*value_struct.mutable_fields())[kFields[1]]; value2.set_number_value(1.0); auto& value3 = (*value_struct.mutable_fields())[kFields[2]]; value3.set_string_value("test"); CelValue value = CelProtoWrapper::CreateMessage(&value_struct, arena()); ASSERT_TRUE(value.IsMap()); const CelMap* cel_map = value.MapOrDie(); CelValue field1 = CelValue::CreateString(&kFields[0]); auto field1_presence = cel_map->Has(field1); ASSERT_OK(field1_presence); EXPECT_TRUE(*field1_presence); auto lookup1 = (*cel_map)[field1]; ASSERT_TRUE(lookup1.has_value()); ASSERT_TRUE(lookup1->IsBool()); EXPECT_EQ(lookup1->BoolOrDie(), true); CelValue field2 = CelValue::CreateString(&kFields[1]); auto field2_presence = cel_map->Has(field2); ASSERT_OK(field2_presence); EXPECT_TRUE(*field2_presence); auto lookup2 = (*cel_map)[field2]; ASSERT_TRUE(lookup2.has_value()); ASSERT_TRUE(lookup2->IsDouble()); EXPECT_DOUBLE_EQ(lookup2->DoubleOrDie(), 1.0); CelValue field3 = CelValue::CreateString(&kFields[2]); auto field3_presence = cel_map->Has(field3); ASSERT_OK(field3_presence); EXPECT_TRUE(*field3_presence); auto lookup3 = (*cel_map)[field3]; ASSERT_TRUE(lookup3.has_value()); ASSERT_TRUE(lookup3->IsString()); EXPECT_EQ(lookup3->StringOrDie().value(), "test"); std::string missing = "missing_field"; CelValue missing_field = CelValue::CreateString(&missing); auto missing_field_presence = cel_map->Has(missing_field); ASSERT_OK(missing_field_presence); EXPECT_FALSE(*missing_field_presence); const CelList* key_list = cel_map->ListKeys().value(); ASSERT_EQ(key_list->size(), kFields.size()); std::vector<std::string> result_keys; for (int i = 0; i < key_list->size(); i++) { CelValue key = (*key_list)[i]; ASSERT_TRUE(key.IsString()); result_keys.push_back(std::string(key.StringOrDie().value())); } EXPECT_THAT(result_keys, UnorderedPointwise(Eq(), kFields)); } TEST_F(CelProtoWrapperTest, UnwrapDynamicStruct) { Struct struct_msg; const std::string kFieldInt = "field_int"; const std::string kFieldBool = "field_bool"; (*struct_msg.mutable_fields())[kFieldInt].set_number_value(1.); (*struct_msg.mutable_fields())[kFieldBool].set_bool_value(true); CelValue value = CelProtoWrapper::CreateMessage(ReflectedCopy(struct_msg).get(), arena()); EXPECT_TRUE(value.IsMap()); const CelMap* cel_map = value.MapOrDie(); ASSERT_TRUE(cel_map != nullptr); { auto lookup = (*cel_map)[CelValue::CreateString(&kFieldInt)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsDouble()); EXPECT_THAT(v.DoubleOrDie(), testing::DoubleEq(1.)); } { auto lookup = (*cel_map)[CelValue::CreateString(&kFieldBool)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsBool()); EXPECT_EQ(v.BoolOrDie(), true); } { auto presence = cel_map->Has(CelValue::CreateBool(true)); ASSERT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); auto lookup = (*cel_map)[CelValue::CreateBool(true)]; ASSERT_TRUE(lookup.has_value()); auto v = lookup.value(); ASSERT_TRUE(v.IsError()); } } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueStruct) { const std::string kField1 = "field1"; const std::string kField2 = "field2"; Value value_msg; (*value_msg.mutable_struct_value()->mutable_fields())[kField1] .set_number_value(1); (*value_msg.mutable_struct_value()->mutable_fields())[kField2] .set_number_value(2); CelValue value = CelProtoWrapper::CreateMessage(ReflectedCopy(value_msg).get(), arena()); EXPECT_TRUE(value.IsMap()); EXPECT_TRUE( (*value.MapOrDie())[CelValue::CreateString(&kField1)].has_value()); EXPECT_TRUE( (*value.MapOrDie())[CelValue::CreateString(&kField2)].has_value()); } TEST_F(CelProtoWrapperTest, UnwrapValueList) { const std::vector<std::string> kFields = {"field1", "field2", "field3"}; ListValue list_value; list_value.add_values()->set_bool_value(true); list_value.add_values()->set_number_value(1.0); list_value.add_values()->set_string_value("test"); CelValue value = CelProtoWrapper::CreateMessage(&list_value, arena()); ASSERT_TRUE(value.IsList()); const CelList* cel_list = value.ListOrDie(); ASSERT_EQ(cel_list->size(), 3); CelValue value1 = (*cel_list)[0]; ASSERT_TRUE(value1.IsBool()); EXPECT_EQ(value1.BoolOrDie(), true); auto value2 = (*cel_list)[1]; ASSERT_TRUE(value2.IsDouble()); EXPECT_DOUBLE_EQ(value2.DoubleOrDie(), 1.0); auto value3 = (*cel_list)[2]; ASSERT_TRUE(value3.IsString()); EXPECT_EQ(value3.StringOrDie().value(), "test"); } TEST_F(CelProtoWrapperTest, UnwrapDynamicValueListValue) { Value value_msg; value_msg.mutable_list_value()->add_values()->set_number_value(1.); value_msg.mutable_list_value()->add_values()->set_number_value(2.); CelValue value = CelProtoWrapper::CreateMessage(ReflectedCopy(value_msg).get(), arena()); EXPECT_TRUE(value.IsList()); EXPECT_THAT((*value.ListOrDie())[0].DoubleOrDie(), testing::DoubleEq(1)); EXPECT_THAT((*value.ListOrDie())[1].DoubleOrDie(), testing::DoubleEq(2)); } TEST_F(CelProtoWrapperTest, UnwrapAnyValue) { TestMessage test_message; test_message.set_string_value("test"); Any any; any.PackFrom(test_message); ExpectUnwrappedMessage(any, &test_message); } TEST_F(CelProtoWrapperTest, UnwrapInvalidAny) { Any any; CelValue value = CelProtoWrapper::CreateMessage(&any, arena()); ASSERT_TRUE(value.IsError()); any.set_type_url("/"); ASSERT_TRUE(CelProtoWrapper::CreateMessage(&any, arena()).IsError()); any.set_type_url("/invalid.proto.name"); ASSERT_TRUE(CelProtoWrapper::CreateMessage(&any, arena()).IsError()); } TEST_F(CelProtoWrapperTest, UnwrapBoolWrapper) { bool value = true; BoolValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapInt32Wrapper) { int64_t value = 12; Int32Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapUInt32Wrapper) { uint64_t value = 12; UInt32Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapInt64Wrapper) { int64_t value = 12; Int64Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapUInt64Wrapper) { uint64_t value = 12; UInt64Value wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapFloatWrapper) { double value = 42.5; FloatValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapDoubleWrapper) { double value = 42.5; DoubleValue wrapper; wrapper.set_value(value); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapStringWrapper) { std::string text = "42"; auto value = CelValue::StringHolder(&text); StringValue wrapper; wrapper.set_value(text); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, UnwrapBytesWrapper) { std::string text = "42"; auto value = CelValue::BytesHolder(&text); BytesValue wrapper; wrapper.set_value("42"); ExpectUnwrappedPrimitive(wrapper, value); } TEST_F(CelProtoWrapperTest, WrapNull) { auto cel_value = CelValue::CreateNull(); Value json; json.set_null_value(protobuf::NULL_VALUE); ExpectWrappedMessage(cel_value, json); Any any; any.PackFrom(json); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBool) { auto cel_value = CelValue::CreateBool(true); Value json; json.set_bool_value(true); ExpectWrappedMessage(cel_value, json); BoolValue wrapper; wrapper.set_value(true); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBytes) { std::string str = "hello world"; auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str)); BytesValue wrapper; wrapper.set_value(str); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapBytesToValue) { std::string str = "hello world"; auto cel_value = CelValue::CreateBytes(CelValue::BytesHolder(&str)); Value json; json.set_string_value("aGVsbG8gd29ybGQ="); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapDuration) { auto cel_value = CelValue::CreateDuration(absl::Seconds(300)); Duration d; d.set_seconds(300); ExpectWrappedMessage(cel_value, d); Any any; any.PackFrom(d); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapDurationToValue) { auto cel_value = CelValue::CreateDuration(absl::Seconds(300)); Value json; json.set_string_value("300s"); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapDouble) { double num = 1.5; auto cel_value = CelValue::CreateDouble(num); Value json; json.set_number_value(num); ExpectWrappedMessage(cel_value, json); DoubleValue wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapDoubleToFloatValue) { double num = 1.5; auto cel_value = CelValue::CreateDouble(num); FloatValue wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); double small_num = -9.9e-100; wrapper.set_value(small_num); cel_value = CelValue::CreateDouble(small_num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapDoubleOverflow) { double lowest_double = std::numeric_limits<double>::lowest(); auto cel_value = CelValue::CreateDouble(lowest_double); FloatValue wrapper; wrapper.set_value(-std::numeric_limits<float>::infinity()); ExpectWrappedMessage(cel_value, wrapper); double max_double = std::numeric_limits<double>::max(); cel_value = CelValue::CreateDouble(max_double); wrapper.set_value(std::numeric_limits<float>::infinity()); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapInt64) { int32_t num = std::numeric_limits<int32_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Value json; json.set_number_value(static_cast<double>(num)); ExpectWrappedMessage(cel_value, json); Int64Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapInt64ToInt32Value) { int32_t num = std::numeric_limits<int32_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Int32Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapFailureInt64ToInt32Value) { int64_t num = std::numeric_limits<int64_t>::lowest(); auto cel_value = CelValue::CreateInt64(num); Int32Value wrapper; ExpectNotWrapped(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapInt64ToValue) { int64_t max = std::numeric_limits<int64_t>::max(); auto cel_value = CelValue::CreateInt64(max); Value json; json.set_string_value(absl::StrCat(max)); ExpectWrappedMessage(cel_value, json); int64_t min = std::numeric_limits<int64_t>::min(); cel_value = CelValue::CreateInt64(min); json.set_string_value(absl::StrCat(min)); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapUint64) { uint32_t num = std::numeric_limits<uint32_t>::max(); auto cel_value = CelValue::CreateUint64(num); Value json; json.set_number_value(static_cast<double>(num)); ExpectWrappedMessage(cel_value, json); UInt64Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapUint64ToUint32Value) { uint32_t num = std::numeric_limits<uint32_t>::max(); auto cel_value = CelValue::CreateUint64(num); UInt32Value wrapper; wrapper.set_value(num); ExpectWrappedMessage(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapUint64ToValue) { uint64_t num = std::numeric_limits<uint64_t>::max(); auto cel_value = CelValue::CreateUint64(num); Value json; json.set_string_value(absl::StrCat(num)); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureUint64ToUint32Value) { uint64_t num = std::numeric_limits<uint64_t>::max(); auto cel_value = CelValue::CreateUint64(num); UInt32Value wrapper; ExpectNotWrapped(cel_value, wrapper); } TEST_F(CelProtoWrapperTest, WrapString) { std::string str = "test"; auto cel_value = CelValue::CreateString(CelValue::StringHolder(&str)); Value json; json.set_string_value(str); ExpectWrappedMessage(cel_value, json); StringValue wrapper; wrapper.set_value(str); ExpectWrappedMessage(cel_value, wrapper); Any any; any.PackFrom(wrapper); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapTimestamp) { absl::Time ts = absl::FromUnixSeconds(1615852799); auto cel_value = CelValue::CreateTimestamp(ts); Timestamp t; t.set_seconds(1615852799); ExpectWrappedMessage(cel_value, t); Any any; any.PackFrom(t); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapTimestampToValue) { absl::Time ts = absl::FromUnixSeconds(1615852799); auto cel_value = CelValue::CreateTimestamp(ts); Value json; json.set_string_value("2021-03-15T23:59:59Z"); ExpectWrappedMessage(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapList) { std::vector<CelValue> list_elems = { CelValue::CreateDouble(1.5), CelValue::CreateInt64(-2L), }; ContainerBackedListImpl list(std::move(list_elems)); auto cel_value = CelValue::CreateList(&list); Value json; json.mutable_list_value()->add_values()->set_number_value(1.5); json.mutable_list_value()->add_values()->set_number_value(-2.); ExpectWrappedMessage(cel_value, json); ExpectWrappedMessage(cel_value, json.list_value()); Any any; any.PackFrom(json.list_value()); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapFailureListValueBadJSON) { TestMessage message; std::vector<CelValue> list_elems = { CelValue::CreateDouble(1.5), CelProtoWrapper::CreateMessage(&message, arena()), }; ContainerBackedListImpl list(std::move(list_elems)); auto cel_value = CelValue::CreateList(&list); Value json; ExpectNotWrapped(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapStruct) { const std::string kField1 = "field1"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(CelValue::StringHolder(&kField1)), CelValue::CreateBool(true)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); auto cel_value = CelValue::CreateMap(cel_map.get()); Value json; (*json.mutable_struct_value()->mutable_fields())[kField1].set_bool_value( true); ExpectWrappedMessage(cel_value, json); ExpectWrappedMessage(cel_value, json.struct_value()); Any any; any.PackFrom(json.struct_value()); ExpectWrappedMessage(cel_value, any); } TEST_F(CelProtoWrapperTest, WrapFailureStructBadKeyType) { std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateInt64(1L), CelValue::CreateBool(true)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); auto cel_value = CelValue::CreateMap(cel_map.get()); Value json; ExpectNotWrapped(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureStructBadValueType) { const std::string kField1 = "field1"; TestMessage bad_value; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(CelValue::StringHolder(&kField1)), CelProtoWrapper::CreateMessage(&bad_value, arena())}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); auto cel_value = CelValue::CreateMap(cel_map.get()); Value json; ExpectNotWrapped(cel_value, json); } TEST_F(CelProtoWrapperTest, WrapFailureWrongType) { auto cel_value = CelValue::CreateNull(); std::vector<const google::protobuf::Message*> wrong_types = { &BoolValue::default_instance(), &BytesValue::default_instance(), &DoubleValue::default_instance(), &Duration::default_instance(), &FloatValue::default_instance(), &Int32Value::default_instance(), &Int64Value::default_instance(), &ListValue::default_instance(), &StringValue::default_instance(), &Struct::default_instance(), &Timestamp::default_instance(), &UInt32Value::default_instance(), &UInt64Value::default_instance(), }; for (const auto* wrong_type : wrong_types) { ExpectNotWrapped(cel_value, *wrong_type); } } TEST_F(CelProtoWrapperTest, WrapFailureErrorToAny) { auto cel_value = CreateNoSuchFieldError(arena(), "error_field"); ExpectNotWrapped(cel_value, Any::default_instance()); } TEST_F(CelProtoWrapperTest, DebugString) { google::protobuf::Empty e; EXPECT_THAT(CelProtoWrapper::CreateMessage(&e, arena()).DebugString(), testing::StartsWith("Message: ")); ListValue list_value; list_value.add_values()->set_bool_value(true); list_value.add_values()->set_number_value(1.0); list_value.add_values()->set_string_value("test"); CelValue value = CelProtoWrapper::CreateMessage(&list_value, arena()); EXPECT_EQ(value.DebugString(), "CelList: [bool: 1, double: 1.000000, string: test]"); Struct value_struct; auto& value1 = (*value_struct.mutable_fields())["a"]; value1.set_bool_value(true); auto& value2 = (*value_struct.mutable_fields())["b"]; value2.set_number_value(1.0); auto& value3 = (*value_struct.mutable_fields())["c"]; value3.set_string_value("test"); value = CelProtoWrapper::CreateMessage(&value_struct, arena()); EXPECT_THAT( value.DebugString(), testing::AllOf(testing::StartsWith("CelMap: {"), testing::HasSubstr("<string: a>: <bool: 1>"), testing::HasSubstr("<string: b>: <double: 1.0"), testing::HasSubstr("<string: c>: <string: test>"))); } } }
113
cpp
google/cel-cpp
legacy_type_provider
eval/public/structs/legacy_type_provider.cc
eval/public/structs/legacy_type_provider_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_TYPE_PROVIDER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_TYPE_PROVIDER_H_ #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/memory.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_factory.h" #include "eval/public/structs/legacy_any_packing.h" #include "eval/public/structs/legacy_type_adapter.h" namespace google::api::expr::runtime { class LegacyTypeProvider : public cel::TypeReflector { public: virtual ~LegacyTypeProvider() = default; virtual absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const = 0; virtual absl::optional<const LegacyTypeInfoApis*> ProvideLegacyTypeInfo( ABSL_ATTRIBUTE_UNUSED absl::string_view name) const { return absl::nullopt; } virtual absl::optional<const LegacyAnyPackingApis*> ProvideLegacyAnyPackingApis( ABSL_ATTRIBUTE_UNUSED absl::string_view name) const { return absl::nullopt; } absl::StatusOr<absl::optional<cel::Unique<cel::StructValueBuilder>>> NewStructValueBuilder(cel::ValueFactory& value_factory, cel::StructTypeView type) const final; protected: absl::StatusOr<absl::optional<cel::Value>> DeserializeValueImpl( cel::ValueFactory& value_factory, absl::string_view type_url, const absl::Cord& value) const final; absl::StatusOr<absl::optional<cel::TypeView>> FindTypeImpl( cel::TypeFactory& type_factory, absl::string_view name, cel::Type& scratch) const final; absl::StatusOr<absl::optional<cel::StructTypeFieldView>> FindStructTypeFieldByNameImpl(cel::TypeFactory& type_factory, absl::string_view type, absl::string_view name, cel::StructTypeField& scratch) const final; }; } #endif #include "eval/public/structs/legacy_type_provider.h" #include <cstdint> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/optional.h" #include "common/any.h" #include "common/legacy_value.h" #include "common/memory.h" #include "common/type.h" #include "common/value.h" #include "common/value_factory.h" #include "eval/public/message_wrapper.h" #include "eval/public/structs/legacy_type_adapter.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using google::api::expr::runtime::LegacyTypeAdapter; using google::api::expr::runtime::LegacyTypeInfoApis; using google::api::expr::runtime::MessageWrapper; class LegacyStructValueBuilder final : public cel::StructValueBuilder { public: LegacyStructValueBuilder(cel::MemoryManagerRef memory_manager, LegacyTypeAdapter adapter, MessageWrapper::Builder builder) : memory_manager_(memory_manager), adapter_(adapter), builder_(std::move(builder)) {} absl::Status SetFieldByName(absl::string_view name, cel::Value value) override { CEL_ASSIGN_OR_RETURN( auto legacy_value, LegacyValue(cel::extensions::ProtoMemoryManagerArena(memory_manager_), value)); return adapter_.mutation_apis()->SetField(name, legacy_value, memory_manager_, builder_); } absl::Status SetFieldByNumber(int64_t number, cel::Value value) override { CEL_ASSIGN_OR_RETURN( auto legacy_value, LegacyValue(cel::extensions::ProtoMemoryManagerArena(memory_manager_), value)); return adapter_.mutation_apis()->SetFieldByNumber( number, legacy_value, memory_manager_, builder_); } absl::StatusOr<cel::StructValue> Build() && override { CEL_ASSIGN_OR_RETURN(auto message, adapter_.mutation_apis()->AdaptFromWellKnownType( memory_manager_, std::move(builder_))); if (!message.IsMessage()) { return absl::FailedPreconditionError("expected MessageWrapper"); } auto message_wrapper = message.MessageWrapperOrDie(); return cel::common_internal::LegacyStructValue{ reinterpret_cast<uintptr_t>(message_wrapper.message_ptr()) | (message_wrapper.HasFullProto() ? cel::base_internal::kMessageWrapperTagMessageValue : uintptr_t{0}), reinterpret_cast<uintptr_t>(message_wrapper.legacy_type_info())}; } private: cel::MemoryManagerRef memory_manager_; LegacyTypeAdapter adapter_; MessageWrapper::Builder builder_; }; } absl::StatusOr<absl::optional<cel::Unique<cel::StructValueBuilder>>> LegacyTypeProvider::NewStructValueBuilder(cel::ValueFactory& value_factory, cel::StructTypeView type) const { if (auto type_adapter = ProvideLegacyType(type.name()); type_adapter.has_value()) { const auto* mutation_apis = type_adapter->mutation_apis(); if (mutation_apis == nullptr) { return absl::FailedPreconditionError(absl::StrCat( "LegacyTypeMutationApis missing for type: ", type.name())); } CEL_ASSIGN_OR_RETURN(auto builder, mutation_apis->NewInstance( value_factory.GetMemoryManager())); return value_factory.GetMemoryManager() .MakeUnique<LegacyStructValueBuilder>(value_factory.GetMemoryManager(), *type_adapter, std::move(builder)); } return absl::nullopt; } absl::StatusOr<absl::optional<cel::Value>> LegacyTypeProvider::DeserializeValueImpl(cel::ValueFactory& value_factory, absl::string_view type_url, const absl::Cord& value) const { auto type_name = absl::StripPrefix(type_url, cel::kTypeGoogleApisComPrefix); if (auto type_info = ProvideLegacyTypeInfo(type_name); type_info.has_value()) { if (auto type_adapter = ProvideLegacyType(type_name); type_adapter.has_value()) { const auto* mutation_apis = type_adapter->mutation_apis(); if (mutation_apis == nullptr) { return absl::FailedPreconditionError(absl::StrCat( "LegacyTypeMutationApis missing for type: ", type_name)); } CEL_ASSIGN_OR_RETURN(auto builder, mutation_apis->NewInstance( value_factory.GetMemoryManager())); if (!builder.message_ptr()->ParsePartialFromCord(value)) { return absl::UnknownError("failed to parse protocol buffer message"); } CEL_ASSIGN_OR_RETURN( auto legacy_value, mutation_apis->AdaptFromWellKnownType( value_factory.GetMemoryManager(), std::move(builder))); cel::Value scratch; CEL_ASSIGN_OR_RETURN(auto modern_value, ModernValue(cel::extensions::ProtoMemoryManagerArena( value_factory.GetMemoryManager()), legacy_value, scratch)); return cel::Value{modern_value}; } } return absl::nullopt; } absl::StatusOr<absl::optional<cel::TypeView>> LegacyTypeProvider::FindTypeImpl( cel::TypeFactory& type_factory, absl::string_view name, cel::Type& scratch) const { if (auto type_info = ProvideLegacyTypeInfo(name); type_info.has_value()) { scratch = type_factory.CreateStructType(name); return scratch; } return absl::nullopt; } absl::StatusOr<absl::optional<cel::StructTypeFieldView>> LegacyTypeProvider::FindStructTypeFieldByNameImpl( cel::TypeFactory& type_factory, absl::string_view type, absl::string_view name, cel::StructTypeField& scratch) const { if (auto type_info = ProvideLegacyTypeInfo(type); type_info.has_value()) { if (auto field_desc = (*type_info)->FindFieldByName(name); field_desc.has_value()) { return cel::StructTypeFieldView{field_desc->name, cel::DynTypeView{}, field_desc->number}; } else { const auto* mutation_apis = (*type_info)->GetMutationApis(MessageWrapper()); if (mutation_apis == nullptr || !mutation_apis->DefinesField(name)) { return absl::nullopt; } return cel::StructTypeFieldView{name, cel::DynTypeView{}, 0}; } } return absl::nullopt; } }
#include "eval/public/structs/legacy_type_provider.h" #include <optional> #include <string> #include "eval/public/structs/legacy_any_packing.h" #include "eval/public/structs/legacy_type_info_apis.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { class LegacyTypeProviderTestEmpty : public LegacyTypeProvider { public: absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const override { return absl::nullopt; } }; class LegacyTypeInfoApisEmpty : public LegacyTypeInfoApis { public: std::string DebugString( const MessageWrapper& wrapped_message) const override { return ""; } const std::string& GetTypename( const MessageWrapper& wrapped_message) const override { return test_string_; } const LegacyTypeAccessApis* GetAccessApis( const MessageWrapper& wrapped_message) const override { return nullptr; } private: const std::string test_string_ = "test"; }; class LegacyAnyPackingApisEmpty : public LegacyAnyPackingApis { public: absl::StatusOr<google::protobuf::MessageLite*> Unpack( const google::protobuf::Any& any_message, google::protobuf::Arena* arena) const override { return absl::UnimplementedError("Unimplemented Unpack"); } absl::Status Pack(const google::protobuf::MessageLite* message, google::protobuf::Any& any_message) const override { return absl::UnimplementedError("Unimplemented Pack"); } }; class LegacyTypeProviderTestImpl : public LegacyTypeProvider { public: explicit LegacyTypeProviderTestImpl( const LegacyTypeInfoApis* test_type_info, const LegacyAnyPackingApis* test_any_packing_apis) : test_type_info_(test_type_info), test_any_packing_apis_(test_any_packing_apis) {} absl::optional<LegacyTypeAdapter> ProvideLegacyType( absl::string_view name) const override { if (name == "test") { return LegacyTypeAdapter(nullptr, nullptr); } return absl::nullopt; } absl::optional<const LegacyTypeInfoApis*> ProvideLegacyTypeInfo( absl::string_view name) const override { if (name == "test") { return test_type_info_; } return absl::nullopt; } absl::optional<const LegacyAnyPackingApis*> ProvideLegacyAnyPackingApis( absl::string_view name) const override { if (name == "test") { return test_any_packing_apis_; } return absl::nullopt; } private: const LegacyTypeInfoApis* test_type_info_ = nullptr; const LegacyAnyPackingApis* test_any_packing_apis_ = nullptr; }; TEST(LegacyTypeProviderTest, EmptyTypeProviderHasProvideTypeInfo) { LegacyTypeProviderTestEmpty provider; EXPECT_EQ(provider.ProvideLegacyType("test"), absl::nullopt); EXPECT_EQ(provider.ProvideLegacyTypeInfo("test"), absl::nullopt); EXPECT_EQ(provider.ProvideLegacyAnyPackingApis("test"), absl::nullopt); } TEST(LegacyTypeProviderTest, NonEmptyTypeProviderProvidesSomeTypes) { LegacyTypeInfoApisEmpty test_type_info; LegacyAnyPackingApisEmpty test_any_packing_apis; LegacyTypeProviderTestImpl provider(&test_type_info, &test_any_packing_apis); EXPECT_TRUE(provider.ProvideLegacyType("test").has_value()); EXPECT_TRUE(provider.ProvideLegacyTypeInfo("test").has_value()); EXPECT_TRUE(provider.ProvideLegacyAnyPackingApis("test").has_value()); EXPECT_EQ(provider.ProvideLegacyType("other"), absl::nullopt); EXPECT_EQ(provider.ProvideLegacyTypeInfo("other"), absl::nullopt); EXPECT_EQ(provider.ProvideLegacyAnyPackingApis("other"), absl::nullopt); } } }
114
cpp
google/cel-cpp
field_access
eval/public/containers/field_access.cc
eval/public/containers/field_access_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_FIELD_ACCESS_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_FIELD_ACCESS_H_ #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" namespace google::api::expr::runtime { absl::Status CreateValueFromSingleField(const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, google::protobuf::Arena* arena, CelValue* result); absl::Status CreateValueFromSingleField(const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, ProtoWrapperTypeOptions options, google::protobuf::Arena* arena, CelValue* result); absl::Status CreateValueFromRepeatedField(const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, google::protobuf::Arena* arena, int index, CelValue* result); absl::Status CreateValueFromMapValue(const google::protobuf::Message* msg, const google::protobuf::FieldDescriptor* desc, const google::protobuf::MapValueConstRef* value_ref, google::protobuf::Arena* arena, CelValue* result); absl::Status SetValueToSingleField(const CelValue& value, const google::protobuf::FieldDescriptor* desc, google::protobuf::Message* msg, google::protobuf::Arena* arena); absl::Status AddValueToRepeatedField(const CelValue& value, const google::protobuf::FieldDescriptor* desc, google::protobuf::Message* msg, google::protobuf::Arena* arena); } #endif #include "eval/public/containers/field_access.h" #include "google/protobuf/arena.h" #include "google/protobuf/map_field.h" #include "absl/status/status.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/structs/field_access_impl.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { using ::google::protobuf::Arena; using ::google::protobuf::FieldDescriptor; using ::google::protobuf::MapValueConstRef; using ::google::protobuf::Message; absl::Status CreateValueFromSingleField(const google::protobuf::Message* msg, const FieldDescriptor* desc, google::protobuf::Arena* arena, CelValue* result) { return CreateValueFromSingleField( msg, desc, ProtoWrapperTypeOptions::kUnsetProtoDefault, arena, result); } absl::Status CreateValueFromSingleField(const google::protobuf::Message* msg, const FieldDescriptor* desc, ProtoWrapperTypeOptions options, google::protobuf::Arena* arena, CelValue* result) { CEL_ASSIGN_OR_RETURN( *result, internal::CreateValueFromSingleField( msg, desc, options, &CelProtoWrapper::InternalWrapMessage, arena)); return absl::OkStatus(); } absl::Status CreateValueFromRepeatedField(const google::protobuf::Message* msg, const FieldDescriptor* desc, google::protobuf::Arena* arena, int index, CelValue* result) { CEL_ASSIGN_OR_RETURN( *result, internal::CreateValueFromRepeatedField( msg, desc, index, &CelProtoWrapper::InternalWrapMessage, arena)); return absl::OkStatus(); } absl::Status CreateValueFromMapValue(const google::protobuf::Message* msg, const FieldDescriptor* desc, const MapValueConstRef* value_ref, google::protobuf::Arena* arena, CelValue* result) { CEL_ASSIGN_OR_RETURN( *result, internal::CreateValueFromMapValue( msg, desc, value_ref, &CelProtoWrapper::InternalWrapMessage, arena)); return absl::OkStatus(); } absl::Status SetValueToSingleField(const CelValue& value, const FieldDescriptor* desc, Message* msg, Arena* arena) { return internal::SetValueToSingleField(value, desc, msg, arena); } absl::Status AddValueToRepeatedField(const CelValue& value, const FieldDescriptor* desc, Message* msg, Arena* arena) { return internal::AddValueToRepeatedField(value, desc, msg, arena); } }
#include "eval/public/containers/field_access.h" #include <array> #include <limits> #include "google/protobuf/arena.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "eval/public/cel_value.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" #include "internal/time.h" #include "proto/test/v1/proto3/test_all_types.pb.h" namespace google::api::expr::runtime { namespace { using ::cel::internal::MaxDuration; using ::cel::internal::MaxTimestamp; using ::google::api::expr::test::v1::proto3::TestAllTypes; using ::google::protobuf::Arena; using ::google::protobuf::FieldDescriptor; using testing::HasSubstr; using cel::internal::StatusIs; TEST(FieldAccessTest, SetDuration) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_duration"); auto status = SetValueToSingleField(CelValue::CreateDuration(MaxDuration()), field, &msg, &arena); EXPECT_TRUE(status.ok()); } TEST(FieldAccessTest, SetDurationBadDuration) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_duration"); auto status = SetValueToSingleField( CelValue::CreateDuration(MaxDuration() + absl::Seconds(1)), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetDurationBadInputType) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_duration"); auto status = SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetTimestamp) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_timestamp"); auto status = SetValueToSingleField(CelValue::CreateTimestamp(MaxTimestamp()), field, &msg, &arena); EXPECT_TRUE(status.ok()); } TEST(FieldAccessTest, SetTimestampBadTime) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_timestamp"); auto status = SetValueToSingleField( CelValue::CreateTimestamp(MaxTimestamp() + absl::Seconds(1)), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetTimestampBadInputType) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_timestamp"); auto status = SetValueToSingleField(CelValue::CreateInt64(1), field, &msg, &arena); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); } TEST(FieldAccessTest, SetInt32Overflow) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_int32"); EXPECT_THAT( SetValueToSingleField( CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L), field, &msg, &arena), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Could not assign"))); } TEST(FieldAccessTest, SetUint32Overflow) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("single_uint32"); EXPECT_THAT( SetValueToSingleField( CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1L), field, &msg, &arena), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Could not assign"))); } TEST(FieldAccessTest, SetMessage) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("standalone_message"); TestAllTypes::NestedMessage* nested_msg = google::protobuf::Arena::Create<TestAllTypes::NestedMessage>(&arena); nested_msg->set_bb(1); auto status = SetValueToSingleField( CelProtoWrapper::CreateMessage(nested_msg, &arena), field, &msg, &arena); EXPECT_TRUE(status.ok()); } TEST(FieldAccessTest, SetMessageWithNul) { Arena arena; TestAllTypes msg; const FieldDescriptor* field = TestAllTypes::descriptor()->FindFieldByName("standalone_message"); auto status = SetValueToSingleField(CelValue::CreateNull(), field, &msg, &arena); EXPECT_TRUE(status.ok()); } constexpr std::array<const char*, 9> kWrapperFieldNames = { "single_bool_wrapper", "single_int64_wrapper", "single_int32_wrapper", "single_uint64_wrapper", "single_uint32_wrapper", "single_double_wrapper", "single_float_wrapper", "single_string_wrapper", "single_bytes_wrapper"}; TEST(CreateValueFromFieldTest, UnsetWrapperTypesNullIfEnabled) { CelValue result; TestAllTypes test_message; google::protobuf::Arena arena; for (const auto& field : kWrapperFieldNames) { ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName(field), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)) << field; ASSERT_TRUE(result.IsNull()) << field << ": " << result.DebugString(); } } TEST(CreateValueFromFieldTest, UnsetWrapperTypesDefaultValueIfDisabled) { CelValue result; TestAllTypes test_message; google::protobuf::Arena arena; for (const auto& field : kWrapperFieldNames) { ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName(field), ProtoWrapperTypeOptions::kUnsetProtoDefault, &arena, &result)) << field; ASSERT_FALSE(result.IsNull()) << field << ": " << result.DebugString(); } } TEST(CreateValueFromFieldTest, SetWrapperTypesDefaultValue) { CelValue result; TestAllTypes test_message; google::protobuf::Arena arena; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( single_bool_wrapper {} single_int64_wrapper {} single_int32_wrapper {} single_uint64_wrapper {} single_uint32_wrapper {} single_double_wrapper {} single_float_wrapper {} single_string_wrapper {} single_bytes_wrapper {} )pb", &test_message)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_bool_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelBool(false)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_int64_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelInt64(0)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_int32_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelInt64(0)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_uint64_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelUint64(0)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_uint32_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelUint64(0)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_double_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelDouble(0.0f)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_float_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelDouble(0.0f)); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_string_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelString("")); ASSERT_OK(CreateValueFromSingleField( &test_message, TestAllTypes::GetDescriptor()->FindFieldByName("single_bytes_wrapper"), ProtoWrapperTypeOptions::kUnsetNull, &arena, &result)); EXPECT_THAT(result, test::IsCelBytes("")); } } }
115
cpp
google/cel-cpp
container_backed_map_impl
eval/public/containers/container_backed_map_impl.cc
eval/public/containers/container_backed_map_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_CONTAINER_BACKED_MAP_IMPL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_CONTAINER_BACKED_MAP_IMPL_H_ #include <memory> #include <utility> #include "absl/container/node_hash_map.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "eval/public/cel_value.h" namespace google::api::expr::runtime { class CelMapBuilder : public CelMap { public: CelMapBuilder() {} absl::Status Add(CelValue key, CelValue value); int size() const override { return values_map_.size(); } absl::optional<CelValue> operator[](CelValue cel_key) const override; absl::StatusOr<bool> Has(const CelValue& cel_key) const override { return values_map_.contains(cel_key); } absl::StatusOr<const CelList*> ListKeys() const override { return &key_list_; } private: class KeyList : public CelList { public: KeyList() {} int size() const override { return keys_.size(); } CelValue operator[](int index) const override { return keys_[index]; } void Add(const CelValue& key) { keys_.push_back(key); } private: std::vector<CelValue> keys_; }; struct Hasher { size_t operator()(const CelValue& key) const; }; struct Equal { bool operator()(const CelValue& key1, const CelValue& key2) const; }; absl::node_hash_map<CelValue, CelValue, Hasher, Equal> values_map_; KeyList key_list_; }; absl::StatusOr<std::unique_ptr<CelMap>> CreateContainerBackedMap( absl::Span<const std::pair<CelValue, CelValue>> key_values); } #endif #include "eval/public/containers/container_backed_map_impl.h" #include <memory> #include <utility> #include "absl/container/node_hash_map.h" #include "absl/hash/hash.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "eval/public/cel_value.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { class HasherOp { public: template <class T> size_t operator()(const T& arg) { return std::hash<T>()(arg); } size_t operator()(const absl::Time arg) { return absl::Hash<absl::Time>()(arg); } size_t operator()(const absl::Duration arg) { return absl::Hash<absl::Duration>()(arg); } size_t operator()(const CelValue::StringHolder& arg) { return absl::Hash<absl::string_view>()(arg.value()); } size_t operator()(const CelValue::BytesHolder& arg) { return absl::Hash<absl::string_view>()(arg.value()); } size_t operator()(const CelValue::CelTypeHolder& arg) { return absl::Hash<absl::string_view>()(arg.value()); } size_t operator()(const std::nullptr_t&) { return 0; } }; template <class T> class EqualOp { public: explicit EqualOp(const T& arg) : arg_(arg) {} template <class U> bool operator()(const U&) const { return false; } bool operator()(const T& other) const { return other == arg_; } private: const T& arg_; }; class CelValueEq { public: explicit CelValueEq(const CelValue& other) : other_(other) {} template <class Type> bool operator()(const Type& arg) { return other_.template Visit<bool>(EqualOp<Type>(arg)); } private: const CelValue& other_; }; } absl::optional<CelValue> CelMapBuilder::operator[](CelValue cel_key) const { auto item = values_map_.find(cel_key); if (item == values_map_.end()) { return absl::nullopt; } return item->second; } absl::Status CelMapBuilder::Add(CelValue key, CelValue value) { auto [unused, inserted] = values_map_.emplace(key, value); if (!inserted) { return absl::InvalidArgumentError("duplicate map keys"); } key_list_.Add(key); return absl::OkStatus(); } size_t CelMapBuilder::Hasher::operator()(const CelValue& key) const { return key.template Visit<size_t>(HasherOp()); } bool CelMapBuilder::Equal::operator()(const CelValue& key1, const CelValue& key2) const { if (key1.type() != key2.type()) { return false; } return key1.template Visit<bool>(CelValueEq(key2)); } absl::StatusOr<std::unique_ptr<CelMap>> CreateContainerBackedMap( absl::Span<const std::pair<CelValue, CelValue>> key_values) { auto map = std::make_unique<CelMapBuilder>(); for (const auto& key_value : key_values) { CEL_RETURN_IF_ERROR(map->Add(key_value.first, key_value.second)); } return map; } } } } }
#include "eval/public/containers/container_backed_map_impl.h" #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "eval/public/cel_value.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using testing::Eq; using testing::IsNull; using testing::Not; using cel::internal::StatusIs; TEST(ContainerBackedMapImplTest, TestMapInt64) { std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(2), CelValue::CreateInt64(3)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateUint64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateInt64(3)]; ASSERT_FALSE(lookup3); } TEST(ContainerBackedMapImplTest, TestMapUint64) { std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateUint64(1), CelValue::CreateInt64(2)}, {CelValue::CreateUint64(2), CelValue::CreateInt64(3)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateUint64(1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateUint64(3)]; ASSERT_FALSE(lookup3); } TEST(ContainerBackedMapImplTest, TestMapString) { const std::string kKey1 = "1"; const std::string kKey2 = "2"; const std::string kKey3 = "3"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)}, {CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateString(&kKey1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateString(&kKey3)]; ASSERT_FALSE(lookup3); } TEST(CelMapBuilder, TestMapString) { const std::string kKey1 = "1"; const std::string kKey2 = "2"; const std::string kKey3 = "3"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)}, {CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}}; CelMapBuilder builder; ASSERT_OK( builder.Add(CelValue::CreateString(&kKey1), CelValue::CreateInt64(2))); ASSERT_OK( builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3))); CelMap* cel_map = &builder; ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateString(&kKey1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateString(&kKey3)]; ASSERT_FALSE(lookup3); } TEST(CelMapBuilder, RepeatKeysFail) { const std::string kKey1 = "1"; const std::string kKey2 = "2"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)}, {CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}}; CelMapBuilder builder; ASSERT_OK( builder.Add(CelValue::CreateString(&kKey1), CelValue::CreateInt64(2))); ASSERT_OK( builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3))); EXPECT_THAT( builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)), StatusIs(absl::StatusCode::kInvalidArgument, "duplicate map keys")); } } }
116
cpp
google/cel-cpp
internal_field_backed_map_impl
eval/public/containers/internal_field_backed_map_impl.cc
eval/public/containers/internal_field_backed_map_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_INTERNAL_FIELD_BACKED_MAP_IMPL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_INTERNAL_FIELD_BACKED_MAP_IMPL_H_ #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "absl/status/statusor.h" #include "eval/public/cel_value.h" #include "eval/public/structs/protobuf_value_factory.h" namespace google::api::expr::runtime::internal { class FieldBackedMapImpl : public CelMap { public: FieldBackedMapImpl(const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* descriptor, ProtobufValueFactory factory, google::protobuf::Arena* arena); int size() const override; absl::optional<CelValue> operator[](CelValue key) const override; absl::StatusOr<bool> Has(const CelValue& key) const override; absl::StatusOr<const CelList*> ListKeys() const override; protected: absl::StatusOr<bool> LookupMapValue( const CelValue& key, google::protobuf::MapValueConstRef* value_ref) const; absl::StatusOr<bool> LegacyHasMapValue(const CelValue& key) const; absl::optional<CelValue> LegacyLookupMapValue(const CelValue& key) const; private: const google::protobuf::Message* message_; const google::protobuf::FieldDescriptor* descriptor_; const google::protobuf::FieldDescriptor* key_desc_; const google::protobuf::FieldDescriptor* value_desc_; const google::protobuf::Reflection* reflection_; ProtobufValueFactory factory_; google::protobuf::Arena* arena_; std::unique_ptr<CelList> key_list_; }; } #endif #include "eval/public/containers/internal_field_backed_map_impl.h" #include <limits> #include <memory> #include <utility> #include "google/protobuf/descriptor.h" #include "google/protobuf/map_field.h" #include "google/protobuf/message.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "eval/public/cel_value.h" #include "eval/public/structs/field_access_impl.h" #include "eval/public/structs/protobuf_value_factory.h" #include "extensions/protobuf/internal/map_reflection.h" namespace google::api::expr::runtime::internal { namespace { using google::protobuf::Descriptor; using google::protobuf::FieldDescriptor; using google::protobuf::MapValueConstRef; using google::protobuf::Message; constexpr int kKeyTag = 1; constexpr int kValueTag = 2; class KeyList : public CelList { public: KeyList(const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* descriptor, const ProtobufValueFactory& factory, google::protobuf::Arena* arena) : message_(message), descriptor_(descriptor), reflection_(message_->GetReflection()), factory_(factory), arena_(arena) {} int size() const override { return reflection_->FieldSize(*message_, descriptor_); } CelValue operator[](int index) const override { const Message* entry = &reflection_->GetRepeatedMessage(*message_, descriptor_, index); if (entry == nullptr) { return CelValue::CreateNull(); } const Descriptor* entry_descriptor = entry->GetDescriptor(); const FieldDescriptor* key_desc = entry_descriptor->FindFieldByNumber(kKeyTag); absl::StatusOr<CelValue> key_value = CreateValueFromSingleField( entry, key_desc, ProtoWrapperTypeOptions::kUnsetProtoDefault, factory_, arena_); if (!key_value.ok()) { return CreateErrorValue(arena_, key_value.status()); } return *key_value; } private: const google::protobuf::Message* message_; const google::protobuf::FieldDescriptor* descriptor_; const google::protobuf::Reflection* reflection_; const ProtobufValueFactory& factory_; google::protobuf::Arena* arena_; }; bool MatchesMapKeyType(const FieldDescriptor* key_desc, const CelValue& key) { switch (key_desc->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return key.IsBool(); case google::protobuf::FieldDescriptor::CPPTYPE_INT32: case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return key.IsInt64(); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return key.IsUint64(); case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return key.IsString(); default: return false; } } absl::Status InvalidMapKeyType(absl::string_view key_type) { return absl::InvalidArgumentError( absl::StrCat("Invalid map key type: '", key_type, "'")); } } FieldBackedMapImpl::FieldBackedMapImpl( const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* descriptor, ProtobufValueFactory factory, google::protobuf::Arena* arena) : message_(message), descriptor_(descriptor), key_desc_(descriptor_->message_type()->FindFieldByNumber(kKeyTag)), value_desc_(descriptor_->message_type()->FindFieldByNumber(kValueTag)), reflection_(message_->GetReflection()), factory_(std::move(factory)), arena_(arena), key_list_( std::make_unique<KeyList>(message, descriptor, factory_, arena)) {} int FieldBackedMapImpl::size() const { return reflection_->FieldSize(*message_, descriptor_); } absl::StatusOr<const CelList*> FieldBackedMapImpl::ListKeys() const { return key_list_.get(); } absl::StatusOr<bool> FieldBackedMapImpl::Has(const CelValue& key) const { MapValueConstRef value_ref; return LookupMapValue(key, &value_ref); } absl::optional<CelValue> FieldBackedMapImpl::operator[](CelValue key) const { MapValueConstRef value_ref; auto lookup_result = LookupMapValue(key, &value_ref); if (!lookup_result.ok()) { return CreateErrorValue(arena_, lookup_result.status()); } if (!*lookup_result) { return absl::nullopt; } absl::StatusOr<CelValue> result = CreateValueFromMapValue( message_, value_desc_, &value_ref, factory_, arena_); if (!result.ok()) { return CreateErrorValue(arena_, result.status()); } return *result; } absl::StatusOr<bool> FieldBackedMapImpl::LookupMapValue( const CelValue& key, MapValueConstRef* value_ref) const { if (!MatchesMapKeyType(key_desc_, key)) { return InvalidMapKeyType(key_desc_->cpp_type_name()); } google::protobuf::MapKey proto_key; switch (key_desc_->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { bool key_value; key.GetValue(&key_value); proto_key.SetBoolValue(key_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { int64_t key_value; key.GetValue(&key_value); if (key_value > std::numeric_limits<int32_t>::max() || key_value < std::numeric_limits<int32_t>::lowest()) { return absl::OutOfRangeError("integer overflow"); } proto_key.SetInt32Value(key_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { int64_t key_value; key.GetValue(&key_value); proto_key.SetInt64Value(key_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { CelValue::StringHolder key_value; key.GetValue(&key_value); auto str = key_value.value(); proto_key.SetStringValue(std::string(str.begin(), str.end())); } break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { uint64_t key_value; key.GetValue(&key_value); if (key_value > std::numeric_limits<uint32_t>::max()) { return absl::OutOfRangeError("unsigned integer overlow"); } proto_key.SetUInt32Value(key_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { uint64_t key_value; key.GetValue(&key_value); proto_key.SetUInt64Value(key_value); } break; default: return InvalidMapKeyType(key_desc_->cpp_type_name()); } return cel::extensions::protobuf_internal::LookupMapValue( *reflection_, *message_, *descriptor_, proto_key, value_ref); } absl::StatusOr<bool> FieldBackedMapImpl::LegacyHasMapValue( const CelValue& key) const { auto lookup_result = LegacyLookupMapValue(key); if (!lookup_result.has_value()) { return false; } auto result = *lookup_result; if (result.IsError()) { return *(result.ErrorOrDie()); } return true; } absl::optional<CelValue> FieldBackedMapImpl::LegacyLookupMapValue( const CelValue& key) const { if (!MatchesMapKeyType(key_desc_, key)) { return CreateErrorValue(arena_, InvalidMapKeyType(key_desc_->cpp_type_name())); } int map_size = size(); for (int i = 0; i < map_size; i++) { const Message* entry = &reflection_->GetRepeatedMessage(*message_, descriptor_, i); if (entry == nullptr) continue; absl::StatusOr<CelValue> key_value = CreateValueFromSingleField( entry, key_desc_, ProtoWrapperTypeOptions::kUnsetProtoDefault, factory_, arena_); if (!key_value.ok()) { return CreateErrorValue(arena_, key_value.status()); } bool match = false; switch (key_desc_->cpp_type()) { case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: match = key.BoolOrDie() == key_value->BoolOrDie(); break; case google::protobuf::FieldDescriptor::CPPTYPE_INT32: case google::protobuf::FieldDescriptor::CPPTYPE_INT64: match = key.Int64OrDie() == key_value->Int64OrDie(); break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: match = key.Uint64OrDie() == key_value->Uint64OrDie(); break; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: match = key.StringOrDie() == key_value->StringOrDie(); break; default: break; } if (match) { absl::StatusOr<CelValue> value_cel_value = CreateValueFromSingleField( entry, value_desc_, ProtoWrapperTypeOptions::kUnsetProtoDefault, factory_, arena_); if (!value_cel_value.ok()) { return CreateErrorValue(arena_, value_cel_value.status()); } return *value_cel_value; } } return {}; } }
#include "eval/public/containers/internal_field_backed_map_impl.h" #include <array> #include <limits> #include <memory> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" namespace google::api::expr::runtime::internal { namespace { using testing::Eq; using testing::HasSubstr; using testing::UnorderedPointwise; using cel::internal::StatusIs; class FieldBackedMapTestImpl : public FieldBackedMapImpl { public: FieldBackedMapTestImpl(const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* descriptor, google::protobuf::Arena* arena) : FieldBackedMapImpl(message, descriptor, &CelProtoWrapper::InternalWrapMessage, arena) {} using FieldBackedMapImpl::LegacyHasMapValue; using FieldBackedMapImpl::LegacyLookupMapValue; }; std::unique_ptr<FieldBackedMapTestImpl> CreateMap(const TestMessage* message, const std::string& field, google::protobuf::Arena* arena) { const google::protobuf::FieldDescriptor* field_desc = message->GetDescriptor()->FindFieldByName(field); return std::make_unique<FieldBackedMapTestImpl>(message, field_desc, arena); } TEST(FieldBackedMapImplTest, BadKeyTypeTest) { TestMessage message; google::protobuf::Arena arena; constexpr std::array<absl::string_view, 6> map_types = { "int64_int32_map", "uint64_int32_map", "string_int32_map", "bool_int32_map", "int32_int32_map", "uint32_uint32_map", }; for (auto map_type : map_types) { auto cel_map = CreateMap(&message, std::string(map_type), &arena); auto result = cel_map->Has(CelValue::CreateNull()); EXPECT_FALSE(result.ok()); EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kInvalidArgument)); result = cel_map->LegacyHasMapValue(CelValue::CreateNull()); EXPECT_FALSE(result.ok()); EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kInvalidArgument)); auto lookup = (*cel_map)[CelValue::CreateNull()]; EXPECT_TRUE(lookup.has_value()); EXPECT_TRUE(lookup->IsError()); EXPECT_THAT(lookup->ErrorOrDie()->code(), Eq(absl::StatusCode::kInvalidArgument)); lookup = cel_map->LegacyLookupMapValue(CelValue::CreateNull()); EXPECT_TRUE(lookup.has_value()); EXPECT_TRUE(lookup->IsError()); EXPECT_THAT(lookup->ErrorOrDie()->code(), Eq(absl::StatusCode::kInvalidArgument)); } } TEST(FieldBackedMapImplTest, Int32KeyTest) { TestMessage message; auto field_map = message.mutable_int32_int32_map(); (*field_map)[0] = 1; (*field_map)[1] = 2; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "int32_int32_map", &arena); EXPECT_EQ((*cel_map)[CelValue::CreateInt64(0)]->Int64OrDie(), 1); EXPECT_EQ((*cel_map)[CelValue::CreateInt64(1)]->Int64OrDie(), 2); EXPECT_TRUE(cel_map->Has(CelValue::CreateInt64(1)).value_or(false)); EXPECT_TRUE( cel_map->LegacyHasMapValue(CelValue::CreateInt64(1)).value_or(false)); EXPECT_FALSE((*cel_map)[CelValue::CreateInt64(3)].has_value()); EXPECT_FALSE(cel_map->Has(CelValue::CreateInt64(3)).value_or(true)); EXPECT_FALSE( cel_map->LegacyHasMapValue(CelValue::CreateInt64(3)).value_or(true)); } TEST(FieldBackedMapImplTest, Int32KeyOutOfRangeTest) { TestMessage message; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "int32_int32_map", &arena); auto result = cel_map->Has( CelValue::CreateInt64(std::numeric_limits<int32_t>::max() + 1L)); EXPECT_THAT(result.status(), StatusIs(absl::StatusCode::kOutOfRange, HasSubstr("overflow"))); result = cel_map->Has( CelValue::CreateInt64(std::numeric_limits<int32_t>::lowest() - 1L)); EXPECT_FALSE(result.ok()); EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kOutOfRange)); } TEST(FieldBackedMapImplTest, Int64KeyTest) { TestMessage message; auto field_map = message.mutable_int64_int32_map(); (*field_map)[0] = 1; (*field_map)[1] = 2; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "int64_int32_map", &arena); EXPECT_EQ((*cel_map)[CelValue::CreateInt64(0)]->Int64OrDie(), 1); EXPECT_EQ((*cel_map)[CelValue::CreateInt64(1)]->Int64OrDie(), 2); EXPECT_TRUE(cel_map->Has(CelValue::CreateInt64(1)).value_or(false)); EXPECT_EQ( cel_map->LegacyLookupMapValue(CelValue::CreateInt64(1))->Int64OrDie(), 2); EXPECT_TRUE( cel_map->LegacyHasMapValue(CelValue::CreateInt64(1)).value_or(false)); EXPECT_EQ((*cel_map)[CelValue::CreateInt64(3)].has_value(), false); } TEST(FieldBackedMapImplTest, BoolKeyTest) { TestMessage message; auto field_map = message.mutable_bool_int32_map(); (*field_map)[false] = 1; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "bool_int32_map", &arena); EXPECT_EQ((*cel_map)[CelValue::CreateBool(false)]->Int64OrDie(), 1); EXPECT_TRUE(cel_map->Has(CelValue::CreateBool(false)).value_or(false)); EXPECT_TRUE( cel_map->LegacyHasMapValue(CelValue::CreateBool(false)).value_or(false)); EXPECT_EQ((*cel_map)[CelValue::CreateBool(true)].has_value(), false); (*field_map)[true] = 2; EXPECT_EQ((*cel_map)[CelValue::CreateBool(true)]->Int64OrDie(), 2); } TEST(FieldBackedMapImplTest, Uint32KeyTest) { TestMessage message; auto field_map = message.mutable_uint32_uint32_map(); (*field_map)[0] = 1u; (*field_map)[1] = 2u; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "uint32_uint32_map", &arena); EXPECT_EQ((*cel_map)[CelValue::CreateUint64(0)]->Uint64OrDie(), 1UL); EXPECT_EQ((*cel_map)[CelValue::CreateUint64(1)]->Uint64OrDie(), 2UL); EXPECT_TRUE(cel_map->Has(CelValue::CreateUint64(1)).value_or(false)); EXPECT_TRUE( cel_map->LegacyHasMapValue(CelValue::CreateUint64(1)).value_or(false)); EXPECT_EQ((*cel_map)[CelValue::CreateUint64(3)].has_value(), false); EXPECT_EQ(cel_map->Has(CelValue::CreateUint64(3)).value_or(true), false); } TEST(FieldBackedMapImplTest, Uint32KeyOutOfRangeTest) { TestMessage message; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "uint32_uint32_map", &arena); auto result = cel_map->Has( CelValue::CreateUint64(std::numeric_limits<uint32_t>::max() + 1UL)); EXPECT_FALSE(result.ok()); EXPECT_THAT(result.status().code(), Eq(absl::StatusCode::kOutOfRange)); } TEST(FieldBackedMapImplTest, Uint64KeyTest) { TestMessage message; auto field_map = message.mutable_uint64_int32_map(); (*field_map)[0] = 1; (*field_map)[1] = 2; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "uint64_int32_map", &arena); EXPECT_EQ((*cel_map)[CelValue::CreateUint64(0)]->Int64OrDie(), 1); EXPECT_EQ((*cel_map)[CelValue::CreateUint64(1)]->Int64OrDie(), 2); EXPECT_TRUE(cel_map->Has(CelValue::CreateUint64(1)).value_or(false)); EXPECT_TRUE( cel_map->LegacyHasMapValue(CelValue::CreateUint64(1)).value_or(false)); EXPECT_EQ((*cel_map)[CelValue::CreateUint64(3)].has_value(), false); } TEST(FieldBackedMapImplTest, StringKeyTest) { TestMessage message; auto field_map = message.mutable_string_int32_map(); (*field_map)["test0"] = 1; (*field_map)["test1"] = 2; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "string_int32_map", &arena); std::string test0 = "test0"; std::string test1 = "test1"; std::string test_notfound = "test_notfound"; EXPECT_EQ((*cel_map)[CelValue::CreateString(&test0)]->Int64OrDie(), 1); EXPECT_EQ((*cel_map)[CelValue::CreateString(&test1)]->Int64OrDie(), 2); EXPECT_TRUE(cel_map->Has(CelValue::CreateString(&test1)).value_or(false)); EXPECT_TRUE(cel_map->LegacyHasMapValue(CelValue::CreateString(&test1)) .value_or(false)); EXPECT_EQ((*cel_map)[CelValue::CreateString(&test_notfound)].has_value(), false); } TEST(FieldBackedMapImplTest, EmptySizeTest) { TestMessage message; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "string_int32_map", &arena); EXPECT_EQ(cel_map->size(), 0); } TEST(FieldBackedMapImplTest, RepeatedAddTest) { TestMessage message; auto field_map = message.mutable_string_int32_map(); (*field_map)["test0"] = 1; (*field_map)["test1"] = 2; (*field_map)["test0"] = 3; google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "string_int32_map", &arena); EXPECT_EQ(cel_map->size(), 2); } TEST(FieldBackedMapImplTest, KeyListTest) { TestMessage message; auto field_map = message.mutable_string_int32_map(); std::vector<std::string> keys; std::vector<std::string> keys1; for (int i = 0; i < 100; i++) { keys.push_back(absl::StrCat("test", i)); (*field_map)[keys.back()] = i; } google::protobuf::Arena arena; auto cel_map = CreateMap(&message, "string_int32_map", &arena); const CelList* key_list = cel_map->ListKeys().value(); EXPECT_EQ(key_list->size(), 100); for (int i = 0; i < key_list->size(); i++) { keys1.push_back(std::string((*key_list)[i].StringOrDie().value())); } EXPECT_THAT(keys, UnorderedPointwise(Eq(), keys1)); } } }
117
cpp
google/cel-cpp
internal_field_backed_list_impl
eval/public/containers/internal_field_backed_list_impl.cc
eval/public/containers/internal_field_backed_list_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_INTERNAL_FIELD_BACKED_LIST_IMPL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_INTERNAL_FIELD_BACKED_LIST_IMPL_H_ #include <utility> #include "eval/public/cel_value.h" #include "eval/public/structs/protobuf_value_factory.h" namespace google::api::expr::runtime::internal { class FieldBackedListImpl : public CelList { public: FieldBackedListImpl(const google::protobuf::Message* message, const google::protobuf::FieldDescriptor* descriptor, ProtobufValueFactory factory, google::protobuf::Arena* arena) : message_(message), descriptor_(descriptor), reflection_(message_->GetReflection()), factory_(std::move(factory)), arena_(arena) {} int size() const override; CelValue operator[](int index) const override; private: const google::protobuf::Message* message_; const google::protobuf::FieldDescriptor* descriptor_; const google::protobuf::Reflection* reflection_; ProtobufValueFactory factory_; google::protobuf::Arena* arena_; }; } #endif #include "eval/public/containers/internal_field_backed_list_impl.h" #include "eval/public/cel_value.h" #include "eval/public/structs/field_access_impl.h" namespace google::api::expr::runtime::internal { int FieldBackedListImpl::size() const { return reflection_->FieldSize(*message_, descriptor_); } CelValue FieldBackedListImpl::operator[](int index) const { auto result = CreateValueFromRepeatedField(message_, descriptor_, index, factory_, arena_); if (!result.ok()) { CreateErrorValue(arena_, result.status().ToString()); } return *result; } }
#include "eval/public/containers/internal_field_backed_list_impl.h" #include <memory> #include <string> #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/testutil/test_message.pb.h" #include "internal/testing.h" #include "testutil/util.h" namespace google::api::expr::runtime::internal { namespace { using ::google::api::expr::testutil::EqualsProto; using testing::DoubleEq; using testing::Eq; std::unique_ptr<CelList> CreateList(const TestMessage* message, const std::string& field, google::protobuf::Arena* arena) { const google::protobuf::FieldDescriptor* field_desc = message->GetDescriptor()->FindFieldByName(field); return std::make_unique<FieldBackedListImpl>( message, field_desc, &CelProtoWrapper::InternalWrapMessage, arena); } TEST(FieldBackedListImplTest, BoolDatatypeTest) { TestMessage message; message.add_bool_list(true); message.add_bool_list(false); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "bool_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].BoolOrDie(), true); EXPECT_EQ((*cel_list)[1].BoolOrDie(), false); } TEST(FieldBackedListImplTest, TestLength0) { TestMessage message; google::protobuf::Arena arena; auto cel_list = CreateList(&message, "int32_list", &arena); ASSERT_EQ(cel_list->size(), 0); } TEST(FieldBackedListImplTest, TestLength1) { TestMessage message; message.add_int32_list(1); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "int32_list", &arena); ASSERT_EQ(cel_list->size(), 1); EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1); } TEST(FieldBackedListImplTest, TestLength100000) { TestMessage message; const int kLen = 100000; for (int i = 0; i < kLen; i++) { message.add_int32_list(i); } google::protobuf::Arena arena; auto cel_list = CreateList(&message, "int32_list", &arena); ASSERT_EQ(cel_list->size(), kLen); for (int i = 0; i < kLen; i++) { EXPECT_EQ((*cel_list)[i].Int64OrDie(), i); } } TEST(FieldBackedListImplTest, Int32DatatypeTest) { TestMessage message; message.add_int32_list(1); message.add_int32_list(2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "int32_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1); EXPECT_EQ((*cel_list)[1].Int64OrDie(), 2); } TEST(FieldBackedListImplTest, Int64DatatypeTest) { TestMessage message; message.add_int64_list(1); message.add_int64_list(2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "int64_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].Int64OrDie(), 1); EXPECT_EQ((*cel_list)[1].Int64OrDie(), 2); } TEST(FieldBackedListImplTest, Uint32DatatypeTest) { TestMessage message; message.add_uint32_list(1); message.add_uint32_list(2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "uint32_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].Uint64OrDie(), 1); EXPECT_EQ((*cel_list)[1].Uint64OrDie(), 2); } TEST(FieldBackedListImplTest, Uint64DatatypeTest) { TestMessage message; message.add_uint64_list(1); message.add_uint64_list(2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "uint64_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].Uint64OrDie(), 1); EXPECT_EQ((*cel_list)[1].Uint64OrDie(), 2); } TEST(FieldBackedListImplTest, FloatDatatypeTest) { TestMessage message; message.add_float_list(1); message.add_float_list(2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "float_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_THAT((*cel_list)[0].DoubleOrDie(), DoubleEq(1)); EXPECT_THAT((*cel_list)[1].DoubleOrDie(), DoubleEq(2)); } TEST(FieldBackedListImplTest, DoubleDatatypeTest) { TestMessage message; message.add_double_list(1); message.add_double_list(2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "double_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_THAT((*cel_list)[0].DoubleOrDie(), DoubleEq(1)); EXPECT_THAT((*cel_list)[1].DoubleOrDie(), DoubleEq(2)); } TEST(FieldBackedListImplTest, StringDatatypeTest) { TestMessage message; message.add_string_list("1"); message.add_string_list("2"); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "string_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].StringOrDie().value(), "1"); EXPECT_EQ((*cel_list)[1].StringOrDie().value(), "2"); } TEST(FieldBackedListImplTest, BytesDatatypeTest) { TestMessage message; message.add_bytes_list("1"); message.add_bytes_list("2"); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "bytes_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_EQ((*cel_list)[0].BytesOrDie().value(), "1"); EXPECT_EQ((*cel_list)[1].BytesOrDie().value(), "2"); } TEST(FieldBackedListImplTest, MessageDatatypeTest) { TestMessage message; TestMessage* msg1 = message.add_message_list(); TestMessage* msg2 = message.add_message_list(); msg1->set_string_value("1"); msg2->set_string_value("2"); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "message_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_THAT(*msg1, EqualsProto(*((*cel_list)[0].MessageOrDie()))); EXPECT_THAT(*msg2, EqualsProto(*((*cel_list)[1].MessageOrDie()))); } TEST(FieldBackedListImplTest, EnumDatatypeTest) { TestMessage message; message.add_enum_list(TestMessage::TEST_ENUM_1); message.add_enum_list(TestMessage::TEST_ENUM_2); google::protobuf::Arena arena; auto cel_list = CreateList(&message, "enum_list", &arena); ASSERT_EQ(cel_list->size(), 2); EXPECT_THAT((*cel_list)[0].Int64OrDie(), Eq(TestMessage::TEST_ENUM_1)); EXPECT_THAT((*cel_list)[1].Int64OrDie(), Eq(TestMessage::TEST_ENUM_2)); } } }
118
cpp
google/cel-cpp
create_struct_step
eval/eval/create_struct_step.cc
eval/eval/create_struct_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_CREATE_STRUCT_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_CREATE_STRUCT_STEP_H_ #include <cstdint> #include <memory> #include <string> #include <vector> #include "absl/container/flat_hash_set.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectCreateStructStep( std::string name, std::vector<std::string> field_keys, std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateCreateStructStep( std::string name, std::vector<std::string> field_keys, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id); } #endif #include "eval/eval/create_struct_step.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::StructValueBuilderInterface; using ::cel::UnknownValue; using ::cel::Value; class CreateStructStepForStruct final : public ExpressionStepBase { public: CreateStructStepForStruct(int64_t expr_id, std::string name, std::vector<std::string> entries, absl::flat_hash_set<int32_t> optional_indices) : ExpressionStepBase(expr_id), name_(std::move(name)), entries_(std::move(entries)), optional_indices_(std::move(optional_indices)) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: absl::StatusOr<Value> DoEvaluate(ExecutionFrame* frame) const; std::string name_; std::vector<std::string> entries_; absl::flat_hash_set<int32_t> optional_indices_; }; absl::StatusOr<Value> CreateStructStepForStruct::DoEvaluate( ExecutionFrame* frame) const { int entries_size = entries_.size(); auto args = frame->value_stack().GetSpan(entries_size); if (frame->enable_unknowns()) { absl::optional<UnknownValue> unknown_set = frame->attribute_utility().IdentifyAndMergeUnknowns( args, frame->value_stack().GetAttributeSpan(entries_size), true); if (unknown_set.has_value()) { return *unknown_set; } } auto builder_or_status = frame->value_manager().NewValueBuilder(name_); if (!builder_or_status.ok()) { return builder_or_status.status(); } auto maybe_builder = std::move(*builder_or_status); if (!maybe_builder.has_value()) { return absl::NotFoundError(absl::StrCat("Unable to find builder: ", name_)); } auto builder = std::move(*maybe_builder); for (int i = 0; i < entries_size; ++i) { const auto& entry = entries_[i]; auto& arg = args[i]; if (optional_indices_.contains(static_cast<int32_t>(i))) { if (auto optional_arg = cel::As<cel::OptionalValue>(arg); optional_arg) { if (!optional_arg->HasValue()) { continue; } CEL_RETURN_IF_ERROR( builder->SetFieldByName(entry, optional_arg->Value())); } } else { CEL_RETURN_IF_ERROR(builder->SetFieldByName(entry, std::move(arg))); } } return std::move(*builder).Build(); } absl::Status CreateStructStepForStruct::Evaluate(ExecutionFrame* frame) const { if (frame->value_stack().size() < entries_.size()) { return absl::InternalError("CreateStructStepForStruct: stack underflow"); } Value result; auto status_or_result = DoEvaluate(frame); if (status_or_result.ok()) { result = std::move(status_or_result).value(); } else { result = frame->value_factory().CreateErrorValue(status_or_result.status()); } frame->value_stack().PopAndPush(entries_.size(), std::move(result)); return absl::OkStatus(); } class DirectCreateStructStep : public DirectExpressionStep { public: DirectCreateStructStep( int64_t expr_id, std::string name, std::vector<std::string> field_keys, std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices) : DirectExpressionStep(expr_id), name_(std::move(name)), field_keys_(std::move(field_keys)), deps_(std::move(deps)), optional_indices_(std::move(optional_indices)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& trail) const override; private: std::string name_; std::vector<std::string> field_keys_; std::vector<std::unique_ptr<DirectExpressionStep>> deps_; absl::flat_hash_set<int32_t> optional_indices_; }; absl::Status DirectCreateStructStep::Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& trail) const { Value field_value; AttributeTrail field_attr; auto unknowns = frame.attribute_utility().CreateAccumulator(); auto builder_or_status = frame.value_manager().NewValueBuilder(name_); if (!builder_or_status.ok()) { result = frame.value_manager().CreateErrorValue(builder_or_status.status()); return absl::OkStatus(); } if (!builder_or_status->has_value()) { result = frame.value_manager().CreateErrorValue( absl::NotFoundError(absl::StrCat("Unable to find builder: ", name_))); return absl::OkStatus(); } auto& builder = **builder_or_status; for (int i = 0; i < field_keys_.size(); i++) { CEL_RETURN_IF_ERROR(deps_[i]->Evaluate(frame, field_value, field_attr)); if (InstanceOf<ErrorValue>(field_value)) { result = std::move(field_value); return absl::OkStatus(); } if (frame.unknown_processing_enabled()) { if (InstanceOf<UnknownValue>(field_value)) { unknowns.Add(Cast<UnknownValue>(field_value)); } else if (frame.attribute_utility().CheckForUnknownPartial(field_attr)) { unknowns.Add(field_attr); } } if (!unknowns.IsEmpty()) { continue; } if (optional_indices_.contains(static_cast<int32_t>(i))) { if (auto optional_arg = cel::As<cel::OptionalValue>( static_cast<const Value&>(field_value)); optional_arg) { if (!optional_arg->HasValue()) { continue; } auto status = builder->SetFieldByName(field_keys_[i], optional_arg->Value()); if (!status.ok()) { result = frame.value_manager().CreateErrorValue(std::move(status)); return absl::OkStatus(); } } continue; } auto status = builder->SetFieldByName(field_keys_[i], std::move(field_value)); if (!status.ok()) { result = frame.value_manager().CreateErrorValue(std::move(status)); return absl::OkStatus(); } } if (!unknowns.IsEmpty()) { result = std::move(unknowns).Build(); return absl::OkStatus(); } result = std::move(*builder).Build(); return absl::OkStatus(); } } std::unique_ptr<DirectExpressionStep> CreateDirectCreateStructStep( std::string resolved_name, std::vector<std::string> field_keys, std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) { return std::make_unique<DirectCreateStructStep>( expr_id, std::move(resolved_name), std::move(field_keys), std::move(deps), std::move(optional_indices)); } std::unique_ptr<ExpressionStep> CreateCreateStructStep( std::string name, std::vector<std::string> field_keys, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) { return std::make_unique<CreateStructStepForStruct>( expr_id, std::move(name), std::move(field_keys), std::move(optional_indices)); } }
#include "eval/eval/create_struct_step.h" #include <cstdint> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "base/ast_internal/expr.h" #include "base/type_provider.h" #include "common/values/legacy_value_manager.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_type_registry.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/structs/protobuf_descriptor_type_provider.h" #include "eval/public/unknown_set.h" #include "eval/testutil/test_message.pb.h" #include "extensions/protobuf/memory_manager.h" #include "internal/proto_matchers.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeProvider; using ::cel::ast_internal::Expr; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::internal::test::EqualsProto; using ::google::protobuf::Arena; using ::google::protobuf::Message; using testing::Eq; using testing::IsNull; using testing::Not; using testing::Pointwise; absl::StatusOr<ExecutionPath> MakeStackMachinePath(absl::string_view field) { ExecutionPath path; Expr expr0; auto& ident = expr0.mutable_ident_expr(); ident.set_name("message"); CEL_ASSIGN_OR_RETURN(auto step0, CreateIdentStep(ident, expr0.id())); auto step1 = CreateCreateStructStep("google.api.expr.runtime.TestMessage", {std::string(field)}, {}, -1); path.push_back(std::move(step0)); path.push_back(std::move(step1)); return path; } absl::StatusOr<ExecutionPath> MakeRecursivePath(absl::string_view field) { ExecutionPath path; std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateDirectIdentStep("message", -1)); auto step1 = CreateDirectCreateStructStep("google.api.expr.runtime.TestMessage", {std::string(field)}, std::move(deps), {}, -1); path.push_back(std::make_unique<WrappedDirectStep>(std::move(step1), -1)); return path; } absl::StatusOr<CelValue> RunExpression(absl::string_view field, const CelValue& value, google::protobuf::Arena* arena, bool enable_unknowns, bool enable_recursive_planning) { CelTypeRegistry type_registry; type_registry.RegisterTypeProvider( std::make_unique<ProtobufDescriptorProvider>( google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory())); auto memory_manager = ProtoMemoryManagerRef(arena); cel::common_internal::LegacyValueManager type_manager( memory_manager, type_registry.GetTypeProvider()); CEL_ASSIGN_OR_RETURN( auto maybe_type, type_manager.FindType("google.api.expr.runtime.TestMessage")); if (!maybe_type.has_value()) { return absl::Status(absl::StatusCode::kFailedPrecondition, "missing proto message type"); } cel::RuntimeOptions options; if (enable_unknowns) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } ExecutionPath path; if (enable_recursive_planning) { CEL_ASSIGN_OR_RETURN(path, MakeRecursivePath(field)); } else { CEL_ASSIGN_OR_RETURN(path, MakeStackMachinePath(field)); } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, type_registry.GetTypeProvider(), options)); Activation activation; activation.InsertValue("message", value); return cel_expr.Evaluate(activation, arena); } void RunExpressionAndGetMessage(absl::string_view field, const CelValue& value, google::protobuf::Arena* arena, TestMessage* test_msg, bool enable_unknowns, bool enable_recursive_planning) { ASSERT_OK_AND_ASSIGN(auto result, RunExpression(field, value, arena, enable_unknowns, enable_recursive_planning)); ASSERT_TRUE(result.IsMessage()) << result.DebugString(); const Message* msg = result.MessageOrDie(); ASSERT_THAT(msg, Not(IsNull())); ASSERT_EQ(msg->GetDescriptor(), TestMessage::descriptor()); test_msg->MergeFrom(*msg); } void RunExpressionAndGetMessage(absl::string_view field, std::vector<CelValue> values, google::protobuf::Arena* arena, TestMessage* test_msg, bool enable_unknowns, bool enable_recursive_planning) { ContainerBackedListImpl cel_list(std::move(values)); CelValue value = CelValue::CreateList(&cel_list); ASSERT_OK_AND_ASSIGN(auto result, RunExpression(field, value, arena, enable_unknowns, enable_recursive_planning)); ASSERT_TRUE(result.IsMessage()) << result.DebugString(); const Message* msg = result.MessageOrDie(); ASSERT_THAT(msg, Not(IsNull())); ASSERT_EQ(msg->GetDescriptor(), TestMessage::descriptor()); test_msg->MergeFrom(*msg); } class CreateCreateStructStepTest : public testing::TestWithParam<std::tuple<bool, bool>> { public: bool enable_unknowns() { return std::get<0>(GetParam()); } bool enable_recursive_planning() { return std::get<1>(GetParam()); } }; TEST_P(CreateCreateStructStepTest, TestEmptyMessageCreation) { ExecutionPath path; CelTypeRegistry type_registry; type_registry.RegisterTypeProvider( std::make_unique<ProtobufDescriptorProvider>( google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory())); google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); cel::common_internal::LegacyValueManager type_manager( memory_manager, type_registry.GetTypeProvider()); auto adapter = type_registry.FindTypeAdapter("google.api.expr.runtime.TestMessage"); ASSERT_TRUE(adapter.has_value() && adapter->mutation_apis() != nullptr); ASSERT_OK_AND_ASSIGN( auto maybe_type, type_manager.FindType("google.api.expr.runtime.TestMessage")); ASSERT_TRUE(maybe_type.has_value()); if (enable_recursive_planning()) { auto step = CreateDirectCreateStructStep("google.api.expr.runtime.TestMessage", {}, {}, {}, -1); path.push_back( std::make_unique<WrappedDirectStep>(std::move(step), -1)); } else { auto step = CreateCreateStructStep("google.api.expr.runtime.TestMessage", {}, {}, -1); path.push_back(std::move(step)); } cel::RuntimeOptions options; if (enable_unknowns(), enable_recursive_planning()) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, type_registry.GetTypeProvider(), options)); Activation activation; ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena)); ASSERT_TRUE(result.IsMessage()) << result.DebugString(); const Message* msg = result.MessageOrDie(); ASSERT_THAT(msg, Not(IsNull())); ASSERT_EQ(msg->GetDescriptor(), TestMessage::descriptor()); } TEST(CreateCreateStructStepTest, TestMessageCreateWithUnknown) { Arena arena; TestMessage test_msg; UnknownSet unknown_set; auto eval_status = RunExpression("bool_value", CelValue::CreateUnknownSet(&unknown_set), &arena, true, false); ASSERT_OK(eval_status); ASSERT_TRUE(eval_status->IsUnknownSet()); } TEST(CreateCreateStructStepTest, TestMessageCreateWithUnknownRecursive) { Arena arena; TestMessage test_msg; UnknownSet unknown_set; auto eval_status = RunExpression("bool_value", CelValue::CreateUnknownSet(&unknown_set), &arena, true, true); ASSERT_OK(eval_status); ASSERT_TRUE(eval_status->IsUnknownSet()) << eval_status->DebugString(); } TEST_P(CreateCreateStructStepTest, TestSetBoolField) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "bool_value", CelValue::CreateBool(true), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_EQ(test_msg.bool_value(), true); } TEST_P(CreateCreateStructStepTest, TestSetInt32Field) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "int32_value", CelValue::CreateInt64(1), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_EQ(test_msg.int32_value(), 1); } TEST_P(CreateCreateStructStepTest, TestSetUInt32Field) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "uint32_value", CelValue::CreateUint64(1), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_EQ(test_msg.uint32_value(), 1); } TEST_P(CreateCreateStructStepTest, TestSetInt64Field) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "int64_value", CelValue::CreateInt64(1), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_EQ(test_msg.int64_value(), 1); } TEST_P(CreateCreateStructStepTest, TestSetUInt64Field) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "uint64_value", CelValue::CreateUint64(1), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_EQ(test_msg.uint64_value(), 1); } TEST_P(CreateCreateStructStepTest, TestSetFloatField) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "float_value", CelValue::CreateDouble(2.0), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_DOUBLE_EQ(test_msg.float_value(), 2.0); } TEST_P(CreateCreateStructStepTest, TestSetDoubleField) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "double_value", CelValue::CreateDouble(2.0), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_DOUBLE_EQ(test_msg.double_value(), 2.0); } TEST_P(CreateCreateStructStepTest, TestSetStringField) { const std::string kTestStr = "test"; Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "string_value", CelValue::CreateString(&kTestStr), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_EQ(test_msg.string_value(), kTestStr); } TEST_P(CreateCreateStructStepTest, TestSetBytesField) { Arena arena; const std::string kTestStr = "test"; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "bytes_value", CelValue::CreateBytes(&kTestStr), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_EQ(test_msg.bytes_value(), kTestStr); } TEST_P(CreateCreateStructStepTest, TestSetDurationField) { Arena arena; google::protobuf::Duration test_duration; test_duration.set_seconds(2); test_duration.set_nanos(3); TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "duration_value", CelProtoWrapper::CreateDuration(&test_duration), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_THAT(test_msg.duration_value(), EqualsProto(test_duration)); } TEST_P(CreateCreateStructStepTest, TestSetTimestampField) { Arena arena; google::protobuf::Timestamp test_timestamp; test_timestamp.set_seconds(2); test_timestamp.set_nanos(3); TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "timestamp_value", CelProtoWrapper::CreateTimestamp(&test_timestamp), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_THAT(test_msg.timestamp_value(), EqualsProto(test_timestamp)); } TEST_P(CreateCreateStructStepTest, TestSetMessageField) { Arena arena; TestMessage orig_msg; orig_msg.set_bool_value(true); orig_msg.set_string_value("test"); TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "message_value", CelProtoWrapper::CreateMessage(&orig_msg, &arena), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_THAT(test_msg.message_value(), EqualsProto(orig_msg)); } TEST_P(CreateCreateStructStepTest, TestSetAnyField) { Arena arena; TestMessage orig_embedded_msg; orig_embedded_msg.set_bool_value(true); orig_embedded_msg.set_string_value("embedded"); TestMessage orig_msg; orig_msg.mutable_any_value()->PackFrom(orig_embedded_msg); TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "any_value", CelProtoWrapper::CreateMessage(&orig_embedded_msg, &arena), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_THAT(test_msg, EqualsProto(orig_msg)); TestMessage test_embedded_msg; ASSERT_TRUE(test_msg.any_value().UnpackTo(&test_embedded_msg)); EXPECT_THAT(test_embedded_msg, EqualsProto(orig_embedded_msg)); } TEST_P(CreateCreateStructStepTest, TestSetEnumField) { Arena arena; TestMessage test_msg; ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "enum_value", CelValue::CreateInt64(TestMessage::TEST_ENUM_2), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); EXPECT_EQ(test_msg.enum_value(), TestMessage::TEST_ENUM_2); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedBoolField) { Arena arena; TestMessage test_msg; std::vector<bool> kValues = {true, false}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateBool(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "bool_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.bool_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedInt32Field) { Arena arena; TestMessage test_msg; std::vector<int32_t> kValues = {23, 12}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateInt64(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "int32_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.int32_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedUInt32Field) { Arena arena; TestMessage test_msg; std::vector<uint32_t> kValues = {23, 12}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateUint64(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "uint32_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.uint32_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedInt64Field) { Arena arena; TestMessage test_msg; std::vector<int64_t> kValues = {23, 12}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateInt64(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "int64_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.int64_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedUInt64Field) { Arena arena; TestMessage test_msg; std::vector<uint64_t> kValues = {23, 12}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateUint64(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "uint64_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.uint64_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedFloatField) { Arena arena; TestMessage test_msg; std::vector<float> kValues = {23, 12}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateDouble(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "float_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.float_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedDoubleField) { Arena arena; TestMessage test_msg; std::vector<double> kValues = {23, 12}; std::vector<CelValue> values; for (auto value : kValues) { values.push_back(CelValue::CreateDouble(value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "double_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.double_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedStringField) { Arena arena; TestMessage test_msg; std::vector<std::string> kValues = {"test1", "test2"}; std::vector<CelValue> values; for (const auto& value : kValues) { values.push_back(CelValue::CreateString(&value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "string_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.string_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedBytesField) { Arena arena; TestMessage test_msg; std::vector<std::string> kValues = {"test1", "test2"}; std::vector<CelValue> values; for (const auto& value : kValues) { values.push_back(CelValue::CreateBytes(&value)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "bytes_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.bytes_list(), Pointwise(Eq(), kValues)); } TEST_P(CreateCreateStructStepTest, TestSetRepeatedMessageField) { Arena arena; TestMessage test_msg; std::vector<TestMessage> kValues(2); kValues[0].set_string_value("test1"); kValues[1].set_string_value("test2"); std::vector<CelValue> values; for (const auto& value : kValues) { values.push_back(CelProtoWrapper::CreateMessage(&value, &arena)); } ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "message_list", values, &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_THAT(test_msg.message_list()[0], EqualsProto(kValues[0])); ASSERT_THAT(test_msg.message_list()[1], EqualsProto(kValues[1])); } TEST_P(CreateCreateStructStepTest, TestSetStringMapField) { Arena arena; TestMessage test_msg; std::vector<std::pair<CelValue, CelValue>> entries; const std::vector<std::string> kKeys = {"test2", "test1"}; entries.push_back( {CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)}); entries.push_back( {CelValue::CreateString(&kKeys[1]), CelValue::CreateInt64(1)}); auto cel_map = *CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>( entries.data(), entries.size())); ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "string_int32_map", CelValue::CreateMap(cel_map.get()), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_EQ(test_msg.string_int32_map().size(), 2); ASSERT_EQ(test_msg.string_int32_map().at(kKeys[0]), 2); ASSERT_EQ(test_msg.string_int32_map().at(kKeys[1]), 1); } TEST_P(CreateCreateStructStepTest, TestSetInt64MapField) { Arena arena; TestMessage test_msg; std::vector<std::pair<CelValue, CelValue>> entries; const std::vector<int64_t> kKeys = {3, 4}; entries.push_back( {CelValue::CreateInt64(kKeys[0]), CelValue::CreateInt64(1)}); entries.push_back( {CelValue::CreateInt64(kKeys[1]), CelValue::CreateInt64(2)}); auto cel_map = *CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>( entries.data(), entries.size())); ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "int64_int32_map", CelValue::CreateMap(cel_map.get()), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_EQ(test_msg.int64_int32_map().size(), 2); ASSERT_EQ(test_msg.int64_int32_map().at(kKeys[0]), 1); ASSERT_EQ(test_msg.int64_int32_map().at(kKeys[1]), 2); } TEST_P(CreateCreateStructStepTest, TestSetUInt64MapField) { Arena arena; TestMessage test_msg; std::vector<std::pair<CelValue, CelValue>> entries; const std::vector<uint64_t> kKeys = {3, 4}; entries.push_back( {CelValue::CreateUint64(kKeys[0]), CelValue::CreateInt64(1)}); entries.push_back( {CelValue::CreateUint64(kKeys[1]), CelValue::CreateInt64(2)}); auto cel_map = *CreateContainerBackedMap(absl::Span<std::pair<CelValue, CelValue>>( entries.data(), entries.size())); ASSERT_NO_FATAL_FAILURE(RunExpressionAndGetMessage( "uint64_int32_map", CelValue::CreateMap(cel_map.get()), &arena, &test_msg, enable_unknowns(), enable_recursive_planning())); ASSERT_EQ(test_msg.uint64_int32_map().size(), 2); ASSERT_EQ(test_msg.uint64_int32_map().at(kKeys[0]), 1); ASSERT_EQ(test_msg.uint64_int32_map().at(kKeys[1]), 2); } INSTANTIATE_TEST_SUITE_P(CombinedCreateStructTest, CreateCreateStructStepTest, testing::Combine(testing::Bool(), testing::Bool())); } }
119
cpp
google/cel-cpp
const_value_step
eval/eval/const_value_step.cc
eval/eval/const_value_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_CONST_VALUE_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_CONST_VALUE_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "base/ast_internal/expr.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateConstValueDirectStep( cel::Value value, int64_t expr_id = -1); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateConstValueStep( cel::Value value, int64_t expr_id, bool comes_from_ast = true); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateConstValueStep( const cel::ast_internal::Constant&, int64_t expr_id, cel::ValueManager& value_factory, bool comes_from_ast = true); } #endif #include "eval/eval/const_value_step.h" #include <cstdint> #include <memory> #include <utility> #include "absl/status/statusor.h" #include "base/ast_internal/expr.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/compiler_constant_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "internal/status_macros.h" #include "runtime/internal/convert_constant.h" namespace google::api::expr::runtime { namespace { using ::cel::ast_internal::Constant; using ::cel::runtime_internal::ConvertConstant; } std::unique_ptr<DirectExpressionStep> CreateConstValueDirectStep( cel::Value value, int64_t id) { return std::make_unique<DirectCompilerConstantStep>(std::move(value), id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateConstValueStep( cel::Value value, int64_t expr_id, bool comes_from_ast) { return std::make_unique<CompilerConstantStep>(std::move(value), expr_id, comes_from_ast); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateConstValueStep( const Constant& value, int64_t expr_id, cel::ValueManager& value_factory, bool comes_from_ast) { CEL_ASSIGN_OR_RETURN(cel::Value converted_value, ConvertConstant(value, value_factory)); return std::make_unique<CompilerConstantStep>(std::move(converted_value), expr_id, comes_from_ast); } }
#include "eval/eval/const_value_step.h" #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/time/time.h" #include "base/ast_internal/expr.h" #include "base/type_provider.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/evaluator_core.h" #include "eval/internal/errors.h" #include "eval/public/activation.h" #include "eval/public/cel_value.h" #include "eval/public/testing/matchers.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeProvider; using ::cel::ast_internal::Constant; using ::cel::ast_internal::Expr; using ::cel::ast_internal::NullValue; using ::cel::extensions::ProtoMemoryManagerRef; using testing::Eq; using testing::HasSubstr; using cel::internal::StatusIs; absl::StatusOr<CelValue> RunConstantExpression( const Expr* expr, const Constant& const_expr, google::protobuf::Arena* arena, cel::ValueManager& value_factory) { CEL_ASSIGN_OR_RETURN( auto step, CreateConstValueStep(const_expr, expr->id(), value_factory)); google::api::expr::runtime::ExecutionPath path; path.push_back(std::move(step)); CelExpressionFlatImpl impl( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); google::api::expr::runtime::Activation activation; return impl.Evaluate(activation, arena); } class ConstValueStepTest : public ::testing::Test { public: ConstValueStepTest() : value_factory_(ProtoMemoryManagerRef(&arena_), cel::TypeProvider::Builtin()) {} protected: google::protobuf::Arena arena_; cel::common_internal::LegacyValueManager value_factory_; }; TEST_F(ConstValueStepTest, TestEvaluationConstInt64) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_int64_value(1); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsInt64()); EXPECT_THAT(value.Int64OrDie(), Eq(1)); } TEST_F(ConstValueStepTest, TestEvaluationConstUint64) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_uint64_value(1); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsUint64()); EXPECT_THAT(value.Uint64OrDie(), Eq(1)); } TEST_F(ConstValueStepTest, TestEvaluationConstBool) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_bool_value(true); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsBool()); EXPECT_THAT(value.BoolOrDie(), Eq(true)); } TEST_F(ConstValueStepTest, TestEvaluationConstNull) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_null_value(nullptr); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); EXPECT_TRUE(value.IsNull()); } TEST_F(ConstValueStepTest, TestEvaluationConstString) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_string_value("test"); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsString()); EXPECT_THAT(value.StringOrDie().value(), Eq("test")); } TEST_F(ConstValueStepTest, TestEvaluationConstDouble) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_double_value(1.0); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsDouble()); EXPECT_THAT(value.DoubleOrDie(), testing::DoubleEq(1.0)); } TEST_F(ConstValueStepTest, TestEvaluationConstBytes) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_bytes_value("test"); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsBytes()); EXPECT_THAT(value.BytesOrDie().value(), Eq("test")); } TEST_F(ConstValueStepTest, TestEvaluationConstDuration) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_duration_value(absl::Seconds(5) + absl::Nanoseconds(2000)); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); EXPECT_THAT(value, test::IsCelDuration(absl::Seconds(5) + absl::Nanoseconds(2000))); } TEST_F(ConstValueStepTest, TestEvaluationConstDurationOutOfRange) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_duration_value(cel::runtime_internal::kDurationHigh); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); EXPECT_THAT(value, test::IsCelError(StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("out of range")))); } TEST_F(ConstValueStepTest, TestEvaluationConstTimestamp) { Expr expr; auto& const_expr = expr.mutable_const_expr(); const_expr.set_time_value(absl::FromUnixSeconds(3600) + absl::Nanoseconds(1000)); auto status = RunConstantExpression(&expr, const_expr, &arena_, value_factory_); ASSERT_OK(status); auto value = status.value(); EXPECT_THAT(value, test::IsCelTimestamp(absl::FromUnixSeconds(3600) + absl::Nanoseconds(1000))); } } }
120
cpp
google/cel-cpp
ident_step
eval/eval/ident_step.cc
eval/eval/ident_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_IDENT_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_IDENT_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "base/ast_internal/expr.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectIdentStep( absl::string_view identifier, int64_t expr_id); std::unique_ptr<DirectExpressionStep> CreateDirectSlotIdentStep( absl::string_view identifier, size_t slot_index, int64_t expr_id); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateIdentStep( const cel::ast_internal::Ident& ident, int64_t expr_id); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateIdentStepForSlot( const cel::ast_internal::Ident& ident_expr, size_t slot_index, int64_t expr_id); } #endif #include "eval/eval/ident_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "base/ast_internal/expr.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/comprehension_slots.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using ::cel::Value; using ::cel::ValueView; using ::cel::runtime_internal::CreateError; class IdentStep : public ExpressionStepBase { public: IdentStep(absl::string_view name, int64_t expr_id) : ExpressionStepBase(expr_id), name_(name) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: struct IdentResult { ValueView value; AttributeTrail trail; }; std::string name_; }; absl::Status LookupIdent(const std::string& name, ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) { if (frame.attribute_tracking_enabled()) { attribute = AttributeTrail(name); if (frame.missing_attribute_errors_enabled() && frame.attribute_utility().CheckForMissingAttribute(attribute)) { CEL_ASSIGN_OR_RETURN( result, frame.attribute_utility().CreateMissingAttributeError( attribute.attribute())); return absl::OkStatus(); } if (frame.unknown_processing_enabled() && frame.attribute_utility().CheckForUnknownExact(attribute)) { result = frame.attribute_utility().CreateUnknownSet(attribute.attribute()); return absl::OkStatus(); } } CEL_ASSIGN_OR_RETURN(auto value, frame.activation().FindVariable( frame.value_manager(), name, result)); if (value.has_value()) { result = *value; return absl::OkStatus(); } result = frame.value_manager().CreateErrorValue(CreateError( absl::StrCat("No value with name \"", name, "\" found in Activation"))); return absl::OkStatus(); } absl::Status IdentStep::Evaluate(ExecutionFrame* frame) const { Value value; AttributeTrail attribute; CEL_RETURN_IF_ERROR(LookupIdent(name_, *frame, value, attribute)); frame->value_stack().Push(std::move(value), std::move(attribute)); return absl::OkStatus(); } absl::StatusOr<absl::Nonnull<const ComprehensionSlots::Slot*>> LookupSlot( absl::string_view name, size_t slot_index, ExecutionFrameBase& frame) { const ComprehensionSlots::Slot* slot = frame.comprehension_slots().Get(slot_index); if (slot == nullptr) { return absl::InternalError( absl::StrCat("Comprehension variable accessed out of scope: ", name)); } return slot; } class SlotStep : public ExpressionStepBase { public: SlotStep(absl::string_view name, size_t slot_index, int64_t expr_id) : ExpressionStepBase(expr_id), name_(name), slot_index_(slot_index) {} absl::Status Evaluate(ExecutionFrame* frame) const override { CEL_ASSIGN_OR_RETURN(const ComprehensionSlots::Slot* slot, LookupSlot(name_, slot_index_, *frame)); frame->value_stack().Push(slot->value, slot->attribute); return absl::OkStatus(); } private: std::string name_; size_t slot_index_; }; class DirectIdentStep : public DirectExpressionStep { public: DirectIdentStep(absl::string_view name, int64_t expr_id) : DirectExpressionStep(expr_id), name_(name) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override { return LookupIdent(name_, frame, result, attribute); } private: std::string name_; }; class DirectSlotStep : public DirectExpressionStep { public: DirectSlotStep(std::string name, size_t slot_index, int64_t expr_id) : DirectExpressionStep(expr_id), name_(std::move(name)), slot_index_(slot_index) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override { CEL_ASSIGN_OR_RETURN(const ComprehensionSlots::Slot* slot, LookupSlot(name_, slot_index_, frame)); if (frame.attribute_tracking_enabled()) { attribute = slot->attribute; } result = slot->value; return absl::OkStatus(); } private: std::string name_; size_t slot_index_; }; } std::unique_ptr<DirectExpressionStep> CreateDirectIdentStep( absl::string_view identifier, int64_t expr_id) { return std::make_unique<DirectIdentStep>(identifier, expr_id); } std::unique_ptr<DirectExpressionStep> CreateDirectSlotIdentStep( absl::string_view identifier, size_t slot_index, int64_t expr_id) { return std::make_unique<DirectSlotStep>(std::string(identifier), slot_index, expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateIdentStep( const cel::ast_internal::Ident& ident_expr, int64_t expr_id) { return std::make_unique<IdentStep>(ident_expr.name(), expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateIdentStepForSlot( const cel::ast_internal::Ident& ident_expr, size_t slot_index, int64_t expr_id) { return std::make_unique<SlotStep>(ident_expr.name(), slot_index, expr_id); } }
#include "eval/eval/ident_step.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "base/type_provider.h" #include "common/memory.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/evaluator_core.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ManagedValueFactory; using ::cel::MemoryManagerRef; using ::cel::RuntimeOptions; using ::cel::TypeProvider; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ast_internal::Expr; using ::google::protobuf::Arena; using testing::Eq; using testing::HasSubstr; using testing::SizeIs; using cel::internal::StatusIs; TEST(IdentStepTest, TestIdentStep) { Expr expr; auto& ident_expr = expr.mutable_ident_expr(); ident_expr.set_name("name0"); ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id())); ExecutionPath path; path.push_back(std::move(step)); CelExpressionFlatImpl impl( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); Activation activation; Arena arena; std::string value("test"); activation.InsertValue("name0", CelValue::CreateString(&value)); auto status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); CelValue result = status0.value(); ASSERT_TRUE(result.IsString()); EXPECT_THAT(result.StringOrDie().value(), Eq("test")); } TEST(IdentStepTest, TestIdentStepNameNotFound) { Expr expr; auto& ident_expr = expr.mutable_ident_expr(); ident_expr.set_name("name0"); ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id())); ExecutionPath path; path.push_back(std::move(step)); CelExpressionFlatImpl impl( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); Activation activation; Arena arena; std::string value("test"); auto status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); CelValue result = status0.value(); ASSERT_TRUE(result.IsError()); } TEST(IdentStepTest, DisableMissingAttributeErrorsOK) { Expr expr; auto& ident_expr = expr.mutable_ident_expr(); ident_expr.set_name("name0"); ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id())); ExecutionPath path; path.push_back(std::move(step)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kDisabled; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; Arena arena; std::string value("test"); activation.InsertValue("name0", CelValue::CreateString(&value)); auto status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); CelValue result = status0.value(); ASSERT_TRUE(result.IsString()); EXPECT_THAT(result.StringOrDie().value(), Eq("test")); const CelAttributePattern pattern("name0", {}); activation.set_missing_attribute_patterns({pattern}); status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); EXPECT_THAT(status0->StringOrDie().value(), Eq("test")); } TEST(IdentStepTest, TestIdentStepMissingAttributeErrors) { Expr expr; auto& ident_expr = expr.mutable_ident_expr(); ident_expr.set_name("name0"); ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id())); ExecutionPath path; path.push_back(std::move(step)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kDisabled; options.enable_missing_attribute_errors = true; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; Arena arena; std::string value("test"); activation.InsertValue("name0", CelValue::CreateString(&value)); auto status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); CelValue result = status0.value(); ASSERT_TRUE(result.IsString()); EXPECT_THAT(result.StringOrDie().value(), Eq("test")); CelAttributePattern pattern("name0", {}); activation.set_missing_attribute_patterns({pattern}); status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); EXPECT_EQ(status0->ErrorOrDie()->code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(status0->ErrorOrDie()->message(), "MissingAttributeError: name0"); } TEST(IdentStepTest, TestIdentStepUnknownAttribute) { Expr expr; auto& ident_expr = expr.mutable_ident_expr(); ident_expr.set_name("name0"); ASSERT_OK_AND_ASSIGN(auto step, CreateIdentStep(ident_expr, expr.id())); ExecutionPath path; path.push_back(std::move(step)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; Arena arena; std::string value("test"); activation.InsertValue("name0", CelValue::CreateString(&value)); std::vector<CelAttributePattern> unknown_patterns; unknown_patterns.push_back(CelAttributePattern("name_bad", {})); activation.set_unknown_attribute_patterns(unknown_patterns); auto status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); CelValue result = status0.value(); ASSERT_TRUE(result.IsString()); EXPECT_THAT(result.StringOrDie().value(), Eq("test")); unknown_patterns.push_back(CelAttributePattern("name0", {})); activation.set_unknown_attribute_patterns(unknown_patterns); status0 = impl.Evaluate(activation, &arena); ASSERT_OK(status0); result = status0.value(); ASSERT_TRUE(result.IsUnknownSet()); } TEST(DirectIdentStepTest, Basic) { ManagedValueFactory value_factory(TypeProvider::Builtin(), MemoryManagerRef::ReferenceCounting()); cel::Activation activation; RuntimeOptions options; activation.InsertOrAssignValue("var1", IntValue(42)); ExecutionFrameBase frame(activation, options, value_factory.get()); Value result; AttributeTrail trail; auto step = CreateDirectIdentStep("var1", -1); ASSERT_OK(step->Evaluate(frame, result, trail)); ASSERT_TRUE(InstanceOf<IntValue>(result)); EXPECT_THAT(Cast<IntValue>(result).NativeValue(), Eq(42)); } TEST(DirectIdentStepTest, UnknownAttribute) { ManagedValueFactory value_factory(TypeProvider::Builtin(), MemoryManagerRef::ReferenceCounting()); cel::Activation activation; RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; activation.InsertOrAssignValue("var1", IntValue(42)); activation.SetUnknownPatterns({CreateCelAttributePattern("var1", {})}); ExecutionFrameBase frame(activation, options, value_factory.get()); Value result; AttributeTrail trail; auto step = CreateDirectIdentStep("var1", -1); ASSERT_OK(step->Evaluate(frame, result, trail)); ASSERT_TRUE(InstanceOf<UnknownValue>(result)); EXPECT_THAT(Cast<UnknownValue>(result).attribute_set(), SizeIs(1)); } TEST(DirectIdentStepTest, MissingAttribute) { ManagedValueFactory value_factory(TypeProvider::Builtin(), MemoryManagerRef::ReferenceCounting()); cel::Activation activation; RuntimeOptions options; options.enable_missing_attribute_errors = true; activation.InsertOrAssignValue("var1", IntValue(42)); activation.SetMissingPatterns({CreateCelAttributePattern("var1", {})}); ExecutionFrameBase frame(activation, options, value_factory.get()); Value result; AttributeTrail trail; auto step = CreateDirectIdentStep("var1", -1); ASSERT_OK(step->Evaluate(frame, result, trail)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("var1"))); } TEST(DirectIdentStepTest, NotFound) { ManagedValueFactory value_factory(TypeProvider::Builtin(), MemoryManagerRef::ReferenceCounting()); cel::Activation activation; RuntimeOptions options; ExecutionFrameBase frame(activation, options, value_factory.get()); Value result; AttributeTrail trail; auto step = CreateDirectIdentStep("var1", -1); ASSERT_OK(step->Evaluate(frame, result, trail)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kUnknown, HasSubstr("\"var1\" found in Activation"))); } } }
121
cpp
google/cel-cpp
function_step
eval/eval/function_step.cc
eval/eval/function_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_FUNCTION_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_FUNCTION_STEP_H_ #include <cstdint> #include <memory> #include <vector> #include "absl/status/statusor.h" #include "base/ast_internal/expr.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "runtime/function_overload_reference.h" #include "runtime/function_registry.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectFunctionStep( int64_t expr_id, const cel::ast_internal::Call& call, std::vector<std::unique_ptr<DirectExpressionStep>> deps, std::vector<cel::FunctionOverloadReference> overloads); std::unique_ptr<DirectExpressionStep> CreateDirectLazyFunctionStep( int64_t expr_id, const cel::ast_internal::Call& call, std::vector<std::unique_ptr<DirectExpressionStep>> deps, std::vector<cel::FunctionRegistry::LazyOverload> providers); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateFunctionStep( const cel::ast_internal::Call& call, int64_t expr_id, std::vector<cel::FunctionRegistry::LazyOverload> lazy_overloads); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateFunctionStep( const cel::ast_internal::Call& call, int64_t expr_id, std::vector<cel::FunctionOverloadReference> overloads); } #endif #include "eval/eval/function_step.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/ast_internal/expr.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "common/casting.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "internal/status_macros.h" #include "runtime/activation_interface.h" #include "runtime/function_overload_reference.h" #include "runtime/function_provider.h" #include "runtime/function_registry.h" namespace google::api::expr::runtime { namespace { using ::cel::FunctionEvaluationContext; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ValueKindToKind; bool ShouldAcceptOverload(const cel::FunctionDescriptor& descriptor, absl::Span<const cel::Value> arguments) { for (size_t i = 0; i < arguments.size(); i++) { if (arguments[i]->Is<cel::UnknownValue>() || arguments[i]->Is<cel::ErrorValue>()) { return !descriptor.is_strict(); } } return true; } bool ArgumentKindsMatch(const cel::FunctionDescriptor& descriptor, absl::Span<const cel::Value> arguments) { auto types_size = descriptor.types().size(); if (types_size != arguments.size()) { return false; } for (size_t i = 0; i < types_size; i++) { const auto& arg = arguments[i]; cel::Kind param_kind = descriptor.types()[i]; if (arg->kind() != param_kind && param_kind != cel::Kind::kAny) { return false; } } return true; } std::string ToLegacyKindName(absl::string_view type_name) { if (type_name == "int" || type_name == "uint") { return absl::StrCat(type_name, "64"); } return std::string(type_name); } std::string CallArgTypeString(absl::Span<const cel::Value> args) { std::string call_sig_string = ""; for (size_t i = 0; i < args.size(); i++) { const auto& arg = args[i]; if (!call_sig_string.empty()) { absl::StrAppend(&call_sig_string, ", "); } absl::StrAppend( &call_sig_string, ToLegacyKindName(cel::KindToString(ValueKindToKind(arg->kind())))); } return absl::StrCat("(", call_sig_string, ")"); } std::vector<cel::Value> CheckForPartialUnknowns( ExecutionFrame* frame, absl::Span<const cel::Value> args, absl::Span<const AttributeTrail> attrs) { std::vector<cel::Value> result; result.reserve(args.size()); for (size_t i = 0; i < args.size(); i++) { const AttributeTrail& trail = attrs.subspan(i, 1)[0]; if (frame->attribute_utility().CheckForUnknown(trail, true)) { result.push_back( frame->attribute_utility().CreateUnknownSet(trail.attribute())); } else { result.push_back(args.at(i)); } } return result; } bool IsUnknownFunctionResultError(const Value& result) { if (!result->Is<cel::ErrorValue>()) { return false; } const auto& status = result.As<cel::ErrorValue>().NativeValue(); if (status.code() != absl::StatusCode::kUnavailable) { return false; } auto payload = status.GetPayload( cel::runtime_internal::kPayloadUrlUnknownFunctionResult); return payload.has_value() && payload.value() == "true"; } using ResolveResult = absl::optional<cel::FunctionOverloadReference>; class AbstractFunctionStep : public ExpressionStepBase { public: AbstractFunctionStep(const std::string& name, size_t num_arguments, int64_t expr_id) : ExpressionStepBase(expr_id), name_(name), num_arguments_(num_arguments) {} absl::Status Evaluate(ExecutionFrame* frame) const override; absl::StatusOr<Value> DoEvaluate(ExecutionFrame* frame) const; virtual absl::StatusOr<ResolveResult> ResolveFunction( absl::Span<const cel::Value> args, const ExecutionFrame* frame) const = 0; protected: std::string name_; size_t num_arguments_; }; inline absl::StatusOr<Value> Invoke( const cel::FunctionOverloadReference& overload, int64_t expr_id, absl::Span<const cel::Value> args, ExecutionFrameBase& frame) { FunctionEvaluationContext context(frame.value_manager()); CEL_ASSIGN_OR_RETURN(Value result, overload.implementation.Invoke(context, args)); if (frame.unknown_function_results_enabled() && IsUnknownFunctionResultError(result)) { return frame.attribute_utility().CreateUnknownSet(overload.descriptor, expr_id, args); } return result; } Value NoOverloadResult(absl::string_view name, absl::Span<const cel::Value> args, ExecutionFrameBase& frame) { for (size_t i = 0; i < args.size(); i++) { const auto& arg = args[i]; if (cel::InstanceOf<cel::ErrorValue>(arg)) { return arg; } } if (frame.unknown_processing_enabled()) { absl::optional<UnknownValue> unknown_set = frame.attribute_utility().MergeUnknowns(args); if (unknown_set.has_value()) { return *unknown_set; } } return frame.value_manager().CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError( absl::StrCat(name, CallArgTypeString(args)))); } absl::StatusOr<Value> AbstractFunctionStep::DoEvaluate( ExecutionFrame* frame) const { auto input_args = frame->value_stack().GetSpan(num_arguments_); std::vector<cel::Value> unknowns_args; if (frame->enable_unknowns()) { auto input_attrs = frame->value_stack().GetAttributeSpan(num_arguments_); unknowns_args = CheckForPartialUnknowns(frame, input_args, input_attrs); input_args = absl::MakeConstSpan(unknowns_args); } CEL_ASSIGN_OR_RETURN(ResolveResult matched_function, ResolveFunction(input_args, frame)); if (matched_function.has_value() && ShouldAcceptOverload(matched_function->descriptor, input_args)) { return Invoke(*matched_function, id(), input_args, *frame); } return NoOverloadResult(name_, input_args, *frame); } absl::Status AbstractFunctionStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(num_arguments_)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } CEL_ASSIGN_OR_RETURN(auto result, DoEvaluate(frame)); frame->value_stack().PopAndPush(num_arguments_, std::move(result)); return absl::OkStatus(); } absl::StatusOr<ResolveResult> ResolveStatic( absl::Span<const cel::Value> input_args, absl::Span<const cel::FunctionOverloadReference> overloads) { ResolveResult result = absl::nullopt; for (const auto& overload : overloads) { if (ArgumentKindsMatch(overload.descriptor, input_args)) { if (result.has_value()) { return absl::Status(absl::StatusCode::kInternal, "Cannot resolve overloads"); } result.emplace(overload); } } return result; } absl::StatusOr<ResolveResult> ResolveLazy( absl::Span<const cel::Value> input_args, absl::string_view name, bool receiver_style, absl::Span<const cel::FunctionRegistry::LazyOverload> providers, const ExecutionFrameBase& frame) { ResolveResult result = absl::nullopt; std::vector<cel::Kind> arg_types(input_args.size()); std::transform( input_args.begin(), input_args.end(), arg_types.begin(), [](const cel::Value& value) { return ValueKindToKind(value->kind()); }); cel::FunctionDescriptor matcher{name, receiver_style, arg_types}; const cel::ActivationInterface& activation = frame.activation(); for (auto provider : providers) { if (!ArgumentKindsMatch(provider.descriptor, input_args)) { continue; } CEL_ASSIGN_OR_RETURN(auto overload, provider.provider.GetFunction(matcher, activation)); if (overload.has_value()) { if (result.has_value()) { return absl::Status(absl::StatusCode::kInternal, "Cannot resolve overloads"); } result.emplace(overload.value()); } } return result; } class EagerFunctionStep : public AbstractFunctionStep { public: EagerFunctionStep(std::vector<cel::FunctionOverloadReference> overloads, const std::string& name, size_t num_args, int64_t expr_id) : AbstractFunctionStep(name, num_args, expr_id), overloads_(std::move(overloads)) {} absl::StatusOr<ResolveResult> ResolveFunction( absl::Span<const cel::Value> input_args, const ExecutionFrame* frame) const override { return ResolveStatic(input_args, overloads_); } private: std::vector<cel::FunctionOverloadReference> overloads_; }; class LazyFunctionStep : public AbstractFunctionStep { public: LazyFunctionStep(const std::string& name, size_t num_args, bool receiver_style, std::vector<cel::FunctionRegistry::LazyOverload> providers, int64_t expr_id) : AbstractFunctionStep(name, num_args, expr_id), receiver_style_(receiver_style), providers_(std::move(providers)) {} absl::StatusOr<ResolveResult> ResolveFunction( absl::Span<const cel::Value> input_args, const ExecutionFrame* frame) const override; private: bool receiver_style_; std::vector<cel::FunctionRegistry::LazyOverload> providers_; }; absl::StatusOr<ResolveResult> LazyFunctionStep::ResolveFunction( absl::Span<const cel::Value> input_args, const ExecutionFrame* frame) const { return ResolveLazy(input_args, name_, receiver_style_, providers_, *frame); } class StaticResolver { public: explicit StaticResolver(std::vector<cel::FunctionOverloadReference> overloads) : overloads_(std::move(overloads)) {} absl::StatusOr<ResolveResult> Resolve(ExecutionFrameBase& frame, absl::Span<const Value> input) const { return ResolveStatic(input, overloads_); } private: std::vector<cel::FunctionOverloadReference> overloads_; }; class LazyResolver { public: explicit LazyResolver( std::vector<cel::FunctionRegistry::LazyOverload> providers, std::string name, bool receiver_style) : providers_(std::move(providers)), name_(std::move(name)), receiver_style_(receiver_style) {} absl::StatusOr<ResolveResult> Resolve(ExecutionFrameBase& frame, absl::Span<const Value> input) const { return ResolveLazy(input, name_, receiver_style_, providers_, frame); } private: std::vector<cel::FunctionRegistry::LazyOverload> providers_; std::string name_; bool receiver_style_; }; template <typename Resolver> class DirectFunctionStepImpl : public DirectExpressionStep { public: DirectFunctionStepImpl( int64_t expr_id, const std::string& name, std::vector<std::unique_ptr<DirectExpressionStep>> arg_steps, Resolver&& resolver) : DirectExpressionStep(expr_id), name_(name), arg_steps_(std::move(arg_steps)), resolver_(std::forward<Resolver>(resolver)) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& trail) const override { absl::InlinedVector<Value, 2> args; absl::InlinedVector<AttributeTrail, 2> arg_trails; args.resize(arg_steps_.size()); arg_trails.resize(arg_steps_.size()); for (size_t i = 0; i < arg_steps_.size(); i++) { CEL_RETURN_IF_ERROR( arg_steps_[i]->Evaluate(frame, args[i], arg_trails[i])); } if (frame.unknown_processing_enabled()) { for (size_t i = 0; i < arg_trails.size(); i++) { if (frame.attribute_utility().CheckForUnknown(arg_trails[i], true)) { args[i] = frame.attribute_utility().CreateUnknownSet( arg_trails[i].attribute()); } } } CEL_ASSIGN_OR_RETURN(ResolveResult resolved_function, resolver_.Resolve(frame, args)); if (resolved_function.has_value() && ShouldAcceptOverload(resolved_function->descriptor, args)) { CEL_ASSIGN_OR_RETURN(result, Invoke(*resolved_function, expr_id_, args, frame)); return absl::OkStatus(); } result = NoOverloadResult(name_, args, frame); return absl::OkStatus(); } absl::optional<std::vector<const DirectExpressionStep*>> GetDependencies() const override { std::vector<const DirectExpressionStep*> dependencies; dependencies.reserve(arg_steps_.size()); for (const auto& arg_step : arg_steps_) { dependencies.push_back(arg_step.get()); } return dependencies; } absl::optional<std::vector<std::unique_ptr<DirectExpressionStep>>> ExtractDependencies() override { return std::move(arg_steps_); } private: friend Resolver; std::string name_; std::vector<std::unique_ptr<DirectExpressionStep>> arg_steps_; Resolver resolver_; }; } std::unique_ptr<DirectExpressionStep> CreateDirectFunctionStep( int64_t expr_id, const cel::ast_internal::Call& call, std::vector<std::unique_ptr<DirectExpressionStep>> deps, std::vector<cel::FunctionOverloadReference> overloads) { return std::make_unique<DirectFunctionStepImpl<StaticResolver>>( expr_id, call.function(), std::move(deps), StaticResolver(std::move(overloads))); } std::unique_ptr<DirectExpressionStep> CreateDirectLazyFunctionStep( int64_t expr_id, const cel::ast_internal::Call& call, std::vector<std::unique_ptr<DirectExpressionStep>> deps, std::vector<cel::FunctionRegistry::LazyOverload> providers) { return std::make_unique<DirectFunctionStepImpl<LazyResolver>>( expr_id, call.function(), std::move(deps), LazyResolver(std::move(providers), call.function(), call.has_target())); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateFunctionStep( const cel::ast_internal::Call& call_expr, int64_t expr_id, std::vector<cel::FunctionRegistry::LazyOverload> lazy_overloads) { bool receiver_style = call_expr.has_target(); size_t num_args = call_expr.args().size() + (receiver_style ? 1 : 0); const std::string& name = call_expr.function(); return std::make_unique<LazyFunctionStep>(name, num_args, receiver_style, std::move(lazy_overloads), expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateFunctionStep( const cel::ast_internal::Call& call_expr, int64_t expr_id, std::vector<cel::FunctionOverloadReference> overloads) { bool receiver_style = call_expr.has_target(); size_t num_args = call_expr.args().size() + (receiver_style ? 1 : 0); const std::string& name = call_expr.function(); return std::make_unique<EagerFunctionStep>(std::move(overloads), name, num_args, expr_id); } }
#include "eval/eval/function_step.h" #include <cmath> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "base/ast_internal/expr.h" #include "base/builtins.h" #include "base/type_provider.h" #include "common/kind.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/const_value_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/internal/interop.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_function.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/portable_cel_function_adapter.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_message.pb.h" #include "extensions/protobuf/memory_manager.h" #include "internal/testing.h" #include "runtime/function_overload_reference.h" #include "runtime/function_registry.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" #include "runtime/standard_functions.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeProvider; using ::cel::ast_internal::Call; using ::cel::ast_internal::Expr; using ::cel::ast_internal::Ident; using testing::Eq; using testing::Not; using testing::Truly; using cel::internal::IsOk; using cel::internal::StatusIs; int GetExprId() { static int id = 0; id++; return id; } class ConstFunction : public CelFunction { public: explicit ConstFunction(const CelValue& value, absl::string_view name) : CelFunction(CreateDescriptor(name)), value_(value) {} static CelFunctionDescriptor CreateDescriptor(absl::string_view name) { return CelFunctionDescriptor{name, false, {}}; } static Call MakeCall(absl::string_view name) { Call call; call.set_function(std::string(name)); call.set_target(nullptr); return call; } absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { if (!args.empty()) { return absl::Status(absl::StatusCode::kInvalidArgument, "Bad arguments number"); } *result = value_; return absl::OkStatus(); } private: CelValue value_; }; enum class ShouldReturnUnknown : bool { kYes = true, kNo = false }; class AddFunction : public CelFunction { public: AddFunction() : CelFunction(CreateDescriptor()), should_return_unknown_(false) {} explicit AddFunction(ShouldReturnUnknown should_return_unknown) : CelFunction(CreateDescriptor()), should_return_unknown_(static_cast<bool>(should_return_unknown)) {} static CelFunctionDescriptor CreateDescriptor() { return CelFunctionDescriptor{ "_+_", false, {CelValue::Type::kInt64, CelValue::Type::kInt64}}; } static Call MakeCall() { Call call; call.set_function("_+_"); call.mutable_args().emplace_back(); call.mutable_args().emplace_back(); call.set_target(nullptr); return call; } absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { if (args.size() != 2 || !args[0].IsInt64() || !args[1].IsInt64()) { return absl::Status(absl::StatusCode::kInvalidArgument, "Mismatched arguments passed to method"); } if (should_return_unknown_) { *result = CreateUnknownFunctionResultError(arena, "Add can't be resolved."); return absl::OkStatus(); } int64_t arg0 = args[0].Int64OrDie(); int64_t arg1 = args[1].Int64OrDie(); *result = CelValue::CreateInt64(arg0 + arg1); return absl::OkStatus(); } private: bool should_return_unknown_; }; class SinkFunction : public CelFunction { public: explicit SinkFunction(CelValue::Type type, bool is_strict = true) : CelFunction(CreateDescriptor(type, is_strict)) {} static CelFunctionDescriptor CreateDescriptor(CelValue::Type type, bool is_strict = true) { return CelFunctionDescriptor{"Sink", false, {type}, is_strict}; } static Call MakeCall() { Call call; call.set_function("Sink"); call.mutable_args().emplace_back(); call.set_target(nullptr); return call; } absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { *result = CelValue::CreateInt64(0); return absl::OkStatus(); } }; void AddDefaults(CelFunctionRegistry& registry) { static UnknownSet* unknown_set = new UnknownSet(); EXPECT_TRUE(registry .Register(std::make_unique<ConstFunction>( CelValue::CreateInt64(3), "Const3")) .ok()); EXPECT_TRUE(registry .Register(std::make_unique<ConstFunction>( CelValue::CreateInt64(2), "Const2")) .ok()); EXPECT_TRUE(registry .Register(std::make_unique<ConstFunction>( CelValue::CreateUnknownSet(unknown_set), "ConstUnknown")) .ok()); EXPECT_TRUE(registry.Register(std::make_unique<AddFunction>()).ok()); EXPECT_TRUE( registry.Register(std::make_unique<SinkFunction>(CelValue::Type::kList)) .ok()); EXPECT_TRUE( registry.Register(std::make_unique<SinkFunction>(CelValue::Type::kMap)) .ok()); EXPECT_TRUE( registry .Register(std::make_unique<SinkFunction>(CelValue::Type::kMessage)) .ok()); } std::vector<CelValue::Type> ArgumentMatcher(int argument_count) { std::vector<CelValue::Type> argument_matcher(argument_count); for (int i = 0; i < argument_count; i++) { argument_matcher[i] = CelValue::Type::kAny; } return argument_matcher; } std::vector<CelValue::Type> ArgumentMatcher(const Call& call) { return ArgumentMatcher(call.has_target() ? call.args().size() + 1 : call.args().size()); } std::unique_ptr<CelExpressionFlatImpl> CreateExpressionImpl( const cel::RuntimeOptions& options, std::unique_ptr<DirectExpressionStep> expr) { ExecutionPath path; path.push_back(std::make_unique<WrappedDirectStep>(std::move(expr), -1)); return std::make_unique<CelExpressionFlatImpl>( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); } absl::StatusOr<std::unique_ptr<ExpressionStep>> MakeTestFunctionStep( const Call& call, const CelFunctionRegistry& registry) { auto argument_matcher = ArgumentMatcher(call); auto lazy_overloads = registry.ModernFindLazyOverloads( call.function(), call.has_target(), argument_matcher); if (!lazy_overloads.empty()) { return CreateFunctionStep(call, GetExprId(), lazy_overloads); } auto overloads = registry.FindStaticOverloads( call.function(), call.has_target(), argument_matcher); return CreateFunctionStep(call, GetExprId(), overloads); } class FunctionStepTest : public testing::TestWithParam<UnknownProcessingOptions> { public: std::unique_ptr<CelExpressionFlatImpl> GetExpression(ExecutionPath&& path) { cel::RuntimeOptions options; options.unknown_processing = GetParam(); return std::make_unique<CelExpressionFlatImpl>( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); } }; TEST_P(FunctionStepTest, SimpleFunctionTest) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); Call call1 = ConstFunction::MakeCall("Const3"); Call call2 = ConstFunction::MakeCall("Const2"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsInt64()); EXPECT_THAT(value.Int64OrDie(), Eq(5)); } TEST_P(FunctionStepTest, TestStackUnderflow) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); AddFunction add_func; Call call1 = ConstFunction::MakeCall("Const3"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; EXPECT_THAT(impl->Evaluate(activation, &arena), Not(IsOk())); } TEST_P(FunctionStepTest, TestNoMatchingOverloadsDuringEvaluation) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); ASSERT_TRUE(registry .Register(std::make_unique<ConstFunction>( CelValue::CreateUint64(4), "Const4")) .ok()); Call call1 = ConstFunction::MakeCall("Const3"); Call call2 = ConstFunction::MakeCall("Const4"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsError()); EXPECT_THAT(*value.ErrorOrDie(), StatusIs(absl::StatusCode::kUnknown, testing::HasSubstr("_+_(int64, uint64)"))); } TEST_P(FunctionStepTest, TestNoMatchingOverloadsUnexpectedArgCount) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); Call call1 = ConstFunction::MakeCall("Const3"); Call add_call = AddFunction::MakeCall(); add_call.mutable_args().emplace_back(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN( auto step3, CreateFunctionStep(add_call, -1, registry.FindStaticOverloads( add_call.function(), false, {cel::Kind::kInt64, cel::Kind::kInt64}))); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); path.push_back(std::move(step3)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsError()); EXPECT_THAT(*value.ErrorOrDie(), StatusIs(absl::StatusCode::kUnknown, testing::HasSubstr("_+_(int64, int64, int64)"))); } TEST_P(FunctionStepTest, TestNoMatchingOverloadsDuringEvaluationErrorForwarding) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); CelError error0 = absl::CancelledError(); CelError error1 = absl::CancelledError(); ASSERT_TRUE(registry .Register(std::make_unique<ConstFunction>( CelValue::CreateError(&error0), "ConstError1")) .ok()); ASSERT_TRUE(registry .Register(std::make_unique<ConstFunction>( CelValue::CreateError(&error1), "ConstError2")) .ok()); Call call1 = ConstFunction::MakeCall("ConstError1"); Call call2 = ConstFunction::MakeCall("ConstError2"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsError()); EXPECT_THAT(*value.ErrorOrDie(), Eq(error0)); } TEST_P(FunctionStepTest, LazyFunctionTest) { ExecutionPath path; Activation activation; CelFunctionRegistry registry; ASSERT_OK( registry.RegisterLazyFunction(ConstFunction::CreateDescriptor("Const3"))); ASSERT_OK(activation.InsertFunction( std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3"))); ASSERT_OK( registry.RegisterLazyFunction(ConstFunction::CreateDescriptor("Const2"))); ASSERT_OK(activation.InsertFunction( std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2"))); ASSERT_OK(registry.Register(std::make_unique<AddFunction>())); Call call1 = ConstFunction::MakeCall("Const3"); Call call2 = ConstFunction::MakeCall("Const2"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsInt64()); EXPECT_THAT(value.Int64OrDie(), Eq(5)); } TEST_P(FunctionStepTest, LazyFunctionOverloadingTest) { ExecutionPath path; Activation activation; CelFunctionRegistry registry; auto floor_int = PortableUnaryFunctionAdapter<int64_t, int64_t>::Create( "Floor", false, [](google::protobuf::Arena*, int64_t val) { return val; }); auto floor_double = PortableUnaryFunctionAdapter<int64_t, double>::Create( "Floor", false, [](google::protobuf::Arena*, double val) { return std::floor(val); }); ASSERT_OK(registry.RegisterLazyFunction(floor_int->descriptor())); ASSERT_OK(activation.InsertFunction(std::move(floor_int))); ASSERT_OK(registry.RegisterLazyFunction(floor_double->descriptor())); ASSERT_OK(activation.InsertFunction(std::move(floor_double))); ASSERT_OK(registry.Register( PortableBinaryFunctionAdapter<bool, int64_t, int64_t>::Create( "_<_", false, [](google::protobuf::Arena*, int64_t lhs, int64_t rhs) -> bool { return lhs < rhs; }))); cel::ast_internal::Constant lhs; lhs.set_int64_value(20); cel::ast_internal::Constant rhs; rhs.set_double_value(21.9); cel::ast_internal::Call call1; call1.mutable_args().emplace_back(); call1.set_function("Floor"); cel::ast_internal::Call call2; call2.mutable_args().emplace_back(); call2.set_function("Floor"); cel::ast_internal::Call lt_call; lt_call.mutable_args().emplace_back(); lt_call.mutable_args().emplace_back(); lt_call.set_function("_<_"); ASSERT_OK_AND_ASSIGN( auto step0, CreateConstValueStep(cel::interop_internal::CreateIntValue(20), -1)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN( auto step2, CreateConstValueStep(cel::interop_internal::CreateDoubleValue(21.9), -1)); ASSERT_OK_AND_ASSIGN(auto step3, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step4, MakeTestFunctionStep(lt_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); path.push_back(std::move(step3)); path.push_back(std::move(step4)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsBool()); EXPECT_TRUE(value.BoolOrDie()); } TEST_P(FunctionStepTest, TestNoMatchingOverloadsDuringEvaluationErrorForwardingLazy) { ExecutionPath path; Activation activation; google::protobuf::Arena arena; CelFunctionRegistry registry; AddDefaults(registry); CelError error0 = absl::CancelledError(); CelError error1 = absl::CancelledError(); ASSERT_OK(registry.RegisterLazyFunction( ConstFunction::CreateDescriptor("ConstError1"))); ASSERT_OK(activation.InsertFunction(std::make_unique<ConstFunction>( CelValue::CreateError(&error0), "ConstError1"))); ASSERT_OK(registry.RegisterLazyFunction( ConstFunction::CreateDescriptor("ConstError2"))); ASSERT_OK(activation.InsertFunction(std::make_unique<ConstFunction>( CelValue::CreateError(&error1), "ConstError2"))); Call call1 = ConstFunction::MakeCall("ConstError1"); Call call2 = ConstFunction::MakeCall("ConstError2"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsError()); EXPECT_THAT(*value.ErrorOrDie(), Eq(error0)); } std::string TestNameFn(testing::TestParamInfo<UnknownProcessingOptions> opt) { switch (opt.param) { case UnknownProcessingOptions::kDisabled: return "disabled"; case UnknownProcessingOptions::kAttributeOnly: return "attribute_only"; case UnknownProcessingOptions::kAttributeAndFunction: return "attribute_and_function"; } return ""; } INSTANTIATE_TEST_SUITE_P( UnknownSupport, FunctionStepTest, testing::Values(UnknownProcessingOptions::kDisabled, UnknownProcessingOptions::kAttributeOnly, UnknownProcessingOptions::kAttributeAndFunction), &TestNameFn); class FunctionStepTestUnknowns : public testing::TestWithParam<UnknownProcessingOptions> { public: std::unique_ptr<CelExpressionFlatImpl> GetExpression(ExecutionPath&& path) { cel::RuntimeOptions options; options.unknown_processing = GetParam(); return std::make_unique<CelExpressionFlatImpl>( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); } }; TEST_P(FunctionStepTestUnknowns, PassedUnknownTest) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); Call call1 = ConstFunction::MakeCall("Const3"); Call call2 = ConstFunction::MakeCall("ConstUnknown"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsUnknownSet()); } TEST_P(FunctionStepTestUnknowns, PartialUnknownHandlingTest) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); Ident ident1; ident1.set_name("param"); Call call1 = SinkFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident1, GetExprId())); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call1, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; TestMessage msg; google::protobuf::Arena arena; activation.InsertValue("param", CelProtoWrapper::CreateMessage(&msg, &arena)); CelAttributePattern pattern( "param", {CreateCelAttributeQualifierPattern(CelValue::CreateBool(true))}); activation.set_unknown_attribute_patterns({pattern}); ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsUnknownSet()); } TEST_P(FunctionStepTestUnknowns, UnknownVsErrorPrecedenceTest) { ExecutionPath path; CelFunctionRegistry registry; AddDefaults(registry); CelError error0 = absl::CancelledError(); CelValue error_value = CelValue::CreateError(&error0); ASSERT_TRUE( registry .Register(std::make_unique<ConstFunction>(error_value, "ConstError")) .ok()); Call call1 = ConstFunction::MakeCall("ConstError"); Call call2 = ConstFunction::MakeCall("ConstUnknown"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); std::unique_ptr<CelExpressionFlatImpl> impl = GetExpression(std::move(path)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl->Evaluate(activation, &arena)); ASSERT_TRUE(value.IsError()); ASSERT_EQ(*value.ErrorOrDie(), *error_value.ErrorOrDie()); } INSTANTIATE_TEST_SUITE_P( UnknownFunctionSupport, FunctionStepTestUnknowns, testing::Values(UnknownProcessingOptions::kAttributeOnly, UnknownProcessingOptions::kAttributeAndFunction), &TestNameFn); TEST(FunctionStepTestUnknownFunctionResults, CaptureArgs) { ExecutionPath path; CelFunctionRegistry registry; ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2"))); ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3"))); ASSERT_OK(registry.Register( std::make_unique<AddFunction>(ShouldReturnUnknown::kYes))); Call call1 = ConstFunction::MakeCall("Const2"); Call call2 = ConstFunction::MakeCall("Const3"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeAndFunction; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena)); ASSERT_TRUE(value.IsUnknownSet()); } TEST(FunctionStepTestUnknownFunctionResults, MergeDownCaptureArgs) { ExecutionPath path; CelFunctionRegistry registry; ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2"))); ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3"))); ASSERT_OK(registry.Register( std::make_unique<AddFunction>(ShouldReturnUnknown::kYes))); Call call1 = ConstFunction::MakeCall("Const2"); Call call2 = ConstFunction::MakeCall("Const3"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); ASSERT_OK_AND_ASSIGN(auto step3, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step4, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step5, MakeTestFunctionStep(add_call, registry)); ASSERT_OK_AND_ASSIGN(auto step6, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); path.push_back(std::move(step3)); path.push_back(std::move(step4)); path.push_back(std::move(step5)); path.push_back(std::move(step6)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeAndFunction; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena)); ASSERT_TRUE(value.IsUnknownSet()); } TEST(FunctionStepTestUnknownFunctionResults, MergeCaptureArgs) { ExecutionPath path; CelFunctionRegistry registry; ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(CelValue::CreateInt64(2), "Const2"))); ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(CelValue::CreateInt64(3), "Const3"))); ASSERT_OK(registry.Register( std::make_unique<AddFunction>(ShouldReturnUnknown::kYes))); Call call1 = ConstFunction::MakeCall("Const2"); Call call2 = ConstFunction::MakeCall("Const3"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); ASSERT_OK_AND_ASSIGN(auto step3, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step4, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step5, MakeTestFunctionStep(add_call, registry)); ASSERT_OK_AND_ASSIGN(auto step6, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); path.push_back(std::move(step3)); path.push_back(std::move(step4)); path.push_back(std::move(step5)); path.push_back(std::move(step6)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeAndFunction; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena)); ASSERT_TRUE(value.IsUnknownSet()) << *(value.ErrorOrDie()); } TEST(FunctionStepTestUnknownFunctionResults, UnknownVsErrorPrecedenceTest) { ExecutionPath path; CelFunctionRegistry registry; CelError error0 = absl::CancelledError(); CelValue error_value = CelValue::CreateError(&error0); UnknownSet unknown_set; CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set); ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(error_value, "ConstError"))); ASSERT_OK(registry.Register( std::make_unique<ConstFunction>(unknown_value, "ConstUnknown"))); ASSERT_OK(registry.Register( std::make_unique<AddFunction>(ShouldReturnUnknown::kYes))); Call call1 = ConstFunction::MakeCall("ConstError"); Call call2 = ConstFunction::MakeCall("ConstUnknown"); Call add_call = AddFunction::MakeCall(); ASSERT_OK_AND_ASSIGN(auto step0, MakeTestFunctionStep(call1, registry)); ASSERT_OK_AND_ASSIGN(auto step1, MakeTestFunctionStep(call2, registry)); ASSERT_OK_AND_ASSIGN(auto step2, MakeTestFunctionStep(add_call, registry)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeAndFunction; CelExpressionFlatImpl impl(FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue value, impl.Evaluate(activation, &arena)); ASSERT_TRUE(value.IsError()); ASSERT_EQ(*value.ErrorOrDie(), *error_value.ErrorOrDie()); } class MessageFunction : public CelFunction { public: MessageFunction() : CelFunction( CelFunctionDescriptor("Fn", false, {CelValue::Type::kMessage})) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { if (args.size() != 1 || !args.at(0).IsMessage()) { return absl::Status(absl::StatusCode::kInvalidArgument, "Bad arguments number"); } *result = CelValue::CreateStringView("message"); return absl::OkStatus(); } }; class MessageIdentityFunction : public CelFunction { public: MessageIdentityFunction() : CelFunction( CelFunctionDescriptor("Fn", false, {CelValue::Type::kMessage})) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { if (args.size() != 1 || !args.at(0).IsMessage()) { return absl::Status(absl::StatusCode::kInvalidArgument, "Bad arguments number"); } *result = args.at(0); return absl::OkStatus(); } }; class NullFunction : public CelFunction { public: NullFunction() : CelFunction( CelFunctionDescriptor("Fn", false, {CelValue::Type::kNullType})) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result, google::protobuf::Arena* arena) const override { if (args.size() != 1 || args.at(0).type() != CelValue::Type::kNullType) {
122
cpp
google/cel-cpp
create_list_step
eval/eval/create_list_step.cc
eval/eval/create_list_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_CREATE_LIST_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_CREATE_LIST_STEP_H_ #include <cstdint> #include <memory> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/statusor.h" #include "base/ast_internal/expr.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectListStep( std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateCreateListStep( const cel::ast_internal::CreateList& create_list_expr, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateMutableListStep(int64_t expr_id); std::unique_ptr<DirectExpressionStep> CreateDirectMutableListStep( int64_t expr_id); } #endif #include "eval/eval/create_list_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "base/ast_internal/expr.h" #include "common/casting.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/attribute_utility.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "internal/status_macros.h" #include "runtime/internal/mutable_list_impl.h" namespace google::api::expr::runtime { namespace { using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::ListValueBuilderInterface; using ::cel::UnknownValue; using ::cel::Value; using ::cel::runtime_internal::MutableListValue; class CreateListStep : public ExpressionStepBase { public: CreateListStep(int64_t expr_id, int list_size, absl::flat_hash_set<int> optional_indices) : ExpressionStepBase(expr_id), list_size_(list_size), optional_indices_(std::move(optional_indices)) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: int list_size_; absl::flat_hash_set<int32_t> optional_indices_; }; absl::Status CreateListStep::Evaluate(ExecutionFrame* frame) const { if (list_size_ < 0) { return absl::Status(absl::StatusCode::kInternal, "CreateListStep: list size is <0"); } if (!frame->value_stack().HasEnough(list_size_)) { return absl::Status(absl::StatusCode::kInternal, "CreateListStep: stack underflow"); } auto args = frame->value_stack().GetSpan(list_size_); cel::Value result; for (const auto& arg : args) { if (arg->Is<cel::ErrorValue>()) { result = arg; frame->value_stack().Pop(list_size_); frame->value_stack().Push(std::move(result)); return absl::OkStatus(); } } if (frame->enable_unknowns()) { absl::optional<UnknownValue> unknown_set = frame->attribute_utility().IdentifyAndMergeUnknowns( args, frame->value_stack().GetAttributeSpan(list_size_), true); if (unknown_set.has_value()) { frame->value_stack().Pop(list_size_); frame->value_stack().Push(std::move(unknown_set).value()); return absl::OkStatus(); } } CEL_ASSIGN_OR_RETURN(auto builder, frame->value_manager().NewListValueBuilder( frame->value_manager().GetDynListType())); builder->Reserve(args.size()); for (size_t i = 0; i < args.size(); ++i) { auto& arg = args[i]; if (optional_indices_.contains(static_cast<int32_t>(i))) { if (auto optional_arg = cel::As<cel::OptionalValue>(arg); optional_arg) { if (!optional_arg->HasValue()) { continue; } CEL_RETURN_IF_ERROR(builder->Add(optional_arg->Value())); } else { return cel::TypeConversionError(arg.GetTypeName(), "optional_type") .NativeValue(); } } else { CEL_RETURN_IF_ERROR(builder->Add(std::move(arg))); } } frame->value_stack().PopAndPush(list_size_, std::move(*builder).Build()); return absl::OkStatus(); } absl::flat_hash_set<int32_t> MakeOptionalIndicesSet( const cel::ast_internal::CreateList& create_list_expr) { absl::flat_hash_set<int32_t> optional_indices; for (size_t i = 0; i < create_list_expr.elements().size(); ++i) { if (create_list_expr.elements()[i].optional()) { optional_indices.insert(static_cast<int32_t>(i)); } } return optional_indices; } class CreateListDirectStep : public DirectExpressionStep { public: CreateListDirectStep( std::vector<std::unique_ptr<DirectExpressionStep>> elements, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) : DirectExpressionStep(expr_id), elements_(std::move(elements)), optional_indices_(std::move(optional_indices)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute_trail) const override { CEL_ASSIGN_OR_RETURN(auto builder, frame.value_manager().NewListValueBuilder( frame.value_manager().GetDynListType())); builder->Reserve(elements_.size()); AttributeUtility::Accumulator unknowns = frame.attribute_utility().CreateAccumulator(); AttributeTrail tmp_attr; for (size_t i = 0; i < elements_.size(); ++i) { const auto& element = elements_[i]; CEL_RETURN_IF_ERROR(element->Evaluate(frame, result, tmp_attr)); if (cel::InstanceOf<ErrorValue>(result)) return absl::OkStatus(); if (frame.attribute_tracking_enabled()) { if (frame.missing_attribute_errors_enabled()) { if (frame.attribute_utility().CheckForMissingAttribute(tmp_attr)) { CEL_ASSIGN_OR_RETURN( result, frame.attribute_utility().CreateMissingAttributeError( tmp_attr.attribute())); return absl::OkStatus(); } } if (frame.unknown_processing_enabled()) { if (InstanceOf<UnknownValue>(result)) { unknowns.Add(Cast<UnknownValue>(result)); } if (frame.attribute_utility().CheckForUnknown(tmp_attr, true)) { unknowns.Add(tmp_attr); } } } if (optional_indices_.contains(static_cast<int32_t>(i))) { if (auto optional_arg = cel::As<cel::OptionalValue>(static_cast<const Value&>(result)); optional_arg) { if (!optional_arg->HasValue()) { continue; } CEL_RETURN_IF_ERROR(builder->Add(optional_arg->Value())); continue; } return cel::TypeConversionError(result.GetTypeName(), "optional_type") .NativeValue(); } CEL_RETURN_IF_ERROR(builder->Add(std::move(result))); } if (!unknowns.IsEmpty()) { result = std::move(unknowns).Build(); return absl::OkStatus(); } result = std::move(*builder).Build(); return absl::OkStatus(); } private: std::vector<std::unique_ptr<DirectExpressionStep>> elements_; absl::flat_hash_set<int32_t> optional_indices_; }; class MutableListStep : public ExpressionStepBase { public: explicit MutableListStep(int64_t expr_id) : ExpressionStepBase(expr_id) {} absl::Status Evaluate(ExecutionFrame* frame) const override; }; absl::Status MutableListStep::Evaluate(ExecutionFrame* frame) const { CEL_ASSIGN_OR_RETURN(auto builder, frame->value_manager().NewListValueBuilder( frame->value_manager().GetDynListType())); frame->value_stack().Push(cel::OpaqueValue{ frame->value_manager().GetMemoryManager().MakeShared<MutableListValue>( std::move(builder))}); return absl::OkStatus(); } class DirectMutableListStep : public DirectExpressionStep { public: explicit DirectMutableListStep(int64_t expr_id) : DirectExpressionStep(expr_id) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override; }; absl::Status DirectMutableListStep::Evaluate( ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute_trail) const { CEL_ASSIGN_OR_RETURN(auto builder, frame.value_manager().NewListValueBuilder( frame.value_manager().GetDynListType())); result = cel::OpaqueValue{ frame.value_manager().GetMemoryManager().MakeShared<MutableListValue>( std::move(builder))}; return absl::OkStatus(); } } std::unique_ptr<DirectExpressionStep> CreateDirectListStep( std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) { return std::make_unique<CreateListDirectStep>( std::move(deps), std::move(optional_indices), expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateCreateListStep( const cel::ast_internal::CreateList& create_list_expr, int64_t expr_id) { return std::make_unique<CreateListStep>( expr_id, create_list_expr.elements().size(), MakeOptionalIndicesSet(create_list_expr)); } std::unique_ptr<ExpressionStep> CreateMutableListStep(int64_t expr_id) { return std::make_unique<MutableListStep>(expr_id); } std::unique_ptr<DirectExpressionStep> CreateDirectMutableListStep( int64_t expr_id) { return std::make_unique<DirectMutableListStep>(expr_id); } }
#include "eval/eval/create_list_step.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "base/ast_internal/expr.h" #include "base/attribute.h" #include "base/attribute_set.h" #include "base/type_provider.h" #include "common/casting.h" #include "common/memory.h" #include "common/value.h" #include "common/value_testing.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/const_value_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/internal/interop.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "eval/public/testing/matchers.h" #include "eval/public/unknown_attribute_set.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::Attribute; using ::cel::AttributeQualifier; using ::cel::AttributeSet; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ListValue; using ::cel::TypeProvider; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ast_internal::Expr; using ::cel::test::IntValueIs; using testing::Eq; using testing::HasSubstr; using testing::Not; using testing::UnorderedElementsAre; using cel::internal::IsOk; using cel::internal::IsOkAndHolds; using cel::internal::StatusIs; absl::StatusOr<CelValue> RunExpression(const std::vector<int64_t>& values, google::protobuf::Arena* arena, bool enable_unknowns) { ExecutionPath path; Expr dummy_expr; auto& create_list = dummy_expr.mutable_list_expr(); for (auto value : values) { auto& expr0 = create_list.mutable_elements().emplace_back().mutable_expr(); expr0.mutable_const_expr().set_int64_value(value); CEL_ASSIGN_OR_RETURN( auto const_step, CreateConstValueStep(cel::interop_internal::CreateIntValue(value), -1)); path.push_back(std::move(const_step)); } CEL_ASSIGN_OR_RETURN(auto step, CreateCreateListStep(create_list, dummy_expr.id())); path.push_back(std::move(step)); cel::RuntimeOptions options; if (enable_unknowns) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; return cel_expr.Evaluate(activation, arena); } absl::StatusOr<CelValue> RunExpressionWithCelValues( const std::vector<CelValue>& values, google::protobuf::Arena* arena, bool enable_unknowns) { ExecutionPath path; Expr dummy_expr; Activation activation; auto& create_list = dummy_expr.mutable_list_expr(); int ind = 0; for (auto value : values) { std::string var_name = absl::StrCat("name_", ind++); auto& expr0 = create_list.mutable_elements().emplace_back().mutable_expr(); expr0.set_id(ind); expr0.mutable_ident_expr().set_name(var_name); CEL_ASSIGN_OR_RETURN(auto ident_step, CreateIdentStep(expr0.ident_expr(), expr0.id())); path.push_back(std::move(ident_step)); activation.InsertValue(var_name, value); } CEL_ASSIGN_OR_RETURN(auto step0, CreateCreateListStep(create_list, dummy_expr.id())); path.push_back(std::move(step0)); cel::RuntimeOptions options; if (enable_unknowns) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); return cel_expr.Evaluate(activation, arena); } class CreateListStepTest : public testing::TestWithParam<bool> {}; TEST(CreateListStepTest, TestCreateListStackUnderflow) { ExecutionPath path; Expr dummy_expr; auto& create_list = dummy_expr.mutable_list_expr(); auto& expr0 = create_list.mutable_elements().emplace_back().mutable_expr(); expr0.mutable_const_expr().set_int64_value(1); ASSERT_OK_AND_ASSIGN(auto step0, CreateCreateListStep(create_list, dummy_expr.id())); path.push_back(std::move(step0)); CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); Activation activation; google::protobuf::Arena arena; auto status = cel_expr.Evaluate(activation, &arena); ASSERT_THAT(status, Not(IsOk())); } TEST_P(CreateListStepTest, CreateListEmpty) { google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression({}, &arena, GetParam())); ASSERT_TRUE(result.IsList()); EXPECT_THAT(result.ListOrDie()->size(), Eq(0)); } TEST_P(CreateListStepTest, CreateListOne) { google::protobuf::Arena arena; ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression({100}, &arena, GetParam())); ASSERT_TRUE(result.IsList()); const auto& list = *result.ListOrDie(); ASSERT_THAT(list.size(), Eq(1)); const CelValue& value = list.Get(&arena, 0); EXPECT_THAT(value, test::IsCelInt64(100)); } TEST_P(CreateListStepTest, CreateListWithError) { google::protobuf::Arena arena; std::vector<CelValue> values; CelError error = absl::InvalidArgumentError("bad arg"); values.push_back(CelValue::CreateError(&error)); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpressionWithCelValues(values, &arena, GetParam())); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), Eq(absl::InvalidArgumentError("bad arg"))); } TEST_P(CreateListStepTest, CreateListWithErrorAndUnknown) { google::protobuf::Arena arena; std::vector<CelValue> values; Expr expr0; expr0.mutable_ident_expr().set_name("name0"); CelAttribute attr0(expr0.ident_expr().name(), {}); UnknownSet unknown_set0(UnknownAttributeSet({attr0})); values.push_back(CelValue::CreateUnknownSet(&unknown_set0)); CelError error = absl::InvalidArgumentError("bad arg"); values.push_back(CelValue::CreateError(&error)); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpressionWithCelValues(values, &arena, GetParam())); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), Eq(absl::InvalidArgumentError("bad arg"))); } TEST_P(CreateListStepTest, CreateListHundred) { google::protobuf::Arena arena; std::vector<int64_t> values; for (size_t i = 0; i < 100; i++) { values.push_back(i); } ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(values, &arena, GetParam())); ASSERT_TRUE(result.IsList()); const auto& list = *result.ListOrDie(); EXPECT_THAT(list.size(), Eq(static_cast<int>(values.size()))); for (size_t i = 0; i < values.size(); i++) { EXPECT_THAT(list.Get(&arena, i), test::IsCelInt64(values[i])); } } INSTANTIATE_TEST_SUITE_P(CombinedCreateListTest, CreateListStepTest, testing::Bool()); TEST(CreateListStepTest, CreateListHundredAnd2Unknowns) { google::protobuf::Arena arena; std::vector<CelValue> values; Expr expr0; expr0.mutable_ident_expr().set_name("name0"); CelAttribute attr0(expr0.ident_expr().name(), {}); Expr expr1; expr1.mutable_ident_expr().set_name("name1"); CelAttribute attr1(expr1.ident_expr().name(), {}); UnknownSet unknown_set0(UnknownAttributeSet({attr0})); UnknownSet unknown_set1(UnknownAttributeSet({attr1})); for (size_t i = 0; i < 100; i++) { values.push_back(CelValue::CreateInt64(i)); } values.push_back(CelValue::CreateUnknownSet(&unknown_set0)); values.push_back(CelValue::CreateUnknownSet(&unknown_set1)); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpressionWithCelValues(values, &arena, true)); ASSERT_TRUE(result.IsUnknownSet()); const UnknownSet* result_set = result.UnknownSetOrDie(); EXPECT_THAT(result_set->unknown_attributes().size(), Eq(2)); } TEST(CreateDirectListStep, Basic) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; ExecutionFrameBase frame(activation, options, value_factory.get()); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateConstValueDirectStep(IntValue(1), -1)); deps.push_back(CreateConstValueDirectStep(IntValue(2), -1)); auto step = CreateDirectListStep(std::move(deps), {}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<ListValue>(result)); EXPECT_THAT(Cast<ListValue>(result).Size(), IsOkAndHolds(2)); } TEST(CreateDirectListStep, ForwardFirstError) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; ExecutionFrameBase frame(activation, options, value_factory.get()); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateConstValueDirectStep( value_factory.get().CreateErrorValue(absl::InternalError("test1")), -1)); deps.push_back(CreateConstValueDirectStep( value_factory.get().CreateErrorValue(absl::InternalError("test2")), -1)); auto step = CreateDirectListStep(std::move(deps), {}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kInternal, "test1")); } std::vector<std::string> UnknownAttrNames(const UnknownValue& v) { std::vector<std::string> names; names.reserve(v.attribute_set().size()); for (const auto& attr : v.attribute_set()) { EXPECT_OK(attr.AsString().status()); names.push_back(attr.AsString().value_or("<empty>")); } return names; } TEST(CreateDirectListStep, MergeUnknowns) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; ExecutionFrameBase frame(activation, options, value_factory.get()); AttributeSet attr_set1({Attribute("var1")}); AttributeSet attr_set2({Attribute("var2")}); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateConstValueDirectStep( value_factory.get().CreateUnknownValue(std::move(attr_set1)), -1)); deps.push_back(CreateConstValueDirectStep( value_factory.get().CreateUnknownValue(std::move(attr_set2)), -1)); auto step = CreateDirectListStep(std::move(deps), {}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<UnknownValue>(result)); EXPECT_THAT(UnknownAttrNames(Cast<UnknownValue>(result)), UnorderedElementsAre("var1", "var2")); } TEST(CreateDirectListStep, ErrorBeforeUnknown) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; ExecutionFrameBase frame(activation, options, value_factory.get()); AttributeSet attr_set1({Attribute("var1")}); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateConstValueDirectStep( value_factory.get().CreateErrorValue(absl::InternalError("test1")), -1)); deps.push_back(CreateConstValueDirectStep( value_factory.get().CreateErrorValue(absl::InternalError("test2")), -1)); auto step = CreateDirectListStep(std::move(deps), {}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kInternal, "test1")); } class SetAttrDirectStep : public DirectExpressionStep { public: explicit SetAttrDirectStep(Attribute attr) : DirectExpressionStep(-1), attr_(std::move(attr)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attr) const override { result = frame.value_manager().GetNullValue(); attr = AttributeTrail(attr_); return absl::OkStatus(); } private: cel::Attribute attr_; }; TEST(CreateDirectListStep, MissingAttribute) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; options.enable_missing_attribute_errors = true; activation.SetMissingPatterns({cel::AttributePattern( "var1", {cel::AttributeQualifierPattern::OfString("field1")})}); ExecutionFrameBase frame(activation, options, value_factory.get()); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back( CreateConstValueDirectStep(value_factory.get().GetNullValue(), -1)); deps.push_back(std::make_unique<SetAttrDirectStep>( Attribute("var1", {AttributeQualifier::OfString("field1")}))); auto step = CreateDirectListStep(std::move(deps), {}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT( Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("var1.field1"))); } TEST(CreateDirectListStep, OptionalPresentSet) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; ExecutionFrameBase frame(activation, options, value_factory.get()); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateConstValueDirectStep(IntValue(1), -1)); deps.push_back(CreateConstValueDirectStep( cel::OptionalValue::Of(value_factory.get().GetMemoryManager(), IntValue(2)), -1)); auto step = CreateDirectListStep(std::move(deps), {1}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<ListValue>(result)); auto list = Cast<ListValue>(result); EXPECT_THAT(list.Size(), IsOkAndHolds(2)); EXPECT_THAT(list.Get(value_factory.get(), 0), IsOkAndHolds(IntValueIs(1))); EXPECT_THAT(list.Get(value_factory.get(), 1), IsOkAndHolds(IntValueIs(2))); } TEST(CreateDirectListStep, OptionalAbsentNotSet) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; ExecutionFrameBase frame(activation, options, value_factory.get()); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back(CreateConstValueDirectStep(IntValue(1), -1)); deps.push_back(CreateConstValueDirectStep(cel::OptionalValue::None(), -1)); auto step = CreateDirectListStep(std::move(deps), {1}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<ListValue>(result)); auto list = Cast<ListValue>(result); EXPECT_THAT(list.Size(), IsOkAndHolds(1)); EXPECT_THAT(list.Get(value_factory.get(), 0), IsOkAndHolds(IntValueIs(1))); } TEST(CreateDirectListStep, PartialUnknown) { cel::ManagedValueFactory value_factory( cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); cel::Activation activation; cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; activation.SetUnknownPatterns({cel::AttributePattern( "var1", {cel::AttributeQualifierPattern::OfString("field1")})}); ExecutionFrameBase frame(activation, options, value_factory.get()); std::vector<std::unique_ptr<DirectExpressionStep>> deps; deps.push_back( CreateConstValueDirectStep(value_factory.get().CreateIntValue(1), -1)); deps.push_back(std::make_unique<SetAttrDirectStep>(Attribute("var1", {}))); auto step = CreateDirectListStep(std::move(deps), {}, -1); cel::Value result; AttributeTrail attr; ASSERT_OK(step->Evaluate(frame, result, attr)); ASSERT_TRUE(InstanceOf<UnknownValue>(result)); EXPECT_THAT(UnknownAttrNames(Cast<UnknownValue>(result)), UnorderedElementsAre("var1")); } } }
123
cpp
google/cel-cpp
create_map_step
eval/eval/create_map_step.cc
eval/eval/create_map_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_CREATE_MAP_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_CREATE_MAP_STEP_H_ #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/statusor.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectCreateMapStep( std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateCreateStructStepForMap( size_t entry_count, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id); } #endif #include "eval/eval/create_map_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/casting.h" #include "common/memory.h" #include "common/type.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::StructValueBuilderInterface; using ::cel::UnknownValue; using ::cel::Value; class CreateStructStepForMap final : public ExpressionStepBase { public: CreateStructStepForMap(int64_t expr_id, size_t entry_count, absl::flat_hash_set<int32_t> optional_indices) : ExpressionStepBase(expr_id), entry_count_(entry_count), optional_indices_(std::move(optional_indices)) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: absl::StatusOr<Value> DoEvaluate(ExecutionFrame* frame) const; size_t entry_count_; absl::flat_hash_set<int32_t> optional_indices_; }; absl::StatusOr<Value> CreateStructStepForMap::DoEvaluate( ExecutionFrame* frame) const { auto args = frame->value_stack().GetSpan(2 * entry_count_); if (frame->enable_unknowns()) { absl::optional<UnknownValue> unknown_set = frame->attribute_utility().IdentifyAndMergeUnknowns( args, frame->value_stack().GetAttributeSpan(args.size()), true); if (unknown_set.has_value()) { return *unknown_set; } } CEL_ASSIGN_OR_RETURN(auto builder, frame->value_manager().NewMapValueBuilder( cel::MapTypeView{})); builder->Reserve(entry_count_); for (size_t i = 0; i < entry_count_; i += 1) { auto& map_key = args[2 * i]; CEL_RETURN_IF_ERROR(cel::CheckMapKey(map_key)); auto& map_value = args[(2 * i) + 1]; if (optional_indices_.contains(static_cast<int32_t>(i))) { if (auto optional_map_value = cel::As<cel::OptionalValue>(map_value); optional_map_value) { if (!optional_map_value->HasValue()) { continue; } auto key_status = builder->Put(std::move(map_key), optional_map_value->Value()); if (!key_status.ok()) { return frame->value_factory().CreateErrorValue(key_status); } } else { return cel::TypeConversionError(map_value.DebugString(), "optional_type") .NativeValue(); } } else { auto key_status = builder->Put(std::move(map_key), std::move(map_value)); if (!key_status.ok()) { return frame->value_factory().CreateErrorValue(key_status); } } } return std::move(*builder).Build(); } absl::Status CreateStructStepForMap::Evaluate(ExecutionFrame* frame) const { if (frame->value_stack().size() < 2 * entry_count_) { return absl::InternalError("CreateStructStepForMap: stack underflow"); } CEL_ASSIGN_OR_RETURN(auto result, DoEvaluate(frame)); frame->value_stack().PopAndPush(2 * entry_count_, std::move(result)); return absl::OkStatus(); } class DirectCreateMapStep : public DirectExpressionStep { public: DirectCreateMapStep(std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) : DirectExpressionStep(expr_id), deps_(std::move(deps)), optional_indices_(std::move(optional_indices)), entry_count_(deps_.size() / 2) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute_trail) const override; private: std::vector<std::unique_ptr<DirectExpressionStep>> deps_; absl::flat_hash_set<int32_t> optional_indices_; size_t entry_count_; }; absl::Status DirectCreateMapStep::Evaluate( ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute_trail) const { Value key; Value value; AttributeTrail tmp_attr; auto unknowns = frame.attribute_utility().CreateAccumulator(); CEL_ASSIGN_OR_RETURN(auto builder, frame.value_manager().NewMapValueBuilder( frame.value_manager().GetDynDynMapType())); builder->Reserve(entry_count_); for (size_t i = 0; i < entry_count_; i += 1) { int map_key_index = 2 * i; int map_value_index = map_key_index + 1; CEL_RETURN_IF_ERROR(deps_[map_key_index]->Evaluate(frame, key, tmp_attr)); if (InstanceOf<ErrorValue>(key)) { result = key; return absl::OkStatus(); } if (frame.unknown_processing_enabled()) { if (InstanceOf<UnknownValue>(key)) { unknowns.Add(Cast<UnknownValue>(key)); } else if (frame.attribute_utility().CheckForUnknownPartial(tmp_attr)) { unknowns.Add(tmp_attr); } } CEL_RETURN_IF_ERROR( deps_[map_value_index]->Evaluate(frame, value, tmp_attr)); if (InstanceOf<ErrorValue>(value)) { result = value; return absl::OkStatus(); } if (frame.unknown_processing_enabled()) { if (InstanceOf<UnknownValue>(value)) { unknowns.Add(Cast<UnknownValue>(value)); } else if (frame.attribute_utility().CheckForUnknownPartial(tmp_attr)) { unknowns.Add(tmp_attr); } } if (!unknowns.IsEmpty()) { continue; } if (optional_indices_.contains(static_cast<int32_t>(i))) { if (auto optional_map_value = cel::As<cel::OptionalValue>(static_cast<const Value&>(value)); optional_map_value) { if (!optional_map_value->HasValue()) { continue; } auto key_status = builder->Put(std::move(key), optional_map_value->Value()); if (!key_status.ok()) { result = frame.value_manager().CreateErrorValue(key_status); return absl::OkStatus(); } continue; } return cel::TypeConversionError(value.DebugString(), "optional_type") .NativeValue(); } CEL_RETURN_IF_ERROR(cel::CheckMapKey(key)); auto put_status = builder->Put(std::move(key), std::move(value)); if (!put_status.ok()) { result = frame.value_manager().CreateErrorValue(put_status); return absl::OkStatus(); } } if (!unknowns.IsEmpty()) { result = std::move(unknowns).Build(); return absl::OkStatus(); } result = std::move(*builder).Build(); return absl::OkStatus(); } } std::unique_ptr<DirectExpressionStep> CreateDirectCreateMapStep( std::vector<std::unique_ptr<DirectExpressionStep>> deps, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) { return std::make_unique<DirectCreateMapStep>( std::move(deps), std::move(optional_indices), expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateCreateStructStepForMap( size_t entry_count, absl::flat_hash_set<int32_t> optional_indices, int64_t expr_id) { return std::make_unique<CreateStructStepForMap>(expr_id, entry_count, std::move(optional_indices)); } }
#include "eval/eval/create_map_step.h" #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "base/ast_internal/expr.h" #include "base/type_provider.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_value.h" #include "eval/public/unknown_set.h" #include "eval/testutil/test_message.pb.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeProvider; using ::cel::ast_internal::Expr; using ::google::protobuf::Arena; absl::StatusOr<ExecutionPath> CreateStackMachineProgram( const std::vector<std::pair<CelValue, CelValue>>& values, Activation& activation) { ExecutionPath path; Expr expr1; Expr expr0; std::vector<Expr> exprs; exprs.reserve(values.size() * 2); int index = 0; auto& create_struct = expr1.mutable_struct_expr(); for (const auto& item : values) { std::string key_name = absl::StrCat("key", index); std::string value_name = absl::StrCat("value", index); auto& key_expr = exprs.emplace_back(); auto& key_ident = key_expr.mutable_ident_expr(); key_ident.set_name(key_name); CEL_ASSIGN_OR_RETURN(auto step_key, CreateIdentStep(key_ident, exprs.back().id())); auto& value_expr = exprs.emplace_back(); auto& value_ident = value_expr.mutable_ident_expr(); value_ident.set_name(value_name); CEL_ASSIGN_OR_RETURN(auto step_value, CreateIdentStep(value_ident, exprs.back().id())); path.push_back(std::move(step_key)); path.push_back(std::move(step_value)); activation.InsertValue(key_name, item.first); activation.InsertValue(value_name, item.second); create_struct.mutable_fields().emplace_back(); index++; } CEL_ASSIGN_OR_RETURN( auto step1, CreateCreateStructStepForMap(values.size(), {}, expr1.id())); path.push_back(std::move(step1)); return path; } absl::StatusOr<ExecutionPath> CreateRecursiveProgram( const std::vector<std::pair<CelValue, CelValue>>& values, Activation& activation) { ExecutionPath path; int index = 0; std::vector<std::unique_ptr<DirectExpressionStep>> deps; for (const auto& item : values) { std::string key_name = absl::StrCat("key", index); std::string value_name = absl::StrCat("value", index); deps.push_back(CreateDirectIdentStep(key_name, -1)); deps.push_back(CreateDirectIdentStep(value_name, -1)); activation.InsertValue(key_name, item.first); activation.InsertValue(value_name, item.second); index++; } path.push_back(std::make_unique<WrappedDirectStep>( CreateDirectCreateMapStep(std::move(deps), {}, -1), -1)); return path; } absl::StatusOr<CelValue> RunCreateMapExpression( const std::vector<std::pair<CelValue, CelValue>>& values, google::protobuf::Arena* arena, bool enable_unknowns, bool enable_recursive_program) { Activation activation; ExecutionPath path; if (enable_recursive_program) { CEL_ASSIGN_OR_RETURN(path, CreateRecursiveProgram(values, activation)); } else { CEL_ASSIGN_OR_RETURN(path, CreateStackMachineProgram(values, activation)); } cel::RuntimeOptions options; if (enable_unknowns) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); return cel_expr.Evaluate(activation, arena); } class CreateMapStepTest : public testing::TestWithParam<std::tuple<bool, bool>> { public: bool enable_unknowns() { return std::get<0>(GetParam()); } bool enable_recursive_program() { return std::get<1>(GetParam()); } absl::StatusOr<CelValue> RunMapExpression( const std::vector<std::pair<CelValue, CelValue>>& values, google::protobuf::Arena* arena) { return RunCreateMapExpression(values, arena, enable_unknowns(), enable_recursive_program()); } }; TEST_P(CreateMapStepTest, TestCreateEmptyMap) { Arena arena; ASSERT_OK_AND_ASSIGN(CelValue result, RunMapExpression({}, &arena)); ASSERT_TRUE(result.IsMap()); const CelMap* cel_map = result.MapOrDie(); ASSERT_EQ(cel_map->size(), 0); } TEST(CreateMapStepTest, TestMapCreateWithUnknown) { Arena arena; UnknownSet unknown_set; std::vector<std::pair<CelValue, CelValue>> entries; std::vector<std::string> kKeys = {"test2", "test1"}; entries.push_back( {CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)}); entries.push_back({CelValue::CreateString(&kKeys[1]), CelValue::CreateUnknownSet(&unknown_set)}); ASSERT_OK_AND_ASSIGN(CelValue result, RunCreateMapExpression(entries, &arena, true, false)); ASSERT_TRUE(result.IsUnknownSet()); } TEST(CreateMapStepTest, TestMapCreateWithUnknownRecursiveProgram) { Arena arena; UnknownSet unknown_set; std::vector<std::pair<CelValue, CelValue>> entries; std::vector<std::string> kKeys = {"test2", "test1"}; entries.push_back( {CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)}); entries.push_back({CelValue::CreateString(&kKeys[1]), CelValue::CreateUnknownSet(&unknown_set)}); ASSERT_OK_AND_ASSIGN(CelValue result, RunCreateMapExpression(entries, &arena, true, true)); ASSERT_TRUE(result.IsUnknownSet()); } TEST_P(CreateMapStepTest, TestCreateStringMap) { Arena arena; std::vector<std::pair<CelValue, CelValue>> entries; std::vector<std::string> kKeys = {"test2", "test1"}; entries.push_back( {CelValue::CreateString(&kKeys[0]), CelValue::CreateInt64(2)}); entries.push_back( {CelValue::CreateString(&kKeys[1]), CelValue::CreateInt64(1)}); ASSERT_OK_AND_ASSIGN(CelValue result, RunMapExpression(entries, &arena)); ASSERT_TRUE(result.IsMap()); const CelMap* cel_map = result.MapOrDie(); ASSERT_EQ(cel_map->size(), 2); auto lookup0 = cel_map->Get(&arena, CelValue::CreateString(&kKeys[0])); ASSERT_TRUE(lookup0.has_value()); ASSERT_TRUE(lookup0->IsInt64()) << lookup0->DebugString(); EXPECT_EQ(lookup0->Int64OrDie(), 2); auto lookup1 = cel_map->Get(&arena, CelValue::CreateString(&kKeys[1])); ASSERT_TRUE(lookup1.has_value()); ASSERT_TRUE(lookup1->IsInt64()); EXPECT_EQ(lookup1->Int64OrDie(), 1); } INSTANTIATE_TEST_SUITE_P(CreateMapStep, CreateMapStepTest, testing::Combine(testing::Bool(), testing::Bool())); } }
124
cpp
google/cel-cpp
regex_match_step
eval/eval/regex_match_step.cc
eval/eval/regex_match_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_REGEX_MATCH_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_REGEX_MATCH_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "re2/re2.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectRegexMatchStep( int64_t expr_id, std::unique_ptr<DirectExpressionStep> subject, std::shared_ptr<const RE2> re2); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateRegexMatchStep( std::shared_ptr<const RE2> re2, int64_t expr_id); } #endif #include "eval/eval/regex_match_step.h" #include <cstdint> #include <cstdio> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "common/casting.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "internal/status_macros.h" #include "re2/re2.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValue; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::StringValue; using ::cel::UnknownValue; using ::cel::Value; inline constexpr int kNumRegexMatchArguments = 1; inline constexpr size_t kRegexMatchStepSubject = 0; struct MatchesVisitor final { const RE2& re; bool operator()(const absl::Cord& value) const { if (auto flat = value.TryFlat(); flat.has_value()) { return RE2::PartialMatch(*flat, re); } return RE2::PartialMatch(static_cast<std::string>(value), re); } bool operator()(absl::string_view value) const { return RE2::PartialMatch(value, re); } }; class RegexMatchStep final : public ExpressionStepBase { public: RegexMatchStep(int64_t expr_id, std::shared_ptr<const RE2> re2) : ExpressionStepBase(expr_id, true), re2_(std::move(re2)) {} absl::Status Evaluate(ExecutionFrame* frame) const override { if (!frame->value_stack().HasEnough(kNumRegexMatchArguments)) { return absl::Status(absl::StatusCode::kInternal, "Insufficient arguments supplied for regular " "expression match"); } auto input_args = frame->value_stack().GetSpan(kNumRegexMatchArguments); const auto& subject = input_args[kRegexMatchStepSubject]; if (!subject->Is<cel::StringValue>()) { return absl::Status(absl::StatusCode::kInternal, "First argument for regular " "expression match must be a string"); } bool match = subject.As<cel::StringValue>().NativeValue(MatchesVisitor{*re2_}); frame->value_stack().Pop(kNumRegexMatchArguments); frame->value_stack().Push(frame->value_factory().CreateBoolValue(match)); return absl::OkStatus(); } private: const std::shared_ptr<const RE2> re2_; }; class RegexMatchDirectStep final : public DirectExpressionStep { public: RegexMatchDirectStep(int64_t expr_id, std::unique_ptr<DirectExpressionStep> subject, std::shared_ptr<const RE2> re2) : DirectExpressionStep(expr_id), subject_(std::move(subject)), re2_(std::move(re2)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override { AttributeTrail subject_attr; CEL_RETURN_IF_ERROR(subject_->Evaluate(frame, result, subject_attr)); if (InstanceOf<ErrorValue>(result) || cel::InstanceOf<UnknownValue>(result)) { return absl::OkStatus(); } if (!InstanceOf<StringValue>(result)) { return absl::Status(absl::StatusCode::kInternal, "First argument for regular " "expression match must be a string"); } bool match = Cast<StringValue>(result).NativeValue(MatchesVisitor{*re2_}); result = BoolValue(match); return absl::OkStatus(); } private: std::unique_ptr<DirectExpressionStep> subject_; const std::shared_ptr<const RE2> re2_; }; } std::unique_ptr<DirectExpressionStep> CreateDirectRegexMatchStep( int64_t expr_id, std::unique_ptr<DirectExpressionStep> subject, std::shared_ptr<const RE2> re2) { return std::make_unique<RegexMatchDirectStep>(expr_id, std::move(subject), std::move(re2)); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateRegexMatchStep( std::shared_ptr<const RE2> re2, int64_t expr_id) { return std::make_unique<RegexMatchStep>(expr_id, std::move(re2)); } }
#include "eval/eval/regex_match_step.h" #include "google/api/expr/v1alpha1/checked.pb.h" #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "eval/public/activation.h" #include "eval/public/builtin_func_registrar.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_options.h" #include "internal/testing.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using google::api::expr::v1alpha1::CheckedExpr; using google::api::expr::v1alpha1::Reference; using testing::Eq; using testing::HasSubstr; using cel::internal::StatusIs; Reference MakeMatchesStringOverload() { Reference reference; reference.add_overload_id("matches_string"); return reference; } TEST(RegexMatchStep, Precompiled) { google::protobuf::Arena arena; Activation activation; ASSERT_OK_AND_ASSIGN(auto parsed_expr, parser::Parse("foo.matches('hello')")); CheckedExpr checked_expr; *checked_expr.mutable_expr() = parsed_expr.expr(); *checked_expr.mutable_source_info() = parsed_expr.source_info(); checked_expr.mutable_reference_map()->insert( {checked_expr.expr().id(), MakeMatchesStringOverload()}); InterpreterOptions options; options.enable_regex_precompilation = true; auto expr_builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterBuiltinFunctions(expr_builder->GetRegistry(), options)); ASSERT_OK_AND_ASSIGN(auto expr, expr_builder->CreateExpression(&checked_expr)); activation.InsertValue("foo", CelValue::CreateStringView("hello world!")); ASSERT_OK_AND_ASSIGN(auto result, expr->Evaluate(activation, &arena)); EXPECT_TRUE(result.IsBool()); EXPECT_TRUE(result.BoolOrDie()); } TEST(RegexMatchStep, PrecompiledInvalidRegex) { google::protobuf::Arena arena; Activation activation; ASSERT_OK_AND_ASSIGN(auto parsed_expr, parser::Parse("foo.matches('(')")); CheckedExpr checked_expr; *checked_expr.mutable_expr() = parsed_expr.expr(); *checked_expr.mutable_source_info() = parsed_expr.source_info(); checked_expr.mutable_reference_map()->insert( {checked_expr.expr().id(), MakeMatchesStringOverload()}); InterpreterOptions options; options.enable_regex_precompilation = true; auto expr_builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterBuiltinFunctions(expr_builder->GetRegistry(), options)); EXPECT_THAT(expr_builder->CreateExpression(&checked_expr), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid_argument"))); } TEST(RegexMatchStep, PrecompiledInvalidProgramTooLarge) { google::protobuf::Arena arena; Activation activation; ASSERT_OK_AND_ASSIGN(auto parsed_expr, parser::Parse("foo.matches('hello')")); CheckedExpr checked_expr; *checked_expr.mutable_expr() = parsed_expr.expr(); *checked_expr.mutable_source_info() = parsed_expr.source_info(); checked_expr.mutable_reference_map()->insert( {checked_expr.expr().id(), MakeMatchesStringOverload()}); InterpreterOptions options; options.regex_max_program_size = 1; options.enable_regex_precompilation = true; auto expr_builder = CreateCelExpressionBuilder(options); ASSERT_OK(RegisterBuiltinFunctions(expr_builder->GetRegistry(), options)); EXPECT_THAT(expr_builder->CreateExpression(&checked_expr), StatusIs(absl::StatusCode::kInvalidArgument, Eq("exceeded RE2 max program size"))); } } }
125
cpp
google/cel-cpp
attribute_trail
eval/eval/attribute_trail.cc
eval/eval/attribute_trail_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_ATTRIBUTE_TRAIL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_ATTRIBUTE_TRAIL_H_ #include <string> #include <utility> #include "absl/types/optional.h" #include "absl/utility/utility.h" #include "base/attribute.h" namespace google::api::expr::runtime { class AttributeTrail { public: AttributeTrail() : attribute_(absl::nullopt) {} explicit AttributeTrail(std::string variable_name) : attribute_(absl::in_place, std::move(variable_name)) {} explicit AttributeTrail(cel::Attribute attribute) : attribute_(std::move(attribute)) {} AttributeTrail(const AttributeTrail&) = default; AttributeTrail& operator=(const AttributeTrail&) = default; AttributeTrail(AttributeTrail&&) = default; AttributeTrail& operator=(AttributeTrail&&) = default; AttributeTrail Step(cel::AttributeQualifier qualifier) const; AttributeTrail Step(const std::string* qualifier) const { return Step(cel::AttributeQualifier::OfString(*qualifier)); } const cel::Attribute& attribute() const { return attribute_.value(); } bool empty() const { return !attribute_.has_value(); } private: absl::optional<cel::Attribute> attribute_; }; } #endif #include "eval/eval/attribute_trail.h" #include <algorithm> #include <iterator> #include <string> #include <utility> #include <vector> #include "base/attribute.h" namespace google::api::expr::runtime { AttributeTrail AttributeTrail::Step(cel::AttributeQualifier qualifier) const { if (empty()) return AttributeTrail(); std::vector<cel::AttributeQualifier> qualifiers; qualifiers.reserve(attribute_->qualifier_path().size() + 1); std::copy_n(attribute_->qualifier_path().begin(), attribute_->qualifier_path().size(), std::back_inserter(qualifiers)); qualifiers.push_back(std::move(qualifier)); return AttributeTrail(cel::Attribute(std::string(attribute_->variable_name()), std::move(qualifiers))); } }
#include "eval/eval/attribute_trail.h" #include <string> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_value.h" #include "internal/testing.h" namespace google::api::expr::runtime { TEST(AttributeTrailTest, AttributeTrailEmptyStep) { std::string step = "step"; CelValue step_value = CelValue::CreateString(&step); AttributeTrail trail; ASSERT_TRUE(trail.Step(&step).empty()); ASSERT_TRUE(trail.Step(CreateCelAttributeQualifier(step_value)).empty()); } TEST(AttributeTrailTest, AttributeTrailStep) { std::string step = "step"; CelValue step_value = CelValue::CreateString(&step); AttributeTrail trail = AttributeTrail("ident").Step(&step); ASSERT_EQ(trail.attribute(), CelAttribute("ident", {CreateCelAttributeQualifier(step_value)})); } }
126
cpp
google/cel-cpp
evaluator_stack
eval/eval/evaluator_stack.cc
eval/eval/evaluator_stack_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_EVALUATOR_STACK_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_EVALUATOR_STACK_H_ #include <cstddef> #include <utility> #include <vector> #include "absl/base/optimization.h" #include "absl/log/absl_log.h" #include "absl/types/span.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" namespace google::api::expr::runtime { class EvaluatorStack { public: explicit EvaluatorStack(size_t max_size) : max_size_(max_size), current_size_(0) { Reserve(max_size); } size_t size() const { return current_size_; } size_t max_size() const { return max_size_; } bool empty() const { return current_size_ == 0; } size_t attribute_size() const { return current_size_; } bool HasEnough(size_t size) const { return current_size_ >= size; } void Clear(); absl::Span<const cel::Value> GetSpan(size_t size) const { if (ABSL_PREDICT_FALSE(!HasEnough(size))) { ABSL_LOG(FATAL) << "Requested span size (" << size << ") exceeds current stack size: " << current_size_; } return absl::Span<const cel::Value>(stack_.data() + current_size_ - size, size); } absl::Span<const AttributeTrail> GetAttributeSpan(size_t size) const { if (ABSL_PREDICT_FALSE(!HasEnough(size))) { ABSL_LOG(FATAL) << "Requested span size (" << size << ") exceeds current stack size: " << current_size_; } return absl::Span<const AttributeTrail>( attribute_stack_.data() + current_size_ - size, size); } cel::Value& Peek() { if (ABSL_PREDICT_FALSE(empty())) { ABSL_LOG(FATAL) << "Peeking on empty EvaluatorStack"; } return stack_[current_size_ - 1]; } const cel::Value& Peek() const { if (ABSL_PREDICT_FALSE(empty())) { ABSL_LOG(FATAL) << "Peeking on empty EvaluatorStack"; } return stack_[current_size_ - 1]; } const AttributeTrail& PeekAttribute() const { if (ABSL_PREDICT_FALSE(empty())) { ABSL_LOG(FATAL) << "Peeking on empty EvaluatorStack"; } return attribute_stack_[current_size_ - 1]; } void Pop(size_t size) { if (ABSL_PREDICT_FALSE(!HasEnough(size))) { ABSL_LOG(FATAL) << "Trying to pop more elements (" << size << ") than the current stack size: " << current_size_; } while (size > 0) { stack_.pop_back(); attribute_stack_.pop_back(); current_size_--; size--; } } void Push(cel::Value value) { Push(std::move(value), AttributeTrail()); } void Push(cel::Value value, AttributeTrail attribute) { if (ABSL_PREDICT_FALSE(current_size_ >= max_size())) { ABSL_LOG(ERROR) << "No room to push more elements on to EvaluatorStack"; } stack_.push_back(std::move(value)); attribute_stack_.push_back(std::move(attribute)); current_size_++; } void PopAndPush(size_t size, cel::Value value, AttributeTrail attribute) { if (size == 0) { Push(std::move(value), std::move(attribute)); return; } Pop(size - 1); stack_[current_size_ - 1] = std::move(value); attribute_stack_[current_size_ - 1] = std::move(attribute); } void PopAndPush(cel::Value value) { PopAndPush(std::move(value), AttributeTrail()); } void PopAndPush(cel::Value value, AttributeTrail attribute) { PopAndPush(1, std::move(value), std::move(attribute)); } void PopAndPush(size_t size, cel::Value value) { PopAndPush(size, std::move(value), AttributeTrail{}); } void SetMaxSize(size_t size) { max_size_ = size; Reserve(size); } private: void Reserve(size_t size) { stack_.reserve(size); attribute_stack_.reserve(size); } std::vector<cel::Value> stack_; std::vector<AttributeTrail> attribute_stack_; size_t max_size_; size_t current_size_; }; } #endif #include "eval/eval/evaluator_stack.h" namespace google::api::expr::runtime { void EvaluatorStack::Clear() { stack_.clear(); attribute_stack_.clear(); current_size_ = 0; } }
#include "eval/eval/evaluator_stack.h" #include "base/attribute.h" #include "base/type_provider.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "extensions/protobuf/memory_manager.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeFactory; using ::cel::TypeManager; using ::cel::TypeProvider; using ::cel::ValueManager; using ::cel::extensions::ProtoMemoryManagerRef; TEST(EvaluatorStackTest, StackPushPop) { google::protobuf::Arena arena; auto manager = ProtoMemoryManagerRef(&arena); cel::common_internal::LegacyValueManager value_factory( manager, TypeProvider::Builtin()); cel::Attribute attribute("name", {}); EvaluatorStack stack(10); stack.Push(value_factory.CreateIntValue(1)); stack.Push(value_factory.CreateIntValue(2), AttributeTrail()); stack.Push(value_factory.CreateIntValue(3), AttributeTrail("name")); ASSERT_EQ(stack.Peek().As<cel::IntValue>().NativeValue(), 3); ASSERT_FALSE(stack.PeekAttribute().empty()); ASSERT_EQ(stack.PeekAttribute().attribute(), attribute); stack.Pop(1); ASSERT_EQ(stack.Peek().As<cel::IntValue>().NativeValue(), 2); ASSERT_TRUE(stack.PeekAttribute().empty()); stack.Pop(1); ASSERT_EQ(stack.Peek().As<cel::IntValue>().NativeValue(), 1); ASSERT_TRUE(stack.PeekAttribute().empty()); } TEST(EvaluatorStackTest, StackBalanced) { google::protobuf::Arena arena; auto manager = ProtoMemoryManagerRef(&arena); cel::common_internal::LegacyValueManager value_factory( manager, TypeProvider::Builtin()); EvaluatorStack stack(10); ASSERT_EQ(stack.size(), stack.attribute_size()); stack.Push(value_factory.CreateIntValue(1)); ASSERT_EQ(stack.size(), stack.attribute_size()); stack.Push(value_factory.CreateIntValue(2), AttributeTrail()); stack.Push(value_factory.CreateIntValue(3), AttributeTrail()); ASSERT_EQ(stack.size(), stack.attribute_size()); stack.PopAndPush(value_factory.CreateIntValue(4), AttributeTrail()); ASSERT_EQ(stack.size(), stack.attribute_size()); stack.PopAndPush(value_factory.CreateIntValue(5)); ASSERT_EQ(stack.size(), stack.attribute_size()); stack.Pop(3); ASSERT_EQ(stack.size(), stack.attribute_size()); } TEST(EvaluatorStackTest, Clear) { google::protobuf::Arena arena; auto manager = ProtoMemoryManagerRef(&arena); cel::common_internal::LegacyValueManager value_factory( manager, TypeProvider::Builtin()); EvaluatorStack stack(10); ASSERT_EQ(stack.size(), stack.attribute_size()); stack.Push(value_factory.CreateIntValue(1)); stack.Push(value_factory.CreateIntValue(2), AttributeTrail()); stack.Push(value_factory.CreateIntValue(3), AttributeTrail()); ASSERT_EQ(stack.size(), 3); stack.Clear(); ASSERT_EQ(stack.size(), 0); ASSERT_TRUE(stack.empty()); } } }
127
cpp
google/cel-cpp
lazy_init_step
eval/eval/lazy_init_step.cc
eval/eval/lazy_init_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_LAZY_INIT_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_LAZY_INIT_STEP_H_ #include <cstddef> #include <cstdint> #include <memory> #include "absl/base/nullability.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectBindStep( size_t slot_index, std::unique_ptr<DirectExpressionStep> expression, int64_t expr_id); std::unique_ptr<DirectExpressionStep> CreateDirectLazyInitStep( size_t slot_index, absl::Nonnull<const DirectExpressionStep*> subexpression, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateCheckLazyInitStep( size_t slot_index, size_t subexpression_index, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateAssignSlotStep(size_t slot_index); std::unique_ptr<ExpressionStep> CreateAssignSlotAndPopStep(size_t slot_index); std::unique_ptr<ExpressionStep> CreateClearSlotStep(size_t slot_index, int64_t expr_id); } #endif #include "eval/eval/lazy_init_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include "google/api/expr/v1alpha1/value.pb.h" #include "absl/base/nullability.h" #include "absl/status/status.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using ::cel::Value; class CheckLazyInitStep : public ExpressionStepBase { public: CheckLazyInitStep(size_t slot_index, size_t subexpression_index, int64_t expr_id) : ExpressionStepBase(expr_id), slot_index_(slot_index), subexpression_index_(subexpression_index) {} absl::Status Evaluate(ExecutionFrame* frame) const override { auto* slot = frame->comprehension_slots().Get(slot_index_); if (slot != nullptr) { frame->value_stack().Push(slot->value, slot->attribute); return frame->JumpTo(1); } frame->Call(0, subexpression_index_); return absl::OkStatus(); } private: size_t slot_index_; size_t subexpression_index_; }; class DirectCheckLazyInitStep : public DirectExpressionStep { public: DirectCheckLazyInitStep(size_t slot_index, const DirectExpressionStep* subexpression, int64_t expr_id) : DirectExpressionStep(expr_id), slot_index_(slot_index), subexpression_(subexpression) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override { auto* slot = frame.comprehension_slots().Get(slot_index_); if (slot != nullptr) { result = slot->value; attribute = slot->attribute; return absl::OkStatus(); } CEL_RETURN_IF_ERROR(subexpression_->Evaluate(frame, result, attribute)); frame.comprehension_slots().Set(slot_index_, result, attribute); return absl::OkStatus(); } private: size_t slot_index_; absl::Nonnull<const DirectExpressionStep*> subexpression_; }; class BindStep : public DirectExpressionStep { public: BindStep(size_t slot_index, std::unique_ptr<DirectExpressionStep> subexpression, int64_t expr_id) : DirectExpressionStep(expr_id), slot_index_(slot_index), subexpression_(std::move(subexpression)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override { CEL_RETURN_IF_ERROR(subexpression_->Evaluate(frame, result, attribute)); frame.comprehension_slots().ClearSlot(slot_index_); return absl::OkStatus(); } private: size_t slot_index_; std::unique_ptr<DirectExpressionStep> subexpression_; }; class AssignSlotStep : public ExpressionStepBase { public: explicit AssignSlotStep(size_t slot_index, bool should_pop) : ExpressionStepBase(-1, false), slot_index_(slot_index), should_pop_(should_pop) {} absl::Status Evaluate(ExecutionFrame* frame) const override { if (!frame->value_stack().HasEnough(1)) { return absl::InternalError("Stack underflow assigning lazy value"); } frame->comprehension_slots().Set(slot_index_, frame->value_stack().Peek(), frame->value_stack().PeekAttribute()); if (should_pop_) { frame->value_stack().Pop(1); } return absl::OkStatus(); } private: size_t slot_index_; bool should_pop_; }; class ClearSlotStep : public ExpressionStepBase { public: explicit ClearSlotStep(size_t slot_index, int64_t expr_id) : ExpressionStepBase(expr_id), slot_index_(slot_index) {} absl::Status Evaluate(ExecutionFrame* frame) const override { frame->comprehension_slots().ClearSlot(slot_index_); return absl::OkStatus(); } private: size_t slot_index_; }; } std::unique_ptr<DirectExpressionStep> CreateDirectBindStep( size_t slot_index, std::unique_ptr<DirectExpressionStep> expression, int64_t expr_id) { return std::make_unique<BindStep>(slot_index, std::move(expression), expr_id); } std::unique_ptr<DirectExpressionStep> CreateDirectLazyInitStep( size_t slot_index, absl::Nonnull<const DirectExpressionStep*> subexpression, int64_t expr_id) { return std::make_unique<DirectCheckLazyInitStep>(slot_index, subexpression, expr_id); } std::unique_ptr<ExpressionStep> CreateCheckLazyInitStep( size_t slot_index, size_t subexpression_index, int64_t expr_id) { return std::make_unique<CheckLazyInitStep>(slot_index, subexpression_index, expr_id); } std::unique_ptr<ExpressionStep> CreateAssignSlotStep(size_t slot_index) { return std::make_unique<AssignSlotStep>(slot_index, false); } std::unique_ptr<ExpressionStep> CreateAssignSlotAndPopStep(size_t slot_index) { return std::make_unique<AssignSlotStep>(slot_index, true); } std::unique_ptr<ExpressionStep> CreateClearSlotStep(size_t slot_index, int64_t expr_id) { return std::make_unique<ClearSlotStep>(slot_index, expr_id); } }
#include "eval/eval/lazy_init_step.h" #include <cstddef> #include <vector> #include "absl/status/status.h" #include "base/type_provider.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/const_value_step.h" #include "eval/eval/evaluator_core.h" #include "extensions/protobuf/memory_manager.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::Activation; using ::cel::IntValue; using ::cel::ManagedValueFactory; using ::cel::RuntimeOptions; using ::cel::TypeProvider; using ::cel::ValueManager; using ::cel::extensions::ProtoMemoryManagerRef; using testing::HasSubstr; using cel::internal::StatusIs; class LazyInitStepTest : public testing::Test { private: static constexpr size_t kValueStack = 5; static constexpr size_t kComprehensionSlotCount = 3; public: LazyInitStepTest() : value_factory_(TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)), evaluator_state_(kValueStack, kComprehensionSlotCount, value_factory_.get()) {} protected: ValueManager& value_factory() { return value_factory_.get(); }; google::protobuf::Arena arena_; ManagedValueFactory value_factory_; FlatExpressionEvaluatorState evaluator_state_; RuntimeOptions runtime_options_; Activation activation_; }; TEST_F(LazyInitStepTest, CreateCheckInitStepDoesInit) { ExecutionPath path; ExecutionPath subpath; path.push_back(CreateCheckLazyInitStep(0, 1, -1)); ASSERT_OK_AND_ASSIGN( subpath.emplace_back(), CreateConstValueStep(value_factory().CreateIntValue(42), -1, false)); std::vector<ExecutionPathView> expression_table{path, subpath}; ExecutionFrame frame(expression_table, activation_, runtime_options_, evaluator_state_); ASSERT_OK_AND_ASSIGN(auto value, frame.Evaluate()); EXPECT_TRUE(value->Is<IntValue>() && value->As<IntValue>().NativeValue() == 42); } TEST_F(LazyInitStepTest, CreateCheckInitStepSkipInit) { ExecutionPath path; ExecutionPath subpath; path.push_back(CreateCheckLazyInitStep(0, 1, -1)); path.push_back(CreateAssignSlotStep(0)); path.push_back(CreateClearSlotStep(0, -1)); ASSERT_OK_AND_ASSIGN( subpath.emplace_back(), CreateConstValueStep(value_factory().CreateIntValue(42), -1, false)); std::vector<ExecutionPathView> expression_table{path, subpath}; ExecutionFrame frame(expression_table, activation_, runtime_options_, evaluator_state_); frame.comprehension_slots().Set(0, value_factory().CreateIntValue(42)); ASSERT_OK_AND_ASSIGN(auto value, frame.Evaluate()); EXPECT_TRUE(value->Is<IntValue>() && value->As<IntValue>().NativeValue() == 42); } TEST_F(LazyInitStepTest, CreateAssignSlotStepBasic) { ExecutionPath path; path.push_back(CreateAssignSlotStep(0)); ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_); frame.comprehension_slots().ClearSlot(0); frame.value_stack().Push(value_factory().CreateIntValue(42)); frame.Evaluate().IgnoreError(); auto* slot = frame.comprehension_slots().Get(0); ASSERT_TRUE(slot != nullptr); EXPECT_TRUE(slot->value->Is<IntValue>() && slot->value->As<IntValue>().NativeValue() == 42); EXPECT_FALSE(frame.value_stack().empty()); } TEST_F(LazyInitStepTest, CreateAssignSlotAndPopStepBasic) { ExecutionPath path; path.push_back(CreateAssignSlotAndPopStep(0)); ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_); frame.comprehension_slots().ClearSlot(0); frame.value_stack().Push(value_factory().CreateIntValue(42)); frame.Evaluate().IgnoreError(); auto* slot = frame.comprehension_slots().Get(0); ASSERT_TRUE(slot != nullptr); EXPECT_TRUE(slot->value->Is<IntValue>() && slot->value->As<IntValue>().NativeValue() == 42); EXPECT_TRUE(frame.value_stack().empty()); } TEST_F(LazyInitStepTest, CreateAssignSlotStepStackUnderflow) { ExecutionPath path; path.push_back(CreateAssignSlotStep(0)); ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_); frame.comprehension_slots().ClearSlot(0); EXPECT_THAT(frame.Evaluate(), StatusIs(absl::StatusCode::kInternal, HasSubstr("Stack underflow assigning lazy value"))); } TEST_F(LazyInitStepTest, CreateClearSlotStepBasic) { ExecutionPath path; path.push_back(CreateClearSlotStep(0, -1)); ExecutionFrame frame(path, activation_, runtime_options_, evaluator_state_); frame.comprehension_slots().Set(0, value_factory().CreateIntValue(42)); frame.Evaluate().IgnoreError(); auto* slot = frame.comprehension_slots().Get(0); ASSERT_TRUE(slot == nullptr); } } }
128
cpp
google/cel-cpp
attribute_utility
eval/eval/attribute_utility.cc
eval/eval/attribute_utility_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_UNKNOWNS_UTILITY_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_UNKNOWNS_UTILITY_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "base/attribute.h" #include "base/attribute_set.h" #include "base/function_descriptor.h" #include "base/function_result_set.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_trail.h" namespace google::api::expr::runtime { class AttributeUtility { public: class Accumulator { public: Accumulator(const Accumulator&) = delete; Accumulator& operator=(const Accumulator&) = delete; Accumulator(Accumulator&&) = delete; Accumulator& operator=(Accumulator&&) = delete; void Add(const cel::UnknownValue& v); void Add(const AttributeTrail& attr); void MaybeAdd(const cel::Value& v); bool IsEmpty() const; cel::UnknownValue Build() &&; private: explicit Accumulator(const AttributeUtility& parent) : parent_(parent), unknown_present_(false) {} friend class AttributeUtility; const AttributeUtility& parent_; cel::AttributeSet attribute_set_; cel::FunctionResultSet function_result_set_; bool unknown_present_; }; AttributeUtility( absl::Span<const cel::AttributePattern> unknown_patterns, absl::Span<const cel::AttributePattern> missing_attribute_patterns, cel::ValueManager& value_factory) : unknown_patterns_(unknown_patterns), missing_attribute_patterns_(missing_attribute_patterns), value_factory_(value_factory) {} AttributeUtility(const AttributeUtility&) = delete; AttributeUtility& operator=(const AttributeUtility&) = delete; AttributeUtility(AttributeUtility&&) = delete; AttributeUtility& operator=(AttributeUtility&&) = delete; bool CheckForMissingAttribute(const AttributeTrail& trail) const; bool CheckForUnknown(const AttributeTrail& trail, bool use_partial) const; bool CheckForUnknownExact(const AttributeTrail& trail) const { return CheckForUnknown(trail, false); } bool CheckForUnknownPartial(const AttributeTrail& trail) const { return CheckForUnknown(trail, true); } cel::AttributeSet CheckForUnknowns(absl::Span<const AttributeTrail> args, bool use_partial) const; absl::optional<cel::UnknownValue> MergeUnknowns( absl::Span<const cel::Value> args) const; cel::UnknownValue MergeUnknownValues(const cel::UnknownValue& left, const cel::UnknownValue& right) const; absl::optional<cel::UnknownValue> IdentifyAndMergeUnknowns( absl::Span<const cel::Value> args, absl::Span<const AttributeTrail> attrs, bool use_partial) const; cel::UnknownValue CreateUnknownSet(cel::Attribute attr) const; absl::StatusOr<cel::ErrorValue> CreateMissingAttributeError( const cel::Attribute& attr) const; cel::UnknownValue CreateUnknownSet( const cel::FunctionDescriptor& fn_descriptor, int64_t expr_id, absl::Span<const cel::Value> args) const; Accumulator CreateAccumulator() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return Accumulator(*this); } private: cel::ValueManager& value_manager() const { return value_factory_; } void Add(Accumulator& a, const cel::UnknownValue& v) const; void Add(Accumulator& a, const AttributeTrail& attr) const; absl::Span<const cel::AttributePattern> unknown_patterns_; absl::Span<const cel::AttributePattern> missing_attribute_patterns_; cel::ValueManager& value_factory_; }; } #endif #include "eval/eval/attribute_utility.h" #include <cstdint> #include <string> #include <utility> #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/attribute.h" #include "base/attribute_set.h" #include "base/function_descriptor.h" #include "base/function_result.h" #include "base/function_result_set.h" #include "base/internal/unknown_set.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/internal/errors.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { using ::cel::AttributeSet; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::FunctionResult; using ::cel::FunctionResultSet; using ::cel::InstanceOf; using ::cel::UnknownValue; using ::cel::Value; using ::cel::base_internal::UnknownSet; using Accumulator = AttributeUtility::Accumulator; bool AttributeUtility::CheckForMissingAttribute( const AttributeTrail& trail) const { if (trail.empty()) { return false; } for (const auto& pattern : missing_attribute_patterns_) { if (pattern.IsMatch(trail.attribute()) == cel::AttributePattern::MatchType::FULL) { return true; } } return false; } bool AttributeUtility::CheckForUnknown(const AttributeTrail& trail, bool use_partial) const { if (trail.empty()) { return false; } for (const auto& pattern : unknown_patterns_) { auto current_match = pattern.IsMatch(trail.attribute()); if (current_match == cel::AttributePattern::MatchType::FULL || (use_partial && current_match == cel::AttributePattern::MatchType::PARTIAL)) { return true; } } return false; } absl::optional<UnknownValue> AttributeUtility::MergeUnknowns( absl::Span<const cel::Value> args) const { absl::optional<UnknownSet> result_set; for (const auto& value : args) { if (!value->Is<cel::UnknownValue>()) continue; if (!result_set.has_value()) { result_set.emplace(); } const auto& current_set = value.As<cel::UnknownValue>(); cel::base_internal::UnknownSetAccess::Add( *result_set, UnknownSet(current_set.attribute_set(), current_set.function_result_set())); } if (!result_set.has_value()) { return absl::nullopt; } return value_factory_.CreateUnknownValue( result_set->unknown_attributes(), result_set->unknown_function_results()); } UnknownValue AttributeUtility::MergeUnknownValues( const UnknownValue& left, const UnknownValue& right) const { AttributeSet attributes; FunctionResultSet function_results; attributes.Add(left.attribute_set()); function_results.Add(left.function_result_set()); attributes.Add(right.attribute_set()); function_results.Add(right.function_result_set()); return value_factory_.CreateUnknownValue(std::move(attributes), std::move(function_results)); } AttributeSet AttributeUtility::CheckForUnknowns( absl::Span<const AttributeTrail> args, bool use_partial) const { AttributeSet attribute_set; for (const auto& trail : args) { if (CheckForUnknown(trail, use_partial)) { attribute_set.Add(trail.attribute()); } } return attribute_set; } absl::optional<UnknownValue> AttributeUtility::IdentifyAndMergeUnknowns( absl::Span<const cel::Value> args, absl::Span<const AttributeTrail> attrs, bool use_partial) const { absl::optional<UnknownSet> result_set; cel::AttributeSet attr_set = CheckForUnknowns(attrs, use_partial); if (!attr_set.empty()) { result_set.emplace(std::move(attr_set)); } absl::optional<UnknownValue> arg_unknowns = MergeUnknowns(args); if (!result_set.has_value()) { return arg_unknowns; } if (arg_unknowns.has_value()) { cel::base_internal::UnknownSetAccess::Add( *result_set, UnknownSet((*arg_unknowns).attribute_set(), (*arg_unknowns).function_result_set())); } return value_factory_.CreateUnknownValue( result_set->unknown_attributes(), result_set->unknown_function_results()); } UnknownValue AttributeUtility::CreateUnknownSet(cel::Attribute attr) const { return value_factory_.CreateUnknownValue(AttributeSet({std::move(attr)})); } absl::StatusOr<ErrorValue> AttributeUtility::CreateMissingAttributeError( const cel::Attribute& attr) const { CEL_ASSIGN_OR_RETURN(std::string message, attr.AsString()); return value_factory_.CreateErrorValue( cel::runtime_internal::CreateMissingAttributeError(message)); } UnknownValue AttributeUtility::CreateUnknownSet( const cel::FunctionDescriptor& fn_descriptor, int64_t expr_id, absl::Span<const cel::Value> args) const { return value_factory_.CreateUnknownValue( FunctionResultSet(FunctionResult(fn_descriptor, expr_id))); } void AttributeUtility::Add(Accumulator& a, const cel::UnknownValue& v) const { a.attribute_set_.Add(v.attribute_set()); a.function_result_set_.Add(v.function_result_set()); } void AttributeUtility::Add(Accumulator& a, const AttributeTrail& attr) const { a.attribute_set_.Add(attr.attribute()); } void Accumulator::Add(const UnknownValue& value) { unknown_present_ = true; parent_.Add(*this, value); } void Accumulator::Add(const AttributeTrail& attr) { parent_.Add(*this, attr); } void Accumulator::MaybeAdd(const Value& v) { if (InstanceOf<UnknownValue>(v)) { Add(Cast<UnknownValue>(v)); } } bool Accumulator::IsEmpty() const { return !unknown_present_ && attribute_set_.empty() && function_result_set_.empty(); } cel::UnknownValue Accumulator::Build() && { return parent_.value_manager().CreateUnknownValue( std::move(attribute_set_), std::move(function_result_set_)); } }
#include "eval/eval/attribute_utility.h" #include <vector> #include "base/attribute_set.h" #include "base/type_provider.h" #include "common/type_factory.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_value.h" #include "eval/public/unknown_attribute_set.h" #include "eval/public/unknown_set.h" #include "extensions/protobuf/memory_manager.h" #include "internal/testing.h" namespace google::api::expr::runtime { using ::cel::AttributeSet; using ::cel::UnknownValue; using ::cel::Value; using ::cel::extensions::ProtoMemoryManagerRef; using testing::Eq; using testing::SizeIs; using testing::UnorderedPointwise; class AttributeUtilityTest : public ::testing::Test { public: AttributeUtilityTest() : value_factory_(ProtoMemoryManagerRef(&arena_), cel::TypeProvider::Builtin()) {} protected: google::protobuf::Arena arena_; cel::common_internal::LegacyValueManager value_factory_; }; TEST_F(AttributeUtilityTest, UnknownsUtilityCheckUnknowns) { std::vector<CelAttributePattern> unknown_patterns = { CelAttributePattern("unknown0", {CreateCelAttributeQualifierPattern( CelValue::CreateInt64(1))}), CelAttributePattern("unknown0", {CreateCelAttributeQualifierPattern( CelValue::CreateInt64(2))}), CelAttributePattern("unknown1", {}), CelAttributePattern("unknown2", {}), }; std::vector<CelAttributePattern> missing_attribute_patterns; AttributeUtility utility(unknown_patterns, missing_attribute_patterns, value_factory_); ASSERT_FALSE(utility.CheckForUnknown(AttributeTrail(), true)); ASSERT_FALSE(utility.CheckForUnknown(AttributeTrail(), false)); AttributeTrail unknown_trail0("unknown0"); { ASSERT_FALSE(utility.CheckForUnknown(unknown_trail0, false)); } { ASSERT_TRUE(utility.CheckForUnknown(unknown_trail0, true)); } { ASSERT_TRUE(utility.CheckForUnknown( unknown_trail0.Step( CreateCelAttributeQualifier(CelValue::CreateInt64(1))), false)); } { ASSERT_TRUE(utility.CheckForUnknown( unknown_trail0.Step( CreateCelAttributeQualifier(CelValue::CreateInt64(1))), true)); } } TEST_F(AttributeUtilityTest, UnknownsUtilityMergeUnknownsFromValues) { std::vector<CelAttributePattern> unknown_patterns; std::vector<CelAttributePattern> missing_attribute_patterns; CelAttribute attribute0("unknown0", {}); CelAttribute attribute1("unknown1", {}); AttributeUtility utility(unknown_patterns, missing_attribute_patterns, value_factory_); UnknownValue unknown_set0 = value_factory_.CreateUnknownValue(AttributeSet({attribute0})); UnknownValue unknown_set1 = value_factory_.CreateUnknownValue(AttributeSet({attribute1})); std::vector<cel::Value> values = { unknown_set0, unknown_set1, value_factory_.CreateBoolValue(true), value_factory_.CreateIntValue(1), }; absl::optional<UnknownValue> unknown_set = utility.MergeUnknowns(values); ASSERT_TRUE(unknown_set.has_value()); EXPECT_THAT((*unknown_set).attribute_set(), UnorderedPointwise( Eq(), std::vector<CelAttribute>{attribute0, attribute1})); } TEST_F(AttributeUtilityTest, UnknownsUtilityCheckForUnknownsFromAttributes) { std::vector<CelAttributePattern> unknown_patterns = { CelAttributePattern("unknown0", {CelAttributeQualifierPattern::CreateWildcard()}), }; std::vector<CelAttributePattern> missing_attribute_patterns; AttributeTrail trail0("unknown0"); AttributeTrail trail1("unknown1"); CelAttribute attribute1("unknown1", {}); UnknownSet unknown_set1(UnknownAttributeSet({attribute1})); AttributeUtility utility(unknown_patterns, missing_attribute_patterns, value_factory_); UnknownSet unknown_attr_set(utility.CheckForUnknowns( { AttributeTrail(), trail0.Step(CreateCelAttributeQualifier(CelValue::CreateInt64(1))), trail0.Step(CreateCelAttributeQualifier(CelValue::CreateInt64(2))), }, false)); UnknownSet unknown_set(unknown_set1, unknown_attr_set); ASSERT_THAT(unknown_set.unknown_attributes(), SizeIs(3)); } TEST_F(AttributeUtilityTest, UnknownsUtilityCheckForMissingAttributes) { std::vector<CelAttributePattern> unknown_patterns; std::vector<CelAttributePattern> missing_attribute_patterns; AttributeTrail trail("destination"); trail = trail.Step(CreateCelAttributeQualifier(CelValue::CreateStringView("ip"))); AttributeUtility utility0(unknown_patterns, missing_attribute_patterns, value_factory_); EXPECT_FALSE(utility0.CheckForMissingAttribute(trail)); missing_attribute_patterns.push_back(CelAttributePattern( "destination", {CreateCelAttributeQualifierPattern(CelValue::CreateStringView("ip"))})); AttributeUtility utility1(unknown_patterns, missing_attribute_patterns, value_factory_); EXPECT_TRUE(utility1.CheckForMissingAttribute(trail)); } TEST_F(AttributeUtilityTest, CreateUnknownSet) { AttributeTrail trail("destination"); trail = trail.Step(CreateCelAttributeQualifier(CelValue::CreateStringView("ip"))); std::vector<CelAttributePattern> empty_patterns; AttributeUtility utility(empty_patterns, empty_patterns, value_factory_); UnknownValue set = utility.CreateUnknownSet(trail.attribute()); ASSERT_THAT(set.attribute_set(), SizeIs(1)); ASSERT_OK_AND_ASSIGN(auto elem, set.attribute_set().begin()->AsString()); EXPECT_EQ(elem, "destination.ip"); } }
129
cpp
google/cel-cpp
logic_step
eval/eval/logic_step.cc
eval/eval/logic_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_LOGIC_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_LOGIC_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectAndStep( std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id, bool shortcircuiting); std::unique_ptr<DirectExpressionStep> CreateDirectOrStep( std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id, bool shortcircuiting); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateAndStep(int64_t expr_id); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateOrStep(int64_t expr_id); } #endif #include "eval/eval/logic_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/builtins.h" #include "common/casting.h" #include "common/value.h" #include "common/value_kind.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "internal/status_macros.h" #include "runtime/internal/errors.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValue; using ::cel::BoolValueView; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ValueKind; using ::cel::ValueView; using ::cel::runtime_internal::CreateNoMatchingOverloadError; enum class OpType { kAnd, kOr }; absl::Status ReturnLogicResult(ExecutionFrameBase& frame, OpType op_type, Value& lhs_result, Value& rhs_result, AttributeTrail& attribute_trail, AttributeTrail& rhs_attr) { ValueKind lhs_kind = lhs_result.kind(); ValueKind rhs_kind = rhs_result.kind(); if (frame.unknown_processing_enabled()) { if (lhs_kind == ValueKind::kUnknown && rhs_kind == ValueKind::kUnknown) { lhs_result = frame.attribute_utility().MergeUnknownValues( Cast<UnknownValue>(lhs_result), Cast<UnknownValue>(rhs_result)); attribute_trail = AttributeTrail(); return absl::OkStatus(); } else if (lhs_kind == ValueKind::kUnknown) { return absl::OkStatus(); } else if (rhs_kind == ValueKind::kUnknown) { lhs_result = std::move(rhs_result); attribute_trail = std::move(rhs_attr); return absl::OkStatus(); } } if (lhs_kind == ValueKind::kError) { return absl::OkStatus(); } else if (rhs_kind == ValueKind::kError) { lhs_result = std::move(rhs_result); attribute_trail = std::move(rhs_attr); return absl::OkStatus(); } if (lhs_kind == ValueKind::kBool && rhs_kind == ValueKind::kBool) { return absl::OkStatus(); } attribute_trail = AttributeTrail(); lhs_result = frame.value_manager().CreateErrorValue(CreateNoMatchingOverloadError( op_type == OpType::kOr ? cel::builtin::kOr : cel::builtin::kAnd)); return absl::OkStatus(); } class ExhaustiveDirectLogicStep : public DirectExpressionStep { public: explicit ExhaustiveDirectLogicStep(std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, OpType op_type, int64_t expr_id) : DirectExpressionStep(expr_id), lhs_(std::move(lhs)), rhs_(std::move(rhs)), op_type_(op_type) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& attribute_trail) const override; private: std::unique_ptr<DirectExpressionStep> lhs_; std::unique_ptr<DirectExpressionStep> rhs_; OpType op_type_; }; absl::Status ExhaustiveDirectLogicStep::Evaluate( ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& attribute_trail) const { CEL_RETURN_IF_ERROR(lhs_->Evaluate(frame, result, attribute_trail)); ValueKind lhs_kind = result.kind(); Value rhs_result; AttributeTrail rhs_attr; CEL_RETURN_IF_ERROR(rhs_->Evaluate(frame, rhs_result, attribute_trail)); ValueKind rhs_kind = rhs_result.kind(); if (lhs_kind == ValueKind::kBool) { bool lhs_bool = Cast<BoolValue>(result).NativeValue(); if ((op_type_ == OpType::kOr && lhs_bool) || (op_type_ == OpType::kAnd && !lhs_bool)) { return absl::OkStatus(); } } if (rhs_kind == ValueKind::kBool) { bool rhs_bool = Cast<BoolValue>(rhs_result).NativeValue(); if ((op_type_ == OpType::kOr && rhs_bool) || (op_type_ == OpType::kAnd && !rhs_bool)) { result = std::move(rhs_result); attribute_trail = std::move(rhs_attr); return absl::OkStatus(); } } return ReturnLogicResult(frame, op_type_, result, rhs_result, attribute_trail, rhs_attr); } class DirectLogicStep : public DirectExpressionStep { public: explicit DirectLogicStep(std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, OpType op_type, int64_t expr_id) : DirectExpressionStep(expr_id), lhs_(std::move(lhs)), rhs_(std::move(rhs)), op_type_(op_type) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& attribute_trail) const override; private: std::unique_ptr<DirectExpressionStep> lhs_; std::unique_ptr<DirectExpressionStep> rhs_; OpType op_type_; }; absl::Status DirectLogicStep::Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute_trail) const { CEL_RETURN_IF_ERROR(lhs_->Evaluate(frame, result, attribute_trail)); ValueKind lhs_kind = result.kind(); if (lhs_kind == ValueKind::kBool) { bool lhs_bool = Cast<BoolValue>(result).NativeValue(); if ((op_type_ == OpType::kOr && lhs_bool) || (op_type_ == OpType::kAnd && !lhs_bool)) { return absl::OkStatus(); } } Value rhs_result; AttributeTrail rhs_attr; CEL_RETURN_IF_ERROR(rhs_->Evaluate(frame, rhs_result, attribute_trail)); ValueKind rhs_kind = rhs_result.kind(); if (rhs_kind == ValueKind::kBool) { bool rhs_bool = Cast<BoolValue>(rhs_result).NativeValue(); if ((op_type_ == OpType::kOr && rhs_bool) || (op_type_ == OpType::kAnd && !rhs_bool)) { result = std::move(rhs_result); attribute_trail = std::move(rhs_attr); return absl::OkStatus(); } } return ReturnLogicResult(frame, op_type_, result, rhs_result, attribute_trail, rhs_attr); } class LogicalOpStep : public ExpressionStepBase { public: LogicalOpStep(OpType op_type, int64_t expr_id) : ExpressionStepBase(expr_id), op_type_(op_type) { shortcircuit_ = (op_type_ == OpType::kOr); } absl::Status Evaluate(ExecutionFrame* frame) const override; private: ValueView Calculate(ExecutionFrame* frame, absl::Span<const Value> args, Value& scratch) const { bool bool_args[2]; bool has_bool_args[2]; for (size_t i = 0; i < args.size(); i++) { has_bool_args[i] = args[i]->Is<BoolValue>(); if (has_bool_args[i]) { bool_args[i] = args[i].As<BoolValue>().NativeValue(); if (bool_args[i] == shortcircuit_) { return BoolValueView{bool_args[i]}; } } } if (has_bool_args[0] && has_bool_args[1]) { switch (op_type_) { case OpType::kAnd: return BoolValueView{bool_args[0] && bool_args[1]}; case OpType::kOr: return BoolValueView{bool_args[0] || bool_args[1]}; } } if (frame->enable_unknowns()) { absl::optional<cel::UnknownValue> unknown_set = frame->attribute_utility().MergeUnknowns(args); if (unknown_set.has_value()) { scratch = *unknown_set; return scratch; } } if (args[0]->Is<cel::ErrorValue>()) { return args[0]; } else if (args[1]->Is<cel::ErrorValue>()) { return args[1]; } scratch = frame->value_factory().CreateErrorValue(CreateNoMatchingOverloadError( (op_type_ == OpType::kOr) ? cel::builtin::kOr : cel::builtin::kAnd)); return scratch; } const OpType op_type_; bool shortcircuit_; }; absl::Status LogicalOpStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(2)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } auto args = frame->value_stack().GetSpan(2); Value scratch; auto result = Calculate(frame, args, scratch); frame->value_stack().PopAndPush(args.size(), Value{result}); return absl::OkStatus(); } std::unique_ptr<DirectExpressionStep> CreateDirectLogicStep( std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id, OpType op_type, bool shortcircuiting) { if (shortcircuiting) { return std::make_unique<DirectLogicStep>(std::move(lhs), std::move(rhs), op_type, expr_id); } else { return std::make_unique<ExhaustiveDirectLogicStep>( std::move(lhs), std::move(rhs), op_type, expr_id); } } } std::unique_ptr<DirectExpressionStep> CreateDirectAndStep( std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id, bool shortcircuiting) { return CreateDirectLogicStep(std::move(lhs), std::move(rhs), expr_id, OpType::kAnd, shortcircuiting); } std::unique_ptr<DirectExpressionStep> CreateDirectOrStep( std::unique_ptr<DirectExpressionStep> lhs, std::unique_ptr<DirectExpressionStep> rhs, int64_t expr_id, bool shortcircuiting) { return CreateDirectLogicStep(std::move(lhs), std::move(rhs), expr_id, OpType::kOr, shortcircuiting); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateAndStep(int64_t expr_id) { return std::make_unique<LogicalOpStep>(OpType::kAnd, expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateOrStep(int64_t expr_id) { return std::make_unique<LogicalOpStep>(OpType::kOr, expr_id); } }
#include "eval/eval/logic_step.h" #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "base/ast_internal/expr.h" #include "base/attribute.h" #include "base/attribute_set.h" #include "base/type_provider.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/const_value_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_value.h" #include "eval/public/unknown_attribute_set.h" #include "eval/public/unknown_set.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::Attribute; using ::cel::AttributeSet; using ::cel::BoolValue; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ManagedValueFactory; using ::cel::TypeProvider; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ValueManager; using ::cel::ast_internal::Expr; using ::cel::extensions::ProtoMemoryManagerRef; using ::google::protobuf::Arena; using testing::Eq; class LogicStepTest : public testing::TestWithParam<bool> { public: absl::Status EvaluateLogic(CelValue arg0, CelValue arg1, bool is_or, CelValue* result, bool enable_unknown) { Expr expr0; auto& ident_expr0 = expr0.mutable_ident_expr(); ident_expr0.set_name("name0"); Expr expr1; auto& ident_expr1 = expr1.mutable_ident_expr(); ident_expr1.set_name("name1"); ExecutionPath path; CEL_ASSIGN_OR_RETURN(auto step, CreateIdentStep(ident_expr0, expr0.id())); path.push_back(std::move(step)); CEL_ASSIGN_OR_RETURN(step, CreateIdentStep(ident_expr1, expr1.id())); path.push_back(std::move(step)); CEL_ASSIGN_OR_RETURN(step, (is_or) ? CreateOrStep(2) : CreateAndStep(2)); path.push_back(std::move(step)); auto dummy_expr = std::make_unique<Expr>(); cel::RuntimeOptions options; if (enable_unknown) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl impl( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; activation.InsertValue("name0", arg0); activation.InsertValue("name1", arg1); CEL_ASSIGN_OR_RETURN(CelValue value, impl.Evaluate(activation, &arena_)); *result = value; return absl::OkStatus(); } private: Arena arena_; }; TEST_P(LogicStepTest, TestAndLogic) { CelValue result; absl::Status status = EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(true), false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(false), false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(true), false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(false), false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); } TEST_P(LogicStepTest, TestOrLogic) { CelValue result; absl::Status status = EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(true), true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(false), true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(true), true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(false), true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); } TEST_P(LogicStepTest, TestAndLogicErrorHandling) { CelValue result; CelError error = absl::CancelledError(); CelValue error_value = CelValue::CreateError(&error); absl::Status status = EvaluateLogic(error_value, CelValue::CreateBool(true), false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsError()); status = EvaluateLogic(CelValue::CreateBool(true), error_value, false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsError()); status = EvaluateLogic(CelValue::CreateBool(false), error_value, false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); status = EvaluateLogic(error_value, CelValue::CreateBool(false), false, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); } TEST_P(LogicStepTest, TestOrLogicErrorHandling) { CelValue result; CelError error = absl::CancelledError(); CelValue error_value = CelValue::CreateError(&error); absl::Status status = EvaluateLogic(error_value, CelValue::CreateBool(false), true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsError()); status = EvaluateLogic(CelValue::CreateBool(false), error_value, true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsError()); status = EvaluateLogic(CelValue::CreateBool(true), error_value, true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(error_value, CelValue::CreateBool(true), true, &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); } TEST_F(LogicStepTest, TestAndLogicUnknownHandling) { CelValue result; UnknownSet unknown_set; CelError cel_error = absl::CancelledError(); CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set); CelValue error_value = CelValue::CreateError(&cel_error); absl::Status status = EvaluateLogic(unknown_value, CelValue::CreateBool(true), false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); status = EvaluateLogic(CelValue::CreateBool(true), unknown_value, false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); status = EvaluateLogic(CelValue::CreateBool(false), unknown_value, false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); status = EvaluateLogic(unknown_value, CelValue::CreateBool(false), false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); status = EvaluateLogic(error_value, unknown_value, false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); status = EvaluateLogic(unknown_value, error_value, false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); Expr expr0; auto& ident_expr0 = expr0.mutable_ident_expr(); ident_expr0.set_name("name0"); Expr expr1; auto& ident_expr1 = expr1.mutable_ident_expr(); ident_expr1.set_name("name1"); CelAttribute attr0(expr0.ident_expr().name(), {}), attr1(expr1.ident_expr().name(), {}); UnknownAttributeSet unknown_attr_set0({attr0}); UnknownAttributeSet unknown_attr_set1({attr1}); UnknownSet unknown_set0(unknown_attr_set0); UnknownSet unknown_set1(unknown_attr_set1); EXPECT_THAT(unknown_attr_set0.size(), Eq(1)); EXPECT_THAT(unknown_attr_set1.size(), Eq(1)); status = EvaluateLogic(CelValue::CreateUnknownSet(&unknown_set0), CelValue::CreateUnknownSet(&unknown_set1), false, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); ASSERT_THAT(result.UnknownSetOrDie()->unknown_attributes().size(), Eq(2)); } TEST_F(LogicStepTest, TestOrLogicUnknownHandling) { CelValue result; UnknownSet unknown_set; CelError cel_error = absl::CancelledError(); CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set); CelValue error_value = CelValue::CreateError(&cel_error); absl::Status status = EvaluateLogic( unknown_value, CelValue::CreateBool(false), true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); status = EvaluateLogic(CelValue::CreateBool(false), unknown_value, true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); status = EvaluateLogic(CelValue::CreateBool(true), unknown_value, true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(unknown_value, CelValue::CreateBool(true), true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(unknown_value, error_value, true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); status = EvaluateLogic(error_value, unknown_value, true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); Expr expr0; auto& ident_expr0 = expr0.mutable_ident_expr(); ident_expr0.set_name("name0"); Expr expr1; auto& ident_expr1 = expr1.mutable_ident_expr(); ident_expr1.set_name("name1"); CelAttribute attr0(expr0.ident_expr().name(), {}), attr1(expr1.ident_expr().name(), {}); UnknownAttributeSet unknown_attr_set0({attr0}); UnknownAttributeSet unknown_attr_set1({attr1}); UnknownSet unknown_set0(unknown_attr_set0); UnknownSet unknown_set1(unknown_attr_set1); EXPECT_THAT(unknown_attr_set0.size(), Eq(1)); EXPECT_THAT(unknown_attr_set1.size(), Eq(1)); status = EvaluateLogic(CelValue::CreateUnknownSet(&unknown_set0), CelValue::CreateUnknownSet(&unknown_set1), true, &result, true); ASSERT_OK(status); ASSERT_TRUE(result.IsUnknownSet()); ASSERT_THAT(result.UnknownSetOrDie()->unknown_attributes().size(), Eq(2)); } INSTANTIATE_TEST_SUITE_P(LogicStepTest, LogicStepTest, testing::Bool()); enum class Op { kAnd, kOr }; enum class OpArg { kTrue, kFalse, kUnknown, kError, kInt }; enum class OpResult { kTrue, kFalse, kUnknown, kError, }; struct TestCase { std::string name; Op op; OpArg arg0; OpArg arg1; OpResult result; }; class DirectLogicStepTest : public testing::TestWithParam<std::tuple<bool, TestCase>> { public: DirectLogicStepTest() : value_factory_(TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)) {} bool ShortcircuitingEnabled() { return std::get<0>(GetParam()); } const TestCase& GetTestCase() { return std::get<1>(GetParam()); } ValueManager& value_manager() { return value_factory_.get(); } UnknownValue MakeUnknownValue(std::string attr) { std::vector<Attribute> attrs; attrs.push_back(Attribute(std::move(attr))); return value_manager().CreateUnknownValue(AttributeSet(attrs)); } protected: Arena arena_; ManagedValueFactory value_factory_; }; TEST_P(DirectLogicStepTest, TestCases) { const TestCase& test_case = GetTestCase(); auto MakeArg = [&](OpArg arg, absl::string_view name) -> std::unique_ptr<DirectExpressionStep> { switch (arg) { case OpArg::kTrue: return CreateConstValueDirectStep(BoolValue(true)); case OpArg::kFalse: return CreateConstValueDirectStep(BoolValue(false)); case OpArg::kUnknown: return CreateConstValueDirectStep(MakeUnknownValue(std::string(name))); case OpArg::kError: return CreateConstValueDirectStep( value_manager().CreateErrorValue(absl::InternalError(name))); case OpArg::kInt: return CreateConstValueDirectStep(IntValue(42)); } }; std::unique_ptr<DirectExpressionStep> lhs = MakeArg(test_case.arg0, "lhs"); std::unique_ptr<DirectExpressionStep> rhs = MakeArg(test_case.arg1, "rhs"); std::unique_ptr<DirectExpressionStep> op = (test_case.op == Op::kAnd) ? CreateDirectAndStep(std::move(lhs), std::move(rhs), -1, ShortcircuitingEnabled()) : CreateDirectOrStep(std::move(lhs), std::move(rhs), -1, ShortcircuitingEnabled()); cel::Activation activation; cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; ExecutionFrameBase frame(activation, options, value_manager()); Value value; AttributeTrail attr; ASSERT_OK(op->Evaluate(frame, value, attr)); switch (test_case.result) { case OpResult::kTrue: ASSERT_TRUE(InstanceOf<BoolValue>(value)); EXPECT_TRUE(Cast<BoolValue>(value).NativeValue()); break; case OpResult::kFalse: ASSERT_TRUE(InstanceOf<BoolValue>(value)); EXPECT_FALSE(Cast<BoolValue>(value).NativeValue()); break; case OpResult::kUnknown: EXPECT_TRUE(InstanceOf<UnknownValue>(value)); break; case OpResult::kError: EXPECT_TRUE(InstanceOf<ErrorValue>(value)); break; } } INSTANTIATE_TEST_SUITE_P( DirectLogicStepTest, DirectLogicStepTest, testing::Combine(testing::Bool(), testing::ValuesIn<std::vector<TestCase>>({ { "AndFalseFalse", Op::kAnd, OpArg::kFalse, OpArg::kFalse, OpResult::kFalse, }, { "AndFalseTrue", Op::kAnd, OpArg::kFalse, OpArg::kTrue, OpResult::kFalse, }, { "AndTrueFalse", Op::kAnd, OpArg::kTrue, OpArg::kFalse, OpResult::kFalse, }, { "AndTrueTrue", Op::kAnd, OpArg::kTrue, OpArg::kTrue, OpResult::kTrue, }, { "AndTrueError", Op::kAnd, OpArg::kTrue, OpArg::kError, OpResult::kError, }, { "AndErrorTrue", Op::kAnd, OpArg::kError, OpArg::kTrue, OpResult::kError, }, { "AndFalseError", Op::kAnd, OpArg::kFalse, OpArg::kError, OpResult::kFalse, }, { "AndErrorFalse", Op::kAnd, OpArg::kError, OpArg::kFalse, OpResult::kFalse, }, { "AndErrorError", Op::kAnd, OpArg::kError, OpArg::kError, OpResult::kError, }, { "AndTrueUnknown", Op::kAnd, OpArg::kTrue, OpArg::kUnknown, OpResult::kUnknown, }, { "AndUnknownTrue", Op::kAnd, OpArg::kUnknown, OpArg::kTrue, OpResult::kUnknown, }, { "AndFalseUnknown", Op::kAnd, OpArg::kFalse, OpArg::kUnknown, OpResult::kFalse, }, { "AndUnknownFalse", Op::kAnd, OpArg::kUnknown, OpArg::kFalse, OpResult::kFalse, }, { "AndUnknownUnknown", Op::kAnd, OpArg::kUnknown, OpArg::kUnknown, OpResult::kUnknown, }, { "AndUnknownError", Op::kAnd, OpArg::kUnknown, OpArg::kError, OpResult::kUnknown, }, { "AndErrorUnknown", Op::kAnd, OpArg::kError, OpArg::kUnknown, OpResult::kUnknown, }, })), [](const testing::TestParamInfo<DirectLogicStepTest::ParamType>& info) -> std::string { bool shortcircuiting_enabled = std::get<0>(info.param); absl::string_view name = std::get<1>(info.param).name; return absl::StrCat( name, (shortcircuiting_enabled ? "ShortcircuitingEnabled" : "")); }); } }
130
cpp
google/cel-cpp
comprehension_step
eval/eval/comprehension_step.cc
eval/eval/comprehension_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_COMPREHENSION_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_COMPREHENSION_STEP_H_ #include <cstddef> #include <cstdint> #include <memory> #include "absl/status/status.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" namespace google::api::expr::runtime { class ComprehensionNextStep : public ExpressionStepBase { public: ComprehensionNextStep(size_t iter_slot, size_t accu_slot, int64_t expr_id); void set_jump_offset(int offset); void set_error_jump_offset(int offset); absl::Status Evaluate(ExecutionFrame* frame) const override; private: size_t iter_slot_; size_t accu_slot_; int jump_offset_; int error_jump_offset_; }; class ComprehensionCondStep : public ExpressionStepBase { public: ComprehensionCondStep(size_t iter_slot, size_t accu_slot, bool shortcircuiting, int64_t expr_id); void set_jump_offset(int offset); void set_error_jump_offset(int offset); absl::Status Evaluate(ExecutionFrame* frame) const override; private: size_t iter_slot_; size_t accu_slot_; int jump_offset_; int error_jump_offset_; bool shortcircuiting_; }; std::unique_ptr<DirectExpressionStep> CreateDirectComprehensionStep( size_t iter_slot, size_t accu_slot, std::unique_ptr<DirectExpressionStep> range, std::unique_ptr<DirectExpressionStep> accu_init, std::unique_ptr<DirectExpressionStep> loop_step, std::unique_ptr<DirectExpressionStep> condition_step, std::unique_ptr<DirectExpressionStep> result_step, bool shortcircuiting, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateComprehensionFinishStep(size_t accu_slot, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateComprehensionInitStep(int64_t expr_id); } #endif #include "eval/eval/comprehension_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "base/attribute.h" #include "base/kind.h" #include "common/casting.h" #include "common/value.h" #include "common/value_kind.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/comprehension_slots.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "eval/public/cel_attribute.h" #include "internal/status_macros.h" #include "runtime/internal/mutable_list_impl.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValue; using ::cel::Cast; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ListValue; using ::cel::MapValue; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ValueView; using ::cel::runtime_internal::CreateNoMatchingOverloadError; using ::cel::runtime_internal::MutableListValue; class ComprehensionFinish : public ExpressionStepBase { public: ComprehensionFinish(size_t accu_slot, int64_t expr_id); absl::Status Evaluate(ExecutionFrame* frame) const override; private: size_t accu_slot_; }; ComprehensionFinish::ComprehensionFinish(size_t accu_slot, int64_t expr_id) : ExpressionStepBase(expr_id), accu_slot_(accu_slot) {} absl::Status ComprehensionFinish::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(3)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } Value result = frame->value_stack().Peek(); frame->value_stack().Pop(3); if (frame->enable_comprehension_list_append() && MutableListValue::Is(result)) { MutableListValue& list_value = MutableListValue::Cast(result); CEL_ASSIGN_OR_RETURN(result, std::move(list_value).Build()); } frame->value_stack().Push(std::move(result)); frame->comprehension_slots().ClearSlot(accu_slot_); return absl::OkStatus(); } class ComprehensionInitStep : public ExpressionStepBase { public: explicit ComprehensionInitStep(int64_t expr_id) : ExpressionStepBase(expr_id, false) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: absl::Status ProjectKeys(ExecutionFrame* frame) const; }; absl::StatusOr<Value> ProjectKeysImpl(ExecutionFrameBase& frame, const MapValue& range, const AttributeTrail& trail) { if (frame.unknown_processing_enabled()) { if (frame.attribute_utility().CheckForUnknownPartial(trail)) { return frame.attribute_utility().CreateUnknownSet(trail.attribute()); } } return range.ListKeys(frame.value_manager()); } absl::Status ComprehensionInitStep::ProjectKeys(ExecutionFrame* frame) const { const auto& map_value = Cast<MapValue>(frame->value_stack().Peek()); CEL_ASSIGN_OR_RETURN( Value keys, ProjectKeysImpl(*frame, map_value, frame->value_stack().PeekAttribute())); frame->value_stack().PopAndPush(std::move(keys)); return absl::OkStatus(); } absl::Status ComprehensionInitStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(1)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } if (frame->value_stack().Peek()->Is<cel::MapValue>()) { CEL_RETURN_IF_ERROR(ProjectKeys(frame)); } const auto& range = frame->value_stack().Peek(); if (!range->Is<cel::ListValue>() && !range->Is<cel::ErrorValue>() && !range->Is<cel::UnknownValue>()) { frame->value_stack().PopAndPush(frame->value_factory().CreateErrorValue( CreateNoMatchingOverloadError("<iter_range>"))); } frame->value_stack().Push(frame->value_factory().CreateIntValue(-1)); return absl::OkStatus(); } class ComprehensionDirectStep : public DirectExpressionStep { public: explicit ComprehensionDirectStep( size_t iter_slot, size_t accu_slot, std::unique_ptr<DirectExpressionStep> range, std::unique_ptr<DirectExpressionStep> accu_init, std::unique_ptr<DirectExpressionStep> loop_step, std::unique_ptr<DirectExpressionStep> condition_step, std::unique_ptr<DirectExpressionStep> result_step, bool shortcircuiting, int64_t expr_id) : DirectExpressionStep(expr_id), iter_slot_(iter_slot), accu_slot_(accu_slot), range_(std::move(range)), accu_init_(std::move(accu_init)), loop_step_(std::move(loop_step)), condition_(std::move(condition_step)), result_step_(std::move(result_step)), shortcircuiting_(shortcircuiting) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& trail) const override; private: size_t iter_slot_; size_t accu_slot_; std::unique_ptr<DirectExpressionStep> range_; std::unique_ptr<DirectExpressionStep> accu_init_; std::unique_ptr<DirectExpressionStep> loop_step_; std::unique_ptr<DirectExpressionStep> condition_; std::unique_ptr<DirectExpressionStep> result_step_; bool shortcircuiting_; }; absl::Status ComprehensionDirectStep::Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& trail) const { cel::Value range; AttributeTrail range_attr; CEL_RETURN_IF_ERROR(range_->Evaluate(frame, range, range_attr)); if (InstanceOf<MapValue>(range)) { const auto& map_value = Cast<MapValue>(range); CEL_ASSIGN_OR_RETURN(range, ProjectKeysImpl(frame, map_value, range_attr)); } switch (range.kind()) { case cel::ValueKind::kError: case cel::ValueKind::kUnknown: result = range; return absl::OkStatus(); break; default: if (!InstanceOf<ListValue>(range)) { result = frame.value_manager().CreateErrorValue( CreateNoMatchingOverloadError("<iter_range>")); return absl::OkStatus(); } } const auto& range_list = Cast<ListValue>(range); Value accu_init; AttributeTrail accu_init_attr; CEL_RETURN_IF_ERROR(accu_init_->Evaluate(frame, accu_init, accu_init_attr)); frame.comprehension_slots().Set(accu_slot_, std::move(accu_init), accu_init_attr); ComprehensionSlots::Slot* accu_slot = frame.comprehension_slots().Get(accu_slot_); ABSL_DCHECK(accu_slot != nullptr); frame.comprehension_slots().Set(iter_slot_); ComprehensionSlots::Slot* iter_slot = frame.comprehension_slots().Get(iter_slot_); ABSL_DCHECK(iter_slot != nullptr); Value condition; AttributeTrail condition_attr; bool should_skip_result = false; CEL_RETURN_IF_ERROR(range_list.ForEach( frame.value_manager(), [&](size_t index, ValueView v) -> absl::StatusOr<bool> { CEL_RETURN_IF_ERROR(frame.IncrementIterations()); CEL_RETURN_IF_ERROR( condition_->Evaluate(frame, condition, condition_attr)); if (condition.kind() == cel::ValueKind::kError || condition.kind() == cel::ValueKind::kUnknown) { result = std::move(condition); should_skip_result = true; return false; } if (condition.kind() != cel::ValueKind::kBool) { result = frame.value_manager().CreateErrorValue( CreateNoMatchingOverloadError("<loop_condition>")); should_skip_result = true; return false; } if (shortcircuiting_ && !Cast<BoolValue>(condition).NativeValue()) { return false; } iter_slot->value = v; if (frame.unknown_processing_enabled()) { iter_slot->attribute = range_attr.Step(CelAttributeQualifier::OfInt(index)); if (frame.attribute_utility().CheckForUnknownExact( iter_slot->attribute)) { iter_slot->value = frame.attribute_utility().CreateUnknownSet( iter_slot->attribute.attribute()); } } CEL_RETURN_IF_ERROR(loop_step_->Evaluate(frame, accu_slot->value, accu_slot->attribute)); return true; })); frame.comprehension_slots().ClearSlot(iter_slot_); if (should_skip_result) { frame.comprehension_slots().ClearSlot(accu_slot_); return absl::OkStatus(); } CEL_RETURN_IF_ERROR(result_step_->Evaluate(frame, result, trail)); if (frame.options().enable_comprehension_list_append && MutableListValue::Is(result)) { MutableListValue& list_value = MutableListValue::Cast(result); CEL_ASSIGN_OR_RETURN(result, std::move(list_value).Build()); } frame.comprehension_slots().ClearSlot(accu_slot_); return absl::OkStatus(); } } ComprehensionNextStep::ComprehensionNextStep(size_t iter_slot, size_t accu_slot, int64_t expr_id) : ExpressionStepBase(expr_id, false), iter_slot_(iter_slot), accu_slot_(accu_slot) {} void ComprehensionNextStep::set_jump_offset(int offset) { jump_offset_ = offset; } void ComprehensionNextStep::set_error_jump_offset(int offset) { error_jump_offset_ = offset; } absl::Status ComprehensionNextStep::Evaluate(ExecutionFrame* frame) const { enum { POS_ITER_RANGE, POS_CURRENT_INDEX, POS_LOOP_STEP_ACCU, }; constexpr int kStackSize = 3; if (!frame->value_stack().HasEnough(kStackSize)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } absl::Span<const Value> state = frame->value_stack().GetSpan(kStackSize); const cel::Value& iter_range = state[POS_ITER_RANGE]; if (!iter_range->Is<cel::ListValue>()) { if (iter_range->Is<cel::ErrorValue>() || iter_range->Is<cel::UnknownValue>()) { frame->value_stack().PopAndPush(kStackSize, std::move(iter_range)); } else { frame->value_stack().PopAndPush( kStackSize, frame->value_factory().CreateErrorValue( CreateNoMatchingOverloadError("<iter_range>"))); } return frame->JumpTo(error_jump_offset_); } const ListValue& iter_range_list = Cast<ListValue>(iter_range); const auto& current_index_value = state[POS_CURRENT_INDEX]; if (!InstanceOf<IntValue>(current_index_value)) { return absl::InternalError(absl::StrCat( "ComprehensionNextStep: want int, got ", cel::KindToString(ValueKindToKind(current_index_value->kind())))); } CEL_RETURN_IF_ERROR(frame->IncrementIterations()); int64_t next_index = Cast<IntValue>(current_index_value).NativeValue() + 1; frame->comprehension_slots().Set(accu_slot_, state[POS_LOOP_STEP_ACCU]); CEL_ASSIGN_OR_RETURN(auto iter_range_list_size, iter_range_list.Size()); if (next_index >= static_cast<int64_t>(iter_range_list_size)) { frame->comprehension_slots().ClearSlot(iter_slot_); frame->value_stack().Pop(1); return frame->JumpTo(jump_offset_); } AttributeTrail iter_trail; if (frame->enable_unknowns()) { iter_trail = frame->value_stack().GetAttributeSpan(kStackSize)[POS_ITER_RANGE].Step( cel::AttributeQualifier::OfInt(next_index)); } Value current_value; if (frame->enable_unknowns() && frame->attribute_utility().CheckForUnknown( iter_trail, false)) { current_value = frame->attribute_utility().CreateUnknownSet(iter_trail.attribute()); } else { CEL_ASSIGN_OR_RETURN(current_value, iter_range_list.Get(frame->value_factory(), static_cast<size_t>(next_index))); } frame->value_stack().PopAndPush( 2, frame->value_factory().CreateIntValue(next_index)); frame->comprehension_slots().Set(iter_slot_, std::move(current_value), std::move(iter_trail)); return absl::OkStatus(); } ComprehensionCondStep::ComprehensionCondStep(size_t iter_slot, size_t accu_slot, bool shortcircuiting, int64_t expr_id) : ExpressionStepBase(expr_id, false), iter_slot_(iter_slot), accu_slot_(accu_slot), shortcircuiting_(shortcircuiting) {} void ComprehensionCondStep::set_jump_offset(int offset) { jump_offset_ = offset; } void ComprehensionCondStep::set_error_jump_offset(int offset) { error_jump_offset_ = offset; } absl::Status ComprehensionCondStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(3)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } auto& loop_condition_value = frame->value_stack().Peek(); if (!loop_condition_value->Is<cel::BoolValue>()) { if (loop_condition_value->Is<cel::ErrorValue>() || loop_condition_value->Is<cel::UnknownValue>()) { frame->value_stack().PopAndPush(3, std::move(loop_condition_value)); } else { frame->value_stack().PopAndPush( 3, frame->value_factory().CreateErrorValue( CreateNoMatchingOverloadError("<loop_condition>"))); } frame->comprehension_slots().ClearSlot(iter_slot_); frame->comprehension_slots().ClearSlot(accu_slot_); return frame->JumpTo(error_jump_offset_); } bool loop_condition = loop_condition_value.As<cel::BoolValue>().NativeValue(); frame->value_stack().Pop(1); if (!loop_condition && shortcircuiting_) { return frame->JumpTo(jump_offset_); } return absl::OkStatus(); } std::unique_ptr<DirectExpressionStep> CreateDirectComprehensionStep( size_t iter_slot, size_t accu_slot, std::unique_ptr<DirectExpressionStep> range, std::unique_ptr<DirectExpressionStep> accu_init, std::unique_ptr<DirectExpressionStep> loop_step, std::unique_ptr<DirectExpressionStep> condition_step, std::unique_ptr<DirectExpressionStep> result_step, bool shortcircuiting, int64_t expr_id) { return std::make_unique<ComprehensionDirectStep>( iter_slot, accu_slot, std::move(range), std::move(accu_init), std::move(loop_step), std::move(condition_step), std::move(result_step), shortcircuiting, expr_id); } std::unique_ptr<ExpressionStep> CreateComprehensionFinishStep(size_t accu_slot, int64_t expr_id) { return std::make_unique<ComprehensionFinish>(accu_slot, expr_id); } std::unique_ptr<ExpressionStep> CreateComprehensionInitStep(int64_t expr_id) { return std::make_unique<ComprehensionInitStep>(expr_id); } }
#include "eval/eval/comprehension_step.h" #include <memory> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/struct.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "base/ast_internal/expr.h" #include "base/type_provider.h" #include "common/value.h" #include "common/value_testing.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/comprehension_slots.h" #include "eval/eval/const_value_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_value.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValue; using ::cel::IntValue; using ::cel::TypeProvider; using ::cel::Value; using ::cel::ast_internal::Expr; using ::cel::ast_internal::Ident; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::test::BoolValueIs; using ::google::protobuf::ListValue; using ::google::protobuf::Struct; using ::google::protobuf::Arena; using testing::_; using testing::Eq; using testing::Return; using testing::SizeIs; using cel::internal::StatusIs; Ident CreateIdent(const std::string& var) { Ident expr; expr.set_name(var); return expr; } class ListKeysStepTest : public testing::Test { public: ListKeysStepTest() = default; std::unique_ptr<CelExpressionFlatImpl> MakeExpression( ExecutionPath&& path, bool unknown_attributes = false) { cel::RuntimeOptions options; if (unknown_attributes) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeAndFunction; } return std::make_unique<CelExpressionFlatImpl>( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); } private: Expr dummy_expr_; }; class GetListKeysResultStep : public ExpressionStepBase { public: GetListKeysResultStep() : ExpressionStepBase(-1, false) {} absl::Status Evaluate(ExecutionFrame* frame) const override { frame->value_stack().Pop(1); return absl::OkStatus(); } }; MATCHER_P(CelStringValue, val, "") { const CelValue& to_match = arg; absl::string_view value = val; return to_match.IsString() && to_match.StringOrDie().value() == value; } TEST_F(ListKeysStepTest, ListPassedThrough) { ExecutionPath path; Ident ident = CreateIdent("var"); auto result = CreateIdentStep(ident, 0); ASSERT_OK(result); path.push_back(*std::move(result)); result = CreateComprehensionInitStep(1); ASSERT_OK(result); path.push_back(*std::move(result)); path.push_back(std::make_unique<GetListKeysResultStep>()); auto expression = MakeExpression(std::move(path)); Activation activation; Arena arena; ListValue value; value.add_values()->set_number_value(1.0); value.add_values()->set_number_value(2.0); value.add_values()->set_number_value(3.0); activation.InsertValue("var", CelProtoWrapper::CreateMessage(&value, &arena)); auto eval_result = expression->Evaluate(activation, &arena); ASSERT_OK(eval_result); ASSERT_TRUE(eval_result->IsList()); EXPECT_THAT(*eval_result->ListOrDie(), SizeIs(3)); } TEST_F(ListKeysStepTest, MapToKeyList) { ExecutionPath path; Ident ident = CreateIdent("var"); auto result = CreateIdentStep(ident, 0); ASSERT_OK(result); path.push_back(*std::move(result)); result = CreateComprehensionInitStep(1); ASSERT_OK(result); path.push_back(*std::move(result)); path.push_back(std::make_unique<GetListKeysResultStep>()); auto expression = MakeExpression(std::move(path)); Activation activation; Arena arena; Struct value; (*value.mutable_fields())["key1"].set_number_value(1.0); (*value.mutable_fields())["key2"].set_number_value(2.0); (*value.mutable_fields())["key3"].set_number_value(3.0); activation.InsertValue("var", CelProtoWrapper::CreateMessage(&value, &arena)); auto eval_result = expression->Evaluate(activation, &arena); ASSERT_OK(eval_result); ASSERT_TRUE(eval_result->IsList()); EXPECT_THAT(*eval_result->ListOrDie(), SizeIs(3)); std::vector<CelValue> keys; keys.reserve(eval_result->ListOrDie()->size()); for (int i = 0; i < eval_result->ListOrDie()->size(); i++) { keys.push_back(eval_result->ListOrDie()->operator[](i)); } EXPECT_THAT(keys, testing::UnorderedElementsAre(CelStringValue("key1"), CelStringValue("key2"), CelStringValue("key3"))); } TEST_F(ListKeysStepTest, MapPartiallyUnknown) { ExecutionPath path; Ident ident = CreateIdent("var"); auto result = CreateIdentStep(ident, 0); ASSERT_OK(result); path.push_back(*std::move(result)); result = CreateComprehensionInitStep(1); ASSERT_OK(result); path.push_back(*std::move(result)); path.push_back(std::make_unique<GetListKeysResultStep>()); auto expression = MakeExpression(std::move(path), true); Activation activation; Arena arena; Struct value; (*value.mutable_fields())["key1"].set_number_value(1.0); (*value.mutable_fields())["key2"].set_number_value(2.0); (*value.mutable_fields())["key3"].set_number_value(3.0); activation.InsertValue("var", CelProtoWrapper::CreateMessage(&value, &arena)); activation.set_unknown_attribute_patterns({CelAttributePattern( "var", {CreateCelAttributeQualifierPattern(CelValue::CreateStringView("key2")), CreateCelAttributeQualifierPattern(CelValue::CreateStringView("foo")), CelAttributeQualifierPattern::CreateWildcard()})}); auto eval_result = expression->Evaluate(activation, &arena); ASSERT_OK(eval_result); ASSERT_TRUE(eval_result->IsUnknownSet()); const auto& attrs = eval_result->UnknownSetOrDie()->unknown_attributes(); EXPECT_THAT(attrs, SizeIs(1)); EXPECT_THAT(attrs.begin()->variable_name(), Eq("var")); EXPECT_THAT(attrs.begin()->qualifier_path(), SizeIs(0)); } TEST_F(ListKeysStepTest, ErrorPassedThrough) { ExecutionPath path; Ident ident = CreateIdent("var"); auto result = CreateIdentStep(ident, 0); ASSERT_OK(result); path.push_back(*std::move(result)); result = CreateComprehensionInitStep(1); ASSERT_OK(result); path.push_back(*std::move(result)); path.push_back(std::make_unique<GetListKeysResultStep>()); auto expression = MakeExpression(std::move(path)); Activation activation; Arena arena; auto eval_result = expression->Evaluate(activation, &arena); ASSERT_OK(eval_result); ASSERT_TRUE(eval_result->IsError()); EXPECT_THAT(eval_result->ErrorOrDie()->message(), testing::HasSubstr("\"var\"")); EXPECT_EQ(eval_result->ErrorOrDie()->code(), absl::StatusCode::kUnknown); } TEST_F(ListKeysStepTest, UnknownSetPassedThrough) { ExecutionPath path; Ident ident = CreateIdent("var"); auto result = CreateIdentStep(ident, 0); ASSERT_OK(result); path.push_back(*std::move(result)); result = CreateComprehensionInitStep(1); ASSERT_OK(result); path.push_back(*std::move(result)); path.push_back(std::make_unique<GetListKeysResultStep>()); auto expression = MakeExpression(std::move(path), true); Activation activation; Arena arena; activation.set_unknown_attribute_patterns({CelAttributePattern("var", {})}); auto eval_result = expression->Evaluate(activation, &arena); ASSERT_OK(eval_result); ASSERT_TRUE(eval_result->IsUnknownSet()); EXPECT_THAT(eval_result->UnknownSetOrDie()->unknown_attributes(), SizeIs(1)); } class MockDirectStep : public DirectExpressionStep { public: MockDirectStep() : DirectExpressionStep(-1) {} MOCK_METHOD(absl::Status, Evaluate, (ExecutionFrameBase&, Value&, AttributeTrail&), (const override)); }; class DirectComprehensionTest : public testing::Test { public: DirectComprehensionTest() : value_manager_(TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)), slots_(2) {} absl::StatusOr<cel::ListValue> MakeList() { CEL_ASSIGN_OR_RETURN(auto builder, value_manager_.get().NewListValueBuilder( value_manager_.get().GetDynListType())); CEL_RETURN_IF_ERROR(builder->Add(IntValue(1))); CEL_RETURN_IF_ERROR(builder->Add(IntValue(2))); return std::move(*builder).Build(); } protected: google::protobuf::Arena arena_; cel::ManagedValueFactory value_manager_; ComprehensionSlots slots_; cel::Activation empty_activation_; }; TEST_F(DirectComprehensionTest, PropagateRangeNonOkStatus) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto range_step = std::make_unique<MockDirectStep>(); MockDirectStep* mock = range_step.get(); ON_CALL(*mock, Evaluate(_, _, _)) .WillByDefault(Return(absl::InternalError("test range error"))); auto compre_step = CreateDirectComprehensionStep( 0, 1, std::move(range_step), CreateConstValueDirectStep(BoolValue(false)), CreateConstValueDirectStep(BoolValue(false)), CreateConstValueDirectStep(BoolValue(true)), CreateDirectSlotIdentStep("__result__", 1, -1), true, -1); Value result; AttributeTrail trail; EXPECT_THAT(compre_step->Evaluate(frame, result, trail), StatusIs(absl::StatusCode::kInternal, "test range error")); } TEST_F(DirectComprehensionTest, PropagateAccuInitNonOkStatus) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto accu_init = std::make_unique<MockDirectStep>(); MockDirectStep* mock = accu_init.get(); ON_CALL(*mock, Evaluate(_, _, _)) .WillByDefault(Return(absl::InternalError("test accu init error"))); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), std::move(accu_init), CreateConstValueDirectStep(BoolValue(false)), CreateConstValueDirectStep(BoolValue(true)), CreateDirectSlotIdentStep("__result__", 1, -1), true, -1); Value result; AttributeTrail trail; EXPECT_THAT(compre_step->Evaluate(frame, result, trail), StatusIs(absl::StatusCode::kInternal, "test accu init error")); } TEST_F(DirectComprehensionTest, PropagateLoopNonOkStatus) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto loop_step = std::make_unique<MockDirectStep>(); MockDirectStep* mock = loop_step.get(); ON_CALL(*mock, Evaluate(_, _, _)) .WillByDefault(Return(absl::InternalError("test loop error"))); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), CreateConstValueDirectStep(BoolValue(false)), std::move(loop_step), CreateConstValueDirectStep(BoolValue(true)), CreateDirectSlotIdentStep("__result__", 1, -1), true, -1); Value result; AttributeTrail trail; EXPECT_THAT(compre_step->Evaluate(frame, result, trail), StatusIs(absl::StatusCode::kInternal, "test loop error")); } TEST_F(DirectComprehensionTest, PropagateConditionNonOkStatus) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto condition = std::make_unique<MockDirectStep>(); MockDirectStep* mock = condition.get(); ON_CALL(*mock, Evaluate(_, _, _)) .WillByDefault(Return(absl::InternalError("test condition error"))); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), CreateConstValueDirectStep(BoolValue(false)), CreateConstValueDirectStep(BoolValue(false)), std::move(condition), CreateDirectSlotIdentStep("__result__", 1, -1), true, -1); Value result; AttributeTrail trail; EXPECT_THAT(compre_step->Evaluate(frame, result, trail), StatusIs(absl::StatusCode::kInternal, "test condition error")); } TEST_F(DirectComprehensionTest, PropagateResultNonOkStatus) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto result_step = std::make_unique<MockDirectStep>(); MockDirectStep* mock = result_step.get(); ON_CALL(*mock, Evaluate(_, _, _)) .WillByDefault(Return(absl::InternalError("test result error"))); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), CreateConstValueDirectStep(BoolValue(false)), CreateConstValueDirectStep(BoolValue(false)), CreateConstValueDirectStep(BoolValue(true)), std::move(result_step), true, -1); Value result; AttributeTrail trail; EXPECT_THAT(compre_step->Evaluate(frame, result, trail), StatusIs(absl::StatusCode::kInternal, "test result error")); } TEST_F(DirectComprehensionTest, Shortcircuit) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto loop_step = std::make_unique<MockDirectStep>(); MockDirectStep* mock = loop_step.get(); EXPECT_CALL(*mock, Evaluate(_, _, _)) .Times(0) .WillRepeatedly([](ExecutionFrameBase&, Value& result, AttributeTrail&) { result = BoolValue(false); return absl::OkStatus(); }); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), CreateConstValueDirectStep(BoolValue(false)), std::move(loop_step), CreateConstValueDirectStep(BoolValue(false)), CreateDirectSlotIdentStep("__result__", 1, -1), true, -1); Value result; AttributeTrail trail; ASSERT_OK(compre_step->Evaluate(frame, result, trail)); EXPECT_THAT(result, BoolValueIs(false)); } TEST_F(DirectComprehensionTest, IterationLimit) { cel::RuntimeOptions options; options.comprehension_max_iterations = 2; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto loop_step = std::make_unique<MockDirectStep>(); MockDirectStep* mock = loop_step.get(); EXPECT_CALL(*mock, Evaluate(_, _, _)) .Times(1) .WillRepeatedly([](ExecutionFrameBase&, Value& result, AttributeTrail&) { result = BoolValue(false); return absl::OkStatus(); }); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), CreateConstValueDirectStep(BoolValue(false)), std::move(loop_step), CreateConstValueDirectStep(BoolValue(true)), CreateDirectSlotIdentStep("__result__", 1, -1), true, -1); Value result; AttributeTrail trail; EXPECT_THAT(compre_step->Evaluate(frame, result, trail), StatusIs(absl::StatusCode::kInternal)); } TEST_F(DirectComprehensionTest, Exhaustive) { cel::RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, nullptr, options, value_manager_.get(), slots_); auto loop_step = std::make_unique<MockDirectStep>(); MockDirectStep* mock = loop_step.get(); EXPECT_CALL(*mock, Evaluate(_, _, _)) .Times(2) .WillRepeatedly([](ExecutionFrameBase&, Value& result, AttributeTrail&) { result = BoolValue(false); return absl::OkStatus(); }); ASSERT_OK_AND_ASSIGN(auto list, MakeList()); auto compre_step = CreateDirectComprehensionStep( 0, 1, CreateConstValueDirectStep(std::move(list)), CreateConstValueDirectStep(BoolValue(false)), std::move(loop_step), CreateConstValueDirectStep(BoolValue(false)), CreateDirectSlotIdentStep("__result__", 1, -1), false, -1); Value result; AttributeTrail trail; ASSERT_OK(compre_step->Evaluate(frame, result, trail)); EXPECT_THAT(result, BoolValueIs(false)); } } }
131
cpp
google/cel-cpp
evaluator_core
eval/eval/evaluator_core.cc
eval/eval/evaluator_core_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_EVALUATOR_CORE_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_EVALUATOR_CORE_H_ #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/type_provider.h" #include "common/memory.h" #include "common/native_type.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_utility.h" #include "eval/eval/comprehension_slots.h" #include "eval/eval/evaluator_stack.h" #include "runtime/activation_interface.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { class ExecutionFrame; using EvaluationListener = cel::TraceableProgram::EvaluationListener; class ExpressionStep { public: explicit ExpressionStep(int64_t id, bool comes_from_ast = true) : id_(id), comes_from_ast_(comes_from_ast) {} ExpressionStep(const ExpressionStep&) = delete; ExpressionStep& operator=(const ExpressionStep&) = delete; virtual ~ExpressionStep() = default; virtual absl::Status Evaluate(ExecutionFrame* context) const = 0; int64_t id() const { return id_; } bool comes_from_ast() const { return comes_from_ast_; } virtual cel::NativeTypeId GetNativeTypeId() const { return cel::NativeTypeId(); } private: const int64_t id_; const bool comes_from_ast_; }; using ExecutionPath = std::vector<std::unique_ptr<const ExpressionStep>>; using ExecutionPathView = absl::Span<const std::unique_ptr<const ExpressionStep>>; class FlatExpressionEvaluatorState { public: FlatExpressionEvaluatorState(size_t value_stack_size, size_t comprehension_slot_count, const cel::TypeProvider& type_provider, cel::MemoryManagerRef memory_manager); FlatExpressionEvaluatorState(size_t value_stack_size, size_t comprehension_slot_count, cel::ValueManager& value_factory); void Reset(); EvaluatorStack& value_stack() { return value_stack_; } ComprehensionSlots& comprehension_slots() { return comprehension_slots_; } cel::MemoryManagerRef memory_manager() { return value_factory_->GetMemoryManager(); } cel::TypeFactory& type_factory() { return *value_factory_; } cel::TypeManager& type_manager() { return *value_factory_; } cel::ValueManager& value_factory() { return *value_factory_; } cel::ValueManager& value_manager() { return *value_factory_; } private: EvaluatorStack value_stack_; ComprehensionSlots comprehension_slots_; absl::optional<cel::ManagedValueFactory> managed_value_factory_; cel::ValueManager* value_factory_; }; class ExecutionFrameBase { public: ExecutionFrameBase(const cel::ActivationInterface& activation, const cel::RuntimeOptions& options, cel::ValueManager& value_manager) : activation_(&activation), callback_(), options_(&options), value_manager_(&value_manager), attribute_utility_(activation.GetUnknownAttributes(), activation.GetMissingAttributes(), value_manager), slots_(&ComprehensionSlots::GetEmptyInstance()), max_iterations_(options.comprehension_max_iterations), iterations_(0) {} ExecutionFrameBase(const cel::ActivationInterface& activation, EvaluationListener callback, const cel::RuntimeOptions& options, cel::ValueManager& value_manager, ComprehensionSlots& slots) : activation_(&activation), callback_(std::move(callback)), options_(&options), value_manager_(&value_manager), attribute_utility_(activation.GetUnknownAttributes(), activation.GetMissingAttributes(), value_manager), slots_(&slots), max_iterations_(options.comprehension_max_iterations), iterations_(0) {} const cel::ActivationInterface& activation() const { return *activation_; } EvaluationListener& callback() { return callback_; } const cel::RuntimeOptions& options() const { return *options_; } cel::ValueManager& value_manager() { return *value_manager_; } const AttributeUtility& attribute_utility() const { return attribute_utility_; } bool attribute_tracking_enabled() const { return options_->unknown_processing != cel::UnknownProcessingOptions::kDisabled || options_->enable_missing_attribute_errors; } bool missing_attribute_errors_enabled() const { return options_->enable_missing_attribute_errors; } bool unknown_processing_enabled() const { return options_->unknown_processing != cel::UnknownProcessingOptions::kDisabled; } bool unknown_function_results_enabled() const { return options_->unknown_processing == cel::UnknownProcessingOptions::kAttributeAndFunction; } ComprehensionSlots& comprehension_slots() { return *slots_; } absl::Status IncrementIterations() { if (max_iterations_ == 0) { return absl::OkStatus(); } iterations_++; if (iterations_ >= max_iterations_) { return absl::Status(absl::StatusCode::kInternal, "Iteration budget exceeded"); } return absl::OkStatus(); } protected: absl::Nonnull<const cel::ActivationInterface*> activation_; EvaluationListener callback_; absl::Nonnull<const cel::RuntimeOptions*> options_; absl::Nonnull<cel::ValueManager*> value_manager_; AttributeUtility attribute_utility_; absl::Nonnull<ComprehensionSlots*> slots_; const int max_iterations_; int iterations_; }; class ExecutionFrame : public ExecutionFrameBase { public: ExecutionFrame(ExecutionPathView flat, const cel::ActivationInterface& activation, const cel::RuntimeOptions& options, FlatExpressionEvaluatorState& state, EvaluationListener callback = EvaluationListener()) : ExecutionFrameBase(activation, std::move(callback), options, state.value_manager(), state.comprehension_slots()), pc_(0UL), execution_path_(flat), state_(state), subexpressions_() {} ExecutionFrame(absl::Span<const ExecutionPathView> subexpressions, const cel::ActivationInterface& activation, const cel::RuntimeOptions& options, FlatExpressionEvaluatorState& state, EvaluationListener callback = EvaluationListener()) : ExecutionFrameBase(activation, std::move(callback), options, state.value_manager(), state.comprehension_slots()), pc_(0UL), execution_path_(subexpressions[0]), state_(state), subexpressions_(subexpressions) { ABSL_DCHECK(!subexpressions.empty()); } const ExpressionStep* Next(); absl::StatusOr<cel::Value> Evaluate(EvaluationListener& listener); absl::StatusOr<cel::Value> Evaluate() { return Evaluate(callback()); } absl::Status JumpTo(int offset) { int new_pc = static_cast<int>(pc_) + offset; if (new_pc < 0 || new_pc > static_cast<int>(execution_path_.size())) { return absl::Status(absl::StatusCode::kInternal, absl::StrCat("Jump address out of range: position: ", pc_, ",offset: ", offset, ", range: ", execution_path_.size())); } pc_ = static_cast<size_t>(new_pc); return absl::OkStatus(); } void Call(int return_pc_offset, size_t subexpression_index) { ABSL_DCHECK_LT(subexpression_index, subexpressions_.size()); ExecutionPathView subexpression = subexpressions_[subexpression_index]; ABSL_DCHECK(subexpression != execution_path_); int return_pc = static_cast<int>(pc_) + return_pc_offset; ABSL_DCHECK_GE(return_pc, 0); ABSL_DCHECK_LE(return_pc, static_cast<int>(execution_path_.size())); call_stack_.push_back(SubFrame{static_cast<size_t>(return_pc), value_stack().size() + 1, execution_path_}); pc_ = 0UL; execution_path_ = subexpression; } EvaluatorStack& value_stack() { return state_.value_stack(); } bool enable_attribute_tracking() const { return attribute_tracking_enabled(); } bool enable_unknowns() const { return unknown_processing_enabled(); } bool enable_unknown_function_results() const { return unknown_function_results_enabled(); } bool enable_missing_attribute_errors() const { return missing_attribute_errors_enabled(); } bool enable_heterogeneous_numeric_lookups() const { return options().enable_heterogeneous_equality; } bool enable_comprehension_list_append() const { return options().enable_comprehension_list_append; } cel::MemoryManagerRef memory_manager() { return state_.memory_manager(); } cel::TypeFactory& type_factory() { return state_.type_factory(); } cel::TypeManager& type_manager() { return state_.type_manager(); } cel::ValueManager& value_factory() { return state_.value_factory(); } const cel::ActivationInterface& modern_activation() const { return *activation_; } private: struct SubFrame { size_t return_pc; size_t expected_stack_size; ExecutionPathView return_expression; }; size_t pc_; ExecutionPathView execution_path_; FlatExpressionEvaluatorState& state_; absl::Span<const ExecutionPathView> subexpressions_; std::vector<SubFrame> call_stack_; }; class FlatExpression { public: FlatExpression(ExecutionPath path, size_t comprehension_slots_size, const cel::TypeProvider& type_provider, const cel::RuntimeOptions& options) : path_(std::move(path)), subexpressions_({path_}), comprehension_slots_size_(comprehension_slots_size), type_provider_(type_provider), options_(options) {} FlatExpression(ExecutionPath path, std::vector<ExecutionPathView> subexpressions, size_t comprehension_slots_size, const cel::TypeProvider& type_provider, const cel::RuntimeOptions& options) : path_(std::move(path)), subexpressions_(std::move(subexpressions)), comprehension_slots_size_(comprehension_slots_size), type_provider_(type_provider), options_(options) {} FlatExpression(FlatExpression&&) = default; FlatExpression& operator=(FlatExpression&&) = delete; FlatExpressionEvaluatorState MakeEvaluatorState( cel::MemoryManagerRef memory_manager) const; FlatExpressionEvaluatorState MakeEvaluatorState( cel::ValueManager& value_factory) const; absl::StatusOr<cel::Value> EvaluateWithCallback( const cel::ActivationInterface& activation, EvaluationListener listener, FlatExpressionEvaluatorState& state) const; cel::ManagedValueFactory MakeValueFactory( cel::MemoryManagerRef memory_manager) const; const ExecutionPath& path() const { return path_; } absl::Span<const ExecutionPathView> subexpressions() const { return subexpressions_; } const cel::RuntimeOptions& options() const { return options_; } size_t comprehension_slots_size() const { return comprehension_slots_size_; } private: ExecutionPath path_; std::vector<ExecutionPathView> subexpressions_; size_t comprehension_slots_size_; const cel::TypeProvider& type_provider_; cel::RuntimeOptions options_; }; } #endif #include "eval/eval/evaluator_core.h" #include <cstddef> #include <memory> #include <utility> #include "absl/base/optimization.h" #include "absl/log/absl_check.h" #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/optional.h" #include "absl/utility/utility.h" #include "base/type_provider.h" #include "common/memory.h" #include "common/value.h" #include "common/value_manager.h" #include "runtime/activation_interface.h" #include "runtime/managed_value_factory.h" namespace google::api::expr::runtime { FlatExpressionEvaluatorState::FlatExpressionEvaluatorState( size_t value_stack_size, size_t comprehension_slot_count, const cel::TypeProvider& type_provider, cel::MemoryManagerRef memory_manager) : value_stack_(value_stack_size), comprehension_slots_(comprehension_slot_count), managed_value_factory_(absl::in_place, type_provider, memory_manager), value_factory_(&managed_value_factory_->get()) {} FlatExpressionEvaluatorState::FlatExpressionEvaluatorState( size_t value_stack_size, size_t comprehension_slot_count, cel::ValueManager& value_factory) : value_stack_(value_stack_size), comprehension_slots_(comprehension_slot_count), managed_value_factory_(absl::nullopt), value_factory_(&value_factory) {} void FlatExpressionEvaluatorState::Reset() { value_stack_.Clear(); comprehension_slots_.Reset(); } const ExpressionStep* ExecutionFrame::Next() { while (true) { const size_t end_pos = execution_path_.size(); if (ABSL_PREDICT_TRUE(pc_ < end_pos)) { const auto* step = execution_path_[pc_++].get(); ABSL_ASSUME(step != nullptr); return step; } if (ABSL_PREDICT_TRUE(pc_ == end_pos)) { if (!call_stack_.empty()) { pc_ = call_stack_.back().return_pc; execution_path_ = call_stack_.back().return_expression; ABSL_DCHECK_EQ(value_stack().size(), call_stack_.back().expected_stack_size); call_stack_.pop_back(); continue; } } else { ABSL_LOG(ERROR) << "Attempting to step beyond the end of execution path."; } return nullptr; } } namespace { class EvaluationStatus final { public: explicit EvaluationStatus(absl::Status&& status) { ::new (static_cast<void*>(&status_[0])) absl::Status(std::move(status)); } EvaluationStatus() = delete; EvaluationStatus(const EvaluationStatus&) = delete; EvaluationStatus(EvaluationStatus&&) = delete; EvaluationStatus& operator=(const EvaluationStatus&) = delete; EvaluationStatus& operator=(EvaluationStatus&&) = delete; absl::Status Consume() && { return std::move(*reinterpret_cast<absl::Status*>(&status_[0])); } bool ok() const { return ABSL_PREDICT_TRUE( reinterpret_cast<const absl::Status*>(&status_[0])->ok()); } private: alignas(absl::Status) char status_[sizeof(absl::Status)]; }; } absl::StatusOr<cel::Value> ExecutionFrame::Evaluate( EvaluationListener& listener) { const size_t initial_stack_size = value_stack().size(); if (!listener) { for (const ExpressionStep* expr = Next(); ABSL_PREDICT_TRUE(expr != nullptr); expr = Next()) { if (EvaluationStatus status(expr->Evaluate(this)); !status.ok()) { return std::move(status).Consume(); } } } else { for (const ExpressionStep* expr = Next(); ABSL_PREDICT_TRUE(expr != nullptr); expr = Next()) { if (EvaluationStatus status(expr->Evaluate(this)); !status.ok()) { return std::move(status).Consume(); } if (!expr->comes_from_ast()) { continue; } if (ABSL_PREDICT_FALSE(value_stack().empty())) { ABSL_LOG(ERROR) << "Stack is empty after a ExpressionStep.Evaluate. " "Try to disable short-circuiting."; continue; } if (EvaluationStatus status( listener(expr->id(), value_stack().Peek(), value_factory())); !status.ok()) { return std::move(status).Consume(); } } } const size_t final_stack_size = value_stack().size(); if (ABSL_PREDICT_FALSE(final_stack_size != initial_stack_size + 1 || final_stack_size == 0)) { return absl::InternalError(absl::StrCat( "Stack error during evaluation: expected=", initial_stack_size + 1, ", actual=", final_stack_size)); } cel::Value value = std::move(value_stack().Peek()); value_stack().Pop(1); return value; } FlatExpressionEvaluatorState FlatExpression::MakeEvaluatorState( cel::MemoryManagerRef manager) const { return FlatExpressionEvaluatorState(path_.size(), comprehension_slots_size_, type_provider_, manager); } FlatExpressionEvaluatorState FlatExpression::MakeEvaluatorState( cel::ValueManager& value_factory) const { return FlatExpressionEvaluatorState(path_.size(), comprehension_slots_size_, value_factory); } absl::StatusOr<cel::Value> FlatExpression::EvaluateWithCallback( const cel::ActivationInterface& activation, EvaluationListener listener, FlatExpressionEvaluatorState& state) const { state.Reset(); ExecutionFrame frame(subexpressions_, activation, options_, state, std::move(listener)); return frame.Evaluate(frame.callback()); } cel::ManagedValueFactory FlatExpression::MakeValueFactory( cel::MemoryManagerRef memory_manager) const { return cel::ManagedValueFactory(type_provider_, memory_manager); } }
#include "eval/eval/evaluator_core.h" #include <memory> #include <utility> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "base/type_provider.h" #include "eval/compiler/cel_expression_builder_flat_impl.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/internal/interop.h" #include "eval/public/activation.h" #include "eval/public/builtin_func_registrar.h" #include "eval/public/cel_value.h" #include "extensions/protobuf/memory_manager.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { using ::cel::IntValue; using ::cel::TypeProvider; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::interop_internal::CreateIntValue; using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::runtime::RegisterBuiltinFunctions; using testing::_; using testing::Eq; class FakeConstExpressionStep : public ExpressionStep { public: FakeConstExpressionStep() : ExpressionStep(0, true) {} absl::Status Evaluate(ExecutionFrame* frame) const override { frame->value_stack().Push(CreateIntValue(0)); return absl::OkStatus(); } }; class FakeIncrementExpressionStep : public ExpressionStep { public: FakeIncrementExpressionStep() : ExpressionStep(0, true) {} absl::Status Evaluate(ExecutionFrame* frame) const override { auto value = frame->value_stack().Peek(); frame->value_stack().Pop(1); EXPECT_TRUE(value->Is<IntValue>()); int64_t val = value->As<IntValue>().NativeValue(); frame->value_stack().Push(CreateIntValue(val + 1)); return absl::OkStatus(); } }; TEST(EvaluatorCoreTest, ExecutionFrameNext) { ExecutionPath path; google::protobuf::Arena arena; auto manager = ProtoMemoryManagerRef(&arena); auto const_step = std::make_unique<const FakeConstExpressionStep>(); auto incr_step1 = std::make_unique<const FakeIncrementExpressionStep>(); auto incr_step2 = std::make_unique<const FakeIncrementExpressionStep>(); path.push_back(std::move(const_step)); path.push_back(std::move(incr_step1)); path.push_back(std::move(incr_step2)); auto dummy_expr = std::make_unique<Expr>(); cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kDisabled; cel::Activation activation; FlatExpressionEvaluatorState state(path.size(), 0, TypeProvider::Builtin(), manager); ExecutionFrame frame(path, activation, options, state); EXPECT_THAT(frame.Next(), Eq(path[0].get())); EXPECT_THAT(frame.Next(), Eq(path[1].get())); EXPECT_THAT(frame.Next(), Eq(path[2].get())); EXPECT_THAT(frame.Next(), Eq(nullptr)); } TEST(EvaluatorCoreTest, SimpleEvaluatorTest) { ExecutionPath path; auto const_step = std::make_unique<FakeConstExpressionStep>(); auto incr_step1 = std::make_unique<FakeIncrementExpressionStep>(); auto incr_step2 = std::make_unique<FakeIncrementExpressionStep>(); path.push_back(std::move(const_step)); path.push_back(std::move(incr_step1)); path.push_back(std::move(incr_step2)); CelExpressionFlatImpl impl(FlatExpression( std::move(path), 0, cel::TypeProvider::Builtin(), cel::RuntimeOptions{})); Activation activation; google::protobuf::Arena arena; auto status = impl.Evaluate(activation, &arena); EXPECT_OK(status); auto value = status.value(); EXPECT_TRUE(value.IsInt64()); EXPECT_THAT(value.Int64OrDie(), Eq(2)); } class MockTraceCallback { public: MOCK_METHOD(void, Call, (int64_t expr_id, const CelValue& value, google::protobuf::Arena*)); }; TEST(EvaluatorCoreTest, TraceTest) { Expr expr; google::api::expr::v1alpha1::SourceInfo source_info; expr.set_id(1); auto and_call = expr.mutable_call_expr(); and_call->set_function("_&&_"); auto true_expr = and_call->add_args(); true_expr->set_id(2); true_expr->mutable_const_expr()->set_int64_value(1); auto comp_expr = and_call->add_args(); comp_expr->set_id(3); auto comp = comp_expr->mutable_comprehension_expr(); comp->set_iter_var("x"); comp->set_accu_var("accu"); auto list_expr = comp->mutable_iter_range(); list_expr->set_id(4); auto el1_expr = list_expr->mutable_list_expr()->add_elements(); el1_expr->set_id(11); el1_expr->mutable_const_expr()->set_int64_value(1); auto el2_expr = list_expr->mutable_list_expr()->add_elements(); el2_expr->set_id(12); el2_expr->mutable_const_expr()->set_int64_value(2); auto el3_expr = list_expr->mutable_list_expr()->add_elements(); el3_expr->set_id(13); el3_expr->mutable_const_expr()->set_int64_value(3); auto accu_init_expr = comp->mutable_accu_init(); accu_init_expr->set_id(20); accu_init_expr->mutable_const_expr()->set_bool_value(true); auto loop_cond_expr = comp->mutable_loop_condition(); loop_cond_expr->set_id(21); loop_cond_expr->mutable_const_expr()->set_bool_value(true); auto loop_step_expr = comp->mutable_loop_step(); loop_step_expr->set_id(22); auto condition = loop_step_expr->mutable_call_expr(); condition->set_function("_>_"); auto iter_expr = condition->add_args(); iter_expr->set_id(23); iter_expr->mutable_ident_expr()->set_name("x"); auto zero_expr = condition->add_args(); zero_expr->set_id(24); zero_expr->mutable_const_expr()->set_int64_value(0); auto result_expr = comp->mutable_result(); result_expr->set_id(25); result_expr->mutable_const_expr()->set_bool_value(true); cel::RuntimeOptions options; options.short_circuiting = false; CelExpressionBuilderFlatImpl builder(options); ASSERT_OK(RegisterBuiltinFunctions(builder.GetRegistry())); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder.CreateExpression(&expr, &source_info)); Activation activation; google::protobuf::Arena arena; MockTraceCallback callback; EXPECT_CALL(callback, Call(accu_init_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(el1_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(el2_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(el3_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(list_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(loop_cond_expr->id(), _, &arena)).Times(3); EXPECT_CALL(callback, Call(iter_expr->id(), _, &arena)).Times(3); EXPECT_CALL(callback, Call(zero_expr->id(), _, &arena)).Times(3); EXPECT_CALL(callback, Call(loop_step_expr->id(), _, &arena)).Times(3); EXPECT_CALL(callback, Call(result_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(comp_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(true_expr->id(), _, &arena)); EXPECT_CALL(callback, Call(expr.id(), _, &arena)); auto eval_status = cel_expr->Trace( activation, &arena, [&](int64_t expr_id, const CelValue& value, google::protobuf::Arena* arena) { callback.Call(expr_id, value, arena); return absl::OkStatus(); }); ASSERT_OK(eval_status); } }
132
cpp
google/cel-cpp
optional_or_step
eval/eval/optional_or_step.cc
eval/eval/optional_or_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_OPTIONAL_OR_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_OPTIONAL_OR_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/jump_step.h" namespace google::api::expr::runtime { absl::StatusOr<std::unique_ptr<JumpStepBase>> CreateOptionalHasValueJumpStep( bool or_value, int64_t expr_id); std::unique_ptr<ExpressionStep> CreateOptionalOrStep(bool is_or_value, int64_t expr_id); std::unique_ptr<DirectExpressionStep> CreateDirectOptionalOrStep( int64_t expr_id, std::unique_ptr<DirectExpressionStep> optional, std::unique_ptr<DirectExpressionStep> alternative, bool is_or_value, bool short_circuiting); } #endif #include "eval/eval/optional_or_step.h" #include <cstdint> #include <memory> #include <utility> #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "common/casting.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/eval/jump_step.h" #include "internal/status_macros.h" #include "runtime/internal/errors.h" namespace google::api::expr::runtime { namespace { using ::cel::As; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::OptionalValue; using ::cel::UnknownValue; using ::cel::Value; using ::cel::runtime_internal::CreateNoMatchingOverloadError; enum class OptionalOrKind { kOrOptional, kOrValue }; ErrorValue MakeNoOverloadError(OptionalOrKind kind) { switch (kind) { case OptionalOrKind::kOrOptional: return ErrorValue(CreateNoMatchingOverloadError("or")); case OptionalOrKind::kOrValue: return ErrorValue(CreateNoMatchingOverloadError("orValue")); } ABSL_UNREACHABLE(); } class OptionalHasValueJumpStep final : public JumpStepBase { public: OptionalHasValueJumpStep(int64_t expr_id, OptionalOrKind kind) : JumpStepBase({}, expr_id), kind_(kind) {} absl::Status Evaluate(ExecutionFrame* frame) const override { if (!frame->value_stack().HasEnough(1)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } const auto& value = frame->value_stack().Peek(); auto optional_value = As<OptionalValue>(value); const bool should_jump = (optional_value.has_value() && optional_value->HasValue()) || (!optional_value.has_value() && (cel::InstanceOf<ErrorValue>(value) || cel::InstanceOf<UnknownValue>(value))); if (should_jump) { if (kind_ == OptionalOrKind::kOrValue && optional_value.has_value()) { frame->value_stack().PopAndPush(optional_value->Value()); } return Jump(frame); } return absl::OkStatus(); } private: const OptionalOrKind kind_; }; class OptionalOrStep : public ExpressionStepBase { public: explicit OptionalOrStep(int64_t expr_id, OptionalOrKind kind) : ExpressionStepBase(expr_id), kind_(kind) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: const OptionalOrKind kind_; }; absl::Status EvalOptionalOr(OptionalOrKind kind, const Value& lhs, const Value& rhs, const AttributeTrail& lhs_attr, const AttributeTrail& rhs_attr, Value& result, AttributeTrail& result_attr) { if (InstanceOf<ErrorValue>(lhs) || InstanceOf<UnknownValue>(lhs)) { result = lhs; result_attr = lhs_attr; return absl::OkStatus(); } auto lhs_optional_value = As<OptionalValue>(lhs); if (!lhs_optional_value.has_value()) { result = MakeNoOverloadError(kind); result_attr = AttributeTrail(); return absl::OkStatus(); } if (lhs_optional_value->HasValue()) { if (kind == OptionalOrKind::kOrValue) { result = lhs_optional_value->Value(); } else { result = lhs; } result_attr = lhs_attr; return absl::OkStatus(); } if (kind == OptionalOrKind::kOrOptional && !InstanceOf<ErrorValue>(rhs) && !InstanceOf<UnknownValue>(rhs) && !InstanceOf<OptionalValue>(rhs)) { result = MakeNoOverloadError(kind); result_attr = AttributeTrail(); return absl::OkStatus(); } result = rhs; result_attr = rhs_attr; return absl::OkStatus(); } absl::Status OptionalOrStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(2)) { return absl::InternalError("Value stack underflow"); } absl::Span<const Value> args = frame->value_stack().GetSpan(2); absl::Span<const AttributeTrail> args_attr = frame->value_stack().GetAttributeSpan(2); Value result; AttributeTrail result_attr; CEL_RETURN_IF_ERROR(EvalOptionalOr(kind_, args[0], args[1], args_attr[0], args_attr[1], result, result_attr)); frame->value_stack().PopAndPush(2, std::move(result), std::move(result_attr)); return absl::OkStatus(); } class ExhaustiveDirectOptionalOrStep : public DirectExpressionStep { public: ExhaustiveDirectOptionalOrStep( int64_t expr_id, std::unique_ptr<DirectExpressionStep> optional, std::unique_ptr<DirectExpressionStep> alternative, OptionalOrKind kind) : DirectExpressionStep(expr_id), kind_(kind), optional_(std::move(optional)), alternative_(std::move(alternative)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override; private: OptionalOrKind kind_; std::unique_ptr<DirectExpressionStep> optional_; std::unique_ptr<DirectExpressionStep> alternative_; }; absl::Status ExhaustiveDirectOptionalOrStep::Evaluate( ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const { CEL_RETURN_IF_ERROR(optional_->Evaluate(frame, result, attribute)); Value rhs; AttributeTrail rhs_attr; CEL_RETURN_IF_ERROR(alternative_->Evaluate(frame, rhs, rhs_attr)); CEL_RETURN_IF_ERROR(EvalOptionalOr(kind_, result, rhs, attribute, rhs_attr, result, attribute)); return absl::OkStatus(); } class DirectOptionalOrStep : public DirectExpressionStep { public: DirectOptionalOrStep(int64_t expr_id, std::unique_ptr<DirectExpressionStep> optional, std::unique_ptr<DirectExpressionStep> alternative, OptionalOrKind kind) : DirectExpressionStep(expr_id), kind_(kind), optional_(std::move(optional)), alternative_(std::move(alternative)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override; private: OptionalOrKind kind_; std::unique_ptr<DirectExpressionStep> optional_; std::unique_ptr<DirectExpressionStep> alternative_; }; absl::Status DirectOptionalOrStep::Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const { CEL_RETURN_IF_ERROR(optional_->Evaluate(frame, result, attribute)); if (InstanceOf<UnknownValue>(result) || InstanceOf<ErrorValue>(result)) { return absl::OkStatus(); } auto optional_value = As<OptionalValue>(static_cast<const Value&>(result)); if (!optional_value.has_value()) { result = MakeNoOverloadError(kind_); return absl::OkStatus(); } if (optional_value->HasValue()) { if (kind_ == OptionalOrKind::kOrValue) { result = optional_value->Value(); } return absl::OkStatus(); } CEL_RETURN_IF_ERROR(alternative_->Evaluate(frame, result, attribute)); if (kind_ == OptionalOrKind::kOrOptional) { if (!InstanceOf<OptionalValue>(result) && !InstanceOf<ErrorValue>(result) && !InstanceOf<UnknownValue>(result)) { result = MakeNoOverloadError(kind_); } } return absl::OkStatus(); } } absl::StatusOr<std::unique_ptr<JumpStepBase>> CreateOptionalHasValueJumpStep( bool or_value, int64_t expr_id) { return std::make_unique<OptionalHasValueJumpStep>( expr_id, or_value ? OptionalOrKind::kOrValue : OptionalOrKind::kOrOptional); } std::unique_ptr<ExpressionStep> CreateOptionalOrStep(bool is_or_value, int64_t expr_id) { return std::make_unique<OptionalOrStep>( expr_id, is_or_value ? OptionalOrKind::kOrValue : OptionalOrKind::kOrOptional); } std::unique_ptr<DirectExpressionStep> CreateDirectOptionalOrStep( int64_t expr_id, std::unique_ptr<DirectExpressionStep> optional, std::unique_ptr<DirectExpressionStep> alternative, bool is_or_value, bool short_circuiting) { auto kind = is_or_value ? OptionalOrKind::kOrValue : OptionalOrKind::kOrOptional; if (short_circuiting) { return std::make_unique<DirectOptionalOrStep>(expr_id, std::move(optional), std::move(alternative), kind); } else { return std::make_unique<ExhaustiveDirectOptionalOrStep>( expr_id, std::move(optional), std::move(alternative), kind); } } }
#include "eval/eval/optional_or_step.h" #include <memory> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "common/casting.h" #include "common/memory.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_kind.h" #include "common/value_testing.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/const_value_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/internal/errors.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::Activation; using ::cel::As; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ManagedValueFactory; using ::cel::MemoryManagerRef; using ::cel::OptionalValue; using ::cel::RuntimeOptions; using ::cel::TypeReflector; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ValueKind; using ::cel::test::ErrorValueIs; using ::cel::test::IntValueIs; using ::cel::test::OptionalValueIs; using ::cel::test::ValueKindIs; using testing::HasSubstr; using testing::NiceMock; using cel::internal::StatusIs; class MockDirectStep : public DirectExpressionStep { public: MOCK_METHOD(absl::Status, Evaluate, (ExecutionFrameBase & frame, Value& result, AttributeTrail& scratch), (const override)); }; std::unique_ptr<DirectExpressionStep> MockNeverCalledDirectStep() { auto* mock = new NiceMock<MockDirectStep>(); EXPECT_CALL(*mock, Evaluate).Times(0); return absl::WrapUnique(mock); } std::unique_ptr<DirectExpressionStep> MockExpectCallDirectStep() { auto* mock = new NiceMock<MockDirectStep>(); EXPECT_CALL(*mock, Evaluate) .Times(1) .WillRepeatedly( [](ExecutionFrameBase& frame, Value& result, AttributeTrail& attr) { result = ErrorValue(absl::InternalError("expected to be unused")); return absl::OkStatus(); }); return absl::WrapUnique(mock); } class OptionalOrTest : public testing::Test { public: OptionalOrTest() : value_factory_(TypeReflector::Builtin(), MemoryManagerRef::ReferenceCounting()) {} protected: ManagedValueFactory value_factory_; Activation empty_activation_; }; TEST_F(OptionalOrTest, OptionalOrLeftPresentShortcutRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(OptionalValue::Of( value_factory_.get().GetMemoryManager(), IntValue(42))), MockNeverCalledDirectStep(), false, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, OptionalValueIs(IntValueIs(42))); } TEST_F(OptionalOrTest, OptionalOrLeftErrorShortcutsRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(ErrorValue(absl::InternalError("error"))), MockNeverCalledDirectStep(), false, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ValueKindIs(ValueKind::kError)); } TEST_F(OptionalOrTest, OptionalOrLeftErrorExhaustiveRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(ErrorValue(absl::InternalError("error"))), MockExpectCallDirectStep(), false, false); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ValueKindIs(ValueKind::kError)); } TEST_F(OptionalOrTest, OptionalOrLeftUnknownShortcutsRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(UnknownValue()), MockNeverCalledDirectStep(), false, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ValueKindIs(ValueKind::kUnknown)); } TEST_F(OptionalOrTest, OptionalOrLeftUnknownExhaustiveRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(UnknownValue()), MockExpectCallDirectStep(), false, false); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ValueKindIs(ValueKind::kUnknown)); } TEST_F(OptionalOrTest, OptionalOrLeftAbsentReturnRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(OptionalValue::None()), CreateConstValueDirectStep(OptionalValue::Of( value_factory_.get().GetMemoryManager(), IntValue(42))), false, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, OptionalValueIs(IntValueIs(42))); } TEST_F(OptionalOrTest, OptionalOrLeftWrongType) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(IntValue(42)), MockNeverCalledDirectStep(), false, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ErrorValueIs(StatusIs( absl::StatusCode::kUnknown, HasSubstr(cel::runtime_internal::kErrNoMatchingOverload)))); } TEST_F(OptionalOrTest, OptionalOrRightWrongType) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(OptionalValue::None()), CreateConstValueDirectStep(IntValue(42)), false, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ErrorValueIs(StatusIs( absl::StatusCode::kUnknown, HasSubstr(cel::runtime_internal::kErrNoMatchingOverload)))); } TEST_F(OptionalOrTest, OptionalOrValueLeftPresentShortcutRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(OptionalValue::Of( value_factory_.get().GetMemoryManager(), IntValue(42))), MockNeverCalledDirectStep(), true, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, IntValueIs(42)); } TEST_F(OptionalOrTest, OptionalOrValueLeftPresentExhaustiveRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(OptionalValue::Of( value_factory_.get().GetMemoryManager(), IntValue(42))), MockExpectCallDirectStep(), true, false); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, IntValueIs(42)); } TEST_F(OptionalOrTest, OptionalOrValueLeftErrorShortcutsRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(ErrorValue(absl::InternalError("error"))), MockNeverCalledDirectStep(), true, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ValueKindIs(ValueKind::kError)); } TEST_F(OptionalOrTest, OptionalOrValueLeftUnknownShortcutsRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(UnknownValue()), MockNeverCalledDirectStep(), true, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ValueKindIs(ValueKind::kUnknown)); } TEST_F(OptionalOrTest, OptionalOrValueLeftAbsentReturnRight) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(OptionalValue::None()), CreateConstValueDirectStep(IntValue(42)), true, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, IntValueIs(42)); } TEST_F(OptionalOrTest, OptionalOrValueLeftWrongType) { RuntimeOptions options; ExecutionFrameBase frame(empty_activation_, options, value_factory_.get()); std::unique_ptr<DirectExpressionStep> step = CreateDirectOptionalOrStep( -1, CreateConstValueDirectStep(IntValue(42)), MockNeverCalledDirectStep(), true, true); Value result; AttributeTrail scratch; ASSERT_OK(step->Evaluate(frame, result, scratch)); EXPECT_THAT(result, ErrorValueIs(StatusIs( absl::StatusCode::kUnknown, HasSubstr(cel::runtime_internal::kErrNoMatchingOverload)))); } } }
133
cpp
google/cel-cpp
shadowable_value_step
eval/eval/shadowable_value_step.cc
eval/eval/shadowable_value_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_SHADOWABLE_VALUE_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_SHADOWABLE_VALUE_STEP_H_ #include <cstdint> #include <memory> #include <string> #include "absl/status/statusor.h" #include "common/value.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateShadowableValueStep( std::string identifier, cel::Value value, int64_t expr_id); std::unique_ptr<DirectExpressionStep> CreateDirectShadowableValueStep( std::string identifier, cel::Value value, int64_t expr_id); } #endif #include "eval/eval/shadowable_value_step.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using ::cel::Value; class ShadowableValueStep : public ExpressionStepBase { public: ShadowableValueStep(std::string identifier, cel::Value value, int64_t expr_id) : ExpressionStepBase(expr_id), identifier_(std::move(identifier)), value_(std::move(value)) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: std::string identifier_; Value value_; }; absl::Status ShadowableValueStep::Evaluate(ExecutionFrame* frame) const { cel::Value scratch; CEL_ASSIGN_OR_RETURN( auto var, frame->modern_activation().FindVariable(frame->value_factory(), identifier_, scratch)); if (var.has_value()) { frame->value_stack().Push(cel::Value{*var}); } else { frame->value_stack().Push(value_); } return absl::OkStatus(); } class DirectShadowableValueStep : public DirectExpressionStep { public: DirectShadowableValueStep(std::string identifier, cel::Value value, int64_t expr_id) : DirectExpressionStep(expr_id), identifier_(std::move(identifier)), value_(std::move(value)) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override; private: std::string identifier_; Value value_; }; absl::Status DirectShadowableValueStep::Evaluate( ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const { cel::Value scratch; CEL_ASSIGN_OR_RETURN(auto var, frame.activation().FindVariable(frame.value_manager(), identifier_, scratch)); if (var.has_value()) { result = *var; } else { result = value_; } return absl::OkStatus(); } } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateShadowableValueStep( std::string identifier, cel::Value value, int64_t expr_id) { return absl::make_unique<ShadowableValueStep>(std::move(identifier), std::move(value), expr_id); } std::unique_ptr<DirectExpressionStep> CreateDirectShadowableValueStep( std::string identifier, cel::Value value, int64_t expr_id) { return std::make_unique<DirectShadowableValueStep>(std::move(identifier), std::move(value), expr_id); } }
#include "eval/eval/shadowable_value_step.h" #include <string> #include <utility> #include "absl/status/statusor.h" #include "base/type_provider.h" #include "common/value.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/evaluator_core.h" #include "eval/internal/interop.h" #include "eval/public/activation.h" #include "eval/public/cel_value.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeProvider; using ::cel::interop_internal::CreateTypeValueFromView; using ::google::protobuf::Arena; using testing::Eq; absl::StatusOr<CelValue> RunShadowableExpression(std::string identifier, cel::Value value, const Activation& activation, Arena* arena) { CEL_ASSIGN_OR_RETURN( auto step, CreateShadowableValueStep(std::move(identifier), std::move(value), 1)); ExecutionPath path; path.push_back(std::move(step)); CelExpressionFlatImpl impl( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); return impl.Evaluate(activation, arena); } TEST(ShadowableValueStepTest, TestEvaluateNoShadowing) { std::string type_name = "google.api.expr.runtime.TestMessage"; Activation activation; Arena arena; auto type_value = CreateTypeValueFromView(&arena, type_name); auto status = RunShadowableExpression(type_name, type_value, activation, &arena); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsCelType()); EXPECT_THAT(value.CelTypeOrDie().value(), Eq(type_name)); } TEST(ShadowableValueStepTest, TestEvaluateShadowedIdentifier) { std::string type_name = "int"; auto shadow_value = CelValue::CreateInt64(1024L); Activation activation; activation.InsertValue(type_name, shadow_value); Arena arena; auto type_value = CreateTypeValueFromView(&arena, type_name); auto status = RunShadowableExpression(type_name, type_value, activation, &arena); ASSERT_OK(status); auto value = status.value(); ASSERT_TRUE(value.IsInt64()); EXPECT_THAT(value.Int64OrDie(), Eq(1024L)); } } }
134
cpp
google/cel-cpp
container_access_step
eval/eval/container_access_step.cc
eval/eval/container_access_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_CONTAINER_ACCESS_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_CONTAINER_ACCESS_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "base/ast_internal/expr.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectContainerAccessStep( std::unique_ptr<DirectExpressionStep> container_step, std::unique_ptr<DirectExpressionStep> key_step, bool enable_optional_types, int64_t expr_id); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateContainerAccessStep( const cel::ast_internal::Call& call, int64_t expr_id, bool enable_optional_types = false); } #endif #include "eval/eval/container_access_step.h" #include <cstdint> #include <memory> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/ast_internal/expr.h" #include "base/attribute.h" #include "base/kind.h" #include "common/casting.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_kind.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/attribute_utility.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "internal/casts.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/internal/errors.h" namespace google::api::expr::runtime { namespace { using ::cel::AttributeQualifier; using ::cel::BoolValue; using ::cel::Cast; using ::cel::DoubleValue; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ListValue; using ::cel::MapValue; using ::cel::StringValue; using ::cel::UintValue; using ::cel::Value; using ::cel::ValueKind; using ::cel::ValueKindToString; using ::cel::ValueView; using ::cel::internal::Number; using ::cel::runtime_internal::CreateNoSuchKeyError; inline constexpr int kNumContainerAccessArguments = 2; absl::optional<Number> CelNumberFromValue(const Value& value) { switch (value->kind()) { case ValueKind::kInt64: return Number::FromInt64(value.As<IntValue>().NativeValue()); case ValueKind::kUint64: return Number::FromUint64(value.As<UintValue>().NativeValue()); case ValueKind::kDouble: return Number::FromDouble(value.As<DoubleValue>().NativeValue()); default: return absl::nullopt; } } absl::Status CheckMapKeyType(const Value& key) { ValueKind kind = key->kind(); switch (kind) { case ValueKind::kString: case ValueKind::kInt64: case ValueKind::kUint64: case ValueKind::kBool: return absl::OkStatus(); default: return absl::InvalidArgumentError(absl::StrCat( "Invalid map key type: '", ValueKindToString(kind), "'")); } } AttributeQualifier AttributeQualifierFromValue(const Value& v) { switch (v->kind()) { case ValueKind::kString: return AttributeQualifier::OfString(v.As<StringValue>().ToString()); case ValueKind::kInt64: return AttributeQualifier::OfInt(v.As<IntValue>().NativeValue()); case ValueKind::kUint64: return AttributeQualifier::OfUint(v.As<UintValue>().NativeValue()); case ValueKind::kBool: return AttributeQualifier::OfBool(v.As<BoolValue>().NativeValue()); default: return AttributeQualifier(); } } ValueView LookupInMap(const MapValue& cel_map, const Value& key, ExecutionFrameBase& frame, Value& scratch) { if (frame.options().enable_heterogeneous_equality) { absl::optional<Number> number = CelNumberFromValue(key); if (number.has_value()) { if (key->Is<UintValue>()) { auto lookup = cel_map.Find(frame.value_manager(), key, scratch); if (!lookup.ok()) { scratch = frame.value_manager().CreateErrorValue( std::move(lookup).status()); return scratch; } if (*lookup) { return scratch; } } if (number->LosslessConvertibleToInt()) { auto lookup = cel_map.Find( frame.value_manager(), frame.value_manager().CreateIntValue(number->AsInt()), scratch); if (!lookup.ok()) { scratch = frame.value_manager().CreateErrorValue( std::move(lookup).status()); return scratch; } if (*lookup) { return scratch; } } if (number->LosslessConvertibleToUint()) { auto lookup = cel_map.Find( frame.value_manager(), frame.value_manager().CreateUintValue(number->AsUint()), scratch); if (!lookup.ok()) { scratch = frame.value_manager().CreateErrorValue( std::move(lookup).status()); return scratch; } if (*lookup) { return scratch; } } scratch = frame.value_manager().CreateErrorValue( CreateNoSuchKeyError(key->DebugString())); return scratch; } } absl::Status status = CheckMapKeyType(key); if (!status.ok()) { scratch = frame.value_manager().CreateErrorValue(std::move(status)); return ValueView{scratch}; } absl::Status lookup = cel_map.Get(frame.value_manager(), key, scratch); if (!lookup.ok()) { scratch = frame.value_manager().CreateErrorValue(std::move(lookup)); return scratch; } return scratch; } ValueView LookupInList(const ListValue& cel_list, const Value& key, ExecutionFrameBase& frame, Value& scratch) { absl::optional<int64_t> maybe_idx; if (frame.options().enable_heterogeneous_equality) { auto number = CelNumberFromValue(key); if (number.has_value() && number->LosslessConvertibleToInt()) { maybe_idx = number->AsInt(); } } else if (InstanceOf<IntValue>(key)) { maybe_idx = key.As<IntValue>().NativeValue(); } if (!maybe_idx.has_value()) { scratch = frame.value_manager().CreateErrorValue(absl::UnknownError( absl::StrCat("Index error: expected integer type, got ", cel::KindToString(ValueKindToKind(key->kind()))))); return ValueView{scratch}; } int64_t idx = *maybe_idx; auto size = cel_list.Size(); if (!size.ok()) { scratch = frame.value_manager().CreateErrorValue(size.status()); return ValueView{scratch}; } if (idx < 0 || idx >= *size) { scratch = frame.value_manager().CreateErrorValue(absl::UnknownError( absl::StrCat("Index error: index=", idx, " size=", *size))); return ValueView{scratch}; } absl::Status lookup = cel_list.Get(frame.value_manager(), idx, scratch); if (!lookup.ok()) { scratch = frame.value_manager().CreateErrorValue(std::move(lookup)); return ValueView{scratch}; } return scratch; } ValueView LookupInContainer(const Value& container, const Value& key, ExecutionFrameBase& frame, Value& scratch) { switch (container.kind()) { case ValueKind::kMap: { return LookupInMap(Cast<MapValue>(container), key, frame, scratch); } case ValueKind::kList: { return LookupInList(Cast<ListValue>(container), key, frame, scratch); } default: scratch = frame.value_manager().CreateErrorValue(absl::InvalidArgumentError( absl::StrCat("Invalid container type: '", ValueKindToString(container->kind()), "'"))); return ValueView{scratch}; } } ValueView PerformLookup(ExecutionFrameBase& frame, const Value& container, const Value& key, const AttributeTrail& container_trail, bool enable_optional_types, Value& scratch, AttributeTrail& trail) { if (frame.unknown_processing_enabled()) { AttributeUtility::Accumulator unknowns = frame.attribute_utility().CreateAccumulator(); unknowns.MaybeAdd(container); unknowns.MaybeAdd(key); if (!unknowns.IsEmpty()) { scratch = std::move(unknowns).Build(); return ValueView{scratch}; } trail = container_trail.Step(AttributeQualifierFromValue(key)); if (frame.attribute_utility().CheckForUnknownExact(trail)) { scratch = frame.attribute_utility().CreateUnknownSet(trail.attribute()); return ValueView{scratch}; } } if (InstanceOf<ErrorValue>(container)) { scratch = container; return ValueView{scratch}; } if (InstanceOf<ErrorValue>(key)) { scratch = key; return ValueView{scratch}; } if (enable_optional_types && cel::NativeTypeId::Of(container) == cel::NativeTypeId::For<cel::OptionalValueInterface>()) { const auto& optional_value = *cel::internal::down_cast<const cel::OptionalValueInterface*>( cel::Cast<cel::OpaqueValue>(container).operator->()); if (!optional_value.HasValue()) { scratch = cel::OptionalValue::None(); return ValueView{scratch}; } auto result = LookupInContainer(optional_value.Value(), key, frame, scratch); if (auto error_value = cel::As<cel::ErrorValueView>(result); error_value && cel::IsNoSuchKey(error_value->NativeValue())) { scratch = cel::OptionalValue::None(); return ValueView{scratch}; } scratch = cel::OptionalValue::Of(frame.value_manager().GetMemoryManager(), Value{result}); return ValueView{scratch}; } return LookupInContainer(container, key, frame, scratch); } class ContainerAccessStep : public ExpressionStepBase { public: ContainerAccessStep(int64_t expr_id, bool enable_optional_types) : ExpressionStepBase(expr_id), enable_optional_types_(enable_optional_types) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: bool enable_optional_types_; }; absl::Status ContainerAccessStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(kNumContainerAccessArguments)) { return absl::Status( absl::StatusCode::kInternal, "Insufficient arguments supplied for ContainerAccess-type expression"); } Value scratch; AttributeTrail result_trail; auto args = frame->value_stack().GetSpan(kNumContainerAccessArguments); const AttributeTrail& container_trail = frame->value_stack().GetAttributeSpan(kNumContainerAccessArguments)[0]; auto result = PerformLookup(*frame, args[0], args[1], container_trail, enable_optional_types_, scratch, result_trail); frame->value_stack().PopAndPush(kNumContainerAccessArguments, Value{result}, std::move(result_trail)); return absl::OkStatus(); } class DirectContainerAccessStep : public DirectExpressionStep { public: DirectContainerAccessStep( std::unique_ptr<DirectExpressionStep> container_step, std::unique_ptr<DirectExpressionStep> key_step, bool enable_optional_types, int64_t expr_id) : DirectExpressionStep(expr_id), container_step_(std::move(container_step)), key_step_(std::move(key_step)), enable_optional_types_(enable_optional_types) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& trail) const override; private: std::unique_ptr<DirectExpressionStep> container_step_; std::unique_ptr<DirectExpressionStep> key_step_; bool enable_optional_types_; }; absl::Status DirectContainerAccessStep::Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& trail) const { Value container; Value key; AttributeTrail container_trail; AttributeTrail key_trail; CEL_RETURN_IF_ERROR( container_step_->Evaluate(frame, container, container_trail)); CEL_RETURN_IF_ERROR(key_step_->Evaluate(frame, key, key_trail)); result = PerformLookup(frame, container, key, container_trail, enable_optional_types_, result, trail); return absl::OkStatus(); } } std::unique_ptr<DirectExpressionStep> CreateDirectContainerAccessStep( std::unique_ptr<DirectExpressionStep> container_step, std::unique_ptr<DirectExpressionStep> key_step, bool enable_optional_types, int64_t expr_id) { return std::make_unique<DirectContainerAccessStep>( std::move(container_step), std::move(key_step), enable_optional_types, expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateContainerAccessStep( const cel::ast_internal::Call& call, int64_t expr_id, bool enable_optional_types) { int arg_count = call.args().size() + (call.has_target() ? 1 : 0); if (arg_count != kNumContainerAccessArguments) { return absl::InvalidArgumentError(absl::StrCat( "Invalid argument count for index operation: ", arg_count)); } return std::make_unique<ContainerAccessStep>(expr_id, enable_optional_types); } }
#include "eval/eval/container_access_step.h" #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/struct.pb.h" #include "absl/status/status.h" #include "base/builtins.h" #include "base/type_provider.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/testing/matchers.h" #include "eval/public/unknown_set.h" #include "internal/testing.h" #include "parser/parser.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::TypeProvider; using ::cel::ast_internal::Expr; using ::cel::ast_internal::SourceInfo; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::protobuf::Struct; using testing::_; using testing::AllOf; using testing::HasSubstr; using cel::internal::StatusIs; using TestParamType = std::tuple<bool, bool, bool>; CelValue EvaluateAttributeHelper( google::protobuf::Arena* arena, CelValue container, CelValue key, bool use_recursive_impl, bool receiver_style, bool enable_unknown, const std::vector<CelAttributePattern>& patterns) { ExecutionPath path; Expr expr; SourceInfo source_info; auto& call = expr.mutable_call_expr(); call.set_function(cel::builtin::kIndex); call.mutable_args().reserve(2); Expr& container_expr = (receiver_style) ? call.mutable_target() : call.mutable_args().emplace_back(); Expr& key_expr = call.mutable_args().emplace_back(); container_expr.mutable_ident_expr().set_name("container"); key_expr.mutable_ident_expr().set_name("key"); if (use_recursive_impl) { path.push_back(std::make_unique<WrappedDirectStep>( CreateDirectContainerAccessStep(CreateDirectIdentStep("container", 1), CreateDirectIdentStep("key", 2), false, 3), 3)); } else { path.push_back( std::move(CreateIdentStep(container_expr.ident_expr(), 1).value())); path.push_back( std::move(CreateIdentStep(key_expr.ident_expr(), 2).value())); path.push_back(std::move(CreateContainerAccessStep(call, 3).value())); } cel::RuntimeOptions options; options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; options.enable_heterogeneous_equality = false; CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; activation.InsertValue("container", container); activation.InsertValue("key", key); activation.set_unknown_attribute_patterns(patterns); auto result = cel_expr.Evaluate(activation, arena); return *result; } class ContainerAccessStepTest : public ::testing::Test { protected: ContainerAccessStepTest() = default; void SetUp() override {} CelValue EvaluateAttribute( CelValue container, CelValue key, bool receiver_style, bool enable_unknown, bool use_recursive_impl = false, const std::vector<CelAttributePattern>& patterns = {}) { return EvaluateAttributeHelper(&arena_, container, key, receiver_style, enable_unknown, use_recursive_impl, patterns); } google::protobuf::Arena arena_; }; class ContainerAccessStepUniformityTest : public ::testing::TestWithParam<TestParamType> { protected: ContainerAccessStepUniformityTest() = default; void SetUp() override {} bool receiver_style() { TestParamType params = GetParam(); return std::get<0>(params); } bool enable_unknown() { TestParamType params = GetParam(); return std::get<1>(params); } bool use_recursive_impl() { TestParamType params = GetParam(); return std::get<2>(params); } CelValue EvaluateAttribute( CelValue container, CelValue key, bool receiver_style, bool enable_unknown, bool use_recursive_impl = false, const std::vector<CelAttributePattern>& patterns = {}) { return EvaluateAttributeHelper(&arena_, container, key, receiver_style, enable_unknown, use_recursive_impl, patterns); } google::protobuf::Arena arena_; }; TEST_P(ContainerAccessStepUniformityTest, TestListIndexAccess) { ContainerBackedListImpl cel_list({CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3)}); CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(1), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsInt64()); ASSERT_EQ(result.Int64OrDie(), 2); } TEST_P(ContainerAccessStepUniformityTest, TestListIndexAccessOutOfBounds) { ContainerBackedListImpl cel_list({CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3)}); CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(0), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsInt64()); result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(2), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsInt64()); result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(-1), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsError()); result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(3), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsError()); } TEST_P(ContainerAccessStepUniformityTest, TestListIndexAccessNotAnInt) { ContainerBackedListImpl cel_list({CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3)}); CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateUint64(1), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsError()); } TEST_P(ContainerAccessStepUniformityTest, TestMapKeyAccess) { const std::string kKey0 = "testkey0"; const std::string kKey1 = "testkey1"; const std::string kKey2 = "testkey2"; Struct cel_struct; (*cel_struct.mutable_fields())[kKey0].set_string_value("value0"); (*cel_struct.mutable_fields())[kKey1].set_string_value("value1"); (*cel_struct.mutable_fields())[kKey2].set_string_value("value2"); CelValue result = EvaluateAttribute( CelProtoWrapper::CreateMessage(&cel_struct, &arena_), CelValue::CreateString(&kKey0), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsString()); ASSERT_EQ(result.StringOrDie().value(), "value0"); } TEST_P(ContainerAccessStepUniformityTest, TestBoolKeyType) { CelMapBuilder cel_map; ASSERT_OK(cel_map.Add(CelValue::CreateBool(true), CelValue::CreateStringView("value_true"))); CelValue result = EvaluateAttribute(CelValue::CreateMap(&cel_map), CelValue::CreateBool(true), receiver_style(), enable_unknown()); ASSERT_THAT(result, test::IsCelString("value_true")); } TEST_P(ContainerAccessStepUniformityTest, TestMapKeyAccessNotFound) { const std::string kKey0 = "testkey0"; const std::string kKey1 = "testkey1"; Struct cel_struct; (*cel_struct.mutable_fields())[kKey0].set_string_value("value0"); CelValue result = EvaluateAttribute( CelProtoWrapper::CreateMessage(&cel_struct, &arena_), CelValue::CreateString(&kKey1), receiver_style(), enable_unknown()); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kNotFound, AllOf(HasSubstr("Key not found in map : "), HasSubstr("testkey1")))); } TEST_F(ContainerAccessStepTest, TestInvalidReceiverCreateContainerAccessStep) { Expr expr; auto& call = expr.mutable_call_expr(); call.set_function(cel::builtin::kIndex); Expr& container_expr = call.mutable_target(); container_expr.mutable_ident_expr().set_name("container"); call.mutable_args().reserve(2); Expr& key_expr = call.mutable_args().emplace_back(); key_expr.mutable_ident_expr().set_name("key"); Expr& extra_arg = call.mutable_args().emplace_back(); extra_arg.mutable_const_expr().set_bool_value(true); EXPECT_THAT(CreateContainerAccessStep(call, 0).status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid argument count"))); } TEST_F(ContainerAccessStepTest, TestInvalidGlobalCreateContainerAccessStep) { Expr expr; auto& call = expr.mutable_call_expr(); call.set_function(cel::builtin::kIndex); call.mutable_args().reserve(3); Expr& container_expr = call.mutable_args().emplace_back(); container_expr.mutable_ident_expr().set_name("container"); Expr& key_expr = call.mutable_args().emplace_back(); key_expr.mutable_ident_expr().set_name("key"); Expr& extra_arg = call.mutable_args().emplace_back(); extra_arg.mutable_const_expr().set_bool_value(true); EXPECT_THAT(CreateContainerAccessStep(call, 0).status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid argument count"))); } TEST_F(ContainerAccessStepTest, TestListIndexAccessUnknown) { ContainerBackedListImpl cel_list({CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3)}); CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(1), true, true, {}); ASSERT_TRUE(result.IsInt64()); ASSERT_EQ(result.Int64OrDie(), 2); std::vector<CelAttributePattern> patterns = {CelAttributePattern( "container", {CreateCelAttributeQualifierPattern(CelValue::CreateInt64(1))})}; result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateInt64(1), true, true, false, patterns); ASSERT_TRUE(result.IsUnknownSet()); } TEST_F(ContainerAccessStepTest, TestListUnknownKey) { ContainerBackedListImpl cel_list({CelValue::CreateInt64(1), CelValue::CreateInt64(2), CelValue::CreateInt64(3)}); UnknownSet unknown_set; CelValue result = EvaluateAttribute(CelValue::CreateList(&cel_list), CelValue::CreateUnknownSet(&unknown_set), true, true); ASSERT_TRUE(result.IsUnknownSet()); } TEST_F(ContainerAccessStepTest, TestMapInvalidKey) { const std::string kKey0 = "testkey0"; const std::string kKey1 = "testkey1"; const std::string kKey2 = "testkey2"; Struct cel_struct; (*cel_struct.mutable_fields())[kKey0].set_string_value("value0"); (*cel_struct.mutable_fields())[kKey1].set_string_value("value1"); (*cel_struct.mutable_fields())[kKey2].set_string_value("value2"); CelValue result = EvaluateAttribute(CelProtoWrapper::CreateMessage(&cel_struct, &arena_), CelValue::CreateDouble(1.0), true, true); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid map key type: 'double'"))); } TEST_F(ContainerAccessStepTest, TestMapUnknownKey) { const std::string kKey0 = "testkey0"; const std::string kKey1 = "testkey1"; const std::string kKey2 = "testkey2"; Struct cel_struct; (*cel_struct.mutable_fields())[kKey0].set_string_value("value0"); (*cel_struct.mutable_fields())[kKey1].set_string_value("value1"); (*cel_struct.mutable_fields())[kKey2].set_string_value("value2"); UnknownSet unknown_set; CelValue result = EvaluateAttribute(CelProtoWrapper::CreateMessage(&cel_struct, &arena_), CelValue::CreateUnknownSet(&unknown_set), true, true); ASSERT_TRUE(result.IsUnknownSet()); } TEST_F(ContainerAccessStepTest, TestUnknownContainer) { UnknownSet unknown_set; CelValue result = EvaluateAttribute(CelValue::CreateUnknownSet(&unknown_set), CelValue::CreateInt64(1), true, true); ASSERT_TRUE(result.IsUnknownSet()); } TEST_F(ContainerAccessStepTest, TestInvalidContainerType) { CelValue result = EvaluateAttribute(CelValue::CreateInt64(1), CelValue::CreateInt64(0), true, true); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid container type: 'int"))); } INSTANTIATE_TEST_SUITE_P( CombinedContainerTest, ContainerAccessStepUniformityTest, testing::Combine( testing::Bool(), testing::Bool(), testing::Bool())); class ContainerAccessHeterogeneousLookupsTest : public testing::Test { public: ContainerAccessHeterogeneousLookupsTest() { options_.enable_heterogeneous_equality = true; builder_ = CreateCelExpressionBuilder(options_); } protected: InterpreterOptions options_; std::unique_ptr<CelExpressionBuilder> builder_; google::protobuf::Arena arena_; Activation activation_; }; TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleMapKeyInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.0]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelInt64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleMapKeyNotAnInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.1]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleMapKeyUint) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1.0]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelUint64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleListIndex) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.0]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelInt64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, DoubleListIndexNotAnInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.1]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, UintKeyAsUint) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u, 1: 2}[1u]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelUint64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, UintKeyAsInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1u]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelInt64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, IntKeyAsUint) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelUint64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, UintListIndex) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][2u]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelInt64(3)); } TEST_F(ContainerAccessHeterogeneousLookupsTest, StringKeyUnaffected) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2, '1': 3}['1']")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelInt64(3)); } class ContainerAccessHeterogeneousLookupsDisabledTest : public testing::Test { public: ContainerAccessHeterogeneousLookupsDisabledTest() { options_.enable_heterogeneous_equality = false; builder_ = CreateCelExpressionBuilder(options_); } protected: InterpreterOptions options_; std::unique_ptr<CelExpressionBuilder> builder_; google::protobuf::Arena arena_; Activation activation_; }; TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleMapKeyInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.0]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleMapKeyNotAnInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1.1]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleMapKeyUint) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1.0]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleListIndex) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.0]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, DoubleListIndexNotAnInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][1.1]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, UintKeyAsUint) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u, 1: 2}[1u]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelUint64(2)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, UintKeyAsInt) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2}[1u]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, IntKeyAsUint) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1u: 2u}[1]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, UintListIndex) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("[1, 2, 3][2u]")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelError(_)); } TEST_F(ContainerAccessHeterogeneousLookupsDisabledTest, StringKeyUnaffected) { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, parser::Parse("{1: 2, '1': 3}['1']")); ASSERT_OK_AND_ASSIGN(auto cel_expr, builder_->CreateExpression( &expr.expr(), &expr.source_info())); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr->Evaluate(activation_, &arena_)); EXPECT_THAT(result, test::IsCelInt64(3)); } } }
135
cpp
google/cel-cpp
select_step
eval/eval/select_step.cc
eval/eval/select_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_SELECT_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_SELECT_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "base/ast_internal/expr.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectSelectStep( std::unique_ptr<DirectExpressionStep> operand, cel::StringValue field, bool test_only, int64_t expr_id, bool enable_wrapper_type_null_unboxing, bool enable_optional_types = false); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateSelectStep( const cel::ast_internal::Select& select_expr, int64_t expr_id, bool enable_wrapper_type_null_unboxing, cel::ValueManager& value_factory, bool enable_optional_types = false); } #endif #include "eval/eval/select_step.h" #include <cstdint> #include <memory> #include <string> #include <tuple> #include <utility> #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/kind.h" #include "common/casting.h" #include "common/native_type.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValueView; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::MapValue; using ::cel::NullValue; using ::cel::OptionalValue; using ::cel::ProtoWrapperTypeOptions; using ::cel::StringValue; using ::cel::StructValue; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ValueKind; using ::cel::ValueView; absl::Status InvalidSelectTargetError() { return absl::Status(absl::StatusCode::kInvalidArgument, "Applying SELECT to non-message type"); } absl::optional<Value> CheckForMarkedAttributes(const AttributeTrail& trail, ExecutionFrameBase& frame) { if (frame.unknown_processing_enabled() && frame.attribute_utility().CheckForUnknownExact(trail)) { return frame.attribute_utility().CreateUnknownSet(trail.attribute()); } if (frame.missing_attribute_errors_enabled() && frame.attribute_utility().CheckForMissingAttribute(trail)) { auto result = frame.attribute_utility().CreateMissingAttributeError( trail.attribute()); if (result.ok()) { return std::move(result).value(); } ABSL_LOG(ERROR) << "Invalid attribute pattern matched select path: " << result.status().ToString(); return frame.value_manager().CreateErrorValue(std::move(result).status()); } return absl::nullopt; } ValueView TestOnlySelect(const StructValue& msg, const std::string& field, cel::ValueManager& value_factory, Value& scratch) { absl::StatusOr<bool> result = msg.HasFieldByName(field); if (!result.ok()) { scratch = value_factory.CreateErrorValue(std::move(result).status()); return scratch; } return BoolValueView(*result); } ValueView TestOnlySelect(const MapValue& map, const StringValue& field_name, cel::ValueManager& value_factory, Value& scratch) { absl::Status presence = map.Has(value_factory, field_name, scratch); if (!presence.ok()) { scratch = value_factory.CreateErrorValue(std::move(presence)); return scratch; } return scratch; } class SelectStep : public ExpressionStepBase { public: SelectStep(StringValue value, bool test_field_presence, int64_t expr_id, bool enable_wrapper_type_null_unboxing, bool enable_optional_types) : ExpressionStepBase(expr_id), field_value_(std::move(value)), field_(field_value_.ToString()), test_field_presence_(test_field_presence), unboxing_option_(enable_wrapper_type_null_unboxing ? ProtoWrapperTypeOptions::kUnsetNull : ProtoWrapperTypeOptions::kUnsetProtoDefault), enable_optional_types_(enable_optional_types) {} absl::Status Evaluate(ExecutionFrame* frame) const override; private: absl::Status PerformTestOnlySelect(ExecutionFrame* frame, const Value& arg, Value& scratch) const; absl::StatusOr<std::pair<ValueView, bool>> PerformSelect( ExecutionFrame* frame, const Value& arg, Value& scratch) const; cel::StringValue field_value_; std::string field_; bool test_field_presence_; ProtoWrapperTypeOptions unboxing_option_; bool enable_optional_types_; }; absl::Status SelectStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(1)) { return absl::Status(absl::StatusCode::kInternal, "No arguments supplied for Select-type expression"); } const Value& arg = frame->value_stack().Peek(); const AttributeTrail& trail = frame->value_stack().PeekAttribute(); if (InstanceOf<UnknownValue>(arg) || InstanceOf<ErrorValue>(arg)) { return absl::OkStatus(); } AttributeTrail result_trail; if (frame->enable_unknowns() || frame->enable_missing_attribute_errors()) { result_trail = trail.Step(&field_); } if (arg->Is<NullValue>()) { frame->value_stack().PopAndPush( frame->value_factory().CreateErrorValue( cel::runtime_internal::CreateError("Message is NULL")), std::move(result_trail)); return absl::OkStatus(); } const cel::OptionalValueInterface* optional_arg = nullptr; if (enable_optional_types_ && cel::NativeTypeId::Of(arg) == cel::NativeTypeId::For<cel::OptionalValueInterface>()) { optional_arg = cel::internal::down_cast<const cel::OptionalValueInterface*>( cel::Cast<cel::OpaqueValue>(arg).operator->()); } if (!(optional_arg != nullptr || arg->Is<MapValue>() || arg->Is<StructValue>())) { frame->value_stack().PopAndPush( frame->value_factory().CreateErrorValue(InvalidSelectTargetError()), std::move(result_trail)); return absl::OkStatus(); } absl::optional<Value> marked_attribute_check = CheckForMarkedAttributes(result_trail, *frame); if (marked_attribute_check.has_value()) { frame->value_stack().PopAndPush(std::move(marked_attribute_check).value(), std::move(result_trail)); return absl::OkStatus(); } Value result_scratch; if (test_field_presence_) { if (optional_arg != nullptr) { if (!optional_arg->HasValue()) { frame->value_stack().PopAndPush(cel::BoolValue{false}); return absl::OkStatus(); } return PerformTestOnlySelect(frame, optional_arg->Value(), result_scratch); } return PerformTestOnlySelect(frame, arg, result_scratch); } if (optional_arg != nullptr) { if (!optional_arg->HasValue()) { return absl::OkStatus(); } ValueView result; bool ok; CEL_ASSIGN_OR_RETURN( std::tie(result, ok), PerformSelect(frame, optional_arg->Value(), result_scratch)); if (!ok) { frame->value_stack().PopAndPush(cel::OptionalValue::None(), std::move(result_trail)); return absl::OkStatus(); } frame->value_stack().PopAndPush( cel::OptionalValue::Of(frame->memory_manager(), cel::Value{result}), std::move(result_trail)); return absl::OkStatus(); } switch (arg->kind()) { case ValueKind::kStruct: { CEL_RETURN_IF_ERROR(arg.As<StructValue>().GetFieldByName( frame->value_factory(), field_, result_scratch, unboxing_option_)); frame->value_stack().PopAndPush(std::move(result_scratch), std::move(result_trail)); return absl::OkStatus(); } case ValueKind::kMap: { CEL_RETURN_IF_ERROR(arg.As<MapValue>().Get(frame->value_factory(), field_value_, result_scratch)); frame->value_stack().PopAndPush(std::move(result_scratch), std::move(result_trail)); return absl::OkStatus(); } default: return InvalidSelectTargetError(); } } absl::Status SelectStep::PerformTestOnlySelect(ExecutionFrame* frame, const Value& arg, Value& scratch) const { switch (arg->kind()) { case ValueKind::kMap: frame->value_stack().PopAndPush(Value{TestOnlySelect( arg.As<MapValue>(), field_value_, frame->value_factory(), scratch)}); return absl::OkStatus(); case ValueKind::kMessage: frame->value_stack().PopAndPush(Value{TestOnlySelect( arg.As<StructValue>(), field_, frame->value_factory(), scratch)}); return absl::OkStatus(); default: return InvalidSelectTargetError(); } } absl::StatusOr<std::pair<ValueView, bool>> SelectStep::PerformSelect( ExecutionFrame* frame, const Value& arg, Value& scratch) const { switch (arg->kind()) { case ValueKind::kStruct: { const auto& struct_value = arg.As<StructValue>(); CEL_ASSIGN_OR_RETURN(auto ok, struct_value.HasFieldByName(field_)); if (!ok) { return std::pair{cel::NullValueView{}, false}; } CEL_RETURN_IF_ERROR(struct_value.GetFieldByName( frame->value_factory(), field_, scratch, unboxing_option_)); return std::pair{scratch, true}; } case ValueKind::kMap: { CEL_ASSIGN_OR_RETURN( auto ok, arg.As<MapValue>().Find(frame->value_factory(), field_value_, scratch)); return std::pair{scratch, ok}; } default: return InvalidSelectTargetError(); } } class DirectSelectStep : public DirectExpressionStep { public: DirectSelectStep(int64_t expr_id, std::unique_ptr<DirectExpressionStep> operand, StringValue field, bool test_only, bool enable_wrapper_type_null_unboxing, bool enable_optional_types) : DirectExpressionStep(expr_id), operand_(std::move(operand)), field_value_(std::move(field)), field_(field_value_.ToString()), test_only_(test_only), unboxing_option_(enable_wrapper_type_null_unboxing ? ProtoWrapperTypeOptions::kUnsetNull : ProtoWrapperTypeOptions::kUnsetProtoDefault), enable_optional_types_(enable_optional_types) {} absl::Status Evaluate(ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const override { CEL_RETURN_IF_ERROR(operand_->Evaluate(frame, result, attribute)); if (InstanceOf<ErrorValue>(result) || InstanceOf<UnknownValue>(result)) { return absl::OkStatus(); } if (frame.attribute_tracking_enabled()) { attribute = attribute.Step(&field_); absl::optional<Value> value = CheckForMarkedAttributes(attribute, frame); if (value.has_value()) { result = std::move(value).value(); return absl::OkStatus(); } } const cel::OptionalValueInterface* optional_arg = nullptr; if (enable_optional_types_ && cel::NativeTypeId::Of(result) == cel::NativeTypeId::For<cel::OptionalValueInterface>()) { optional_arg = cel::internal::down_cast<const cel::OptionalValueInterface*>( cel::Cast<cel::OpaqueValue>(result).operator->()); } switch (result.kind()) { case ValueKind::kStruct: case ValueKind::kMap: break; case ValueKind::kNull: result = frame.value_manager().CreateErrorValue( cel::runtime_internal::CreateError("Message is NULL")); return absl::OkStatus(); default: if (optional_arg != nullptr) { break; } result = frame.value_manager().CreateErrorValue(InvalidSelectTargetError()); return absl::OkStatus(); } Value scratch; if (test_only_) { if (optional_arg != nullptr) { if (!optional_arg->HasValue()) { result = cel::BoolValue{false}; return absl::OkStatus(); } result = PerformTestOnlySelect(frame, optional_arg->Value(), scratch); return absl::OkStatus(); } result = PerformTestOnlySelect(frame, result, scratch); return absl::OkStatus(); } if (optional_arg != nullptr) { if (!optional_arg->HasValue()) { return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN( result, PerformOptionalSelect(frame, optional_arg->Value(), scratch)); return absl::OkStatus(); } CEL_ASSIGN_OR_RETURN(result, PerformSelect(frame, result, scratch)); return absl::OkStatus(); } private: std::unique_ptr<DirectExpressionStep> operand_; ValueView PerformTestOnlySelect(ExecutionFrameBase& frame, const Value& value, Value& scratch) const; absl::StatusOr<ValueView> PerformOptionalSelect(ExecutionFrameBase& frame, const Value& value, Value& scratch) const; absl::StatusOr<ValueView> PerformSelect(ExecutionFrameBase& frame, const Value& value, Value& scratch) const; StringValue field_value_; std::string field_; bool test_only_; ProtoWrapperTypeOptions unboxing_option_; bool enable_optional_types_; }; ValueView DirectSelectStep::PerformTestOnlySelect(ExecutionFrameBase& frame, const cel::Value& value, Value& scratch) const { switch (value.kind()) { case ValueKind::kMap: return TestOnlySelect(Cast<MapValue>(value), field_value_, frame.value_manager(), scratch); case ValueKind::kMessage: return TestOnlySelect(Cast<StructValue>(value), field_, frame.value_manager(), scratch); default: scratch = frame.value_manager().CreateErrorValue(InvalidSelectTargetError()); return ValueView{scratch}; } } absl::StatusOr<ValueView> DirectSelectStep::PerformOptionalSelect( ExecutionFrameBase& frame, const Value& value, Value& scratch) const { switch (value.kind()) { case ValueKind::kStruct: { auto struct_value = Cast<StructValue>(value); CEL_ASSIGN_OR_RETURN(auto ok, struct_value.HasFieldByName(field_)); if (!ok) { scratch = OptionalValue::None(); return ValueView{scratch}; } CEL_RETURN_IF_ERROR(struct_value.GetFieldByName( frame.value_manager(), field_, scratch, unboxing_option_)); scratch = OptionalValue::Of(frame.value_manager().GetMemoryManager(), Value(scratch)); return ValueView{scratch}; } case ValueKind::kMap: { CEL_ASSIGN_OR_RETURN(auto lookup, Cast<MapValue>(value).Find(frame.value_manager(), field_value_, scratch)); if (!lookup) { scratch = OptionalValue::None(); return ValueView{scratch}; } scratch = OptionalValue::Of(frame.value_manager().GetMemoryManager(), Value(scratch)); return ValueView{scratch}; } default: return InvalidSelectTargetError(); } } absl::StatusOr<ValueView> DirectSelectStep::PerformSelect( ExecutionFrameBase& frame, const cel::Value& value, Value& scratch) const { switch (value.kind()) { case ValueKind::kStruct: { CEL_RETURN_IF_ERROR(Cast<StructValue>(value).GetFieldByName( frame.value_manager(), field_, scratch, unboxing_option_)); return scratch; } case ValueKind::kMap: { CEL_RETURN_IF_ERROR(Cast<MapValue>(value).Get(frame.value_manager(), field_value_, scratch)); return scratch; } default: return InvalidSelectTargetError(); } } } std::unique_ptr<DirectExpressionStep> CreateDirectSelectStep( std::unique_ptr<DirectExpressionStep> operand, StringValue field, bool test_only, int64_t expr_id, bool enable_wrapper_type_null_unboxing, bool enable_optional_types) { return std::make_unique<DirectSelectStep>( expr_id, std::move(operand), std::move(field), test_only, enable_wrapper_type_null_unboxing, enable_optional_types); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateSelectStep( const cel::ast_internal::Select& select_expr, int64_t expr_id, bool enable_wrapper_type_null_unboxing, cel::ValueManager& value_factory, bool enable_optional_types) { return std::make_unique<SelectStep>( value_factory.CreateUncheckedStringValue(select_expr.field()), select_expr.test_only(), expr_id, enable_wrapper_type_null_unboxing, enable_optional_types); } }
#include "eval/eval/select_step.h" #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/wrappers.pb.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "base/ast_internal/expr.h" #include "base/attribute.h" #include "base/attribute_set.h" #include "base/type_provider.h" #include "common/legacy_value.h" #include "common/value.h" #include "common/value_manager.h" #include "common/value_testing.h" #include "common/values/legacy_value_manager.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/const_value_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/structs/legacy_type_adapter.h" #include "eval/public/structs/trivial_legacy_type_info.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_extensions.pb.h" #include "eval/testutil/test_message.pb.h" #include "extensions/protobuf/memory_manager.h" #include "extensions/protobuf/value.h" #include "internal/proto_matchers.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" #include "proto/test/v1/proto3/test_all_types.pb.h" namespace google::api::expr::runtime { namespace { using ::cel::Attribute; using ::cel::AttributeQualifier; using ::cel::AttributeSet; using ::cel::BoolValue; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::ManagedValueFactory; using ::cel::OptionalValue; using ::cel::RuntimeOptions; using ::cel::TypeProvider; using ::cel::UnknownValue; using ::cel::Value; using ::cel::ast_internal::Expr; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::extensions::ProtoMessageToValue; using ::cel::internal::test::EqualsProto; using ::cel::test::IntValueIs; using ::google::api::expr::test::v1::proto3::TestAllTypes; using testing::_; using testing::Eq; using testing::HasSubstr; using testing::Return; using testing::UnorderedElementsAre; using cel::internal::StatusIs; struct RunExpressionOptions { bool enable_unknowns = false; bool enable_wrapper_type_null_unboxing = false; }; class MockAccessor : public LegacyTypeAccessApis, public LegacyTypeInfoApis { public: MOCK_METHOD(absl::StatusOr<bool>, HasField, (absl::string_view field_name, const CelValue::MessageWrapper& value), (const override)); MOCK_METHOD(absl::StatusOr<CelValue>, GetField, (absl::string_view field_name, const CelValue::MessageWrapper& instance, ProtoWrapperTypeOptions unboxing_option, cel::MemoryManagerRef memory_manager), (const override)); MOCK_METHOD((const std::string&), GetTypename, (const CelValue::MessageWrapper& instance), (const override)); MOCK_METHOD(std::string, DebugString, (const CelValue::MessageWrapper& instance), (const override)); MOCK_METHOD(std::vector<absl::string_view>, ListFields, (const CelValue::MessageWrapper& value), (const override)); const LegacyTypeAccessApis* GetAccessApis( const CelValue::MessageWrapper& instance) const override { return this; } }; class SelectStepTest : public testing::Test { public: SelectStepTest() : value_factory_(ProtoMemoryManagerRef(&arena_), cel::TypeProvider::Builtin()) {} absl::StatusOr<CelValue> RunExpression(const CelValue target, absl::string_view field, bool test, absl::string_view unknown_path, RunExpressionOptions options) { ExecutionPath path; Expr expr; auto& select = expr.mutable_select_expr(); select.set_field(std::string(field)); select.set_test_only(test); Expr& expr0 = select.mutable_operand(); auto& ident = expr0.mutable_ident_expr(); ident.set_name("target"); CEL_ASSIGN_OR_RETURN(auto step0, CreateIdentStep(ident, expr0.id())); CEL_ASSIGN_OR_RETURN( auto step1, CreateSelectStep(select, expr.id(), options.enable_wrapper_type_null_unboxing, value_factory_)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); cel::RuntimeOptions runtime_options; if (options.enable_unknowns) { runtime_options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), runtime_options)); Activation activation; activation.InsertValue("target", target); return cel_expr.Evaluate(activation, &arena_); } absl::StatusOr<CelValue> RunExpression(const TestExtensions* message, absl::string_view field, bool test, RunExpressionOptions options) { return RunExpression(CelProtoWrapper::CreateMessage(message, &arena_), field, test, "", options); } absl::StatusOr<CelValue> RunExpression(const TestMessage* message, absl::string_view field, bool test, absl::string_view unknown_path, RunExpressionOptions options) { return RunExpression(CelProtoWrapper::CreateMessage(message, &arena_), field, test, unknown_path, options); } absl::StatusOr<CelValue> RunExpression(const TestMessage* message, absl::string_view field, bool test, RunExpressionOptions options) { return RunExpression(message, field, test, "", options); } absl::StatusOr<CelValue> RunExpression(const CelMap* map_value, absl::string_view field, bool test, absl::string_view unknown_path, RunExpressionOptions options) { return RunExpression(CelValue::CreateMap(map_value), field, test, unknown_path, options); } absl::StatusOr<CelValue> RunExpression(const CelMap* map_value, absl::string_view field, bool test, RunExpressionOptions options) { return RunExpression(map_value, field, test, "", options); } protected: google::protobuf::Arena arena_; cel::common_internal::LegacyValueManager value_factory_; }; class SelectStepConformanceTest : public SelectStepTest, public testing::WithParamInterface<bool> {}; TEST_P(SelectStepConformanceTest, SelectMessageIsNull) { RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(static_cast<const TestMessage*>(nullptr), "bool_value", true, options)); ASSERT_TRUE(result.IsError()); } TEST_P(SelectStepConformanceTest, SelectTargetNotStructOrMap) { RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(CelValue::CreateStringView("some_value"), "some_field", false, "", options)); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Applying SELECT to non-message type"))); } TEST_P(SelectStepConformanceTest, PresenseIsFalseTest) { TestMessage message; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "bool_value", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), false); } TEST_P(SelectStepConformanceTest, PresenseIsTrueTest) { RunExpressionOptions options; options.enable_unknowns = GetParam(); TestMessage message; message.set_bool_value(true); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "bool_value", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), true); } TEST_P(SelectStepConformanceTest, ExtensionsPresenceIsTrueTest) { TestExtensions exts; TestExtensions* nested = exts.MutableExtension(nested_ext); nested->set_name("nested"); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.nested_ext", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_TRUE(result.BoolOrDie()); } TEST_P(SelectStepConformanceTest, ExtensionsPresenceIsFalseTest) { TestExtensions exts; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.nested_ext", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_FALSE(result.BoolOrDie()); } TEST_P(SelectStepConformanceTest, MapPresenseIsFalseTest) { RunExpressionOptions options; options.enable_unknowns = GetParam(); std::string key1 = "key1"; std::vector<std::pair<CelValue, CelValue>> key_values{ {CelValue::CreateString(&key1), CelValue::CreateInt64(1)}}; auto map_value = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(key_values)) .value(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(map_value.get(), "key2", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), false); } TEST_P(SelectStepConformanceTest, MapPresenseIsTrueTest) { RunExpressionOptions options; options.enable_unknowns = GetParam(); std::string key1 = "key1"; std::vector<std::pair<CelValue, CelValue>> key_values{ {CelValue::CreateString(&key1), CelValue::CreateInt64(1)}}; auto map_value = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(key_values)) .value(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(map_value.get(), "key1", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), true); } TEST_F(SelectStepTest, MapPresenseIsErrorTest) { TestMessage message; Expr select_expr; auto& select = select_expr.mutable_select_expr(); select.set_field("1"); select.set_test_only(true); Expr& expr1 = select.mutable_operand(); auto& select_map = expr1.mutable_select_expr(); select_map.set_field("int32_int32_map"); Expr& expr0 = select_map.mutable_operand(); auto& ident = expr0.mutable_ident_expr(); ident.set_name("target"); ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id())); ASSERT_OK_AND_ASSIGN( auto step1, CreateSelectStep(select_map, expr1.id(), false, value_factory_)); ASSERT_OK_AND_ASSIGN( auto step2, CreateSelectStep(select, select_expr.id(), false, value_factory_)); ExecutionPath path; path.push_back(std::move(step0)); path.push_back(std::move(step1)); path.push_back(std::move(step2)); CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); Activation activation; activation.InsertValue("target", CelProtoWrapper::CreateMessage(&message, &arena_)); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_)); EXPECT_TRUE(result.IsError()); EXPECT_EQ(result.ErrorOrDie()->code(), absl::StatusCode::kInvalidArgument); } TEST_F(SelectStepTest, MapPresenseIsTrueWithUnknownTest) { UnknownSet unknown_set; std::string key1 = "key1"; std::vector<std::pair<CelValue, CelValue>> key_values{ {CelValue::CreateString(&key1), CelValue::CreateUnknownSet(&unknown_set)}}; auto map_value = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(key_values)) .value(); RunExpressionOptions options; options.enable_unknowns = true; ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(map_value.get(), "key1", true, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), true); } TEST_P(SelectStepConformanceTest, FieldIsNotPresentInProtoTest) { TestMessage message; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "fake_field", false, options)); ASSERT_TRUE(result.IsError()); EXPECT_THAT(result.ErrorOrDie()->code(), Eq(absl::StatusCode::kNotFound)); } TEST_P(SelectStepConformanceTest, FieldIsNotSetTest) { TestMessage message; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "bool_value", false, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), false); } TEST_P(SelectStepConformanceTest, SimpleBoolTest) { TestMessage message; message.set_bool_value(true); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "bool_value", false, options)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), true); } TEST_P(SelectStepConformanceTest, SimpleInt32Test) { TestMessage message; message.set_int32_value(1); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "int32_value", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_EQ(result.Int64OrDie(), 1); } TEST_P(SelectStepConformanceTest, SimpleInt64Test) { TestMessage message; message.set_int64_value(1); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "int64_value", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_EQ(result.Int64OrDie(), 1); } TEST_P(SelectStepConformanceTest, SimpleUInt32Test) { TestMessage message; message.set_uint32_value(1); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "uint32_value", false, options)); ASSERT_TRUE(result.IsUint64()); EXPECT_EQ(result.Uint64OrDie(), 1); } TEST_P(SelectStepConformanceTest, SimpleUint64Test) { TestMessage message; message.set_uint64_value(1); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "uint64_value", false, options)); ASSERT_TRUE(result.IsUint64()); EXPECT_EQ(result.Uint64OrDie(), 1); } TEST_P(SelectStepConformanceTest, SimpleStringTest) { TestMessage message; std::string value = "test"; message.set_string_value(value); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "string_value", false, options)); ASSERT_TRUE(result.IsString()); EXPECT_EQ(result.StringOrDie().value(), "test"); } TEST_P(SelectStepConformanceTest, WrapperTypeNullUnboxingEnabledTest) { TestMessage message; message.mutable_string_wrapper_value()->set_value("test"); RunExpressionOptions options; options.enable_unknowns = GetParam(); options.enable_wrapper_type_null_unboxing = true; ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&message, "string_wrapper_value", false, options)); ASSERT_TRUE(result.IsString()); EXPECT_EQ(result.StringOrDie().value(), "test"); ASSERT_OK_AND_ASSIGN( result, RunExpression(&message, "int32_wrapper_value", false, options)); EXPECT_TRUE(result.IsNull()); } TEST_P(SelectStepConformanceTest, WrapperTypeNullUnboxingDisabledTest) { TestMessage message; message.mutable_string_wrapper_value()->set_value("test"); RunExpressionOptions options; options.enable_unknowns = GetParam(); options.enable_wrapper_type_null_unboxing = false; ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&message, "string_wrapper_value", false, options)); ASSERT_TRUE(result.IsString()); EXPECT_EQ(result.StringOrDie().value(), "test"); ASSERT_OK_AND_ASSIGN( result, RunExpression(&message, "int32_wrapper_value", false, options)); EXPECT_TRUE(result.IsInt64()); } TEST_P(SelectStepConformanceTest, SimpleBytesTest) { TestMessage message; std::string value = "test"; message.set_bytes_value(value); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "bytes_value", false, options)); ASSERT_TRUE(result.IsBytes()); EXPECT_EQ(result.BytesOrDie().value(), "test"); } TEST_P(SelectStepConformanceTest, SimpleMessageTest) { TestMessage message; TestMessage* message2 = message.mutable_message_value(); message2->set_int32_value(1); message2->set_string_value("test"); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "message_value", false, options)); ASSERT_TRUE(result.IsMessage()); EXPECT_THAT(*message2, EqualsProto(*result.MessageOrDie())); } TEST_P(SelectStepConformanceTest, GlobalExtensionsIntTest) { TestExtensions exts; exts.SetExtension(int32_ext, 42); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&exts, "google.api.expr.runtime.int32_ext", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_EQ(result.Int64OrDie(), 42L); } TEST_P(SelectStepConformanceTest, GlobalExtensionsMessageTest) { TestExtensions exts; TestExtensions* nested = exts.MutableExtension(nested_ext); nested->set_name("nested"); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.nested_ext", false, options)); ASSERT_TRUE(result.IsMessage()); EXPECT_THAT(result.MessageOrDie(), Eq(nested)); } TEST_P(SelectStepConformanceTest, GlobalExtensionsMessageUnsetTest) { TestExtensions exts; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.nested_ext", false, options)); ASSERT_TRUE(result.IsMessage()); EXPECT_THAT(result.MessageOrDie(), Eq(&TestExtensions::default_instance())); } TEST_P(SelectStepConformanceTest, GlobalExtensionsWrapperTest) { TestExtensions exts; google::protobuf::Int32Value* wrapper = exts.MutableExtension(int32_wrapper_ext); wrapper->set_value(42); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.int32_wrapper_ext", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_THAT(result.Int64OrDie(), Eq(42L)); } TEST_P(SelectStepConformanceTest, GlobalExtensionsWrapperUnsetTest) { TestExtensions exts; RunExpressionOptions options; options.enable_wrapper_type_null_unboxing = true; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.int32_wrapper_ext", false, options)); ASSERT_TRUE(result.IsNull()); } TEST_P(SelectStepConformanceTest, MessageExtensionsEnumTest) { TestExtensions exts; exts.SetExtension(TestMessageExtensions::enum_ext, TestExtEnum::TEST_EXT_1); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&exts, "google.api.expr.runtime.TestMessageExtensions.enum_ext", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_THAT(result.Int64OrDie(), Eq(TestExtEnum::TEST_EXT_1)); } TEST_P(SelectStepConformanceTest, MessageExtensionsRepeatedStringTest) { TestExtensions exts; exts.AddExtension(TestMessageExtensions::repeated_string_exts, "test1"); exts.AddExtension(TestMessageExtensions::repeated_string_exts, "test2"); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression( &exts, "google.api.expr.runtime.TestMessageExtensions.repeated_string_exts", false, options)); ASSERT_TRUE(result.IsList()); const CelList* cel_list = result.ListOrDie(); EXPECT_THAT(cel_list->size(), Eq(2)); } TEST_P(SelectStepConformanceTest, MessageExtensionsRepeatedStringUnsetTest) { TestExtensions exts; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression( &exts, "google.api.expr.runtime.TestMessageExtensions.repeated_string_exts", false, options)); ASSERT_TRUE(result.IsList()); const CelList* cel_list = result.ListOrDie(); EXPECT_THAT(cel_list->size(), Eq(0)); } TEST_P(SelectStepConformanceTest, NullMessageAccessor) { TestMessage message; TestMessage* message2 = message.mutable_message_value(); message2->set_int32_value(1); message2->set_string_value("test"); RunExpressionOptions options; options.enable_unknowns = GetParam(); CelValue value = CelValue::CreateMessageWrapper( CelValue::MessageWrapper(&message, TrivialTypeInfo::GetInstance())); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(value, "message_value", false, "", options)); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kNotFound)); ASSERT_OK_AND_ASSIGN(result, RunExpression(value, "message_value", true, "", options)); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), StatusIs(absl::StatusCode::kNotFound)); } TEST_P(SelectStepConformanceTest, CustomAccessor) { TestMessage message; TestMessage* message2 = message.mutable_message_value(); message2->set_int32_value(1); message2->set_string_value("test"); RunExpressionOptions options; options.enable_unknowns = GetParam(); testing::NiceMock<MockAccessor> accessor; CelValue value = CelValue::CreateMessageWrapper( CelValue::MessageWrapper(&message, &accessor)); ON_CALL(accessor, GetField(_, _, _, _)) .WillByDefault(Return(CelValue::CreateInt64(2))); ON_CALL(accessor, HasField(_, _)).WillByDefault(Return(false)); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(value, "message_value", false, "", options)); EXPECT_THAT(result, test::IsCelInt64(2)); ASSERT_OK_AND_ASSIGN(result, RunExpression(value, "message_value", true, "", options)); EXPECT_THAT(result, test::IsCelBool(false)); } TEST_P(SelectStepConformanceTest, CustomAccessorErrorHandling) { TestMessage message; TestMessage* message2 = message.mutable_message_value(); message2->set_int32_value(1); message2->set_string_value("test"); RunExpressionOptions options; options.enable_unknowns = GetParam(); testing::NiceMock<MockAccessor> accessor; CelValue value = CelValue::CreateMessageWrapper( CelValue::MessageWrapper(&message, &accessor)); ON_CALL(accessor, GetField(_, _, _, _)) .WillByDefault(Return(absl::InternalError("bad data"))); ON_CALL(accessor, HasField(_, _)) .WillByDefault(Return(absl::NotFoundError("not found"))); ASSERT_THAT(RunExpression(value, "message_value", false, "", options), StatusIs(absl::StatusCode::kInternal)); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(value, "message_value", true, "", options)); EXPECT_THAT(result, test::IsCelError(StatusIs(absl::StatusCode::kNotFound))); } TEST_P(SelectStepConformanceTest, SimpleEnumTest) { TestMessage message; message.set_enum_value(TestMessage::TEST_ENUM_1); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "enum_value", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_THAT(result.Int64OrDie(), Eq(TestMessage::TEST_ENUM_1)); } TEST_P(SelectStepConformanceTest, SimpleListTest) { TestMessage message; message.add_int32_list(1); message.add_int32_list(2); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(&message, "int32_list", false, options)); ASSERT_TRUE(result.IsList()); const CelList* cel_list = result.ListOrDie(); EXPECT_THAT(cel_list->size(), Eq(2)); } TEST_P(SelectStepConformanceTest, SimpleMapTest) { TestMessage message; auto map_field = message.mutable_string_int32_map(); (*map_field)["test0"] = 1; (*map_field)["test1"] = 2; RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN( CelValue result, RunExpression(&message, "string_int32_map", false, options)); ASSERT_TRUE(result.IsMap()); const CelMap* cel_map = result.MapOrDie(); EXPECT_THAT(cel_map->size(), Eq(2)); } TEST_P(SelectStepConformanceTest, MapSimpleInt32Test) { std::string key1 = "key1"; std::string key2 = "key2"; std::vector<std::pair<CelValue, CelValue>> key_values{ {CelValue::CreateString(&key1), CelValue::CreateInt64(1)}, {CelValue::CreateString(&key2), CelValue::CreateInt64(2)}}; auto map_value = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(key_values)) .value(); RunExpressionOptions options; options.enable_unknowns = GetParam(); ASSERT_OK_AND_ASSIGN(CelValue result, RunExpression(map_value.get(), "key1", false, options)); ASSERT_TRUE(result.IsInt64()); EXPECT_EQ(result.Int64OrDie(), 1); } TEST_P(SelectStepConformanceTest, CelErrorAsArgument) { ExecutionPath path; Expr dummy_expr; auto& select = dummy_expr.mutable_select_expr(); select.set_field("position"); select.set_test_only(false); Expr& expr0 = select.mutable_operand(); auto& ident = expr0.mutable_ident_expr(); ident.set_name("message"); ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id())); ASSERT_OK_AND_ASSIGN( auto step1, CreateSelectStep(select, dummy_expr.id(), false, value_factory_)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); CelError error = absl::CancelledError(); cel::RuntimeOptions options; if (GetParam()) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; activation.InsertValue("message", CelValue::CreateError(&error)); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_)); ASSERT_TRUE(result.IsError()); EXPECT_THAT(*result.ErrorOrDie(), Eq(error)); } TEST_F(SelectStepTest, DisableMissingAttributeOK) { TestMessage message; message.set_bool_value(true); ExecutionPath path; Expr dummy_expr; auto& select = dummy_expr.mutable_select_expr(); select.set_field("bool_value"); select.set_test_only(false); Expr& expr0 = select.mutable_operand(); auto& ident = expr0.mutable_ident_expr(); ident.set_name("message"); ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id())); ASSERT_OK_AND_ASSIGN( auto step1, CreateSelectStep(select, dummy_expr.id(), false, value_factory_)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), cel::RuntimeOptions{})); Activation activation; activation.InsertValue("message", CelProtoWrapper::CreateMessage(&message, &arena_)); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), true); CelAttributePattern pattern("message", {}); activation.set_missing_attribute_patterns({pattern}); ASSERT_OK_AND_ASSIGN(result, cel_expr.Evaluate(activation, &arena_)); EXPECT_EQ(result.BoolOrDie(), true); } TEST_F(SelectStepTest, UnrecoverableUnknownValueProducesError) { TestMessage message; message.set_bool_value(true); ExecutionPath path; Expr dummy_expr; auto& select = dummy_expr.mutable_select_expr(); select.set_field("bool_value"); select.set_test_only(false); Expr& expr0 = select.mutable_operand(); auto& ident = expr0.mutable_ident_expr(); ident.set_name("message"); ASSERT_OK_AND_ASSIGN(auto step0, CreateIdentStep(ident, expr0.id())); ASSERT_OK_AND_ASSIGN( auto step1, CreateSelectStep(select, dummy_expr.id(), false, value_factory_)); path.push_back(std::move(step0)); path.push_back(std::move(step1)); cel::RuntimeOptions options; options.enable_missing_attribute_errors = true; CelExpressionFlatImpl cel_expr( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; activation.InsertValue("message", CelProtoWrapper::CreateMessage(&message, &arena_)); ASSERT_OK_AND_ASSIGN(CelValue result, cel_expr.Evaluate(activation, &arena_)); ASSERT_TRUE(result.IsBool()); EXPECT_EQ(result.BoolOrDie(), true); CelAttributePattern pattern("message", {CreateCelAttributeQualifierPattern( CelValue::CreateStringView("bool_value"))}); activation.set_missing_attribute_patterns({pattern}); ASSERT_OK_AND_ASSIGN(result, cel_expr.Evaluate(activation, &
136
cpp
google/cel-cpp
ternary_step
eval/eval/ternary_step.cc
eval/eval/ternary_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_TERNARY_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_TERNARY_STEP_H_ #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { std::unique_ptr<DirectExpressionStep> CreateDirectTernaryStep( std::unique_ptr<DirectExpressionStep> condition, std::unique_ptr<DirectExpressionStep> left, std::unique_ptr<DirectExpressionStep> right, int64_t expr_id, bool shortcircuiting = true); absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateTernaryStep( int64_t expr_id); } #endif #include "eval/eval/ternary_step.h" #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "base/builtins.h" #include "common/casting.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" #include "eval/internal/errors.h" #include "internal/status_macros.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValue; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::UnknownValue; using ::cel::builtin::kTernary; using ::cel::runtime_internal::CreateNoMatchingOverloadError; inline constexpr size_t kTernaryStepCondition = 0; inline constexpr size_t kTernaryStepTrue = 1; inline constexpr size_t kTernaryStepFalse = 2; class ExhaustiveDirectTernaryStep : public DirectExpressionStep { public: ExhaustiveDirectTernaryStep(std::unique_ptr<DirectExpressionStep> condition, std::unique_ptr<DirectExpressionStep> left, std::unique_ptr<DirectExpressionStep> right, int64_t expr_id) : DirectExpressionStep(expr_id), condition_(std::move(condition)), left_(std::move(left)), right_(std::move(right)) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& attribute) const override { cel::Value condition; cel::Value lhs; cel::Value rhs; AttributeTrail condition_attr; AttributeTrail lhs_attr; AttributeTrail rhs_attr; CEL_RETURN_IF_ERROR(condition_->Evaluate(frame, condition, condition_attr)); CEL_RETURN_IF_ERROR(left_->Evaluate(frame, lhs, lhs_attr)); CEL_RETURN_IF_ERROR(right_->Evaluate(frame, rhs, rhs_attr)); if (InstanceOf<ErrorValue>(condition) || InstanceOf<UnknownValue>(condition)) { result = std::move(condition); attribute = std::move(condition_attr); return absl::OkStatus(); } if (!InstanceOf<BoolValue>(condition)) { result = frame.value_manager().CreateErrorValue( CreateNoMatchingOverloadError(kTernary)); return absl::OkStatus(); } if (Cast<BoolValue>(condition).NativeValue()) { result = std::move(lhs); attribute = std::move(lhs_attr); } else { result = std::move(rhs); attribute = std::move(rhs_attr); } return absl::OkStatus(); } private: std::unique_ptr<DirectExpressionStep> condition_; std::unique_ptr<DirectExpressionStep> left_; std::unique_ptr<DirectExpressionStep> right_; }; class ShortcircuitingDirectTernaryStep : public DirectExpressionStep { public: ShortcircuitingDirectTernaryStep( std::unique_ptr<DirectExpressionStep> condition, std::unique_ptr<DirectExpressionStep> left, std::unique_ptr<DirectExpressionStep> right, int64_t expr_id) : DirectExpressionStep(expr_id), condition_(std::move(condition)), left_(std::move(left)), right_(std::move(right)) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& attribute) const override { cel::Value condition; AttributeTrail condition_attr; CEL_RETURN_IF_ERROR(condition_->Evaluate(frame, condition, condition_attr)); if (InstanceOf<ErrorValue>(condition) || InstanceOf<UnknownValue>(condition)) { result = std::move(condition); attribute = std::move(condition_attr); return absl::OkStatus(); } if (!InstanceOf<BoolValue>(condition)) { result = frame.value_manager().CreateErrorValue( CreateNoMatchingOverloadError(kTernary)); return absl::OkStatus(); } if (Cast<BoolValue>(condition).NativeValue()) { return left_->Evaluate(frame, result, attribute); } return right_->Evaluate(frame, result, attribute); } private: std::unique_ptr<DirectExpressionStep> condition_; std::unique_ptr<DirectExpressionStep> left_; std::unique_ptr<DirectExpressionStep> right_; }; class TernaryStep : public ExpressionStepBase { public: explicit TernaryStep(int64_t expr_id) : ExpressionStepBase(expr_id) {} absl::Status Evaluate(ExecutionFrame* frame) const override; }; absl::Status TernaryStep::Evaluate(ExecutionFrame* frame) const { if (!frame->value_stack().HasEnough(3)) { return absl::Status(absl::StatusCode::kInternal, "Value stack underflow"); } auto args = frame->value_stack().GetSpan(3); const auto& condition = args[kTernaryStepCondition]; if (frame->enable_unknowns()) { if (condition->Is<cel::UnknownValue>()) { frame->value_stack().Pop(2); return absl::OkStatus(); } } if (condition->Is<cel::ErrorValue>()) { frame->value_stack().Pop(2); return absl::OkStatus(); } cel::Value result; if (!condition->Is<cel::BoolValue>()) { result = frame->value_factory().CreateErrorValue( CreateNoMatchingOverloadError(kTernary)); } else if (condition.As<cel::BoolValue>().NativeValue()) { result = args[kTernaryStepTrue]; } else { result = args[kTernaryStepFalse]; } frame->value_stack().PopAndPush(args.size(), std::move(result)); return absl::OkStatus(); } } std::unique_ptr<DirectExpressionStep> CreateDirectTernaryStep( std::unique_ptr<DirectExpressionStep> condition, std::unique_ptr<DirectExpressionStep> left, std::unique_ptr<DirectExpressionStep> right, int64_t expr_id, bool shortcircuiting) { if (shortcircuiting) { return std::make_unique<ShortcircuitingDirectTernaryStep>( std::move(condition), std::move(left), std::move(right), expr_id); } return std::make_unique<ExhaustiveDirectTernaryStep>( std::move(condition), std::move(left), std::move(right), expr_id); } absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateTernaryStep( int64_t expr_id) { return std::make_unique<TernaryStep>(expr_id); } }
#include "eval/eval/ternary_step.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/status/status.h" #include "base/ast_internal/expr.h" #include "base/attribute.h" #include "base/attribute_set.h" #include "base/type_provider.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/cel_expression_flat_impl.h" #include "eval/eval/const_value_step.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/ident_step.h" #include "eval/public/activation.h" #include "eval/public/cel_value.h" #include "eval/public/unknown_attribute_set.h" #include "eval/public/unknown_set.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace google::api::expr::runtime { namespace { using ::cel::BoolValue; using ::cel::Cast; using ::cel::ErrorValue; using ::cel::InstanceOf; using ::cel::IntValue; using ::cel::RuntimeOptions; using ::cel::TypeProvider; using ::cel::UnknownValue; using ::cel::ValueManager; using ::cel::ast_internal::Expr; using ::cel::extensions::ProtoMemoryManagerRef; using ::google::protobuf::Arena; using testing::ElementsAre; using testing::Eq; using testing::HasSubstr; using testing::Truly; using cel::internal::StatusIs; class LogicStepTest : public testing::TestWithParam<bool> { public: absl::Status EvaluateLogic(CelValue arg0, CelValue arg1, CelValue arg2, CelValue* result, bool enable_unknown) { Expr expr0; expr0.set_id(1); auto& ident_expr0 = expr0.mutable_ident_expr(); ident_expr0.set_name("name0"); Expr expr1; expr1.set_id(2); auto& ident_expr1 = expr1.mutable_ident_expr(); ident_expr1.set_name("name1"); Expr expr2; expr2.set_id(3); auto& ident_expr2 = expr2.mutable_ident_expr(); ident_expr2.set_name("name2"); ExecutionPath path; CEL_ASSIGN_OR_RETURN(auto step, CreateIdentStep(ident_expr0, expr0.id())); path.push_back(std::move(step)); CEL_ASSIGN_OR_RETURN(step, CreateIdentStep(ident_expr1, expr1.id())); path.push_back(std::move(step)); CEL_ASSIGN_OR_RETURN(step, CreateIdentStep(ident_expr2, expr2.id())); path.push_back(std::move(step)); CEL_ASSIGN_OR_RETURN(step, CreateTernaryStep(4)); path.push_back(std::move(step)); cel::RuntimeOptions options; if (enable_unknown) { options.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; } CelExpressionFlatImpl impl( FlatExpression(std::move(path), 0, TypeProvider::Builtin(), options)); Activation activation; std::string value("test"); activation.InsertValue("name0", arg0); activation.InsertValue("name1", arg1); activation.InsertValue("name2", arg2); auto status0 = impl.Evaluate(activation, &arena_); if (!status0.ok()) return status0.status(); *result = status0.value(); return absl::OkStatus(); } private: Arena arena_; }; TEST_P(LogicStepTest, TestBoolCond) { CelValue result; absl::Status status = EvaluateLogic(CelValue::CreateBool(true), CelValue::CreateBool(true), CelValue::CreateBool(false), &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_TRUE(result.BoolOrDie()); status = EvaluateLogic(CelValue::CreateBool(false), CelValue::CreateBool(true), CelValue::CreateBool(false), &result, GetParam()); ASSERT_OK(status); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); } TEST_P(LogicStepTest, TestErrorHandling) { CelValue result; CelError error = absl::CancelledError(); CelValue error_value = CelValue::CreateError(&error); ASSERT_OK(EvaluateLogic(error_value, CelValue::CreateBool(true), CelValue::CreateBool(false), &result, GetParam())); ASSERT_TRUE(result.IsError()); ASSERT_OK(EvaluateLogic(CelValue::CreateBool(true), error_value, CelValue::CreateBool(false), &result, GetParam())); ASSERT_TRUE(result.IsError()); ASSERT_OK(EvaluateLogic(CelValue::CreateBool(false), error_value, CelValue::CreateBool(false), &result, GetParam())); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); } TEST_F(LogicStepTest, TestUnknownHandling) { CelValue result; UnknownSet unknown_set; CelError cel_error = absl::CancelledError(); CelValue unknown_value = CelValue::CreateUnknownSet(&unknown_set); CelValue error_value = CelValue::CreateError(&cel_error); ASSERT_OK(EvaluateLogic(unknown_value, CelValue::CreateBool(true), CelValue::CreateBool(false), &result, true)); ASSERT_TRUE(result.IsUnknownSet()); ASSERT_OK(EvaluateLogic(CelValue::CreateBool(true), unknown_value, CelValue::CreateBool(false), &result, true)); ASSERT_TRUE(result.IsUnknownSet()); ASSERT_OK(EvaluateLogic(CelValue::CreateBool(false), unknown_value, CelValue::CreateBool(false), &result, true)); ASSERT_TRUE(result.IsBool()); ASSERT_FALSE(result.BoolOrDie()); ASSERT_OK(EvaluateLogic(error_value, unknown_value, CelValue::CreateBool(false), &result, true)); ASSERT_TRUE(result.IsError()); ASSERT_OK(EvaluateLogic(unknown_value, error_value, CelValue::CreateBool(false), &result, true)); ASSERT_TRUE(result.IsUnknownSet()); Expr expr0; auto& ident_expr0 = expr0.mutable_ident_expr(); ident_expr0.set_name("name0"); Expr expr1; auto& ident_expr1 = expr1.mutable_ident_expr(); ident_expr1.set_name("name1"); CelAttribute attr0(expr0.ident_expr().name(), {}), attr1(expr1.ident_expr().name(), {}); UnknownAttributeSet unknown_attr_set0({attr0}); UnknownAttributeSet unknown_attr_set1({attr1}); UnknownSet unknown_set0(unknown_attr_set0); UnknownSet unknown_set1(unknown_attr_set1); EXPECT_THAT(unknown_attr_set0.size(), Eq(1)); EXPECT_THAT(unknown_attr_set1.size(), Eq(1)); ASSERT_OK(EvaluateLogic(CelValue::CreateUnknownSet(&unknown_set0), CelValue::CreateUnknownSet(&unknown_set1), CelValue::CreateBool(false), &result, true)); ASSERT_TRUE(result.IsUnknownSet()); const auto& attrs = result.UnknownSetOrDie()->unknown_attributes(); ASSERT_THAT(attrs, testing::SizeIs(1)); EXPECT_THAT(attrs.begin()->variable_name(), Eq("name0")); } INSTANTIATE_TEST_SUITE_P(LogicStepTest, LogicStepTest, testing::Bool()); class TernaryStepDirectTest : public testing::TestWithParam<bool> { public: TernaryStepDirectTest() : value_factory_(TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)) {} bool Shortcircuiting() { return GetParam(); } ValueManager& value_manager() { return value_factory_.get(); } protected: Arena arena_; cel::ManagedValueFactory value_factory_; }; TEST_P(TernaryStepDirectTest, ReturnLhs) { cel::Activation activation; RuntimeOptions opts; ExecutionFrameBase frame(activation, opts, value_manager()); std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep( CreateConstValueDirectStep(BoolValue(true), -1), CreateConstValueDirectStep(IntValue(1), -1), CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting()); cel::Value result; AttributeTrail attr_unused; ASSERT_OK(step->Evaluate(frame, result, attr_unused)); ASSERT_TRUE(InstanceOf<IntValue>(result)); EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 1); } TEST_P(TernaryStepDirectTest, ReturnRhs) { cel::Activation activation; RuntimeOptions opts; ExecutionFrameBase frame(activation, opts, value_manager()); std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep( CreateConstValueDirectStep(BoolValue(false), -1), CreateConstValueDirectStep(IntValue(1), -1), CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting()); cel::Value result; AttributeTrail attr_unused; ASSERT_OK(step->Evaluate(frame, result, attr_unused)); ASSERT_TRUE(InstanceOf<IntValue>(result)); EXPECT_EQ(Cast<IntValue>(result).NativeValue(), 2); } TEST_P(TernaryStepDirectTest, ForwardError) { cel::Activation activation; RuntimeOptions opts; ExecutionFrameBase frame(activation, opts, value_manager()); cel::Value error_value = value_manager().CreateErrorValue(absl::InternalError("test error")); std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep( CreateConstValueDirectStep(error_value, -1), CreateConstValueDirectStep(IntValue(1), -1), CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting()); cel::Value result; AttributeTrail attr_unused; ASSERT_OK(step->Evaluate(frame, result, attr_unused)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kInternal, "test error")); } TEST_P(TernaryStepDirectTest, ForwardUnknown) { cel::Activation activation; RuntimeOptions opts; opts.unknown_processing = cel::UnknownProcessingOptions::kAttributeOnly; ExecutionFrameBase frame(activation, opts, value_manager()); std::vector<cel::Attribute> attrs{{cel::Attribute("var")}}; cel::UnknownValue unknown_value = value_manager().CreateUnknownValue(cel::AttributeSet(attrs)); std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep( CreateConstValueDirectStep(unknown_value, -1), CreateConstValueDirectStep(IntValue(2), -1), CreateConstValueDirectStep(IntValue(3), -1), -1, Shortcircuiting()); cel::Value result; AttributeTrail attr_unused; ASSERT_OK(step->Evaluate(frame, result, attr_unused)); ASSERT_TRUE(InstanceOf<UnknownValue>(result)); EXPECT_THAT(Cast<UnknownValue>(result).NativeValue().unknown_attributes(), ElementsAre(Truly([](const cel::Attribute& attr) { return attr.variable_name() == "var"; }))); } TEST_P(TernaryStepDirectTest, UnexpectedCondtionKind) { cel::Activation activation; RuntimeOptions opts; ExecutionFrameBase frame(activation, opts, value_manager()); std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep( CreateConstValueDirectStep(IntValue(-1), -1), CreateConstValueDirectStep(IntValue(1), -1), CreateConstValueDirectStep(IntValue(2), -1), -1, Shortcircuiting()); cel::Value result; AttributeTrail attr_unused; ASSERT_OK(step->Evaluate(frame, result, attr_unused)); ASSERT_TRUE(InstanceOf<ErrorValue>(result)); EXPECT_THAT(Cast<ErrorValue>(result).NativeValue(), StatusIs(absl::StatusCode::kUnknown, HasSubstr("No matching overloads found"))); } TEST_P(TernaryStepDirectTest, Shortcircuiting) { class RecordCallStep : public DirectExpressionStep { public: explicit RecordCallStep(bool& was_called) : DirectExpressionStep(-1), was_called_(&was_called) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& trail) const override { *was_called_ = true; result = IntValue(1); return absl::OkStatus(); } private: absl::Nonnull<bool*> was_called_; }; bool lhs_was_called = false; bool rhs_was_called = false; cel::Activation activation; RuntimeOptions opts; ExecutionFrameBase frame(activation, opts, value_manager()); std::unique_ptr<DirectExpressionStep> step = CreateDirectTernaryStep( CreateConstValueDirectStep(BoolValue(false), -1), std::make_unique<RecordCallStep>(lhs_was_called), std::make_unique<RecordCallStep>(rhs_was_called), -1, Shortcircuiting()); cel::Value result; AttributeTrail attr_unused; ASSERT_OK(step->Evaluate(frame, result, attr_unused)); ASSERT_TRUE(InstanceOf<IntValue>(result)); EXPECT_THAT(Cast<IntValue>(result).NativeValue(), Eq(1)); bool expect_eager_eval = !Shortcircuiting(); EXPECT_EQ(lhs_was_called, expect_eager_eval); EXPECT_TRUE(rhs_was_called); } INSTANTIATE_TEST_SUITE_P(TernaryStepDirectTest, TernaryStepDirectTest, testing::Bool()); } }
137
cpp
google/cel-cpp
compiler_constant_step
eval/eval/compiler_constant_step.cc
eval/eval/compiler_constant_step_test.cc
#ifndef THIRD_PARTY_CEL_CPP_EVAL_EVAL_COMPILER_CONSTANT_STEP_H_ #define THIRD_PARTY_CEL_CPP_EVAL_EVAL_COMPILER_CONSTANT_STEP_H_ #include <cstdint> #include <utility> #include "absl/status/status.h" #include "common/native_type.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/direct_expression_step.h" #include "eval/eval/evaluator_core.h" #include "eval/eval/expression_step_base.h" namespace google::api::expr::runtime { class DirectCompilerConstantStep : public DirectExpressionStep { public: DirectCompilerConstantStep(cel::Value value, int64_t expr_id) : DirectExpressionStep(expr_id), value_(std::move(value)) {} absl::Status Evaluate(ExecutionFrameBase& frame, cel::Value& result, AttributeTrail& attribute) const override; cel::NativeTypeId GetNativeTypeId() const override { return cel::NativeTypeId::For<DirectCompilerConstantStep>(); } const cel::Value& value() const { return value_; } private: cel::Value value_; }; class CompilerConstantStep : public ExpressionStepBase { public: CompilerConstantStep(cel::Value value, int64_t expr_id, bool comes_from_ast) : ExpressionStepBase(expr_id, comes_from_ast), value_(std::move(value)) {} absl::Status Evaluate(ExecutionFrame* frame) const override; cel::NativeTypeId GetNativeTypeId() const override { return cel::NativeTypeId::For<CompilerConstantStep>(); } const cel::Value& value() const { return value_; } private: cel::Value value_; }; } #endif #include "eval/eval/compiler_constant_step.h" #include "absl/status/status.h" #include "common/value.h" #include "eval/eval/attribute_trail.h" #include "eval/eval/evaluator_core.h" namespace google::api::expr::runtime { using ::cel::Value; absl::Status DirectCompilerConstantStep::Evaluate( ExecutionFrameBase& frame, Value& result, AttributeTrail& attribute) const { result = value_; return absl::OkStatus(); } absl::Status CompilerConstantStep::Evaluate(ExecutionFrame* frame) const { frame->value_stack().Push(value_); return absl::OkStatus(); } }
#include "eval/eval/compiler_constant_step.h" #include <memory> #include "base/type_provider.h" #include "common/native_type.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "eval/eval/evaluator_core.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/runtime_options.h" namespace google::api::expr::runtime { namespace { using ::cel::extensions::ProtoMemoryManagerRef; class CompilerConstantStepTest : public testing::Test { public: CompilerConstantStepTest() : value_factory_(ProtoMemoryManagerRef(&arena_), cel::TypeProvider::Builtin()), state_(2, 0, cel::TypeProvider::Builtin(), ProtoMemoryManagerRef(&arena_)) {} protected: google::protobuf::Arena arena_; cel::common_internal::LegacyValueManager value_factory_; FlatExpressionEvaluatorState state_; cel::Activation empty_activation_; cel::RuntimeOptions options_; }; TEST_F(CompilerConstantStepTest, Evaluate) { ExecutionPath path; path.push_back(std::make_unique<CompilerConstantStep>( value_factory_.CreateIntValue(42), -1, false)); ExecutionFrame frame(path, empty_activation_, options_, state_); ASSERT_OK_AND_ASSIGN(cel::Value result, frame.Evaluate()); EXPECT_EQ(result->As<cel::IntValue>().NativeValue(), 42); } TEST_F(CompilerConstantStepTest, TypeId) { CompilerConstantStep step(value_factory_.CreateIntValue(42), -1, false); ExpressionStep& abstract_step = step; EXPECT_EQ(abstract_step.GetNativeTypeId(), cel::NativeTypeId::For<CompilerConstantStep>()); } TEST_F(CompilerConstantStepTest, Value) { CompilerConstantStep step(value_factory_.CreateIntValue(42), -1, false); EXPECT_EQ(step.value()->As<cel::IntValue>().NativeValue(), 42); } } }
138
cpp
google/cel-cpp
optional_types
runtime/optional_types.cc
runtime/optional_types_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_OPTIONAL_TYPES_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_OPTIONAL_TYPES_H_ #include "absl/status/status.h" #include "runtime/runtime_builder.h" namespace cel::extensions { absl::Status EnableOptionalTypes(RuntimeBuilder& builder); } #endif #include "runtime/optional_types.h" #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <string> #include <tuple> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/function_adapter.h" #include "common/casting.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/casts.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" namespace cel::extensions { namespace { Value OptionalOf(ValueManager& value_manager, const Value& value) { return OptionalValue::Of(value_manager.GetMemoryManager(), value); } Value OptionalNone(ValueManager&) { return OptionalValue::None(); } Value OptionalOfNonZeroValue(ValueManager& value_manager, const Value& value) { if (value.IsZeroValue()) { return OptionalNone(value_manager); } return OptionalOf(value_manager, value); } absl::StatusOr<Value> OptionalGetValue(ValueManager& value_manager, const OpaqueValue& opaque_value) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { return optional_value->Value(); } return ErrorValue{runtime_internal::CreateNoMatchingOverloadError("value")}; } absl::StatusOr<Value> OptionalHasValue(ValueManager& value_manager, const OpaqueValue& opaque_value) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { return BoolValue{optional_value->HasValue()}; } return ErrorValue{ runtime_internal::CreateNoMatchingOverloadError("hasValue")}; } absl::StatusOr<Value> SelectOptionalFieldStruct(ValueManager& value_manager, const StructValue& struct_value, const StringValue& key) { std::string field_name; auto field_name_view = key.NativeString(field_name); CEL_ASSIGN_OR_RETURN(auto has_field, struct_value.HasFieldByName(field_name_view)); if (!has_field) { return OptionalValue::None(); } CEL_ASSIGN_OR_RETURN( auto field, struct_value.GetFieldByName(value_manager, field_name_view)); return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(field)); } absl::StatusOr<Value> SelectOptionalFieldMap(ValueManager& value_manager, const MapValue& map, const StringValue& key) { Value value; bool ok; CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, key)); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } return OptionalValue::None(); } absl::StatusOr<Value> SelectOptionalField(ValueManager& value_manager, const OpaqueValue& opaque_value, const StringValue& key) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { if (!optional_value->HasValue()) { return OptionalValue::None(); } auto container = optional_value->Value(); if (auto map_value = As<MapValue>(container); map_value) { return SelectOptionalFieldMap(value_manager, *map_value, key); } if (auto struct_value = As<StructValue>(container); struct_value) { return SelectOptionalFieldStruct(value_manager, *struct_value, key); } } return ErrorValue{runtime_internal::CreateNoMatchingOverloadError("_[?_]")}; } absl::StatusOr<Value> MapOptIndexOptionalValue(ValueManager& value_manager, const MapValue& map, const Value& key) { Value value; bool ok; if (auto double_key = cel::As<DoubleValue>(key); double_key) { auto number = internal::Number::FromDouble(double_key->NativeValue()); if (number.LosslessConvertibleToInt()) { CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, IntValue{number.AsInt()})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } if (number.LosslessConvertibleToUint()) { CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, UintValue{number.AsUint()})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } } else { CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, key)); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } if (auto int_key = cel::As<IntValue>(key); int_key && int_key->NativeValue() >= 0) { CEL_ASSIGN_OR_RETURN( std::tie(value, ok), map.Find(value_manager, UintValue{static_cast<uint64_t>(int_key->NativeValue())})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } else if (auto uint_key = cel::As<UintValue>(key); uint_key && uint_key->NativeValue() <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { CEL_ASSIGN_OR_RETURN( std::tie(value, ok), map.Find(value_manager, IntValue{static_cast<int64_t>(uint_key->NativeValue())})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } } return OptionalValue::None(); } absl::StatusOr<Value> ListOptIndexOptionalInt(ValueManager& value_manager, const ListValue& list, int64_t key) { CEL_ASSIGN_OR_RETURN(auto list_size, list.Size()); if (key < 0 || static_cast<size_t>(key) >= list_size) { return OptionalValue::None(); } CEL_ASSIGN_OR_RETURN(auto element, list.Get(value_manager, static_cast<size_t>(key))); return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(element)); } absl::StatusOr<Value> OptionalOptIndexOptionalValue( ValueManager& value_manager, const OpaqueValue& opaque_value, const Value& key) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { if (!optional_value->HasValue()) { return OptionalValue::None(); } auto container = optional_value->Value(); if (auto map_value = cel::As<MapValue>(container); map_value) { return MapOptIndexOptionalValue(value_manager, *map_value, key); } if (auto list_value = cel::As<ListValue>(container); list_value) { if (auto int_value = cel::As<IntValue>(key); int_value) { return ListOptIndexOptionalInt(value_manager, *list_value, int_value->NativeValue()); } } } return ErrorValue{runtime_internal::CreateNoMatchingOverloadError("_[?_]")}; } absl::Status RegisterOptionalTypeFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (!options.enable_qualified_type_identifiers) { return absl::FailedPreconditionError( "optional_type requires " "RuntimeOptions.enable_qualified_type_identifiers"); } if (!options.enable_heterogeneous_equality) { return absl::FailedPreconditionError( "optional_type requires RuntimeOptions.enable_heterogeneous_equality"); } CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, Value>::CreateDescriptor("optional.of", false), UnaryFunctionAdapter<Value, Value>::WrapFunction(&OptionalOf))); CEL_RETURN_IF_ERROR( registry.Register(UnaryFunctionAdapter<Value, Value>::CreateDescriptor( "optional.ofNonZeroValue", false), UnaryFunctionAdapter<Value, Value>::WrapFunction( &OptionalOfNonZeroValue))); CEL_RETURN_IF_ERROR(registry.Register( VariadicFunctionAdapter<Value>::CreateDescriptor("optional.none", false), VariadicFunctionAdapter<Value>::WrapFunction(&OptionalNone))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::CreateDescriptor("value", true), UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::WrapFunction( &OptionalGetValue))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::CreateDescriptor("hasValue", true), UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::WrapFunction( &OptionalHasValue))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, StructValue, StringValue>::CreateDescriptor("_?._", false), BinaryFunctionAdapter<absl::StatusOr<Value>, StructValue, StringValue>:: WrapFunction(&SelectOptionalFieldStruct))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, StringValue>::CreateDescriptor("_?._", false), BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, StringValue>:: WrapFunction(&SelectOptionalFieldMap))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, StringValue>::CreateDescriptor("_?._", false), BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, StringValue>::WrapFunction(&SelectOptionalField))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, Value>::CreateDescriptor("_[?_]", false), BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, Value>::WrapFunction(&MapOptIndexOptionalValue))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, ListValue, int64_t>::CreateDescriptor("_[?_]", false), BinaryFunctionAdapter<absl::StatusOr<Value>, ListValue, int64_t>::WrapFunction(&ListOptIndexOptionalInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, Value>::CreateDescriptor("_[?_]", false), BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, Value>:: WrapFunction(&OptionalOptIndexOptionalValue))); return absl::OkStatus(); } class OptionalTypeProvider final : public TypeReflector { protected: absl::StatusOr<absl::optional<TypeView>> FindTypeImpl(TypeFactory&, absl::string_view name, Type&) const override { if (name != "optional_type") { return absl::nullopt; } return OptionalTypeView{}; } }; } absl::Status EnableOptionalTypes(RuntimeBuilder& builder) { auto& runtime = cel::internal::down_cast<runtime_internal::RuntimeImpl&>( runtime_internal::RuntimeFriendAccess::GetMutableRuntime(builder)); CEL_RETURN_IF_ERROR(RegisterOptionalTypeFunctions( builder.function_registry(), runtime.expr_builder().options())); builder.type_registry().AddTypeProvider( std::make_unique<OptionalTypeProvider>()); runtime.expr_builder().enable_optional_types(); return absl::OkStatus(); } }
#include "runtime/optional_types.h" #include <cstdint> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "base/function.h" #include "base/function_descriptor.h" #include "common/kind.h" #include "common/memory.h" #include "common/value.h" #include "common/value_testing.h" #include "common/values/legacy_value_manager.h" #include "extensions/protobuf/memory_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/internal/runtime_impl.h" #include "runtime/reference_resolver.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" #include "google/protobuf/arena.h" namespace cel::extensions { namespace { using ::cel::extensions::ProtobufRuntimeAdapter; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::test::BoolValueIs; using ::cel::test::IntValueIs; using ::cel::test::OptionalValueIs; using ::cel::test::OptionalValueIsEmpty; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::parser::ParserOptions; using testing::ElementsAre; using testing::HasSubstr; using cel::internal::IsOk; using cel::internal::StatusIs; MATCHER_P(MatchesOptionalReceiver1, name, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{Kind::kOpaque}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } MATCHER_P2(MatchesOptionalReceiver2, name, kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{Kind::kOpaque, kind}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } MATCHER_P2(MatchesOptionalSelect, kind1, kind2, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{kind1, kind2}; return descriptor.name() == "_?._" && descriptor.receiver_style() == false && descriptor.types() == types; } MATCHER_P2(MatchesOptionalIndex, kind1, kind2, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{kind1, kind2}; return descriptor.name() == "_[?_]" && descriptor.receiver_style() == false && descriptor.types() == types; } TEST(EnableOptionalTypes, HeterogeneousEqualityRequired) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = true, .enable_heterogeneous_equality = false})); EXPECT_THAT(EnableOptionalTypes(builder), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(EnableOptionalTypes, QualifiedTypeIdentifiersRequired) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = false, .enable_heterogeneous_equality = true})); EXPECT_THAT(EnableOptionalTypes(builder), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(EnableOptionalTypes, PreconditionsSatisfied) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = true, .enable_heterogeneous_equality = true})); EXPECT_THAT(EnableOptionalTypes(builder), IsOk()); } TEST(EnableOptionalTypes, Functions) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = true, .enable_heterogeneous_equality = true})); ASSERT_THAT(EnableOptionalTypes(builder), IsOk()); EXPECT_THAT(builder.function_registry().FindStaticOverloads("hasValue", true, {Kind::kOpaque}), ElementsAre(MatchesOptionalReceiver1("hasValue"))); EXPECT_THAT(builder.function_registry().FindStaticOverloads("value", true, {Kind::kOpaque}), ElementsAre(MatchesOptionalReceiver1("value"))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_?._", false, {Kind::kStruct, Kind::kString}), ElementsAre(MatchesOptionalSelect(Kind::kStruct, Kind::kString))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_?._", false, {Kind::kMap, Kind::kString}), ElementsAre(MatchesOptionalSelect(Kind::kMap, Kind::kString))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_?._", false, {Kind::kOpaque, Kind::kString}), ElementsAre(MatchesOptionalSelect(Kind::kOpaque, Kind::kString))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_[?_]", false, {Kind::kMap, Kind::kAny}), ElementsAre(MatchesOptionalIndex(Kind::kMap, Kind::kAny))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_[?_]", false, {Kind::kList, Kind::kInt}), ElementsAre(MatchesOptionalIndex(Kind::kList, Kind::kInt))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_[?_]", false, {Kind::kOpaque, Kind::kAny}), ElementsAre(MatchesOptionalIndex(Kind::kOpaque, Kind::kAny))); } struct EvaluateResultTestCase { std::string name; std::string expression; test::ValueMatcher value_matcher; }; class OptionalTypesTest : public common_internal::ThreadCompatibleValueTest<EvaluateResultTestCase, bool> { public: const EvaluateResultTestCase& GetTestCase() { return std::get<1>(GetParam()); } bool EnableShortCircuiting() { return std::get<2>(GetParam()); } }; std::ostream& operator<<(std::ostream& os, const EvaluateResultTestCase& test_case) { return os << test_case.name; } TEST_P(OptionalTypesTest, RecursivePlan) { RuntimeOptions opts; opts.use_legacy_container_builders = false; opts.enable_qualified_type_identifiers = true; opts.max_recursion_depth = -1; opts.short_circuiting = EnableShortCircuiting(); const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK(EnableOptionalTypes(builder)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse(test_case.expression, "<input>", ParserOptions{.enable_optional_syntax = true})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); EXPECT_TRUE(runtime_internal::TestOnly_IsRecursiveImpl(program.get())); cel::common_internal::LegacyValueManager value_factory( memory_manager(), runtime->GetTypeProvider()); Activation activation; ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, test_case.value_matcher) << test_case.expression; } TEST_P(OptionalTypesTest, Defaults) { RuntimeOptions opts; opts.use_legacy_container_builders = false; opts.enable_qualified_type_identifiers = true; opts.short_circuiting = EnableShortCircuiting(); const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK(EnableOptionalTypes(builder)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse(test_case.expression, "<input>", ParserOptions{.enable_optional_syntax = true})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); common_internal::LegacyValueManager value_factory(this->memory_manager(), runtime->GetTypeProvider()); Activation activation; ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, test_case.value_matcher) << test_case.expression; } INSTANTIATE_TEST_SUITE_P( Basic, OptionalTypesTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"optional_none_hasValue", "optional.none().hasValue()", BoolValueIs(false)}, {"optional_of_hasValue", "optional.of(0).hasValue()", BoolValueIs(true)}, {"optional_ofNonZeroValue_hasValue", "optional.ofNonZeroValue(0).hasValue()", BoolValueIs(false)}, {"optional_or_absent", "optional.ofNonZeroValue(0).or(optional.ofNonZeroValue(0))", OptionalValueIsEmpty()}, {"optional_or_present", "optional.of(1).or(optional.none())", OptionalValueIs(IntValueIs(1))}, {"optional_orValue_absent", "optional.ofNonZeroValue(0).orValue(1)", IntValueIs(1)}, {"optional_orValue_present", "optional.of(1).orValue(2)", IntValueIs(1)}, {"list_of_optional", "[optional.of(1)][0].orValue(1)", IntValueIs(1)}}), testing::Bool()), OptionalTypesTest::ToString); class UnreachableFunction final : public cel::Function { public: explicit UnreachableFunction(int64_t* count) : count_(count) {} absl::StatusOr<Value> Invoke(const InvokeContext& context, absl::Span<const Value> args) const override { ++(*count_); return ErrorValue{absl::CancelledError()}; } private: int64_t* const count_; }; TEST(OptionalTypesTest, ErrorShortCircuiting) { RuntimeOptions opts{.enable_qualified_type_identifiers = true}; google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); int64_t unreachable_count = 0; ASSERT_OK(EnableOptionalTypes(builder)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); ASSERT_OK(builder.function_registry().Register( cel::FunctionDescriptor("unreachable", false, {}), std::make_unique<UnreachableFunction>(&unreachable_count))); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN( ParsedExpr expr, Parse("optional.of(1 / 0).orValue(unreachable())", "<input>", ParserOptions{.enable_optional_syntax = true})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); common_internal::LegacyValueManager value_factory(memory_manager, runtime->GetTypeProvider()); Activation activation; ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_EQ(unreachable_count, 0); ASSERT_TRUE(result->Is<ErrorValue>()) << result->DebugString(); EXPECT_THAT(result->As<ErrorValue>().NativeValue(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("divide by zero"))); } } }
139
cpp
google/cel-cpp
reference_resolver
runtime/reference_resolver.cc
runtime/reference_resolver_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_REFERENCE_RESOLVER_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_REFERENCE_RESOLVER_H_ #include "absl/status/status.h" #include "runtime/runtime_builder.h" namespace cel { enum class ReferenceResolverEnabled { kCheckedExpressionOnly, kAlways }; absl::Status EnableReferenceResolver(RuntimeBuilder& builder, ReferenceResolverEnabled enabled); } #endif #include "runtime/reference_resolver.h" #include "absl/base/macros.h" #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/native_type.h" #include "eval/compiler/qualified_reference_resolver.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" namespace cel { namespace { using ::cel::internal::down_cast; using ::cel::runtime_internal::RuntimeFriendAccess; using ::cel::runtime_internal::RuntimeImpl; absl::StatusOr<RuntimeImpl*> RuntimeImplFromBuilder(RuntimeBuilder& builder) { Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(builder); if (RuntimeFriendAccess::RuntimeTypeId(runtime) != NativeTypeId::For<RuntimeImpl>()) { return absl::UnimplementedError( "regex precompilation only supported on the default cel::Runtime " "implementation."); } RuntimeImpl& runtime_impl = down_cast<RuntimeImpl&>(runtime); return &runtime_impl; } google::api::expr::runtime::ReferenceResolverOption Convert( ReferenceResolverEnabled enabled) { switch (enabled) { case ReferenceResolverEnabled::kCheckedExpressionOnly: return google::api::expr::runtime::ReferenceResolverOption::kCheckedOnly; case ReferenceResolverEnabled::kAlways: return google::api::expr::runtime::ReferenceResolverOption::kAlways; } ABSL_LOG(FATAL) << "unsupported ReferenceResolverEnabled enumerator: " << static_cast<int>(enabled); } } absl::Status EnableReferenceResolver(RuntimeBuilder& builder, ReferenceResolverEnabled enabled) { CEL_ASSIGN_OR_RETURN(RuntimeImpl * runtime_impl, RuntimeImplFromBuilder(builder)); ABSL_ASSERT(runtime_impl != nullptr); runtime_impl->expr_builder().AddAstTransform( NewReferenceResolverExtension(Convert(enabled))); return absl::OkStatus(); } }
#include "runtime/reference_resolver.h" #include <cstdint> #include <utility> #include "google/api/expr/v1alpha1/checked.pb.h" #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/function_adapter.h" #include "common/value.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" #include "google/protobuf/text_format.h" namespace cel { namespace { using ::cel::extensions::ProtobufRuntimeAdapter; using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using testing::HasSubstr; using cel::internal::StatusIs; TEST(ReferenceResolver, ResolveQualifiedFunctions) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); absl::Status status = RegisterHelper<BinaryFunctionAdapter<int64_t, int64_t, int64_t>>:: RegisterGlobalOverload( "com.example.Exp", [](ValueManager& value_factory, int64_t base, int64_t exp) -> int64_t { int64_t result = 1; for (int64_t i = 0; i < exp; ++i) { result *= base; } return result; }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("com.example.Exp(2, 3) == 8")); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, parsed_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<BoolValue>()); EXPECT_TRUE(value->As<BoolValue>().NativeValue()); } TEST(ReferenceResolver, ResolveQualifiedFunctionsCheckedOnly) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); absl::Status status = RegisterHelper<BinaryFunctionAdapter<int64_t, int64_t, int64_t>>:: RegisterGlobalOverload( "com.example.Exp", [](ValueManager& value_factory, int64_t base, int64_t exp) -> int64_t { int64_t result = 1; for (int64_t i = 0; i < exp; ++i) { result *= base; } return result; }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("com.example.Exp(2, 3) == 8")); EXPECT_THAT(ProtobufRuntimeAdapter::CreateProgram(*runtime, parsed_expr), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("No overloads provided"))); } constexpr absl::string_view kIdentifierExpression = R"pb( reference_map: { key: 3 value: { name: "com.example.x" } } reference_map: { key: 4 value: { overload_id: "add_int64" } } reference_map: { key: 7 value: { name: "com.example.y" } } type_map: { key: 3 value: { primitive: INT64 } } type_map: { key: 4 value: { primitive: INT64 } } type_map: { key: 7 value: { primitive: INT64 } } source_info: { location: "<input>" line_offsets: 30 positions: { key: 1 value: 0 } positions: { key: 2 value: 3 } positions: { key: 3 value: 11 } positions: { key: 4 value: 14 } positions: { key: 5 value: 16 } positions: { key: 6 value: 19 } positions: { key: 7 value: 27 } } expr: { id: 4 call_expr: { function: "_+_" args: { id: 3 # compilers typically already apply this rewrite, but older saved # expressions might preserve the original parse. select_expr { operand { id: 8 select_expr { operand: { id: 9 ident_expr { name: "com" } } field: "example" } } field: "x" } } args: { id: 7 ident_expr: { name: "com.example.y" } } } })pb"; TEST(ReferenceResolver, ResolveQualifiedIdentifiers) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kIdentifierExpression, &checked_expr)); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, checked_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; activation.InsertOrAssignValue("com.example.x", value_factory.get().CreateIntValue(3)); activation.InsertOrAssignValue("com.example.y", value_factory.get().CreateIntValue(4)); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<IntValue>()); EXPECT_EQ(value->As<IntValue>().NativeValue(), 7); } TEST(ReferenceResolver, ResolveQualifiedIdentifiersSkipParseOnly) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kIdentifierExpression, &checked_expr)); Expr unchecked_expr = checked_expr.expr(); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, checked_expr.expr())); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; activation.InsertOrAssignValue("com.example.x", value_factory.get().CreateIntValue(3)); activation.InsertOrAssignValue("com.example.y", value_factory.get().CreateIntValue(4)); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<ErrorValue>()); EXPECT_THAT(value->As<ErrorValue>().NativeValue(), StatusIs(absl::StatusCode::kUnknown, HasSubstr("\"com\""))); } constexpr absl::string_view kEnumExpr = R"pb( reference_map: { key: 8 value: { name: "google.api.expr.test.v1.proto2.GlobalEnum.GAZ" value: { int64_value: 2 } } } reference_map: { key: 9 value: { overload_id: "equals" } } type_map: { key: 8 value: { primitive: INT64 } } type_map: { key: 9 value: { primitive: BOOL } } type_map: { key: 10 value: { primitive: INT64 } } source_info: { location: "<input>" line_offsets: 1 line_offsets: 64 line_offsets: 77 positions: { key: 1 value: 13 } positions: { key: 2 value: 19 } positions: { key: 3 value: 23 } positions: { key: 4 value: 28 } positions: { key: 5 value: 33 } positions: { key: 6 value: 36 } positions: { key: 7 value: 43 } positions: { key: 8 value: 54 } positions: { key: 9 value: 59 } positions: { key: 10 value: 62 } } expr: { id: 9 call_expr: { function: "_==_" args: { id: 8 ident_expr: { name: "google.api.expr.test.v1.proto2.GlobalEnum.GAZ" } } args: { id: 10 const_expr: { int64_value: 2 } } } })pb"; TEST(ReferenceResolver, ResolveEnumConstants) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kEnumExpr, &checked_expr)); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, checked_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<BoolValue>()); EXPECT_TRUE(value->As<BoolValue>().NativeValue()); } TEST(ReferenceResolver, ResolveEnumConstantsSkipParseOnly) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kEnumExpr, &checked_expr)); Expr unchecked_expr = checked_expr.expr(); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, unchecked_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<ErrorValue>()); EXPECT_THAT( value->As<ErrorValue>().NativeValue(), StatusIs(absl::StatusCode::kUnknown, HasSubstr("\"google.api.expr.test.v1.proto2.GlobalEnum.GAZ\""))); } } }
140
cpp
google/cel-cpp
regex_precompilation
runtime/regex_precompilation.cc
runtime/regex_precompilation_test.cc
#ifndef THIRD_PARTY_CEL_CPP_REGEX_PRECOMPILATION_FOLDING_H_ #define THIRD_PARTY_CEL_CPP_REGEX_PRECOMPILATION_FOLDING_H_ #include "absl/status/status.h" #include "common/memory.h" #include "runtime/runtime_builder.h" namespace cel::extensions { absl::Status EnableRegexPrecompilation(RuntimeBuilder& builder); } #endif #include "runtime/regex_precompilation.h" #include "absl/base/macros.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/native_type.h" #include "eval/compiler/regex_precompilation_optimization.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" namespace cel::extensions { namespace { using ::cel::internal::down_cast; using ::cel::runtime_internal::RuntimeFriendAccess; using ::cel::runtime_internal::RuntimeImpl; using ::google::api::expr::runtime::CreateRegexPrecompilationExtension; absl::StatusOr<RuntimeImpl*> RuntimeImplFromBuilder(RuntimeBuilder& builder) { Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(builder); if (RuntimeFriendAccess::RuntimeTypeId(runtime) != NativeTypeId::For<RuntimeImpl>()) { return absl::UnimplementedError( "regex precompilation only supported on the default cel::Runtime " "implementation."); } RuntimeImpl& runtime_impl = down_cast<RuntimeImpl&>(runtime); return &runtime_impl; } } absl::Status EnableRegexPrecompilation(RuntimeBuilder& builder) { CEL_ASSIGN_OR_RETURN(RuntimeImpl * runtime_impl, RuntimeImplFromBuilder(builder)); ABSL_ASSERT(runtime_impl != nullptr); runtime_impl->expr_builder().AddProgramOptimizer( CreateRegexPrecompilationExtension( runtime_impl->expr_builder().options().regex_max_program_size)); return absl::OkStatus(); } }
#include "runtime/regex_precompilation.h" #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "base/function_adapter.h" #include "common/value.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/constant_folding.h" #include "runtime/managed_value_factory.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" namespace cel::extensions { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using testing::_; using testing::HasSubstr; using cel::internal::StatusIs; using ValueMatcher = testing::Matcher<Value>; struct TestCase { std::string name; std::string expression; ValueMatcher result_matcher; absl::Status create_status; }; MATCHER_P(IsIntValue, expected, "") { const Value& value = arg; return value->Is<IntValue>() && value->As<IntValue>().NativeValue() == expected; } MATCHER_P(IsBoolValue, expected, "") { const Value& value = arg; return value->Is<BoolValue>() && value->As<BoolValue>().NativeValue() == expected; } MATCHER_P(IsErrorValue, expected_substr, "") { const Value& value = arg; return value->Is<ErrorValue>() && absl::StrContains(value->As<ErrorValue>().NativeValue().message(), expected_substr); } class RegexPrecompilationTest : public testing::TestWithParam<TestCase> {}; TEST_P(RegexPrecompilationTest, Basic) { RuntimeOptions options; const TestCase& test_case = GetParam(); ASSERT_OK_AND_ASSIGN(cel::RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const StringValue&>>:: RegisterGlobalOverload( "prepend", [](ValueManager& f, const StringValue& value, const StringValue& prefix) { return StringValue::Concat(f, prefix, value); }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK(EnableRegexPrecompilation(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse(test_case.expression)); auto program_or = ProtobufRuntimeAdapter::CreateProgram(*runtime, parsed_expr); if (!test_case.create_status.ok()) { ASSERT_THAT(program_or.status(), StatusIs(test_case.create_status.code(), HasSubstr(test_case.create_status.message()))); return; } ASSERT_OK_AND_ASSIGN(auto program, std::move(program_or)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(auto var, value_factory.get().CreateStringValue("string_var")); activation.InsertOrAssignValue("string_var", var); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); EXPECT_THAT(value, test_case.result_matcher); } TEST_P(RegexPrecompilationTest, WithConstantFolding) { RuntimeOptions options; const TestCase& test_case = GetParam(); ASSERT_OK_AND_ASSIGN(cel::RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const StringValue&>>:: RegisterGlobalOverload( "prepend", [](ValueManager& f, const StringValue& value, const StringValue& prefix) { return StringValue::Concat(f, prefix, value); }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK( EnableConstantFolding(builder, MemoryManagerRef::ReferenceCounting())); ASSERT_OK(EnableRegexPrecompilation(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse(test_case.expression)); auto program_or = ProtobufRuntimeAdapter::CreateProgram(*runtime, parsed_expr); if (!test_case.create_status.ok()) { ASSERT_THAT(program_or.status(), StatusIs(test_case.create_status.code(), HasSubstr(test_case.create_status.message()))); return; } ASSERT_OK_AND_ASSIGN(auto program, std::move(program_or)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(auto var, value_factory.get().CreateStringValue("string_var")); activation.InsertOrAssignValue("string_var", var); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); EXPECT_THAT(value, test_case.result_matcher); } INSTANTIATE_TEST_SUITE_P( Cases, RegexPrecompilationTest, testing::ValuesIn(std::vector<TestCase>{ {"matches_receiver", R"(string_var.matches(r's\w+_var'))", IsBoolValue(true)}, {"matches_receiver_false", R"(string_var.matches(r'string_var\d+'))", IsBoolValue(false)}, {"matches_global_true", R"(matches(string_var, r's\w+_var'))", IsBoolValue(true)}, {"matches_global_false", R"(matches(string_var, r'string_var\d+'))", IsBoolValue(false)}, {"matches_bad_re2_expression", "matches('123', r'(?<!a)123')", _, absl::InvalidArgumentError("unsupported RE2")}, {"matches_unsupported_call_signature", "matches('123', r'(?<!a)123', 'gi')", _, absl::InvalidArgumentError("No overloads")}, {"constant_computation", "matches(string_var, r'string' + '_' + r'var')", IsBoolValue(true)}, }), [](const testing::TestParamInfo<TestCase>& info) { return info.param.name; }); } }
141
cpp
google/cel-cpp
function_registry
runtime/function_registry.cc
runtime/function_registry_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_FUNCTION_REGISTRY_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_FUNCTION_REGISTRY_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_map.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "runtime/function_overload_reference.h" #include "runtime/function_provider.h" namespace cel { class FunctionRegistry { public: struct LazyOverload { const cel::FunctionDescriptor& descriptor; const cel::runtime_internal::FunctionProvider& provider; }; FunctionRegistry() = default; FunctionRegistry(FunctionRegistry&&) = default; FunctionRegistry& operator=(FunctionRegistry&&) = default; absl::Status Register(const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> implementation); absl::Status RegisterLazyFunction(const cel::FunctionDescriptor& descriptor); std::vector<cel::FunctionOverloadReference> FindStaticOverloads( absl::string_view name, bool receiver_style, absl::Span<const cel::Kind> types) const; std::vector<LazyOverload> FindLazyOverloads( absl::string_view name, bool receiver_style, absl::Span<const cel::Kind> types) const; absl::node_hash_map<std::string, std::vector<const cel::FunctionDescriptor*>> ListFunctions() const; private: struct StaticFunctionEntry { StaticFunctionEntry(const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> impl) : descriptor(std::make_unique<cel::FunctionDescriptor>(descriptor)), implementation(std::move(impl)) {} std::unique_ptr<cel::FunctionDescriptor> descriptor; std::unique_ptr<cel::Function> implementation; }; struct LazyFunctionEntry { LazyFunctionEntry( const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::runtime_internal::FunctionProvider> provider) : descriptor(std::make_unique<cel::FunctionDescriptor>(descriptor)), function_provider(std::move(provider)) {} std::unique_ptr<cel::FunctionDescriptor> descriptor; std::unique_ptr<cel::runtime_internal::FunctionProvider> function_provider; }; struct RegistryEntry { std::vector<StaticFunctionEntry> static_overloads; std::vector<LazyFunctionEntry> lazy_overloads; }; bool DescriptorRegistered(const cel::FunctionDescriptor& descriptor) const; bool ValidateNonStrictOverload( const cel::FunctionDescriptor& descriptor) const; absl::flat_hash_map<std::string, RegistryEntry> functions_; }; } #endif #include "runtime/function_registry.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/node_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 "absl/types/span.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "runtime/activation_interface.h" #include "runtime/function_overload_reference.h" #include "runtime/function_provider.h" namespace cel { namespace { class ActivationFunctionProviderImpl : public cel::runtime_internal::FunctionProvider { public: ActivationFunctionProviderImpl() = default; absl::StatusOr<absl::optional<cel::FunctionOverloadReference>> GetFunction( const cel::FunctionDescriptor& descriptor, const cel::ActivationInterface& activation) const override { std::vector<cel::FunctionOverloadReference> overloads = activation.FindFunctionOverloads(descriptor.name()); absl::optional<cel::FunctionOverloadReference> matching_overload = absl::nullopt; for (const auto& overload : overloads) { if (overload.descriptor.ShapeMatches(descriptor)) { if (matching_overload.has_value()) { return absl::Status(absl::StatusCode::kInvalidArgument, "Couldn't resolve function."); } matching_overload.emplace(overload); } } return matching_overload; } }; std::unique_ptr<cel::runtime_internal::FunctionProvider> CreateActivationFunctionProvider() { return std::make_unique<ActivationFunctionProviderImpl>(); } } absl::Status FunctionRegistry::Register( const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> implementation) { if (DescriptorRegistered(descriptor)) { return absl::Status( absl::StatusCode::kAlreadyExists, "CelFunction with specified parameters already registered"); } if (!ValidateNonStrictOverload(descriptor)) { return absl::Status(absl::StatusCode::kAlreadyExists, "Only one overload is allowed for non-strict function"); } auto& overloads = functions_[descriptor.name()]; overloads.static_overloads.push_back( StaticFunctionEntry(descriptor, std::move(implementation))); return absl::OkStatus(); } absl::Status FunctionRegistry::RegisterLazyFunction( const cel::FunctionDescriptor& descriptor) { if (DescriptorRegistered(descriptor)) { return absl::Status( absl::StatusCode::kAlreadyExists, "CelFunction with specified parameters already registered"); } if (!ValidateNonStrictOverload(descriptor)) { return absl::Status(absl::StatusCode::kAlreadyExists, "Only one overload is allowed for non-strict function"); } auto& overloads = functions_[descriptor.name()]; overloads.lazy_overloads.push_back( LazyFunctionEntry(descriptor, CreateActivationFunctionProvider())); return absl::OkStatus(); } std::vector<cel::FunctionOverloadReference> FunctionRegistry::FindStaticOverloads(absl::string_view name, bool receiver_style, absl::Span<const cel::Kind> types) const { std::vector<cel::FunctionOverloadReference> matched_funcs; auto overloads = functions_.find(name); if (overloads == functions_.end()) { return matched_funcs; } for (const auto& overload : overloads->second.static_overloads) { if (overload.descriptor->ShapeMatches(receiver_style, types)) { matched_funcs.push_back({*overload.descriptor, *overload.implementation}); } } return matched_funcs; } std::vector<FunctionRegistry::LazyOverload> FunctionRegistry::FindLazyOverloads( absl::string_view name, bool receiver_style, absl::Span<const cel::Kind> types) const { std::vector<FunctionRegistry::LazyOverload> matched_funcs; auto overloads = functions_.find(name); if (overloads == functions_.end()) { return matched_funcs; } for (const auto& entry : overloads->second.lazy_overloads) { if (entry.descriptor->ShapeMatches(receiver_style, types)) { matched_funcs.push_back({*entry.descriptor, *entry.function_provider}); } } return matched_funcs; } absl::node_hash_map<std::string, std::vector<const cel::FunctionDescriptor*>> FunctionRegistry::ListFunctions() const { absl::node_hash_map<std::string, std::vector<const cel::FunctionDescriptor*>> descriptor_map; for (const auto& entry : functions_) { std::vector<const cel::FunctionDescriptor*> descriptors; const RegistryEntry& function_entry = entry.second; descriptors.reserve(function_entry.static_overloads.size() + function_entry.lazy_overloads.size()); for (const auto& entry : function_entry.static_overloads) { descriptors.push_back(entry.descriptor.get()); } for (const auto& entry : function_entry.lazy_overloads) { descriptors.push_back(entry.descriptor.get()); } descriptor_map[entry.first] = std::move(descriptors); } return descriptor_map; } bool FunctionRegistry::DescriptorRegistered( const cel::FunctionDescriptor& descriptor) const { return !(FindStaticOverloads(descriptor.name(), descriptor.receiver_style(), descriptor.types()) .empty()) || !(FindLazyOverloads(descriptor.name(), descriptor.receiver_style(), descriptor.types()) .empty()); } bool FunctionRegistry::ValidateNonStrictOverload( const cel::FunctionDescriptor& descriptor) const { auto overloads = functions_.find(descriptor.name()); if (overloads == functions_.end()) { return true; } const RegistryEntry& entry = overloads->second; if (!descriptor.is_strict()) { return false; } return (entry.static_overloads.empty() || entry.static_overloads[0].descriptor->is_strict()) && (entry.lazy_overloads.empty() || entry.lazy_overloads[0].descriptor->is_strict()); } }
#include "runtime/function_registry.h" #include <cstdint> #include <memory> #include <tuple> #include <vector> #include "absl/status/status.h" #include "base/function.h" #include "base/function_adapter.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "common/value_manager.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/function_overload_reference.h" #include "runtime/function_provider.h" namespace cel { namespace { using ::cel::runtime_internal::FunctionProvider; using testing::ElementsAre; using testing::HasSubstr; using testing::SizeIs; using testing::Truly; using cel::internal::StatusIs; class ConstIntFunction : public cel::Function { public: static cel::FunctionDescriptor MakeDescriptor() { return {"ConstFunction", false, {}}; } absl::StatusOr<Value> Invoke(const FunctionEvaluationContext& context, absl::Span<const Value> args) const override { return context.value_factory().CreateIntValue(42); } }; TEST(FunctionRegistryTest, InsertAndRetrieveLazyFunction) { cel::FunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; FunctionRegistry registry; Activation activation; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); const auto descriptors = registry.FindLazyOverloads("LazyFunction", false, {}); EXPECT_THAT(descriptors, SizeIs(1)); } TEST(FunctionRegistryTest, LazyAndStaticFunctionShareDescriptorSpace) { FunctionRegistry registry; cel::FunctionDescriptor desc = ConstIntFunction::MakeDescriptor(); ASSERT_OK(registry.RegisterLazyFunction(desc)); absl::Status status = registry.Register(ConstIntFunction::MakeDescriptor(), std::make_unique<ConstIntFunction>()); EXPECT_FALSE(status.ok()); } TEST(FunctionRegistryTest, FindStaticOverloadsReturns) { FunctionRegistry registry; cel::FunctionDescriptor desc = ConstIntFunction::MakeDescriptor(); ASSERT_OK(registry.Register(desc, std::make_unique<ConstIntFunction>())); 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(FunctionRegistryTest, ListFunctions) { cel::FunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; FunctionRegistry registry; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); EXPECT_OK(registry.Register(ConstIntFunction::MakeDescriptor(), std::make_unique<ConstIntFunction>())); 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(FunctionRegistryTest, DefaultLazyProviderNoOverloadFound) { FunctionRegistry registry; Activation activation; cel::FunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; EXPECT_OK(registry.RegisterLazyFunction(lazy_function_desc)); auto providers = registry.FindLazyOverloads("LazyFunction", false, {}); ASSERT_THAT(providers, SizeIs(1)); const FunctionProvider& provider = providers[0].provider; ASSERT_OK_AND_ASSIGN( absl::optional<FunctionOverloadReference> func, provider.GetFunction({"LazyFunc", false, {cel::Kind::kInt64}}, activation)); EXPECT_EQ(func, absl::nullopt); } TEST(FunctionRegistryTest, DefaultLazyProviderReturnsImpl) { FunctionRegistry registry; Activation activation; EXPECT_OK(registry.RegisterLazyFunction( FunctionDescriptor("LazyFunction", false, {Kind::kAny}))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kInt}), UnaryFunctionAdapter<int64_t, int64_t>::WrapFunction( [](ValueManager&, int64_t x) { return 2 * x; }))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kDouble}), UnaryFunctionAdapter<double, double>::WrapFunction( [](ValueManager&, double x) { return 2 * x; }))); auto providers = registry.FindLazyOverloads("LazyFunction", false, {Kind::kInt}); ASSERT_THAT(providers, SizeIs(1)); const FunctionProvider& provider = providers[0].provider; ASSERT_OK_AND_ASSIGN( absl::optional<FunctionOverloadReference> func, provider.GetFunction( FunctionDescriptor("LazyFunction", false, {Kind::kInt}), activation)); ASSERT_TRUE(func.has_value()); EXPECT_EQ(func->descriptor.name(), "LazyFunction"); EXPECT_EQ(func->descriptor.types(), std::vector{cel::Kind::kInt64}); } TEST(FunctionRegistryTest, DefaultLazyProviderAmbiguousOverload) { FunctionRegistry registry; Activation activation; EXPECT_OK(registry.RegisterLazyFunction( FunctionDescriptor("LazyFunction", false, {Kind::kAny}))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kInt}), UnaryFunctionAdapter<int64_t, int64_t>::WrapFunction( [](ValueManager&, int64_t x) { return 2 * x; }))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kDouble}), UnaryFunctionAdapter<double, double>::WrapFunction( [](ValueManager&, double x) { return 2 * x; }))); auto providers = registry.FindLazyOverloads("LazyFunction", false, {Kind::kInt}); ASSERT_THAT(providers, SizeIs(1)); const FunctionProvider& provider = providers[0].provider; EXPECT_THAT( provider.GetFunction( FunctionDescriptor("LazyFunction", false, {Kind::kAny}), activation), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Couldn't resolve function"))); } TEST(FunctionRegistryTest, CanRegisterNonStrictFunction) { { FunctionRegistry registry; cel::FunctionDescriptor descriptor("NonStrictFunction", false, {Kind::kAny}, false); ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); EXPECT_THAT( registry.FindStaticOverloads("NonStrictFunction", false, {Kind::kAny}), SizeIs(1)); } { FunctionRegistry registry; cel::FunctionDescriptor descriptor("NonStrictLazyFunction", false, {Kind::kAny}, false); EXPECT_OK(registry.RegisterLazyFunction(descriptor)); EXPECT_THAT(registry.FindLazyOverloads("NonStrictLazyFunction", false, {Kind::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(); FunctionRegistry registry; cel::FunctionDescriptor descriptor("OverloadedFunction", false, {Kind::kAny}, true); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); } cel::FunctionDescriptor new_descriptor("OverloadedFunction", false, {Kind::kAny, Kind::kAny}, false); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register(new_descriptor, std::make_unique<ConstIntFunction>()); } 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(); FunctionRegistry registry; cel::FunctionDescriptor descriptor("OverloadedFunction", false, {Kind::kAny}, false); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); } cel::FunctionDescriptor new_descriptor("OverloadedFunction", false, {Kind::kAny, Kind::kAny}, true); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register(new_descriptor, std::make_unique<ConstIntFunction>()); } 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(); FunctionRegistry registry; cel::FunctionDescriptor descriptor("OverloadedFunction", false, {Kind::kAny}, true); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); } cel::FunctionDescriptor new_descriptor("OverloadedFunction", false, {Kind::kAny, Kind::kAny}, true); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register(new_descriptor, std::make_unique<ConstIntFunction>()); } EXPECT_OK(status); } INSTANTIATE_TEST_SUITE_P(NonStrictRegistrationFailTest, NonStrictRegistrationFailTest, testing::Combine(testing::Bool(), testing::Bool())); } }
142
cpp
google/cel-cpp
standard_runtime_builder_factory
runtime/standard_runtime_builder_factory.cc
runtime/standard_runtime_builder_factory_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_RUNTIME_BUILDER_FACTORY_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_RUNTIME_BUILDER_FACTORY_H_ #include "absl/status/statusor.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" namespace cel { absl::StatusOr<RuntimeBuilder> CreateStandardRuntimeBuilder( const RuntimeOptions& options); } #endif #include "runtime/standard_runtime_builder_factory.h" #include "absl/status/statusor.h" #include "internal/status_macros.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_builder_factory.h" #include "runtime/runtime_options.h" #include "runtime/standard_functions.h" namespace cel { absl::StatusOr<RuntimeBuilder> CreateStandardRuntimeBuilder( const RuntimeOptions& options) { RuntimeBuilder result = CreateRuntimeBuilder(options); CEL_RETURN_IF_ERROR( RegisterStandardFunctions(result.function_registry(), options)); return result; } }
#include "runtime/standard_runtime_builder_factory.h" #include <functional> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "common/memory.h" #include "common/source.h" #include "common/value.h" #include "common/value_manager.h" #include "common/value_testing.h" #include "common/values/legacy_value_manager.h" #include "extensions/bindings_ext.h" #include "extensions/protobuf/memory_manager.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/macro_registry.h" #include "parser/parser.h" #include "parser/standard_macros.h" #include "runtime/activation.h" #include "runtime/internal/runtime_impl.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime.h" #include "runtime/runtime_issue.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::cel::extensions::ProtobufRuntimeAdapter; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::test::BoolValueIs; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using testing::ElementsAre; using testing::Truly; struct EvaluateResultTestCase { std::string name; std::string expression; bool expected_result; std::function<absl::Status(ValueManager&, Activation&)> activation_builder; }; std::ostream& operator<<(std::ostream& os, const EvaluateResultTestCase& test_case) { return os << test_case.name; } const cel::MacroRegistry& GetMacros() { static absl::NoDestructor<cel::MacroRegistry> macros([]() { MacroRegistry registry; ABSL_CHECK_OK(cel::RegisterStandardMacros(registry, {})); for (const auto& macro : extensions::bindings_macros()) { ABSL_CHECK_OK(registry.RegisterMacro(macro)); } return registry; }()); return *macros; } absl::StatusOr<ParsedExpr> ParseWithTestMacros(absl::string_view expression) { auto src = cel::NewSource(expression, "<input>"); ABSL_CHECK_OK(src.status()); return Parse(**src, GetMacros()); } class StandardRuntimeTest : public common_internal::ThreadCompatibleValueTest< EvaluateResultTestCase> { public: const EvaluateResultTestCase& GetTestCase() { return std::get<1>(GetParam()); } }; TEST_P(StandardRuntimeTest, Defaults) { RuntimeOptions opts; const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithTestMacros(test_case.expression)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); EXPECT_FALSE(runtime_internal::TestOnly_IsRecursiveImpl(program.get())); common_internal::LegacyValueManager value_factory(memory_manager(), runtime->GetTypeProvider()); Activation activation; if (test_case.activation_builder != nullptr) { ASSERT_OK(test_case.activation_builder(value_factory, activation)); } ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, BoolValueIs(test_case.expected_result)) << test_case.expression; } TEST_P(StandardRuntimeTest, Recursive) { RuntimeOptions opts; opts.max_recursion_depth = -1; const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithTestMacros(test_case.expression)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); EXPECT_TRUE(runtime_internal::TestOnly_IsRecursiveImpl(program.get())); common_internal::LegacyValueManager value_factory(memory_manager(), runtime->GetTypeProvider()); Activation activation; if (test_case.activation_builder != nullptr) { ASSERT_OK(test_case.activation_builder(value_factory, activation)); } ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, BoolValueIs(test_case.expected_result)) << test_case.expression; } INSTANTIATE_TEST_SUITE_P( Basic, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"int_identifier", "int_var == 42", true, [](ValueManager& value_factory, Activation& activation) { activation.InsertOrAssignValue("int_var", value_factory.CreateIntValue(42)); return absl::OkStatus(); }}, {"logic_and_true", "true && 1 < 2", true}, {"logic_and_false", "true && 1 > 2", false}, {"logic_or_true", "false || 1 < 2", true}, {"logic_or_false", "false && 1 > 2", false}, {"ternary_true_cond", "(1 < 2 ? 'yes' : 'no') == 'yes'", true}, {"ternary_false_cond", "(1 > 2 ? 'yes' : 'no') == 'no'", true}, {"list_index", "['a', 'b', 'c', 'd'][1] == 'b'", true}, {"map_index_bool", "{true: 1, false: 2}[false] == 2", true}, {"map_index_string", "{'abc': 123}['abc'] == 123", true}, {"map_index_int", "{1: 2, 2: 4}[2] == 4", true}, {"map_index_uint", "{1u: 1, 2u: 2}[1u] == 1", true}, {"map_index_coerced_double", "{1: 2, 2: 4}[2.0] == 4", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( Equality, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"eq_bool_bool_true", "false == false", true}, {"eq_bool_bool_false", "false == true", false}, {"eq_int_int_true", "-1 == -1", true}, {"eq_int_int_false", "-1 == 1", false}, {"eq_uint_uint_true", "2u == 2u", true}, {"eq_uint_uint_false", "2u == 3u", false}, {"eq_double_double_true", "2.4 == 2.4", true}, {"eq_double_double_false", "2.4 == 3.3", false}, {"eq_string_string_true", "'abc' == 'abc'", true}, {"eq_string_string_false", "'abc' == 'def'", false}, {"eq_bytes_bytes_true", "b'abc' == b'abc'", true}, {"eq_bytes_bytes_false", "b'abc' == b'def'", false}, {"eq_duration_duration_true", "duration('15m') == duration('15m')", true}, {"eq_duration_duration_false", "duration('15m') == duration('1h')", false}, {"eq_timestamp_timestamp_true", "timestamp('1970-01-01T00:02:00Z') == " "timestamp('1970-01-01T00:02:00Z')", true}, {"eq_timestamp_timestamp_false", "timestamp('1970-01-01T00:02:00Z') == " "timestamp('2020-01-01T00:02:00Z')", false}, {"eq_null_null_true", "null == null", true}, {"eq_list_list_true", "[1, 2, 3] == [1, 2, 3]", true}, {"eq_list_list_false", "[1, 2, 3] == [1, 2, 3, 4]", false}, {"eq_map_map_true", "{1: 2, 2: 4} == {1: 2, 2: 4}", true}, {"eq_map_map_false", "{1: 2, 2: 4} == {1: 2, 2: 5}", false}, {"neq_bool_bool_true", "false != false", false}, {"neq_bool_bool_false", "false != true", true}, {"neq_int_int_true", "-1 != -1", false}, {"neq_int_int_false", "-1 != 1", true}, {"neq_uint_uint_true", "2u != 2u", false}, {"neq_uint_uint_false", "2u != 3u", true}, {"neq_double_double_true", "2.4 != 2.4", false}, {"neq_double_double_false", "2.4 != 3.3", true}, {"neq_string_string_true", "'abc' != 'abc'", false}, {"neq_string_string_false", "'abc' != 'def'", true}, {"neq_bytes_bytes_true", "b'abc' != b'abc'", false}, {"neq_bytes_bytes_false", "b'abc' != b'def'", true}, {"neq_duration_duration_true", "duration('15m') != duration('15m')", false}, {"neq_duration_duration_false", "duration('15m') != duration('1h')", true}, {"neq_timestamp_timestamp_true", "timestamp('1970-01-01T00:02:00Z') != " "timestamp('1970-01-01T00:02:00Z')", false}, {"neq_timestamp_timestamp_false", "timestamp('1970-01-01T00:02:00Z') != " "timestamp('2020-01-01T00:02:00Z')", true}, {"neq_null_null_true", "null != null", false}, {"neq_list_list_true", "[1, 2, 3] != [1, 2, 3]", false}, {"neq_list_list_false", "[1, 2, 3] != [1, 2, 3, 4]", true}, {"neq_map_map_true", "{1: 2, 2: 4} != {1: 2, 2: 4}", false}, {"neq_map_map_false", "{1: 2, 2: 4} != {1: 2, 2: 5}", true}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( ArithmeticFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"lt_int_int_true", "-1 < 2", true}, {"lt_int_int_false", "2 < -1", false}, {"lt_double_double_true", "-1.1 < 2.2", true}, {"lt_double_double_false", "2.2 < -1.1", false}, {"lt_uint_uint_true", "1u < 2u", true}, {"lt_uint_uint_false", "2u < 1u", false}, {"lt_string_string_true", "'abc' < 'def'", true}, {"lt_string_string_false", "'def' < 'abc'", false}, {"lt_duration_duration_true", "duration('1s') < duration('2s')", true}, {"lt_duration_duration_false", "duration('2s') < duration('1s')", false}, {"lt_timestamp_timestamp_true", "timestamp(1) < timestamp(2)", true}, {"lt_timestamp_timestamp_false", "timestamp(2) < timestamp(1)", false}, {"gt_int_int_false", "-1 > 2", false}, {"gt_int_int_true", "2 > -1", true}, {"gt_double_double_false", "-1.1 > 2.2", false}, {"gt_double_double_true", "2.2 > -1.1", true}, {"gt_uint_uint_false", "1u > 2u", false}, {"gt_uint_uint_true", "2u > 1u", true}, {"gt_string_string_false", "'abc' > 'def'", false}, {"gt_string_string_true", "'def' > 'abc'", true}, {"gt_duration_duration_false", "duration('1s') > duration('2s')", false}, {"gt_duration_duration_true", "duration('2s') > duration('1s')", true}, {"gt_timestamp_timestamp_false", "timestamp(1) > timestamp(2)", false}, {"gt_timestamp_timestamp_true", "timestamp(2) > timestamp(1)", true}, {"le_int_int_true", "-1 <= -1", true}, {"le_int_int_false", "2 <= -1", false}, {"le_double_double_true", "-1.1 <= -1.1", true}, {"le_double_double_false", "2.2 <= -1.1", false}, {"le_uint_uint_true", "1u <= 1u", true}, {"le_uint_uint_false", "2u <= 1u", false}, {"le_string_string_true", "'abc' <= 'abc'", true}, {"le_string_string_false", "'def' <= 'abc'", false}, {"le_duration_duration_true", "duration('1s') <= duration('1s')", true}, {"le_duration_duration_false", "duration('2s') <= duration('1s')", false}, {"le_timestamp_timestamp_true", "timestamp(1) <= timestamp(1)", true}, {"le_timestamp_timestamp_false", "timestamp(2) <= timestamp(1)", false}, {"ge_int_int_false", "-1 >= 2", false}, {"ge_int_int_true", "2 >= 2", true}, {"ge_double_double_false", "-1.1 >= 2.2", false}, {"ge_double_double_true", "2.2 >= 2.2", true}, {"ge_uint_uint_false", "1u >= 2u", false}, {"ge_uint_uint_true", "2u >= 2u", true}, {"ge_string_string_false", "'abc' >= 'def'", false}, {"ge_string_string_true", "'abc' >= 'abc'", true}, {"ge_duration_duration_false", "duration('1s') >= duration('2s')", false}, {"ge_duration_duration_true", "duration('1s') >= duration('1s')", true}, {"ge_timestamp_timestamp_false", "timestamp(1) >= timestamp(2)", false}, {"ge_timestamp_timestamp_true", "timestamp(1) >= timestamp(1)", true}, {"sum_int_int", "1 + 2 == 3", true}, {"sum_uint_uint", "3u + 4u == 7", true}, {"sum_double_double", "1.0 + 2.5 == 3.5", true}, {"sum_duration_duration", "duration('2m') + duration('30s') == duration('150s')", true}, {"sum_time_duration", "timestamp(0) + duration('2m') == " "timestamp('1970-01-01T00:02:00Z')", true}, {"difference_int_int", "1 - 2 == -1", true}, {"difference_uint_uint", "4u - 3u == 1u", true}, {"difference_double_double", "1.0 - 2.5 == -1.5", true}, {"difference_duration_duration", "duration('5m') - duration('45s') == duration('4m15s')", true}, {"difference_time_time", "timestamp(10) - timestamp(0) == duration('10s')", true}, {"difference_time_duration", "timestamp(0) - duration('2m') == " "timestamp('1969-12-31T23:58:00Z')", true}, {"multiplication_int_int", "2 * 3 == 6", true}, {"multiplication_uint_uint", "2u * 3u == 6u", true}, {"multiplication_double_double", "2.5 * 3.0 == 7.5", true}, {"division_int_int", "6 / 3 == 2", true}, {"division_uint_uint", "8u / 4u == 2u", true}, {"division_double_double", "1.0 / 0.0 == double('inf')", true}, {"modulo_int_int", "6 % 4 == 2", true}, {"modulo_uint_uint", "8u % 5u == 3u", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( Macros, StandardRuntimeTest, testing::Combine(testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"map", "[1, 2, 3, 4].map(x, x * x)[3] == 16", true}, {"filter", "[1, 2, 3, 4].filter(x, x < 4).size() == 3", true}, {"exists", "[1, 2, 3, 4].exists(x, x < 4)", true}, {"all", "[1, 2, 3, 4].all(x, x < 5)", true}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( StringFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"string_contains", "'tacocat'.contains('acoca')", true}, {"string_contains_global", "contains('tacocat', 'dog')", false}, {"string_ends_with", "'abcdefg'.endsWith('efg')", true}, {"string_ends_with_global", "endsWith('abcdefg', 'fgh')", false}, {"string_starts_with", "'abcdefg'.startsWith('abc')", true}, {"string_starts_with_global", "startsWith('abcd', 'bcd')", false}, {"string_size", "'Hello World! 😀'.size() == 14", true}, {"string_size_global", "size('Hello world!') == 12", true}, {"bytes_size", "b'0123'.size() == 4", true}, {"bytes_size_global", "size(b'😀') == 4", true}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( RegExFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"matches_string_re", "'127.0.0.1'.matches(r'127\\.\\d+\\.\\d+\\.\\d+')", true}, {"matches_string_re_global", "matches('192.168.0.1', r'127\\.\\d+\\.\\d+\\.\\d+')", false}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( TimeFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"timestamp_get_full_year", "timestamp('2001-02-03T04:05:06.007Z').getFullYear() == 2001", true}, {"timestamp_get_date", "timestamp('2001-02-03T04:05:06.007Z').getDate() == 3", true}, {"timestamp_get_hours", "timestamp('2001-02-03T04:05:06.007Z').getHours() == 4", true}, {"timestamp_get_minutes", "timestamp('2001-02-03T04:05:06.007Z').getMinutes() == 5", true}, {"timestamp_get_seconds", "timestamp('2001-02-03T04:05:06.007Z').getSeconds() == 6", true}, {"timestamp_get_milliseconds", "timestamp('2001-02-03T04:05:06.007Z').getMilliseconds() == 7", true}, {"timestamp_get_month", "timestamp('2001-02-03T04:05:06.007Z').getMonth() == 1", true}, {"timestamp_get_day_of_year", "timestamp('2001-02-03T04:05:06.007Z').getDayOfYear() == 33", true}, {"timestamp_get_day_of_month", "timestamp('2001-02-03T04:05:06.007Z').getDayOfMonth() == 2", true}, {"timestamp_get_day_of_week", "timestamp('2001-02-03T04:05:06.007Z').getDayOfWeek() == 6", true}, {"duration_get_hours", "duration('10h20m30s40ms').getHours() == 10", true}, {"duration_get_minutes", "duration('10h20m30s40ms').getMinutes() == 20 + 600", true}, {"duration_get_seconds", "duration('10h20m30s40ms').getSeconds() == 30 + 20 * 60 + 10 * 60 " "* " "60", true}, {"duration_get_milliseconds", "duration('10h20m30s40ms').getMilliseconds() == 40", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( TypeConversionFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"string_timestamp", "string(timestamp(1)) == '1970-01-01T00:00:01Z'", true}, {"string_duration", "string(duration('10m30s')) == '630s'", true}, {"string_int", "string(-1) == '-1'", true}, {"string_uint", "string(1u) == '1'", true}, {"string_double", "string(double('inf')) == 'inf'", true}, {"string_bytes", R"(string(b'\xF0\x9F\x98\x80') == '😀')", true}, {"string_string", "string('hello!') == 'hello!'", true}, {"bytes_bytes", "bytes(b'123') == b'123'", true}, {"bytes_string", "bytes('😀') == b'\xF0\x9F\x98\x80'", true}, {"timestamp", "timestamp(1) == timestamp('1970-01-01T00:00:01Z')", true}, {"duration", "duration('10h') == duration('600m')", true}, {"double_string", "double('1.0') == 1.0", true}, {"double_string_nan", "double('nan') != double('nan')", true}, {"double_int", "double(1) == 1.0", true}, {"double_uint", "double(1u) == 1.0", true}, {"double_double", "double(1.0) == 1.0", true}, {"uint_string", "uint('1') == 1u", true}, {"uint_int", "uint(1) == 1u", true}, {"uint_uint", "uint(1u) == 1u", true}, {"uint_double", "uint(1.1) == 1u", true}, {"int_string", "int('-1') == -1", true}, {"int_int", "int(-1) == -1", true}, {"int_uint", "int(1u) == 1", true}, {"int_double", "int(-1.1) == -1", true}, {"int_timestamp", "int(timestamp('1969-12-31T23:30:00Z')) == -1800", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( ContainerFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"map_size", "{'abc': 1, 'def': 2}.size() == 2", true}, {"map_in", "'abc' in {'abc': 1, 'def': 2}", true}, {"map_in_numeric", "1.0 in {1u: 1, 2u: 2}", true}, {"list_size", "[1, 2, 3, 4].size() == 4", true}, {"list_size_global", "size([1, 2, 3]) == 3", true}, {"list_concat", "[1, 2] + [3, 4] == [1, 2, 3, 4]", true}, {"list_in", "'a' in ['a', 'b', 'c', 'd']", true}, {"list_in_numeric", "3u in [1.1, 2.3, 3.0, 4.4]", true}})), StandardRuntimeTest::ToString); TEST(StandardRuntimeTest, RuntimeIssueSupport) { RuntimeOptions options; options.fail_on_warnings = false; google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithTestMacros("unregistered_function(1)")); std::vector<RuntimeIssue> issues; ASSERT_OK_AND_ASSIGN( std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr, {&issues})); EXPECT_THAT(issues, ElementsAre(Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }))); } { ASSERT_OK_AND_ASSIGN( ParsedExpr expr, ParseWithTestMacros( "unregistered_function(1) || unregistered_function(2)")); std::vector<RuntimeIssue> issues; ASSERT_OK_AND_ASSIGN( std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr, {&issues})); EXPECT_THAT( issues, ElementsAre( Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }), Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }))); } { ASSERT_OK_AND_ASSIGN( ParsedExpr expr, ParseWithTestMacros( "unregistered_function(1) || unregistered_function(2) || true")); std::vector<RuntimeIssue> issues; ASSERT_OK_AND_ASSIGN( std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr, {&issues})); EXPECT_THAT( issues, ElementsAre( Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }), Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }))); ManagedValueFactory value_factory(program->GetTypeProvider(), memory_manager); Activation activation; ASSERT_OK_AND_ASSIGN(auto result, program->Evaluate(activation, value_factory.get())); EXPECT_TRUE(result->Is<BoolValue>() && result->As<BoolValue>().NativeValue()); } } } }
143
cpp
google/cel-cpp
mutable_list_impl
runtime/internal/mutable_list_impl.cc
runtime/internal/mutable_list_impl_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_INTERNAL_MUTABLE_LIST_IMPL_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_INTERNAL_MUTABLE_LIST_IMPL_H_ #include <string> #include "absl/status/status.h" #include "common/memory.h" #include "common/type.h" #include "common/value.h" #include "internal/casts.h" namespace cel::runtime_internal { constexpr char kMutableListTypeName[] = "#cel.MutableList"; class MutableListValue final : public cel::OpaqueValueInterface { public: static bool Is(const Value& value) { return InstanceOf<OpaqueValue>(value) && NativeTypeId::Of(value) == NativeTypeId::For<MutableListValue>(); } static MutableListValue& Cast(Value& value) { return const_cast<MutableListValue&>( cel::internal::down_cast<const MutableListValue&>( *cel::Cast<OpaqueValue>(value))); } static MutableListValue& Cast(OpaqueValue& value) { return const_cast<MutableListValue&>( cel::internal::down_cast<const MutableListValue&>(*value)); } explicit MutableListValue(cel::Unique<cel::ListValueBuilder> list_builder); absl::string_view GetTypeName() const override { return kMutableListTypeName; } absl::Status Equal(ValueManager&, ValueView, cel::Value& result) const override { result = BoolValueView{false}; return absl::OkStatus(); } absl::Status Append(cel::Value element); absl::StatusOr<cel::ListValue> Build() &&; std::string DebugString() const override; private: Type GetTypeImpl(TypeManager& type_manager) const override; cel::NativeTypeId GetNativeTypeId() const override; cel::Unique<cel::ListValueBuilder> list_builder_; }; } #endif #include "runtime/internal/mutable_list_impl.h" #include <memory> #include <string> #include <utility> #include "common/native_type.h" #include "common/type.h" #include "common/value.h" namespace cel::runtime_internal { using ::cel::NativeTypeId; MutableListValue::MutableListValue( cel::Unique<cel::ListValueBuilder> list_builder) : cel::OpaqueValueInterface(), list_builder_(std::move(list_builder)) {} absl::Status MutableListValue::Append(cel::Value element) { return list_builder_->Add(std::move(element)); } absl::StatusOr<cel::ListValue> MutableListValue::Build() && { return std::move(*list_builder_).Build(); } std::string MutableListValue::DebugString() const { return kMutableListTypeName; } Type MutableListValue::GetTypeImpl(TypeManager& type_manager) const { return type_manager.CreateOpaqueType(kMutableListTypeName, {}); } NativeTypeId MutableListValue::GetNativeTypeId() const { return cel::NativeTypeId::For<MutableListValue>(); } }
#include "runtime/internal/mutable_list_impl.h" #include "base/type_provider.h" #include "common/memory.h" #include "common/type.h" #include "common/type_factory.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "internal/testing.h" namespace cel::runtime_internal { namespace { using cel::internal::IsOkAndHolds; TEST(MutableListImplValue, Creation) { common_internal::LegacyValueManager value_factory( MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()); ASSERT_OK_AND_ASSIGN(auto builder, value_factory.NewListValueBuilder( value_factory.GetDynListType())); auto mutable_list_value = value_factory.GetMemoryManager().MakeShared<MutableListValue>( std::move(builder)); OpaqueValue opaque_handle = mutable_list_value; EXPECT_EQ(NativeTypeId::Of(opaque_handle), NativeTypeId::For<MutableListValue>()); EXPECT_EQ(opaque_handle.operator->(), mutable_list_value.operator->()); } TEST(MutableListImplValue, ListBuilding) { common_internal::LegacyValueManager value_factory( MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()); ASSERT_OK_AND_ASSIGN(auto builder, value_factory.NewListValueBuilder( value_factory.GetDynListType())); auto mutable_list_value = value_factory.GetMemoryManager().MakeShared<MutableListValue>( std::move(builder)); MutableListValue& mutable_ref = const_cast<MutableListValue&>(*mutable_list_value); ASSERT_OK(mutable_ref.Append(value_factory.CreateIntValue(1))); ASSERT_OK_AND_ASSIGN(ListValue list_value, std::move(mutable_ref).Build()); EXPECT_THAT(list_value.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(auto element, list_value.Get(value_factory, 0)); ASSERT_TRUE(InstanceOf<IntValue>(element)); EXPECT_EQ(Cast<IntValue>(element).NativeValue(), 1); } } }
144
cpp
google/cel-cpp
time_functions
runtime/standard/time_functions.cc
runtime/standard/time_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_TIME_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_TIME_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterTimeFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/time_functions.h" #include <functional> #include <string> #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/overflow.h" #include "internal/status_macros.h" namespace cel { namespace { absl::Status FindTimeBreakdown(absl::Time timestamp, absl::string_view tz, absl::TimeZone::CivilInfo* breakdown) { absl::TimeZone time_zone; if (tz.empty()) { *breakdown = time_zone.At(timestamp); return absl::OkStatus(); } if (absl::LoadTimeZone(tz, &time_zone)) { *breakdown = time_zone.At(timestamp); return absl::OkStatus(); } if (absl::StrContains(tz, ":")) { std::string dur = absl::StrCat(tz, "m"); absl::StrReplaceAll({{":", "h"}}, &dur); absl::Duration d; if (absl::ParseDuration(dur, &d)) { timestamp += d; *breakdown = time_zone.At(timestamp); return absl::OkStatus(); } } return absl::InvalidArgumentError("Invalid timezone"); } Value GetTimeBreakdownPart( ValueManager& value_factory, absl::Time timestamp, absl::string_view tz, const std::function<int64_t(const absl::TimeZone::CivilInfo&)>& extractor_func) { absl::TimeZone::CivilInfo breakdown; auto status = FindTimeBreakdown(timestamp, tz, &breakdown); if (!status.ok()) { return value_factory.CreateErrorValue(status); } return value_factory.CreateIntValue(extractor_func(breakdown)); } Value GetFullYear(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.year(); }); } Value GetMonth(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.month() - 1; }); } Value GetDayOfYear(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart( value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return absl::GetYearDay(absl::CivilDay(breakdown.cs)) - 1; }); } Value GetDayOfMonth(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.day() - 1; }); } Value GetDate(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.day(); }); } Value GetDayOfWeek(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart( value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { absl::Weekday weekday = absl::GetWeekday(breakdown.cs); int weekday_num = static_cast<int>(weekday); weekday_num = (weekday_num == 6) ? 0 : weekday_num + 1; return weekday_num; }); } Value GetHours(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.hour(); }); } Value GetMinutes(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.minute(); }); } Value GetSeconds(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.second(); }); } Value GetMilliseconds(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart( value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return absl::ToInt64Milliseconds(breakdown.subsecond); }); } absl::Status RegisterTimestampFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kFullYear, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetFullYear(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kFullYear, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetFullYear(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kMonth, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetMonth(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor(builtin::kMonth, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetMonth(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDayOfYear, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDayOfYear(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kDayOfYear, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDayOfYear(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDayOfMonth, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDayOfMonth(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kDayOfMonth, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDayOfMonth(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDate, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDate(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor(builtin::kDate, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDate(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDayOfWeek, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDayOfWeek(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kDayOfWeek, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDayOfWeek(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kHours, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetHours(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor(builtin::kHours, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetHours(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kMinutes, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetMinutes(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kMinutes, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetMinutes(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kSeconds, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetSeconds(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kSeconds, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetSeconds(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kMilliseconds, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetMilliseconds(value_factory, ts, tz.ToString()); }))); return registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kMilliseconds, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetMilliseconds(value_factory, ts, ""); })); } absl::Status RegisterCheckedTimeArithmeticFunctions( FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> absl::StatusOr<Value> { auto sum = cel::internal::CheckedAdd(t1, d2); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateTimestampValue(*sum); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Time>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Time>:: WrapFunction([](ValueManager& value_factory, absl::Duration d2, absl::Time t1) -> absl::StatusOr<Value> { auto sum = cel::internal::CheckedAdd(t1, d2); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateTimestampValue(*sum); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> absl::StatusOr<Value> { auto sum = cel::internal::CheckedAdd(d1, d2); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateDurationValue(*sum); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Duration>:: CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> absl::StatusOr<Value> { auto diff = cel::internal::CheckedSub(t1, d2); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateTimestampValue(*diff); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Time>::CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Time>:: WrapFunction([](ValueManager& value_factory, absl::Time t1, absl::Time t2) -> absl::StatusOr<Value> { auto diff = cel::internal::CheckedSub(t1, t2); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateDurationValue(*diff); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, absl::Duration, absl::Duration>::CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> absl::StatusOr<Value> { auto diff = cel::internal::CheckedSub(d1, d2); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateDurationValue(*diff); }))); return absl::OkStatus(); } absl::Status RegisterUncheckedTimeArithmeticFunctions( FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::WrapFunction( [](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedTimestampValue(t1 + d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Duration, absl::Time>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<Value, absl::Duration, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Duration d2, absl::Time t1) -> Value { return value_factory.CreateUncheckedTimestampValue(t1 + d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedDurationValue(d1 + d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Duration>:: CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::WrapFunction( [](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedTimestampValue(t1 - d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Time>::CreateDescriptor( builtin::kSubtract, false), BinaryFunctionAdapter<Value, absl::Time, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time t1, absl::Time t2) -> Value { return value_factory.CreateUncheckedDurationValue(t1 - t2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>:: CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedDurationValue(d1 - d2); }))); return absl::OkStatus(); } absl::Status RegisterDurationFunctions(FunctionRegistry& registry) { using DurationAccessorFunction = UnaryFunctionAdapter<int64_t, absl::Duration>; CEL_RETURN_IF_ERROR(registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kHours, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { return absl::ToInt64Hours(d); }))); CEL_RETURN_IF_ERROR(registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kMinutes, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { return absl::ToInt64Minutes(d); }))); CEL_RETURN_IF_ERROR(registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kSeconds, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { return absl::ToInt64Seconds(d); }))); return registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kMilliseconds, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { constexpr int64_t millis_per_second = 1000L; return absl::ToInt64Milliseconds(d) % millis_per_second; })); } } absl::Status RegisterTimeFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterTimestampFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterDurationFunctions(registry)); if (options.enable_timestamp_duration_overflow_errors) { return RegisterCheckedTimeArithmeticFunctions(registry); } return RegisterUncheckedTimeArithmeticFunctions(registry); } }
#include "runtime/standard/time_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using testing::UnorderedElementsAre; MATCHER_P3(MatchesOperatorDescriptor, name, expected_kind1, expected_kind2, "") { const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{expected_kind1, expected_kind2}; return descriptor.name() == name && descriptor.receiver_style() == false && descriptor.types() == types; } MATCHER_P2(MatchesTimeAccessor, name, kind, "") { const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{kind}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } MATCHER_P2(MatchesTimezoneTimeAccessor, name, kind, "") { const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{kind, Kind::kString}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } TEST(RegisterTimeFunctions, MathOperatorsRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTimeFunctions(registry, options)); auto registered_functions = registry.ListFunctions(); EXPECT_THAT(registered_functions[builtin::kAdd], UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kAdd, Kind::kDuration, Kind::kDuration), MatchesOperatorDescriptor(builtin::kAdd, Kind::kTimestamp, Kind::kDuration), MatchesOperatorDescriptor(builtin::kAdd, Kind::kDuration, Kind::kTimestamp))); EXPECT_THAT(registered_functions[builtin::kSubtract], UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kSubtract, Kind::kDuration, Kind::kDuration), MatchesOperatorDescriptor(builtin::kSubtract, Kind::kTimestamp, Kind::kDuration), MatchesOperatorDescriptor( builtin::kSubtract, Kind::kTimestamp, Kind::kTimestamp))); } TEST(RegisterTimeFunctions, AccessorsRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTimeFunctions(registry, options)); auto registered_functions = registry.ListFunctions(); EXPECT_THAT( registered_functions[builtin::kFullYear], UnorderedElementsAre( MatchesTimeAccessor(builtin::kFullYear, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kFullYear, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDate], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDate, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDate, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kMonth], UnorderedElementsAre( MatchesTimeAccessor(builtin::kMonth, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kMonth, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDayOfYear], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDayOfYear, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDayOfYear, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDayOfMonth], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDayOfMonth, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDayOfMonth, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDayOfWeek], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDayOfWeek, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDayOfWeek, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kHours], UnorderedElementsAre( MatchesTimeAccessor(builtin::kHours, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kHours, Kind::kTimestamp), MatchesTimeAccessor(builtin::kHours, Kind::kDuration))); EXPECT_THAT( registered_functions[builtin::kMinutes], UnorderedElementsAre( MatchesTimeAccessor(builtin::kMinutes, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kMinutes, Kind::kTimestamp), MatchesTimeAccessor(builtin::kMinutes, Kind::kDuration))); EXPECT_THAT( registered_functions[builtin::kSeconds], UnorderedElementsAre( MatchesTimeAccessor(builtin::kSeconds, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kSeconds, Kind::kTimestamp), MatchesTimeAccessor(builtin::kSeconds, Kind::kDuration))); EXPECT_THAT( registered_functions[builtin::kMilliseconds], UnorderedElementsAre( MatchesTimeAccessor(builtin::kMilliseconds, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kMilliseconds, Kind::kTimestamp), MatchesTimeAccessor(builtin::kMilliseconds, Kind::kDuration))); } } }
145
cpp
google/cel-cpp
equality_functions
runtime/standard/equality_functions.cc
runtime/standard/equality_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_EQUALITY_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_EQUALITY_FUNCTIONS_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "common/value.h" #include "common/value_manager.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace runtime_internal { absl::StatusOr<absl::optional<bool>> ValueEqualImpl(ValueManager& value_factory, const Value& v1, const Value& v2); } absl::Status RegisterEqualityFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/equality_functions.h" #include <cstdint> #include <functional> #include <optional> #include <type_traits> #include <utility> #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "base/kind.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::cel::Cast; using ::cel::InstanceOf; using ::cel::builtin::kEqual; using ::cel::builtin::kInequal; using ::cel::internal::Number; struct HomogenousEqualProvider { static constexpr bool kIsHeterogeneous = false; absl::StatusOr<absl::optional<bool>> operator()(ValueManager& value_factory, const Value& lhs, const Value& rhs) const; }; struct HeterogeneousEqualProvider { static constexpr bool kIsHeterogeneous = true; absl::StatusOr<absl::optional<bool>> operator()(ValueManager& value_factory, const Value& lhs, const Value& rhs) const; }; template <class Type> absl::optional<bool> Inequal(Type lhs, Type rhs) { return lhs != rhs; } template <> absl::optional<bool> Inequal(const StringValue& lhs, const StringValue& rhs) { return !lhs.Equals(rhs); } template <> absl::optional<bool> Inequal(const BytesValue& lhs, const BytesValue& rhs) { return !lhs.Equals(rhs); } template <> absl::optional<bool> Inequal(const NullValue&, const NullValue&) { return false; } template <> absl::optional<bool> Inequal(const TypeValue& lhs, const TypeValue& rhs) { return lhs.name() != rhs.name(); } template <class Type> absl::optional<bool> Equal(Type lhs, Type rhs) { return lhs == rhs; } template <> absl::optional<bool> Equal(const StringValue& lhs, const StringValue& rhs) { return lhs.Equals(rhs); } template <> absl::optional<bool> Equal(const BytesValue& lhs, const BytesValue& rhs) { return lhs.Equals(rhs); } template <> absl::optional<bool> Equal(const NullValue&, const NullValue&) { return true; } template <> absl::optional<bool> Equal(const TypeValue& lhs, const TypeValue& rhs) { return lhs.name() == rhs.name(); } template <typename EqualsProvider> absl::StatusOr<absl::optional<bool>> ListEqual(ValueManager& factory, const ListValue& lhs, const ListValue& rhs) { if (&lhs == &rhs) { return true; } CEL_ASSIGN_OR_RETURN(auto lhs_size, lhs.Size()); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { return false; } for (int i = 0; i < lhs_size; ++i) { CEL_ASSIGN_OR_RETURN(auto lhs_i, lhs.Get(factory, i)); CEL_ASSIGN_OR_RETURN(auto rhs_i, rhs.Get(factory, i)); CEL_ASSIGN_OR_RETURN(absl::optional<bool> eq, EqualsProvider()(factory, lhs_i, rhs_i)); if (!eq.has_value() || !*eq) { return eq; } } return true; } absl::StatusOr<absl::optional<bool>> OpaqueEqual(ValueManager& manager, const OpaqueValue& lhs, const OpaqueValue& rhs) { Value result; CEL_RETURN_IF_ERROR(lhs.Equal(manager, rhs, result)); if (auto bool_value = As<BoolValue>(result); bool_value) { return bool_value->NativeValue(); } return TypeConversionError(result.GetTypeName(), "bool").NativeValue(); } absl::optional<Number> NumberFromValue(const Value& value) { if (value.Is<IntValue>()) { return Number::FromInt64(value.As<IntValue>().NativeValue()); } else if (value.Is<UintValue>()) { return Number::FromUint64(value.As<UintValue>().NativeValue()); } else if (value.Is<DoubleValue>()) { return Number::FromDouble(value.As<DoubleValue>().NativeValue()); } return absl::nullopt; } absl::StatusOr<absl::optional<Value>> CheckAlternativeNumericType( ValueManager& value_factory, const Value& key, const MapValue& rhs) { absl::optional<Number> number = NumberFromValue(key); if (!number.has_value()) { return absl::nullopt; } if (!InstanceOf<IntValue>(key) && number->LosslessConvertibleToInt()) { Value entry; bool ok; CEL_ASSIGN_OR_RETURN( std::tie(entry, ok), rhs.Find(value_factory, value_factory.CreateIntValue(number->AsInt()))); if (ok) { return entry; } } if (!InstanceOf<UintValue>(key) && number->LosslessConvertibleToUint()) { Value entry; bool ok; CEL_ASSIGN_OR_RETURN(std::tie(entry, ok), rhs.Find(value_factory, value_factory.CreateUintValue( number->AsUint()))); if (ok) { return entry; } } return absl::nullopt; } template <typename EqualsProvider> absl::StatusOr<absl::optional<bool>> MapEqual(ValueManager& value_factory, const MapValue& lhs, const MapValue& rhs) { if (&lhs == &rhs) { return true; } if (lhs.Size() != rhs.Size()) { return false; } CEL_ASSIGN_OR_RETURN(auto iter, lhs.NewIterator(value_factory)); while (iter->HasNext()) { CEL_ASSIGN_OR_RETURN(auto lhs_key, iter->Next(value_factory)); Value rhs_value; bool rhs_ok; CEL_ASSIGN_OR_RETURN(std::tie(rhs_value, rhs_ok), rhs.Find(value_factory, lhs_key)); if (!rhs_ok && EqualsProvider::kIsHeterogeneous) { CEL_ASSIGN_OR_RETURN( auto maybe_rhs_value, CheckAlternativeNumericType(value_factory, lhs_key, rhs)); rhs_ok = maybe_rhs_value.has_value(); if (rhs_ok) { rhs_value = std::move(*maybe_rhs_value); } } if (!rhs_ok) { return false; } CEL_ASSIGN_OR_RETURN(auto lhs_value, lhs.Get(value_factory, lhs_key)); CEL_ASSIGN_OR_RETURN(absl::optional<bool> eq, EqualsProvider()(value_factory, lhs_value, rhs_value)); if (!eq.has_value() || !*eq) { return eq; } } return true; } template <typename Type, typename Op> std::function<Value(cel::ValueManager& factory, Type, Type)> WrapComparison( Op op, absl::string_view name) { return [op = std::move(op), name](cel::ValueManager& factory, Type lhs, Type rhs) -> Value { absl::optional<bool> result = op(lhs, rhs); if (result.has_value()) { return factory.CreateBoolValue(*result); } return factory.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(name)); }; } template <class Type> absl::Status RegisterEqualityFunctionsForType(cel::FunctionRegistry& registry) { using FunctionAdapter = cel::RegisterHelper<BinaryFunctionAdapter<Value, Type, Type>>; CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kInequal, WrapComparison<Type>(&Inequal<Type>, kInequal), registry)); CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kEqual, WrapComparison<Type>(&Equal<Type>, kEqual), registry)); return absl::OkStatus(); } template <typename Type, typename Op> auto ComplexEquality(Op&& op) { return [op = std::forward<Op>(op)](cel::ValueManager& f, const Type& t1, const Type& t2) -> absl::StatusOr<Value> { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, op(f, t1, t2)); if (!result.has_value()) { return f.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kEqual)); } return f.CreateBoolValue(*result); }; } template <typename Type, typename Op> auto ComplexInequality(Op&& op) { return [op = std::forward<Op>(op)](cel::ValueManager& f, Type t1, Type t2) -> absl::StatusOr<Value> { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, op(f, t1, t2)); if (!result.has_value()) { return f.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kInequal)); } return f.CreateBoolValue(!*result); }; } template <class Type> absl::Status RegisterComplexEqualityFunctionsForType( absl::FunctionRef<absl::StatusOr<absl::optional<bool>>(ValueManager&, Type, Type)> op, cel::FunctionRegistry& registry) { using FunctionAdapter = cel::RegisterHelper< BinaryFunctionAdapter<absl::StatusOr<Value>, Type, Type>>; CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kInequal, ComplexInequality<Type>(op), registry)); CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kEqual, ComplexEquality<Type>(op), registry)); return absl::OkStatus(); } absl::Status RegisterHomogenousEqualityFunctions( cel::FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<bool>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<int64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<uint64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<double>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::StringValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::BytesValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<absl::Duration>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<absl::Time>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::NullValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::TypeValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterComplexEqualityFunctionsForType<const cel::ListValue&>( &ListEqual<HomogenousEqualProvider>, registry)); CEL_RETURN_IF_ERROR( RegisterComplexEqualityFunctionsForType<const cel::MapValue&>( &MapEqual<HomogenousEqualProvider>, registry)); return absl::OkStatus(); } absl::Status RegisterNullMessageEqualityFunctions(FunctionRegistry& registry) { CEL_RETURN_IF_ERROR( (cel::RegisterHelper< BinaryFunctionAdapter<bool, const StructValue&, const NullValue&>>:: RegisterGlobalOverload( kEqual, [](ValueManager&, const StructValue&, const NullValue&) { return false; }, registry))); CEL_RETURN_IF_ERROR( (cel::RegisterHelper< BinaryFunctionAdapter<bool, const NullValue&, const StructValue&>>:: RegisterGlobalOverload( kEqual, [](ValueManager&, const NullValue&, const StructValue&) { return false; }, registry))); CEL_RETURN_IF_ERROR( (cel::RegisterHelper< BinaryFunctionAdapter<bool, const StructValue&, const NullValue&>>:: RegisterGlobalOverload( kInequal, [](ValueManager&, const StructValue&, const NullValue&) { return true; }, registry))); return cel::RegisterHelper< BinaryFunctionAdapter<bool, const NullValue&, const StructValue&>>:: RegisterGlobalOverload( kInequal, [](ValueManager&, const NullValue&, const StructValue&) { return true; }, registry); } template <typename EqualsProvider> absl::StatusOr<absl::optional<bool>> HomogenousValueEqual(ValueManager& factory, const Value& v1, const Value& v2) { if (v1->kind() != v2->kind()) { return absl::nullopt; } static_assert(std::is_lvalue_reference_v<decltype(Cast<StringValue>(v1))>, "unexpected value copy"); switch (v1->kind()) { case ValueKind::kBool: return Equal<bool>(Cast<BoolValue>(v1).NativeValue(), Cast<BoolValue>(v2).NativeValue()); case ValueKind::kNull: return Equal<const NullValue&>(Cast<NullValue>(v1), Cast<NullValue>(v2)); case ValueKind::kInt: return Equal<int64_t>(Cast<IntValue>(v1).NativeValue(), Cast<IntValue>(v2).NativeValue()); case ValueKind::kUint: return Equal<uint64_t>(Cast<UintValue>(v1).NativeValue(), Cast<UintValue>(v2).NativeValue()); case ValueKind::kDouble: return Equal<double>(Cast<DoubleValue>(v1).NativeValue(), Cast<DoubleValue>(v2).NativeValue()); case ValueKind::kDuration: return Equal<absl::Duration>(Cast<DurationValue>(v1).NativeValue(), Cast<DurationValue>(v2).NativeValue()); case ValueKind::kTimestamp: return Equal<absl::Time>(Cast<TimestampValue>(v1).NativeValue(), Cast<TimestampValue>(v2).NativeValue()); case ValueKind::kCelType: return Equal<const TypeValue&>(Cast<TypeValue>(v1), Cast<TypeValue>(v2)); case ValueKind::kString: return Equal<const StringValue&>(Cast<StringValue>(v1), Cast<StringValue>(v2)); case ValueKind::kBytes: return Equal<const cel::BytesValue&>(v1->As<cel::BytesValue>(), v2->As<cel::BytesValue>()); case ValueKind::kList: return ListEqual<EqualsProvider>(factory, Cast<ListValue>(v1), Cast<ListValue>(v2)); case ValueKind::kMap: return MapEqual<EqualsProvider>(factory, Cast<MapValue>(v1), Cast<MapValue>(v2)); case ValueKind::kOpaque: return OpaqueEqual(factory, Cast<OpaqueValue>(v1), Cast<OpaqueValue>(v2)); default: return absl::nullopt; } } absl::StatusOr<Value> EqualOverloadImpl(ValueManager& factory, const Value& lhs, const Value& rhs) { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, runtime_internal::ValueEqualImpl(factory, lhs, rhs)); if (result.has_value()) { return factory.CreateBoolValue(*result); } return factory.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kEqual)); } absl::StatusOr<Value> InequalOverloadImpl(ValueManager& factory, const Value& lhs, const Value& rhs) { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, runtime_internal::ValueEqualImpl(factory, lhs, rhs)); if (result.has_value()) { return factory.CreateBoolValue(!*result); } return factory.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kInequal)); } absl::Status RegisterHeterogeneousEqualityFunctions( cel::FunctionRegistry& registry) { using Adapter = cel::RegisterHelper< BinaryFunctionAdapter<absl::StatusOr<Value>, const Value&, const Value&>>; CEL_RETURN_IF_ERROR( Adapter::RegisterGlobalOverload(kEqual, &EqualOverloadImpl, registry)); CEL_RETURN_IF_ERROR(Adapter::RegisterGlobalOverload( kInequal, &InequalOverloadImpl, registry)); return absl::OkStatus(); } absl::StatusOr<absl::optional<bool>> HomogenousEqualProvider::operator()( ValueManager& factory, const Value& lhs, const Value& rhs) const { return HomogenousValueEqual<HomogenousEqualProvider>(factory, lhs, rhs); } absl::StatusOr<absl::optional<bool>> HeterogeneousEqualProvider::operator()( ValueManager& factory, const Value& lhs, const Value& rhs) const { return runtime_internal::ValueEqualImpl(factory, lhs, rhs); } } namespace runtime_internal { absl::StatusOr<absl::optional<bool>> ValueEqualImpl(ValueManager& value_factory, const Value& v1, const Value& v2) { if (v1->kind() == v2->kind()) { if (InstanceOf<StructValue>(v1) && InstanceOf<StructValue>(v2)) { CEL_ASSIGN_OR_RETURN(Value result, Cast<StructValue>(v1).Equal(value_factory, v2)); if (InstanceOf<BoolValue>(result)) { return Cast<BoolValue>(result).NativeValue(); } return false; } return HomogenousValueEqual<HeterogeneousEqualProvider>(value_factory, v1, v2); } absl::optional<Number> lhs = NumberFromValue(v1); absl::optional<Number> rhs = NumberFromValue(v2); if (rhs.has_value() && lhs.has_value()) { return *lhs == *rhs; } if (InstanceOf<ErrorValue>(v1) || InstanceOf<UnknownValue>(v1) || InstanceOf<ErrorValue>(v2) || InstanceOf<UnknownValue>(v2)) { return absl::nullopt; } return false; } } absl::Status RegisterEqualityFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (options.enable_heterogeneous_equality) { CEL_RETURN_IF_ERROR(RegisterHeterogeneousEqualityFunctions(registry)); } else { CEL_RETURN_IF_ERROR(RegisterHomogenousEqualityFunctions(registry)); CEL_RETURN_IF_ERROR(RegisterNullMessageEqualityFunctions(registry)); } return absl::OkStatus(); } }
#include "runtime/standard/equality_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "internal/testing.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using testing::UnorderedElementsAre; MATCHER_P3(MatchesDescriptor, name, receiver, expected_kinds, "") { const FunctionDescriptor& descriptor = *arg; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } TEST(RegisterEqualityFunctionsHomogeneous, RegistersEqualOperators) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = false; ASSERT_OK(RegisterEqualityFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT( overloads[builtin::kEqual], UnorderedElementsAre( MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kList, Kind::kList}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kMap, Kind::kMap}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kBool, Kind::kBool}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kInt, Kind::kInt}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kUint, Kind::kUint}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kDouble, Kind::kDouble}), MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kDuration, Kind::kDuration}), MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kTimestamp, Kind::kTimestamp}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kBytes, Kind::kBytes}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kType, Kind::kType}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kStruct, Kind::kNullType}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kNullType, Kind::kStruct}), MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kNullType, Kind::kNullType}))); EXPECT_THAT( overloads[builtin::kInequal], UnorderedElementsAre( MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kList, Kind::kList}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kMap, Kind::kMap}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kBool, Kind::kBool}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kInt, Kind::kInt}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kUint, Kind::kUint}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kDouble, Kind::kDouble}), MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kDuration, Kind::kDuration}), MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kTimestamp, Kind::kTimestamp}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kBytes, Kind::kBytes}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kType, Kind::kType}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kStruct, Kind::kNullType}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kNullType, Kind::kStruct}), MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kNullType, Kind::kNullType}))); } TEST(RegisterEqualityFunctionsHeterogeneous, RegistersEqualOperators) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = true; ASSERT_OK(RegisterEqualityFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT( overloads[builtin::kEqual], UnorderedElementsAre(MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kAny, Kind::kAny}))); EXPECT_THAT(overloads[builtin::kInequal], UnorderedElementsAre(MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kAny, Kind::kAny}))); } } }
146
cpp
google/cel-cpp
logical_functions
runtime/standard/logical_functions.cc
runtime/standard/logical_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_LOGICAL_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_LOGICAL_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterLogicalFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/logical_functions.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/register_function_helper.h" namespace cel { namespace { using ::cel::runtime_internal::CreateNoMatchingOverloadError; Value NotStrictlyFalseImpl(ValueManager& value_factory, const Value& value) { if (InstanceOf<BoolValue>(value)) { return value; } if (InstanceOf<ErrorValue>(value) || InstanceOf<UnknownValue>(value)) { return value_factory.CreateBoolValue(true); } return value_factory.CreateErrorValue( CreateNoMatchingOverloadError(builtin::kNotStrictlyFalse)); } } absl::Status RegisterLogicalFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR( (RegisterHelper<UnaryFunctionAdapter<bool, bool>>::RegisterGlobalOverload( builtin::kNot, [](ValueManager&, bool value) -> bool { return !value; }, registry))); using StrictnessHelper = RegisterHelper<UnaryFunctionAdapter<Value, Value>>; CEL_RETURN_IF_ERROR(StrictnessHelper::RegisterNonStrictOverload( builtin::kNotStrictlyFalse, &NotStrictlyFalseImpl, registry)); CEL_RETURN_IF_ERROR(StrictnessHelper::RegisterNonStrictOverload( builtin::kNotStrictlyFalseDeprecated, &NotStrictlyFalseImpl, registry)); return absl::OkStatus(); } }
#include "runtime/standard/logical_functions.h" #include <functional> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "base/builtins.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "base/type_provider.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "internal/testing.h" #include "runtime/function_overload_reference.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using testing::ElementsAre; using testing::HasSubstr; using testing::Matcher; using testing::Truly; MATCHER_P3(DescriptorIs, name, arg_kinds, is_receiver, "") { const FunctionOverloadReference& ref = arg; const FunctionDescriptor& descriptor = ref.descriptor; return descriptor.name() == name && descriptor.ShapeMatches(is_receiver, arg_kinds); } MATCHER_P(IsBool, expected, "") { const Value& value = arg; return value->Is<BoolValue>() && value->As<BoolValue>().NativeValue() == expected; } absl::StatusOr<Value> TestDispatchToFunction(const FunctionRegistry& registry, absl::string_view simple_name, absl::Span<const Value> args, ValueManager& value_factory) { std::vector<Kind> arg_matcher_; arg_matcher_.reserve(args.size()); for (const auto& value : args) { arg_matcher_.push_back(ValueKindToKind(value->kind())); } std::vector<FunctionOverloadReference> refs = registry.FindStaticOverloads( simple_name, false, arg_matcher_); if (refs.size() != 1) { return absl::InvalidArgumentError("ambiguous overloads"); } Function::InvokeContext ctx(value_factory); return refs[0].implementation.Invoke(ctx, args); } TEST(RegisterLogicalFunctions, NotStrictlyFalseRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterLogicalFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kNotStrictlyFalse, false, {Kind::kAny}), ElementsAre(DescriptorIs(builtin::kNotStrictlyFalse, std::vector<Kind>{Kind::kBool}, false))); } TEST(RegisterLogicalFunctions, LogicalNotRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterLogicalFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kNot, false, {Kind::kAny}), ElementsAre( DescriptorIs(builtin::kNot, std::vector<Kind>{Kind::kBool}, false))); } struct TestCase { using ArgumentFactory = std::function<std::vector<Value>(ValueManager&)>; std::string function; ArgumentFactory arguments; absl::StatusOr<Matcher<Value>> result_matcher; }; class LogicalFunctionsTest : public testing::TestWithParam<TestCase> { public: LogicalFunctionsTest() : value_factory_(MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()) {} protected: common_internal::LegacyValueManager value_factory_; }; TEST_P(LogicalFunctionsTest, Runner) { const TestCase& test_case = GetParam(); cel::FunctionRegistry registry; ASSERT_OK(RegisterLogicalFunctions(registry, RuntimeOptions())); std::vector<Value> args = test_case.arguments(value_factory_); absl::StatusOr<Value> result = TestDispatchToFunction( registry, test_case.function, args, value_factory_); EXPECT_EQ(result.ok(), test_case.result_matcher.ok()); if (!test_case.result_matcher.ok()) { EXPECT_EQ(result.status().code(), test_case.result_matcher.status().code()); EXPECT_THAT(result.status().message(), HasSubstr(test_case.result_matcher.status().message())); } else { ASSERT_TRUE(result.ok()) << "unexpected error" << result.status(); EXPECT_THAT(*result, *test_case.result_matcher); } } INSTANTIATE_TEST_SUITE_P( Cases, LogicalFunctionsTest, testing::ValuesIn(std::vector<TestCase>{ TestCase{builtin::kNot, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(true)}; }, IsBool(false)}, TestCase{builtin::kNot, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(false)}; }, IsBool(true)}, TestCase{builtin::kNot, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(true), value_factory.CreateBoolValue(false)}; }, absl::InvalidArgumentError("")}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(true)}; }, IsBool(true)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(false)}; }, IsBool(false)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateErrorValue( absl::InternalError("test"))}; }, IsBool(true)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateUnknownValue()}; }, IsBool(true)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateIntValue(42)}; }, Truly([](const Value& v) { return v->Is<ErrorValue>() && absl::StrContains( v->As<ErrorValue>().NativeValue().message(), "No matching overloads"); })}, })); } }
147
cpp
google/cel-cpp
container_membership_functions
runtime/standard/container_membership_functions.cc
runtime/standard/container_membership_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_CONTAINER_MEMBERSHIP_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_CONTAINER_MEMBERSHIP_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterContainerMembershipFunctions( FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/container_membership_functions.h" #include <array> #include <cstddef> #include <cstdint> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_options.h" #include "runtime/standard/equality_functions.h" namespace cel { namespace { using ::cel::internal::Number; static constexpr std::array<absl::string_view, 3> in_operators = { cel::builtin::kIn, cel::builtin::kInFunction, cel::builtin::kInDeprecated, }; template <class T> bool ValueEquals(ValueView value, T other); template <> bool ValueEquals(ValueView value, bool other) { if (auto bool_value = As<BoolValueView>(value); bool_value) { return bool_value->NativeValue() == other; } return false; } template <> bool ValueEquals(ValueView value, int64_t other) { if (auto int_value = As<IntValueView>(value); int_value) { return int_value->NativeValue() == other; } return false; } template <> bool ValueEquals(ValueView value, uint64_t other) { if (auto uint_value = As<UintValueView>(value); uint_value) { return uint_value->NativeValue() == other; } return false; } template <> bool ValueEquals(ValueView value, double other) { if (auto double_value = As<DoubleValueView>(value); double_value) { return double_value->NativeValue() == other; } return false; } template <> bool ValueEquals(ValueView value, const StringValue& other) { if (auto string_value = As<StringValueView>(value); string_value) { return string_value->Equals(other); } return false; } template <> bool ValueEquals(ValueView value, const BytesValue& other) { if (auto bytes_value = As<BytesValueView>(value); bytes_value) { return bytes_value->Equals(other); } return false; } template <typename T> absl::StatusOr<bool> In(ValueManager& value_factory, T value, const ListValue& list) { CEL_ASSIGN_OR_RETURN(auto size, list.Size()); Value element; for (int i = 0; i < size; i++) { CEL_RETURN_IF_ERROR(list.Get(value_factory, i, element)); if (ValueEquals<T>(element, value)) { return true; } } return false; } absl::StatusOr<Value> HeterogeneousEqualityIn(ValueManager& value_factory, const Value& value, const ListValue& list) { return list.Contains(value_factory, value); } absl::Status RegisterListMembershipFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { for (absl::string_view op : in_operators) { if (options.enable_heterogeneous_equality) { CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const Value&, const ListValue&>>:: RegisterGlobalOverload(op, &HeterogeneousEqualityIn, registry))); } else { CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, bool, const ListValue&>>:: RegisterGlobalOverload(op, In<bool>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, int64_t, const ListValue&>>:: RegisterGlobalOverload(op, In<int64_t>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, uint64_t, const ListValue&>>:: RegisterGlobalOverload(op, In<uint64_t>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, double, const ListValue&>>:: RegisterGlobalOverload(op, In<double>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<bool>, const StringValue&, const ListValue&>>:: RegisterGlobalOverload(op, In<const StringValue&>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<bool>, const BytesValue&, const ListValue&>>:: RegisterGlobalOverload(op, In<const BytesValue&>, registry))); } } return absl::OkStatus(); } absl::Status RegisterMapMembershipFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { const bool enable_heterogeneous_equality = options.enable_heterogeneous_equality; auto boolKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, bool key, const MapValue& map_value) -> absl::StatusOr<Value> { auto result = map_value.Has(factory, factory.CreateBoolValue(key)); if (result.ok()) { return std::move(*result); } if (enable_heterogeneous_equality) { return factory.CreateBoolValue(false); } return factory.CreateErrorValue(result.status()); }; auto intKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, int64_t key, const MapValue& map_value) -> absl::StatusOr<Value> { Value int_key = factory.CreateIntValue(key); auto result = map_value.Has(factory, int_key); if (enable_heterogeneous_equality) { if (result.ok() && (*result)->Is<BoolValue>() && (*result)->As<BoolValue>().NativeValue()) { return std::move(*result); } Number number = Number::FromInt64(key); if (number.LosslessConvertibleToUint()) { const auto& result = map_value.Has(factory, factory.CreateUintValue(number.AsUint())); if (result.ok() && (*result)->Is<BoolValue>() && (*result)->As<BoolValue>().NativeValue()) { return std::move(*result); } } return factory.CreateBoolValue(false); } if (!result.ok()) { return factory.CreateErrorValue(result.status()); } return std::move(*result); }; auto stringKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, const StringValue& key, const MapValue& map_value) -> absl::StatusOr<Value> { auto result = map_value.Has(factory, key); if (result.ok()) { return std::move(*result); } if (enable_heterogeneous_equality) { return factory.CreateBoolValue(false); } return factory.CreateErrorValue(result.status()); }; auto uintKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, uint64_t key, const MapValue& map_value) -> absl::StatusOr<Value> { Value uint_key = factory.CreateUintValue(key); const auto& result = map_value.Has(factory, uint_key); if (enable_heterogeneous_equality) { if (result.ok() && (*result)->Is<BoolValue>() && (*result)->As<BoolValue>().NativeValue()) { return std::move(*result); } Number number = Number::FromUint64(key); if (number.LosslessConvertibleToInt()) { const auto& result = map_value.Has(factory, factory.CreateIntValue(number.AsInt())); if (result.ok() && (*result)->Is<BoolValue>() && (*result)->As<BoolValue>().NativeValue()) { return std::move(*result); } } return factory.CreateBoolValue(false); } if (!result.ok()) { return factory.CreateErrorValue(result.status()); } return std::move(*result); }; auto doubleKeyInSet = [](ValueManager& factory, double key, const MapValue& map_value) -> absl::StatusOr<Value> { Number number = Number::FromDouble(key); if (number.LosslessConvertibleToInt()) { const auto& result = map_value.Has(factory, factory.CreateIntValue(number.AsInt())); if (result.ok() && (*result)->Is<BoolValue>() && (*result)->As<BoolValue>().NativeValue()) { return std::move(*result); } } if (number.LosslessConvertibleToUint()) { const auto& result = map_value.Has(factory, factory.CreateUintValue(number.AsUint())); if (result.ok() && (*result)->Is<BoolValue>() && (*result)->As<BoolValue>().NativeValue()) { return std::move(*result); } } return factory.CreateBoolValue(false); }; for (auto op : in_operators) { auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const MapValue&>>::RegisterGlobalOverload(op, stringKeyInSet, registry); if (!status.ok()) return status; status = RegisterHelper< BinaryFunctionAdapter<absl::StatusOr<Value>, bool, const MapValue&>>:: RegisterGlobalOverload(op, boolKeyInSet, registry); if (!status.ok()) return status; status = RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<Value>, int64_t, const MapValue&>>:: RegisterGlobalOverload(op, intKeyInSet, registry); if (!status.ok()) return status; status = RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<Value>, uint64_t, const MapValue&>>:: RegisterGlobalOverload(op, uintKeyInSet, registry); if (!status.ok()) return status; if (enable_heterogeneous_equality) { status = RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<Value>, double, const MapValue&>>:: RegisterGlobalOverload(op, doubleKeyInSet, registry); if (!status.ok()) return status; } } return absl::OkStatus(); } } absl::Status RegisterContainerMembershipFunctions( FunctionRegistry& registry, const RuntimeOptions& options) { if (options.enable_list_contains) { CEL_RETURN_IF_ERROR(RegisterListMembershipFunctions(registry, options)); } return RegisterMapMembershipFunctions(registry, options); } }
#include "runtime/standard/container_membership_functions.h" #include <array> #include <vector> #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "internal/testing.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using testing::UnorderedElementsAre; MATCHER_P3(MatchesDescriptor, name, receiver, expected_kinds, "") { const FunctionDescriptor& descriptor = *arg; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } static constexpr std::array<absl::string_view, 3> kInOperators = { builtin::kIn, builtin::kInDeprecated, builtin::kInFunction}; TEST(RegisterContainerMembershipFunctions, RegistersHomogeneousInOperator) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = false; ASSERT_OK(RegisterContainerMembershipFunctions(registry, options)); auto overloads = registry.ListFunctions(); for (absl::string_view operator_name : kInOperators) { EXPECT_THAT( overloads[operator_name], UnorderedElementsAre( MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kDouble, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBytes, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kMap}))); } } TEST(RegisterContainerMembershipFunctions, RegistersHeterogeneousInOperation) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = true; ASSERT_OK(RegisterContainerMembershipFunctions(registry, options)); auto overloads = registry.ListFunctions(); for (absl::string_view operator_name : kInOperators) { EXPECT_THAT( overloads[operator_name], UnorderedElementsAre( MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kAny, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kDouble, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kMap}))); } } TEST(RegisterContainerMembershipFunctions, RegistersInOperatorListsDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_list_contains = false; ASSERT_OK(RegisterContainerMembershipFunctions(registry, options)); auto overloads = registry.ListFunctions(); for (absl::string_view operator_name : kInOperators) { EXPECT_THAT( overloads[operator_name], UnorderedElementsAre( MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kDouble, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kMap}))); } } } }
148
cpp
google/cel-cpp
type_conversion_functions
runtime/standard/type_conversion_functions.cc
runtime/standard/type_conversion_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_TYPE_CONVERSION_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_TYPE_CONVERSION_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterTypeConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/type_conversion_functions.h" #include <cstdint> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/overflow.h" #include "internal/status_macros.h" #include "internal/time.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::cel::internal::EncodeDurationToJson; using ::cel::internal::EncodeTimestampToJson; using ::cel::internal::MaxTimestamp; const absl::Time kMaxTime = MaxTimestamp(); absl::Status RegisterIntConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<int64_t, bool>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager&, bool v) { return static_cast<int64_t>(v); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, double>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager& value_factory, double v) -> Value { auto conv = cel::internal::CheckedDoubleToInt64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateIntValue(*conv); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<int64_t, int64_t>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager&, int64_t v) { return v; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager& value_factory, const StringValue& s) -> Value { int64_t result; if (!absl::SimpleAtoi(s.ToString(), &result)) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("cannot convert string to int")); } return value_factory.CreateIntValue(result); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<int64_t, absl::Time>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager&, absl::Time t) { return absl::ToUnixSeconds(t); }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<Value, uint64_t>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager& value_factory, uint64_t v) -> Value { auto conv = cel::internal::CheckedUint64ToInt64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateIntValue(*conv); }, registry); } absl::Status RegisterStringConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (!options.enable_string_conversion) { return absl::OkStatus(); } absl::Status status = UnaryFunctionAdapter<Value, const BytesValue&>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, const BytesValue& value) -> Value { auto handle_or = value_factory.CreateStringValue(value.ToString()); if (!handle_or.ok()) { return value_factory.CreateErrorValue(handle_or.status()); } return *handle_or; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, double>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, double value) -> StringValue { return value_factory.CreateUncheckedStringValue(absl::StrCat(value)); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, int64_t>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, int64_t value) -> StringValue { return value_factory.CreateUncheckedStringValue(absl::StrCat(value)); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, StringValue>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager&, StringValue value) -> StringValue { return value; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, uint64_t>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, uint64_t value) -> StringValue { return value_factory.CreateUncheckedStringValue(absl::StrCat(value)); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, absl::Duration>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, absl::Duration value) -> Value { auto encode = EncodeDurationToJson(value); if (!encode.ok()) { return value_factory.CreateErrorValue(encode.status()); } return value_factory.CreateUncheckedStringValue(*encode); }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<Value, absl::Time>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, absl::Time value) -> Value { auto encode = EncodeTimestampToJson(value); if (!encode.ok()) { return value_factory.CreateErrorValue(encode.status()); } return value_factory.CreateUncheckedStringValue(*encode); }, registry); } absl::Status RegisterUintConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<Value, double>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager& value_factory, double v) -> Value { auto conv = cel::internal::CheckedDoubleToUint64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateUintValue(*conv); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, int64_t>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager& value_factory, int64_t v) -> Value { auto conv = cel::internal::CheckedInt64ToUint64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateUintValue(*conv); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager& value_factory, const StringValue& s) -> Value { uint64_t result; if (!absl::SimpleAtoi(s.ToString(), &result)) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("doesn't convert to a string")); } return value_factory.CreateUintValue(result); }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<uint64_t, uint64_t>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager&, uint64_t v) { return v; }, registry); } absl::Status RegisterBytesConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<BytesValue, BytesValue>::RegisterGlobalOverload( cel::builtin::kBytes, [](ValueManager&, BytesValue value) -> BytesValue { return value; }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<absl::StatusOr<BytesValue>, const StringValue&>:: RegisterGlobalOverload( cel::builtin::kBytes, [](ValueManager& value_factory, const StringValue& value) { return value_factory.CreateBytesValue(value.ToString()); }, registry); } absl::Status RegisterDoubleConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<double, double>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager&, double v) { return v; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<double, int64_t>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager&, int64_t v) { return static_cast<double>(v); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager& value_factory, const StringValue& s) -> Value { double result; if (absl::SimpleAtod(s.ToString(), &result)) { return value_factory.CreateDoubleValue(result); } else { return value_factory.CreateErrorValue(absl::InvalidArgumentError( "cannot convert string to double")); } }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<double, uint64_t>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager&, uint64_t v) { return static_cast<double>(v); }, registry); } Value CreateDurationFromString(ValueManager& value_factory, const StringValue& dur_str) { absl::Duration d; if (!absl::ParseDuration(dur_str.ToString(), &d)) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("String to Duration conversion failed")); } auto duration = value_factory.CreateDurationValue(d); if (!duration.ok()) { return value_factory.CreateErrorValue(duration.status()); } return *duration; } absl::Status RegisterTimeConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { absl::Status status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kDuration, CreateDurationFromString, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, int64_t>::RegisterGlobalOverload( cel::builtin::kTimestamp, [](ValueManager& value_factory, int64_t epoch_seconds) -> Value { return value_factory.CreateUncheckedTimestampValue( absl::FromUnixSeconds(epoch_seconds)); }, registry); CEL_RETURN_IF_ERROR(status); bool enable_timestamp_duration_overflow_errors = options.enable_timestamp_duration_overflow_errors; return UnaryFunctionAdapter<Value, const StringValue&>:: RegisterGlobalOverload( cel::builtin::kTimestamp, [=](ValueManager& value_factory, const StringValue& time_str) -> Value { absl::Time ts; if (!absl::ParseTime(absl::RFC3339_full, time_str.ToString(), &ts, nullptr)) { return value_factory.CreateErrorValue(absl::InvalidArgumentError( "String to Timestamp conversion failed")); } if (enable_timestamp_duration_overflow_errors) { if (ts < absl::UniversalEpoch() || ts > kMaxTime) { return value_factory.CreateErrorValue( absl::OutOfRangeError("timestamp overflow")); } } return value_factory.CreateUncheckedTimestampValue(ts); }, registry); } } absl::Status RegisterTypeConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterBytesConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterDoubleConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterIntConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterStringConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterUintConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterTimeConversionFunctions(registry, options)); absl::Status status = UnaryFunctionAdapter<Value, const Value&>::RegisterGlobalOverload( cel::builtin::kDyn, [](ValueManager&, const Value& value) -> Value { return value; }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<Value, const Value&>::RegisterGlobalOverload( cel::builtin::kType, [](ValueManager& factory, const Value& value) { return factory.CreateTypeValue(value.GetType(factory)); }, registry); } }
#include "runtime/standard/type_conversion_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using testing::IsEmpty; using testing::UnorderedElementsAre; MATCHER_P3(MatchesUnaryDescriptor, name, receiver, expected_kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{expected_kind}; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } TEST(RegisterTypeConversionFunctions, RegisterIntConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kInt, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kInt, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kBool), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kString), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kTimestamp))); } TEST(RegisterTypeConversionFunctions, RegisterUintConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kUint, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kUint, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kUint, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kUint, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kUint, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterDoubleConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kDouble, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterStringConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; options.enable_string_conversion = true; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kString, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kString, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kString, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kString, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kString, false, Kind::kString), MatchesUnaryDescriptor(builtin::kString, false, Kind::kBytes), MatchesUnaryDescriptor(builtin::kString, false, Kind::kDuration), MatchesUnaryDescriptor(builtin::kString, false, Kind::kTimestamp))); } TEST(RegisterTypeConversionFunctions, RegisterStringConversionFunctionsDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_string_conversion = false; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kString, false, {Kind::kAny}), IsEmpty()); } TEST(RegisterTypeConversionFunctions, RegisterBytesConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kBytes, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kBytes, false, Kind::kBytes), MatchesUnaryDescriptor(builtin::kBytes, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterTimeConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kTimestamp, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kTimestamp, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kTimestamp, false, Kind::kString))); EXPECT_THAT( registry.FindStaticOverloads(builtin::kDuration, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kDuration, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterMetaTypeConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kDyn, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kDyn, false, Kind::kAny))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kType, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kType, false, Kind::kAny))); } } }
149
cpp
google/cel-cpp
string_functions
runtime/standard/string_functions.cc
runtime/standard/string_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_STRING_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_STRING_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterStringFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/string_functions.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" namespace cel { namespace { absl::StatusOr<StringValue> ConcatString(ValueManager& factory, const StringValue& value1, const StringValue& value2) { return factory.CreateUncheckedStringValue( absl::StrCat(value1.ToString(), value2.ToString())); } absl::StatusOr<BytesValue> ConcatBytes(ValueManager& factory, const BytesValue& value1, const BytesValue& value2) { return factory.CreateBytesValue( absl::StrCat(value1.ToString(), value2.ToString())); } bool StringContains(ValueManager&, const StringValue& value, const StringValue& substr) { return absl::StrContains(value.ToString(), substr.ToString()); } bool StringEndsWith(ValueManager&, const StringValue& value, const StringValue& suffix) { return absl::EndsWith(value.ToString(), suffix.ToString()); } bool StringStartsWith(ValueManager&, const StringValue& value, const StringValue& prefix) { return absl::StartsWith(value.ToString(), prefix.ToString()); } absl::Status RegisterSizeFunctions(FunctionRegistry& registry) { auto size_func = [](ValueManager& value_factory, const StringValue& value) -> int64_t { return value.Size(); }; using StrSizeFnAdapter = UnaryFunctionAdapter<int64_t, const StringValue&>; CEL_RETURN_IF_ERROR(StrSizeFnAdapter::RegisterGlobalOverload( cel::builtin::kSize, size_func, registry)); CEL_RETURN_IF_ERROR(StrSizeFnAdapter::RegisterMemberOverload( cel::builtin::kSize, size_func, registry)); auto bytes_size_func = [](ValueManager&, const BytesValue& value) -> int64_t { return value.Size(); }; using BytesSizeFnAdapter = UnaryFunctionAdapter<int64_t, const BytesValue&>; CEL_RETURN_IF_ERROR(BytesSizeFnAdapter::RegisterGlobalOverload( cel::builtin::kSize, bytes_size_func, registry)); return BytesSizeFnAdapter::RegisterMemberOverload(cel::builtin::kSize, bytes_size_func, registry); } absl::Status RegisterConcatFunctions(FunctionRegistry& registry) { using StrCatFnAdapter = BinaryFunctionAdapter<absl::StatusOr<StringValue>, const StringValue&, const StringValue&>; CEL_RETURN_IF_ERROR(StrCatFnAdapter::RegisterGlobalOverload( cel::builtin::kAdd, &ConcatString, registry)); using BytesCatFnAdapter = BinaryFunctionAdapter<absl::StatusOr<BytesValue>, const BytesValue&, const BytesValue&>; return BytesCatFnAdapter::RegisterGlobalOverload(cel::builtin::kAdd, &ConcatBytes, registry); } } absl::Status RegisterStringFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { for (bool receiver_style : {true, false}) { auto status = BinaryFunctionAdapter<bool, const StringValue&, const StringValue&>:: Register(cel::builtin::kStringContains, receiver_style, StringContains, registry); CEL_RETURN_IF_ERROR(status); status = BinaryFunctionAdapter<bool, const StringValue&, const StringValue&>:: Register(cel::builtin::kStringEndsWith, receiver_style, StringEndsWith, registry); CEL_RETURN_IF_ERROR(status); status = BinaryFunctionAdapter<bool, const StringValue&, const StringValue&>:: Register(cel::builtin::kStringStartsWith, receiver_style, StringStartsWith, registry); CEL_RETURN_IF_ERROR(status); } if (options.enable_string_concat) { CEL_RETURN_IF_ERROR(RegisterConcatFunctions(registry)); } return RegisterSizeFunctions(registry); } }
#include "runtime/standard/string_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using testing::IsEmpty; using testing::UnorderedElementsAre; enum class CallStyle { kFree, kReceiver }; MATCHER_P3(MatchesDescriptor, name, call_style, expected_kinds, "") { bool receiver_style; switch (call_style) { case CallStyle::kFree: receiver_style = false; break; case CallStyle::kReceiver: receiver_style = true; break; } const FunctionDescriptor& descriptor = *arg; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver_style && descriptor.types() == types; } TEST(RegisterStringFunctions, FunctionsRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterStringFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT( overloads[builtin::kAdd], UnorderedElementsAre( MatchesDescriptor(builtin::kAdd, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kAdd, CallStyle::kFree, std::vector<Kind>{Kind::kBytes, Kind::kBytes}))); EXPECT_THAT(overloads[builtin::kSize], UnorderedElementsAre( MatchesDescriptor(builtin::kSize, CallStyle::kFree, std::vector<Kind>{Kind::kString}), MatchesDescriptor(builtin::kSize, CallStyle::kFree, std::vector<Kind>{Kind::kBytes}), MatchesDescriptor(builtin::kSize, CallStyle::kReceiver, std::vector<Kind>{Kind::kString}), MatchesDescriptor(builtin::kSize, CallStyle::kReceiver, std::vector<Kind>{Kind::kBytes}))); EXPECT_THAT( overloads[builtin::kStringContains], UnorderedElementsAre( MatchesDescriptor(builtin::kStringContains, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kStringContains, CallStyle::kReceiver, std::vector<Kind>{Kind::kString, Kind::kString}))); EXPECT_THAT( overloads[builtin::kStringStartsWith], UnorderedElementsAre( MatchesDescriptor(builtin::kStringStartsWith, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kStringStartsWith, CallStyle::kReceiver, std::vector<Kind>{Kind::kString, Kind::kString}))); EXPECT_THAT( overloads[builtin::kStringEndsWith], UnorderedElementsAre( MatchesDescriptor(builtin::kStringEndsWith, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kStringEndsWith, CallStyle::kReceiver, std::vector<Kind>{Kind::kString, Kind::kString}))); } TEST(RegisterStringFunctions, ConcatSkippedWhenDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_string_concat = false; ASSERT_OK(RegisterStringFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT(overloads[builtin::kAdd], IsEmpty()); } } }
150
cpp
google/cel-cpp
container_functions
runtime/standard/container_functions.cc
runtime/standard/container_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_CONTAINER_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_CONTAINER_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterContainerFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/container_functions.h" #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/mutable_list_impl.h" #include "runtime/runtime_options.h" namespace cel { namespace { using cel::runtime_internal::MutableListValue; absl::StatusOr<int64_t> MapSizeImpl(ValueManager&, const MapValue& value) { return value.Size(); } absl::StatusOr<int64_t> ListSizeImpl(ValueManager&, const ListValue& value) { return value.Size(); } absl::StatusOr<ListValue> ConcatList(ValueManager& factory, const ListValue& value1, const ListValue& value2) { CEL_ASSIGN_OR_RETURN(auto size1, value1.Size()); if (size1 == 0) { return value2; } CEL_ASSIGN_OR_RETURN(auto size2, value2.Size()); if (size2 == 0) { return value1; } CEL_ASSIGN_OR_RETURN(auto list_builder, factory.NewListValueBuilder(factory.GetDynListType())); list_builder->Reserve(size1 + size2); for (int i = 0; i < size1; i++) { CEL_ASSIGN_OR_RETURN(Value elem, value1.Get(factory, i)); CEL_RETURN_IF_ERROR(list_builder->Add(std::move(elem))); } for (int i = 0; i < size2; i++) { CEL_ASSIGN_OR_RETURN(Value elem, value2.Get(factory, i)); CEL_RETURN_IF_ERROR(list_builder->Add(std::move(elem))); } return std::move(*list_builder).Build(); } absl::StatusOr<OpaqueValue> AppendList(ValueManager& factory, OpaqueValue value1, const ListValue& value2) { if (!MutableListValue::Is(value1)) { return absl::InvalidArgumentError( "Unexpected call to runtime list append."); } MutableListValue& mutable_list = MutableListValue::Cast(value1); CEL_ASSIGN_OR_RETURN(auto size2, value2.Size()); for (int i = 0; i < size2; i++) { CEL_ASSIGN_OR_RETURN(Value elem, value2.Get(factory, i)); CEL_RETURN_IF_ERROR(mutable_list.Append(std::move(elem))); } return value1; } } absl::Status RegisterContainerFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { for (bool receiver_style : {true, false}) { CEL_RETURN_IF_ERROR(registry.Register( cel::UnaryFunctionAdapter<absl::StatusOr<int64_t>, const ListValue&>:: CreateDescriptor(cel::builtin::kSize, receiver_style), UnaryFunctionAdapter<absl::StatusOr<int64_t>, const ListValue&>::WrapFunction(ListSizeImpl))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<int64_t>, const MapValue&>:: CreateDescriptor(cel::builtin::kSize, receiver_style), UnaryFunctionAdapter<absl::StatusOr<int64_t>, const MapValue&>::WrapFunction(MapSizeImpl))); } if (options.enable_list_concat) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, const ListValue&, const ListValue&>::CreateDescriptor(cel::builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, const ListValue&, const ListValue&>::WrapFunction(ConcatList))); } return registry.Register( BinaryFunctionAdapter< absl::StatusOr<OpaqueValue>, OpaqueValue, const ListValue&>::CreateDescriptor(cel::builtin::kRuntimeListAppend, false), BinaryFunctionAdapter<absl::StatusOr<OpaqueValue>, OpaqueValue, const ListValue&>::WrapFunction(AppendList)); } }
#include "runtime/standard/container_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using testing::IsEmpty; using testing::UnorderedElementsAre; MATCHER_P3(MatchesDescriptor, name, receiver, expected_kinds, "") { const FunctionDescriptor& descriptor = arg.descriptor; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } TEST(RegisterContainerFunctions, RegistersSizeFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kSize, false, {Kind::kAny}), UnorderedElementsAre(MatchesDescriptor(builtin::kSize, false, std::vector<Kind>{Kind::kList}), MatchesDescriptor(builtin::kSize, false, std::vector<Kind>{Kind::kMap}))); EXPECT_THAT( registry.FindStaticOverloads(builtin::kSize, true, {Kind::kAny}), UnorderedElementsAre(MatchesDescriptor(builtin::kSize, true, std::vector<Kind>{Kind::kList}), MatchesDescriptor(builtin::kSize, true, std::vector<Kind>{Kind::kMap}))); } TEST(RegisterContainerFunctions, RegisterListConcatEnabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_list_concat = true; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kAdd, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre(MatchesDescriptor( builtin::kAdd, false, std::vector<Kind>{Kind::kList, Kind::kList}))); } TEST(RegisterContainerFunctions, RegisterListConcateDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_list_concat = false; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kAdd, false, {Kind::kAny, Kind::kAny}), IsEmpty()); } TEST(RegisterContainerFunctions, RegisterRuntimeListAppend) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kRuntimeListAppend, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre(MatchesDescriptor( builtin::kRuntimeListAppend, false, std::vector<Kind>{Kind::kOpaque, Kind::kList}))); } } }
151
cpp
google/cel-cpp
arithmetic_functions
runtime/standard/arithmetic_functions.cc
runtime/standard/arithmetic_functions_test.cc
#ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_ARITHMETIC_FUNCTIONS_H_ #define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_ARITHMETIC_FUNCTIONS_H_ #include "absl/status/status.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { absl::Status RegisterArithmeticFunctions(FunctionRegistry& registry, const RuntimeOptions& options); } #endif #include "runtime/standard/arithmetic_functions.h" #include <limits> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/overflow.h" #include "internal/status_macros.h" namespace cel { namespace { template <class Type> Value Add(ValueManager&, Type v0, Type v1); template <> Value Add<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto sum = cel::internal::CheckedAdd(v0, v1); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateIntValue(*sum); } template <> Value Add<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto sum = cel::internal::CheckedAdd(v0, v1); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateUintValue(*sum); } template <> Value Add<double>(ValueManager& value_factory, double v0, double v1) { return value_factory.CreateDoubleValue(v0 + v1); } template <class Type> Value Sub(ValueManager&, Type v0, Type v1); template <> Value Sub<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto diff = cel::internal::CheckedSub(v0, v1); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateIntValue(*diff); } template <> Value Sub<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto diff = cel::internal::CheckedSub(v0, v1); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateUintValue(*diff); } template <> Value Sub<double>(ValueManager& value_factory, double v0, double v1) { return value_factory.CreateDoubleValue(v0 - v1); } template <class Type> Value Mul(ValueManager&, Type v0, Type v1); template <> Value Mul<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto prod = cel::internal::CheckedMul(v0, v1); if (!prod.ok()) { return value_factory.CreateErrorValue(prod.status()); } return value_factory.CreateIntValue(*prod); } template <> Value Mul<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto prod = cel::internal::CheckedMul(v0, v1); if (!prod.ok()) { return value_factory.CreateErrorValue(prod.status()); } return value_factory.CreateUintValue(*prod); } template <> Value Mul<double>(ValueManager& value_factory, double v0, double v1) { return value_factory.CreateDoubleValue(v0 * v1); } template <class Type> Value Div(ValueManager&, Type v0, Type v1); template <> Value Div<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto quot = cel::internal::CheckedDiv(v0, v1); if (!quot.ok()) { return value_factory.CreateErrorValue(quot.status()); } return value_factory.CreateIntValue(*quot); } template <> Value Div<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto quot = cel::internal::CheckedDiv(v0, v1); if (!quot.ok()) { return value_factory.CreateErrorValue(quot.status()); } return value_factory.CreateUintValue(*quot); } template <> Value Div<double>(ValueManager& value_factory, double v0, double v1) { static_assert(std::numeric_limits<double>::is_iec559, "Division by zero for doubles must be supported"); return value_factory.CreateDoubleValue(v0 / v1); } template <class Type> Value Modulo(ValueManager& value_factory, Type v0, Type v1); template <> Value Modulo<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto mod = cel::internal::CheckedMod(v0, v1); if (!mod.ok()) { return value_factory.CreateErrorValue(mod.status()); } return value_factory.CreateIntValue(*mod); } template <> Value Modulo<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto mod = cel::internal::CheckedMod(v0, v1); if (!mod.ok()) { return value_factory.CreateErrorValue(mod.status()); } return value_factory.CreateUintValue(*mod); } template <class Type> absl::Status RegisterArithmeticFunctionsForType(FunctionRegistry& registry) { using FunctionAdapter = cel::BinaryFunctionAdapter<Value, Type, Type>; CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kAdd, false), FunctionAdapter::WrapFunction(&Add<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kSubtract, false), FunctionAdapter::WrapFunction(&Sub<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kMultiply, false), FunctionAdapter::WrapFunction(&Mul<Type>))); return registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kDivide, false), FunctionAdapter::WrapFunction(&Div<Type>)); } } absl::Status RegisterArithmeticFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterArithmeticFunctionsForType<int64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterArithmeticFunctionsForType<uint64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterArithmeticFunctionsForType<double>(registry)); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, int64_t, int64_t>::CreateDescriptor( cel::builtin::kModulo, false), BinaryFunctionAdapter<Value, int64_t, int64_t>::WrapFunction( &Modulo<int64_t>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, uint64_t, uint64_t>::CreateDescriptor( cel::builtin::kModulo, false), BinaryFunctionAdapter<Value, uint64_t, uint64_t>::WrapFunction( &Modulo<uint64_t>))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, int64_t>::CreateDescriptor(cel::builtin::kNeg, false), UnaryFunctionAdapter<Value, int64_t>::WrapFunction( [](ValueManager& value_factory, int64_t value) -> Value { auto inv = cel::internal::CheckedNegation(value); if (!inv.ok()) { return value_factory.CreateErrorValue(inv.status()); } return value_factory.CreateIntValue(*inv); }))); return registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor(cel::builtin::kNeg, false), UnaryFunctionAdapter<double, double>::WrapFunction( [](ValueManager&, double value) -> double { return -value; })); } }
#include "runtime/standard/arithmetic_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using testing::UnorderedElementsAre; MATCHER_P2(MatchesOperatorDescriptor, name, expected_kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{expected_kind, expected_kind}; return descriptor.name() == name && descriptor.receiver_style() == false && descriptor.types() == types; } MATCHER_P(MatchesNegationDescriptor, expected_kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{expected_kind}; return descriptor.name() == builtin::kNeg && descriptor.receiver_style() == false && descriptor.types() == types; } TEST(RegisterArithmeticFunctions, Registered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterArithmeticFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kAdd, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kAdd, Kind::kInt), MatchesOperatorDescriptor(builtin::kAdd, Kind::kDouble), MatchesOperatorDescriptor(builtin::kAdd, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kSubtract, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kSubtract, Kind::kInt), MatchesOperatorDescriptor(builtin::kSubtract, Kind::kDouble), MatchesOperatorDescriptor(builtin::kSubtract, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kDivide, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kDivide, Kind::kInt), MatchesOperatorDescriptor(builtin::kDivide, Kind::kDouble), MatchesOperatorDescriptor(builtin::kDivide, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kMultiply, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kMultiply, Kind::kInt), MatchesOperatorDescriptor(builtin::kMultiply, Kind::kDouble), MatchesOperatorDescriptor(builtin::kMultiply, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kModulo, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kModulo, Kind::kInt), MatchesOperatorDescriptor(builtin::kModulo, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kNeg, false, {Kind::kAny}), UnorderedElementsAre(MatchesNegationDescriptor(Kind::kInt), MatchesNegationDescriptor(Kind::kDouble))); } } }
152
cpp
google/glog
logging
src/logging.cc
src/logging_unittest.cc
#ifndef GLOG_LOGGING_H #define GLOG_LOGGING_H #include <atomic> #include <cerrno> #include <chrono> #include <cstddef> #include <cstdlib> #include <cstring> #include <ctime> #include <iosfwd> #include <memory> #include <ostream> #include <sstream> #include <string> #include <thread> #include <utility> #include <vector> #if defined(GLOG_USE_GLOG_EXPORT) # include "glog/export.h" #endif #if !defined(GLOG_EXPORT) || !defined(GLOG_NO_EXPORT) # error <glog/logging.h> was not included correctly. See the documentation for how to consume the library. #endif #include "glog/flags.h" #include "glog/platform.h" #include "glog/types.h" #if defined(__has_attribute) # if __has_attribute(used) # define GLOG_USED __attribute__((used)) # endif #endif #if !defined(GLOG_USED) # define GLOG_USED #endif #include "glog/log_severity.h" #include "glog/vlog_is_on.h" namespace google { struct GLOG_EXPORT LogMessageTime { LogMessageTime(); explicit LogMessageTime(std::chrono::system_clock::time_point now); const std::chrono::system_clock::time_point& when() const noexcept { return timestamp_; } int sec() const noexcept { return tm_.tm_sec; } long usec() const noexcept { return usecs_.count(); } int(min)() const noexcept { return tm_.tm_min; } int hour() const noexcept { return tm_.tm_hour; } int day() const noexcept { return tm_.tm_mday; } int month() const noexcept { return tm_.tm_mon; } int year() const noexcept { return tm_.tm_year; } int dayOfWeek() const noexcept { return tm_.tm_wday; } int dayInYear() const noexcept { return tm_.tm_yday; } int dst() const noexcept { return tm_.tm_isdst; } std::chrono::seconds gmtoffset() const noexcept { return gmtoffset_; } const std::tm& tm() const noexcept { return tm_; } private: std::tm tm_{}; std::chrono::system_clock::time_point timestamp_; std::chrono::microseconds usecs_; std::chrono::seconds gmtoffset_; }; } #ifndef GOOGLE_STRIP_LOG # define GOOGLE_STRIP_LOG 0 #endif #if defined(__has_builtin) # if __has_builtin(__builtin_expect) # define GLOG_BUILTIN_EXPECT_PRESENT # endif #endif #if !defined(GLOG_BUILTIN_EXPECT_PRESENT) && defined(__GNUG__) # define GLOG_BUILTIN_EXPECT_PRESENT #endif #if defined(GLOG_BUILTIN_EXPECT_PRESENT) # ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN # define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0)) # endif # ifndef GOOGLE_PREDICT_FALSE # define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) # endif # ifndef GOOGLE_PREDICT_TRUE # define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) # endif #else # ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN # define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x # endif # ifndef GOOGLE_PREDICT_TRUE # define GOOGLE_PREDICT_FALSE(x) x # endif # ifndef GOOGLE_PREDICT_TRUE # define GOOGLE_PREDICT_TRUE(x) x # endif #endif #undef GLOG_BUILTIN_EXPECT_PRESENT #if GOOGLE_STRIP_LOG == 0 # define COMPACT_GOOGLE_LOG_INFO google::LogMessage(__FILE__, __LINE__) # define LOG_TO_STRING_INFO(message) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, message) #else # define COMPACT_GOOGLE_LOG_INFO google::NullStream() # define LOG_TO_STRING_INFO(message) google::NullStream() #endif #if GOOGLE_STRIP_LOG <= 1 # define COMPACT_GOOGLE_LOG_WARNING \ google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING) # define LOG_TO_STRING_WARNING(message) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, message) #else # define COMPACT_GOOGLE_LOG_WARNING google::NullStream() # define LOG_TO_STRING_WARNING(message) google::NullStream() #endif #if GOOGLE_STRIP_LOG <= 2 # define COMPACT_GOOGLE_LOG_ERROR \ google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR) # define LOG_TO_STRING_ERROR(message) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, message) #else # define COMPACT_GOOGLE_LOG_ERROR google::NullStream() # define LOG_TO_STRING_ERROR(message) google::NullStream() #endif #if GOOGLE_STRIP_LOG <= 3 # define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal(__FILE__, __LINE__) # define LOG_TO_STRING_FATAL(message) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, message) #else # define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal() # define LOG_TO_STRING_FATAL(message) google::NullStreamFatal() #endif #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) # define DCHECK_IS_ON() 0 #else # define DCHECK_IS_ON() 1 #endif #if !DCHECK_IS_ON() # define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR #elif GOOGLE_STRIP_LOG <= 3 # define COMPACT_GOOGLE_LOG_DFATAL \ google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL) #else # define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal() #endif #define GOOGLE_LOG_INFO(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, \ &google::LogMessage::SendToLog) #define SYSLOG_INFO(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, \ &google::LogMessage::SendToSyslogAndLog) #define GOOGLE_LOG_WARNING(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \ &google::LogMessage::SendToLog) #define SYSLOG_WARNING(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \ &google::LogMessage::SendToSyslogAndLog) #define GOOGLE_LOG_ERROR(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \ &google::LogMessage::SendToLog) #define SYSLOG_ERROR(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \ &google::LogMessage::SendToSyslogAndLog) #define GOOGLE_LOG_FATAL(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \ &google::LogMessage::SendToLog) #define SYSLOG_FATAL(counter) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \ &google::LogMessage::SendToSyslogAndLog) #define GOOGLE_LOG_DFATAL(counter) \ google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \ &google::LogMessage::SendToLog) #define SYSLOG_DFATAL(counter) \ google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \ &google::LogMessage::SendToSyslogAndLog) #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \ defined(__CYGWIN__) || defined(__CYGWIN32__) # define LOG_SYSRESULT(result) \ if (FAILED(HRESULT_FROM_WIN32(result))) { \ LPSTR message = nullptr; \ LPSTR msg = reinterpret_cast<LPSTR>(&message); \ DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ FORMAT_MESSAGE_FROM_SYSTEM | \ FORMAT_MESSAGE_IGNORE_INSERTS, \ 0, result, 0, msg, 100, nullptr); \ std::unique_ptr<char, decltype(&LocalFree)> release{message, \ &LocalFree}; \ if (message_length > 0) { \ google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, 0, \ &google::LogMessage::SendToLog) \ .stream() \ << reinterpret_cast<const char*>(message); \ } \ } #endif #define LOG(severity) COMPACT_GOOGLE_LOG_##severity.stream() #define SYSLOG(severity) SYSLOG_##severity(0).stream() namespace google { GLOG_EXPORT void InitGoogleLogging(const char* argv0); GLOG_EXPORT bool IsGoogleLoggingInitialized(); GLOG_EXPORT void ShutdownGoogleLogging(); #if defined(__GNUC__) typedef void (*logging_fail_func_t)() __attribute__((noreturn)); #else typedef void (*logging_fail_func_t)(); #endif class LogMessage; using PrefixFormatterCallback = void (*)(std::ostream&, const LogMessage&, void*); GLOG_EXPORT void InstallPrefixFormatter(PrefixFormatterCallback callback, void* data = nullptr); GLOG_EXPORT logging_fail_func_t InstallFailureFunction(logging_fail_func_t fail_func); GLOG_EXPORT void EnableLogCleaner(const std::chrono::minutes& overdue); GLOG_EXPORT void DisableLogCleaner(); GLOG_EXPORT void SetApplicationFingerprint(const std::string& fingerprint); class LogSink; #define LOG_TO_SINK(sink, severity) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \ static_cast<google::LogSink*>(sink), true) \ .stream() #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \ google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \ static_cast<google::LogSink*>(sink), false) \ .stream() #define LOG_TO_STRING(severity, message) \ LOG_TO_STRING_##severity(static_cast<std::string*>(message)).stream() #define LOG_STRING(severity, outvec) \ LOG_TO_STRING_##severity(static_cast<std::vector<std::string>*>(outvec)) \ .stream() #define LOG_IF(severity, condition) \ static_cast<void>(0), \ !(condition) \ ? (void)0 \ : google::logging::internal::LogMessageVoidify() & LOG(severity) #define SYSLOG_IF(severity, condition) \ static_cast<void>(0), \ !(condition) \ ? (void)0 \ : google::logging::internal::LogMessageVoidify() & SYSLOG(severity) #define LOG_ASSERT(condition) \ LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition #define SYSLOG_ASSERT(condition) \ SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition #define CHECK(condition) \ LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ << "Check failed: " #condition " " namespace logging { namespace internal { struct CheckOpString { CheckOpString(std::unique_ptr<std::string> str) : str_(std::move(str)) {} explicit operator bool() const noexcept { return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != nullptr); } std::unique_ptr<std::string> str_; }; template <class T> inline const T& GetReferenceableValue(const T& t) { return t; } inline char GetReferenceableValue(char t) { return t; } inline unsigned char GetReferenceableValue(unsigned char t) { return t; } inline signed char GetReferenceableValue(signed char t) { return t; } inline short GetReferenceableValue(short t) { return t; } inline unsigned short GetReferenceableValue(unsigned short t) { return t; } inline int GetReferenceableValue(int t) { return t; } inline unsigned int GetReferenceableValue(unsigned int t) { return t; } inline long GetReferenceableValue(long t) { return t; } inline unsigned long GetReferenceableValue(unsigned long t) { return t; } inline long long GetReferenceableValue(long long t) { return t; } inline unsigned long long GetReferenceableValue(unsigned long long t) { return t; } struct DummyClassToDefineOperator {}; inline std::ostream& operator<<(std::ostream& out, const DummyClassToDefineOperator&) { return out; } template <typename T> inline void MakeCheckOpValueString(std::ostream* os, const T& v) { (*os) << v; } template <> GLOG_EXPORT void MakeCheckOpValueString(std::ostream* os, const char& v); template <> GLOG_EXPORT void MakeCheckOpValueString(std::ostream* os, const signed char& v); template <> GLOG_EXPORT void MakeCheckOpValueString(std::ostream* os, const unsigned char& v); template <> GLOG_EXPORT void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& v); template <typename T1, typename T2> std::unique_ptr<std::string> MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) #if defined(__has_attribute) # if __has_attribute(used) __attribute__((noinline)) # endif #endif ; class GLOG_EXPORT CheckOpMessageBuilder { public: explicit CheckOpMessageBuilder(const char* exprtext); ~CheckOpMessageBuilder(); std::ostream* ForVar1() { return stream_; } std::ostream* ForVar2(); std::unique_ptr<std::string> NewString(); private: std::ostringstream* stream_; }; template <typename T1, typename T2> std::unique_ptr<std::string> MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) { CheckOpMessageBuilder comb(exprtext); MakeCheckOpValueString(comb.ForVar1(), v1); MakeCheckOpValueString(comb.ForVar2(), v2); return comb.NewString(); } #define DEFINE_CHECK_OP_IMPL(name, op) \ template <typename T1, typename T2> \ inline std::unique_ptr<std::string> name##Impl(const T1& v1, const T2& v2, \ const char* exprtext) { \ if (GOOGLE_PREDICT_TRUE(v1 op v2)) { \ return nullptr; \ } \ return MakeCheckOpString(v1, v2, exprtext); \ } \ inline std::unique_ptr<std::string> name##Impl(int v1, int v2, \ const char* exprtext) { \ return name##Impl<int, int>(v1, v2, exprtext); \ } DEFINE_CHECK_OP_IMPL(Check_EQ, ==) DEFINE_CHECK_OP_IMPL(Check_NE, !=) DEFINE_CHECK_OP_IMPL(Check_LE, <=) DEFINE_CHECK_OP_IMPL(Check_LT, <) DEFINE_CHECK_OP_IMPL(Check_GE, >=) DEFINE_CHECK_OP_IMPL(Check_GT, >) #undef DEFINE_CHECK_OP_IMPL #if defined(STATIC_ANALYSIS) # define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1)op(val2)) #elif DCHECK_IS_ON() using _Check_string = std::string; # define CHECK_OP_LOG(name, op, val1, val2, log) \ while (std::unique_ptr<google::logging::internal::_Check_string> _result = \ google::logging::internal::Check##name##Impl( \ google::logging::internal::GetReferenceableValue(val1), \ google::logging::internal::GetReferenceableValue(val2), \ #val1 " " #op " " #val2)) \ log(__FILE__, __LINE__, \ google::logging::internal::CheckOpString(std::move(_result))) \ .stream() #else # define CHECK_OP_LOG(name, op, val1, val2, log) \ while (google::logging::internal::CheckOpString _result = \ google::logging::internal::Check##name##Impl( \ google::logging::internal::GetReferenceableValue(val1), \ google::logging::internal::GetReferenceableValue(val2), \ #val1 " " #op " " #val2)) \ log(__FILE__, __LINE__, _result).stream() #endif #if GOOGLE_STRIP_LOG <= 3 # define CHECK_OP(name, op, val1, val2) \ CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal) #else # define CHECK_OP(name, op, val1, val2) \ CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal) #endif #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2) #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2) #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2) #define CHECK_LT(val1, val2) CHECK_OP(_LT, <, val1, val2) #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2) #define CHECK_GT(val1, val2) CHECK_OP(_GT, >, val1, val2) #define CHECK_NOTNULL(val) \ google::logging::internal::CheckNotNull( \ __FILE__, __LINE__, "'" #val "' Must be non nullptr", (val)) #define
#include <fcntl.h> #include <chrono> #include <cstdio> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <memory> #include <mutex> #include <queue> #include <sstream> #include <stdexcept> #include <string> #include <thread> #include <vector> #include "config.h" #ifdef HAVE_GLOB_H # include <glob.h> #endif #include <sys/stat.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_SYS_WAIT_H # include <sys/wait.h> #endif #include "base/commandlineflags.h" #include "glog/logging.h" #include "glog/raw_logging.h" #include "googletest.h" #include "stacktrace.h" #include "utilities.h" #ifdef GLOG_USE_GFLAGS # include <gflags/gflags.h> using namespace GFLAGS_NAMESPACE; #endif #ifdef HAVE_LIB_GMOCK # include <gmock/gmock.h> # include "mock-log.h" using google::glog_testing::ScopedMockLog; using testing::_; using testing::AllOf; using testing::AnyNumber; using testing::HasSubstr; using testing::InitGoogleMock; using testing::StrictMock; using testing::StrNe; #endif using namespace std; using namespace google; namespace google { namespace base { namespace internal { bool GetExitOnDFatal(); void SetExitOnDFatal(bool value); } } } static void TestLogging(bool check_counts); static void TestRawLogging(); static void LogWithLevels(int v, int severity, bool err, bool alsoerr); static void TestLoggingLevels(); static void TestVLogModule(); static void TestLogString(); static void TestLogSink(); static void TestLogToString(); static void TestLogSinkWaitTillSent(); static void TestCHECK(); static void TestDCHECK(); static void TestSTREQ(); static void TestBasename(); static void TestBasenameAppendWhenNoTimestamp(); static void TestTwoProcessesWrite(); static void TestSymlink(); static void TestExtension(); static void TestWrapper(); static void TestErrno(); static void TestTruncate(); static void TestCustomLoggerDeletionOnShutdown(); static void TestLogPeriodically(); static int x = -1; static void BM_Check1(int n) { while (n-- > 0) { CHECK_GE(n, x); CHECK_GE(n, x); CHECK_GE(n, x); CHECK_GE(n, x); CHECK_GE(n, x); CHECK_GE(n, x); CHECK_GE(n, x); CHECK_GE(n, x); } } BENCHMARK(BM_Check1) static void CheckFailure(int a, int b, const char* file, int line, const char* msg); static void BM_Check3(int n) { while (n-- > 0) { if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); } } BENCHMARK(BM_Check3) static void BM_Check2(int n) { if (n == 17) { x = 5; } while (n-- > 0) { CHECK(n >= x); CHECK(n >= x); CHECK(n >= x); CHECK(n >= x); CHECK(n >= x); CHECK(n >= x); CHECK(n >= x); CHECK(n >= x); } } BENCHMARK(BM_Check2) static void CheckFailure(int, int, const char* , int , const char* ) {} static void BM_logspeed(int n) { while (n-- > 0) { LOG(INFO) << "test message"; } } BENCHMARK(BM_logspeed) static void BM_vlog(int n) { while (n-- > 0) { VLOG(1) << "test message"; } } BENCHMARK(BM_vlog) namespace { void PrefixAttacher(std::ostream& s, const LogMessage& m, void* data) { if (data == nullptr || *static_cast<string*>(data) != "good data") { return; } s << GetLogSeverityName(m.severity())[0] << setw(4) << 1900 + m.time().year() << setw(2) << 1 + m.time().month() << setw(2) << m.time().day() << ' ' << setw(2) << m.time().hour() << ':' << setw(2) << m.time().min() << ':' << setw(2) << m.time().sec() << "." << setw(6) << m.time().usec() << ' ' << setfill(' ') << setw(5) << m.thread_id() << setfill('0') << ' ' << m.basename() << ':' << m.line() << "]"; } } int main(int argc, char** argv) { FLAGS_colorlogtostderr = false; FLAGS_timestamp_in_logfile_name = true; setbuf(stderr, nullptr); CaptureTestStderr(); LogWithLevels(FLAGS_v, FLAGS_stderrthreshold, FLAGS_logtostderr, FLAGS_alsologtostderr); LogWithLevels(0, 0, false, false); const string early_stderr = GetCapturedTestStderr(); EXPECT_FALSE(IsGoogleLoggingInitialized()); string prefix_attacher_data = "good data"; InitGoogleLogging(argv[0]); InstallPrefixFormatter(&PrefixAttacher, &prefix_attacher_data); EXPECT_TRUE(IsGoogleLoggingInitialized()); RunSpecifiedBenchmarks(); FLAGS_logtostderr = true; InitGoogleTest(&argc, argv); #ifdef HAVE_LIB_GMOCK InitGoogleMock(&argc, argv); #endif #ifdef GLOG_USE_GFLAGS ParseCommandLineFlags(&argc, &argv, true); #endif CHECK_EQ(RUN_ALL_TESTS(), 0); CaptureTestStderr(); LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << early_stderr; TestLogging(true); TestRawLogging(); TestLoggingLevels(); TestVLogModule(); TestLogString(); TestLogSink(); TestLogToString(); TestLogSinkWaitTillSent(); TestCHECK(); TestDCHECK(); TestSTREQ(); EXPECT_TRUE( MungeAndDiffTestStderr(FLAGS_test_srcdir + "/src/logging_unittest.err")); FLAGS_logtostderr = false; FLAGS_logtostdout = true; FLAGS_stderrthreshold = NUM_SEVERITIES; CaptureTestStdout(); TestRawLogging(); TestLoggingLevels(); TestLogString(); TestLogSink(); TestLogToString(); TestLogSinkWaitTillSent(); TestCHECK(); TestDCHECK(); TestSTREQ(); EXPECT_TRUE( MungeAndDiffTestStdout(FLAGS_test_srcdir + "/src/logging_unittest.out")); FLAGS_logtostdout = false; TestBasename(); TestBasenameAppendWhenNoTimestamp(); TestTwoProcessesWrite(); TestSymlink(); TestExtension(); TestWrapper(); TestErrno(); TestTruncate(); TestCustomLoggerDeletionOnShutdown(); TestLogPeriodically(); fprintf(stdout, "PASS\n"); return 0; } void TestLogging(bool check_counts) { int64 base_num_infos = LogMessage::num_messages(GLOG_INFO); int64 base_num_warning = LogMessage::num_messages(GLOG_WARNING); int64 base_num_errors = LogMessage::num_messages(GLOG_ERROR); LOG(INFO) << string("foo ") << "bar " << 10 << ' ' << 3.4; for (int i = 0; i < 10; ++i) { int old_errno = errno; errno = i; PLOG_EVERY_N(ERROR, 2) << "Plog every 2, iteration " << COUNTER; errno = old_errno; LOG_EVERY_N(ERROR, 3) << "Log every 3, iteration " << COUNTER << endl; LOG_EVERY_N(ERROR, 4) << "Log every 4, iteration " << COUNTER << endl; LOG_IF_EVERY_N(WARNING, true, 5) << "Log if every 5, iteration " << COUNTER; LOG_IF_EVERY_N(WARNING, false, 3) << "Log if every 3, iteration " << COUNTER; LOG_IF_EVERY_N(INFO, true, 1) << "Log if every 1, iteration " << COUNTER; LOG_IF_EVERY_N(ERROR, (i < 3), 2) << "Log if less than 3 every 2, iteration " << COUNTER; } LOG_IF(WARNING, true) << "log_if this"; LOG_IF(WARNING, false) << "don't log_if this"; char s[] = "array"; LOG(INFO) << s; const char const_s[] = "const array"; LOG(INFO) << const_s; int j = 1000; LOG(ERROR) << string("foo") << ' ' << j << ' ' << setw(10) << j << " " << setw(1) << hex << j; LOG(INFO) << "foo " << std::setw(10) << 1.0; { google::LogMessage outer(__FILE__, __LINE__, GLOG_ERROR); outer.stream() << "outer"; LOG(ERROR) << "inner"; } LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << "no prefix"; if (check_counts) { CHECK_EQ(base_num_infos + 15, LogMessage::num_messages(GLOG_INFO)); CHECK_EQ(base_num_warning + 3, LogMessage::num_messages(GLOG_WARNING)); CHECK_EQ(base_num_errors + 17, LogMessage::num_messages(GLOG_ERROR)); } } static void NoAllocNewHook() { LOG(FATAL) << "unexpected new"; } struct NewHook { NewHook() { g_new_hook = &NoAllocNewHook; } ~NewHook() { g_new_hook = nullptr; } }; namespace { int* allocInt() { return new int; } } TEST(DeathNoAllocNewHook, logging) { NewHook new_hook; (void)&allocInt; ASSERT_DEATH({ allocInt(); }, "unexpected new"); } void TestRawLogging() { auto* foo = new string("foo "); string huge_str(50000, 'a'); FlagSaver saver; NewHook new_hook; RAW_LOG(INFO, "%s%s%d%c%f", foo->c_str(), "bar ", 10, ' ', 3.4); char s[] = "array"; RAW_LOG(WARNING, "%s", s); const char const_s[] = "const array"; RAW_LOG(INFO, "%s", const_s); void* p = reinterpret_cast<void*>(PTR_TEST_VALUE); RAW_LOG(INFO, "ptr %p", p); p = nullptr; RAW_LOG(INFO, "ptr %p", p); int j = 1000; RAW_LOG(ERROR, "%s%d%c%010d%s%1x", foo->c_str(), j, ' ', j, " ", j); RAW_VLOG(0, "foo %d", j); #if defined(NDEBUG) RAW_LOG(INFO, "foo %d", j); #else RAW_DLOG(INFO, "foo %d", j); #endif RAW_LOG(WARNING, "Huge string: %s", huge_str.c_str()); RAW_VLOG(0, "Huge string: %s", huge_str.c_str()); FLAGS_v = 0; RAW_LOG(INFO, "log"); RAW_VLOG(0, "vlog 0 on"); RAW_VLOG(1, "vlog 1 off"); RAW_VLOG(2, "vlog 2 off"); RAW_VLOG(3, "vlog 3 off"); FLAGS_v = 2; RAW_LOG(INFO, "log"); RAW_VLOG(1, "vlog 1 on"); RAW_VLOG(2, "vlog 2 on"); RAW_VLOG(3, "vlog 3 off"); #if defined(NDEBUG) RAW_DCHECK(1 == 2, " RAW_DCHECK's shouldn't be compiled in normal mode"); #endif RAW_CHECK(1 == 1, "should be ok"); RAW_DCHECK(true, "should be ok"); delete foo; } void LogWithLevels(int v, int severity, bool err, bool alsoerr) { RAW_LOG(INFO, "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d", v, severity, err, alsoerr); FlagSaver saver; FLAGS_v = v; FLAGS_stderrthreshold = severity; FLAGS_logtostderr = err; FLAGS_alsologtostderr = alsoerr; RAW_VLOG(-1, "vlog -1"); RAW_VLOG(0, "vlog 0"); RAW_VLOG(1, "vlog 1"); RAW_LOG(INFO, "log info"); RAW_LOG(WARNING, "log warning"); RAW_LOG(ERROR, "log error"); VLOG(-1) << "vlog -1"; VLOG(0) << "vlog 0"; VLOG(1) << "vlog 1"; LOG(INFO) << "log info"; LOG(WARNING) << "log warning"; LOG(ERROR) << "log error"; VLOG_IF(-1, true) << "vlog_if -1"; VLOG_IF(-1, false) << "don't vlog_if -1"; VLOG_IF(0, true) << "vlog_if 0"; VLOG_IF(0, false) << "don't vlog_if 0"; VLOG_IF(1, true) << "vlog_if 1"; VLOG_IF(1, false) << "don't vlog_if 1"; LOG_IF(INFO, true) << "log_if info"; LOG_IF(INFO, false) << "don't log_if info"; LOG_IF(WARNING, true) << "log_if warning"; LOG_IF(WARNING, false) << "don't log_if warning"; LOG_IF(ERROR, true) << "log_if error"; LOG_IF(ERROR, false) << "don't log_if error"; int c; c = 1; VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; EXPECT_EQ(c, -1); c = 1; VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1); c = 1; LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1); c = 1; LOG_IF(ERROR, c -= 2) << "log_if error expr"; EXPECT_EQ(c, -1); c = 2; VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0); c = 2; LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0); c = 3; LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr"; EXPECT_EQ(c, -1); c = 3; LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr"; EXPECT_EQ(c, -1); c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr"; EXPECT_EQ(c, 0); c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr"; EXPECT_EQ(c, 0); c = 5; VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr"; EXPECT_EQ(c, 1); c = 5; VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr"; EXPECT_EQ(c, 1); c = 6; VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr"; EXPECT_EQ(c, 0); c = 6; VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr"; EXPECT_EQ(c, 0); } void TestLoggingLevels() { LogWithLevels(0, GLOG_INFO, false, false); LogWithLevels(1, GLOG_INFO, false, false); LogWithLevels(-1, GLOG_INFO, false, false); LogWithLevels(0, GLOG_WARNING, false, false); LogWithLevels(0, GLOG_ERROR, false, false); LogWithLevels(0, GLOG_FATAL, false, false); LogWithLevels(0, GLOG_FATAL, true, false); LogWithLevels(0, GLOG_FATAL, false, true); LogWithLevels(1, GLOG_WARNING, false, false); LogWithLevels(1, GLOG_FATAL, false, true); } int TestVlogHelper() { if (VLOG_IS_ON(1)) { return 1; } return 0; } void TestVLogModule() { int c = TestVlogHelper(); EXPECT_EQ(0, c); #if defined(__GNUC__) EXPECT_EQ(0, SetVLOGLevel("logging_unittest", 1)); c = TestVlogHelper(); EXPECT_EQ(1, c); #endif } TEST(DeathRawCHECK, logging) { ASSERT_DEATH(RAW_CHECK(false, "failure 1"), "RAW: Check false failed: failure 1"); ASSERT_DEBUG_DEATH(RAW_DCHECK(1 == 2, "failure 2"), "RAW: Check 1 == 2 failed: failure 2"); } void TestLogString() { vector<string> errors; vector<string>* no_errors = nullptr; LOG_STRING(INFO, &errors) << "LOG_STRING: " << "collected info"; LOG_STRING(WARNING, &errors) << "LOG_STRING: " << "collected warning"; LOG_STRING(ERROR, &errors) << "LOG_STRING: " << "collected error"; LOG_STRING(INFO, no_errors) << "LOG_STRING: " << "reported info"; LOG_STRING(WARNING, no_errors) << "LOG_STRING: " << "reported warning"; LOG_STRING(ERROR, nullptr) << "LOG_STRING: " << "reported error"; for (auto& error : errors) { LOG(INFO) << "Captured by LOG_STRING: " << error; } } void TestLogToString() { string error; string* no_error = nullptr; LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " << "collected info"; LOG(INFO) << "Captured by LOG_TO_STRING: " << error; LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " << "collected warning"; LOG(INFO) << "Captured by LOG_TO_STRING: " << error; LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " << "collected error"; LOG(INFO) << "Captured by LOG_TO_STRING: " << error; LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " << "reported info"; LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " << "reported warning"; LOG_TO_STRING(ERROR, nullptr) << "LOG_TO_STRING: " << "reported error"; } class TestLogSinkImpl : public LogSink { public: vector<string> errors; void send(LogSeverity severity, const char* , const char* base_filename, int line, const LogMessageTime& logmsgtime, const char* message, size_t message_len) override { errors.push_back(ToString(severity, base_filename, line, logmsgtime, message, message_len)); } }; void TestLogSink() { TestLogSinkImpl sink; LogSink* no_sink = nullptr; LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " << "collected info"; LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " << "collected warning"; LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " << "collected error"; LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " << "reported info"; LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " << "reported warning"; LOG_TO_SINK(nullptr, ERROR) << "LOG_TO_SINK: " << "reported error"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, INFO) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected info"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, WARNING) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected warning"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, ERROR) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected error"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, INFO) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed info"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, WARNING) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed warning"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(nullptr, ERROR) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed error"; LOG(INFO) << "Captured by LOG_TO_SINK:"; for (auto& error : sink.errors) { LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << error; } } enum { CASE_A, CASE_B }; void TestCHECK() { CHECK(1 == 1); CHECK_EQ(1, 1); CHECK_NE(1, 2); CHECK_GE(1, 1); CHECK_GE(2, 1); CHECK_LE(1, 1); CHECK_LE(1, 2); CHECK_GT(2, 1); CHECK_LT(1, 2); #if !defined(GLOG_OS_MACOSX) CHECK_EQ(CASE_A, CASE_A); CHECK_NE(CASE_A, CASE_B); CHECK_GE(CASE_A, CASE_A); CHECK_GE(CASE_B, CASE_A); CHECK_LE(CASE_A, CASE_A); CHECK_LE(CASE_A, CASE_B); CHECK_GT(CASE_B, CASE_A); CHECK_LT(CASE_A, CASE_B); #endif } void TestDCHECK() { #if defined(NDEBUG) DCHECK(1 == 2) << " DCHECK's shouldn't be compiled in normal mode"; #endif DCHECK(1 == 1); DCHECK_EQ(1, 1); DCHECK_NE(1, 2); DCHECK_GE(1, 1); DCHECK_GE(2, 1); DCHECK_LE(1, 1); DCHECK_LE(1, 2); DCHECK_GT(2, 1); DCHECK_LT(1, 2); auto* orig_ptr = new int64; int64* ptr = DCHECK_NOTNULL(orig_ptr); CHECK_EQ(ptr, orig_ptr); delete orig_ptr; } void TestSTREQ() { CHECK_STREQ("this", "this"); CHECK_STREQ(nullptr, nullptr); CHECK_STRCASEEQ("this", "tHiS"); CHECK_STRCASEEQ(nullptr, nullptr); CHECK_STRNE("this", "tHiS"); CHECK_STRNE("this", nullptr); CHECK_STRCASENE("this", "that"); CHECK_STRCASENE(nullptr, "that"); CHECK_STREQ((string("a") + "b").c_str(), "ab"); CHECK_STREQ(string("test").c_str(), (string("te") + string("st")).c_str()); } TEST(DeathSTREQ, logging) { ASSERT_DEATH(CHECK_STREQ(nullptr, "this"), ""); ASSERT_DEATH(CHECK_STREQ("this", "siht"), ""); ASSERT_DEATH(CHECK_STRCASEEQ(nullptr, "siht"), ""); ASSERT_DEATH(CHECK_STRCASEEQ("this", "siht"), ""); ASSERT_DEATH(CHECK_STRNE(nullptr, nullptr), ""); ASSERT_DEATH(CHECK_STRNE("this", "this"), ""); ASSERT_DEATH(CHECK_STREQ((string("a") + "b").c_str(), "abc"), ""); } TEST(CheckNOTNULL, Simple) { int64 t; void* ptr = static_cast<void*>(&t); void* ref = CHECK_NOTNULL(ptr); EXPECT_EQ(ptr, ref); CHECK_NOTNULL(reinterpret_cast<char*>(ptr)); CHECK_NOTNULL(reinterpret_cast<unsigned char*>(ptr)); CHECK_NOTNULL(reinterpret_cast<int*>(ptr)); CHECK_NOTNULL(reinterpret_cast<int64*>(ptr)); } TEST(DeathCheckNN, Simple) { ASSERT_DEATH(CHECK_NOTNULL(static_cast<void*>(nullptr)), ""); } static void GetFiles(const string& pattern, vector<string>* files) { files->clear(); #if defined(HAVE_GLOB_H) glob_t g; const int r = glob(pattern.c_str(), 0, nullptr, &g); CHECK((r == 0) || (r == GLOB_NOMATCH)) << ": error matching " << pattern; for (size_t i = 0; i < g.gl_pathc; i++) { files->push_back(string(g.gl_pathv[i])); } globfree(&g); #elif defined(GLOG_OS_WINDOWS) WIN32_FIND_DATAA data; HANDLE handle = FindFirstFileA(pattern.c_str(), &data); size_t index = pattern.rfind('\\'); if (index == string::npos) { LOG(FATAL) << "No directory separator."; } const string dirname = pattern.substr(0, index + 1); if (handle == INVALID_HANDLE_VALUE) { return; } do { files->push_back(dirname + data.cFileName); } while (FindNextFileA(handle, &data)); if (!FindClose(handle)) { LOG_SYSRESULT(GetLastError()); } #else # error There is no way to do glob. #endif } static void DeleteFiles(const string& pattern) { vector<string> files; GetFiles(pattern, &files); for (auto& file : files) { CHECK(unlink(file.c_str()) == 0) << ": " << strerror(errno); } } static void CheckFile(const string& name, const string& expected_string, const bool checkInFileOrNot = true) { vector<string> files; GetFiles(name + "*", &files); CHECK_EQ(files.size(), 1UL); std::unique_ptr<std::FILE> file{fopen(files[0].c_str(), "r")}; CHECK(file != nullptr) << ": could not open " << files[0]; char buf[1000]; while (fgets(buf, sizeof(buf), file.get()) != nullptr) { char* first = strstr(buf, expected_string.c_str()); if (checkInFileOrNot != (first == nullptr)) { return; } } LOG(FATAL) << "Did " << (checkInFileOrNot ? "not " : "") << "find " << expected_string << " in " << files[0]; } static void TestBasename() { fprintf(stderr, "==== Test setting log file basename\n"); const string dest = FLAGS_test_tmpdir + "/logging_test_basename"; DeleteFiles(dest + "*"); SetLogDestination(GLOG_INFO, dest.c_str()); LOG(INFO) << "message to new base"; FlushLogFiles(GLOG_INFO); CheckFile(dest, "message to new base"); LogToStderr(); DeleteFiles(dest + "*"); } static void TestBasenameAppendWhenNoTimestamp() { fprintf(stderr, "==== Test setting log file basename without timestamp and appending " "properly\n"); const string dest = FLAGS_test_tmpdir + "/logging_test_basename_append_when_no_timestamp"; DeleteFiles(dest + "*"); ofstream out(dest.c_str()); out << "test preexisting content" << endl; out.close(); CheckFile(dest, "test preexisting content"); FLAGS_timestamp_in_logfile_name = false; SetLogDestination(GLOG_INFO, dest.c_str()); LOG(INFO) << "message to new base, appending to preexisting file"; FlushLogFiles(GLOG_INFO); FLAGS_timestamp_in_logfile_name = true; CheckFile(dest, "test preexisting content"); CheckFile(dest, "message to new base, appending to preexisting file"); LogToStderr(); DeleteFiles(dest + "*"); } static void TestTwoProcessesWrite() { #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_UNISTD_H) && defined(HAVE_FCNTL) fprintf(stderr, "==== Test setting log file basename and two processes writing - " "second should fail\n"); const string dest = FLAGS_test_tmpdir + "/logging_test_basename_two_processes_writing"; DeleteFiles(dest + "*"); FLAGS_timestamp_in_logfile_name = false; SetLogDestination(GLOG_INFO, dest.c_str()); LOG(INFO) << "message to new base, parent"; FlushLogFiles(GLOG_INFO); pid_t pid = fork(); CHECK_ERR(pid); if (pid == 0) { LOG(INFO) << "message to new base, child - should only appear on STDERR " "not on the file"; ShutdownGoogleLogging(); exit(EXIT_SUCCESS); } else if (pid > 0) { wait(nullptr); } FLAGS_timestamp_in_logfile_name = true; CheckFile(dest, "message to new base, parent"); CheckFile(dest, "message to new base, child - should only appear on STDERR not on " "the file", false); LogToStderr(); DeleteFiles(dest + "*"); #endif } static void TestSymlink() { #ifndef GLOG_OS_WINDOWS fprintf(stderr, "==== Test setting log file symlink\n"); string dest = FLAGS_test_tmpdir + "/logging_test_symlink"; string sym = FLAGS_test_tmpdir + "/symlinkbase"; DeleteFiles(dest + "*"); DeleteFiles(sym + "*"); SetLogSymlink(GLOG_INFO, "symlinkbase"); SetLogDestination(GLOG_INFO, dest.c_str()); LOG(INFO) << "message to new symlink"; FlushLogFiles(GLOG_INFO); CheckFile(sym, "message to new symlink"); DeleteFiles(dest + "*"); DeleteFiles(sym + "*"); #endif } static void TestExtension() { fprintf(stderr, "==== Test setting log file extension\n"); string dest = FLAGS_test_tmpdir + "/logging_test_extension"; DeleteFiles(dest + "*"); SetLogDestination(GLOG_INFO, dest.c_str()); SetLogFilenameExtension("specialextension"); LOG(INFO) << "message to new extension"; FlushLogFiles(GLOG_INFO); CheckFile(dest, "message to new extension"); vector<string> filenames; GetFiles(dest + "*", &filenames); CHECK_EQ(filenames.size(), 1UL); CHECK(strstr(filenames[0].c_str(), "specialextension") != nullptr); LogToStderr(); DeleteFiles(dest + "*"); } struct MyLogger : public base::Logger { string data; explicit MyLogger(bool* set_on_destruction) : set_on_destruction_(set_on_destruction) {} ~MyLogger() override { *set_on_destruction_ = true; } void Write(bool , const std::chrono::system_clock::time_point& , const char* message, size_t length) override { data.append(message, length); } void Flush() override {} uint32 LogSize() override { return static_cast<uint32>(data.length()); } private: bool* set_on_destruction_; }; static void TestWrapper() { fprintf(stderr, "==== Test log wrapper\n"); bool custom_logger_deleted = false; auto* my_logger = new MyLogger(&custom_logger_deleted); base::Logger* old_logger = base::GetLogger(GLOG_INFO); base::SetLogger(GLOG_INFO, my_logger); LOG(INFO) << "Send to wrapped logger"; CHECK(strstr(my_logger->data.c_str(), "Send to wrapped logger") != nullptr); FlushLogFiles(GLOG_INFO); EXPECT_FALSE(custom_logger_deleted); base::SetLogger(GLOG_INFO, old_logger); EXPECT_TRUE(custom_logger_deleted); } static void TestErrno() { fprintf(stderr, "==== Test errno preservation\n"); errno = ENOENT; TestLogging(false); CHECK_EQ(errno, ENOENT); } static void TestOneTruncate(const char* path, uint64 limit, uint64 keep, size_t dsize, size_t ksize, size_t expect) { FileDescriptor fd{open(path, O_RDWR | O_CREAT | O_TRUNC, 0600)}; CHECK_ERR(fd); const char *discardstr = "DISCARDME!", *keepstr = "KEEPME!"; const size_t discard_size = strlen(discardstr), keep_size = strlen(keepstr); size_t written = 0; while (written < dsize) { size_t bytes = min(dsize - written, discard_size); CHECK_ERR(write(fd.get(), discardstr, bytes)); written += bytes; } written = 0; while (written < ksize) { size_t bytes = min(ksize - written, keep_size); CHECK_ERR(write(fd.get(), keepstr, bytes)); written += bytes; } TruncateLogFile(path, limit, keep); struct stat statbuf; CHECK_ERR(fstat(fd.get(), &statbuf)); CHECK_EQ(static_cast<size_t>(statbuf.st_size), expect); CHECK_ERR(lseek(fd.get(), 0, SEEK_SET)); const size_t buf_size = static_cast<size_t>(statbuf.st_size) + 1; std::vector<char> buf(buf_size); CHECK_ERR(read(fd.get(), buf.data(), buf_size)); const char* p = buf.data(); size_t checked = 0; while (checked < expect) { size_t bytes = min(expect - checked, keep_size); CHECK(!memcmp(p, keepstr, bytes)); checked += bytes; } } static void TestTruncate() { #ifdef HAVE_UNISTD_H fprintf(stderr, "==== Test log truncation\n"); string path = FLAGS_test_tmpdir + "/truncatefile"; TestOneTruncate(path.c_str(), 10, 10, 10, 10, 10); TestOneTruncate(path.c_str(), 2U << 20U, 4U << 10U, 3U << 20U, 4U << 10U, 4U << 10U); TestOneTruncate(path.c_str(), 10, 20, 0, 20, 20); TestOneTruncate(path.c_str(), 10, 0, 0, 0, 0); TestOneTruncate(path.c_str(), 10, 50, 0, 10, 10); TestOneTruncate(path.c_str(), 50, 100, 0, 30, 30); # if !defined(GLOG_OS_MACOSX) && !defined(GLOG_OS_WINDOWS) string linkname = path + ".link"; unlink(linkname.c_str()); CHECK_ERR(symlink(path.c_str(), linkname.c_str())); TestOneTruncate(linkname.c_str(), 10, 10, 0, 30, 30); # endif # if defined(GLOG_OS_LINUX) int fd; CHECK_ERR(fd = open(path.c_str(), O_APPEND | O_WRONLY)); char fdpath[64]; std::snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd); TestOneTruncate(fdpath, 10, 10, 10, 10, 10); # endif #endif } struct RecordDeletionLogger : public base::Logger { RecordDeletionLogger(bool* set_on_destruction, base::Logger* wrapped_logger) : set_on_destruction_(set_on_destruction), wrapped_logger_(wrapped_logger) { *set_on_destruction_ = false; } ~RecordDeletionLogger() override { *set_on_destruction_ = true; } void Write(bool force_flush, const std::chrono::system_clock::time_point& timestamp, const char* message, size_t length) override { wrapped_logger_->Write(force_flush, timestamp, message, length); } void Flush() override { wrapped_logger_->Flush(); } uint32 LogSize() override { return wrapped_logger_->LogSize(); } private: bool* set_on_destruction_; base::Logger* wrapped_logger_; }; static void TestCustomLoggerDeletionOnShutdown() { boo
153
cpp
google/glog
demangle
src/demangle.cc
src/demangle_unittest.cc
#ifndef GLOG_INTERNAL_DEMANGLE_H #define GLOG_INTERNAL_DEMANGLE_H #include <cstddef> #if defined(GLOG_USE_GLOG_EXPORT) # include "glog/export.h" #endif #if !defined(GLOG_NO_EXPORT) # error "demangle.h" was not included correctly. #endif namespace google { inline namespace glog_internal_namespace_ { bool GLOG_NO_EXPORT Demangle(const char* mangled, char* out, size_t out_size); } } #endif #include "demangle.h" #include <algorithm> #include <cstdlib> #include <limits> #include "utilities.h" #if defined(HAVE___CXA_DEMANGLE) # include <cxxabi.h> #endif #if defined(GLOG_OS_WINDOWS) # include <dbghelp.h> #endif namespace google { inline namespace glog_internal_namespace_ { #if !defined(GLOG_OS_WINDOWS) && !defined(HAVE___CXA_DEMANGLE) namespace { struct AbbrevPair { const char* const abbrev; const char* const real_name; }; const AbbrevPair kOperatorList[] = { {"nw", "new"}, {"na", "new[]"}, {"dl", "delete"}, {"da", "delete[]"}, {"ps", "+"}, {"ng", "-"}, {"ad", "&"}, {"de", "*"}, {"co", "~"}, {"pl", "+"}, {"mi", "-"}, {"ml", "*"}, {"dv", "/"}, {"rm", "%"}, {"an", "&"}, {"or", "|"}, {"eo", "^"}, {"aS", "="}, {"pL", "+="}, {"mI", "-="}, {"mL", "*="}, {"dV", "/="}, {"rM", "%="}, {"aN", "&="}, {"oR", "|="}, {"eO", "^="}, {"ls", "<<"}, {"rs", ">>"}, {"lS", "<<="}, {"rS", ">>="}, {"eq", "=="}, {"ne", "!="}, {"lt", "<"}, {"gt", ">"}, {"le", "<="}, {"ge", ">="}, {"nt", "!"}, {"aa", "&&"}, {"oo", "||"}, {"pp", "++"}, {"mm", "--"}, {"cm", ","}, {"pm", "->*"}, {"pt", "->"}, {"cl", "()"}, {"ix", "[]"}, {"qu", "?"}, {"st", "sizeof"}, {"sz", "sizeof"}, {nullptr, nullptr}, }; const AbbrevPair kBuiltinTypeList[] = { {"v", "void"}, {"w", "wchar_t"}, {"b", "bool"}, {"c", "char"}, {"a", "signed char"}, {"h", "unsigned char"}, {"s", "short"}, {"t", "unsigned short"}, {"i", "int"}, {"j", "unsigned int"}, {"l", "long"}, {"m", "unsigned long"}, {"x", "long long"}, {"y", "unsigned long long"}, {"n", "__int128"}, {"o", "unsigned __int128"}, {"f", "float"}, {"d", "double"}, {"e", "long double"}, {"g", "__float128"}, {"z", "ellipsis"}, {"Dn", "decltype(nullptr)"}, {nullptr, nullptr}}; const AbbrevPair kSubstitutionList[] = { {"St", ""}, {"Sa", "allocator"}, {"Sb", "basic_string"}, {"Ss", "string"}, {"Si", "istream"}, {"So", "ostream"}, {"Sd", "iostream"}, {nullptr, nullptr}}; struct State { const char* mangled_cur; char* out_cur; const char* out_begin; const char* out_end; const char* prev_name; ssize_t prev_name_length; short nest_level; bool append; bool overflowed; uint32 local_level; uint32 expr_level; uint32 arg_level; }; size_t StrLen(const char* str) { size_t len = 0; while (*str != '\0') { ++str; ++len; } return len; } bool AtLeastNumCharsRemaining(const char* str, ssize_t n) { for (ssize_t i = 0; i < n; ++i) { if (str[i] == '\0') { return false; } } return true; } bool StrPrefix(const char* str, const char* prefix) { size_t i = 0; while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) { ++i; } return prefix[i] == '\0'; } void InitState(State* state, const char* mangled, char* out, size_t out_size) { state->mangled_cur = mangled; state->out_cur = out; state->out_begin = out; state->out_end = out + out_size; state->prev_name = nullptr; state->prev_name_length = -1; state->nest_level = -1; state->append = true; state->overflowed = false; state->local_level = 0; state->expr_level = 0; state->arg_level = 0; } bool ParseOneCharToken(State* state, const char one_char_token) { if (state->mangled_cur[0] == one_char_token) { ++state->mangled_cur; return true; } return false; } bool ParseTwoCharToken(State* state, const char* two_char_token) { if (state->mangled_cur[0] == two_char_token[0] && state->mangled_cur[1] == two_char_token[1]) { state->mangled_cur += 2; return true; } return false; } bool ParseCharClass(State* state, const char* char_class) { const char* p = char_class; for (; *p != '\0'; ++p) { if (state->mangled_cur[0] == *p) { ++state->mangled_cur; return true; } } return false; } bool Optional(bool) { return true; } using ParseFunc = bool (*)(State*); bool OneOrMore(ParseFunc parse_func, State* state) { if (parse_func(state)) { while (parse_func(state)) { } return true; } return false; } bool ZeroOrMore(ParseFunc parse_func, State* state) { while (parse_func(state)) { } return true; } void Append(State* state, const char* const str, ssize_t length) { if (state->out_cur == nullptr) { state->overflowed = true; return; } for (ssize_t i = 0; i < length; ++i) { if (state->out_cur + 1 < state->out_end) { *state->out_cur = str[i]; ++state->out_cur; } else { state->overflowed = true; break; } } if (!state->overflowed) { *state->out_cur = '\0'; } } bool IsLower(char c) { return c >= 'a' && c <= 'z'; } bool IsAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } bool IsDigit(char c) { return c >= '0' && c <= '9'; } bool IsFunctionCloneSuffix(const char* str) { size_t i = 0; while (str[i] != '\0') { if (str[i] != '.' || !IsAlpha(str[i + 1])) { return false; } i += 2; while (IsAlpha(str[i])) { ++i; } if (str[i] != '.' || !IsDigit(str[i + 1])) { return false; } i += 2; while (IsDigit(str[i])) { ++i; } } return true; } void MaybeAppendWithLength(State* state, const char* const str, ssize_t length) { if (state->append && length > 0) { if (str[0] == '<' && state->out_begin < state->out_cur && state->out_cur[-1] == '<') { Append(state, " ", 1); } if (IsAlpha(str[0]) || str[0] == '_') { state->prev_name = state->out_cur; state->prev_name_length = length; } Append(state, str, length); } } bool MaybeAppend(State* state, const char* const str) { if (state->append) { size_t length = StrLen(str); MaybeAppendWithLength(state, str, static_cast<ssize_t>(length)); } return true; } bool EnterNestedName(State* state) { state->nest_level = 0; return true; } bool LeaveNestedName(State* state, short prev_value) { state->nest_level = prev_value; return true; } bool DisableAppend(State* state) { state->append = false; return true; } bool RestoreAppend(State* state, bool prev_value) { state->append = prev_value; return true; } void MaybeIncreaseNestLevel(State* state) { if (state->nest_level > -1) { ++state->nest_level; } } void MaybeAppendSeparator(State* state) { if (state->nest_level >= 1) { MaybeAppend(state, "::"); } } void MaybeCancelLastSeparator(State* state) { if (state->nest_level >= 1 && state->append && state->out_begin <= state->out_cur - 2) { state->out_cur -= 2; *state->out_cur = '\0'; } } bool IdentifierIsAnonymousNamespace(State* state, ssize_t length) { const char anon_prefix[] = "_GLOBAL__N_"; return (length > static_cast<ssize_t>(sizeof(anon_prefix)) - 1 && StrPrefix(state->mangled_cur, anon_prefix)); } bool ParseMangledName(State* state); bool ParseEncoding(State* state); bool ParseName(State* state); bool ParseUnscopedName(State* state); bool ParseUnscopedTemplateName(State* state); bool ParseNestedName(State* state); bool ParsePrefix(State* state); bool ParseUnqualifiedName(State* state); bool ParseSourceName(State* state); bool ParseLocalSourceName(State* state); bool ParseNumber(State* state, int* number_out); bool ParseFloatNumber(State* state); bool ParseSeqId(State* state); bool ParseIdentifier(State* state, ssize_t length); bool ParseAbiTags(State* state); bool ParseAbiTag(State* state); bool ParseOperatorName(State* state); bool ParseSpecialName(State* state); bool ParseCallOffset(State* state); bool ParseNVOffset(State* state); bool ParseVOffset(State* state); bool ParseCtorDtorName(State* state); bool ParseType(State* state); bool ParseCVQualifiers(State* state); bool ParseBuiltinType(State* state); bool ParseFunctionType(State* state); bool ParseBareFunctionType(State* state); bool ParseClassEnumType(State* state); bool ParseArrayType(State* state); bool ParsePointerToMemberType(State* state); bool ParseTemplateParam(State* state); bool ParseTemplateTemplateParam(State* state); bool ParseTemplateArgs(State* state); bool ParseTemplateArg(State* state); bool ParseExpression(State* state); bool ParseExprPrimary(State* state); bool ParseLocalName(State* state); bool ParseDiscriminator(State* state); bool ParseSubstitution(State* state); bool ParseMangledName(State* state) { return ParseTwoCharToken(state, "_Z") && ParseEncoding(state); } bool ParseEncoding(State* state) { State copy = *state; if (ParseName(state) && ParseBareFunctionType(state)) { return true; } *state = copy; if (ParseName(state) || ParseSpecialName(state)) { return true; } return false; } bool ParseName(State* state) { if (ParseNestedName(state) || ParseLocalName(state)) { return true; } State copy = *state; if (ParseUnscopedTemplateName(state) && ParseTemplateArgs(state)) { return true; } *state = copy; if (ParseUnscopedName(state)) { return true; } return false; } bool ParseUnscopedName(State* state) { if (ParseUnqualifiedName(state)) { return true; } State copy = *state; if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") && ParseUnqualifiedName(state)) { return true; } *state = copy; return false; } bool ParseUnscopedTemplateName(State* state) { return ParseUnscopedName(state) || ParseSubstitution(state); } bool ParseNestedName(State* state) { State copy = *state; if (ParseOneCharToken(state, 'N') && EnterNestedName(state) && Optional(ParseCVQualifiers(state)) && ParsePrefix(state) && LeaveNestedName(state, copy.nest_level) && ParseOneCharToken(state, 'E')) { return true; } *state = copy; return false; } bool ParsePrefix(State* state) { bool has_something = false; while (true) { MaybeAppendSeparator(state); if (ParseTemplateParam(state) || ParseSubstitution(state) || ParseUnscopedName(state)) { has_something = true; MaybeIncreaseNestLevel(state); continue; } MaybeCancelLastSeparator(state); if (has_something && ParseTemplateArgs(state)) { return ParsePrefix(state); } else { break; } } return true; } bool ParseUnqualifiedName(State* state) { return (ParseOperatorName(state) || ParseCtorDtorName(state) || (ParseSourceName(state) && Optional(ParseAbiTags(state))) || (ParseLocalSourceName(state) && Optional(ParseAbiTags(state)))); } bool ParseSourceName(State* state) { State copy = *state; int length = -1; if (ParseNumber(state, &length) && ParseIdentifier(state, length)) { return true; } *state = copy; return false; } bool ParseLocalSourceName(State* state) { State copy = *state; if (ParseOneCharToken(state, 'L') && ParseSourceName(state) && Optional(ParseDiscriminator(state))) { return true; } *state = copy; return false; } bool ParseNumber(State* state, int* number_out) { int sign = 1; if (ParseOneCharToken(state, 'n')) { sign = -1; } const char* p = state->mangled_cur; int number = 0; constexpr int int_max_by_10 = std::numeric_limits<int>::max() / 10; for (; *p != '\0'; ++p) { if (IsDigit(*p)) { if (number > int_max_by_10) { return false; } const int digit = *p - '0'; const int shifted = number * 10; if (digit > std::numeric_limits<int>::max() - shifted) { return false; } number = shifted + digit; } else { break; } } if (p != state->mangled_cur) { state->mangled_cur = p; if (number_out != nullptr) { *number_out = number * sign; } return true; } return false; } bool ParseFloatNumber(State* state) { const char* p = state->mangled_cur; for (; *p != '\0'; ++p) { if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) { break; } } if (p != state->mangled_cur) { state->mangled_cur = p; return true; } return false; } bool ParseSeqId(State* state) { const char* p = state->mangled_cur; for (; *p != '\0'; ++p) { if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) { break; } } if (p != state->mangled_cur) { state->mangled_cur = p; return true; } return false; } bool ParseIdentifier(State* state, ssize_t length) { if (length == -1 || !AtLeastNumCharsRemaining(state->mangled_cur, length)) { return false; } if (IdentifierIsAnonymousNamespace(state, length)) { MaybeAppend(state, "(anonymous namespace)"); } else { MaybeAppendWithLength(state, state->mangled_cur, length); } if (length < 0 || static_cast<std::size_t>(length) > StrLen(state->mangled_cur)) { return false; } state->mangled_cur += length; return true; } bool ParseAbiTags(State* state) { State copy = *state; DisableAppend(state); if (OneOrMore(ParseAbiTag, state)) { RestoreAppend(state, copy.append); return true; } *state = copy; return false; } bool ParseAbiTag(State* state) { return ParseOneCharToken(state, 'B') && ParseSourceName(state); } bool ParseOperatorName(State* state) { if (!AtLeastNumCharsRemaining(state->mangled_cur, 2)) { return false; } State copy = *state; if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") && EnterNestedName(state) && ParseType(state) && LeaveNestedName(state, copy.nest_level)) { return true; } *state = copy; if (ParseOneCharToken(state, 'v') && ParseCharClass(state, "0123456789") && ParseSourceName(state)) { return true; } *state = copy; if (!(IsLower(state->mangled_cur[0]) && IsAlpha(state->mangled_cur[1]))) { return false; } const AbbrevPair* p; for (p = kOperatorList; p->abbrev != nullptr; ++p) { if (state->mangled_cur[0] == p->abbrev[0] && state->mangled_cur[1] == p->abbrev[1]) { MaybeAppend(state, "operator"); if (IsLower(*p->real_name)) { MaybeAppend(state, " "); } MaybeAppend(state, p->real_name); state->mangled_cur += 2; return true; } } return false; } bool ParseSpecialName(State* state) { State copy = *state; if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTIS") && ParseType(state)) { return true; } *state = copy; if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) && ParseCallOffset(state) && ParseEncoding(state)) { return true; } *state = copy; if (ParseTwoCharToken(state, "GV") && ParseName(state)) { return true; } *state = copy; if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) && ParseEncoding(state)) { return true; } *state = copy; if (ParseTwoCharToken(state, "TC") && ParseType(state) && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') && DisableAppend(state) && ParseType(state)) { RestoreAppend(state, copy.append); return true; } *state = copy; if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") && ParseType(state)) { return true; } *state = copy; if (ParseTwoCharToken(state, "GR") && ParseName(state)) { return true; } *state = copy; if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) { return true; } *state = copy; if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") && ParseCallOffset(state) && ParseEncoding(state)) { return true; } *state = copy; return false; } bool ParseCallOffset(State* state) { State copy = *state; if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) && ParseOneCharToken(state, '_')) { return true; } *state = copy; if (ParseOneCharToken(state, 'v') && ParseVOffset(state) && ParseOneCharToken(state, '_')) { return true; } *state = copy; return false; } bool ParseNVOffset(State* state) { return ParseNumber(state, nullptr); } bool ParseVOffset(State* state) { State copy = *state; if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') && ParseNumber(state, nullptr)) { return true; } *state = copy; return false; } bool ParseCtorDtorName(State* state) { State copy = *state; if (ParseOneCharToken(state, 'C') && ParseCharClass(state, "123")) { const char* const prev_name = state->prev_name; const ssize_t prev_name_length = state->prev_name_length; MaybeAppendWithLength(state, prev_name, prev_name_length); return true; } *state = copy; if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "012")) { const char* const prev_name = state->prev_name; const ssize_t prev_name_length = state->prev_name_length; MaybeAppend(state, "~"); MaybeAppendWithLength(state, prev_name, prev_name_length); return true; } *state = copy; return false; } bool ParseType(State* state) { State copy = *state; if (ParseCVQualifiers(state) && ParseType(state)) { return true; } *state = copy; if (ParseCharClass(state, "OPRCG") && ParseType(state)) { return true; } *state = copy; if (ParseTwoCharToken(state, "Dp") && ParseType(state)) { return true; } *state = copy; if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") && ParseExpression(state) && ParseOneCharToken(state, 'E')) { return true; } *state = copy; if (ParseOneCharToken(state, 'U') && ParseSourceName(state) && ParseType(state)) { return true; } *state = copy; if (ParseBuiltinType(state) || ParseFunctionType(state) || ParseClassEnumType(state) || ParseArrayType(state) || ParsePointerToMemberType(s
#include "demangle.h" #include <fstream> #include <iostream> #include <string> #include "config.h" #include "glog/logging.h" #include "googletest.h" #include "utilities.h" #ifdef GLOG_USE_GFLAGS # include <gflags/gflags.h> using namespace GFLAGS_NAMESPACE; #endif GLOG_DEFINE_bool(demangle_filter, false, "Run demangle_unittest in filter mode"); using namespace std; using namespace google; static const char* DemangleIt(const char* const mangled) { static char demangled[4096]; if (Demangle(mangled, demangled, sizeof(demangled))) { return demangled; } else { return mangled; } } #if defined(GLOG_OS_WINDOWS) # if defined(HAVE_DBGHELP) && !defined(NDEBUG) TEST(Demangle, Windows) { EXPECT_STREQ("public: static void __cdecl Foo::func(int)", DemangleIt("?func@Foo@@SAXH@Z")); EXPECT_STREQ("public: static void __cdecl Foo::func(int)", DemangleIt("@ILT+1105(?func@Foo@@SAXH@Z)")); EXPECT_STREQ("int __cdecl foobarArray(int * const)", DemangleIt("?foobarArray@@YAHQAH@Z")); } # endif #else TEST(Demangle, CornerCases) { const size_t size = 10; char tmp[size] = {0}; const char* demangled = "foobar()"; const char* mangled = "_Z6foobarv"; EXPECT_TRUE(Demangle(mangled, tmp, sizeof(tmp))); EXPECT_STREQ(demangled, tmp); EXPECT_TRUE(Demangle(mangled, tmp, size - 1)); EXPECT_STREQ(demangled, tmp); EXPECT_FALSE(Demangle(mangled, tmp, size - 2)); EXPECT_FALSE(Demangle(mangled, tmp, 1)); EXPECT_FALSE(Demangle(mangled, tmp, 0)); EXPECT_FALSE(Demangle(mangled, nullptr, 0)); } TEST(Demangle, Clones) { char tmp[20]; EXPECT_TRUE(Demangle("_ZL3Foov", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.clone.3", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.constprop.80", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.isra.18", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.isra.2.constprop.18", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_FALSE(Demangle("_ZL3Foov.clo", tmp, sizeof(tmp))); EXPECT_FALSE(Demangle("_ZL3Foov.clone.", tmp, sizeof(tmp))); EXPECT_FALSE(Demangle("_ZL3Foov.clone.foo", tmp, sizeof(tmp))); EXPECT_FALSE(Demangle("_ZL3Foov.isra.2.constprop.", tmp, sizeof(tmp))); } TEST(Demangle, FromFile) { string test_file = FLAGS_test_srcdir + "/src/demangle_unittest.txt"; ifstream f(test_file.c_str()); EXPECT_FALSE(f.fail()); string line; while (getline(f, line)) { if (line.empty() || line[0] == '#') { continue; } string::size_type tab_pos = line.find('\t'); EXPECT_NE(string::npos, tab_pos); string mangled = line.substr(0, tab_pos); string demangled = line.substr(tab_pos + 1); EXPECT_EQ(demangled, DemangleIt(mangled.c_str())); } } #endif int main(int argc, char** argv) { InitGoogleTest(&argc, argv); #ifdef GLOG_USE_GFLAGS ParseCommandLineFlags(&argc, &argv, true); #endif FLAGS_logtostderr = true; InitGoogleLogging(argv[0]); if (FLAGS_demangle_filter) { string line; while (getline(cin, line, '\n')) { cout << DemangleIt(line.c_str()) << endl; } return 0; } else if (argc > 1) { cout << DemangleIt(argv[1]) << endl; return 0; } else { return RUN_ALL_TESTS(); } }
154
cpp
google/glog
utilities
src/utilities.cc
src/utilities_unittest.cc
#ifndef GLOG_INTERNAL_UTILITIES_H #define GLOG_INTERNAL_UTILITIES_H #include <cstddef> #include <cstdio> #include <memory> #include <string> #include <type_traits> #include <utility> #ifdef _LP64 # define __PRIS_PREFIX "z" #else # define __PRIS_PREFIX #endif #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" #include "config.h" #include "glog/platform.h" #if defined(GLOG_USE_WINDOWS_PORT) # include "port.h" #endif #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if !defined(HAVE_SSIZE_T) # if defined(GLOG_OS_WINDOWS) # include <basetsd.h> using ssize_t = SSIZE_T; # else using ssize_t = std::ptrdiff_t; # endif #endif #include "glog/log_severity.h" #include "glog/types.h" #ifndef ARRAYSIZE # define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) #endif namespace google { namespace logging { namespace internal { struct CrashReason { CrashReason() = default; const char* filename{nullptr}; int line_number{0}; const char* message{nullptr}; void* stack[32]; int depth{0}; }; } } inline namespace glog_internal_namespace_ { #if defined(__has_attribute) # if __has_attribute(noinline) # define ATTRIBUTE_NOINLINE __attribute__((noinline)) # define HAVE_ATTRIBUTE_NOINLINE # endif #endif #if !defined(HAVE_ATTRIBUTE_NOINLINE) # if defined(GLOG_OS_WINDOWS) # define ATTRIBUTE_NOINLINE __declspec(noinline) # define HAVE_ATTRIBUTE_NOINLINE # endif #endif #if !defined(HAVE_ATTRIBUTE_NOINLINE) # define ATTRIBUTE_NOINLINE #endif void AlsoErrorWrite(LogSeverity severity, const char* tag, const char* message) noexcept; const char* ProgramInvocationShortName(); int32 GetMainThreadPid(); bool PidHasChanged(); const std::string& MyUserName(); const char* const_basename(const char* filepath); void SetCrashReason(const logging::internal::CrashReason* r); void InitGoogleLoggingUtilities(const char* argv0); void ShutdownGoogleLoggingUtilities(); template <class Functor> class ScopedExit final { public: template <class F, std::enable_if_t< std::is_constructible<Functor, F&&>::value>* = nullptr> constexpr explicit ScopedExit(F&& functor) noexcept( std::is_nothrow_constructible<Functor, F&&>::value) : functor_{std::forward<F>(functor)} {} ~ScopedExit() noexcept(noexcept(std::declval<Functor&>()())) { functor_(); } ScopedExit(const ScopedExit& other) = delete; ScopedExit& operator=(const ScopedExit& other) = delete; ScopedExit(ScopedExit&& other) noexcept = delete; ScopedExit& operator=(ScopedExit&& other) noexcept = delete; private: Functor functor_; }; class GLOG_NO_EXPORT FileDescriptor final { static constexpr int InvalidHandle = -1; public: constexpr FileDescriptor() noexcept : FileDescriptor{nullptr} {} constexpr explicit FileDescriptor(int fd) noexcept : fd_{fd} {} constexpr FileDescriptor(std::nullptr_t) noexcept : fd_{InvalidHandle} {} FileDescriptor(const FileDescriptor& other) = delete; FileDescriptor& operator=(const FileDescriptor& other) = delete; FileDescriptor(FileDescriptor&& other) noexcept : fd_{other.release()} {} FileDescriptor& operator=(FileDescriptor&& other) noexcept { reset(other.release()); return *this; } constexpr explicit operator bool() const noexcept { return fd_ != InvalidHandle; } constexpr int get() const noexcept { return fd_; } int release() noexcept { return std::exchange(fd_, InvalidHandle); } void reset(std::nullptr_t) noexcept { safe_close(); } void reset() noexcept { reset(nullptr); } void reset(int fd) noexcept { reset(); fd_ = fd; } int close() noexcept { return unsafe_close(); } ~FileDescriptor() { safe_close(); } private: int unsafe_close() noexcept { return ::close(release()); } void safe_close() noexcept { if (*this) { unsafe_close(); } } int fd_; }; constexpr bool operator==(const FileDescriptor& lhs, int rhs) noexcept { return lhs.get() == rhs; } constexpr bool operator==(int lhs, const FileDescriptor& rhs) noexcept { return rhs == lhs; } constexpr bool operator!=(const FileDescriptor& lhs, int rhs) noexcept { return !(lhs == rhs); } constexpr bool operator!=(int lhs, const FileDescriptor& rhs) noexcept { return !(lhs == rhs); } constexpr bool operator==(const FileDescriptor& lhs, std::nullptr_t) noexcept { return !lhs; } constexpr bool operator==(std::nullptr_t, const FileDescriptor& rhs) noexcept { return !rhs; } constexpr bool operator!=(const FileDescriptor& lhs, std::nullptr_t) noexcept { return static_cast<bool>(lhs); } constexpr bool operator!=(std::nullptr_t, const FileDescriptor& rhs) noexcept { return static_cast<bool>(rhs); } } } template <> struct std::default_delete<std::FILE> { void operator()(FILE* p) const noexcept { fclose(p); } }; #endif #define _GNU_SOURCE 1 #include "utilities.h" #include <atomic> #include <cerrno> #include <csignal> #include <cstdio> #include <cstdlib> #include "base/googleinit.h" #include "config.h" #include "glog/flags.h" #include "glog/logging.h" #include "stacktrace.h" #include "symbolize.h" #ifdef GLOG_OS_ANDROID # include <android/log.h> #endif #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif #if defined(HAVE_SYSCALL_H) # include <syscall.h> #elif defined(HAVE_SYS_SYSCALL_H) # include <sys/syscall.h> #endif #ifdef HAVE_SYSLOG_H # include <syslog.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_PWD_H # include <pwd.h> #endif #if defined(HAVE___PROGNAME) extern char* __progname; #endif using std::string; namespace google { static const char* g_program_invocation_short_name = nullptr; bool IsGoogleLoggingInitialized() { return g_program_invocation_short_name != nullptr; } inline namespace glog_internal_namespace_ { constexpr int FileDescriptor::InvalidHandle; void AlsoErrorWrite(LogSeverity severity, const char* tag, const char* message) noexcept { #if defined(GLOG_OS_WINDOWS) (void)severity; (void)tag; ::OutputDebugStringA(message); #elif defined(GLOG_OS_ANDROID) constexpr int android_log_levels[] = { ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL, }; __android_log_write(android_log_levels[severity], tag, message); #else (void)severity; (void)tag; (void)message; #endif } } } #ifdef HAVE_STACKTRACE # include "base/commandlineflags.h" # include "stacktrace.h" # include "symbolize.h" namespace google { using DebugWriter = void(const char*, void*); static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*); static void DebugWriteToStderr(const char* data, void*) { if (write(fileno(stderr), data, strlen(data)) < 0) { } AlsoErrorWrite(GLOG_FATAL, glog_internal_namespace_::ProgramInvocationShortName(), data); } static void DebugWriteToString(const char* data, void* arg) { reinterpret_cast<string*>(arg)->append(data); } # ifdef HAVE_SYMBOLIZE static void DumpPCAndSymbol(DebugWriter* writerfn, void* arg, void* pc, const char* const prefix) { char tmp[1024]; const char* symbol = "(unknown)"; if (Symbolize(reinterpret_cast<char*>(pc) - 1, tmp, sizeof(tmp))) { symbol = tmp; } char buf[1024]; std::snprintf(buf, sizeof(buf), "%s@ %*p %s\n", prefix, kPrintfPointerFieldWidth, pc, symbol); writerfn(buf, arg); } # endif static void DumpPC(DebugWriter* writerfn, void* arg, void* pc, const char* const prefix) { char buf[100]; std::snprintf(buf, sizeof(buf), "%s@ %*p\n", prefix, kPrintfPointerFieldWidth, pc); writerfn(buf, arg); } static void DumpStackTrace(int skip_count, DebugWriter* writerfn, void* arg) { void* stack[32]; int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count + 1); for (int i = 0; i < depth; i++) { # if defined(HAVE_SYMBOLIZE) if (FLAGS_symbolize_stacktrace) { DumpPCAndSymbol(writerfn, arg, stack[i], " "); } else { DumpPC(writerfn, arg, stack[i], " "); } # else DumpPC(writerfn, arg, stack[i], " "); # endif } } # ifdef __GNUC__ __attribute__((noreturn)) # endif static void DumpStackTraceAndExit() { DumpStackTrace(1, DebugWriteToStderr, nullptr); if (IsFailureSignalHandlerInstalled()) { # ifdef HAVE_SIGACTION struct sigaction sig_action; memset(&sig_action, 0, sizeof(sig_action)); sigemptyset(&sig_action.sa_mask); sig_action.sa_handler = SIG_DFL; sigaction(SIGABRT, &sig_action, nullptr); # elif defined(GLOG_OS_WINDOWS) signal(SIGABRT, SIG_DFL); # endif } abort(); } } #endif namespace google { inline namespace glog_internal_namespace_ { const char* const_basename(const char* filepath) { const char* base = strrchr(filepath, '/'); #ifdef GLOG_OS_WINDOWS if (!base) base = strrchr(filepath, '\\'); #endif return base ? (base + 1) : filepath; } const char* ProgramInvocationShortName() { if (g_program_invocation_short_name != nullptr) { return g_program_invocation_short_name; } #if defined(HAVE_PROGRAM_INVOCATION_SHORT_NAME) return program_invocation_short_name; #elif defined(HAVE_GETPROGNAME) return getprogname(); #elif defined(HAVE___PROGNAME) return __progname; #elif defined(HAVE___ARGV) return const_basename(__argv[0]); #else return "UNKNOWN"; #endif } static int32 g_main_thread_pid = getpid(); int32 GetMainThreadPid() { return g_main_thread_pid; } bool PidHasChanged() { int32 pid = getpid(); if (g_main_thread_pid == pid) { return false; } g_main_thread_pid = pid; return true; } static string g_my_user_name; const string& MyUserName() { return g_my_user_name; } static void MyUserNameInitializer() { #if defined(GLOG_OS_WINDOWS) const char* user = getenv("USERNAME"); #else const char* user = getenv("USER"); #endif if (user != nullptr) { g_my_user_name = user; } else { #if defined(HAVE_PWD_H) && defined(HAVE_UNISTD_H) struct passwd pwd; struct passwd* result = nullptr; char buffer[1024] = {'\0'}; uid_t uid = geteuid(); int pwuid_res = getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &result); if (pwuid_res == 0 && result) { g_my_user_name = pwd.pw_name; } else { std::snprintf(buffer, sizeof(buffer), "uid%d", uid); g_my_user_name = buffer; } #endif if (g_my_user_name.empty()) { g_my_user_name = "invalid-user"; } } } REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer()) static std::atomic<const logging::internal::CrashReason*> g_reason{nullptr}; void SetCrashReason(const logging::internal::CrashReason* r) { const logging::internal::CrashReason* expected = nullptr; g_reason.compare_exchange_strong(expected, r); } void InitGoogleLoggingUtilities(const char* argv0) { CHECK(!IsGoogleLoggingInitialized()) << "You called InitGoogleLogging() twice!"; g_program_invocation_short_name = const_basename(argv0); #ifdef HAVE_STACKTRACE InstallFailureFunction(&DumpStackTraceAndExit); #endif } void ShutdownGoogleLoggingUtilities() { CHECK(IsGoogleLoggingInitialized()) << "You called ShutdownGoogleLogging() without calling " "InitGoogleLogging() first!"; g_program_invocation_short_name = nullptr; #ifdef HAVE_SYSLOG_H closelog(); #endif } } #ifdef HAVE_STACKTRACE std::string GetStackTrace() { std::string stacktrace; DumpStackTrace(1, DebugWriteToString, &stacktrace); return stacktrace; } #endif }
#include "utilities.h" #include "glog/logging.h" #include "googletest.h" #ifdef GLOG_USE_GFLAGS # include <gflags/gflags.h> using namespace GFLAGS_NAMESPACE; #endif using namespace google; TEST(utilities, InitGoogleLoggingDeathTest) { ASSERT_DEATH(InitGoogleLogging("foobar"), ""); } int main(int argc, char** argv) { InitGoogleLogging(argv[0]); InitGoogleTest(&argc, argv); CHECK_EQ(RUN_ALL_TESTS(), 0); }
155
cpp
google/glog
symbolize
src/symbolize.cc
src/symbolize_unittest.cc
#ifndef GLOG_INTERNAL_SYMBOLIZE_H #define GLOG_INTERNAL_SYMBOLIZE_H #include <cstddef> #include <cstdint> #include <type_traits> #include "config.h" #include "glog/platform.h" #if defined(HAVE_LINK_H) # include <link.h> #elif defined(HAVE_ELF_H) # include <elf.h> #elif defined(HAVE_SYS_EXEC_ELF_H) # include <sys/exec_elf.h> #endif #if defined(GLOG_USE_GLOG_EXPORT) # include "glog/export.h" #endif #if !defined(GLOG_NO_EXPORT) # error "symbolize.h" was not included correctly. #endif #ifndef GLOG_NO_SYMBOLIZE_DETECTION # ifndef HAVE_SYMBOLIZE # if defined(HAVE_ELF_H) || defined(HAVE_SYS_EXEC_ELF_H) # define HAVE_SYMBOLIZE # elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) # define HAVE_SYMBOLIZE # elif defined(GLOG_OS_WINDOWS) # define HAVE_SYMBOLIZE # endif # endif #endif #ifdef HAVE_SYMBOLIZE # if !defined(SIZEOF_VOID_P) && defined(__SIZEOF_POINTER__) # define SIZEOF_VOID_P __SIZEOF_POINTER__ # endif # if defined(HAVE_ELF_H) || defined(HAVE_SYS_EXEC_ELF_H) # ifndef ElfW # if SIZEOF_VOID_P == 4 # define ElfW(type) Elf32_##type # elif SIZEOF_VOID_P == 8 # define ElfW(type) Elf64_##type # else # error "Unknown sizeof(void *)" # endif # endif namespace google { inline namespace glog_internal_namespace_ { GLOG_NO_EXPORT bool GetSectionHeaderByName(int fd, const char* name, size_t name_len, ElfW(Shdr) * out); } } # endif namespace google { inline namespace glog_internal_namespace_ { using SymbolizeCallback = int (*)(int, void*, char*, size_t, uint64_t); GLOG_NO_EXPORT void InstallSymbolizeCallback(SymbolizeCallback callback); using SymbolizeOpenObjectFileCallback = int (*)(uint64_t, uint64_t&, uint64_t&, char*, size_t); GLOG_NO_EXPORT void InstallSymbolizeOpenObjectFileCallback( SymbolizeOpenObjectFileCallback callback); } } #endif namespace google { inline namespace glog_internal_namespace_ { #if defined(HAVE_SYMBOLIZE) enum class SymbolizeOptions { kNone = 0, kNoLineNumbers = 1 }; constexpr SymbolizeOptions operator&(SymbolizeOptions lhs, SymbolizeOptions rhs) noexcept { return static_cast<SymbolizeOptions>( static_cast<std::underlying_type_t<SymbolizeOptions>>(lhs) & static_cast<std::underlying_type_t<SymbolizeOptions>>(rhs)); } constexpr SymbolizeOptions operator|(SymbolizeOptions lhs, SymbolizeOptions rhs) noexcept { return static_cast<SymbolizeOptions>( static_cast<std::underlying_type_t<SymbolizeOptions>>(lhs) | static_cast<std::underlying_type_t<SymbolizeOptions>>(rhs)); } GLOG_NO_EXPORT bool Symbolize( void* pc, char* out, size_t out_size, SymbolizeOptions options = SymbolizeOptions::kNone); #endif } } #endif #ifdef GLOG_BUILD_CONFIG_INCLUDE # include GLOG_BUILD_CONFIG_INCLUDE #endif #include "symbolize.h" #include "utilities.h" #if defined(HAVE_SYMBOLIZE) # include <algorithm> # include <cstdlib> # include <cstring> # include <limits> # include "demangle.h" # define GLOG_SAFE_ASSERT(expr) ((expr) ? 0 : (std::abort(), 0)) namespace google { inline namespace glog_internal_namespace_ { namespace { SymbolizeCallback g_symbolize_callback = nullptr; SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback = nullptr; ATTRIBUTE_NOINLINE void DemangleInplace(char* out, size_t out_size) { char demangled[256]; if (Demangle(out, demangled, sizeof(demangled))) { size_t len = strlen(demangled); if (len + 1 <= out_size) { GLOG_SAFE_ASSERT(len < sizeof(demangled)); memmove(out, demangled, len + 1); } } } } void InstallSymbolizeCallback(SymbolizeCallback callback) { g_symbolize_callback = callback; } void InstallSymbolizeOpenObjectFileCallback( SymbolizeOpenObjectFileCallback callback) { g_symbolize_open_object_file_callback = callback; } } } # if defined(HAVE_LINK_H) # if defined(HAVE_DLFCN_H) # include <dlfcn.h> # endif # include <fcntl.h> # include <sys/stat.h> # include <sys/types.h> # include <unistd.h> # include <cerrno> # include <climits> # include <cstddef> # include <cstdint> # include <cstdio> # include <cstdlib> # include <cstring> # include "config.h" # include "glog/raw_logging.h" # include "symbolize.h" namespace google { inline namespace glog_internal_namespace_ { namespace { template <class Functor> auto FailureRetry(Functor run, int error = EINTR) noexcept(noexcept(run())) { decltype(run()) result; while ((result = run()) == -1 && errno == error) { } return result; } } static ssize_t ReadFromOffset(const int fd, void* buf, const size_t count, const size_t offset) { GLOG_SAFE_ASSERT(fd >= 0); GLOG_SAFE_ASSERT(count <= static_cast<size_t>(std::numeric_limits<ssize_t>::max())); char* buf0 = reinterpret_cast<char*>(buf); size_t num_bytes = 0; while (num_bytes < count) { ssize_t len = FailureRetry([fd, p = buf0 + num_bytes, n = count - num_bytes, m = static_cast<off_t>(offset + num_bytes)] { return pread(fd, p, n, m); }); if (len < 0) { return -1; } if (len == 0) { break; } num_bytes += static_cast<size_t>(len); } GLOG_SAFE_ASSERT(num_bytes <= count); return static_cast<ssize_t>(num_bytes); } static bool ReadFromOffsetExact(const int fd, void* buf, const size_t count, const size_t offset) { ssize_t len = ReadFromOffset(fd, buf, count, offset); return static_cast<size_t>(len) == count; } static int FileGetElfType(const int fd) { ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return -1; } if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) { return -1; } return elf_header.e_type; } static ATTRIBUTE_NOINLINE bool GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const size_t sh_offset, ElfW(Word) type, ElfW(Shdr) * out) { ElfW(Shdr) buf[16]; for (size_t i = 0; i < sh_num;) { const size_t num_bytes_left = (sh_num - i) * sizeof(buf[0]); const size_t num_bytes_to_read = (sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf); const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read, sh_offset + i * sizeof(buf[0])); if (len == -1) { return false; } GLOG_SAFE_ASSERT(static_cast<size_t>(len) % sizeof(buf[0]) == 0); const size_t num_headers_in_buf = static_cast<size_t>(len) / sizeof(buf[0]); GLOG_SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0])); for (size_t j = 0; j < num_headers_in_buf; ++j) { if (buf[j].sh_type == type) { *out = buf[j]; return true; } } i += num_headers_in_buf; } return false; } const int kMaxSectionNameLen = 64; bool GetSectionHeaderByName(int fd, const char* name, size_t name_len, ElfW(Shdr) * out) { ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return false; } ElfW(Shdr) shstrtab; size_t shstrtab_offset = (elf_header.e_shoff + static_cast<size_t>(elf_header.e_shentsize) * static_cast<size_t>(elf_header.e_shstrndx)); if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) { return false; } for (size_t i = 0; i < elf_header.e_shnum; ++i) { size_t section_header_offset = (elf_header.e_shoff + elf_header.e_shentsize * i); if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) { return false; } char header_name[kMaxSectionNameLen]; if (sizeof(header_name) < name_len) { RAW_LOG(WARNING, "Section name '%s' is too long (%zu); " "section will not be found (even if present).", name, name_len); return false; } size_t name_offset = shstrtab.sh_offset + out->sh_name; ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset); if (n_read == -1) { return false; } else if (static_cast<size_t>(n_read) != name_len) { continue; } if (memcmp(header_name, name, name_len) == 0) { return true; } } return false; } static ATTRIBUTE_NOINLINE bool FindSymbol(uint64_t pc, const int fd, char* out, size_t out_size, uint64_t symbol_offset, const ElfW(Shdr) * strtab, const ElfW(Shdr) * symtab) { if (symtab == nullptr) { return false; } const size_t num_symbols = symtab->sh_size / symtab->sh_entsize; for (unsigned i = 0; i < num_symbols;) { size_t offset = symtab->sh_offset + i * symtab->sh_entsize; # if defined(__WORDSIZE) && __WORDSIZE == 64 const size_t NUM_SYMBOLS = 32U; # else const size_t NUM_SYMBOLS = 64U; # endif ElfW(Sym) buf[NUM_SYMBOLS]; size_t num_symbols_to_read = std::min(NUM_SYMBOLS, num_symbols - i); const ssize_t len = ReadFromOffset(fd, &buf, sizeof(buf[0]) * num_symbols_to_read, offset); GLOG_SAFE_ASSERT(static_cast<size_t>(len) % sizeof(buf[0]) == 0); const size_t num_symbols_in_buf = static_cast<size_t>(len) / sizeof(buf[0]); GLOG_SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read); for (unsigned j = 0; j < num_symbols_in_buf; ++j) { const ElfW(Sym)& symbol = buf[j]; uint64_t start_address = symbol.st_value; start_address += symbol_offset; uint64_t end_address = start_address + symbol.st_size; if (symbol.st_value != 0 && symbol.st_shndx != 0 && start_address <= pc && pc < end_address) { ssize_t len1 = ReadFromOffset(fd, out, out_size, strtab->sh_offset + symbol.st_name); if (len1 <= 0 || memchr(out, '\0', out_size) == nullptr) { memset(out, 0, out_size); return false; } return true; } } i += num_symbols_in_buf; } return false; } static bool GetSymbolFromObjectFile(const int fd, uint64_t pc, char* out, size_t out_size, uint64_t base_address) { ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return false; } ElfW(Shdr) symtab, strtab; if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, SHT_SYMTAB, &symtab)) { if (!ReadFromOffsetExact( fd, &strtab, sizeof(strtab), elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) { return false; } if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { return true; } } if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, SHT_DYNSYM, &symtab)) { if (!ReadFromOffsetExact( fd, &strtab, sizeof(strtab), elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) { return false; } if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { return true; } } return false; } namespace { class LineReader { public: explicit LineReader(int fd, char* buf, size_t buf_len, size_t offset) : fd_(fd), buf_(buf), buf_len_(buf_len), offset_(offset), bol_(buf), eol_(buf), eod_(buf) {} bool ReadLine(const char** bol, const char** eol) { if (BufferIsEmpty()) { const ssize_t num_bytes = ReadFromOffset(fd_, buf_, buf_len_, offset_); if (num_bytes <= 0) { return false; } offset_ += static_cast<size_t>(num_bytes); eod_ = buf_ + num_bytes; bol_ = buf_; } else { bol_ = eol_ + 1; GLOG_SAFE_ASSERT(bol_ <= eod_); if (!HasCompleteLine()) { const auto incomplete_line_length = static_cast<size_t>(eod_ - bol_); memmove(buf_, bol_, incomplete_line_length); char* const append_pos = buf_ + incomplete_line_length; const size_t capacity_left = buf_len_ - incomplete_line_length; const ssize_t num_bytes = ReadFromOffset(fd_, append_pos, capacity_left, offset_); if (num_bytes <= 0) { return false; } offset_ += static_cast<size_t>(num_bytes); eod_ = append_pos + num_bytes; bol_ = buf_; } } eol_ = FindLineFeed(); if (eol_ == nullptr) { return false; } *eol_ = '\0'; *bol = bol_; *eol = eol_; return true; } const char* bol() { return bol_; } const char* eol() { return eol_; } private: LineReader(const LineReader&) = delete; void operator=(const LineReader&) = delete; char* FindLineFeed() { return reinterpret_cast<char*>( memchr(bol_, '\n', static_cast<size_t>(eod_ - bol_))); } bool BufferIsEmpty() { return buf_ == eod_; } bool HasCompleteLine() { return !BufferIsEmpty() && FindLineFeed() != nullptr; } const int fd_; char* const buf_; const size_t buf_len_; size_t offset_; char* bol_; char* eol_; const char* eod_; }; } static char* GetHex(const char* start, const char* end, uint64_t* hex) { *hex = 0; const char* p; for (p = start; p < end; ++p) { int ch = *p; if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) { *hex = (*hex << 4U) | (ch < 'A' ? static_cast<uint64_t>(ch - '0') : (ch & 0xF) + 9U); } else { break; } } GLOG_SAFE_ASSERT(p <= end); return const_cast<char*>(p); } static ATTRIBUTE_NOINLINE FileDescriptor OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, uint64_t& start_address, uint64_t& base_address, char* out_file_name, size_t out_file_name_size) { FileDescriptor maps_fd{ FailureRetry([] { return open("/proc/self/maps", O_RDONLY); })}; if (!maps_fd) { return nullptr; } FileDescriptor mem_fd{ FailureRetry([] { return open("/proc/self/mem", O_RDONLY); })}; if (!mem_fd) { return nullptr; } char buf[1024]; LineReader reader(maps_fd.get(), buf, sizeof(buf), 0); while (true) { const char* cursor; const char* eol; if (!reader.ReadLine(&cursor, &eol)) { return nullptr; } cursor = GetHex(cursor, eol, &start_address); if (cursor == eol || *cursor != '-') { return nullptr; } ++cursor; uint64_t end_address; cursor = GetHex(cursor, eol, &end_address); if (cursor == eol || *cursor != ' ') { return nullptr; } ++cursor; const char* const flags_start = cursor; while (cursor < eol && *cursor != ' ') { ++cursor; } if (cursor == eol || cursor < flags_start + 4) { return nullptr; } ElfW(Ehdr) ehdr; if (flags_start[0] == 'r' && ReadFromOffsetExact(mem_fd.get(), &ehdr, sizeof(ElfW(Ehdr)), start_address) && memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) { switch (ehdr.e_type) { case ET_EXEC: base_address = 0; break; case ET_DYN: base_address = start_address; for (unsigned i = 0; i != ehdr.e_phnum; ++i) { ElfW(Phdr) phdr; if (ReadFromOffsetExact( mem_fd.get(), &phdr, sizeof(phdr), start_address + ehdr.e_phoff + i * sizeof(phdr)) && phdr.p_type == PT_LOAD && phdr.p_offset == 0) { base_address = start_address - phdr.p_vaddr; break; } } break; default: break; } } if (start_address > pc || pc >= end_address) { continue; } if (flags_start[0] != 'r' || flags_start[2] != 'x') { continue; } ++cursor; uint64_t file_offset; cursor = GetHex(cursor, eol, &file_offset); if (cursor == eol || *cursor != ' ') { return nullptr; } ++cursor; int num_spaces = 0; while (cursor < eol) { if (*cursor == ' ') { ++num_spaces; } else if (num_spaces >= 2) { break; } ++cursor; } if (cursor == eol) { return nullptr; } strncpy(out_file_name, cursor, out_file_name_size); out_file_name[out_file_name_size - 1] = '\0'; return FileDescriptor{ FailureRetry([cursor] { return open(cursor, O_RDONLY); })}; } } static char* itoa_r(uintptr_t i, char* buf, size_t sz, unsigned base, size_t padding) { size_t n = 1; if (n > sz) { return nullptr; } if (base < 2 || base > 16) { buf[0] = '\000'; return nullptr; } char* start = buf; char* ptr = start; do { if (++n > sz) { buf[0] = '\000'; return nullptr; } *ptr++ = "0123456789abcdef"[i % base]; i /= base; if (padding > 0) { padding--; } } while (i > 0 || padding > 0); *ptr = '\000'; while (--ptr > start) { char ch = *ptr; *ptr = *start; *start++ = ch; } return buf; } static void SafeAppendString(const char* source, char* dest, size_t dest_size) { size_t
#include "symbolize.h" #include <csignal> #include <iostream> #include "config.h" #include "glog/logging.h" #include "googletest.h" #include "utilities.h" #include "stacktrace.h" #ifdef GLOG_USE_GFLAGS # include <gflags/gflags.h> using namespace GFLAGS_NAMESPACE; #endif using namespace std; using namespace google; #if defined(__GNUG__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpedantic" #endif #if defined(HAVE_STACKTRACE) # define always_inline # if defined(HAVE_ELF_H) || defined(HAVE_SYS_EXEC_ELF_H) || \ defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) static const char* TrySymbolize(void* pc, google::SymbolizeOptions options = google::SymbolizeOptions::kNone) { static char symbol[4096]; if (Symbolize(pc, symbol, sizeof(symbol), options)) { return symbol; } else { return nullptr; } } # endif # if defined(HAVE_ELF_H) || defined(HAVE_SYS_EXEC_ELF_H) # if defined(__GNUC__) && !defined(__OPENCC__) # if __GNUC__ >= 4 # define TEST_WITH_MODERN_GCC # if defined(__i386__) && __i386__ # undef always_inline # define always_inline __attribute__((always_inline)) # define HAVE_ALWAYS_INLINE # endif # else # endif # define TEST_WITH_LABEL_ADDRESSES # endif extern "C" { void nonstatic_func(); void nonstatic_func() { volatile int a = 0; a = a + 1; } static void static_func() { volatile int a = 0; a = a + 1; } } TEST(Symbolize, Symbolize) { EXPECT_STREQ("nonstatic_func", TrySymbolize((void*)(&nonstatic_func))); const char* static_func_symbol = TrySymbolize(reinterpret_cast<void*>(&static_func)); # if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(nullptr != static_func_symbol); EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 || strcmp("static_func()", static_func_symbol) == 0); # endif EXPECT_TRUE(nullptr == TrySymbolize(nullptr)); } struct Foo { static void func(int x); }; void ATTRIBUTE_NOINLINE Foo::func(int x) { volatile int a = x; a = a + 1; } # ifdef TEST_WITH_MODERN_GCC TEST(Symbolize, SymbolizeWithDemangling) { Foo::func(100); # if !defined(_MSC_VER) || !defined(NDEBUG) # if defined(HAVE___CXA_DEMANGLE) EXPECT_STREQ("Foo::func(int)", TrySymbolize((void*)(&Foo::func))); # else EXPECT_STREQ("Foo::func()", TrySymbolize((void*)(&Foo::func))); # endif # endif } # endif static void* g_pc_to_symbolize; static char g_symbolize_buffer[4096]; static char* g_symbolize_result; static void EmptySignalHandler(int ) {} static void SymbolizeSignalHandler(int ) { if (Symbolize(g_pc_to_symbolize, g_symbolize_buffer, sizeof(g_symbolize_buffer))) { g_symbolize_result = g_symbolize_buffer; } else { g_symbolize_result = nullptr; } } const int kAlternateStackSize = 8096; const char kAlternateStackFillValue = 0x55; static ATTRIBUTE_NOINLINE bool StackGrowsDown(int* x) { int y; return &y < x; } static int GetStackConsumption(const char* alt_stack) { int x; if (StackGrowsDown(&x)) { for (int i = 0; i < kAlternateStackSize; i++) { if (alt_stack[i] != kAlternateStackFillValue) { return (kAlternateStackSize - i); } } } else { for (int i = (kAlternateStackSize - 1); i >= 0; i--) { if (alt_stack[i] != kAlternateStackFillValue) { return i; } } } return -1; } # ifdef HAVE_SIGALTSTACK static const char* SymbolizeStackConsumption(void* pc, int* stack_consumed) { g_pc_to_symbolize = pc; char altstack[kAlternateStackSize]; memset(altstack, kAlternateStackFillValue, kAlternateStackSize); stack_t sigstk; memset(&sigstk, 0, sizeof(stack_t)); stack_t old_sigstk; sigstk.ss_sp = altstack; sigstk.ss_size = kAlternateStackSize; sigstk.ss_flags = 0; CHECK_ERR(sigaltstack(&sigstk, &old_sigstk)); struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); struct sigaction old_sa1, old_sa2; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_ONSTACK; sa.sa_handler = EmptySignalHandler; CHECK_ERR(sigaction(SIGUSR1, &sa, &old_sa1)); sa.sa_handler = SymbolizeSignalHandler; CHECK_ERR(sigaction(SIGUSR2, &sa, &old_sa2)); CHECK_ERR(kill(getpid(), SIGUSR1)); int stack_consumption1 = GetStackConsumption(altstack); CHECK_ERR(kill(getpid(), SIGUSR2)); int stack_consumption2 = GetStackConsumption(altstack); if (stack_consumption1 != -1 && stack_consumption2 != -1) { *stack_consumed = stack_consumption2 - stack_consumption1; } else { *stack_consumed = -1; } LOG(INFO) << "Stack consumption of empty signal handler: " << stack_consumption1; LOG(INFO) << "Stack consumption of symbolize signal handler: " << stack_consumption2; LOG(INFO) << "Stack consumption of Symbolize: " << *stack_consumed; CHECK_ERR(sigaltstack(&old_sigstk, nullptr)); CHECK_ERR(sigaction(SIGUSR1, &old_sa1, nullptr)); CHECK_ERR(sigaction(SIGUSR2, &old_sa2, nullptr)); return g_symbolize_result; } # if !defined(HAVE___CXA_DEMANGLE) # ifdef __ppc64__ constexpr int kStackConsumptionUpperLimit = 4096; # else constexpr int kStackConsumptionUpperLimit = 2048; # endif # endif TEST(Symbolize, SymbolizeStackConsumption) { int stack_consumed; const char* symbol; symbol = SymbolizeStackConsumption(reinterpret_cast<void*>(&nonstatic_func), &stack_consumed); EXPECT_STREQ("nonstatic_func", symbol); EXPECT_GT(stack_consumed, 0); # if !defined(HAVE___CXA_DEMANGLE) EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); # endif symbol = SymbolizeStackConsumption(reinterpret_cast<void*>(&static_func), &stack_consumed); CHECK(nullptr != symbol); EXPECT_TRUE(strcmp("static_func", symbol) == 0 || strcmp("static_func()", symbol) == 0); EXPECT_GT(stack_consumed, 0); # if !defined(HAVE___CXA_DEMANGLE) EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); # endif } # if defined(TEST_WITH_MODERN_GCC) && !defined(HAVE___CXA_DEMANGLE) TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) { Foo::func(100); int stack_consumed; const char* symbol; symbol = SymbolizeStackConsumption(reinterpret_cast<void*>(&Foo::func), &stack_consumed); # if defined(HAVE___CXA_DEMANGLE) EXPECT_STREQ("Foo::func(int)", symbol); # else EXPECT_STREQ("Foo::func()", symbol); # endif EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); } # endif # endif extern "C" { inline void* always_inline inline_func() { void* pc = nullptr; # ifdef TEST_WITH_LABEL_ADDRESSES pc = &&curr_pc; curr_pc: # endif return pc; } void* ATTRIBUTE_NOINLINE non_inline_func(); void* ATTRIBUTE_NOINLINE non_inline_func() { void* pc = nullptr; # ifdef TEST_WITH_LABEL_ADDRESSES pc = &&curr_pc; curr_pc: # endif return pc; } static void ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() { # if defined(TEST_WITH_LABEL_ADDRESSES) && defined(HAVE_ATTRIBUTE_NOINLINE) void* pc = non_inline_func(); const char* symbol = TrySymbolize(pc); # if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, "non_inline_func"); # endif cout << "Test case TestWithPCInsideNonInlineFunction passed." << endl; # endif } static void ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() { # if defined(TEST_WITH_LABEL_ADDRESSES) && defined(HAVE_ALWAYS_INLINE) void* pc = inline_func(); const char* symbol = TrySymbolize(pc); # if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, __FUNCTION__); # endif cout << "Test case TestWithPCInsideInlineFunction passed." << endl; # endif } } static void ATTRIBUTE_NOINLINE TestWithReturnAddress() { # if defined(HAVE_ATTRIBUTE_NOINLINE) void* return_address = __builtin_return_address(0); const char* symbol = TrySymbolize(return_address, google::SymbolizeOptions::kNoLineNumbers); # if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, "main"); # endif cout << "Test case TestWithReturnAddress passed." << endl; # endif } # elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) # ifdef _MSC_VER # include <intrin.h> # pragma intrinsic(_ReturnAddress) # endif struct Foo { static void func(int x); }; __declspec(noinline) void Foo::func(int x) { volatile int a = x; a = a + 1; } TEST(Symbolize, SymbolizeWithDemangling) { Foo::func(100); const char* ret = TrySymbolize((void*)(&Foo::func)); # if defined(HAVE_DBGHELP) && !defined(NDEBUG) EXPECT_STREQ("public: static void __cdecl Foo::func(int)", ret); # endif } __declspec(noinline) void TestWithReturnAddress() { void* return_address = # ifdef __GNUC__ __builtin_return_address(0) # else _ReturnAddress() # endif ; const char* symbol = TrySymbolize(return_address, google::SymbolizeOptions::kNoLineNumbers); # if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, "main"); # endif cout << "Test case TestWithReturnAddress passed." << endl; } # endif #endif int main(int argc, char** argv) { FLAGS_logtostderr = true; InitGoogleLogging(argv[0]); InitGoogleTest(&argc, argv); #if defined(HAVE_SYMBOLIZE) && defined(HAVE_STACKTRACE) # if defined(HAVE_ELF_H) || defined(HAVE_SYS_EXEC_ELF_H) InstallSymbolizeCallback(nullptr); TestWithPCInsideInlineFunction(); TestWithPCInsideNonInlineFunction(); TestWithReturnAddress(); return RUN_ALL_TESTS(); # elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) TestWithReturnAddress(); return RUN_ALL_TESTS(); # else printf("PASS (no symbolize_unittest support)\n"); return 0; # endif #else printf("PASS (no symbolize support)\n"); return 0; #endif } #if defined(__GNUG__) # pragma GCC diagnostic pop #endif
156
cpp
google/glog
stacktrace
src/stacktrace.cc
src/stacktrace_unittest.cc
#ifndef GLOG_INTERNAL_STACKTRACE_H #define GLOG_INTERNAL_STACKTRACE_H #include "glog/platform.h" #if defined(GLOG_USE_GLOG_EXPORT) # include "glog/export.h" #endif #if !defined(GLOG_NO_EXPORT) # error "stacktrace.h" was not included correctly. #endif #include "config.h" #if defined(HAVE_LIBUNWIND) # define STACKTRACE_H "stacktrace_libunwind-inl.h" #elif defined(HAVE_UNWIND) # define STACKTRACE_H "stacktrace_unwind-inl.h" #elif !defined(NO_FRAME_POINTER) # if defined(__i386__) && __GNUC__ >= 2 # define STACKTRACE_H "stacktrace_x86-inl.h" # elif (defined(__ppc__) || defined(__PPC__)) && __GNUC__ >= 2 # define STACKTRACE_H "stacktrace_powerpc-inl.h" # elif defined(GLOG_OS_WINDOWS) # define STACKTRACE_H "stacktrace_windows-inl.h" # endif #endif #if !defined(STACKTRACE_H) && defined(HAVE_EXECINFO_BACKTRACE) # define STACKTRACE_H "stacktrace_generic-inl.h" #endif #if defined(STACKTRACE_H) # define HAVE_STACKTRACE #endif namespace google { inline namespace glog_internal_namespace_ { #if defined(HAVE_STACKTRACE) GLOG_NO_EXPORT int GetStackTrace(void** result, int max_depth, int skip_count); #endif } } #endif #include "stacktrace.h" #if defined(STACKTRACE_H) # include STACKTRACE_H #endif
#include "stacktrace.h" #include <cstdio> #include <cstdlib> #include "base/commandlineflags.h" #include "config.h" #include "glog/logging.h" #include "utilities.h" #ifdef HAVE_EXECINFO_BACKTRACE_SYMBOLS # include <execinfo.h> #endif #ifdef HAVE_STACKTRACE const int BACKTRACE_STEPS = 6; struct AddressRange { const void *start, *end; }; AddressRange expected_range[BACKTRACE_STEPS]; # if __GNUC__ # define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ do { \ (prange)->start = &&start_label; \ (prange)->end = &&end_label; \ CHECK_LT((prange)->start, (prange)->end); \ } while (0) # define DECLARE_ADDRESS_LABEL(a_label) \ a_label: \ do { \ __asm__ __volatile__(""); \ } while (0) # define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ do { \ void* ra = __builtin_return_address(0); \ CHECK_LT((prange)->start, ra); \ if (ra > (prange)->end) { \ printf("Adjusting range from %p..%p to %p..%p\n", (prange)->start, \ (prange)->end, (prange)->start, ra); \ (prange)->end = ra; \ } \ } while (0) # else # define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ do { \ (prange)->start = reinterpret_cast<const void*>(&fn); \ (prange)->end = reinterpret_cast<const char*>(&fn) + 256; \ } while (0) # define DECLARE_ADDRESS_LABEL(a_label) \ do { \ } while (0) # define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ do { \ } while (0) # endif static void CheckRetAddrIsInFunction(void* ret_addr, const AddressRange& range) { CHECK_GE(ret_addr, range.start); CHECK_LE(ret_addr, range.end); } # if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu-label-as-value" # endif void ATTRIBUTE_NOINLINE CheckStackTrace(int); static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf() { const int STACK_LEN = 10; void* stack[STACK_LEN]; int size; ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[1]); INIT_ADDRESS_RANGE(CheckStackTraceLeaf, start, end, &expected_range[0]); DECLARE_ADDRESS_LABEL(start); size = google::GetStackTrace(stack, STACK_LEN, 0); printf("Obtained %d stack frames.\n", size); CHECK_GE(size, 1); CHECK_LE(size, STACK_LEN); if (true) { # ifdef HAVE_EXECINFO_BACKTRACE_SYMBOLS char** strings = backtrace_symbols(stack, size); printf("Obtained %d stack frames.\n", size); for (int i = 0; i < size; i++) { printf("%s %p\n", strings[i], stack[i]); } union { void (*p1)(int); void* p2; } p = {&CheckStackTrace}; printf("CheckStackTrace() addr: %p\n", p.p2); free(strings); # endif } for (int i = 0; i < BACKTRACE_STEPS; i++) { printf("Backtrace %d: expected: %p..%p actual: %p ... ", i, expected_range[i].start, expected_range[i].end, stack[i]); fflush(stdout); CheckRetAddrIsInFunction(stack[i], expected_range[i]); printf("OK\n"); } DECLARE_ADDRESS_LABEL(end); } static void ATTRIBUTE_NOINLINE CheckStackTrace4(int i) { ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[2]); INIT_ADDRESS_RANGE(CheckStackTrace4, start, end, &expected_range[1]); DECLARE_ADDRESS_LABEL(start); for (int j = i; j >= 0; j--) { CheckStackTraceLeaf(); } DECLARE_ADDRESS_LABEL(end); } static void ATTRIBUTE_NOINLINE CheckStackTrace3(int i) { ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[3]); INIT_ADDRESS_RANGE(CheckStackTrace3, start, end, &expected_range[2]); DECLARE_ADDRESS_LABEL(start); for (int j = i; j >= 0; j--) { CheckStackTrace4(j); } DECLARE_ADDRESS_LABEL(end); } static void ATTRIBUTE_NOINLINE CheckStackTrace2(int i) { ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[4]); INIT_ADDRESS_RANGE(CheckStackTrace2, start, end, &expected_range[3]); DECLARE_ADDRESS_LABEL(start); for (int j = i; j >= 0; j--) { CheckStackTrace3(j); } DECLARE_ADDRESS_LABEL(end); } static void ATTRIBUTE_NOINLINE CheckStackTrace1(int i) { ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[5]); INIT_ADDRESS_RANGE(CheckStackTrace1, start, end, &expected_range[4]); DECLARE_ADDRESS_LABEL(start); for (int j = i; j >= 0; j--) { CheckStackTrace2(j); } DECLARE_ADDRESS_LABEL(end); } # ifndef __GNUC__ static # endif void ATTRIBUTE_NOINLINE CheckStackTrace(int i) { INIT_ADDRESS_RANGE(CheckStackTrace, start, end, &expected_range[5]); DECLARE_ADDRESS_LABEL(start); for (int j = i; j >= 0; j--) { CheckStackTrace1(j); } DECLARE_ADDRESS_LABEL(end); } # if defined(__clang__) # pragma clang diagnostic pop # endif int main(int, char** argv) { FLAGS_logtostderr = true; google::InitGoogleLogging(argv[0]); CheckStackTrace(0); printf("PASS\n"); return 0; } #else int main() { # ifdef GLOG_BAZEL_BUILD printf("HAVE_STACKTRACE is expected to be defined in Bazel tests\n"); exit(EXIT_FAILURE); # endif printf("PASS (no stacktrace support)\n"); return 0; } #endif
157
cpp
google/libphonenumber
generate_geocoding_data
tools/cpp/src/cpp-build/generate_geocoding_data.cc
tools/cpp/test/cpp-build/generate_geocoding_data_test.cc
#ifndef I18N_PHONENUMBERS_GENERATE_GEOCODING_DATA_H #define I18N_PHONENUMBERS_GENERATE_GEOCODING_DATA_H #include <string> namespace i18n { namespace phonenumbers { using std::string; string MakeStringLiteral(const string& s); string ReplaceAll(const string& input, const string& pattern, const string& value); int Main(int argc, const char* argv[]); } } #endif #include "cpp-build/generate_geocoding_data.h" #include <dirent.h> #include <errno.h> #include <locale> #include <sys/stat.h> #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstring> #include <iomanip> #include <iterator> #include <map> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "absl/container/btree_map.h" #include "absl/container/btree_set.h" namespace i18n { namespace phonenumbers { using std::map; using std::string; using std::vector; using std::set; using std::pair; template <typename ResourceType> class AutoCloser { public: typedef int (*ReleaseFunction) (ResourceType* resource); AutoCloser(ResourceType** resource, ReleaseFunction release_function) : resource_(resource), release_function_(release_function) {} ~AutoCloser() { Close(); } ResourceType* get_resource() const { return *resource_; } void Close() { if (*resource_) { release_function_(*resource_); *resource_ = NULL; } } private: ResourceType** resource_; ReleaseFunction release_function_; }; enum DirEntryKinds { kFile = 0, kDirectory = 1, }; class DirEntry { public: DirEntry(const char* n, DirEntryKinds k) : name_(n), kind_(k) {} const std::string& name() const { return name_; } DirEntryKinds kind() const { return kind_; } private: std::string name_; DirEntryKinds kind_; }; bool ListDirectory(const string& path, vector<DirEntry>* entries) { entries->clear(); DIR* dir = opendir(path.c_str()); if (!dir) { return false; } AutoCloser<DIR> dir_closer(&dir, closedir); struct dirent *entry; struct stat entry_stat; while (true) { errno = 0; entry = readdir(dir); if (entry == NULL) { return errno == 0; } if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } const string entry_path = path + "/" + entry->d_name; if (stat(entry_path.c_str(), &entry_stat)) { return false; } DirEntryKinds kind = kFile; if (S_ISDIR(entry_stat.st_mode)) { kind = kDirectory; } else if (!S_ISREG(entry_stat.st_mode)) { continue; } entries->push_back(DirEntry(entry->d_name, kind)); } } bool EndsWith(const string& s, const string& suffix) { if (suffix.length() > s.length()) { return false; } return std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } bool StrToInt(const string& s, int32* n) { std::stringstream stream; stream << s; stream >> *n; return !stream.fail(); } bool IntToStr(int32 n, string* s) { std::stringstream stream; stream << n; stream >> *s; return !stream.fail(); } bool ParsePrefixes(const string& path, absl::btree_map<int32, string>* prefixes) { prefixes->clear(); FILE* input = fopen(path.c_str(), "r"); if (!input) { return false; } AutoCloser<FILE> input_closer(&input, fclose); const int kMaxLineLength = 2*1024; vector<char> buffer(kMaxLineLength); vector<char>::iterator begin, end, sep; string prefix, description; int32 prefix_code; while (fgets(&buffer[0], buffer.size(), input)) { begin = buffer.begin(); end = std::find(begin, buffer.end(), '\0'); if (end == begin) { continue; } --end; if (*end != '\n' && !feof(input)) { return false; } for (; begin != end && std::isspace(*begin); ++begin) {} for (; end != begin && std::isspace(*(end - 1)); --end) {} if (begin == end || *begin == '#') { continue; } sep = std::find(begin, end, '|'); if (sep == end) { continue; } prefix = string(begin, sep); if (!StrToInt(prefix, &prefix_code)) { return false; } (*prefixes)[prefix_code] = string(sep + 1, end); } return ferror(input) == 0; } string MakeStringLiteral(const string& s) { std::stringstream buffer; int prev_is_hex = 0; buffer << std::hex << std::setfill('0'); buffer << "\""; for (string::const_iterator it = s.begin(); it != s.end(); ++it) { const char c = *it; if (c >= 32 && c < 127) { if (prev_is_hex == 2) { buffer << "\"\""; } if (c == '\'') { buffer << "\\"; } buffer << c; prev_is_hex = 1; } else { if (prev_is_hex != 0) { buffer << "\"\""; } buffer << "\\x" << std::setw(2) << (c < 0 ? c + 256 : c); prev_is_hex = 2; } } buffer << "\""; return buffer.str(); } void WriteStringLiteral(const string& s, FILE* output) { string literal = MakeStringLiteral(s); fprintf(output, "%s", literal.c_str()); } const char kLicense[] = " " " " " " " " " " " "implied.\n" " " " " "\n"; void WriteLicense(FILE* output) { fprintf(output, "%s", kLicense); } const char kI18NNS[] = "i18n"; const char kPhoneNumbersNS[] = "phonenumbers"; void WriteNSHeader(FILE* output) { fprintf(output, "namespace %s {\n", kI18NNS); fprintf(output, "namespace %s {\n", kPhoneNumbersNS); } void WriteNSFooter(FILE* output) { fprintf(output, "} fprintf(output, "} } void WriteCppHeader(const string& base_name, FILE* output) { fprintf(output, "#include \"phonenumbers/geocoding/%s.h\"\n", base_name.c_str()); fprintf(output, "\n"); fprintf(output, "#include <cstdint>\n"); fprintf(output, "\n"); } void WriteArrayAndSize(const string& name, FILE* output) { fprintf(output, " %s,\n", name.c_str()); fprintf(output, " sizeof(%s)/sizeof(*%s),\n", name.c_str(), name.c_str()); } void WritePrefixDescriptionsDefinition( const string& name, const string& prefixes_name, const string& desc_name, const string& possible_lengths_name, FILE* output) { fprintf(output, "const PrefixDescriptions %s = {\n", name.c_str()); WriteArrayAndSize(prefixes_name, output); fprintf(output, " %s,\n", desc_name.c_str()); WriteArrayAndSize(possible_lengths_name, output); fprintf(output, "};\n"); } void WritePrefixDescriptions(const string& var_name, const absl::btree_map<int, string>& prefixes, FILE* output) { absl::btree_set<int> possible_lengths; const string prefixes_name = var_name + "_prefixes"; fprintf(output, "const int32_t %s[] = {\n", prefixes_name.c_str()); for (absl::btree_map<int, string>::const_iterator it = prefixes.begin(); it != prefixes.end(); ++it) { fprintf(output, " %d,\n", it->first); possible_lengths.insert(static_cast<int>(log10(it->first) + 1)); } fprintf(output, "};\n" "\n"); const string desc_name = var_name + "_descriptions"; fprintf(output, "const char* %s[] = {\n", desc_name.c_str()); for (absl::btree_map<int, string>::const_iterator it = prefixes.begin(); it != prefixes.end(); ++it) { fprintf(output, " "); WriteStringLiteral(it->second, output); fprintf(output, ",\n"); } fprintf(output, "};\n" "\n"); const string possible_lengths_name = var_name + "_possible_lengths"; fprintf(output, "const int32_t %s[] = {\n ", possible_lengths_name.c_str()); for (absl::btree_set<int>::const_iterator it = possible_lengths.begin(); it != possible_lengths.end(); ++it) { fprintf(output, " %d,", *it); } fprintf(output, "\n" "};\n" "\n"); WritePrefixDescriptionsDefinition(var_name, prefixes_name, desc_name, possible_lengths_name, output); fprintf(output, "\n"); } void WritePrefixesDescriptions( const absl::btree_map<string, string>& prefix_var_names, FILE* output) { fprintf(output, "const char* prefix_language_code_pairs[] = {\n"); for (absl::btree_map<string, string>::const_iterator it = prefix_var_names.begin(); it != prefix_var_names.end(); ++it) { fprintf(output, " \"%s\",\n", it->first.c_str()); } fprintf(output, "};\n" "\n" "const PrefixDescriptions* prefixes_descriptions[] = {\n"); for (absl::btree_map<string, string>::const_iterator it = prefix_var_names.begin(); it != prefix_var_names.end(); ++it) { fprintf(output, " &%s,\n", it->second.c_str()); } fprintf(output, "};\n" "\n"); } bool WriteCountryLanguages(const map<int32, set<string> >& languages, FILE* output) { vector<string> country_languages_vars; vector<string> countries; for (map<int32, set<string> >::const_iterator it = languages.begin(); it != languages.end(); ++it) { string country_code; if (!IntToStr(it->first, &country_code)) { return false; } const string country_var = "country_" + country_code; fprintf(output, "const char* %s[] = {\n", country_var.c_str()); for (set<string>::const_iterator it_lang = it->second.begin(); it_lang != it->second.end(); ++it_lang) { fprintf(output, " \"%s\",\n", it_lang->c_str()); } fprintf(output, "};\n" "\n"); const string country_languages_var = country_var + "_languages"; fprintf(output, "const CountryLanguages %s = {\n", country_languages_var.c_str()); WriteArrayAndSize(country_var, output); fprintf(output, "};\n" "\n"); country_languages_vars.push_back(country_languages_var); countries.push_back(country_code); } fprintf(output, "\n" "const CountryLanguages* countries_languages[] = {\n"); for (vector<string>::const_iterator it_languages_var = country_languages_vars.begin(); it_languages_var != country_languages_vars.end(); ++it_languages_var) { fprintf(output, " &%s,\n", it_languages_var->c_str()); } fprintf(output, "};\n" "\n" "const int country_calling_codes[] = {\n"); for (vector<string>::const_iterator it_country = countries.begin(); it_country != countries.end(); ++it_country) { fprintf(output, " %s,\n", it_country->c_str()); } fprintf(output, "};\n" "\n"); return true; } string ReplaceAll(const string& input, const string& pattern, const string& value) { if (pattern.size() == 0) { return input; } string replaced; std::back_insert_iterator<string> output = std::back_inserter(replaced); string::const_iterator begin = input.begin(), end = begin; while (true) { const size_t pos = input.find(pattern, begin - input.begin()); if (pos == string::npos) { std::copy(begin, input.end(), output); break; } end = input.begin() + pos; std::copy(begin, end, output); std::copy(value.begin(), value.end(), output); begin = end + pattern.length(); } return replaced; } void WriteAccessorsDefinitions(const string& accessor_prefix, FILE* output) { string templ = "const int* get$prefix$_country_calling_codes() {\n" " return country_calling_codes;\n" "}\n" "\n" "int get$prefix$_country_calling_codes_size() {\n" " return sizeof(country_calling_codes)\n" " /sizeof(*country_calling_codes);\n" "}\n" "\n" "const CountryLanguages* get$prefix$_country_languages(int index) {\n" " return countries_languages[index];\n" "}\n" "\n" "const char** get$prefix$_prefix_language_code_pairs() {\n" " return prefix_language_code_pairs;\n" "}\n" "\n" "int get$prefix$_prefix_language_code_pairs_size() {\n" " return sizeof(prefix_language_code_pairs)\n" " /sizeof(*prefix_language_code_pairs);\n" "}\n" "\n" "const PrefixDescriptions* get$prefix$_prefix_descriptions(int index) {\n" " return prefixes_descriptions[index];\n" "}\n"; string defs = ReplaceAll(templ, "$prefix$", accessor_prefix); fprintf(output, "%s", defs.c_str()); } bool WriteSource(const string& data_path, const string& base_name, const string& accessor_prefix, FILE* output) { WriteLicense(output); WriteCppHeader(base_name, output); WriteNSHeader(output); fprintf(output, "namespace {\n" "\n"); absl::btree_map<string, string> prefix_vars; map<int32, set<string> > country_languages; vector<DirEntry> entries; if (!ListDirectory(data_path, &entries)) { fprintf(stderr, "failed to read directory entries"); return false; } for (vector<DirEntry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { if (it->kind() != kDirectory) { continue; } const string dir_path = data_path + "/" + it->name(); vector<DirEntry> files; if (!ListDirectory(dir_path, &files)) { fprintf(stderr, "failed to read file entries\n"); return false; } for (vector<DirEntry>::const_iterator it_files = files.begin(); it_files != files.end(); ++it_files) { const string fname = it_files->name(); if (!EndsWith(fname, ".txt")) { continue; } int32 country_code; const string country_code_str = fname.substr(0, fname.length() - 4); if (!StrToInt(country_code_str, &country_code)) { return false; } const string path = dir_path + "/" + fname; absl::btree_map<int32, string> prefixes; if (!ParsePrefixes(path, &prefixes)) { return false; } const string prefix_var = "prefix_" + country_code_str + "_" + it->name(); WritePrefixDescriptions(prefix_var, prefixes, output); prefix_vars[country_code_str + "_" + it->name()] = prefix_var; country_languages[country_code].insert(it->name()); } } WritePrefixesDescriptions(prefix_vars, output); if (!WriteCountryLanguages(country_languages, output)) { return false; } fprintf(output, "} fprintf(output, "\n"); WriteAccessorsDefinitions(accessor_prefix, output); WriteNSFooter(output); return ferror(output) == 0; } int PrintHelp(const string& message) { fprintf(stderr, "error: %s\n", message.c_str()); fprintf(stderr, "generate_geocoding_data DATADIR CCPATH"); return 1; } int Main(int argc, const char* argv[]) { if (argc < 2) { return PrintHelp("geocoding data root directory expected"); } if (argc < 3) { return PrintHelp("output source path expected"); } string accessor_prefix = ""; if (argc > 3) { accessor_prefix = argv[3]; } const string root_path(argv[1]); string source_path(argv[2]); std::replace(source_path.begin(), source_path.end(), '\\', '/'); string base_name = source_path; if (base_name.rfind('/') != string::npos) { base_name = base_name.substr(base_name.rfind('/') + 1); } base_name = base_name.substr(0, base_name.rfind('.')); FILE* source_fp = fopen(source_path.c_str(), "w"); if (!source_fp) { fprintf(stderr, "failed to open %s\n", source_path.c_str()); return 1; } AutoCloser<FILE> source_closer(&source_fp, fclose); if (!WriteSource(root_path, base_name, accessor_prefix, source_fp)) { return 1; } return 0; } } }
#include "cpp-build/generate_geocoding_data.h" #include <gtest/gtest.h> namespace i18n { namespace phonenumbers { TEST(GenerateGeocodingDataTest, TestMakeStringLiteral) { EXPECT_EQ("\"\"", MakeStringLiteral("")); EXPECT_EQ("\"Op\"\"\\xc3\"\"\\xa9\"\"ra\"", MakeStringLiteral("Op\xc3\xa9ra")); } TEST(GenerateGeocodingDataTest, TestReplaceAll) { EXPECT_EQ("", ReplaceAll("", "$input$", "cc")); EXPECT_EQ("accb", ReplaceAll("a$input$b", "$input$", "cc")); EXPECT_EQ("ab", ReplaceAll("a$input$b", "$input$", "")); EXPECT_EQ("ab", ReplaceAll("ab", "", "cc")); EXPECT_EQ("acdc", ReplaceAll("a$input$d$input$", "$input$", "c")); } } }
158
cpp
google/libphonenumber
asyoutypeformatter
cpp/src/phonenumbers/asyoutypeformatter.cc
cpp/test/phonenumbers/asyoutypeformatter_test.cc
#ifndef I18N_PHONENUMBERS_ASYOUTYPEFORMATTER_H_ #define I18N_PHONENUMBERS_ASYOUTYPEFORMATTER_H_ #include <list> #include <string> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/regexp_adapter.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/unicodestring.h" namespace i18n { namespace phonenumbers { using std::list; class PhoneNumberUtil; class AsYouTypeFormatter { public: AsYouTypeFormatter(const AsYouTypeFormatter&) = delete; AsYouTypeFormatter& operator=(const AsYouTypeFormatter&) = delete; ~AsYouTypeFormatter() {} const string& InputDigit(char32 next_char, string* result); const string& InputDigitAndRememberPosition(char32 next_char, string* result); int GetRememberedPosition() const; void Clear(); private: explicit AsYouTypeFormatter(const string& region_code); const PhoneMetadata* GetMetadataForRegion(const string& region_code) const; bool MaybeCreateNewTemplate(); void GetAvailableFormats(const string& leading_digits); void NarrowDownPossibleFormats(const string& leading_digits); void SetShouldAddSpaceAfterNationalPrefix(const NumberFormat& format); bool CreateFormattingTemplate(const NumberFormat& format); void GetFormattingTemplate(const string& number_pattern, const string& number_format, UnicodeString* formatting_template); void InputDigitWithOptionToRememberPosition(char32 next_char, bool remember_position, string* phone_number); void AttemptToChoosePatternWithPrefixExtracted(string* formatted_number); const string& GetExtractedNationalPrefix() const; bool AbleToExtractLongerNdd(); void AttemptToFormatAccruedDigits(string* formatted_number); void AppendNationalNumber(const string& national_number, string* phone_number) const; void AttemptToChooseFormattingPattern(string* formatted_number); void InputAccruedNationalNumber(string* number); bool IsNanpaNumberWithNationalPrefix() const; void RemoveNationalPrefixFromNationalNumber(string* national_prefix); bool AttemptToExtractIdd(); bool AttemptToExtractCountryCode(); char NormalizeAndAccrueDigitsAndPlusSign(char32 next_char, bool remember_position); void InputDigitHelper(char next_char, string* number); static int ConvertUnicodeStringPosition(const UnicodeString& s, int pos); const scoped_ptr<const AbstractRegExpFactory> regexp_factory_; RegExpCache regexp_cache_; string current_output_; UnicodeString formatting_template_; string current_formatting_pattern_; UnicodeString accrued_input_; UnicodeString accrued_input_without_formatting_; bool able_to_format_; bool input_has_formatting_; bool is_complete_number_; bool is_expecting_country_code_; const PhoneNumberUtil& phone_util_; const string default_country_; const PhoneMetadata empty_metadata_; const PhoneMetadata* const default_metadata_; const PhoneMetadata* current_metadata_; int last_match_position_; int original_position_; int position_to_remember_; string prefix_before_national_number_; bool should_add_space_after_national_prefix_; string extracted_national_prefix_; string national_number_; list<const NumberFormat*> possible_formats_; friend class PhoneNumberUtil; friend class AsYouTypeFormatterTest; }; } } #endif #include "phonenumbers/asyoutypeformatter.h" #include <math.h> #include <cctype> #include <list> #include <string> #include <google/protobuf/message_lite.h> #include "phonenumbers/base/logging.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/regexp_factory.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/unicodestring.h" namespace i18n { namespace phonenumbers { using google::protobuf::RepeatedPtrField; namespace { const char kPlusSign = '+'; const size_t kMinLeadingDigitsLength = 3; const char kDigitPlaceholder[] = "\xE2\x80\x88"; const char kSeparatorBeforeNationalNumber = ' '; const char kNationalPrefixSeparatorsPattern[] = "[- ]"; void MatchAllGroups(const string& pattern, const string& input, const AbstractRegExpFactory& regexp_factory, RegExpCache* cache, string* group) { DCHECK(cache); DCHECK(group); string new_pattern(pattern); strrmm(&new_pattern, "()"); new_pattern = StrCat("(", new_pattern, ")"); const scoped_ptr<RegExpInput> consume_input( regexp_factory.CreateInput(input)); bool status = cache->GetRegExp(new_pattern).Consume(consume_input.get(), group); DCHECK(status); IGNORE_UNUSED(status); } PhoneMetadata CreateEmptyMetadata() { PhoneMetadata metadata; metadata.set_international_prefix("NA"); return metadata; } } AsYouTypeFormatter::AsYouTypeFormatter(const string& region_code) : regexp_factory_(new RegExpFactory()), regexp_cache_(*regexp_factory_.get(), 64), current_output_(), formatting_template_(), current_formatting_pattern_(), accrued_input_(), accrued_input_without_formatting_(), able_to_format_(true), input_has_formatting_(false), is_complete_number_(false), is_expecting_country_code_(false), phone_util_(*PhoneNumberUtil::GetInstance()), default_country_(region_code), empty_metadata_(CreateEmptyMetadata()), default_metadata_(GetMetadataForRegion(region_code)), current_metadata_(default_metadata_), last_match_position_(0), original_position_(0), position_to_remember_(0), prefix_before_national_number_(), should_add_space_after_national_prefix_(false), extracted_national_prefix_(), national_number_(), possible_formats_() { } const PhoneMetadata* AsYouTypeFormatter::GetMetadataForRegion( const string& region_code) const { int country_calling_code = phone_util_.GetCountryCodeForRegion(region_code); string main_country; phone_util_.GetRegionCodeForCountryCode(country_calling_code, &main_country); const PhoneMetadata* const metadata = phone_util_.GetMetadataForRegion(main_country); if (metadata) { return metadata; } return &empty_metadata_; } bool AsYouTypeFormatter::MaybeCreateNewTemplate() { for (list<const NumberFormat*>::const_iterator it = possible_formats_.begin(); it != possible_formats_.end(); ++it) { DCHECK(*it); const NumberFormat& number_format = **it; const string& pattern = number_format.pattern(); if (current_formatting_pattern_ == pattern) { return false; } if (CreateFormattingTemplate(number_format)) { current_formatting_pattern_ = pattern; SetShouldAddSpaceAfterNationalPrefix(number_format); last_match_position_ = 0; return true; } } able_to_format_ = false; return false; } void AsYouTypeFormatter::GetAvailableFormats(const string& leading_digits) { bool is_international_number = is_complete_number_ && extracted_national_prefix_.empty(); const RepeatedPtrField<NumberFormat>& format_list = (is_international_number && current_metadata_->intl_number_format().size() > 0) ? current_metadata_->intl_number_format() : current_metadata_->number_format(); for (RepeatedPtrField<NumberFormat>::const_iterator it = format_list.begin(); it != format_list.end(); ++it) { if (!extracted_national_prefix_.empty() && phone_util_.FormattingRuleHasFirstGroupOnly( it->national_prefix_formatting_rule()) && !it->national_prefix_optional_when_formatting() && !it->has_domestic_carrier_code_formatting_rule()) { continue; } else if (extracted_national_prefix_.empty() && !is_complete_number_ && !phone_util_.FormattingRuleHasFirstGroupOnly( it->national_prefix_formatting_rule()) && !it->national_prefix_optional_when_formatting()) { continue; } if (phone_util_.IsFormatEligibleForAsYouTypeFormatter(it->format())) { possible_formats_.push_back(&*it); } } NarrowDownPossibleFormats(leading_digits); } void AsYouTypeFormatter::NarrowDownPossibleFormats( const string& leading_digits) { const int index_of_leading_digits_pattern = static_cast<int>(leading_digits.length() - kMinLeadingDigitsLength); for (list<const NumberFormat*>::iterator it = possible_formats_.begin(); it != possible_formats_.end(); ) { DCHECK(*it); const NumberFormat& format = **it; if (format.leading_digits_pattern_size() == 0) { ++it; continue; } int last_leading_digits_pattern = format.leading_digits_pattern_size() - 1; if (last_leading_digits_pattern > index_of_leading_digits_pattern) last_leading_digits_pattern = index_of_leading_digits_pattern; const scoped_ptr<RegExpInput> input( regexp_factory_->CreateInput(leading_digits)); if (!regexp_cache_.GetRegExp(format.leading_digits_pattern().Get( last_leading_digits_pattern)).Consume(input.get())) { it = possible_formats_.erase(it); continue; } ++it; } } void AsYouTypeFormatter::SetShouldAddSpaceAfterNationalPrefix( const NumberFormat& format) { static const scoped_ptr<const RegExp> national_prefix_separators_pattern( regexp_factory_->CreateRegExp(kNationalPrefixSeparatorsPattern)); should_add_space_after_national_prefix_ = national_prefix_separators_pattern->PartialMatch( format.national_prefix_formatting_rule()); } bool AsYouTypeFormatter::CreateFormattingTemplate(const NumberFormat& format) { string number_pattern = format.pattern(); string number_format = format.format(); formatting_template_.remove(); UnicodeString temp_template; GetFormattingTemplate(number_pattern, number_format, &temp_template); if (temp_template.length() > 0) { formatting_template_.append(temp_template); return true; } return false; } void AsYouTypeFormatter::GetFormattingTemplate( const string& number_pattern, const string& number_format, UnicodeString* formatting_template) { DCHECK(formatting_template); static const char longest_phone_number[] = "999999999999999"; string a_phone_number; MatchAllGroups(number_pattern, longest_phone_number, *regexp_factory_, &regexp_cache_, &a_phone_number); if (a_phone_number.length() < national_number_.length()) { formatting_template->remove(); return; } regexp_cache_.GetRegExp(number_pattern).GlobalReplace( &a_phone_number, number_format); GlobalReplaceSubstring("9", kDigitPlaceholder, &a_phone_number); formatting_template->setTo(a_phone_number.c_str(), a_phone_number.size()); } void AsYouTypeFormatter::Clear() { current_output_.clear(); accrued_input_.remove(); accrued_input_without_formatting_.remove(); formatting_template_.remove(); last_match_position_ = 0; current_formatting_pattern_.clear(); prefix_before_national_number_.clear(); extracted_national_prefix_.clear(); national_number_.clear(); able_to_format_ = true; input_has_formatting_ = false; position_to_remember_ = 0; original_position_ = 0; is_complete_number_ = false; is_expecting_country_code_ = false; possible_formats_.clear(); should_add_space_after_national_prefix_ = false; if (current_metadata_ != default_metadata_) { current_metadata_ = GetMetadataForRegion(default_country_); } } const string& AsYouTypeFormatter::InputDigit(char32 next_char, string* result) { DCHECK(result); InputDigitWithOptionToRememberPosition(next_char, false, &current_output_); result->assign(current_output_); return *result; } const string& AsYouTypeFormatter::InputDigitAndRememberPosition( char32 next_char, string* result) { DCHECK(result); InputDigitWithOptionToRememberPosition(next_char, true, &current_output_); result->assign(current_output_); return *result; } void AsYouTypeFormatter::InputDigitWithOptionToRememberPosition( char32 next_char, bool remember_position, string* phone_number) { DCHECK(phone_number); accrued_input_.append(next_char); if (remember_position) { original_position_ = accrued_input_.length(); } string next_char_string; UnicodeString(next_char).toUTF8String(next_char_string); char normalized_next_char = '\0'; if (!(phone_util_.ContainsOnlyValidDigits(next_char_string) || (accrued_input_.length() == 1 && next_char == kPlusSign))) { able_to_format_ = false; input_has_formatting_ = true; } else { normalized_next_char = NormalizeAndAccrueDigitsAndPlusSign(next_char, remember_position); } if (!able_to_format_) { if (input_has_formatting_) { phone_number->clear(); accrued_input_.toUTF8String(*phone_number); } else if (AttemptToExtractIdd()) { if (AttemptToExtractCountryCode()) { AttemptToChoosePatternWithPrefixExtracted(phone_number); return; } } else if (AbleToExtractLongerNdd()) { prefix_before_national_number_.push_back(kSeparatorBeforeNationalNumber); AttemptToChoosePatternWithPrefixExtracted(phone_number); return; } phone_number->clear(); accrued_input_.toUTF8String(*phone_number); return; } switch (accrued_input_without_formatting_.length()) { case 0: case 1: case 2: phone_number->clear(); accrued_input_.toUTF8String(*phone_number); return; case 3: if (AttemptToExtractIdd()) { is_expecting_country_code_ = true; } else { RemoveNationalPrefixFromNationalNumber(&extracted_national_prefix_); AttemptToChooseFormattingPattern(phone_number); return; } default: if (is_expecting_country_code_) { if (AttemptToExtractCountryCode()) { is_expecting_country_code_ = false; } phone_number->assign(prefix_before_national_number_); phone_number->append(national_number_); return; } if (possible_formats_.size() > 0) { string temp_national_number; InputDigitHelper(normalized_next_char, &temp_national_number); string formatted_number; AttemptToFormatAccruedDigits(&formatted_number); if (formatted_number.length() > 0) { phone_number->assign(formatted_number); return; } NarrowDownPossibleFormats(national_number_); if (MaybeCreateNewTemplate()) { InputAccruedNationalNumber(phone_number); return; } if (able_to_format_) { AppendNationalNumber(temp_national_number, phone_number); } else { phone_number->clear(); accrued_input_.toUTF8String(*phone_number); } return; } else { AttemptToChooseFormattingPattern(phone_number); } } } void AsYouTypeFormatter::AttemptToChoosePatternWithPrefixExtracted( string* formatted_number) { able_to_format_ = true; is_expecting_country_code_ = false; possible_formats_.clear(); last_match_position_ = 0; formatting_template_.remove(); current_formatting_pattern_.clear(); AttemptToChooseFormattingPattern(formatted_number); } const string& AsYouTypeFormatter::GetExtractedNationalPrefix() const { return extracted_national_prefix_; } bool AsYouTypeFormatter::AbleToExtractLongerNdd() { if (extracted_national_prefix_.length() > 0) { national_number_.insert(0, extracted_national_prefix_); int index_of_previous_ndd = static_cast<int>( prefix_before_national_number_.find_last_of(extracted_national_prefix_)); prefix_before_national_number_.resize(index_of_previous_ndd); } string new_national_prefix; RemoveNationalPrefixFromNationalNumber(&new_national_prefix); return extracted_national_prefix_ != new_national_prefix; } void AsYouTypeFormatter::AttemptToFormatAccruedDigits( string* formatted_result) { DCHECK(formatted_result); for (list<const NumberFormat*>::const_iterator it = possible_formats_.begin(); it != possible_formats_.end(); ++it) { DCHECK(*it); const NumberFormat& number_format = **it; const string& pattern = number_format.pattern(); if (regexp_cache_.GetRegExp(pattern).FullMatch(national_number_)) { SetShouldAddSpaceAfterNationalPrefix(number_format); string formatted_number(national_number_); bool status = regexp_cache_.GetRegExp(pattern).GlobalReplace( &formatted_number, number_format.format()); DCHECK(status); IGNORE_UNUSED(status); string full_output(*formatted_result); AppendNationalNumber(formatted_number, &full_output); phone_util_.NormalizeDiallableCharsOnly(&full_output); string accrued_input_without_formatting_stdstring; accrued_input_without_formatting_.toUTF8String( accrued_input_without_formatting_stdstring); if (full_output == accrued_input_without_formatting_stdstring) { AppendNationalNumber(formatted_number, formatted_result); return; } } } } int AsYouTypeFormatter::GetRememberedPosition() const { UnicodeString current_output(current_output_.c_str()); if (!able_to_format_) { return ConvertUnicodeStringPosition(current_output, original_position_); } int accrued_input_index = 0; int current_output_index = 0; while (accrued_input_index < position_to_remember_ && current_output_index < current_output.length()) { if (accrued_input_without_formatting_[accrued_input_index] == current_output[current_output_index]) { ++accrued_input_index; } ++current_output_index; } return ConvertUnicodeStringPosition(current_output, current_output_index); } void AsYouTypeFormatter::AppendNationalNumber(const string& national_number, string* phone_number) const { int prefix_before_national_number_length = static_cast<int>(prefix_before_national_number_.size()); if (should_add_space_after_national_prefix_ && prefix_before_national_number_length > 0 && prefix_before_national_number_.at( prefix_before_national_number_length - 1) != kSeparatorBeforeNationalNumber) { phone_number->assign(prefix_before_national_number_); phone_number->push_back(kSeparatorBeforeNationalNumber); StrAppend(phone_number, national_number); } else { phone_number->assign( StrCat(prefix_before_national_number_, national_number)); } } void AsYouTypeFormatter::AttemptToChooseFormattingPattern( string* formatted_number) { DCHECK(formatted_number); if (national_number_.length() >= kMinLeadingDigitsLength) { GetAvailableFormats(national_number_); formatted_number->clear(); AttemptToFormatAccruedDigits(formatted_number); if (formatted_number->length() > 0) { return; } if (MaybeCreateNewTemplate()) { InputAccruedNationalNumber(formatted_number); } else { formatted_number->clear(); accrued_input_.toUTF8String(*formatted_number); } return; } else { AppendNationalNumber(national_number_, formatted_number); } } void AsYouTypeFormatter::InputAccruedNationalNumber(string* number) { DCHECK(number); int length_of_national_number = static_cast<int>(national_number_.length()); if (length_of_national_number > 0) { string temp_national_number; for (int i = 0; i < length_of_national_number; ++i) { temp_national_number.clear(); InputDigitHelper(national_number_[i], &temp_national_number); } if (able_to_format_) { AppendNationalNumber(temp_national_number, number); } else { number->clear(); accrued_input_.toUTF8String(*number); } return; } else { number->assign(prefix_before_national_number_); } } bool AsYouTypeFormatter::IsNanpaNumberWithNationalPrefix() const {
#include "phonenumbers/asyoutypeformatter.h" #include <gtest/gtest.h> #include "phonenumbers/base/logging.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { class PhoneMetadata; class AsYouTypeFormatterTest : public testing::Test { public: AsYouTypeFormatterTest(const AsYouTypeFormatterTest&) = delete; AsYouTypeFormatterTest& operator=(const AsYouTypeFormatterTest&) = delete; protected: AsYouTypeFormatterTest() : phone_util_(*PhoneNumberUtil::GetInstance()) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } const PhoneMetadata* GetCurrentMetadata() const { return formatter_->current_metadata_; } const string& GetExtractedNationalPrefix() const { return formatter_->GetExtractedNationalPrefix(); } int ConvertUnicodeStringPosition(const UnicodeString& s, int pos) const { return AsYouTypeFormatter::ConvertUnicodeStringPosition(s, pos); } const PhoneNumberUtil& phone_util_; scoped_ptr<AsYouTypeFormatter> formatter_; string result_; }; TEST_F(AsYouTypeFormatterTest, ConvertUnicodeStringPosition) { EXPECT_EQ(-1, ConvertUnicodeStringPosition(UnicodeString("12345"), 10)); EXPECT_EQ(3, ConvertUnicodeStringPosition(UnicodeString("12345"), 3)); EXPECT_EQ(0, ConvertUnicodeStringPosition( UnicodeString("\xEF\xBC\x95" ), 0)); EXPECT_EQ(4, ConvertUnicodeStringPosition( UnicodeString("0\xEF\xBC\x95""3" ), 2)); EXPECT_EQ(5, ConvertUnicodeStringPosition( UnicodeString("0\xEF\xBC\x95""3" ), 3)); } TEST_F(AsYouTypeFormatterTest, Constructor) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_TRUE(GetCurrentMetadata() != NULL); } TEST_F(AsYouTypeFormatterTest, InvalidPlusSign) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GetUnknown())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+48 ", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+48 88 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+48 88 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48881231+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+48881231+2", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, TooLongNumberMatchingMultipleLeadingDigits) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GetUnknown())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+81 90", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+81 90 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 90 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 90 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+81 90 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+81 90 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+81 90 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+81 90 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+81 90 1234 5678", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 90 12 345 6789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+81901234567890", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+819012345678901", formatter_->InputDigit('1', &result_)); } TEST_F(AsYouTypeFormatterTest, CountryWithSpaceInNationalPrefixFormattingRule) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::BY())); EXPECT_EQ("8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("881", formatter_->InputDigit('1', &result_)); EXPECT_EQ("8 819", formatter_->InputDigit('9', &result_)); EXPECT_EQ("8 8190", formatter_->InputDigit('0', &result_)); EXPECT_EQ("881 901", formatter_->InputDigit('1', &result_)); EXPECT_EQ("8 819 012", formatter_->InputDigit('2', &result_)); EXPECT_EQ("88190123", formatter_->InputDigit('3', &result_)); } TEST_F(AsYouTypeFormatterTest, CountryWithSpaceInNationalPrefixFormattingRuleAndLongNdd) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::BY())); EXPECT_EQ("9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("99", formatter_->InputDigit('9', &result_)); EXPECT_EQ("999", formatter_->InputDigit('9', &result_)); EXPECT_EQ("9999", formatter_->InputDigit('9', &result_)); EXPECT_EQ("99999 ", formatter_->InputDigit('9', &result_)); EXPECT_EQ("99999 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("99999 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("99999 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("99999 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("99999 12 345", formatter_->InputDigit('5', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_US) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("650 2532", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 253 2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("16", formatter_->InputDigit('6', &result_)); EXPECT_EQ("1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 44 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 44 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("011 44 61", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 44 6 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 44 6 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 44 6 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 44 6 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 44 6 123 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 44 6 123 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 44 6 123 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 44 6 123 123 123", formatter_->InputDigit('3', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("011 54 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 54 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("011 54 91", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 54 9 11 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 54 9 11 231", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11 2312", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 54 9 11 2312 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11 2312 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 54 9 11 2312 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 54 9 11 2312 1234", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 24", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 244 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 244 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 244 28", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011 244 280", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000 0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000 00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000 000", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+48 ", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+48 88 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+48 88 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+48 88 123 12 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 123 12 12", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_USFullWidthCharacters) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("\xEF\xBC\x96" , formatter_->InputDigit(UnicodeString("\xEF\xBC\x96" )[0], &result_)); EXPECT_EQ("\xEF\xBC\x96\xEF\xBC\x95" , formatter_->InputDigit(UnicodeString("\xEF\xBC\x95" )[0], &result_)); EXPECT_EQ("650", formatter_->InputDigit(UnicodeString("\xEF\xBC\x90" )[0], &result_)); EXPECT_EQ("650 2", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 25", formatter_->InputDigit(UnicodeString("\xEF\xBC\x95" )[0], &result_)); EXPECT_EQ("650 253", formatter_->InputDigit(UnicodeString("\xEF\xBC\x93" )[0], &result_)); EXPECT_EQ("650 2532", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 253 22", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 253 222", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 253 2222", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_USMobileShortCode) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("*", formatter_->InputDigit('*', &result_)); EXPECT_EQ("*1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("*12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("*121", formatter_->InputDigit('1', &result_)); EXPECT_EQ("*121#", formatter_->InputDigit('#', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_USVanityNumber) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("80", formatter_->InputDigit('0', &result_)); EXPECT_EQ("800", formatter_->InputDigit('0', &result_)); EXPECT_EQ("800 ", formatter_->InputDigit(' ', &result_)); EXPECT_EQ("800 M", formatter_->InputDigit('M', &result_)); EXPECT_EQ("800 MY", formatter_->InputDigit('Y', &result_)); EXPECT_EQ("800 MY ", formatter_->InputDigit(' ', &result_)); EXPECT_EQ("800 MY A", formatter_->InputDigit('A', &result_)); EXPECT_EQ("800 MY AP", formatter_->InputDigit('P', &result_)); EXPECT_EQ("800 MY APP", formatter_->InputDigit('P', &result_)); EXPECT_EQ("800 MY APPL", formatter_->InputDigit('L', &result_)); EXPECT_EQ("800 MY APPLE", formatter_->InputDigit('E', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTFAndRememberPositionUS) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("1", formatter_->InputDigitAndRememberPosition('1', &result_)); EXPECT_EQ(1, formatter_->GetRememberedPosition()); EXPECT_EQ("16", formatter_->InputDigit('6', &result_)); EXPECT_EQ("1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ(1, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650", formatter_->InputDigitAndRememberPosition('0', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253 222", formatter_->InputDigitAndRememberPosition('2', &result_)); EXPECT_EQ(13, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253 2222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(13, formatter_->GetRememberedPosition()); EXPECT_EQ("165025322222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(10, formatter_->GetRememberedPosition()); EXPECT_EQ("1650253222222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(10, formatter_->GetRememberedPosition()); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("16", formatter_->InputDigitAndRememberPosition('6', &result_)); EXPECT_EQ(2, formatter_->GetRememberedPosition()); EXPECT_EQ("1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 2222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("165025322222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(2, formatter_->GetRememberedPosition()); EXPECT_EQ("1650253222222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(2, formatter_->GetRememberedPosition()); formatter_->Clear(); EXPECT_EQ("6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("650 2532", formatter_->InputDigitAndRememberPosition('2', &result_)); EXPECT_EQ(8, formatter_->GetRememberedPosition()); EXPECT_EQ("650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ(9, formatter_->GetRememberedPosition()); EXPECT_EQ("650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650253222;", formatter_->InputDigit(';', &result_)); EXPECT_EQ(7, formatter_->GetRememberedPosition()); EXPECT_EQ("650253222;2", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("650-", formatter_->InputDigit('-', &result_)); EXPECT_EQ("650-2", formatter_->InputDigitAndRememberPosition('2', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("650-25", formatter_->InputDigit('5', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("650-253", formatter_->InputDigit('3', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("650-253-", formatter_->InputDigit('-', &result_)); EXPECT_EQ("650-253-2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650-253-22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650-253-222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650-253-2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 4", formatter_->InputDigitAndRememberPosition('4', &result_)); EXPECT_EQ("011 48 ", formatter_->InputDigit('8', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("011 48 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("011 48 88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011 48 88 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 48 88 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("011 48 88 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 48 88 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 48 88 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 48 88 123 12 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 48 88 123 12 12", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+1 6", formatter_->InputDigitAndRememberPosition('6', &result_)); EXPECT_EQ("+1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650 253", formatter_->InputDigitAndRememberPosition('3', &result_)); EXPECT_EQ("+1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(10, formatter_->GetRememberedPosition()); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+1 6", formatter_->InputDigitAndRememberPosition('6', &result_)); EXPECT_EQ("+1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1650253222;", formatter_->InputDigit(';', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); } TEST_F(AsYouTypeFormatterTest, AYTF_GBFixedLine) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GB())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("020", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 7", formatter_->InputDigitAndRememberPosition('7', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("020 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("020 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("020 7031 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("020 7031 30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 7031 300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 7031 3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_GBTollFree) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GB())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08", formatter_->InputDigit('8', &result_)); EXPECT_EQ("080", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("080 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ("080 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("080 7031 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("080 7031 30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 7031 300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 7031 3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_GBPremiumRate) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GB())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("09", formatter_->InputDigit('9', &result_)); EXPECT_EQ("090", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("090 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ("090 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("090 7031 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("090 7031 30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 7031 300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 7031 3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_NZMobile) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::NZ())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("021", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-112", formatter_->InputDigit('2', &result_)); EXPECT_EQ("02-112 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("02-112 34", formatter_->InputDigit('4', &result_)); EXPECT_EQ("02-112 345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("02-112 3456", formatter_->InputDigit('6', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_DE) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::DE())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("03", formatter_->InputDigit('3', &result_)); EXPECT_EQ("030", formatter_->InputDigit('0', &result_)); EXPECT_EQ("030/1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("030/12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("030/123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("030/1234", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08", formatter_->InputDigit('8', &result_)); EXPECT_EQ("080", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("080 21", formatter_->InputDigit('1', &result_)); EXPECT_EQ("08021 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("08021 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("08021 234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("08021 2345", formatter_->InputDigit('5', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00 1 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("00 1 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("00 1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00 1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00 1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00 1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("00 1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 253 2222", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_AR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AR())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("011 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 7031-3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 7031-30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 7031-300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 7031-3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ARMobile) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AR())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+54 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+54 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+54 91", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+54 9 11 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+54 9 11 231", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11 2312", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+54 9 11 2312 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11 2312 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+54 9 11 2312 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+54 9 11 2312 1234", formatter_->InputDigit('4', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_KR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::KR())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 51", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 51-2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 51-23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 51-234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+82 51-234-5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 51-234-56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 51-234-567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+82 51-234-5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-53", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 2-531", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 2-531-5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-531-56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-531-567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+82 2-531-5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 2-36", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-366", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-3665", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-3665-5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-3665-56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-3665-567", formatter_->InputDigit('7', &result_)); EXPECT_EQ
159
cpp
google/libphonenumber
phonenumbermatch
cpp/src/phonenumbers/phonenumbermatch.cc
cpp/test/phonenumbers/phonenumbermatch_test.cc
#ifndef I18N_PHONENUMBERS_PHONENUMBERMATCH_H_ #define I18N_PHONENUMBERS_PHONENUMBERMATCH_H_ #include <string> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { using std::string; class PhoneNumberMatch { public: PhoneNumberMatch(int start, const string& raw_string, const PhoneNumber& number); PhoneNumberMatch(); PhoneNumberMatch(const PhoneNumberMatch&) = delete; PhoneNumberMatch& operator=(const PhoneNumberMatch&) = delete; ~PhoneNumberMatch() {} const PhoneNumber& number() const; int start() const; int end() const; int length() const; const string& raw_string() const; string ToString() const; void set_start(int start); void set_raw_string(const string& raw_string); void set_number(const PhoneNumber& number); bool Equals(const PhoneNumberMatch& number) const; void CopyFrom(const PhoneNumberMatch& number); private: int start_; string raw_string_; PhoneNumber number_; }; } } #endif #include "phonenumbers/phonenumbermatch.h" #include <string> #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/stringutil.h" namespace i18n { namespace phonenumbers { PhoneNumberMatch::PhoneNumberMatch(int start, const string& raw_string, const PhoneNumber& number) : start_(start), raw_string_(raw_string), number_(number) { } PhoneNumberMatch::PhoneNumberMatch() : start_(-1), raw_string_(""), number_(PhoneNumber::default_instance()) { } const PhoneNumber& PhoneNumberMatch::number() const { return number_; } int PhoneNumberMatch::start() const { return start_; } int PhoneNumberMatch::end() const { return static_cast<int>(start_ + raw_string_.length()); } int PhoneNumberMatch::length() const { return static_cast<int>(raw_string_.length()); } const string& PhoneNumberMatch::raw_string() const { return raw_string_; } void PhoneNumberMatch::set_start(int start) { start_ = start; } void PhoneNumberMatch::set_raw_string(const string& raw_string) { raw_string_ = raw_string; } void PhoneNumberMatch::set_number(const PhoneNumber& number) { number_.CopyFrom(number); } string PhoneNumberMatch::ToString() const { return StrCat("PhoneNumberMatch [", start(), ",", end(), ") ", raw_string_.c_str()); } bool PhoneNumberMatch::Equals(const PhoneNumberMatch& match) const { return ExactlySameAs(match.number_, number_) && match.raw_string_.compare(raw_string_) == 0 && match.start_ == start_; } void PhoneNumberMatch::CopyFrom(const PhoneNumberMatch& match) { raw_string_ = match.raw_string(); start_ = match.start(); number_ = match.number(); } } }
#include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumbermatch.h" #include <gtest/gtest.h> #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { TEST(PhoneNumberMatch, TestGetterMethods) { PhoneNumber number; const int start_index = 10; const string raw_phone_number("1 800 234 45 67"); PhoneNumberMatch match1(start_index, raw_phone_number, number); EXPECT_EQ(start_index, match1.start()); EXPECT_EQ(start_index + static_cast<int>(raw_phone_number.length()), match1.end()); EXPECT_EQ(static_cast<int>(raw_phone_number.length()), match1.length()); EXPECT_EQ(raw_phone_number, match1.raw_string()); EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString()); } TEST(PhoneNumberMatch, TestEquals) { PhoneNumber number; PhoneNumberMatch match1(10, "1 800 234 45 67", number); PhoneNumberMatch match2(10, "1 800 234 45 67", number); match2.set_start(11); ASSERT_FALSE(match1.Equals(match2)); match2.set_start(match1.start()); EXPECT_TRUE(match1.Equals(match2)); PhoneNumber number2; number2.set_raw_input("123"); match2.set_number(number2); ASSERT_FALSE(match1.Equals(match2)); match2.set_number(match1.number()); EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number())); EXPECT_TRUE(match1.Equals(match2)); match2.set_raw_string("123"); ASSERT_FALSE(match1.Equals(match2)); } TEST(PhoneNumberMatch, TestAssignmentOverload) { PhoneNumber number; PhoneNumberMatch match1(10, "1 800 234 45 67", number); PhoneNumberMatch match2; ASSERT_FALSE(match1.Equals(match2)); match2.CopyFrom(match1); ASSERT_TRUE(match1.Equals(match2)); PhoneNumberMatch match3; PhoneNumberMatch match4; match4.CopyFrom(match2); match3.CopyFrom(match2); ASSERT_TRUE(match3.Equals(match4)); ASSERT_TRUE(match4.Equals(match2)); } TEST(PhoneNumberMatch, TestCopyConstructor) { PhoneNumber number; PhoneNumberMatch match1(10, "1 800 234 45 67", number); PhoneNumberMatch match2; match2.CopyFrom(match1); ASSERT_TRUE(match1.Equals(match2)); } } }
160
cpp
google/libphonenumber
regexp_cache
cpp/src/phonenumbers/regexp_cache.cc
cpp/test/phonenumbers/regexp_cache_test.cc
#ifndef I18N_PHONENUMBERS_REGEXP_CACHE_H_ #define I18N_PHONENUMBERS_REGEXP_CACHE_H_ #include <cstddef> #include <string> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/base/synchronization/lock.h" #ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP # include <tr1/unordered_map> #else # include <map> #endif namespace i18n { namespace phonenumbers { using std::string; class AbstractRegExpFactory; class RegExp; class RegExpCache { private: #ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP typedef std::tr1::unordered_map<string, const RegExp*> CacheImpl; #else typedef std::map<string, const RegExp*> CacheImpl; #endif public: explicit RegExpCache(const AbstractRegExpFactory& regexp_factory, size_t min_items); RegExpCache(const RegExpCache&) = delete; RegExpCache& operator=(const RegExpCache&) = delete; ~RegExpCache(); const RegExp& GetRegExp(const string& pattern); private: const AbstractRegExpFactory& regexp_factory_; Lock lock_; scoped_ptr<CacheImpl> cache_impl_; friend class RegExpCacheTest_CacheConstructor_Test; }; } } #endif #include "phonenumbers/regexp_cache.h" #include <cstddef> #include <string> #include <utility> #include "phonenumbers/base/synchronization/lock.h" #include "phonenumbers/regexp_adapter.h" using std::string; namespace i18n { namespace phonenumbers { RegExpCache::RegExpCache(const AbstractRegExpFactory& regexp_factory, size_t min_items) : regexp_factory_(regexp_factory), #ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP cache_impl_(new CacheImpl(min_items)) #else cache_impl_(new CacheImpl()) #endif {} RegExpCache::~RegExpCache() { AutoLock l(lock_); for (CacheImpl::const_iterator it = cache_impl_->begin(); it != cache_impl_->end(); ++it) { delete it->second; } } const RegExp& RegExpCache::GetRegExp(const string& pattern) { AutoLock l(lock_); CacheImpl::const_iterator it = cache_impl_->find(pattern); if (it != cache_impl_->end()) return *it->second; const RegExp* regexp = regexp_factory_.CreateRegExp(pattern); cache_impl_->insert(std::make_pair(pattern, regexp)); return *regexp; } } }
#include <cstddef> #include <string> #include <gtest/gtest.h> #include "phonenumbers/base/synchronization/lock.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/regexp_factory.h" namespace i18n { namespace phonenumbers { using std::string; class RegExpCacheTest : public testing::Test { protected: static constexpr size_t min_items_ = 2; RegExpCacheTest() : cache_(regexp_factory_, min_items_) {} virtual ~RegExpCacheTest() {} RegExpFactory regexp_factory_; RegExpCache cache_; }; TEST_F(RegExpCacheTest, CacheConstructor) { AutoLock l(cache_.lock_); ASSERT_TRUE(cache_.cache_impl_ != NULL); EXPECT_TRUE(cache_.cache_impl_->empty()); } TEST_F(RegExpCacheTest, GetRegExp) { static const string pattern1("foo"); static const string pattern2("foo"); const RegExp& regexp1 = cache_.GetRegExp(pattern1); const RegExp& regexp2 = cache_.GetRegExp(pattern2); EXPECT_TRUE(&regexp1 == &regexp2); } } }
161
cpp
google/libphonenumber
shortnumberinfo
cpp/src/phonenumbers/shortnumberinfo.cc
cpp/test/phonenumbers/shortnumberinfo_test.cc
#ifndef I18N_PHONENUMBERS_SHORTNUMBERINFO_H_ #define I18N_PHONENUMBERS_SHORTNUMBERINFO_H_ #include <list> #include <map> #include <set> #include <string> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "absl/container/flat_hash_set.h" #include "absl/container/flat_hash_map.h" namespace i18n { namespace phonenumbers { using std::list; using std::map; using std::set; using std::string; class MatcherApi; class PhoneMetadata; class PhoneNumber; class PhoneNumberUtil; class ShortNumberInfo { public: ShortNumberInfo(); ShortNumberInfo(const ShortNumberInfo&) = delete; ShortNumberInfo& operator=(const ShortNumberInfo&) = delete; ~ShortNumberInfo(); enum ShortNumberCost { TOLL_FREE, STANDARD_RATE, PREMIUM_RATE, UNKNOWN_COST }; bool IsPossibleShortNumberForRegion( const PhoneNumber& short_number, const string& region_dialing_from) const; bool IsPossibleShortNumber(const PhoneNumber& number) const; bool IsValidShortNumberForRegion( const PhoneNumber& short_number, const string& region_dialing_from) const; bool IsValidShortNumber(const PhoneNumber& number) const; ShortNumberCost GetExpectedCostForRegion( const PhoneNumber& short_number, const string& region_dialing_from) const; ShortNumberCost GetExpectedCost(const PhoneNumber& number) const; string GetExampleShortNumber(const string& region_code) const; string GetExampleShortNumberForCost(const string& region_code, ShortNumberCost cost) const; bool ConnectsToEmergencyNumber(const string& number, const string& region_code) const; bool IsEmergencyNumber(const string& number, const string& region_code) const; bool IsCarrierSpecific(const PhoneNumber& number) const; bool IsCarrierSpecificForRegion( const PhoneNumber& number, const string& region_dialing_from) const; bool IsSmsServiceForRegion( const PhoneNumber& number, const string& region_dialing_from) const; private: const PhoneNumberUtil& phone_util_; const scoped_ptr<const MatcherApi> matcher_api_; scoped_ptr<absl::flat_hash_map<string, PhoneMetadata> > region_to_short_metadata_map_; scoped_ptr<absl::flat_hash_set<string> > regions_where_emergency_numbers_must_be_exact_; const i18n::phonenumbers::PhoneMetadata* GetMetadataForRegion( const string& region_code) const; bool RegionDialingFromMatchesNumber(const PhoneNumber& number, const string& region_dialing_from) const; void GetRegionCodeForShortNumberFromRegionList( const PhoneNumber& number, const list<string>& region_codes, string* region_code) const; bool MatchesEmergencyNumberHelper(const string& number, const string& region_code, bool allow_prefix_match) const; }; } } #endif #include "phonenumbers/shortnumberinfo.h" #include <algorithm> #include <string.h> #include <iterator> #include <map> #include "phonenumbers/default_logger.h" #include "phonenumbers/matcher_api.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/regex_based_matcher.h" #include "phonenumbers/region_code.h" #include "phonenumbers/short_metadata.h" namespace i18n { namespace phonenumbers { using google::protobuf::RepeatedField; using std::map; using std::string; bool LoadCompiledInMetadata(PhoneMetadataCollection* metadata) { if (!metadata->ParseFromArray(short_metadata_get(), short_metadata_size())) { LOG(ERROR) << "Could not parse binary data."; return false; } return true; } ShortNumberInfo::ShortNumberInfo() : phone_util_(*PhoneNumberUtil::GetInstance()), matcher_api_(new RegexBasedMatcher()), region_to_short_metadata_map_(new absl::flat_hash_map<string, PhoneMetadata>()), regions_where_emergency_numbers_must_be_exact_(new absl::flat_hash_set<string>()) { PhoneMetadataCollection metadata_collection; if (!LoadCompiledInMetadata(&metadata_collection)) { LOG(DFATAL) << "Could not parse compiled-in metadata."; return; } for (const auto& metadata : metadata_collection.metadata()) { const string& region_code = metadata.id(); region_to_short_metadata_map_->insert(std::make_pair(region_code, metadata)); } regions_where_emergency_numbers_must_be_exact_->insert("BR"); regions_where_emergency_numbers_must_be_exact_->insert("CL"); regions_where_emergency_numbers_must_be_exact_->insert("NI"); } ShortNumberInfo::~ShortNumberInfo() {} const PhoneMetadata* ShortNumberInfo::GetMetadataForRegion( const string& region_code) const { auto it = region_to_short_metadata_map_->find(region_code); if (it != region_to_short_metadata_map_->end()) { return &it->second; } return nullptr; } namespace { bool MatchesPossibleNumberAndNationalNumber( const MatcherApi& matcher_api, const string& number, const PhoneNumberDesc& desc) { const RepeatedField<int>& lengths = desc.possible_length(); if (desc.possible_length_size() > 0 && std::find(lengths.begin(), lengths.end(), number.length()) == lengths.end()) { return false; } return matcher_api.MatchNationalNumber(number, desc, false); } } bool ShortNumberInfo::RegionDialingFromMatchesNumber(const PhoneNumber& number, const string& region_dialing_from) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); return std::find(region_codes.begin(), region_codes.end(), region_dialing_from) != region_codes.end(); } bool ShortNumberInfo::IsPossibleShortNumberForRegion(const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); if (!phone_metadata) { return false; } string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); const RepeatedField<int>& lengths = phone_metadata->general_desc().possible_length(); return (std::find(lengths.begin(), lengths.end(), short_number.length()) != lengths.end()); } bool ShortNumberInfo::IsPossibleShortNumber(const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); for (const auto& region_code : region_codes) { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); if (!phone_metadata) { continue; } const RepeatedField<int>& lengths = phone_metadata->general_desc().possible_length(); if (std::find(lengths.begin(), lengths.end(), short_number.length()) != lengths.end()) { return true; } } return false; } bool ShortNumberInfo::IsValidShortNumberForRegion( const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); if (!phone_metadata) { return false; } string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); const PhoneNumberDesc& general_desc = phone_metadata->general_desc(); if (!MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, general_desc)) { return false; } const PhoneNumberDesc& short_number_desc = phone_metadata->short_code(); return MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, short_number_desc); } bool ShortNumberInfo::IsValidShortNumber(const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); string region_code; GetRegionCodeForShortNumberFromRegionList(number, region_codes, &region_code); if (region_codes.size() > 1 && region_code != RegionCode::GetUnknown()) { return true; } return IsValidShortNumberForRegion(number, region_code); } ShortNumberInfo::ShortNumberCost ShortNumberInfo::GetExpectedCostForRegion( const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return ShortNumberInfo::UNKNOWN_COST; } const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); if (!phone_metadata) { return ShortNumberInfo::UNKNOWN_COST; } string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); const RepeatedField<int>& lengths = phone_metadata->general_desc().possible_length(); if (std::find(lengths.begin(), lengths.end(), short_number.length()) == lengths.end()) { return ShortNumberInfo::UNKNOWN_COST; } if (MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, phone_metadata->premium_rate())) { return ShortNumberInfo::PREMIUM_RATE; } if (MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, phone_metadata->standard_rate())) { return ShortNumberInfo::STANDARD_RATE; } if (MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, phone_metadata->toll_free())) { return ShortNumberInfo::TOLL_FREE; } if (IsEmergencyNumber(short_number, region_dialing_from)) { return ShortNumberInfo::TOLL_FREE; } return ShortNumberInfo::UNKNOWN_COST; } ShortNumberInfo::ShortNumberCost ShortNumberInfo::GetExpectedCost( const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); if (region_codes.size() == 0) { return ShortNumberInfo::UNKNOWN_COST; } if (region_codes.size() == 1) { return GetExpectedCostForRegion(number, region_codes.front()); } ShortNumberInfo::ShortNumberCost cost = ShortNumberInfo::TOLL_FREE; for (const auto& region_code : region_codes) { ShortNumberInfo::ShortNumberCost cost_for_region = GetExpectedCostForRegion(number, region_code); switch (cost_for_region) { case ShortNumberInfo::PREMIUM_RATE: return ShortNumberInfo::PREMIUM_RATE; case ShortNumberInfo::UNKNOWN_COST: return ShortNumberInfo::UNKNOWN_COST; case ShortNumberInfo::STANDARD_RATE: if (cost != ShortNumberInfo::UNKNOWN_COST) { cost = ShortNumberInfo::STANDARD_RATE; } break; case ShortNumberInfo::TOLL_FREE: break; default: LOG(ERROR) << "Unrecognised cost for region: " << static_cast<int>(cost_for_region); break; } } return cost; } void ShortNumberInfo::GetRegionCodeForShortNumberFromRegionList( const PhoneNumber& number, const list<string>& region_codes, string* region_code) const { if (region_codes.size() == 0) { region_code->assign(RegionCode::GetUnknown()); return; } else if (region_codes.size() == 1) { region_code->assign(region_codes.front()); return; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); for (const auto& region_code_it : region_codes) { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code_it); if (phone_metadata != nullptr && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->short_code())) { region_code->assign(region_code_it); return; } } region_code->assign(RegionCode::GetUnknown()); } string ShortNumberInfo::GetExampleShortNumber(const string& region_code) const { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); if (!phone_metadata) { return ""; } const PhoneNumberDesc& desc = phone_metadata->short_code(); if (desc.has_example_number()) { return desc.example_number(); } return ""; } string ShortNumberInfo::GetExampleShortNumberForCost(const string& region_code, ShortNumberInfo::ShortNumberCost cost) const { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); if (!phone_metadata) { return ""; } const PhoneNumberDesc* desc = nullptr; switch (cost) { case TOLL_FREE: desc = &(phone_metadata->toll_free()); break; case STANDARD_RATE: desc = &(phone_metadata->standard_rate()); break; case PREMIUM_RATE: desc = &(phone_metadata->premium_rate()); break; default: break; } if (desc != nullptr && desc->has_example_number()) { return desc->example_number(); } return ""; } bool ShortNumberInfo::ConnectsToEmergencyNumber(const string& number, const string& region_code) const { return MatchesEmergencyNumberHelper(number, region_code, true ); } bool ShortNumberInfo::IsEmergencyNumber(const string& number, const string& region_code) const { return MatchesEmergencyNumberHelper(number, region_code, false ); } bool ShortNumberInfo::MatchesEmergencyNumberHelper(const string& number, const string& region_code, bool allow_prefix_match) const { string extracted_number; phone_util_.ExtractPossibleNumber(number, &extracted_number); if (phone_util_.StartsWithPlusCharsPattern(extracted_number)) { return false; } const PhoneMetadata* metadata = GetMetadataForRegion(region_code); if (!metadata || !metadata->has_emergency()) { return false; } phone_util_.NormalizeDigitsOnly(&extracted_number); bool allow_prefix_match_for_region = allow_prefix_match && regions_where_emergency_numbers_must_be_exact_->find(region_code) == regions_where_emergency_numbers_must_be_exact_->end(); return matcher_api_->MatchNationalNumber( extracted_number, metadata->emergency(), allow_prefix_match_for_region); } bool ShortNumberInfo::IsCarrierSpecific(const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); string region_code; GetRegionCodeForShortNumberFromRegionList(number, region_codes, &region_code); string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); return phone_metadata && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->carrier_specific()); } bool ShortNumberInfo::IsCarrierSpecificForRegion(const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); return phone_metadata && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->carrier_specific()); } bool ShortNumberInfo::IsSmsServiceForRegion(const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); return phone_metadata && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->sms_services()); } } }
#include "phonenumbers/shortnumberinfo.h" #include <gtest/gtest.h> #include "phonenumbers/base/logging.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { class ShortNumberInfoTest : public testing::Test { public: ShortNumberInfoTest(const ShortNumberInfoTest&) = delete; ShortNumberInfoTest& operator=(const ShortNumberInfoTest&) = delete; protected: PhoneNumber ParseNumberForTesting(const string& number, const string& region_code) { PhoneNumber phone_number; PhoneNumberUtil::ErrorType error_type = phone_util_.Parse( number, region_code, &phone_number); CHECK_EQ(error_type, PhoneNumberUtil::NO_PARSING_ERROR); IGNORE_UNUSED(error_type); return phone_number; } ShortNumberInfoTest() : short_info_() { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } const PhoneNumberUtil phone_util_; const ShortNumberInfo short_info_; }; TEST_F(ShortNumberInfoTest, IsPossibleShortNumber) { PhoneNumber possible_number; possible_number.set_country_code(33); possible_number.set_national_number(uint64{123456}); EXPECT_TRUE(short_info_.IsPossibleShortNumber(possible_number)); EXPECT_TRUE(short_info_.IsPossibleShortNumberForRegion( ParseNumberForTesting("123456", RegionCode::FR()), RegionCode::FR())); PhoneNumber impossible_number; impossible_number.set_country_code(33); impossible_number.set_national_number(uint64{9}); EXPECT_FALSE(short_info_.IsPossibleShortNumber(impossible_number)); PhoneNumber shared_number; shared_number.set_country_code(44); shared_number.set_national_number(uint64{11001}); EXPECT_TRUE(short_info_.IsPossibleShortNumber(shared_number)); } TEST_F(ShortNumberInfoTest, IsValidShortNumber) { PhoneNumber valid_number; valid_number.set_country_code(33); valid_number.set_national_number(uint64{1010}); EXPECT_TRUE(short_info_.IsValidShortNumber(valid_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("1010", RegionCode::FR()), RegionCode::FR())); PhoneNumber invalid_number; invalid_number.set_country_code(33); invalid_number.set_national_number(uint64{123456}); EXPECT_FALSE(short_info_.IsValidShortNumber(invalid_number)); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("123456", RegionCode::FR()), RegionCode::FR())); PhoneNumber shared_number; shared_number.set_country_code(44); shared_number.set_national_number(uint64{18001}); EXPECT_TRUE(short_info_.IsValidShortNumber(shared_number)); } TEST_F(ShortNumberInfoTest, IsCarrierSpecific) { PhoneNumber carrier_specific_number; carrier_specific_number.set_country_code(1); carrier_specific_number.set_national_number(uint64{33669}); EXPECT_TRUE(short_info_.IsCarrierSpecific(carrier_specific_number)); EXPECT_TRUE(short_info_.IsCarrierSpecificForRegion( ParseNumberForTesting("33669", RegionCode::US()), RegionCode::US())); PhoneNumber not_carrier_specific_number; not_carrier_specific_number.set_country_code(1); not_carrier_specific_number.set_national_number(uint64{911}); EXPECT_FALSE(short_info_.IsCarrierSpecific(not_carrier_specific_number)); EXPECT_FALSE(short_info_.IsCarrierSpecificForRegion( ParseNumberForTesting("911", RegionCode::US()), RegionCode::US())); PhoneNumber carrier_specific_number_for_some_region; carrier_specific_number_for_some_region.set_country_code(1); carrier_specific_number_for_some_region.set_national_number(uint64{211}); EXPECT_TRUE(short_info_.IsCarrierSpecific( carrier_specific_number_for_some_region)); EXPECT_TRUE(short_info_.IsCarrierSpecificForRegion( carrier_specific_number_for_some_region, RegionCode::US())); EXPECT_FALSE(short_info_.IsCarrierSpecificForRegion( carrier_specific_number_for_some_region, RegionCode::BB())); } TEST_F(ShortNumberInfoTest, IsSmsService) { PhoneNumber sms_service_number_for_some_region; sms_service_number_for_some_region.set_country_code(1); sms_service_number_for_some_region.set_national_number(uint64{21234}); EXPECT_TRUE(short_info_.IsSmsServiceForRegion( sms_service_number_for_some_region, RegionCode::US())); EXPECT_FALSE(short_info_.IsSmsServiceForRegion( sms_service_number_for_some_region, RegionCode::BB())); } TEST_F(ShortNumberInfoTest, GetExpectedCost) { uint64 national_number; const string& premium_rate_example = short_info_.GetExampleShortNumberForCost( RegionCode::FR(), ShortNumberInfo::PREMIUM_RATE); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(premium_rate_example, RegionCode::FR()), RegionCode::FR())); PhoneNumber premium_rate_number; premium_rate_number.set_country_code(33); safe_strtou64(premium_rate_example, &national_number); premium_rate_number.set_national_number(national_number); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCost(premium_rate_number)); const string& standard_rate_example = short_info_.GetExampleShortNumberForCost( RegionCode::FR(), ShortNumberInfo::STANDARD_RATE); EXPECT_EQ(ShortNumberInfo::STANDARD_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(standard_rate_example, RegionCode::FR()), RegionCode::FR())); PhoneNumber standard_rate_number; standard_rate_number.set_country_code(33); safe_strtou64(standard_rate_example, &national_number); standard_rate_number.set_national_number(national_number); EXPECT_EQ(ShortNumberInfo::STANDARD_RATE, short_info_.GetExpectedCost(standard_rate_number)); const string& toll_free_example = short_info_.GetExampleShortNumberForCost( RegionCode::FR(), ShortNumberInfo::TOLL_FREE); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(toll_free_example, RegionCode::FR()), RegionCode::FR())); PhoneNumber toll_free_number; toll_free_number.set_country_code(33); safe_strtou64(toll_free_example, &national_number); toll_free_number.set_national_number(national_number); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCost(toll_free_number)); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("12345", RegionCode::FR()), RegionCode::FR())); PhoneNumber unknown_cost_number; unknown_cost_number.set_country_code(33); unknown_cost_number.set_national_number(uint64{12345}); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(unknown_cost_number)); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("116123", RegionCode::FR()), RegionCode::FR())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("116123", RegionCode::FR()), RegionCode::FR())); PhoneNumber invalid_number; invalid_number.set_country_code(33); invalid_number.set_national_number(uint64{116123}); EXPECT_FALSE(short_info_.IsValidShortNumber(invalid_number)); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCost(invalid_number)); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("911", RegionCode::US()), RegionCode::ZZ())); unknown_cost_number.Clear(); unknown_cost_number.set_country_code(123); unknown_cost_number.set_national_number(uint64{911}); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(unknown_cost_number)); } TEST_F(ShortNumberInfoTest, GetExpectedCostForSharedCountryCallingCode) { string ambiguous_premium_rate_string("1234"); PhoneNumber ambiguous_premium_rate_number; ambiguous_premium_rate_number.set_country_code(61); ambiguous_premium_rate_number.set_national_number(uint64{1234}); string ambiguous_standard_rate_string("1194"); PhoneNumber ambiguous_standard_rate_number; ambiguous_standard_rate_number.set_country_code(61); ambiguous_standard_rate_number.set_national_number(uint64{1194}); string ambiguous_toll_free_string("733"); PhoneNumber ambiguous_toll_free_number; ambiguous_toll_free_number.set_country_code(61); ambiguous_toll_free_number.set_national_number(uint64{733}); EXPECT_TRUE(short_info_.IsValidShortNumber(ambiguous_premium_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumber(ambiguous_standard_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumber(ambiguous_toll_free_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCost(ambiguous_premium_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_EQ(ShortNumberInfo::STANDARD_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(ambiguous_standard_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::AU()), RegionCode::AU())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::AU()), RegionCode::AU())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(ambiguous_toll_free_number)); } TEST_F(ShortNumberInfoTest, GetExampleShortNumber) { EXPECT_FALSE(short_info_.GetExampleShortNumber(RegionCode::AD()).empty()); EXPECT_FALSE(short_info_.GetExampleShortNumber(RegionCode::FR()).empty()); EXPECT_TRUE(short_info_.GetExampleShortNumber(RegionCode::UN001()).empty()); EXPECT_TRUE( short_info_.GetExampleShortNumber(RegionCode::GetUnknown()).empty()); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_US) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::US())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("112", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberLongNumber_US) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("9116666666", RegionCode::US())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("1126666666", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9996666666", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberWithFormatting_US) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("9-1-1", RegionCode::US())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("1-1-2", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9-9-9", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberWithPlusSign_US) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("+911", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("\xEF\xBC\x8B" "911", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber(" +911", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("+112", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("+999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_BR) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::BR())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("190", RegionCode::BR())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("999", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberLongNumber_BR) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9111", RegionCode::BR())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("1900", RegionCode::BR())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9996", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_CL) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("131", RegionCode::CL())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("133", RegionCode::CL())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberLongNumber_CL) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("1313", RegionCode::CL())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("1330", RegionCode::CL())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_AO) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::AO())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("222123456", RegionCode::AO())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("923123456", RegionCode::AO())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_ZW) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::ZW())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("01312345", RegionCode::ZW())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("0711234567", RegionCode::ZW())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_US) { EXPECT_TRUE(short_info_.IsEmergencyNumber("911", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("112", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumberLongNumber_US) { EXPECT_FALSE(short_info_.IsEmergencyNumber("9116666666", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("1126666666", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("9996666666", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumberWithFormatting_US) { EXPECT_TRUE(short_info_.IsEmergencyNumber("9-1-1", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("*911", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("1-1-2", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("*112", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("9-9-9", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("*999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumberWithPlusSign_US) { EXPECT_FALSE(short_info_.IsEmergencyNumber("+911", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("\xEF\xBC\x8B" "911", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber(" +911", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("+112", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("+999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_BR) { EXPECT_TRUE(short_info_.IsEmergencyNumber("911", RegionCode::BR())); EXPECT_TRUE(short_info_.IsEmergencyNumber("190", RegionCode::BR())); EXPECT_FALSE(short_info_.IsEmergencyNumber("999", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, EmergencyNumberLongNumber_BR) { EXPECT_FALSE(short_info_.IsEmergencyNumber("9111", RegionCode::BR())); EXPECT_FALSE(short_info_.IsEmergencyNumber("1900", RegionCode::BR())); EXPECT_FALSE(short_info_.IsEmergencyNumber("9996", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_AO) { EXPECT_FALSE(short_info_.IsEmergencyNumber("911", RegionCode::AO())); EXPECT_FALSE(short_info_.IsEmergencyNumber("222123456", RegionCode::AO())); EXPECT_FALSE(short_info_.IsEmergencyNumber("923123456", RegionCode::AO())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_ZW) { EXPECT_FALSE(short_info_.IsEmergencyNumber("911", RegionCode::ZW())); EXPECT_FALSE(short_info_.IsEmergencyNumber("01312345", RegionCode::ZW())); EXPECT_FALSE(short_info_.IsEmergencyNumber("0711234567", RegionCode::ZW())); } TEST_F(ShortNumberInfoTest, EmergencyNumberForSharedCountryCallingCode) { EXPECT_TRUE(short_info_.IsEmergencyNumber("112", RegionCode::AU())); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("112", RegionCode::AU()), RegionCode::AU())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("112", RegionCode::AU()), RegionCode::AU())); EXPECT_TRUE(short_info_.IsEmergencyNumber("112", RegionCode::CX())); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("112", RegionCode::CX()), RegionCode::CX())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("112", RegionCode::CX()), RegionCode::CX())); PhoneNumber shared_emergency_number; shared_emergency_number.set_country_code(61); shared_emergency_number.set_national_number(uint64{112}); EXPECT_TRUE(short_info_.IsValidShortNumber(shared_emergency_number)); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCost(shared_emergency_number)); } TEST_F(ShortNumberInfoTest, OverlappingNANPANumber) { EXPECT_TRUE(short_info_.IsEmergencyNumber("211", RegionCode::BB())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("211", RegionCode::BB()), RegionCode::BB())); EXPECT_FALSE(short_info_.IsEmergencyNumber("211", RegionCode::US())); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("211", RegionCode::US()), RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("211", RegionCode::CA())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("211", RegionCode::CA()), RegionCode::CA())); } TEST_F(ShortNumberInfoTest, CountryCallingCodeIsNotIgnored) { EXPECT_FALSE(short_info_.IsPossibleShortNumberForRegion( ParseNumberForTesting("+4640404", RegionCode::SE()), RegionCode::US())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("+4640404", RegionCode::SE()), RegionCode::US())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("+4640404", RegionCode::SE()), RegionCode::US())); } } }
162
cpp
google/libphonenumber
phonenumbermatcher
cpp/src/phonenumbers/phonenumbermatcher.cc
cpp/test/phonenumbers/phonenumbermatcher_test.cc
#ifndef I18N_PHONENUMBERS_PHONENUMBERMATCHER_H_ #define I18N_PHONENUMBERS_PHONENUMBERMATCHER_H_ #include <string> #include <vector> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/callback.h" #include "phonenumbers/regexp_adapter.h" namespace i18n { namespace phonenumbers { template <class R, class A1, class A2, class A3, class A4> class ResultCallback4; using std::string; using std::vector; class AlternateFormats; class NumberFormat; class PhoneNumber; class PhoneNumberMatch; class PhoneNumberMatcherRegExps; class PhoneNumberUtil; class PhoneNumberMatcher { friend class PhoneNumberMatcherTest; public: enum Leniency { POSSIBLE, VALID, STRICT_GROUPING, EXACT_GROUPING, }; PhoneNumberMatcher(const PhoneNumberUtil& util, const string& text, const string& region_code, Leniency leniency, int max_tries); PhoneNumberMatcher(const string& text, const string& region_code); ~PhoneNumberMatcher(); bool HasNext(); bool Next(PhoneNumberMatch* match); private: enum State { NOT_READY, READY, DONE, }; bool IsInputUtf8(); bool Find(int index, PhoneNumberMatch* match); bool IsNationalPrefixPresentIfRequired(const PhoneNumber& number) const; bool ExtractMatch(const string& candidate, int offset, PhoneNumberMatch* match); bool ExtractInnerMatch(const string& candidate, int offset, PhoneNumberMatch* match); bool ParseAndVerify(const string& candidate, int offset, PhoneNumberMatch* match); bool CheckNumberGroupingIsValid( const PhoneNumber& phone_number, const string& candidate, ResultCallback4<bool, const PhoneNumberUtil&, const PhoneNumber&, const string&, const vector<string>&>* checker) const; void GetNationalNumberGroups( const PhoneNumber& number, vector<string>* digit_blocks) const; void GetNationalNumberGroupsForPattern( const PhoneNumber& number, const NumberFormat* formatting_pattern, vector<string>* digit_blocks) const; bool AllNumberGroupsAreExactlyPresent( const PhoneNumberUtil& util, const PhoneNumber& phone_number, const string& normalized_candidate, const vector<string>& formatted_number_groups) const; bool VerifyAccordingToLeniency(Leniency leniency, const PhoneNumber& number, const string& candidate) const; static bool ContainsMoreThanOneSlashInNationalNumber( const PhoneNumber& number, const string& candidate, const PhoneNumberUtil& util); static bool IsLatinLetter(char32 letter); const PhoneNumberMatcherRegExps* reg_exps_; const AlternateFormats* alternate_formats_; const PhoneNumberUtil& phone_util_; const string text_; const string preferred_region_; Leniency leniency_; int max_tries_; State state_; scoped_ptr<PhoneNumberMatch> last_match_; int search_index_; bool is_input_valid_utf8_; DISALLOW_COPY_AND_ASSIGN(PhoneNumberMatcher); }; } } #endif #include "phonenumbers/phonenumbermatcher.h" #ifndef I18N_PHONENUMBERS_USE_ICU_REGEXP #error phonenumbermatcher depends on ICU \ (i.e. I18N_PHONENUMBERS_USE_ICU_REGEXP must be set) #endif #include <ctype.h> #include <stddef.h> #include <limits> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include <unicode/uchar.h> #include "phonenumbers/alternate_format.h" #include "phonenumbers/base/logging.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/base/memory/singleton.h" #include "phonenumbers/callback.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/encoding_utils.h" #include "phonenumbers/normalize_utf8.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/phonenumbermatch.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/regexp_adapter.h" #include "phonenumbers/regexp_adapter_icu.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/utf/unicodetext.h" #ifdef I18N_PHONENUMBERS_USE_RE2 #include "phonenumbers/regexp_adapter_re2.h" #endif using std::map; using std::numeric_limits; using std::string; namespace i18n { namespace phonenumbers { namespace { string Limit(int lower, int upper) { DCHECK_GE(lower, 0); DCHECK_GT(upper, 0); DCHECK_LT(lower, upper); return StrCat("{", lower, ",", upper, "}"); } bool IsInvalidPunctuationSymbol(char32 character) { return character == '%' || u_charType(character) == U_CURRENCY_SYMBOL; } bool ContainsOnlyValidXChars(const PhoneNumber& number, const string& candidate, const PhoneNumberUtil& util) { size_t found; found = candidate.find_first_of("xX"); while (found != string::npos && found < candidate.length() - 1) { char next_char = candidate[found + 1]; if (next_char == 'x' || next_char == 'X') { ++found; if (util.IsNumberMatchWithOneString( number, candidate.substr(found, candidate.length() - found)) != PhoneNumberUtil::NSN_MATCH) { return false; } } else { string normalized_extension(candidate.substr(found, candidate.length() - found)); util.NormalizeDigitsOnly(&normalized_extension); if (normalized_extension != number.extension()) { return false; } } found = candidate.find_first_of("xX", found + 1); } return true; } bool AllNumberGroupsRemainGrouped( const PhoneNumberUtil& util, const PhoneNumber& number, const string& normalized_candidate, const std::vector<string>& formatted_number_groups) { size_t from_index = 0; if (number.country_code_source() != PhoneNumber::FROM_DEFAULT_COUNTRY) { string country_code = SimpleItoa(number.country_code()); from_index = normalized_candidate.find(country_code) + country_code.size(); } for (size_t i = 0; i < formatted_number_groups.size(); ++i) { from_index = normalized_candidate.find(formatted_number_groups.at(i), from_index); if (from_index == string::npos) { return false; } from_index += formatted_number_groups.at(i).length(); if (i == 0 && from_index < normalized_candidate.length()) { string region; util.GetRegionCodeForCountryCode(number.country_code(), &region); string ndd_prefix; util.GetNddPrefixForRegion(region, true, &ndd_prefix); if (!ndd_prefix.empty() && isdigit(normalized_candidate.at(from_index))) { string national_significant_number; util.GetNationalSignificantNumber(number, &national_significant_number); return HasPrefixString(normalized_candidate.substr( from_index - formatted_number_groups.at(i).length()), national_significant_number); } } } return normalized_candidate.substr(from_index) .find(number.extension()) != string::npos; } bool LoadAlternateFormats(PhoneMetadataCollection* alternate_formats) { #if defined(I18N_PHONENUMBERS_USE_ALTERNATE_FORMATS) if (!alternate_formats->ParseFromArray(alternate_format_get(), alternate_format_size())) { LOG(ERROR) << "Could not parse binary data."; return false; } return true; #else return false; #endif } } class PhoneNumberMatcherRegExps : public Singleton<PhoneNumberMatcherRegExps> { private: friend class Singleton<PhoneNumberMatcherRegExps>; string opening_parens_; string closing_parens_; string non_parens_; string bracket_pair_limit_; string leading_maybe_matched_bracket_; string bracket_pairs_; string lead_limit_; string punctuation_limit_; int digit_block_limit_; string block_limit_; string punctuation_; string digit_sequence_; string lead_class_chars_; string lead_class_; public: scoped_ptr<const AbstractRegExpFactory> regexp_factory_for_pattern_; scoped_ptr<const AbstractRegExpFactory> regexp_factory_; mutable RegExpCache regexp_cache_; scoped_ptr<const RegExp> pub_pages_; scoped_ptr<const RegExp> slash_separated_dates_; scoped_ptr<const RegExp> time_stamps_; scoped_ptr<const RegExp> time_stamps_suffix_; scoped_ptr<const RegExp> matching_brackets_; scoped_ptr<std::vector<const RegExp*> > inner_matches_; scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_; scoped_ptr<const RegExp> capturing_ascii_digits_pattern_; scoped_ptr<const RegExp> lead_class_pattern_; scoped_ptr<const RegExp> pattern_; PhoneNumberMatcherRegExps() : opening_parens_("(\\[\xEF\xBC\x88\xEF\xBC\xBB" ), closing_parens_(")\\]\xEF\xBC\x89\xEF\xBC\xBD" ), non_parens_(StrCat("[^", opening_parens_, closing_parens_, "]")), bracket_pair_limit_(Limit(0, 3)), leading_maybe_matched_bracket_(StrCat( "(?:[", opening_parens_, "])?", "(?:", non_parens_, "+[", closing_parens_, "])?")), bracket_pairs_(StrCat( "(?:[", opening_parens_, "]", non_parens_, "+", "[", closing_parens_, "])", bracket_pair_limit_)), lead_limit_(Limit(0, 2)), punctuation_limit_(Limit(0, 4)), digit_block_limit_(PhoneNumberUtil::kMaxLengthForNsn + PhoneNumberUtil::kMaxLengthCountryCode), block_limit_(Limit(0, digit_block_limit_)), punctuation_(StrCat("[", PhoneNumberUtil::kValidPunctuation, "]", punctuation_limit_)), digit_sequence_(StrCat("\\p{Nd}", Limit(1, digit_block_limit_))), lead_class_chars_(StrCat(opening_parens_, PhoneNumberUtil::kPlusChars)), lead_class_(StrCat("[", lead_class_chars_, "]")), regexp_factory_for_pattern_(new ICURegExpFactory()), #ifdef I18N_PHONENUMBERS_USE_RE2 regexp_factory_(new RE2RegExpFactory()), #else regexp_factory_(new ICURegExpFactory()), #endif regexp_cache_(*regexp_factory_, 32), pub_pages_(regexp_factory_->CreateRegExp( "\\d{1,5}-+\\d{1,5}\\s{0,4}\\(\\d{1,4}")), slash_separated_dates_(regexp_factory_->CreateRegExp( "(?:(?:[0-3]?\\d/[01]?\\d)|" "(?:[01]?\\d/[0-3]?\\d))/(?:[12]\\d)?\\d{2}")), time_stamps_(regexp_factory_->CreateRegExp( "[12]\\d{3}[-/]?[01]\\d[-/]?[0-3]\\d +[0-2]\\d$")), time_stamps_suffix_(regexp_factory_->CreateRegExp(":[0-5]\\d")), matching_brackets_(regexp_factory_->CreateRegExp( StrCat(leading_maybe_matched_bracket_, non_parens_, "+", bracket_pairs_, non_parens_, "*"))), inner_matches_(new std::vector<const RegExp*>()), capture_up_to_second_number_start_pattern_( regexp_factory_->CreateRegExp( PhoneNumberUtil::kCaptureUpToSecondNumberStart)), capturing_ascii_digits_pattern_( regexp_factory_->CreateRegExp("(\\d+)")), lead_class_pattern_(regexp_factory_->CreateRegExp(lead_class_)), pattern_(regexp_factory_for_pattern_->CreateRegExp(StrCat( "((?:", lead_class_, punctuation_, ")", lead_limit_, digit_sequence_, "(?:", punctuation_, digit_sequence_, ")", block_limit_, "(?i)(?:", PhoneNumberUtil::GetInstance()->GetExtnPatternsForMatching(), ")?)"))) { inner_matches_->push_back( regexp_factory_->CreateRegExp("/+(.*)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("(\\([^(]*)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("(?:\\p{Z}-|-\\p{Z})\\p{Z}*(.+)")); inner_matches_->push_back( regexp_factory_->CreateRegExp( "[\xE2\x80\x92-\xE2\x80\x95\xEF\xBC\x8D]" "\\p{Z}*(.+)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("\\.+\\p{Z}*([^.]+)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("\\p{Z}+(\\P{Z}+)")); } private: DISALLOW_COPY_AND_ASSIGN(PhoneNumberMatcherRegExps); }; class AlternateFormats : public Singleton<AlternateFormats> { public: PhoneMetadataCollection format_data_; map<int, const PhoneMetadata*> calling_code_to_alternate_formats_map_; AlternateFormats() : format_data_(), calling_code_to_alternate_formats_map_() { if (!LoadAlternateFormats(&format_data_)) { LOG(DFATAL) << "Could not parse compiled-in metadata."; return; } for (RepeatedPtrField<PhoneMetadata>::const_iterator it = format_data_.metadata().begin(); it != format_data_.metadata().end(); ++it) { calling_code_to_alternate_formats_map_.insert( std::make_pair(it->country_code(), &*it)); } } const PhoneMetadata* GetAlternateFormatsForCountry(int country_calling_code) const { map<int, const PhoneMetadata*>::const_iterator it = calling_code_to_alternate_formats_map_.find(country_calling_code); if (it != calling_code_to_alternate_formats_map_.end()) { return it->second; } return NULL; } private: DISALLOW_COPY_AND_ASSIGN(AlternateFormats); }; PhoneNumberMatcher::PhoneNumberMatcher(const PhoneNumberUtil& util, const string& text, const string& region_code, PhoneNumberMatcher::Leniency leniency, int max_tries) : reg_exps_(PhoneNumberMatcherRegExps::GetInstance()), alternate_formats_(AlternateFormats::GetInstance()), phone_util_(util), text_(text), preferred_region_(region_code), leniency_(leniency), max_tries_(max_tries), state_(NOT_READY), last_match_(NULL), search_index_(0), is_input_valid_utf8_(true) { is_input_valid_utf8_ = IsInputUtf8(); } PhoneNumberMatcher::PhoneNumberMatcher(const string& text, const string& region_code) : reg_exps_(PhoneNumberMatcherRegExps::GetInstance()), alternate_formats_(NULL), phone_util_(*PhoneNumberUtil::GetInstance()), text_(text), preferred_region_(region_code), leniency_(VALID), max_tries_(numeric_limits<int>::max()), state_(NOT_READY), last_match_(NULL), search_index_(0), is_input_valid_utf8_(true) { is_input_valid_utf8_ = IsInputUtf8(); } PhoneNumberMatcher::~PhoneNumberMatcher() { } bool PhoneNumberMatcher::IsInputUtf8() { UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(text_.c_str(), text_.size()); return number_as_unicode.UTF8WasValid(); } bool PhoneNumberMatcher::IsLatinLetter(char32 letter) { if (!u_isalpha(letter) && (u_charType(letter) != U_NON_SPACING_MARK)) { return false; } UBlockCode block = ublock_getCode(letter); return ((block == UBLOCK_BASIC_LATIN) || (block == UBLOCK_LATIN_1_SUPPLEMENT) || (block == UBLOCK_LATIN_EXTENDED_A) || (block == UBLOCK_LATIN_EXTENDED_ADDITIONAL) || (block == UBLOCK_LATIN_EXTENDED_B) || (block == UBLOCK_COMBINING_DIACRITICAL_MARKS)); } bool PhoneNumberMatcher::ParseAndVerify(const string& candidate, int offset, PhoneNumberMatch* match) { DCHECK(match); if (!reg_exps_->matching_brackets_->FullMatch(candidate) || reg_exps_->pub_pages_->PartialMatch(candidate)) { return false; } if (leniency_ >= VALID) { scoped_ptr<RegExpInput> candidate_input( reg_exps_->regexp_factory_->CreateInput(candidate)); if (offset > 0 && !reg_exps_->lead_class_pattern_->Consume(candidate_input.get())) { char32 previous_char; const char* previous_char_ptr = EncodingUtils::BackUpOneUTF8Character(text_.c_str(), text_.c_str() + offset); EncodingUtils::DecodeUTF8Char(previous_char_ptr, &previous_char); if (IsInvalidPunctuationSymbol(previous_char) || IsLatinLetter(previous_char)) { return false; } } size_t lastCharIndex = offset + candidate.length(); if (lastCharIndex < text_.length()) { char32 next_char; const char* next_char_ptr = EncodingUtils::AdvanceOneUTF8Character( text_.c_str() + lastCharIndex - 1); EncodingUtils::DecodeUTF8Char(next_char_ptr, &next_char); if (IsInvalidPunctuationSymbol(next_char) || IsLatinLetter(next_char)) { return false; } } } PhoneNumber number; if (phone_util_.ParseAndKeepRawInput(candidate, preferred_region_, &number) != PhoneNumberUtil::NO_PARSING_ERROR) { return false; } if (VerifyAccordingToLeniency(leniency_, number, candidate)) { match->set_start(offset); match->set_raw_string(candidate); number.clear_country_code_source(); number.clear_preferred_domestic_carrier_code(); number.clear_raw_input(); match->set_number(number); return true; } return false; } bool PhoneNumberMatcher::VerifyAccordingToLeniency( Leniency leniency, const PhoneNumber& number, const string& candidate) const { switch (leniency) { case PhoneNumberMatcher::POSSIBLE: return phone_util_.IsPossibleNumber(number); case PhoneNumberMatcher::VALID: if (!phone_util_.IsValidNumber(number) || !ContainsOnlyValidXChars(number, candidate, phone_util_)) { return false; } return IsNationalPrefixPresentIfRequired(number); case PhoneNumberMatcher::STRICT_GROUPING: { if (!phone_util_.IsValidNumber(number) || !ContainsOnlyValidXChars(number, candidate, phone_util_) || ContainsMoreThanOneSlashInNationalNumber( number, candidate, phone_util_) || !IsNationalPrefixPresentIfRequired(number)) { return false; } ResultCallback4<bool, const PhoneNumberUtil&, const PhoneNumber&, const string&, const std::vector<string>&>* callback = NewPermanentCallback(&AllNumberGroupsRemainGrouped); bool is_valid = CheckNumberGroupingIsValid(number, candidate, callback); delete(callback); return is_valid; } case PhoneNumberMatcher::EXACT_GROUPING: { if (!phone_util_.IsValidNumber(number) || !ContainsOnlyValidXChars(number, candidate, phone_util_) || ContainsMoreThanOneSlashInNationalNumber( number, candidate, phone_util_) || !IsNationalPrefixPresentIfRequired(number)) { return false; } ResultCallback4<bool, const PhoneNumberUtil&, const PhoneNumber&, const string&, const std::vector<string>&>* callback = NewPermanentCallback( this, &PhoneNumberMatcher::AllNumberGroupsAreExactlyPresent); bool is_valid = CheckNumberGroupingIsValid(number, candidate, callback); delete(callback); return is_valid; } default: LOG(ERROR) << "No implementation defined for verification for leniency " << static_cast<int>(leniency); return false; } } bool PhoneNumberMatcher::ExtractInnerMatch(const string& candidate, int offset, PhoneNumberMatch* match) { DCHECK(match); for (std::vector<const RegExp*>::const_iterator regex = reg_exps_->inner_matches_->begin(); regex != reg_exps_->inner_matches_->end(); regex++) { scoped_ptr<RegExpInput> candidate_input( reg_exps_->regexp_factory_->CreateInput(candidate)); bool is_first_match = t
#include "phonenumbers/phonenumbermatcher.h" #include <string> #include <vector> #include <gtest/gtest.h> #include <unicode/unistr.h> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/base/memory/singleton.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/phonenumbermatch.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { using std::string; using icu::UnicodeString; namespace { struct NumberContext { string leading_text_; string trailing_text_; NumberContext(const string& leading_text, const string& trailing_text) : leading_text_(leading_text), trailing_text_(trailing_text) { } }; struct NumberTest { string raw_string_; string region_; string ToString() const { return StrCat(raw_string_, " (", region_, ")"); } NumberTest(const string& raw_string, const string& region) : raw_string_(raw_string), region_(region) { } }; } class PhoneNumberMatcherTest : public testing::Test { protected: PhoneNumberMatcherTest() : phone_util_(*PhoneNumberUtil::GetInstance()), matcher_(phone_util_, "", RegionCode::US(), PhoneNumberMatcher::VALID, 5), offset_(0) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } bool IsLatinLetter(char32 letter) { return PhoneNumberMatcher::IsLatinLetter(letter); } bool ContainsMoreThanOneSlashInNationalNumber( const PhoneNumber& phone_number, const string& candidate) { return PhoneNumberMatcher::ContainsMoreThanOneSlashInNationalNumber( phone_number, candidate, phone_util_); } bool ExtractMatch(const string& text, PhoneNumberMatch* match) { return matcher_.ExtractMatch(text, offset_, match); } PhoneNumberMatcher* GetMatcherWithLeniency( const string& text, const string& region, PhoneNumberMatcher::Leniency leniency) const { return new PhoneNumberMatcher(phone_util_, text, region, leniency, 100 ); } void DoTestNumberMatchesForLeniency( const std::vector<NumberTest>& test_cases, PhoneNumberMatcher::Leniency leniency) const { scoped_ptr<PhoneNumberMatcher> matcher; for (std::vector<NumberTest>::const_iterator test = test_cases.begin(); test != test_cases.end(); ++test) { matcher.reset(GetMatcherWithLeniency( test->raw_string_, test->region_, leniency)); EXPECT_TRUE(matcher->HasNext()) << "No match found in " << test->ToString() << " for leniency: " << leniency; if (matcher->HasNext()) { PhoneNumberMatch match; matcher->Next(&match); EXPECT_EQ(test->raw_string_, match.raw_string()) << "Found wrong match in test " << test->ToString() << ". Found " << match.raw_string(); } } } void DoTestNumberNonMatchesForLeniency( const std::vector<NumberTest>& test_cases, PhoneNumberMatcher::Leniency leniency) const { scoped_ptr<PhoneNumberMatcher> matcher; for (std::vector<NumberTest>::const_iterator test = test_cases.begin(); test != test_cases.end(); ++test) { matcher.reset(GetMatcherWithLeniency( test->raw_string_, test->region_, leniency)); EXPECT_FALSE(matcher->HasNext()) << "Match found in " << test->ToString() << " for leniency: " << leniency; } } void AssertMatchProperties(const PhoneNumberMatch& match, const string& text, const string& number, const string& region_code) { PhoneNumber expected_result; phone_util_.Parse(number, region_code, &expected_result); EXPECT_EQ(expected_result, match.number()); EXPECT_EQ(number, match.raw_string()) << " Wrong number found in " << text; } void AssertEqualRange(const string& text, int index, int start, int end) { string sub = text.substr(index); PhoneNumberMatcher matcher(phone_util_, sub, RegionCode::NZ(), PhoneNumberMatcher::POSSIBLE, 1000000 ); PhoneNumberMatch match; ASSERT_TRUE(matcher.HasNext()); matcher.Next(&match); EXPECT_EQ(start - index, match.start()); EXPECT_EQ(end - index, match.end()); EXPECT_EQ(sub.substr(match.start(), match.length()), match.raw_string()); } void DoTestFindInContext(const string& number, const string& default_country) { FindPossibleInContext(number, default_country); PhoneNumber parsed; phone_util_.Parse(number, default_country, &parsed); if (phone_util_.IsValidNumber(parsed)) { FindValidInContext(number, default_country); } } void FindMatchesInContexts(const std::vector<NumberContext>& contexts, bool is_valid, bool is_possible, const string& region, const string& number) { if (is_valid) { DoTestInContext(number, region, contexts, PhoneNumberMatcher::VALID); } else { for (std::vector<NumberContext>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) { string text = StrCat(it->leading_text_, number, it->trailing_text_); PhoneNumberMatcher matcher(text, region); EXPECT_FALSE(matcher.HasNext()); } } if (is_possible) { DoTestInContext(number, region, contexts, PhoneNumberMatcher::POSSIBLE); } else { for (std::vector<NumberContext>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) { string text = StrCat(it->leading_text_, number, it->trailing_text_); PhoneNumberMatcher matcher(phone_util_, text, region, PhoneNumberMatcher::POSSIBLE, 10000); EXPECT_FALSE(matcher.HasNext()); } } } void FindMatchesInContexts(const std::vector<NumberContext>& contexts, bool is_valid, bool is_possible) { const string& region = RegionCode::US(); const string number("415-666-7777"); FindMatchesInContexts(contexts, is_valid, is_possible, region, number); } void FindPossibleInContext(const string& number, const string& default_country) { std::vector<NumberContext> context_pairs; context_pairs.push_back(NumberContext("", "")); context_pairs.push_back(NumberContext(" ", "\t")); context_pairs.push_back(NumberContext("Hello ", "")); context_pairs.push_back(NumberContext("", " to call me!")); context_pairs.push_back(NumberContext("Hi there, call ", " to reach me!")); context_pairs.push_back(NumberContext("Hi there, call ", ", or don't")); context_pairs.push_back(NumberContext("Hi call", "")); context_pairs.push_back(NumberContext("", "forme")); context_pairs.push_back(NumberContext("Hi call", "forme")); context_pairs.push_back(NumberContext("It's cheap! Call ", " before 6:30")); context_pairs.push_back(NumberContext("Call ", " or +1800-123-4567!")); context_pairs.push_back(NumberContext("Call me on June 2 at", "")); context_pairs.push_back(NumberContext( "As quoted by Alfonso 12-15 (2009), you may call me at ", "")); context_pairs.push_back(NumberContext( "As quoted by Alfonso et al. 12-15 (2009), you may call me at ", "")); context_pairs.push_back(NumberContext( "As I said on 03/10/2011, you may call me at ", "")); context_pairs.push_back(NumberContext("", ", 45 days a year")); context_pairs.push_back(NumberContext("", ";x 7246433")); context_pairs.push_back(NumberContext("Call ", "/x12 more")); DoTestInContext(number, default_country, context_pairs, PhoneNumberMatcher::POSSIBLE); } void FindValidInContext(const string& number, const string& default_country) { std::vector<NumberContext> context_pairs; context_pairs.push_back(NumberContext("It's only 9.99! Call ", " to buy")); context_pairs.push_back(NumberContext("Call me on 21.6.1984 at ", "")); context_pairs.push_back(NumberContext("Call me on 06/21 at ", "")); context_pairs.push_back(NumberContext("Call me on 21.6. at ", "")); context_pairs.push_back(NumberContext("Call me on 06/21/84 at ", "")); DoTestInContext(number, default_country, context_pairs, PhoneNumberMatcher::VALID); } void DoTestInContext(const string& number, const string& default_country, const std::vector<NumberContext>& context_pairs, PhoneNumberMatcher::Leniency leniency) { for (std::vector<NumberContext>::const_iterator it = context_pairs.begin(); it != context_pairs.end(); ++it) { string prefix = it->leading_text_; string text = StrCat(prefix, number, it->trailing_text_); int start = prefix.length(); int end = start + number.length(); PhoneNumberMatcher matcher(phone_util_, text, default_country, leniency, 1000000 ); PhoneNumberMatch match; ASSERT_TRUE(matcher.HasNext()) << "Did not find a number in '" << text << "'; expected '" << number << "'"; matcher.Next(&match); string extracted = text.substr(match.start(), match.length()); EXPECT_EQ(start, match.start()); EXPECT_EQ(end, match.end()); EXPECT_EQ(number, extracted); EXPECT_EQ(extracted, match.raw_string()) << "Unexpected phone region in '" << text << "'; extracted '" << extracted << "'"; EnsureTermination(text, default_country, leniency); } } void EnsureTermination(const string& text, const string& default_country, PhoneNumberMatcher::Leniency leniency) { for (size_t index = 0; index <= text.length(); ++index) { string sub = text.substr(index); PhoneNumberMatcher matcher(phone_util_, text, default_country, leniency, 1000000 ); string matches; PhoneNumberMatch match; int match_count = 0; while (matcher.HasNext()) { matcher.Next(&match); StrAppend(&matches, ",", match.ToString()); ++match_count; } ASSERT_LT(match_count, 10); } } const PhoneNumberUtil& phone_util_; private: PhoneNumberMatcher matcher_; int offset_; }; TEST_F(PhoneNumberMatcherTest, ContainsMoreThanOneSlashInNationalNumber) { PhoneNumber number; number.set_country_code(1); number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); string candidate = "1/05/2013"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(274); number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); candidate = "27/4/2013"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(49); number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); candidate = "49/69/2013"; EXPECT_FALSE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(49); number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); candidate = "+49/69/2013"; EXPECT_FALSE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); candidate = "+ 49/69/2013"; EXPECT_FALSE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); candidate = "+ 49/69/20/13"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(49); number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); candidate = "49/69/2013"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); } TEST_F(PhoneNumberMatcherTest, FindNationalNumber) { DoTestFindInContext("033316005", RegionCode::NZ()); DoTestFindInContext("03-331 6005", RegionCode::NZ()); DoTestFindInContext("03 331 6005", RegionCode::NZ()); DoTestFindInContext("0064 3 331 6005", RegionCode::NZ()); DoTestFindInContext("01164 3 331 6005", RegionCode::US()); DoTestFindInContext("+64 3 331 6005", RegionCode::US()); DoTestFindInContext("64(0)64123456", RegionCode::NZ()); DoTestFindInContext("0123/456789", RegionCode::PL()); DoTestFindInContext("123-456-7890", RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, FindWithInternationalPrefixes) { DoTestFindInContext("+1 (650) 333-6000", RegionCode::NZ()); DoTestFindInContext("1-650-333-6000", RegionCode::US()); DoTestFindInContext("0011-650-333-6000", RegionCode::SG()); DoTestFindInContext("0081-650-333-6000", RegionCode::SG()); DoTestFindInContext("0191-650-333-6000", RegionCode::SG()); DoTestFindInContext("0~01-650-333-6000", RegionCode::PL()); DoTestFindInContext("++1 (650) 333-6000", RegionCode::PL()); DoTestFindInContext( "\xEF\xBC\x8B""1 (650) 333-6000" , RegionCode::SG()); DoTestFindInContext( "\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88\xEF\xBC\x96\xEF\xBC\x95" "\xEF\xBC\x90\xEF\xBC\x89\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93" "\xEF\xBC\x8D\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90\xEF\xBC\x90", RegionCode::SG()); } TEST_F(PhoneNumberMatcherTest, FindWithLeadingZero) { DoTestFindInContext("+39 02-36618 300", RegionCode::NZ()); DoTestFindInContext("02-36618 300", RegionCode::IT()); DoTestFindInContext("312 345 678", RegionCode::IT()); } TEST_F(PhoneNumberMatcherTest, FindNationalNumberArgentina) { DoTestFindInContext("+54 9 343 555 1212", RegionCode::AR()); DoTestFindInContext("0343 15 555 1212", RegionCode::AR()); DoTestFindInContext("+54 9 3715 65 4320", RegionCode::AR()); DoTestFindInContext("03715 15 65 4320", RegionCode::AR()); DoTestFindInContext("+54 11 3797 0000", RegionCode::AR()); DoTestFindInContext("011 3797 0000", RegionCode::AR()); DoTestFindInContext("+54 3715 65 4321", RegionCode::AR()); DoTestFindInContext("03715 65 4321", RegionCode::AR()); DoTestFindInContext("+54 23 1234 0000", RegionCode::AR()); DoTestFindInContext("023 1234 0000", RegionCode::AR()); } TEST_F(PhoneNumberMatcherTest, FindWithXInNumber) { DoTestFindInContext("(0xx) 123456789", RegionCode::AR()); DoTestFindInContext("(0xx) 123456789 x 1234", RegionCode::AR()); DoTestFindInContext("011xx5481429712", RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, FindNumbersMexico) { DoTestFindInContext("+52 (449)978-0001", RegionCode::MX()); DoTestFindInContext("01 (449)978-0001", RegionCode::MX()); DoTestFindInContext("(449)978-0001", RegionCode::MX()); DoTestFindInContext("+52 1 33 1234-5678", RegionCode::MX()); DoTestFindInContext("044 (33) 1234-5678", RegionCode::MX()); DoTestFindInContext("045 33 1234-5678", RegionCode::MX()); } TEST_F(PhoneNumberMatcherTest, FindNumbersWithPlusWithNoRegion) { DoTestFindInContext("+64 3 331 6005", RegionCode::ZZ()); } TEST_F(PhoneNumberMatcherTest, FindExtensions) { DoTestFindInContext("03 331 6005 ext 3456", RegionCode::NZ()); DoTestFindInContext("03-3316005x3456", RegionCode::NZ()); DoTestFindInContext("03-3316005 int.3456", RegionCode::NZ()); DoTestFindInContext("03 3316005 #3456", RegionCode::NZ()); DoTestFindInContext("0~0 1800 7493 524", RegionCode::PL()); DoTestFindInContext("(1800) 7493.524", RegionCode::US()); DoTestFindInContext("0~0 1800 7493 524 ~1234", RegionCode::PL()); DoTestFindInContext("+44 2034567890x456", RegionCode::NZ()); DoTestFindInContext("+44 2034567890x456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 x456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X 456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X 456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X 456", RegionCode::GB()); DoTestFindInContext("(800) 901-3355 x 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 , ext 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 ,extension 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 ,x 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 ext: 7246433", RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, FindInterspersedWithSpace) { DoTestFindInContext("0 3 3 3 1 6 0 0 5", RegionCode::NZ()); } TEST_F(PhoneNumberMatcherTest, IntermediateParsePositions) { string text = "Call 033316005 or 032316005!"; for (int i = 0; i <= 5; ++i) { AssertEqualRange(text, i, 5, 14); } AssertEqualRange(text, 6, 6, 14); AssertEqualRange(text, 7, 7, 14); for (int i = 8; i <= 19; ++i) { AssertEqualRange(text, i, 19, 28); } } TEST_F(PhoneNumberMatcherTest, FourMatchesInARow) { string number1 = "415-666-7777"; string number2 = "800-443-1223"; string number3 = "212-443-1223"; string number4 = "650-443-1223"; string text = StrCat(number1, " - ", number2, " - ", number3, " - ", number4); PhoneNumberMatcher matcher(text, RegionCode::US()); PhoneNumberMatch match; EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number1, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number2, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number3, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number4, RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, MatchesFoundWithMultipleSpaces) { string number1 = "415-666-7777"; string number2 = "800-443-1223"; string text = StrCat(number1, " ", number2); PhoneNumberMatcher matcher(text, RegionCode::US()); PhoneNumberMatch match; EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number1, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number2, RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, MatchWithSurroundingZipcodes) { string number = "415-666-7777"; string zip_preceding = StrCat("My address is CA 34215 - ", number, " is my number."); PhoneNumber expected_result; phone_util_.Parse(number, RegionCode::US(), &expected_result); scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency(zip_preceding, RegionCode::US(), PhoneNumberMatcher::VALID)); PhoneNumberMatch match; EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match)); AssertMatchProperties(match, zip_preceding, number, RegionCode::US()); number = "(415) 666 7777"; string zip_following = StrCat("My number is ", number, ". 34215 is my zip-code."); matcher.reset( GetMatcherWithLeniency(zip_following, RegionCode::US(), PhoneNumberMatcher::VALID)); PhoneNumberMatch match_with_spaces; EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match_with_spaces)); AssertMatchProperties( match_with_spaces, zip_following, number, RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, IsLatinLetter) { EXPECT_TRUE(IsLatinLetter('c')); EXPECT_TRUE(IsLatinLetter('C')); EXPECT_TRUE(IsLatinLetter(UnicodeString::fromUTF8("\xC3\x89" )[0])); EXPECT_TRUE(IsLatinLetter(UnicodeString::fromUTF8("\xCC\x81")[0])); EXPECT_FALSE(IsLatinLetter(':')); EXPECT_FALSE(IsLatinLetter('5')); EXPECT_FALSE(IsLatinLetter('-')); EXPECT_FALSE(IsLatinLetter('.')); EXPECT_FALSE(IsLatinLetter(' ')); EXPECT_FALSE( IsLatinLetter(UnicodeString::fromUTF8("\xE6\x88\x91" )[0])); EXPECT_FALSE(IsLatinLetter(UnicodeString::fromUTF8("\xE3\x81\xAE")[0])); EXPECT_FALSE(IsLatinLetter(UnicodeString::fromUTF8("\xE3\x81\xAE")[2])); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingLatinChars) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("abc", "def")); possible_only_contexts.push_back(NumberContext("abc", "")); possible_only_contexts.push_back(NumberContext("", "def")); possible_only_contexts.push_back(NumberContext("\xC3\x89" , "")); possible_only_contexts.push_back( NumberContext("\x20\x22\xCC\x81""e\xCC\x81" , "")); FindMatchesInContexts(possible_only_contexts, false, true); } TEST_F(PhoneNumberMatcherTest, MoneyNotSeenAsPhoneNumber) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("$", "")); possible_only_contexts.push_back(NumberContext("", "$")); possible_only_contexts.push_back(NumberContext("\xC2\xA3" , "")); possible_only_contexts.push_back(NumberContext("\xC2\xA5" , "")); FindMatchesInContexts(possible_only_contexts, false, true); } TEST_F(PhoneNumberMatcherTest, PercentageNotSeenAsPhoneNumber) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("", "%")); FindMatchesInContexts(possible_only_contexts, false, true); } TEST_F(PhoneNumberMatcherTest, PhoneNumberWithLeadingOrTrailingMoneyMatches) { std::vector<NumberContext> contexts; contexts.push_back(NumberContext("$20 ", "")); contexts.push_back(NumberContext("", " 100$")); FindMatchesInContexts(contexts, true, true); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingLatinCharsAndLeadingPunctuation) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("abc", "def")); possible_only_contexts.push_back(NumberContext("", "def")); possible_only_contexts.push_back(NumberContext("", "\xC3\x89" )); string number_with_plus = "+14156667777"; string number_with_brackets = "(415)6667777"; FindMatchesInContexts(possible_only_contexts, false, true, RegionCode::US(), number_with_plus); FindMatchesInContexts(possible_only_contexts, false, true, RegionCode::US(), number_with_brackets); std::vector<NumberContext> valid_contexts; valid_contexts.push_back(NumberContext("abc", "")); valid_contexts.push_back(NumberContext("\xC3\x89" , "")); valid_contexts.push_back( NumberContext("\xC3\x89" , ".")); valid_contexts.push_back(NumberContext("\xC3\x89" , " def")); FindMatchesInContexts(valid_contexts, true, true, RegionCode::US(), number_with_plus); FindMatchesInContexts(valid_contexts, true, true, RegionCode::US(), number_with_brackets); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingChineseChars) { std::vector<NumberContext> valid_contexts; valid_contexts.push_back(NumberContext( "\xE6\x88\x91\xE7\x9A\x84\xE7\x94\xB5\xE8\xAF\x9D\xE5\x8F\xB7\xE7\xA0\x81" "\xE6\x98\xAF", "")); valid_contexts.push_back(NumberContext( "", "\xE6\x98\xAF\xE6\x88\x91\xE7\x9A\x84\xE7\x94\xB5\xE8\xAF\x9D\xE5\x8F\xB7" "\xE7\xA0\x81")); valid_contexts.push_back(NumberContext( "\xE8\xAF\xB7\xE6\x8B\xA8\xE6\x89\x93" , "\xE6\x88\x91\xE5\x9C\xA8\xE6\x98\x8E\xE5\xA4\xA9" )); FindMatchesInContexts(valid_contexts, true, true); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingPunctuation) { std::vector<NumberContext> valid_contexts; valid_contexts.push_back(NumberContext("My number-", "")); valid_contexts.push_back(NumberContext("", ".Nice day.")); valid_contexts.push_back(NumberContext("Tel:", ".")); valid_contexts.push_back(NumberContext("Tel: ", " on Saturdays.")); FindMatchesInContexts(valid_contexts, true, true); } TEST_F(PhoneNumberMatcherTest, MatchesMultiplePhoneNumbersSeparatedByPhoneNumberPunctuation) { const string text = "Call 650-253-4561 -- 455-234-3451"; const string& region = RegionCode::US(); PhoneNumber number1; number1.set_country_code(phone_util_.GetCountryCodeForRegion(region)); number1.set_national_number(6502534561ULL); PhoneNumberMatch match1(5, "650-253-
163
cpp
google/libphonenumber
phonenumberutil
cpp/src/phonenumbers/phonenumberutil.cc
cpp/test/phonenumbers/phonenumberutil_test.cc
#ifndef I18N_PHONENUMBERS_PHONENUMBERUTIL_H_ #define I18N_PHONENUMBERS_PHONENUMBERUTIL_H_ #include <stddef.h> #include <list> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/base/memory/singleton.h" #include "phonenumbers/phonenumber.pb.h" #include "absl/container/node_hash_set.h" #include "absl/container/node_hash_map.h" class TelephoneNumber; namespace i18n { namespace phonenumbers { using google::protobuf::RepeatedPtrField; using std::string; class AsYouTypeFormatter; class Logger; class MatcherApi; class NumberFormat; class PhoneMetadata; class PhoneNumberDesc; class PhoneNumberRegExpsAndMappings; class RegExp; class PhoneNumberUtil : public Singleton<PhoneNumberUtil> { private: friend class AsYouTypeFormatter; friend class PhoneNumberMatcher; friend class PhoneNumberMatcherRegExps; friend class PhoneNumberMatcherTest; friend class PhoneNumberRegExpsAndMappings; friend class PhoneNumberUtilTest; friend class ShortNumberInfo; friend class ShortNumberInfoTest; friend class Singleton<PhoneNumberUtil>; public: PhoneNumberUtil(const PhoneNumberUtil&) = delete; PhoneNumberUtil& operator=(const PhoneNumberUtil&) = delete; ~PhoneNumberUtil(); static const char kRegionCodeForNonGeoEntity[]; enum PhoneNumberFormat { E164, INTERNATIONAL, NATIONAL, RFC3966 }; static const PhoneNumberFormat kMaxNumberFormat = RFC3966; enum PhoneNumberType { FIXED_LINE, MOBILE, FIXED_LINE_OR_MOBILE, TOLL_FREE, PREMIUM_RATE, SHARED_COST, VOIP, PERSONAL_NUMBER, PAGER, UAN, VOICEMAIL, UNKNOWN }; static const PhoneNumberType kMaxNumberType = UNKNOWN; enum MatchType { INVALID_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH, }; static const MatchType kMaxMatchType = EXACT_MATCH; enum ErrorType { NO_PARSING_ERROR, INVALID_COUNTRY_CODE_ERROR, NOT_A_NUMBER, TOO_SHORT_AFTER_IDD, TOO_SHORT_NSN, TOO_LONG_NSN, }; static const ErrorType kMaxErrorType = TOO_LONG_NSN; enum ValidationResult { IS_POSSIBLE, IS_POSSIBLE_LOCAL_ONLY, INVALID_COUNTRY_CODE, TOO_SHORT, INVALID_LENGTH, TOO_LONG, }; static const ValidationResult kMaxValidationResult = TOO_LONG; void GetSupportedRegions( std::set<string>* regions) const; void GetSupportedGlobalNetworkCallingCodes( std::set<int>* calling_codes) const; void GetSupportedCallingCodes(std::set<int>* calling_codes) const; void GetSupportedTypesForRegion( const string& region_code, std::set<PhoneNumberType>* types) const; void GetSupportedTypesForNonGeoEntity( int country_calling_code, std::set<PhoneNumberType>* types) const; static PhoneNumberUtil* GetInstance(); bool IsAlphaNumber(const string& number) const; void ConvertAlphaCharactersInNumber(string* number) const; void NormalizeDigitsOnly(string* number) const; void NormalizeDiallableCharsOnly(string* number) const; void GetNationalSignificantNumber(const PhoneNumber& number, string* national_significant_num) const; int GetLengthOfGeographicalAreaCode(const PhoneNumber& number) const; int GetLengthOfNationalDestinationCode(const PhoneNumber& number) const; void GetCountryMobileToken(int country_calling_code, string* mobile_token) const; void Format(const PhoneNumber& number, PhoneNumberFormat number_format, string* formatted_number) const; void FormatByPattern( const PhoneNumber& number, PhoneNumberFormat number_format, const RepeatedPtrField<NumberFormat>& user_defined_formats, string* formatted_number) const; void FormatNationalNumberWithCarrierCode(const PhoneNumber& number, const string& carrier_code, string* formatted_number) const; void FormatNationalNumberWithPreferredCarrierCode( const PhoneNumber& number, const string& fallback_carrier_code, string* formatted_number) const; void FormatNumberForMobileDialing( const PhoneNumber& number, const string& region_calling_from, bool with_formatting, string* formatted_number) const; void FormatOutOfCountryCallingNumber( const PhoneNumber& number, const string& calling_from, string* formatted_number) const; void FormatInOriginalFormat(const PhoneNumber& number, const string& region_calling_from, string* formatted_number) const; void FormatOutOfCountryKeepingAlphaChars( const PhoneNumber& number, const string& calling_from, string* formatted_number) const; bool TruncateTooLongNumber(PhoneNumber* number) const; PhoneNumberType GetNumberType(const PhoneNumber& number) const; bool IsValidNumber(const PhoneNumber& number) const; bool IsValidNumberForRegion( const PhoneNumber& number, const string& region_code) const; void GetRegionCodeForNumber(const PhoneNumber& number, string* region_code) const; int GetCountryCodeForRegion(const string& region_code) const; void GetRegionCodeForCountryCode(int country_code, string* region_code) const; void GetRegionCodesForCountryCallingCode( int country_calling_code, std::list<string>* region_codes) const; bool IsNANPACountry(const string& region_code) const; void GetNddPrefixForRegion(const string& region_code, bool strip_non_digits, string* national_prefix) const; ValidationResult IsPossibleNumberWithReason(const PhoneNumber& number) const; bool IsPossibleNumber(const PhoneNumber& number) const; ValidationResult IsPossibleNumberForTypeWithReason( const PhoneNumber& number, PhoneNumberType type) const; bool IsPossibleNumberForType(const PhoneNumber& number, PhoneNumberType type) const; bool IsPossibleNumberForString( const string& number, const string& region_dialing_from) const; bool CanBeInternationallyDialled(const PhoneNumber& number) const; bool IsNumberGeographical(const PhoneNumber& phone_number) const; bool IsNumberGeographical(PhoneNumberType phone_number_type, int country_calling_code) const; bool GetExampleNumber(const string& region_code, PhoneNumber* number) const; bool GetInvalidExampleNumber(const string& region_code, PhoneNumber* number) const; bool GetExampleNumberForType(const string& region_code, PhoneNumberType type, PhoneNumber* number) const; bool GetExampleNumberForType(PhoneNumberType type, PhoneNumber* number) const; bool GetExampleNumberForNonGeoEntity( int country_calling_code, PhoneNumber* number) const;
#include "phonenumbers/phonenumberutil.h" #include <algorithm> #include <iostream> #include <list> #include <set> #include <string> #include <gtest/gtest.h> #include <unicode/uchar.h> #include "phonenumbers/default_logger.h" #include "phonenumbers/normalize_utf8.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { using std::find; using std::ostream; using google::protobuf::RepeatedPtrField; static const int kInvalidCountryCode = 2; class PhoneNumberUtilTest : public testing::Test { public: PhoneNumberUtilTest(const PhoneNumberUtilTest&) = delete; PhoneNumberUtilTest& operator=(const PhoneNumberUtilTest&) = delete; protected: PhoneNumberUtilTest() : phone_util_(*PhoneNumberUtil::GetInstance()) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } const PhoneMetadata* GetPhoneMetadata(const string& region_code) const { return phone_util_.GetMetadataForRegion(region_code); } const PhoneMetadata* GetMetadataForNonGeographicalRegion( int country_code) const { return phone_util_.GetMetadataForNonGeographicalRegion(country_code); } void ExtractPossibleNumber(const string& number, string* extracted_number) const { phone_util_.ExtractPossibleNumber(number, extracted_number); } bool IsViablePhoneNumber(const string& number) const { return phone_util_.IsViablePhoneNumber(number); } void Normalize(string* number) const { phone_util_.Normalize(number); } PhoneNumber::CountryCodeSource MaybeStripInternationalPrefixAndNormalize( const string& possible_idd_prefix, string* number) const { return phone_util_.MaybeStripInternationalPrefixAndNormalize( possible_idd_prefix, number); } void MaybeStripNationalPrefixAndCarrierCode(const PhoneMetadata& metadata, string* number, string* carrier_code) const { phone_util_.MaybeStripNationalPrefixAndCarrierCode(metadata, number, carrier_code); } bool MaybeStripExtension(string* number, string* extension) const { return phone_util_.MaybeStripExtension(number, extension); } PhoneNumberUtil::ErrorType MaybeExtractCountryCode( const PhoneMetadata* default_region_metadata, bool keep_raw_input, string* national_number, PhoneNumber* phone_number) const { return phone_util_.MaybeExtractCountryCode(default_region_metadata, keep_raw_input, national_number, phone_number); } bool ContainsOnlyValidDigits(const string& s) const { return phone_util_.ContainsOnlyValidDigits(s); } void AssertThrowsForInvalidPhoneContext(const string number_to_parse) { PhoneNumber actual_number; EXPECT_EQ( PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(number_to_parse, RegionCode::ZZ(), &actual_number)); } const PhoneNumberUtil& phone_util_; }; TEST_F(PhoneNumberUtilTest, ContainsOnlyValidDigits) { EXPECT_TRUE(ContainsOnlyValidDigits("")); EXPECT_TRUE(ContainsOnlyValidDigits("2")); EXPECT_TRUE(ContainsOnlyValidDigits("25")); EXPECT_TRUE(ContainsOnlyValidDigits("\xEF\xBC\x96" )); EXPECT_FALSE(ContainsOnlyValidDigits("a")); EXPECT_FALSE(ContainsOnlyValidDigits("2a")); } TEST_F(PhoneNumberUtilTest, InterchangeInvalidCodepoints) { PhoneNumber phone_number; std::vector<string> valid_inputs = { "+44" "\xE2\x80\x93" "2087654321", }; for (auto input : valid_inputs) { EXPECT_EQ(input, NormalizeUTF8::NormalizeDecimalDigits(input)); EXPECT_TRUE(IsViablePhoneNumber(input)); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(input, RegionCode::GB(), &phone_number)); } std::vector<string> invalid_inputs = { "+44" "\x96" "2087654321", "+44" "\xC2\x96" "2087654321", "+44" "\xEF\xBF\xBE" "2087654321", }; for (auto input : invalid_inputs) { EXPECT_TRUE(NormalizeUTF8::NormalizeDecimalDigits(input).empty()); EXPECT_FALSE(IsViablePhoneNumber(input)); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(input, RegionCode::GB(), &phone_number)); } } TEST_F(PhoneNumberUtilTest, GetSupportedRegions) { std::set<string> regions; phone_util_.GetSupportedRegions(&regions); EXPECT_GT(regions.size(), 0U); } TEST_F(PhoneNumberUtilTest, GetSupportedGlobalNetworkCallingCodes) { std::set<int> calling_codes; phone_util_.GetSupportedGlobalNetworkCallingCodes(&calling_codes); EXPECT_GT(calling_codes.size(), 0U); for (std::set<int>::const_iterator it = calling_codes.begin(); it != calling_codes.end(); ++it) { EXPECT_GT(*it, 0); string region_code; phone_util_.GetRegionCodeForCountryCode(*it, &region_code); EXPECT_EQ(RegionCode::UN001(), region_code); } } TEST_F(PhoneNumberUtilTest, GetSupportedCallingCodes) { std::set<int> calling_codes; phone_util_.GetSupportedCallingCodes(&calling_codes); EXPECT_GT(calling_codes.size(), 0U); for (std::set<int>::const_iterator it = calling_codes.begin(); it != calling_codes.end(); ++it) { EXPECT_GT(*it, 0); string region_code; phone_util_.GetRegionCodeForCountryCode(*it, &region_code); EXPECT_NE(RegionCode::ZZ(), region_code); } std::set<int> supported_global_network_calling_codes; phone_util_.GetSupportedGlobalNetworkCallingCodes( &supported_global_network_calling_codes); EXPECT_GT(calling_codes.size(), supported_global_network_calling_codes.size()); EXPECT_NE(calling_codes.find(979), calling_codes.end()); } TEST_F(PhoneNumberUtilTest, GetSupportedTypesForRegion) { std::set<PhoneNumberUtil::PhoneNumberType> types; phone_util_.GetSupportedTypesForRegion(RegionCode::BR(), &types); EXPECT_NE(types.find(PhoneNumberUtil::FIXED_LINE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::MOBILE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::UNKNOWN), types.end()); types.clear(); phone_util_.GetSupportedTypesForRegion(RegionCode::US(), &types); EXPECT_NE(types.find(PhoneNumberUtil::FIXED_LINE), types.end()); EXPECT_NE(types.find(PhoneNumberUtil::MOBILE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::FIXED_LINE_OR_MOBILE), types.end()); types.clear(); phone_util_.GetSupportedTypesForRegion(RegionCode::ZZ(), &types); EXPECT_EQ(0u, types.size()); } TEST_F(PhoneNumberUtilTest, GetSupportedTypesForNonGeoEntity) { std::set<PhoneNumberUtil::PhoneNumberType> types; phone_util_.GetSupportedTypesForNonGeoEntity(999, &types); EXPECT_EQ(0u, types.size()); types.clear(); phone_util_.GetSupportedTypesForNonGeoEntity(979, &types); EXPECT_NE(types.find(PhoneNumberUtil::PREMIUM_RATE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::MOBILE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::UNKNOWN), types.end()); } TEST_F(PhoneNumberUtilTest, GetRegionCodesForCountryCallingCode) { std::list<string> regions; phone_util_.GetRegionCodesForCountryCallingCode(1, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::US()) != regions.end()); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::BS()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode(44, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::GB()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode(49, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::DE()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode(800, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::UN001()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode( kInvalidCountryCode, &regions); EXPECT_TRUE(regions.empty()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadUSMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US()); EXPECT_EQ("US", metadata->id()); EXPECT_EQ(1, metadata->country_code()); EXPECT_EQ("011", metadata->international_prefix()); EXPECT_TRUE(metadata->has_national_prefix()); ASSERT_EQ(2, metadata->number_format_size()); EXPECT_EQ("(\\d{3})(\\d{3})(\\d{4})", metadata->number_format(1).pattern()); EXPECT_EQ("$1 $2 $3", metadata->number_format(1).format()); EXPECT_EQ("[13-689]\\d{9}|2[0-35-9]\\d{8}", metadata->general_desc().national_number_pattern()); EXPECT_EQ("[13-689]\\d{9}|2[0-35-9]\\d{8}", metadata->fixed_line().national_number_pattern()); EXPECT_EQ(1, metadata->general_desc().possible_length_size()); EXPECT_EQ(10, metadata->general_desc().possible_length(0)); EXPECT_EQ(0, metadata->toll_free().possible_length_size()); EXPECT_EQ("900\\d{7}", metadata->premium_rate().national_number_pattern()); EXPECT_FALSE(metadata->shared_cost().has_national_number_pattern()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadDEMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::DE()); EXPECT_EQ("DE", metadata->id()); EXPECT_EQ(49, metadata->country_code()); EXPECT_EQ("00", metadata->international_prefix()); EXPECT_EQ("0", metadata->national_prefix()); ASSERT_EQ(6, metadata->number_format_size()); EXPECT_EQ(1, metadata->number_format(5).leading_digits_pattern_size()); EXPECT_EQ("900", metadata->number_format(5).leading_digits_pattern(0)); EXPECT_EQ("(\\d{3})(\\d{3,4})(\\d{4})", metadata->number_format(5).pattern()); EXPECT_EQ(2, metadata->general_desc().possible_length_local_only_size()); EXPECT_EQ(8, metadata->general_desc().possible_length_size()); EXPECT_EQ(0, metadata->fixed_line().possible_length_size()); EXPECT_EQ(2, metadata->mobile().possible_length_size()); EXPECT_EQ("$1 $2 $3", metadata->number_format(5).format()); EXPECT_EQ("(?:[24-6]\\d{2}|3[03-9]\\d|[789](?:0[2-9]|[1-9]\\d))\\d{1,8}", metadata->fixed_line().national_number_pattern()); EXPECT_EQ("30123456", metadata->fixed_line().example_number()); EXPECT_EQ(10, metadata->toll_free().possible_length(0)); EXPECT_EQ("900([135]\\d{6}|9\\d{7})", metadata->premium_rate().national_number_pattern()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadARMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::AR()); EXPECT_EQ("AR", metadata->id()); EXPECT_EQ(54, metadata->country_code()); EXPECT_EQ("00", metadata->international_prefix()); EXPECT_EQ("0", metadata->national_prefix()); EXPECT_EQ("0(?:(11|343|3715)15)?", metadata->national_prefix_for_parsing()); EXPECT_EQ("9$1", metadata->national_prefix_transform_rule()); ASSERT_EQ(5, metadata->number_format_size()); EXPECT_EQ("$2 15 $3-$4", metadata->number_format(2).format()); EXPECT_EQ("(\\d)(\\d{4})(\\d{2})(\\d{4})", metadata->number_format(3).pattern()); EXPECT_EQ("(\\d)(\\d{4})(\\d{2})(\\d{4})", metadata->intl_number_format(3).pattern()); EXPECT_EQ("$1 $2 $3 $4", metadata->intl_number_format(3).format()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadInternationalTollFreeMetadata) { const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(800); EXPECT_FALSE(metadata == NULL); EXPECT_EQ("001", metadata->id()); EXPECT_EQ(800, metadata->country_code()); EXPECT_EQ("$1 $2", metadata->number_format(0).format()); EXPECT_EQ("(\\d{4})(\\d{4})", metadata->number_format(0).pattern()); EXPECT_EQ(0, metadata->general_desc().possible_length_local_only_size()); EXPECT_EQ(1, metadata->general_desc().possible_length_size()); EXPECT_EQ("12345678", metadata->toll_free().example_number()); } TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502530000}); string national_significant_number; phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("6502530000", national_significant_number); national_significant_number.clear(); number.set_country_code(39); number.set_national_number(uint64{312345678}); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("312345678", national_significant_number); national_significant_number.clear(); number.set_country_code(39); number.set_national_number(uint64{236618300}); number.set_italian_leading_zero(true); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("0236618300", national_significant_number); national_significant_number.clear(); number.Clear(); number.set_country_code(800); number.set_national_number(uint64{12345678}); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("12345678", national_significant_number); } TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber_ManyLeadingZeros) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{650}); number.set_italian_leading_zero(true); number.set_number_of_leading_zeros(2); string national_significant_number; phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("00650", national_significant_number); number.set_number_of_leading_zeros(-3); national_significant_number.clear(); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("650", national_significant_number); } TEST_F(PhoneNumberUtilTest, GetExampleNumber) { PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(uint64{30123456}); PhoneNumber test_number; bool success = phone_util_.GetExampleNumber(RegionCode::DE(), &test_number); EXPECT_TRUE(success); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType( RegionCode::DE(), PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType( RegionCode::DE(), PhoneNumberUtil::FIXED_LINE_OR_MOBILE, &test_number); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType( RegionCode::DE(), PhoneNumberUtil::MOBILE, &test_number); success = phone_util_.GetExampleNumberForType( RegionCode::US(), PhoneNumberUtil::VOICEMAIL, &test_number); test_number.Clear(); EXPECT_FALSE(success); EXPECT_EQ(PhoneNumber::default_instance(), test_number); success = phone_util_.GetExampleNumberForType( RegionCode::US(), PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); success = phone_util_.GetExampleNumberForType( RegionCode::US(), PhoneNumberUtil::MOBILE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); test_number.Clear(); EXPECT_FALSE(phone_util_.GetExampleNumberForType( RegionCode::CS(), PhoneNumberUtil::MOBILE, &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_FALSE(phone_util_.GetExampleNumber(RegionCode::UN001(), &test_number)); } TEST_F(PhoneNumberUtilTest, GetInvalidExampleNumber) { PhoneNumber test_number; EXPECT_FALSE(phone_util_.GetInvalidExampleNumber(RegionCode::UN001(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_FALSE(phone_util_.GetInvalidExampleNumber(RegionCode::CS(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_TRUE(phone_util_.GetInvalidExampleNumber(RegionCode::US(), &test_number)); EXPECT_EQ(1, test_number.country_code()); EXPECT_NE(0u, test_number.national_number()); } TEST_F(PhoneNumberUtilTest, GetExampleNumberForNonGeoEntity) { PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(uint64{12345678}); PhoneNumber test_number; bool success = phone_util_.GetExampleNumberForNonGeoEntity(800 , &test_number); EXPECT_TRUE(success); EXPECT_EQ(toll_free_number, test_number); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(uint64{123456789}); success = phone_util_.GetExampleNumberForNonGeoEntity(979 , &test_number); EXPECT_TRUE(success); EXPECT_EQ(universal_premium_rate, test_number); } TEST_F(PhoneNumberUtilTest, GetExampleNumberWithoutRegion) { PhoneNumber test_number; bool success = phone_util_.GetExampleNumberForType( PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); test_number.Clear(); success = phone_util_.GetExampleNumberForType(PhoneNumberUtil::MOBILE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); test_number.Clear(); success = phone_util_.GetExampleNumberForType(PhoneNumberUtil::PREMIUM_RATE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); } TEST_F(PhoneNumberUtilTest, FormatUSNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{6502530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("650 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 650 253 0000", formatted_number); test_number.set_national_number(uint64{8002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("800 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 800 253 0000", formatted_number); test_number.set_national_number(uint64{9002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("900 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 900 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ("tel:+1-900-253-0000", formatted_number); test_number.set_national_number(uint64{0}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("0", formatted_number); test_number.set_raw_input("000-000-0000"); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("000-000-0000", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatBSNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{2421234567}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("242 123 4567", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 242 123 4567", formatted_number); test_number.set_national_number(uint64{8002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("800 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 800 253 0000", formatted_number); test_number.set_national_number(uint64{9002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("900 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 900 253 0000", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatGBNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(44); test_number.set_national_number(uint64{2087389353}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("(020) 8738 9353", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+44 20 8738 9353", formatted_number); test_number.set_national_number(uint64{7912345678}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("(07912) 345 678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+44 7912 345 678", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatDENumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(49); test_number.set_national_number(uint64{301234}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("030/1234", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 30/1234", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ("tel:+49-30-1234", formatted_number); test_number.set_national_number(uint64{291123}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("0291 123", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 291 123", formatted_number); test_number.set_national_number(uint64{29112345678}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("0291 12345678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 291 12345678", formatted_number); test_number.set_national_number(uint64{9123123}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("09123 123", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 9123 123", formatted_number); test_number.set_national_number(uint64{80212345}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("08021 2345", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 8021 2345", formatted_number); test_number.set_national_number(uint64{1234}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("1234", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 1234", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatITNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(39); test_number.set_national_number(uint64{236618300}); test_number.set_italian_leading_zero(true); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("02 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+39 02 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+390236618300", formatted_number); test_number.set_national_number(uint64{345678901}); test_number.set_italian_leading_zero(false); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("345 678 901", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+39 345 678 901", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+39345678901", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatAUNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(61); test_number.set_national_number(uint64{236618300}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("02 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+61 2 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+61236618300", formatted_number); test_number.set_national_number(uint64{1800123456}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("1800 123 456", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+61 1800 123 456", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+611800123456", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatARNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(54); test_number.set_national_number(uint64{1187654321}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("011 8765-4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+54 11 8765-4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+541187654321", formatted_number); test_number.set_national_number(uint64{91187654321}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("011 15 8765-4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+54 9 11 8765 4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5491187654321", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatMXNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(52); test_number.set_national_number(uint64{12345678900}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("045 234 567 8900", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 1 234 567 8900", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5212345678900", formatted_number); test_number.set_national_number(uint64{15512345678}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("045 55 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 1 55 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5215512345678", formatted_number); test_number.set_national_number(3312345678LL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("01 33 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 33 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+523312345678", formatted_number); test_number.set_national_number(8211234567LL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("01 821 123 4567", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 821 123 4567", formatted_number); phone_uti
164
cpp
google/libphonenumber
logger
cpp/src/phonenumbers/logger.cc
cpp/test/phonenumbers/logger_test.cc
#ifndef I18N_PHONENUMBERS_LOGGER_H_ #define I18N_PHONENUMBERS_LOGGER_H_ #include <cstdio> #include <string> namespace i18n { namespace phonenumbers { using std::string; enum { LOG_FATAL = 1, LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG, }; enum { DFATAL = LOG_FATAL, #ifndef ERROR ERROR = LOG_ERROR, #endif WARNING = LOG_WARNING, }; class Logger { public: Logger() : level_(LOG_ERROR) {} virtual ~Logger() {} virtual void WriteLevel() {} virtual void WriteMessage(const string& msg) = 0; inline int level() const { return level_; } inline void set_level(int level) { level_ = level; } inline void set_verbosity_level(int verbose_logs_level) { set_level(LOG_DEBUG + verbose_logs_level); } static inline Logger* set_logger_impl(Logger* logger) { impl_ = logger; return logger; } static inline Logger* mutable_logger_impl() { return impl_; } private: static Logger* impl_; int level_; }; class NullLogger : public Logger { public: virtual ~NullLogger() {} virtual void WriteMessage(const string& ) {} }; } } #endif #include "phonenumbers/logger.h" #include <cstddef> namespace i18n { namespace phonenumbers { Logger* Logger::impl_ = NULL; } }
#include <string> #include <gtest/gtest.h> #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/logger.h" namespace i18n { namespace phonenumbers { class StringLogger : public Logger { public: virtual ~StringLogger() {} const string& message() const { return msg_; } virtual void WriteMessage(const string& msg) { msg_ += msg; } private: string msg_; }; class LoggerTest : public ::testing::Test { protected: virtual void SetUp() { test_logger_.reset(new StringLogger()); test_logger_->set_level(LOG_INFO); old_logger_ = Logger::mutable_logger_impl(); Logger::set_logger_impl(test_logger_.get()); } virtual void TearDown() { Logger::set_logger_impl(old_logger_); } scoped_ptr<StringLogger> test_logger_; Logger* old_logger_; }; TEST_F(LoggerTest, LoggerIgnoresHigherVerbosity) { LOG(LOG_DEBUG) << "Hello"; EXPECT_EQ("", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsNewline) { LOG(LOG_INFO) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerLogsEqualVerbosity) { LOG(LOG_INFO) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerLogsMoreSeriousMessages) { LOG(LOG_WARNING) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerConcatenatesMessages) { LOG(LOG_INFO) << "Hello"; ASSERT_EQ("Hello\n", test_logger_->message()); LOG(LOG_INFO) << " World"; EXPECT_EQ("Hello\n World\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerHandlesDifferentTypes) { LOG(LOG_INFO) << "Hello " << 42; EXPECT_EQ("Hello 42\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerIgnoresVerboseLogs) { VLOG(1) << "Hello"; EXPECT_EQ("", test_logger_->message()); VLOG(0) << "Hello"; EXPECT_EQ("", test_logger_->message()); test_logger_->set_level(LOG_DEBUG); VLOG(1) << "Hello"; EXPECT_EQ("", test_logger_->message()); VLOG(0) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerShowsDebugLogsAtDebugLevel) { test_logger_->set_level(LOG_DEBUG); LOG(LOG_DEBUG) << "Debug hello"; EXPECT_EQ("Debug hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsDebugLogsWhenVerbositySet) { int verbose_log_level = 2; test_logger_->set_verbosity_level(verbose_log_level); LOG(LOG_DEBUG) << "Debug hello"; EXPECT_EQ("Debug hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsErrorLogsWhenVerbositySet) { int verbose_log_level = 2; test_logger_->set_verbosity_level(verbose_log_level); LOG(ERROR) << "Error hello"; EXPECT_EQ("Error hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsLogsAccordingToVerbosity) { int verbose_log_level = 2; test_logger_->set_verbosity_level(verbose_log_level); VLOG(verbose_log_level + 1) << "Hello 3"; EXPECT_EQ("", test_logger_->message()); VLOG(verbose_log_level - 1) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); VLOG(verbose_log_level) << "Hello 2"; EXPECT_EQ("Hello\nHello 2\n", test_logger_->message()); } } }
165
cpp
google/libphonenumber
unicodestring
cpp/src/phonenumbers/unicodestring.cc
cpp/test/phonenumbers/unicodestring_test.cc
#ifndef I18N_PHONENUMBERS_UNICODESTRING_H_ #define I18N_PHONENUMBERS_UNICODESTRING_H_ #include "phonenumbers/utf/unicodetext.h" #include <cstring> #include <limits> namespace i18n { namespace phonenumbers { class UnicodeString { public: UnicodeString() : cached_index_(-1) {} explicit UnicodeString(const char* utf8) : text_(UTF8ToUnicodeText(utf8, static_cast<int>(std::strlen(utf8)))), cached_index_(-1) {} explicit UnicodeString(char32 codepoint) : cached_index_(-1) { append(codepoint); } UnicodeString(const UnicodeString& src) : text_(src.text_), cached_index_(-1) {} UnicodeString& operator=(const UnicodeString& src); bool operator==(const UnicodeString& rhs) const; void append(const UnicodeString& unicode_string); inline void append(char32 codepoint) { invalidateCachedIndex(); text_.push_back(codepoint); } typedef UnicodeText::const_iterator const_iterator; inline const_iterator begin() const { return text_.begin(); } inline const_iterator end() const { return text_.end(); } int indexOf(char32 codepoint) const; inline int length() const { return text_.size(); } inline void remove() { invalidateCachedIndex(); text_.clear(); } void replace(int start, int length, const UnicodeString& src); void setCharAt(int pos, char32 c); inline void setTo(const char* s, size_t len) { invalidateCachedIndex(); text_.CopyUTF8(s, static_cast<int>(len)); } bool UTF8WasValid() const { return text_.UTF8WasValid(); } UnicodeString tempSubString( int start, int length = std::numeric_limits<int>::max()) const; inline void toUTF8String(string& out) const { out = UnicodeTextToUTF8(text_); } char32 operator[](int index) const; private: UnicodeText text_; inline void invalidateCachedIndex() { cached_index_ = -1; } mutable UnicodeText::const_iterator cached_it_; mutable int cached_index_; }; } } #endif #include "phonenumbers/unicodestring.h" #include <algorithm> #include <cassert> #include <iterator> using std::advance; using std::equal; namespace i18n { namespace phonenumbers { UnicodeString& UnicodeString::operator=(const UnicodeString& src) { if (&src != this) { invalidateCachedIndex(); text_ = src.text_; } return *this; } bool UnicodeString::operator==(const UnicodeString& rhs) const { return equal(text_.begin(), text_.end(), rhs.text_.begin()); } void UnicodeString::append(const UnicodeString& unicode_string) { invalidateCachedIndex(); for (UnicodeString::const_iterator it = unicode_string.begin(); it != unicode_string.end(); ++it) { append(*it); } } int UnicodeString::indexOf(char32 codepoint) const { int pos = 0; for (UnicodeText::const_iterator it = text_.begin(); it != text_.end(); ++it, ++pos) { if (*it == codepoint) { return pos; } } return -1; } void UnicodeString::replace(int start, int length, const UnicodeString& src) { assert(length >= 0 && length <= this->length()); invalidateCachedIndex(); UnicodeText::const_iterator start_it = text_.begin(); advance(start_it, start); UnicodeText unicode_text; unicode_text.append(text_.begin(), start_it); unicode_text.append(src.text_); advance(start_it, length); unicode_text.append(start_it, text_.end()); text_ = unicode_text; } void UnicodeString::setCharAt(int pos, char32 c) { assert(pos < length()); invalidateCachedIndex(); UnicodeText::const_iterator pos_it = text_.begin(); advance(pos_it, pos); UnicodeText unicode_text; unicode_text.append(text_.begin(), pos_it); unicode_text.push_back(c); ++pos_it; unicode_text.append(pos_it, text_.end()); text_ = unicode_text; } UnicodeString UnicodeString::tempSubString(int start, int length) const { const int unicodestring_length = this->length(); if (length == std::numeric_limits<int>::max()) { length = unicodestring_length - start; } if (start > unicodestring_length || length > unicodestring_length) { return UnicodeString(""); } UnicodeText::const_iterator start_it = text_.begin(); advance(start_it, start); UnicodeText::const_iterator end_it = start_it; advance(end_it, length); UnicodeString substring; substring.text_.PointTo(start_it, end_it); return substring; } char32 UnicodeString::operator[](int index) const { assert(index < length()); if (cached_index_ == -1 || cached_index_ > index) { cached_it_ = text_.begin(); cached_index_ = 0; } for (; cached_index_ < index; ++cached_index_, ++cached_it_) {} return *cached_it_; } } }
#include <iostream> #include <gtest/gtest.h> #include "phonenumbers/unicodestring.h" using std::ostream; namespace i18n { namespace phonenumbers { ostream& operator<<(ostream& out, const UnicodeString& s) { string utf8; s.toUTF8String(utf8); out << utf8; return out; } TEST(UnicodeString, ToUTF8StringWithEmptyString) { UnicodeString s; string utf8; s.toUTF8String(utf8); EXPECT_EQ("", utf8); } TEST(UnicodeString, ToUTF8String) { UnicodeString s("hello"); string utf8; s.toUTF8String(utf8); EXPECT_EQ("hello", utf8); } TEST(UnicodeString, ToUTF8StringWithNonAscii) { UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" ); string utf8; s.toUTF8String(utf8); EXPECT_EQ("\xEF\xBC\x95\xEF\xBC\x93", utf8); } TEST(UnicodeString, AppendCodepoint) { UnicodeString s; s.append('h'); ASSERT_EQ(UnicodeString("h"), s); s.append('e'); EXPECT_EQ(UnicodeString("he"), s); } TEST(UnicodeString, AppendCodepointWithNonAscii) { UnicodeString s; s.append(0xFF15 ); ASSERT_EQ(UnicodeString("\xEF\xBC\x95" ), s); s.append(0xFF13 ); EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" ), s); } TEST(UnicodeString, AppendUnicodeString) { UnicodeString s; s.append(UnicodeString("he")); ASSERT_EQ(UnicodeString("he"), s); s.append(UnicodeString("llo")); EXPECT_EQ(UnicodeString("hello"), s); } TEST(UnicodeString, AppendUnicodeStringWithNonAscii) { UnicodeString s; s.append(UnicodeString("\xEF\xBC\x95" )); ASSERT_EQ(UnicodeString("\xEF\xBC\x95"), s); s.append(UnicodeString("\xEF\xBC\x93" )); EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" ), s); } TEST(UnicodeString, IndexOf) { UnicodeString s("hello"); EXPECT_EQ(0, s.indexOf('h')); EXPECT_EQ(2, s.indexOf('l')); EXPECT_EQ(4, s.indexOf('o')); } TEST(UnicodeString, IndexOfWithNonAscii) { UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" ); EXPECT_EQ(1, s.indexOf(0xFF13 )); } TEST(UnicodeString, ReplaceWithEmptyInputs) { UnicodeString s; s.replace(0, 0, UnicodeString("")); EXPECT_EQ(UnicodeString(""), s); } TEST(UnicodeString, ReplaceWithEmptyReplacement) { UnicodeString s("hello"); s.replace(0, 5, UnicodeString("")); EXPECT_EQ(UnicodeString(""), s); } TEST(UnicodeString, ReplaceBegining) { UnicodeString s("hello world"); s.replace(0, 5, UnicodeString("HELLO")); EXPECT_EQ(UnicodeString("HELLO world"), s); } TEST(UnicodeString, ReplaceMiddle) { UnicodeString s("hello world"); s.replace(5, 1, UnicodeString("AB")); EXPECT_EQ(UnicodeString("helloABworld"), s); } TEST(UnicodeString, ReplaceEnd) { UnicodeString s("hello world"); s.replace(10, 1, UnicodeString("AB")); EXPECT_EQ(UnicodeString("hello worlAB"), s); } TEST(UnicodeString, ReplaceWithNonAscii) { UnicodeString s("hello world"); s.replace(3, 2, UnicodeString("\xEF\xBC\x91\xEF\xBC\x90" )); EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90 world"), s); } TEST(UnicodeString, SetCharBegining) { UnicodeString s("hello"); s.setCharAt(0, 'H'); EXPECT_EQ(UnicodeString("Hello"), s); } TEST(UnicodeString, SetCharMiddle) { UnicodeString s("hello"); s.setCharAt(2, 'L'); EXPECT_EQ(UnicodeString("heLlo"), s); } TEST(UnicodeString, SetCharEnd) { UnicodeString s("hello"); s.setCharAt(4, 'O'); EXPECT_EQ(UnicodeString("hellO"), s); } TEST(UnicodeString, SetCharWithNonAscii) { UnicodeString s("hello"); s.setCharAt(4, 0xFF10 ); EXPECT_EQ(UnicodeString("hell\xEF\xBC\x90" ), s); } TEST(UnicodeString, TempSubStringWithEmptyString) { EXPECT_EQ(UnicodeString(""), UnicodeString().tempSubString(0, 0)); } TEST(UnicodeString, TempSubStringWithInvalidInputs) { UnicodeString s("hello"); EXPECT_EQ(UnicodeString(""), s.tempSubString(6)); EXPECT_EQ(UnicodeString(""), s.tempSubString(2, 6)); } TEST(UnicodeString, TempSubString) { UnicodeString s("hello"); EXPECT_EQ(UnicodeString(""), s.tempSubString(0, 0)); EXPECT_EQ(UnicodeString("h"), s.tempSubString(0, 1)); EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0, 5)); EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2, 3)); } TEST(UnicodeString, TempSubStringWithNoLength) { UnicodeString s("hello"); EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0)); EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2)); } TEST(UnicodeString, TempSubStringWithNonAscii) { UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" ); EXPECT_EQ(UnicodeString("\xEF\xBC\x91" ), s.tempSubString(3, 1)); } TEST(UnicodeString, OperatorEqual) { UnicodeString s("hello"); s = UnicodeString("Hello"); EXPECT_EQ(UnicodeString("Hello"), s); } TEST(UnicodeString, OperatorEqualWithNonAscii) { UnicodeString s("hello"); s = UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90" ); EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90"), s); } TEST(UnicodeString, OperatorBracket) { UnicodeString s("hello"); EXPECT_EQ('h', s[0]); EXPECT_EQ('e', s[1]); EXPECT_EQ('l', s[2]); EXPECT_EQ('l', s[3]); EXPECT_EQ('o', s[4]); } TEST(UnicodeString, OperatorBracketWithNonAscii) { UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" ); EXPECT_EQ('h', s[0]); EXPECT_EQ('e', s[1]); EXPECT_EQ('l', s[2]); EXPECT_EQ(0xFF11 , s[3]); EXPECT_EQ(0xFF10 , s[4]); } TEST(UnicodeString, OperatorBracketWithIteratorCacheInvalidation) { UnicodeString s("hello"); EXPECT_EQ('h', s[0]); EXPECT_EQ('e', s[1]); s.setCharAt(1, 'E'); EXPECT_EQ(UnicodeString("hEllo"), s); EXPECT_EQ('E', s[1]); EXPECT_EQ('h', s[0]); EXPECT_EQ('o', s[4]); } } }
166
cpp
google/libphonenumber
stringutil
cpp/src/phonenumbers/stringutil.cc
cpp/test/phonenumbers/stringutil_test.cc
#ifndef I18N_PHONENUMBERS_STRINGUTIL_H_ #define I18N_PHONENUMBERS_STRINGUTIL_H_ #include <cstddef> #include <string> #include <vector> #include "phonenumbers/base/basictypes.h" #include "absl/strings/string_view.h" #include "absl/strings/str_cat.h" namespace i18n { namespace phonenumbers { using std::string; using std::vector; string operator+(const string& s, int n); string SimpleItoa(uint64_t n); string SimpleItoa(int64_t n); string SimpleItoa(int n); bool HasPrefixString(const string& s, const string& prefix); size_t FindNth(const string& s, char c, int n); void SplitStringUsing(const string& s, char delimiter, vector<string>* result); bool TryStripPrefixString(const string& in, const string& prefix, string* out); bool HasSuffixString(const string& s, const string& suffix); void safe_strto32(const string& s, int32_t *n); void safe_strtou64(const string& s, uint64_t *n); void safe_strto64(const string& s, int64_t* n); void strrmm(string* s, const string& chars); int GlobalReplaceSubstring(const string& substring, const string& replacement, string* s); class StringHolder: public absl::AlphaNum { public: StringHolder(const string& s); StringHolder(const char* s); StringHolder(uint64_t n); ~StringHolder(); const absl::string_view GetString() const { return Piece(); } const char* GetCString() const { return data(); } size_t Length() const { return size(); } }; string& operator+=(string& lhs, const StringHolder& rhs); string StrCat(const StringHolder& s1, const StringHolder& s2); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14, const StringHolder& s15); string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14, const StringHolder& s15, const StringHolder& s16); void StrAppend(string* dest, const StringHolder& s1); void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2); void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3); void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4); void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5); } } #endif #include <algorithm> #include <cassert> #include <cstring> #include <sstream> #include "phonenumbers/stringutil.h" #include "absl/strings/str_replace.h" #include "absl/strings/substitute.h" #include "absl/strings/match.h" namespace i18n { namespace phonenumbers { using std::equal; using std::stringstream; string operator+(const string& s, int n) { string result; absl::StrAppend(&result,s,n); return result; } string SimpleItoa(int n) { return absl::StrCat(n); } string SimpleItoa(uint64 n) { return absl::StrCat(n); } string SimpleItoa(int64 n) { return absl::StrCat(n); } bool HasPrefixString(const string& s, const string& prefix) { return absl::StartsWith(s, prefix); } size_t FindNth(const string& s, char c, int n) { size_t pos = string::npos; for (int i = 0; i < n; ++i) { pos = s.find_first_of(c, pos + 1); if (pos == string::npos) { break; } } return pos; } void SplitStringUsing(const string& s, char delimiter, vector<string>* result) { assert(result); for (absl::string_view split_piece : absl::StrSplit( s, absl::ByChar(delimiter), absl::SkipEmpty())) { result->push_back(std::string(split_piece)); } } bool TryStripPrefixString(const string& in, const string& prefix, string* out) { assert(out); const bool has_prefix = in.compare(0, prefix.length(), prefix) == 0; out->assign(has_prefix ? in.substr(prefix.length()) : in); return has_prefix; } bool HasSuffixString(const string& s, const string& suffix) { return absl::EndsWith(s, suffix); } template <typename T> void GenericAtoi(const string& s, T* out) { if (!absl::SimpleAtoi(s, out)) *out = 0; } void safe_strto32(const string& s, int32 *n) { GenericAtoi(s, n); } void safe_strtou64(const string& s, uint64 *n) { GenericAtoi(s, n); } void safe_strto64(const string& s, int64* n) { GenericAtoi(s, n); } void strrmm(string* s, const string& chars) { for (string::iterator it = s->begin(); it != s->end(); ) { const char current_char = *it; if (chars.find(current_char) != string::npos) { it = s->erase(it); } else { ++it; } } } int GlobalReplaceSubstring(const string& substring, const string& replacement, string* s) { return absl::StrReplaceAll({{substring, replacement}}, s);; } StringHolder::StringHolder(const string& s) : absl::AlphaNum(s) {} StringHolder::StringHolder(const char* cp) : absl::AlphaNum(cp) {} StringHolder::StringHolder(uint64 n) : absl::AlphaNum(n) {} StringHolder::~StringHolder() {} string& operator+=(string& lhs, const StringHolder& rhs) { absl::string_view s = rhs.GetString();; if (s.size() != 0) { lhs += s.data(); } else { const char* const cs = rhs.GetCString(); if (cs) lhs.append(cs, rhs.Length()); } return lhs; } string StrCat(const StringHolder& s1, const StringHolder& s2) { return absl::StrCat(s1, s2); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3) { return absl::StrCat(s1, s2, s3); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4) { return absl::StrCat(s1, s2, s3, s4); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5) { return absl::StrCat(s1, s2, s3, s4, s5); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6) { return absl::StrCat(s1, s2, s3, s4, s5, s6); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8) { string result; result.reserve(s1.Length() + s2.Length() + s3.Length() + s4.Length() + s5.Length() + s6.Length() + s7.Length() + s8.Length() + 1); return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14, const StringHolder& s15) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14, const StringHolder& s15, const StringHolder& s16) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16); } void StrAppend(string* dest, const StringHolder& s1) { absl::StrAppend(dest, s1); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2) { absl::StrAppend(dest, s1, s2); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3) { absl::StrAppend(dest, s1, s2, s3); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4) { absl::StrAppend(dest, s1, s2, s3, s4); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5) { absl::StrAppend(dest, s1, s2, s3, s4, s5); } } }
#include "phonenumbers/stringutil.h" #include <string> #include <vector> #include <gtest/gtest.h> using std::string; using std::vector; namespace i18n { namespace phonenumbers { TEST(StringUtilTest, OperatorPlus) { EXPECT_EQ("hello10", string("hello") + 10); } TEST(StringUtilTest, SimpleItoa) { EXPECT_EQ("10", SimpleItoa(10)); } TEST(StringUtilTest, HasPrefixString) { EXPECT_TRUE(HasPrefixString("hello world", "hello")); EXPECT_FALSE(HasPrefixString("hello world", "hellO")); } TEST(StringUtilTest, FindNthWithEmptyString) { EXPECT_EQ(string::npos, FindNth("", 'a', 1)); } TEST(StringUtilTest, FindNthWithNNegative) { EXPECT_EQ(string::npos, FindNth("hello world", 'o', -1)); } TEST(StringUtilTest, FindNthWithNTooHigh) { EXPECT_EQ(string::npos, FindNth("hello world", 'o', 3)); } TEST(StringUtilTest, FindNth) { EXPECT_EQ(7U, FindNth("hello world", 'o', 2)); } TEST(StringUtilTest, SplitStringUsingWithEmptyString) { vector<string> result; SplitStringUsing("", ':', &result); EXPECT_EQ(0U, result.size()); } TEST(StringUtilTest, SplitStringUsing) { vector<string> result; SplitStringUsing(":hello:world:", ':', &result); EXPECT_EQ(2U, result.size()); EXPECT_EQ("hello", result[0]); EXPECT_EQ("world", result[1]); } TEST(StringUtilTest, SplitStringUsingIgnoresEmptyToken) { vector<string> result; SplitStringUsing("hello::world", ':', &result); EXPECT_EQ(2U, result.size()); EXPECT_EQ("hello", result[0]); EXPECT_EQ("world", result[1]); } TEST(StringUtilTest, TryStripPrefixString) { string s; EXPECT_TRUE(TryStripPrefixString("hello world", "hello", &s)); EXPECT_EQ(" world", s); s.clear(); EXPECT_FALSE(TryStripPrefixString("hello world", "helloa", &s)); s.clear(); EXPECT_TRUE(TryStripPrefixString("hello world", "", &s)); EXPECT_EQ("hello world", s); s.clear(); EXPECT_FALSE(TryStripPrefixString("", "hello", &s)); s.clear(); } TEST(StringUtilTest, HasSuffixString) { EXPECT_TRUE(HasSuffixString("hello world", "hello world")); EXPECT_TRUE(HasSuffixString("hello world", "world")); EXPECT_FALSE(HasSuffixString("hello world", "world!")); EXPECT_TRUE(HasSuffixString("hello world", "")); EXPECT_FALSE(HasSuffixString("", "hello")); } TEST(StringUtilTest, safe_strto32) { int32 n; safe_strto32("0", &n); EXPECT_EQ(0, n); safe_strto32("16", &n); EXPECT_EQ(16, n); safe_strto32("2147483647", &n); EXPECT_EQ(2147483647, n); safe_strto32("-2147483648", &n); EXPECT_EQ(-2147483648LL, n); } TEST(StringUtilTest, safe_strtou64) { uint64 n; safe_strtou64("0", &n); EXPECT_EQ(0U, n); safe_strtou64("16", &n); EXPECT_EQ(16U, n); safe_strtou64("18446744073709551615", &n); EXPECT_EQ(18446744073709551615ULL, n); } TEST(StringUtilTest, strrmm) { string input("hello"); strrmm(&input, ""); EXPECT_EQ(input, input); string empty; strrmm(&empty, ""); EXPECT_EQ("", empty); strrmm(&empty, "aa"); EXPECT_EQ("", empty); strrmm(&input, "h"); EXPECT_EQ("ello", input); strrmm(&input, "el"); EXPECT_EQ("o", input); } TEST(StringUtilTest, GlobalReplaceSubstring) { string input("hello"); EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(0, GlobalReplaceSubstring("", "aaa", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(0, GlobalReplaceSubstring("", "", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "bbb", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(1, GlobalReplaceSubstring("o", "o world", &input)); ASSERT_EQ("hello world", input); EXPECT_EQ(2, GlobalReplaceSubstring("o", "O", &input)); EXPECT_EQ("hellO wOrld", input); } TEST(StringUtilTest, StringHolder) { static const char cstring[] = "aaa"; StringHolder sh1(cstring); EXPECT_EQ(cstring, sh1.GetCString()); string s = "aaa"; StringHolder sh2(s); EXPECT_EQ(cstring, sh2.GetString()); string s2 = "hello"; StringHolder sh3(s2); EXPECT_EQ(5U, sh3.Length()); StringHolder sh4(42); static const char cstring2[] = "42";; EXPECT_EQ(cstring2, sh4.GetString()); } TEST(StringUtilTest, OperatorPlusEquals) { string s = "h"; static const char append1[] = "ello"; s += StringHolder(append1); EXPECT_EQ("hello", s); s = "h"; string append2 = "ello"; s += StringHolder(append2); EXPECT_EQ("hello", s); } TEST(StringUtilTest, StrCat) { string s; s = StrCat("a", "b"); EXPECT_EQ("ab", s); s = StrCat("a", "b", "c"); EXPECT_EQ("abc", s); s = StrCat("a", "b", "c", "d"); EXPECT_EQ("abcd", s); s = StrCat("a", "b", "c", "d", "e"); EXPECT_EQ("abcde", s); s = StrCat("a", "b", "c", "d", "e", "f"); EXPECT_EQ("abcdef", s); s = StrCat("a", "b", "c", "d", "e", "f", "g"); EXPECT_EQ("abcdefg", s); s = StrCat("a", "b", "c", "d", "e", "f", "g", "h"); EXPECT_EQ("abcdefgh", s); s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i"); EXPECT_EQ("abcdefghi", s); s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); EXPECT_EQ("abcdefghijk", s); } TEST(StringUtilTest, StrAppend) { string s; StrAppend(&s, "a"); ASSERT_EQ("a", s); StrAppend(&s, "b", "c"); ASSERT_EQ("abc", s); StrAppend(&s, "d", "e", "f"); ASSERT_EQ("abcdef", s); StrAppend(&s, "g", "h", "i", "j"); ASSERT_EQ("abcdefghij", s); StrAppend(&s, "k", "l", "m", "n", "o"); ASSERT_EQ("abcdefghijklmno", s); StrAppend(&s, 42); ASSERT_EQ("abcdefghijklmno42", s); } } }
167
cpp
google/libphonenumber
unicodetext
cpp/src/phonenumbers/utf/unicodetext.cc
cpp/test/phonenumbers/utf/unicodetext_test.cc
#ifndef UTIL_UTF8_UNICODETEXT_H__ #define UTIL_UTF8_UNICODETEXT_H__ #include <iterator> #include <string> #include <utility> #include "phonenumbers/base/basictypes.h" namespace i18n { namespace phonenumbers { using std::string; using std::bidirectional_iterator_tag; using std::pair; class UnicodeText { public: class const_iterator; typedef char32 value_type; UnicodeText(); UnicodeText(const UnicodeText& src); UnicodeText(const const_iterator& first, const const_iterator& last); UnicodeText& operator=(const UnicodeText& src); UnicodeText& Copy(const UnicodeText& src); inline UnicodeText& assign(const UnicodeText& src) { return Copy(src); } UnicodeText& PointTo(const UnicodeText& src); UnicodeText& PointTo(const const_iterator& first, const const_iterator& last); ~UnicodeText(); void clear(); bool empty() { return repr_.size_ == 0; } void push_back(char32 codepoint); template<typename ForwardIterator> UnicodeText& append(ForwardIterator first, const ForwardIterator last) { while (first != last) { push_back(*first++); } return *this; } UnicodeText& append(const const_iterator& first, const const_iterator& last); UnicodeText& append(const UnicodeText& source); int size() const; friend bool operator==(const UnicodeText& lhs, const UnicodeText& rhs); friend bool operator!=(const UnicodeText& lhs, const UnicodeText& rhs); class const_iterator { typedef const_iterator CI; public: typedef bidirectional_iterator_tag iterator_category; typedef char32 value_type; typedef ptrdiff_t difference_type; typedef void pointer; typedef const char32 reference; const_iterator(); const_iterator(const const_iterator& other); const_iterator& operator=(const const_iterator& other); char32 operator*() const; const_iterator& operator++(); const_iterator operator++(int) { const_iterator result(*this); ++*this; return result; } const_iterator& operator--(); const_iterator operator--(int) { const_iterator result(*this); --*this; return result; } friend bool operator==(const CI& lhs, const CI& rhs) { return lhs.it_ == rhs.it_; } friend bool operator!=(const CI& lhs, const CI& rhs) { return !(lhs == rhs); } friend bool operator<(const CI& lhs, const CI& rhs); friend bool operator>(const CI& lhs, const CI& rhs) { return rhs < lhs; } friend bool operator<=(const CI& lhs, const CI& rhs) { return !(rhs < lhs); } friend bool operator>=(const CI& lhs, const CI& rhs) { return !(lhs < rhs); } friend difference_type distance(const CI& first, const CI& last); int get_utf8(char* buf) const; const char* utf8_data() const { return it_; } string DebugString() const; private: friend class UnicodeText; friend class UnicodeTextUtils; friend class UTF8StateTableProperty; explicit const_iterator(const char* it) : it_(it) {} const char* it_; }; const_iterator begin() const; const_iterator end() const; class const_reverse_iterator : public std::reverse_iterator<const_iterator> { public: const_reverse_iterator(const_iterator it) : std::reverse_iterator<const_iterator>(it) {} const char* utf8_data() const { const_iterator tmp_it = base(); return (--tmp_it).utf8_data(); } int get_utf8(char* buf) const { const_iterator tmp_it = base(); return (--tmp_it).get_utf8(buf); } }; const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } const_iterator find(const UnicodeText& look, const_iterator start_pos) const; const_iterator find(const UnicodeText& look) const; bool HasReplacementChar() const; const char* utf8_data() const { return repr_.data_; } int utf8_length() const { return repr_.size_; } int utf8_capacity() const { return repr_.capacity_; } static string UTF8Substring(const const_iterator& first, const const_iterator& last); UnicodeText& CopyUTF8(const char* utf8_buffer, int byte_length); UnicodeText& TakeOwnershipOfUTF8(char* utf8_buffer, int byte_length, int byte_capacity); UnicodeText& PointToUTF8(const char* utf8_buffer, int byte_length); bool UTF8WasValid() const { return repr_.utf8_was_valid_; } const_iterator MakeIterator(const char* p) const; string DebugString() const; private: friend class const_iterator; friend class UnicodeTextUtils; class Repr { public: char* data_; int size_; int capacity_; bool ours_; bool utf8_was_valid_; Repr() : data_(NULL), size_(0), capacity_(0), ours_(true), utf8_was_valid_(true) {} ~Repr() { if (ours_) delete[] data_; } void clear(); void reserve(int capacity); void resize(int size); void append(const char* bytes, int byte_length); void Copy(const char* data, int size); void TakeOwnershipOf(char* data, int size, int capacity); void PointTo(const char* data, int size); string DebugString() const; private: Repr& operator=(const Repr&); Repr(const Repr& other); }; Repr repr_; UnicodeText& UnsafeCopyUTF8(const char* utf8_buffer, int byte_length); UnicodeText& UnsafeTakeOwnershipOfUTF8( char* utf8_buffer, int byte_length, int byte_capacity); UnicodeText& UnsafePointToUTF8(const char* utf8_buffer, int byte_length); UnicodeText& UnsafeAppendUTF8(const char* utf8_buffer, int byte_length); const_iterator UnsafeFind(const UnicodeText& look, const_iterator start_pos) const; }; bool operator==(const UnicodeText& lhs, const UnicodeText& rhs); inline bool operator!=(const UnicodeText& lhs, const UnicodeText& rhs) { return !(lhs == rhs); } typedef pair<UnicodeText::const_iterator, UnicodeText::const_iterator> UnicodeTextRange; inline bool UnicodeTextRangeIsEmpty(const UnicodeTextRange& r) { return r.first == r.second; } inline UnicodeText MakeUnicodeTextAcceptingOwnership( char* utf8_buffer, int byte_length, int byte_capacity) { return UnicodeText().TakeOwnershipOfUTF8( utf8_buffer, byte_length, byte_capacity); } inline UnicodeText MakeUnicodeTextWithoutAcceptingOwnership( const char* utf8_buffer, int byte_length) { return UnicodeText().PointToUTF8(utf8_buffer, byte_length); } inline UnicodeText UTF8ToUnicodeText(const char* utf8_buf, int len, bool do_copy) { UnicodeText t; if (do_copy) { t.CopyUTF8(utf8_buf, len); } else { t.PointToUTF8(utf8_buf, len); } return t; } inline UnicodeText UTF8ToUnicodeText(const string& utf_string, bool do_copy) { return UTF8ToUnicodeText(utf_string.data(), static_cast<int>(utf_string.size()), do_copy); } inline UnicodeText UTF8ToUnicodeText(const char* utf8_buf, int len) { return UTF8ToUnicodeText(utf8_buf, len, true); } inline UnicodeText UTF8ToUnicodeText(const string& utf8_string) { return UTF8ToUnicodeText(utf8_string, true); } inline string UnicodeTextToUTF8(const UnicodeText& t) { return string(t.utf8_data(), t.utf8_length()); } } } #endif #include <algorithm> #include <sstream> #include <cassert> #include <cstdio> #include "phonenumbers/default_logger.h" #include "phonenumbers/utf/unicodetext.h" #include "phonenumbers/utf/stringpiece.h" #include "phonenumbers/utf/utf.h" #include "phonenumbers/utf/unilib.h" namespace i18n { namespace phonenumbers { using std::string; using std::stringstream; using std::max; using std::hex; using std::dec; static int CodepointDistance(const char* start, const char* end) { int n = 0; for (const char* p = start; p < end; ++p) { n += (*reinterpret_cast<const signed char*>(p) >= -0x40); } return n; } static int CodepointCount(const char* utf8, int len) { return CodepointDistance(utf8, utf8 + len); } UnicodeText::const_iterator::difference_type distance(const UnicodeText::const_iterator& first, const UnicodeText::const_iterator& last) { return CodepointDistance(first.it_, last.it_); } static int ConvertToInterchangeValid(char* start, int len) { char* const in = start; char* out = start; char* const end = start + len; while (start < end) { int good = UniLib::SpanInterchangeValid(start, static_cast<int>(end - start)); if (good > 0) { if (out != start) { memmove(out, start, good); } out += good; start += good; if (start == end) { break; } } Rune rune; int n; if (isvalidcharntorune(start, static_cast<int>(end - start), &rune, &n)) { start += n; } else { start += 1; } *out++ = ' '; } return static_cast<int>(out - in); } void UnicodeText::Repr::reserve(int new_capacity) { if (capacity_ >= new_capacity && ours_) return; capacity_ = max(new_capacity, (3 * capacity_) / 2 + 20); char* new_data = new char[capacity_]; if (data_) { memcpy(new_data, data_, size_); if (ours_) delete[] data_; } data_ = new_data; ours_ = true; } void UnicodeText::Repr::resize(int new_size) { if (new_size == 0) { clear(); } else { if (!ours_ || new_size > capacity_) reserve(new_size); if (size_ < new_size) memset(data_ + size_, 0, new_size - size_); size_ = new_size; ours_ = true; } } void UnicodeText::Repr::clear() { if (ours_) delete[] data_; data_ = NULL; size_ = capacity_ = 0; ours_ = true; } void UnicodeText::Repr::Copy(const char* data, int size) { resize(size); memcpy(data_, data, size); } void UnicodeText::Repr::TakeOwnershipOf(char* data, int size, int capacity) { if (data == data_) return; if (ours_ && data_) delete[] data_; data_ = data; size_ = size; capacity_ = capacity; ours_ = true; } void UnicodeText::Repr::PointTo(const char* data, int size) { if (ours_ && data_) delete[] data_; data_ = const_cast<char*>(data); size_ = size; capacity_ = size; ours_ = false; } void UnicodeText::Repr::append(const char* bytes, int byte_length) { reserve(size_ + byte_length); memcpy(data_ + size_, bytes, byte_length); size_ += byte_length; } string UnicodeText::Repr::DebugString() const { stringstream ss; ss << "{Repr " << hex << this << " data=" << data_ << " size=" << dec << size_ << " capacity=" << capacity_ << " " << (ours_ ? "Owned" : "Alias") << "}"; string result; ss >> result; return result; } UnicodeText::UnicodeText() { } UnicodeText::UnicodeText(const UnicodeText& src) { Copy(src); } UnicodeText::UnicodeText(const UnicodeText::const_iterator& first, const UnicodeText::const_iterator& last) { assert(first <= last && "Incompatible iterators"); repr_.append(first.it_, static_cast<int>(last.it_ - first.it_)); } string UnicodeText::UTF8Substring(const const_iterator& first, const const_iterator& last) { assert(first <= last && "Incompatible iterators"); return string(first.it_, last.it_ - first.it_); } UnicodeText& UnicodeText::operator=(const UnicodeText& src) { if (this != &src) { Copy(src); } return *this; } UnicodeText& UnicodeText::Copy(const UnicodeText& src) { repr_.Copy(src.repr_.data_, src.repr_.size_); return *this; } UnicodeText& UnicodeText::CopyUTF8(const char* buffer, int byte_length) { repr_.Copy(buffer, byte_length); repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length); if (!repr_.utf8_was_valid_) { LOG(WARNING) << "UTF-8 buffer is not interchange-valid."; repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length); } return *this; } UnicodeText& UnicodeText::UnsafeCopyUTF8(const char* buffer, int byte_length) { repr_.Copy(buffer, byte_length); return *this; } UnicodeText& UnicodeText::TakeOwnershipOfUTF8(char* buffer, int byte_length, int byte_capacity) { repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity); repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length); if (!repr_.utf8_was_valid_) { LOG(WARNING) << "UTF-8 buffer is not interchange-valid."; repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length); } return *this; } UnicodeText& UnicodeText::UnsafeTakeOwnershipOfUTF8(char* buffer, int byte_length, int byte_capacity) { repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity); return *this; } UnicodeText& UnicodeText::PointToUTF8(const char* buffer, int byte_length) { repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length); if (repr_.utf8_was_valid_) { repr_.PointTo(buffer, byte_length); } else { LOG(WARNING) << "UTF-8 buffer is not interchange-valid."; repr_.Copy(buffer, byte_length); repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length); } return *this; } UnicodeText& UnicodeText::UnsafePointToUTF8(const char* buffer, int byte_length) { repr_.PointTo(buffer, byte_length); return *this; } UnicodeText& UnicodeText::PointTo(const UnicodeText& src) { repr_.PointTo(src.repr_.data_, src.repr_.size_); return *this; } UnicodeText& UnicodeText::PointTo(const const_iterator &first, const const_iterator &last) { assert(first <= last && " Incompatible iterators"); repr_.PointTo(first.utf8_data(), static_cast<int>(last.utf8_data() - first.utf8_data())); return *this; } UnicodeText& UnicodeText::append(const UnicodeText& u) { repr_.append(u.repr_.data_, u.repr_.size_); return *this; } UnicodeText& UnicodeText::append(const const_iterator& first, const const_iterator& last) { assert(first <= last && "Incompatible iterators"); repr_.append(first.it_, static_cast<int>(last.it_ - first.it_)); return *this; } UnicodeText& UnicodeText::UnsafeAppendUTF8(const char* utf8, int len) { repr_.append(utf8, len); return *this; } UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look, const_iterator start_pos) const { assert(start_pos.utf8_data() >= utf8_data()); assert(start_pos.utf8_data() <= utf8_data() + utf8_length()); return UnsafeFind(look, start_pos); } UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look) const { return UnsafeFind(look, begin()); } UnicodeText::const_iterator UnicodeText::UnsafeFind( const UnicodeText& look, const_iterator start_pos) const { StringPiece searching(utf8_data(), utf8_length()); StringPiece look_piece(look.utf8_data(), look.utf8_length()); StringPiece::size_type found = searching.find(look_piece, start_pos.utf8_data() - utf8_data()); if (found == StringPiece::npos) return end(); return const_iterator(utf8_data() + found); } bool UnicodeText::HasReplacementChar() const { StringPiece searching(utf8_data(), utf8_length()); StringPiece looking_for("\xEF\xBF\xBD", 3); return searching.find(looking_for) != StringPiece::npos; } void UnicodeText::clear() { repr_.clear(); } UnicodeText::~UnicodeText() {} void UnicodeText::push_back(char32 c) { if (UniLib::IsValidCodepoint(c)) { char buf[UTFmax]; Rune rune = c; int len = runetochar(buf, &rune); if (UniLib::IsInterchangeValid(buf, len)) { repr_.append(buf, len); } else { fprintf(stderr, "Unicode value 0x%x is not valid for interchange\n", c); repr_.append(" ", 1); } } else { fprintf(stderr, "Illegal Unicode value: 0x%x\n", c); repr_.append(" ", 1); } } int UnicodeText::size() const { return CodepointCount(repr_.data_, repr_.size_); } bool operator==(const UnicodeText& lhs, const UnicodeText& rhs) { if (&lhs == &rhs) return true; if (lhs.repr_.size_ != rhs.repr_.size_) return false; return memcmp(lhs.repr_.data_, rhs.repr_.data_, lhs.repr_.size_) == 0; } string UnicodeText::DebugString() const { stringstream ss; ss << "{UnicodeText " << hex << this << dec << " chars=" << size() << " repr=" << repr_.DebugString() << "}"; #if 0 return StringPrintf("{UnicodeText %p chars=%d repr=%s}", this, size(), repr_.DebugString().c_str()); #endif string result; ss >> result; return result; } UnicodeText::const_iterator::const_iterator() : it_(0) {} UnicodeText::const_iterator::const_iterator(const const_iterator& other) : it_(other.it_) { } UnicodeText::const_iterator& UnicodeText::const_iterator::operator=(const const_iterator& other) { if (&other != this) it_ = other.it_; return *this; } UnicodeText::const_iterator UnicodeText::begin() const { return const_iterator(repr_.data_); } UnicodeText::const_iterator UnicodeText::end() const { return const_iterator(repr_.data_ + repr_.size_); } bool operator<(const UnicodeText::const_iterator& lhs, const UnicodeText::const_iterator& rhs) { return lhs.it_ < rhs.it_; } char32 UnicodeText::const_iterator::operator*() const { uint8 byte1 = static_cast<uint8>(it_[0]); if (byte1 < 0x80) return byte1; uint8 byte2 = static_cast<uint8>(it_[1]); if (byte1 < 0xE0) return ((byte1 & 0x1F) << 6) | (byte2 & 0x3F); uint8 byte3 = static_cast<uint8>(it_[2]); if (byte1 < 0xF0) return ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F); uint8 byte4 = static_cast<uint8>(it_[3]); return ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) | ((byte3 & 0x3F) << 6) | (byte4 & 0x3F); } UnicodeText::const_iterator& UnicodeText::const_iterator::operator++() { it_ += UniLib::OneCharLen(it_); return *this; } UnicodeText::const_iterator& UnicodeText::const_iterator::operator--() { while (UniLib::IsTrailByte(*--it_)) { } return *this; } int UnicodeText::const_iterator::get_utf8(char* utf8_output) const { utf8_output[0] = it_[0]; if (static_cast<unsigned char>(it_[0]) < 0x80) return 1; utf8_output[1] = it_[1]; if (static_cast<unsigned char>(it_[0]) < 0xE0) return 2; utf8_output[2] = it_[2]; if (static_cast<unsigned char>(it_[0]) < 0xF0) return 3; utf8_output[3] = it_[3]; return 4; } UnicodeText::const_iterator UnicodeText::MakeIterator(const char* p) const { #ifn
#include <gtest/gtest.h> #include "phonenumbers/utf/unicodetext.h" namespace i18n { namespace phonenumbers { TEST(UnicodeTextTest, Iterator) { struct value { const char* utf8; char32 code_point; } values[] = { { "\x31", 0x31 }, { "\xC2\xBD", 0x00BD }, { "\xEF\xBC\x91", 0xFF11 }, { "\xF0\x9F\x80\x80", 0x1F000 }, }; for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) { string number(values[i].utf8); UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(number.data(), number.size()); EXPECT_TRUE(number_as_unicode.UTF8WasValid()); UnicodeText::const_iterator it = number_as_unicode.begin(); EXPECT_EQ(values[i].code_point, *it); } } } }
168
cpp
google/libphonenumber
phonenumber_offline_geocoder
cpp/src/phonenumbers/geocoding/phonenumber_offline_geocoder.cc
cpp/test/phonenumbers/geocoding/phonenumber_offline_geocoder_test.cc
#ifndef I18N_PHONENUMBERS_GEOCODING_PHONENUMBER_OFFLINE_GEOCODER_H_ #define I18N_PHONENUMBERS_GEOCODING_PHONENUMBER_OFFLINE_GEOCODER_H_ #include <map> #include <string> #include <unicode/locid.h> #include "absl/synchronization/mutex.h" #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" namespace i18n { namespace phonenumbers { using std::map; using std::string; class AreaCodeMap; class MappingFileProvider; class PhoneNumber; class PhoneNumberUtil; struct CountryLanguages; struct PrefixDescriptions; typedef icu::Locale Locale; class PhoneNumberOfflineGeocoder { private: typedef map<string, const AreaCodeMap*> AreaCodeMaps; public: typedef const CountryLanguages* (*country_languages_getter)(int index); typedef const PrefixDescriptions* (*prefix_descriptions_getter)(int index); PhoneNumberOfflineGeocoder(); PhoneNumberOfflineGeocoder( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions); PhoneNumberOfflineGeocoder(const PhoneNumberOfflineGeocoder&) = delete; PhoneNumberOfflineGeocoder& operator=(const PhoneNumberOfflineGeocoder&) = delete; virtual ~PhoneNumberOfflineGeocoder(); string GetDescriptionForValidNumber(const PhoneNumber& number, const Locale& language) const; string GetDescriptionForValidNumber(const PhoneNumber& number, const Locale& language, const string& user_region) const; string GetDescriptionForNumber(const PhoneNumber& number, const Locale& locale) const; string GetDescriptionForNumber(const PhoneNumber& number, const Locale& language, const string& user_region) const; private: void Init(const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions); const AreaCodeMap* LoadAreaCodeMapFromFile( const string& filename) const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); const AreaCodeMap* GetPhonePrefixDescriptions( int prefix, const string& language, const string& script, const string& region) const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); string GetRegionDisplayName(const string* region_code, const Locale& language) const; string GetCountryNameForNumber(const PhoneNumber& number, const Locale& language) const; const char* GetAreaDescription(const PhoneNumber& number, const string& lang, const string& script, const string& region) const ABSL_LOCKS_EXCLUDED(mu_); bool MayFallBackToEnglish(const string& lang) const; private: const PhoneNumberUtil* phone_util_; scoped_ptr<const MappingFileProvider> provider_; const char** prefix_language_code_pairs_; int prefix_language_code_pairs_size_; prefix_descriptions_getter get_prefix_descriptions_; mutable absl::Mutex mu_; mutable AreaCodeMaps available_maps_ ABSL_GUARDED_BY(mu_); }; } } #endif #include "phonenumbers/geocoding/phonenumber_offline_geocoder.h" #include <algorithm> #include <string> #include <unicode/unistr.h> #include "phonenumbers/geocoding/area_code_map.h" #include "phonenumbers/geocoding/geocoding_data.h" #include "phonenumbers/geocoding/mapping_file_provider.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stl_util.h" #include "absl/synchronization/mutex.h" namespace i18n { namespace phonenumbers { using icu::UnicodeString; using std::string; namespace { bool IsLowerThan(const char* s1, const char* s2) { return strcmp(s1, s2) < 0; } } PhoneNumberOfflineGeocoder::PhoneNumberOfflineGeocoder() { Init(get_country_calling_codes(), get_country_calling_codes_size(), get_country_languages, get_prefix_language_code_pairs(), get_prefix_language_code_pairs_size(), get_prefix_descriptions); } PhoneNumberOfflineGeocoder::PhoneNumberOfflineGeocoder( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { Init(country_calling_codes, country_calling_codes_size, get_country_languages, prefix_language_code_pairs, prefix_language_code_pairs_size, get_prefix_descriptions); } void PhoneNumberOfflineGeocoder::Init( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { phone_util_ = PhoneNumberUtil::GetInstance(); provider_.reset(new MappingFileProvider(country_calling_codes, country_calling_codes_size, get_country_languages)); prefix_language_code_pairs_ = prefix_language_code_pairs; prefix_language_code_pairs_size_ = prefix_language_code_pairs_size; get_prefix_descriptions_ = get_prefix_descriptions; } PhoneNumberOfflineGeocoder::~PhoneNumberOfflineGeocoder() { absl::MutexLock l(&mu_); gtl::STLDeleteContainerPairSecondPointers( available_maps_.begin(), available_maps_.end()); } const AreaCodeMap* PhoneNumberOfflineGeocoder::GetPhonePrefixDescriptions( int prefix, const string& language, const string& script, const string& region) const { string filename; provider_->GetFileName(prefix, language, script, region, &filename); if (filename.empty()) { return NULL; } AreaCodeMaps::const_iterator it = available_maps_.find(filename); if (it == available_maps_.end()) { return LoadAreaCodeMapFromFile(filename); } return it->second; } const AreaCodeMap* PhoneNumberOfflineGeocoder::LoadAreaCodeMapFromFile( const string& filename) const { const char** const prefix_language_code_pairs_end = prefix_language_code_pairs_ + prefix_language_code_pairs_size_; const char** const prefix_language_code_pair = std::lower_bound(prefix_language_code_pairs_, prefix_language_code_pairs_end, filename.c_str(), IsLowerThan); if (prefix_language_code_pair != prefix_language_code_pairs_end && filename.compare(*prefix_language_code_pair) == 0) { AreaCodeMap* const m = new AreaCodeMap(); m->ReadAreaCodeMap(get_prefix_descriptions_( prefix_language_code_pair - prefix_language_code_pairs_)); return available_maps_.insert(AreaCodeMaps::value_type(filename, m)) .first->second; } return NULL; } string PhoneNumberOfflineGeocoder::GetCountryNameForNumber( const PhoneNumber& number, const Locale& language) const { string region_code; phone_util_->GetRegionCodeForNumber(number, &region_code); return GetRegionDisplayName(&region_code, language); } string PhoneNumberOfflineGeocoder::GetRegionDisplayName( const string* region_code, const Locale& language) const { if (region_code == NULL || region_code->compare("ZZ") == 0 || region_code->compare( PhoneNumberUtil::kRegionCodeForNonGeoEntity) == 0) { return ""; } UnicodeString udisplay_country; icu::Locale("", region_code->c_str()).getDisplayCountry( language, udisplay_country); string display_country; udisplay_country.toUTF8String(display_country); return display_country; } string PhoneNumberOfflineGeocoder::GetDescriptionForValidNumber( const PhoneNumber& number, const Locale& language) const { const char* const description = GetAreaDescription( number, language.getLanguage(), "", language.getCountry()); return *description != '\0' ? description : GetCountryNameForNumber(number, language); } string PhoneNumberOfflineGeocoder::GetDescriptionForValidNumber( const PhoneNumber& number, const Locale& language, const string& user_region) const { string region_code; phone_util_->GetRegionCodeForNumber(number, &region_code); if (user_region.compare(region_code) == 0) { return GetDescriptionForValidNumber(number, language); } return GetRegionDisplayName(&region_code, language); } string PhoneNumberOfflineGeocoder::GetDescriptionForNumber( const PhoneNumber& number, const Locale& locale) const { PhoneNumberUtil::PhoneNumberType number_type = phone_util_->GetNumberType(number); if (number_type == PhoneNumberUtil::UNKNOWN) { return ""; } else if (!phone_util_->IsNumberGeographical(number_type, number.country_code())) { return GetCountryNameForNumber(number, locale); } return GetDescriptionForValidNumber(number, locale); } string PhoneNumberOfflineGeocoder::GetDescriptionForNumber( const PhoneNumber& number, const Locale& language, const string& user_region) const { PhoneNumberUtil::PhoneNumberType number_type = phone_util_->GetNumberType(number); if (number_type == PhoneNumberUtil::UNKNOWN) { return ""; } else if (!phone_util_->IsNumberGeographical(number_type, number.country_code())) { return GetCountryNameForNumber(number, language); } return GetDescriptionForValidNumber(number, language, user_region); } const char* PhoneNumberOfflineGeocoder::GetAreaDescription( const PhoneNumber& number, const string& lang, const string& script, const string& region) const { const int country_calling_code = number.country_code(); const int phone_prefix = country_calling_code; absl::MutexLock l(&mu_); const AreaCodeMap* const descriptions = GetPhonePrefixDescriptions( phone_prefix, lang, script, region); const char* description = descriptions ? descriptions->Lookup(number) : NULL; if ((!description || *description == '\0') && MayFallBackToEnglish(lang)) { const AreaCodeMap* default_descriptions = GetPhonePrefixDescriptions( phone_prefix, "en", "", ""); if (!default_descriptions) { return ""; } description = default_descriptions->Lookup(number); } return description ? description : ""; } bool PhoneNumberOfflineGeocoder::MayFallBackToEnglish( const string& lang) const { return lang.compare("zh") && lang.compare("ja") && lang.compare("ko"); } } }
#include "phonenumbers/geocoding/phonenumber_offline_geocoder.h" #include <gtest/gtest.h> #include <unicode/locid.h> #include "phonenumbers/geocoding/geocoding_test_data.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { using icu::Locale; namespace { PhoneNumber MakeNumber(int32 country_code, uint64 national_number) { PhoneNumber n; n.set_country_code(country_code); n.set_national_number(national_number); return n; } const Locale kEnglishLocale = Locale("en", "GB"); const Locale kFrenchLocale = Locale("fr", "FR"); const Locale kGermanLocale = Locale("de", "DE"); const Locale kItalianLocale = Locale("it", "IT"); const Locale kKoreanLocale = Locale("ko", "KR"); const Locale kSimplifiedChineseLocale = Locale("zh", "CN"); } class PhoneNumberOfflineGeocoderTest : public testing::Test { protected: PhoneNumberOfflineGeocoderTest() : KO_NUMBER1(MakeNumber(82, 22123456UL)), KO_NUMBER2(MakeNumber(82, 322123456UL)), KO_NUMBER3(MakeNumber(82, uint64{6421234567})), KO_INVALID_NUMBER(MakeNumber(82, 1234UL)), KO_MOBILE(MakeNumber(82, uint64{101234567})), US_NUMBER1(MakeNumber(1, uint64{6502530000})), US_NUMBER2(MakeNumber(1, uint64{6509600000})), US_NUMBER3(MakeNumber(1, 2128120000UL)), US_NUMBER4(MakeNumber(1, uint64{6174240000})), US_INVALID_NUMBER(MakeNumber(1, 123456789UL)), BS_NUMBER1(MakeNumber(1, 2423651234UL)), AU_NUMBER(MakeNumber(61, 236618300UL)), NUMBER_WITH_INVALID_COUNTRY_CODE(MakeNumber(999, 2423651234UL)), INTERNATIONAL_TOLL_FREE(MakeNumber(800, 12345678UL)) { } virtual void SetUp() { geocoder_.reset( new PhoneNumberOfflineGeocoder( get_test_country_calling_codes(), get_test_country_calling_codes_size(), get_test_country_languages, get_test_prefix_language_code_pairs(), get_test_prefix_language_code_pairs_size(), get_test_prefix_descriptions)); } protected: scoped_ptr<PhoneNumberOfflineGeocoder> geocoder_; const PhoneNumber KO_NUMBER1; const PhoneNumber KO_NUMBER2; const PhoneNumber KO_NUMBER3; const PhoneNumber KO_INVALID_NUMBER; const PhoneNumber KO_MOBILE; const PhoneNumber US_NUMBER1; const PhoneNumber US_NUMBER2; const PhoneNumber US_NUMBER3; const PhoneNumber US_NUMBER4; const PhoneNumber US_INVALID_NUMBER; const PhoneNumber BS_NUMBER1; const PhoneNumber AU_NUMBER; const PhoneNumber NUMBER_WITH_INVALID_COUNTRY_CODE; const PhoneNumber INTERNATIONAL_TOLL_FREE; }; TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumberWithNoDataFile) { EXPECT_EQ("\xe7""\xbe""\x8e""\xe5""\x9b""\xbd", geocoder_->GetDescriptionForNumber(US_NUMBER1, kSimplifiedChineseLocale)); EXPECT_EQ("Bahamas", geocoder_->GetDescriptionForNumber(BS_NUMBER1, Locale("en", "US"))); EXPECT_EQ("Australia", geocoder_->GetDescriptionForNumber(AU_NUMBER, Locale("en", "US"))); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(NUMBER_WITH_INVALID_COUNTRY_CODE, Locale("en", "US"))); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(INTERNATIONAL_TOLL_FREE, Locale("en", "US"))); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumberWithMissingPrefix) { EXPECT_EQ("United States", geocoder_->GetDescriptionForNumber(US_NUMBER4, Locale("en", "US"))); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumber_en_US) { EXPECT_EQ("CA", geocoder_->GetDescriptionForNumber(US_NUMBER1, Locale("en", "US"))); EXPECT_EQ("Mountain View, CA", geocoder_->GetDescriptionForNumber(US_NUMBER2, Locale("en", "US"))); EXPECT_EQ("New York, NY", geocoder_->GetDescriptionForNumber(US_NUMBER3, Locale("en", "US"))); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForKoreanNumber) { EXPECT_EQ("Seoul", geocoder_->GetDescriptionForNumber(KO_NUMBER1, kEnglishLocale)); EXPECT_EQ("Incheon", geocoder_->GetDescriptionForNumber(KO_NUMBER2, kEnglishLocale)); EXPECT_EQ("Jeju", geocoder_->GetDescriptionForNumber(KO_NUMBER3, kEnglishLocale)); EXPECT_EQ("\xec""\x84""\x9c""\xec""\x9a""\xb8", geocoder_->GetDescriptionForNumber(KO_NUMBER1, kKoreanLocale)); EXPECT_EQ("\xec""\x9d""\xb8""\xec""\xb2""\x9c", geocoder_->GetDescriptionForNumber(KO_NUMBER2, kKoreanLocale)); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForFallBack) { EXPECT_EQ("Kalifornien", geocoder_->GetDescriptionForNumber(US_NUMBER1, kGermanLocale)); EXPECT_EQ("New York, NY", geocoder_->GetDescriptionForNumber(US_NUMBER3, kGermanLocale)); EXPECT_EQ("CA", geocoder_->GetDescriptionForNumber(US_NUMBER1, kItalianLocale)); EXPECT_EQ("\xeb""\x8c""\x80""\xed""\x95""\x9c""\xeb""\xaf""\xbc""\xea""\xb5" "\xad", geocoder_->GetDescriptionForNumber(KO_NUMBER3, kKoreanLocale)); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumberWithUserRegion) { EXPECT_EQ("Estados Unidos", geocoder_->GetDescriptionForNumber(US_NUMBER1, Locale("es", "ES"), "IT")); EXPECT_EQ("Estados Unidos", geocoder_->GetDescriptionForNumber(US_NUMBER1, Locale("es", "ES"), "ZZ")); EXPECT_EQ("Kalifornien", geocoder_->GetDescriptionForNumber(US_NUMBER1, kGermanLocale, "US")); EXPECT_EQ("CA", geocoder_->GetDescriptionForNumber(US_NUMBER1, kFrenchLocale, "US")); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(US_INVALID_NUMBER, kEnglishLocale, "US")); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForInvalidNumber) { EXPECT_EQ("", geocoder_->GetDescriptionForNumber(KO_INVALID_NUMBER, kEnglishLocale)); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(US_INVALID_NUMBER, kEnglishLocale)); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNonGeographicalNumberWithGeocodingPrefix) { EXPECT_EQ("South Korea", geocoder_->GetDescriptionForNumber(KO_MOBILE, kEnglishLocale)); } } }
169
cpp
google/libphonenumber
mapping_file_provider
cpp/src/phonenumbers/geocoding/mapping_file_provider.cc
cpp/test/phonenumbers/geocoding/mapping_file_provider_test.cc
#ifndef I18N_PHONENUMBERS_GEOCODING_MAPPING_FILE_PROVIDER_H_ #define I18N_PHONENUMBERS_GEOCODING_MAPPING_FILE_PROVIDER_H_ #include <string> #include "phonenumbers/base/basictypes.h" namespace i18n { namespace phonenumbers { using std::string; struct CountryLanguages; class MappingFileProvider { public: typedef const CountryLanguages* (*country_languages_getter)(int index); MappingFileProvider(const int* country_calling_codes, int country_calling_code_size, country_languages_getter get_country_languages); MappingFileProvider(const MappingFileProvider&) = delete; MappingFileProvider& operator=(const MappingFileProvider&) = delete; const string& GetFileName(int country_calling_code, const string& language, const string& script, const string& region, string* filename) const; private: void FindBestMatchingLanguageCode(const CountryLanguages* languages, const string& language, const string& script, const string& region, string* best_match) const; const int* const country_calling_codes_; const int country_calling_codes_size_; const country_languages_getter get_country_languages_; }; } } #endif #include "phonenumbers/geocoding/mapping_file_provider.h" #include <algorithm> #include <cstddef> #include <cstring> #include <sstream> #include <string> #include "phonenumbers/geocoding/geocoding_data.h" namespace i18n { namespace phonenumbers { using std::string; namespace { struct NormalizedLocale { const char* locale; const char* normalized_locale; }; const NormalizedLocale kNormalizedLocales[] = { {"zh_TW", "zh_Hant"}, {"zh_HK", "zh_Hant"}, {"zh_MO", "zh_Hant"}, }; const char* GetNormalizedLocale(const string& full_locale) { const int size = sizeof(kNormalizedLocales) / sizeof(*kNormalizedLocales); for (int i = 0; i != size; ++i) { if (full_locale.compare(kNormalizedLocales[i].locale) == 0) { return kNormalizedLocales[i].normalized_locale; } } return NULL; } void AppendLocalePart(const string& part, string* full_locale) { if (!part.empty()) { full_locale->append("_"); full_locale->append(part); } } void ConstructFullLocale(const string& language, const string& script, const string& region, string* full_locale) { full_locale->assign(language); AppendLocalePart(script, full_locale); AppendLocalePart(region, full_locale); } bool IsLowerThan(const char* s1, const char* s2) { return strcmp(s1, s2) < 0; } bool HasLanguage(const CountryLanguages* languages, const string& language) { const char** const start = languages->available_languages; const char** const end = start + languages->available_languages_size; const char** const it = std::lower_bound(start, end, language.c_str(), IsLowerThan); return it != end && strcmp(language.c_str(), *it) == 0; } } MappingFileProvider::MappingFileProvider( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages) : country_calling_codes_(country_calling_codes), country_calling_codes_size_(country_calling_codes_size), get_country_languages_(get_country_languages) { } const string& MappingFileProvider::GetFileName(int country_calling_code, const string& language, const string& script, const string& region, string* filename) const { filename->clear(); if (language.empty()) { return *filename; } const int* const country_calling_codes_end = country_calling_codes_ + country_calling_codes_size_; const int* const it = std::lower_bound(country_calling_codes_, country_calling_codes_end, country_calling_code); if (it == country_calling_codes_end || *it != country_calling_code) { return *filename; } const CountryLanguages* const langs = get_country_languages_(it - country_calling_codes_); if (langs->available_languages_size > 0) { string language_code; FindBestMatchingLanguageCode(langs, language, script, region, &language_code); if (!language_code.empty()) { std::stringstream filename_buf; filename_buf << country_calling_code << "_" << language_code; *filename = filename_buf.str(); } } return *filename; } void MappingFileProvider::FindBestMatchingLanguageCode( const CountryLanguages* languages, const string& language, const string& script, const string& region, string* best_match) const { string full_locale; ConstructFullLocale(language, script, region, &full_locale); const char* const normalized_locale = GetNormalizedLocale(full_locale); if (normalized_locale != NULL) { string normalized_locale_str(normalized_locale); if (HasLanguage(languages, normalized_locale_str)) { best_match->swap(normalized_locale_str); return; } } if (HasLanguage(languages, full_locale)) { best_match->swap(full_locale); return; } if (script.empty() != region.empty()) { if (HasLanguage(languages, language)) { *best_match = language; return; } } else if (!script.empty() && !region.empty()) { string lang_with_script(language); lang_with_script.append("_"); lang_with_script.append(script); if (HasLanguage(languages, lang_with_script)) { best_match->swap(lang_with_script); return; } } string lang_with_region(language); lang_with_region.append("_"); lang_with_region.append(region); if (HasLanguage(languages, lang_with_region)) { best_match->swap(lang_with_region); return; } if (HasLanguage(languages, language)) { *best_match = language; return; } best_match->clear(); } } }
#include "phonenumbers/geocoding/mapping_file_provider.h" #include <gtest/gtest.h> #include "phonenumbers/geocoding/geocoding_data.h" namespace i18n { namespace phonenumbers { using std::string; namespace { #define COUNTRY_LANGUAGES(code, languagelist) \ const char* country_languages_##code[] = languagelist; \ const CountryLanguages country_##code = { \ country_languages_##code, \ sizeof(country_languages_##code) / sizeof(*country_languages_##code), \ }; #define ARRAY_WRAPPER(...) __VA_ARGS__ const int country_calling_codes[] = {1, 41, 65, 86}; const int country_calling_codes_size = sizeof(country_calling_codes) / sizeof(*country_calling_codes); COUNTRY_LANGUAGES(1, ARRAY_WRAPPER({"en"})); COUNTRY_LANGUAGES(41, ARRAY_WRAPPER({"de", "fr", "it", "rm"})); COUNTRY_LANGUAGES(65, ARRAY_WRAPPER({"en", "ms", "ta", "zh_Hans"})); COUNTRY_LANGUAGES(86, ARRAY_WRAPPER({"en", "zh", "zh_Hant"})); const CountryLanguages* country_languages[] = { &country_1, &country_41, &country_65, &country_86, }; const CountryLanguages* test_get_country_languages(int index) { return country_languages[index]; } } TEST(MappingFileProviderTest, TestGetFileName) { MappingFileProvider provider(country_calling_codes, country_calling_codes_size, test_get_country_languages); string filename; EXPECT_EQ("1_en", provider.GetFileName(1, "en", "", "", &filename)); EXPECT_EQ("1_en", provider.GetFileName(1, "en", "", "US", &filename)); EXPECT_EQ("1_en", provider.GetFileName(1, "en", "", "GB", &filename)); EXPECT_EQ("41_de", provider.GetFileName(41, "de", "", "CH", &filename)); EXPECT_EQ("", provider.GetFileName(44, "en", "", "GB", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "", "", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "Hans", "", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "", "CN", &filename)); EXPECT_EQ("", provider.GetFileName(86, "", "", "CN", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "Hans", "CN", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "Hans", "SG", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "", "SG", &filename)); EXPECT_EQ("86_zh_Hant", provider.GetFileName(86, "zh", "", "TW", &filename)); EXPECT_EQ("86_zh_Hant", provider.GetFileName(86, "zh", "", "HK", &filename)); EXPECT_EQ("86_zh_Hant", provider.GetFileName(86, "zh", "Hant", "TW", &filename)); } } }
170
cpp
google/libphonenumber
area_code_map
cpp/src/phonenumbers/geocoding/area_code_map.cc
cpp/test/phonenumbers/geocoding/area_code_map_test.cc
#ifndef I18N_PHONENUMBERS_AREA_CODE_MAP_H_ #define I18N_PHONENUMBERS_AREA_CODE_MAP_H_ #include <cstdint> #include <map> #include <string> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" namespace i18n { namespace phonenumbers { using std::map; using std::string; class DefaultMapStorage; class PhoneNumber; class PhoneNumberUtil; struct PrefixDescriptions; class AreaCodeMap { public: AreaCodeMap(); AreaCodeMap(const AreaCodeMap&) = delete; AreaCodeMap& operator=(const AreaCodeMap&) = delete; ~AreaCodeMap(); const char* Lookup(const PhoneNumber& number) const; void ReadAreaCodeMap(const PrefixDescriptions* descriptions); private: int BinarySearch(int start, int end, int64_t value) const; const PhoneNumberUtil& phone_util_; scoped_ptr<const DefaultMapStorage> storage_; }; } } #endif #include "phonenumbers/geocoding/area_code_map.h" #include <cstddef> #include "phonenumbers/geocoding/default_map_storage.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stringutil.h" namespace i18n { namespace phonenumbers { AreaCodeMap::AreaCodeMap() : phone_util_(*PhoneNumberUtil::GetInstance()) { } AreaCodeMap::~AreaCodeMap() { } void AreaCodeMap::ReadAreaCodeMap(const PrefixDescriptions* descriptions) { DefaultMapStorage* storage = new DefaultMapStorage(); storage->ReadFromMap(descriptions); storage_.reset(storage); } const char* AreaCodeMap::Lookup(const PhoneNumber& number) const { const int entries = storage_->GetNumOfEntries(); if (!entries) { return NULL; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); int64 phone_prefix; safe_strto64(SimpleItoa(number.country_code()) + national_number, &phone_prefix); const int* const lengths = storage_->GetPossibleLengths(); const int lengths_size = storage_->GetPossibleLengthsSize(); int current_index = entries - 1; for (int lengths_index = lengths_size - 1; lengths_index >= 0; --lengths_index) { const int possible_length = lengths[lengths_index]; string phone_prefix_str = SimpleItoa(phone_prefix); if (static_cast<int>(phone_prefix_str.length()) > possible_length) { safe_strto64(phone_prefix_str.substr(0, possible_length), &phone_prefix); } current_index = BinarySearch(0, current_index, phone_prefix); if (current_index < 0) { return NULL; } const int32 current_prefix = storage_->GetPrefix(current_index); if (phone_prefix == current_prefix) { return storage_->GetDescription(current_index); } } return NULL; } int AreaCodeMap::BinarySearch(int start, int end, int64 value) const { int current = 0; while (start <= end) { current = (start + end) / 2; int32 current_value = storage_->GetPrefix(current); if (current_value == value) { return current; } else if (current_value > value) { --current; end = current; } else { start = current + 1; } } return current; } } }
#include "phonenumbers/geocoding/area_code_map.h" #include <cstddef> #include <vector> #include <gtest/gtest.h> #include "phonenumbers/geocoding/geocoding_data.h" #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { namespace { void MakeCodeMap(const PrefixDescriptions* descriptions, scoped_ptr<AreaCodeMap>* code_map) { scoped_ptr<AreaCodeMap> cm(new AreaCodeMap()); cm->ReadAreaCodeMap(descriptions); code_map->swap(cm); } const int32 prefix_1_us_prefixes[] = { 1212, 1480, 1650, 1907, 1201664, 1480893, 1501372, 1626308, 1650345, 1867993, 1972480, }; const char* prefix_1_us_descriptions[] = { "New York", "Arizona", "California", "Alaska", "Westwood, NJ", "Phoenix, AZ", "Little Rock, AR", "Alhambra, CA", "San Mateo, CA", "Dawson, YT", "Richardson, TX", }; const int32 prefix_1_us_lengths[] = { 4, 7, }; const PrefixDescriptions prefix_1_us = { prefix_1_us_prefixes, sizeof(prefix_1_us_prefixes) / sizeof(*prefix_1_us_prefixes), prefix_1_us_descriptions, prefix_1_us_lengths, sizeof(prefix_1_us_lengths) / sizeof(*prefix_1_us_lengths), }; const int32 prefix_39_it_prefixes[] = { 3902, 3906, 39010, 390131, 390321, 390975, }; const char* prefix_39_it_descriptions[] = { "Milan", "Rome", "Genoa", "Alessandria", "Novara", "Potenza", }; const int32 prefix_39_it_lengths[] = { 4, 5, 6, }; const PrefixDescriptions prefix_39_it = { prefix_39_it_prefixes, sizeof(prefix_39_it_prefixes) / sizeof(*prefix_39_it_prefixes), prefix_39_it_descriptions, prefix_39_it_lengths, sizeof(prefix_39_it_lengths) / sizeof(*prefix_1_us_lengths), }; void MakeCodeMapUS(scoped_ptr<AreaCodeMap>* code_map) { MakeCodeMap(&prefix_1_us, code_map); } void MakeCodeMapIT(scoped_ptr<AreaCodeMap>* code_map) { MakeCodeMap(&prefix_39_it, code_map); } PhoneNumber MakePhoneNumber(int32 country_code, uint64 national_number) { PhoneNumber number; number.set_country_code(country_code); number.set_national_number(national_number); return number; } } class AreaCodeMapTest : public testing::Test { protected: virtual void SetUp() { MakeCodeMapUS(&map_US_); MakeCodeMapIT(&map_IT_); } scoped_ptr<AreaCodeMap> map_US_; scoped_ptr<AreaCodeMap> map_IT_; }; TEST_F(AreaCodeMapTest, TestLookupInvalidNumberUS) { EXPECT_STREQ("New York", map_US_->Lookup(MakePhoneNumber(1, 2121234567L))); } TEST_F(AreaCodeMapTest, TestLookupNumberNJ) { EXPECT_STREQ("Westwood, NJ", map_US_->Lookup(MakePhoneNumber(1, 2016641234L))); } TEST_F(AreaCodeMapTest, TestLookupNumberNY) { EXPECT_STREQ("New York", map_US_->Lookup(MakePhoneNumber(1, 2126641234L))); } TEST_F(AreaCodeMapTest, TestLookupNumberCA1) { EXPECT_STREQ("San Mateo, CA", map_US_->Lookup(MakePhoneNumber(1, 6503451234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberCA2) { EXPECT_STREQ("California", map_US_->Lookup(MakePhoneNumber(1, 6502531234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberTX) { EXPECT_STREQ("Richardson, TX", map_US_->Lookup(MakePhoneNumber(1, 9724801234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberNotFoundTX) { EXPECT_STREQ(NULL, map_US_->Lookup(MakePhoneNumber(1, 9724811234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberCH) { EXPECT_STREQ(NULL, map_US_->Lookup(MakePhoneNumber(41, 446681300L))); } TEST_F(AreaCodeMapTest, TestLookupNumberIT) { PhoneNumber number = MakePhoneNumber(39, 212345678L); number.set_italian_leading_zero(true); EXPECT_STREQ("Milan", map_IT_->Lookup(number)); number.set_national_number(612345678L); EXPECT_STREQ("Rome", map_IT_->Lookup(number)); number.set_national_number(3211234L); EXPECT_STREQ("Novara", map_IT_->Lookup(number)); number.set_national_number(321123456L); number.set_italian_leading_zero(false); EXPECT_STREQ(NULL, map_IT_->Lookup(number)); number.set_national_number(321123L); number.set_italian_leading_zero(true); EXPECT_STREQ("Novara", map_IT_->Lookup(number)); } } }
171
cpp
google/langsvr
buffer_writer
src/buffer_writer.cc
src/buffer_writer_test.cc
#ifndef LANGSVR_BUFFER_WRITER_H_ #define LANGSVR_BUFFER_WRITER_H_ #include <cstring> #include <vector> #include "langsvr/writer.h" namespace langsvr { class BufferWriter final : public Writer { public: BufferWriter(); Result<SuccessType> Write(const std::byte* in, size_t count) override; std::string_view BufferString() const; std::vector<std::byte> buffer; }; } #endif #include "langsvr/buffer_writer.h" namespace langsvr { BufferWriter::BufferWriter() = default; Result<SuccessType> BufferWriter::Write(const std::byte* in, size_t count) { size_t at = buffer.size(); buffer.resize(at + count); memcpy(&buffer[at], in, count); return Success; } std::string_view BufferWriter::BufferString() const { if (buffer.empty()) { return ""; } auto* data = reinterpret_cast<const char*>(&buffer[0]); static_assert(sizeof(std::byte) == sizeof(char), "length needs calculation"); return std::string_view(data, buffer.size()); } }
#include "langsvr/buffer_writer.h" #include "gmock/gmock.h" namespace langsvr { namespace { template <typename T, typename U> std::vector<T> Cast(const std::vector<U>& in) { std::vector<T> out; out.resize(in.size()); for (size_t i = 0, n = in.size(); i < n; i++) { out[i] = static_cast<T>(in[i]); } return out; } TEST(BufferWriterTest, String) { BufferWriter writer; EXPECT_EQ(writer.String("hello world"), Success); EXPECT_THAT(Cast<int>(writer.buffer), testing::ElementsAre(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100)); } } }
172
cpp
google/langsvr
content_stream
src/content_stream.cc
src/content_stream_test.cc
#ifndef LANGSVR_CONTENT_STREAM_H_ #define LANGSVR_CONTENT_STREAM_H_ #include <string> #include "langsvr/result.h" namespace langsvr { class Reader; class Writer; } namespace langsvr { Result<std::string> ReadContent(Reader& reader); Result<SuccessType> WriteContent(Writer& writer, std::string_view content); } #endif #include "langsvr/content_stream.h" #include <sstream> #include <string> #include "langsvr/reader.h" #include "langsvr/writer.h" #include "src/utils/replace_all.h" namespace langsvr { namespace { static constexpr std::string_view kContentLength = "Content-Length: "; Result<SuccessType> Match(Reader& reader, std::string_view str) { auto got = reader.String(str.size()); if (got != Success) { return got.Failure(); } if (got.Get() != str) { std::stringstream err; err << "expected '" << str << "' got '" << got.Get() << "'"; return Failure{err.str()}; } return Success; } } Result<std::string> ReadContent(Reader& reader) { if (auto match = Match(reader, kContentLength); match != Success) { return match.Failure(); } uint64_t len = 0; while (true) { char c = 0; if (auto read = reader.Read(reinterpret_cast<std::byte*>(&c), sizeof(c)); read != sizeof(c)) { return Failure{"end of stream while parsing content length"}; } if (c >= '0' && c <= '9') { len = len * 10 + static_cast<uint64_t>(c - '0'); continue; } if (c == '\r') { break; } return Failure{"invalid content length value"}; } auto got = reader.String(3); if (got != Success) { return got.Failure(); } if (got.Get() != "\n\r\n") { auto fmt = [](std::string s) { s = ReplaceAll(s, "\n", "␊"); s = ReplaceAll(s, "\r", "␍"); return s; }; std::stringstream err; err << "expected '␍␊␍␊' got '␍" << fmt(got.Get()) << "'"; return Failure{err.str()}; } return reader.String(len); } Result<SuccessType> WriteContent(Writer& writer, std::string_view content) { std::stringstream ss; ss << kContentLength << content.length() << "\r\n\r\n" << content; return writer.String(ss.str()); } }
#include "langsvr/content_stream.h" #include "gtest/gtest.h" #include "langsvr/buffer_reader.h" #include "langsvr/buffer_writer.h" namespace langsvr { namespace { TEST(ReadContent, Empty) { BufferReader reader(""); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "EOF"); } TEST(ReadContent, InvalidContentLength) { BufferReader reader("Content-Length: apples"); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "invalid content length value"); } TEST(ReadContent, MissingFirstCR) { BufferReader reader("Content-Length: 10\r "); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "expected '␍␊␍␊' got '␍ '"); } TEST(ReadContent, MissingSecondLF) { BufferReader reader("Content-Length: 10\r\n "); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "expected '␍␊␍␊' got '␍␊ '"); } TEST(ReadContent, MissingSecondCR) { BufferReader reader("Content-Length: 10\r\n\r "); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "expected '␍␊␍␊' got '␍␊␍ '"); } TEST(ReadContent, ValidMessage) { BufferReader reader("Content-Length: 11\r\n\r\nhello world"); auto got = ReadContent(reader); EXPECT_EQ(got, Success); EXPECT_EQ(got.Get(), "hello world"); } TEST(ReadContent, BufferTooShort) { BufferReader reader("Content-Length: 99\r\n\r\nhello world"); auto got = ReadContent(reader); EXPECT_NE(got, Success); } TEST(ReadContent, ValidMessages) { BufferReader reader("Content-Length: 5\r\n\r\nhelloContent-Length: 5\r\n\r\nworld"); { auto got = ReadContent(reader); EXPECT_EQ(got, "hello"); } { auto got = ReadContent(reader); EXPECT_EQ(got, "world"); } } TEST(WriteContent, Single) { BufferWriter writer; auto got = WriteContent(writer, "hello world"); EXPECT_EQ(got, Success); EXPECT_EQ(writer.BufferString(), "Content-Length: 11\r\n\r\nhello world"); } TEST(WriteContent, Multiple) { BufferWriter writer; { auto got = WriteContent(writer, "hello"); EXPECT_EQ(got, Success); EXPECT_EQ(writer.BufferString(), "Content-Length: 5\r\n\r\nhello"); } { auto got = WriteContent(writer, "world"); EXPECT_EQ(got, Success); EXPECT_EQ(writer.BufferString(), "Content-Length: 5\r\n\r\nhelloContent-Length: 5\r\n\r\nworld"); } } } }
173
cpp
google/langsvr
session
src/session.cc
src/session_test.cc
#ifndef LANGSVR_SESSION_H_ #define LANGSVR_SESSION_H_ #include <functional> #include <future> #include <string> #include <string_view> #include <type_traits> #include <unordered_map> #include <utility> #include "langsvr/json/builder.h" #include "langsvr/json/value.h" #include "langsvr/lsp/lsp.h" #include "langsvr/lsp/message_kind.h" #include "langsvr/one_of.h" #include "langsvr/result.h" namespace langsvr { class Session { struct RequestHandler { std::function<Result<json::Builder::Member>(const json::Value&, json::Builder&)> function; std::function<void()> post_send; }; struct NotificationHandler { std::function<Result<SuccessType>(const json::Value&)> function; }; public: using Sender = std::function<Result<SuccessType>(std::string_view)>; void SetSender(Sender&& sender) { sender_ = std::move(sender); } Result<SuccessType> Receive(std::string_view json); template <typename T> auto Send(T&& message) { using Message = std::decay_t<T>; static constexpr bool kIsRequest = Message::kMessageKind == lsp::MessageKind::kRequest; static constexpr bool kIsNotification = Message::kMessageKind == lsp::MessageKind::kNotification; static_assert(kIsRequest || kIsNotification); if constexpr (kIsRequest) { return SendRequest(std::forward<T>(message)); } else { return SendNotification(std::forward<T>(message)); } } template <typename T> Result<std::future<typename std::decay_t<T>::ResultType>> SendRequest(T&& request) { using Request = std::decay_t<T>; auto b = json::Builder::Create(); auto id = next_request_id_++; std::vector<json::Builder::Member> members{ json::Builder::Member{"id", b->I64(id)}, json::Builder::Member{"method", b->String(Request::kMethod)}, }; if constexpr (Request::kHasParams) { auto params = Encode(request, *b.get()); if (params != Success) { return params.Failure(); } members.push_back(json::Builder::Member{"params", params.Get()}); } using ResponseResultType = typename Request::ResultType; using ResponseSuccessType = typename Request::SuccessType; using ResponseFailureType = typename Request::FailureType; auto promise = std::make_shared<std::promise<ResponseResultType>>(); response_handlers_.emplace( id, [promise](const json::Value& response) -> Result<SuccessType> { if (auto result_json = response.Get(kResponseResult); result_json == Success) { ResponseSuccessType result; if (auto res = lsp::Decode(*result_json.Get(), result); res != Success) { return res.Failure(); } promise->set_value(ResponseResultType{std::move(result)}); return Success; } if constexpr (std::is_same_v<ResponseFailureType, void>) { return Failure{"response missing 'result'"}; } else { ResponseFailureType error; auto error_json = response.Get(kResponseError); if (error_json != Success) { return error_json.Failure(); } if (auto res = lsp::Decode(*error_json.Get(), error); res != Success) { return res.Failure(); } promise->set_value(ResponseResultType{std::move(error)}); } return Success; }); auto send = SendJson(b->Object(members)->Json()); if (send != Success) { return send.Failure(); } return promise->get_future(); } template <typename T> Result<SuccessType> SendNotification(T&& notification) { using Notification = std::decay_t<T>; auto b = json::Builder::Create(); std::vector<json::Builder::Member> members{ json::Builder::Member{"method", b->String(Notification::kMethod)}, }; if constexpr (Notification::kHasParams) { auto params = Encode(notification, *b.get()); if (params != Success) { return params.Failure(); } members.push_back(json::Builder::Member{"params", params.Get()}); } return SendJson(b->Object(members)->Json()); } class RegisteredRequestHandler { public: void OnPostSend(std::function<void()>&& callback) { handler.post_send = std::move(callback); } private: friend class Session; RegisteredRequestHandler(RequestHandler& h) : handler{h} {} RegisteredRequestHandler(const RegisteredRequestHandler&) = delete; RegisteredRequestHandler& operator=(const RegisteredRequestHandler&) = delete; RequestHandler& handler; }; template <typename F> auto Register(F&& callback) { using Sig = SignatureOf<F>; static_assert(Sig::parameter_count == 1); using Message = typename Sig::template parameter<0>; static constexpr bool kIsRequest = Message::kMessageKind == lsp::MessageKind::kRequest; static constexpr bool kIsNotification = Message::kMessageKind == lsp::MessageKind::kNotification; static_assert(kIsRequest || kIsNotification); auto method = std::string(Message::kMethod); if constexpr (kIsRequest) { auto& handler = request_handlers_[method]; handler.function = [f = std::forward<F>(callback)]( const json::Value& object, json::Builder& json_builder) -> Result<json::Builder::Member> { Message request; if constexpr (Message::kHasParams) { auto params = object.Get("params"); if (params != Success) { return params.Failure(); } if (auto res = Decode(*params.Get(), request); res != Success) { return res.Failure(); } } auto res = f(request); using RES_TYPE = std::decay_t<decltype(res)>; using RequestSuccessType = typename Message::SuccessType; using RequestFailureType = typename Message::FailureType; if constexpr (IsResult<RES_TYPE>) { using ResultSuccessType = typename RES_TYPE::ResultSuccess; using ResultFailureType = typename RES_TYPE::ResultFailure; static_assert( std::is_same_v<ResultSuccessType, RequestSuccessType>, "request handler Result<> success return type does not match Request's " "Result type"); static_assert(std::is_same_v<ResultFailureType, RequestFailureType>, "request handler Result<> failure return type does not match " "Request's Failure type"); if (res == Success) { auto enc = Encode(res.Get(), json_builder); if (enc != Success) { return enc.Failure(); } return json::Builder::Member{std::string(kResponseResult), enc.Get()}; } else { auto enc = Encode(res.Failure(), json_builder); if (enc != Success) { return enc.Failure(); } return json::Builder::Member{std::string(kResponseError), enc.Get()}; } } else { static_assert((std::is_same_v<RES_TYPE, RequestSuccessType> || std::is_same_v<RES_TYPE, RequestFailureType>), "request handler return type is not supported"); auto enc = Encode(res, json_builder); if (enc != Success) { return enc.Failure(); } return json::Builder::Member{ std::string(std::is_same_v<RES_TYPE, RequestSuccessType> ? kResponseResult : kResponseError), enc.Get()}; } }; return RegisteredRequestHandler{handler}; } else if constexpr (kIsNotification) { auto& handler = notification_handlers_[method]; handler.function = [f = std::forward<F>(callback)](const json::Value& object) -> Result<SuccessType> { Message notification; if constexpr (Message::kHasParams) { auto params = object.Get("params"); if (params != Success) { return params.Failure(); } if (auto res = Decode(*params.Get(), notification); res != Success) { return res.Failure(); } } return f(notification); }; return; } } private: static constexpr std::string_view kResponseResult = "result"; static constexpr std::string_view kResponseError = "error"; Result<SuccessType> SendJson(std::string_view msg); Sender sender_; std::unordered_map<std::string, RequestHandler> request_handlers_; std::unordered_map<std::string, NotificationHandler> notification_handlers_; std::unordered_map<json::I64, std::function<Result<SuccessType>(const json::Value&)>> response_handlers_; json::I64 next_request_id_ = 1; }; } #endif #include "langsvr/session.h" #include <string> #include "langsvr/json/builder.h" namespace langsvr { Result<SuccessType> Session::Receive(std::string_view json) { auto json_builder = json::Builder::Create(); auto object = json_builder->Parse(json); if (object != Success) { return object.Failure(); } auto method = object.Get()->Get<json::String>("method"); if (method != Success) { auto id = object.Get()->Get<json::I64>("id"); if (id != Success) { return id.Failure(); } auto handler_it = response_handlers_.find(id.Get()); if (handler_it == response_handlers_.end()) { return Failure{"received response for unknown request with ID " + std::to_string(id.Get())}; } auto handler = std::move(handler_it->second); response_handlers_.erase(handler_it); return handler(*object.Get()); } if (object.Get()->Has("id")) { auto id = object.Get()->Get<json::I64>("id"); if (id != Success) { return id.Failure(); } auto it = request_handlers_.find(method.Get()); if (it == request_handlers_.end()) { return Failure{"no handler registered for request method '" + method.Get() + "'"}; } auto& request_handler = it->second; auto result = request_handler.function(*object.Get(), *json_builder.get()); if (result != Success) { return result.Failure(); } std::array response_members{ json::Builder::Member{"id", json_builder->I64(id.Get())}, result.Get(), }; auto* response = json_builder->Object(response_members); if (auto res = SendJson(response->Json()); res != Success) { return res.Failure(); } if (request_handler.post_send) { request_handler.post_send(); } } else { auto it = notification_handlers_.find(method.Get()); if (it == notification_handlers_.end()) { return Failure{"no handler registered for request method '" + method.Get() + "'"}; } auto& notification_handler = it->second; return notification_handler.function(*object.Get()); } return Success; } Result<SuccessType> Session::SendJson(std::string_view msg) { if (!sender_) [[unlikely]] { return Failure{"no sender set"}; } return sender_(msg); } }
#include "langsvr/lsp/lsp.h" #include "langsvr/session.h" #include <gtest/gtest.h> #include "langsvr/json/builder.h" #include "langsvr/lsp/decode.h" #include "gmock/gmock.h" #include "langsvr/result.h" namespace langsvr { namespace { Result<lsp::InitializeRequest> GetInitializeRequest() { static constexpr std::string_view kJSON = R"({"processId":71875,"clientInfo":{"name":"My Awesome Editor","version":"1.2.3"},"locale":"en-gb","rootPath":"/home/bob/src/langsvr","rootUri":"file: auto b = json::Builder::Create(); auto msg = b->Parse(kJSON); if (msg != Success) { return msg.Failure(); } lsp::InitializeRequest request; if (auto res = lsp::Decode(*msg.Get(), request); res != Success) { return res.Failure(); } return request; } TEST(Session, InitializeRequest_ResultOrFailure) { auto request = GetInitializeRequest(); ASSERT_EQ(request, Success); Session server_session; Session client_session; client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); }); server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); }); bool handler_called = false; server_session.Register([&](const lsp::InitializeRequest& init) -> Result<lsp::InitializeResult, lsp::InitializeError> { handler_called = true; EXPECT_EQ(request, init); lsp::InitializeResult res; res.capabilities.hover_provider = true; return res; }); auto response_future = client_session.Send(request.Get()); ASSERT_EQ(response_future, Success); EXPECT_TRUE(handler_called); auto response = response_future.Get().get(); ASSERT_EQ(response, Success); lsp::InitializeResult expected; expected.capabilities.hover_provider = true; EXPECT_EQ(response.Get(), expected); } TEST(Session, InitializeRequest_ResultOnly) { auto request = GetInitializeRequest(); ASSERT_EQ(request, Success); Session server_session; Session client_session; client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); }); server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); }); bool handler_called = false; server_session.Register([&](const lsp::InitializeRequest& init) { handler_called = true; EXPECT_EQ(request, init); lsp::InitializeResult res; res.capabilities.hover_provider = true; return res; }); auto response_future = client_session.Send(request.Get()); ASSERT_EQ(response_future, Success); EXPECT_TRUE(handler_called); auto response = response_future.Get().get(); ASSERT_EQ(response, Success); lsp::InitializeResult expected; expected.capabilities.hover_provider = true; EXPECT_EQ(response.Get(), expected); } TEST(Session, InitializeRequest_FailureOnly) { auto request = GetInitializeRequest(); ASSERT_EQ(request, Success); Session server_session; Session client_session; client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); }); server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); }); bool handler_called = false; server_session.Register([&](const lsp::InitializeRequest& init) { handler_called = true; EXPECT_EQ(request, init); lsp::InitializeError err; err.retry = true; return err; }); auto response_future = client_session.Send(request.Get()); ASSERT_EQ(response_future, Success); EXPECT_TRUE(handler_called); auto response = response_future.Get().get(); ASSERT_NE(response, Success); lsp::InitializeError expected; expected.retry = true; EXPECT_EQ(response.Failure(), expected); } } }
174
cpp
google/langsvr
buffer_reader
src/buffer_reader.cc
src/buffer_reader_test.cc
#ifndef LANGSVR_BUFFER_READER_H_ #define LANGSVR_BUFFER_READER_H_ #include "langsvr/reader.h" namespace langsvr { class BufferReader final : public Reader { public: ~BufferReader() override; explicit BufferReader(std::string_view string) : data_(reinterpret_cast<const std::byte*>(string.data())), bytes_remaining_(string.length()) {} size_t Read(std::byte* out, size_t count) override; private: const std::byte* data_ = nullptr; size_t bytes_remaining_ = 0; }; } #endif #include "langsvr/buffer_reader.h" #include <cstring> namespace langsvr { BufferReader::~BufferReader() = default; size_t BufferReader::Read(std::byte* out, size_t count) { size_t n = std::min(count, bytes_remaining_); memcpy(out, data_, n); data_ += n; bytes_remaining_ -= n; return n; } }
#include "langsvr/buffer_reader.h" #include "gtest/gtest.h" namespace langsvr { namespace { template <typename... ARGS> auto Data(ARGS&&... args) { return std::vector{std::byte{static_cast<uint8_t>(args)}...}; } TEST(BufferReaderTest, String) { BufferReader reader{"hello world"}; auto first = reader.String(5); ASSERT_EQ(first, Success); EXPECT_EQ(first.Get(), "hello"); auto second = reader.String(6); ASSERT_EQ(second, Success); EXPECT_EQ(second.Get(), " world"); auto third = reader.String(1); EXPECT_NE(third, Success); } } }
175
cpp
google/langsvr
encode
src/lsp/encode.cc
src/lsp/encode_test.cc
#ifndef LANGSVR_LSP_ENCODE_H_ #define LANGSVR_LSP_ENCODE_H_ #include <string> #include <tuple> #include <unordered_map> #include <utility> #include <vector> #include "langsvr/json/builder.h" #include "langsvr/lsp/primitives.h" #include "langsvr/one_of.h" #include "langsvr/optional.h" #include "langsvr/traits.h" namespace langsvr::lsp { template <typename T> Result<const json::Value*> Encode(const Optional<T>& in, json::Builder& b); template <typename T> Result<const json::Value*> Encode(const std::vector<T>& in, json::Builder& b); template <typename... TYPES> Result<const json::Value*> Encode(const std::tuple<TYPES...>& in, json::Builder& b); template <typename V> Result<const json::Value*> Encode(const std::unordered_map<std::string, V>& in, json::Builder& b); template <typename... TYPES> Result<const json::Value*> Encode(const OneOf<TYPES...>& in, json::Builder& b); } namespace langsvr::lsp { Result<const json::Value*> Encode(Null in, json::Builder& b); Result<const json::Value*> Encode(Boolean in, json::Builder& b); Result<const json::Value*> Encode(Integer in, json::Builder& b); Result<const json::Value*> Encode(Uinteger in, json::Builder& b); Result<const json::Value*> Encode(Decimal in, json::Builder& b); Result<const json::Value*> Encode(const String& in, json::Builder& b); template <typename T> Result<const json::Value*> Encode(const Optional<T>& in, json::Builder& b) { return Encode(*in, b); } template <typename T> Result<const json::Value*> Encode(const std::vector<T>& in, json::Builder& b) { std::vector<const json::Value*> values; values.reserve(in.size()); for (auto& element : in) { auto value = Encode(element, b); if (value != Success) { return value.Failure(); } values.push_back(value.Get()); } return b.Array(values); } template <typename... TYPES> Result<const json::Value*> Encode(const std::tuple<TYPES...>& in, json::Builder& b) { std::string error; std::vector<const json::Value*> values; values.reserve(sizeof...(TYPES)); auto encode = [&](auto& el) { auto value = Encode(el, b); if (value != Success) { error = std::move(value.Failure().reason); return false; } values.push_back(value.Get()); return true; }; std::apply([&](auto&... elements) { (encode(elements) && ...); }, in); if (error.empty()) { return b.Array(values); } return Failure{std::move(error)}; } template <typename V> Result<const json::Value*> Encode(const std::unordered_map<std::string, V>& in, json::Builder& b) { std::vector<json::Builder::Member> members; members.reserve(in.size()); for (auto it : in) { auto value = Encode(it.second, b); if (value != Success) { return value.Failure(); } members.push_back(json::Builder::Member{it.first, value.Get()}); } return b.Object(members); } template <typename... TYPES> Result<const json::Value*> Encode(const OneOf<TYPES...>& in, json::Builder& b) { return in.Visit([&](const auto& v) { return Encode(v, b); }); } } #endif #include "langsvr/lsp/encode.h" namespace langsvr::lsp { Result<const json::Value*> Encode(Null, json::Builder& b) { return b.Null(); } Result<const json::Value*> Encode(Boolean in, json::Builder& b) { return b.Bool(in); } Result<const json::Value*> Encode(Integer in, json::Builder& b) { return b.I64(in); } Result<const json::Value*> Encode(Uinteger in, json::Builder& b) { return b.U64(in); } Result<const json::Value*> Encode(Decimal in, json::Builder& b) { return b.F64(in); } Result<const json::Value*> Encode(const String& in, json::Builder& b) { return b.String(in); } }
#include "langsvr/json/builder.h" #include "langsvr/lsp/lsp.h" #include "gmock/gmock.h" namespace langsvr::lsp { namespace { TEST(EncodeTest, ShowDocumentParams) { ShowDocumentParams params; params.uri = "file.txt"; params.selection = Range{{1, 2}, {3, 4}}; auto b = json::Builder::Create(); auto res = Encode(params, *b); EXPECT_EQ(res, Success); EXPECT_EQ( res.Get()->Json(), R"({"selection":{"end":{"character":4,"line":3},"start":{"character":2,"line":1}},"uri":"file.txt"})"); } } }
176
cpp
google/langsvr
decode
src/lsp/decode.cc
src/lsp/decode_test.cc
#ifndef LANGSVR_DECODE_H_ #define LANGSVR_DECODE_H_ #include <string> #include <tuple> #include <unordered_map> #include <utility> #include <vector> #include "langsvr/json/value.h" #include "langsvr/lsp/primitives.h" #include "langsvr/one_of.h" #include "langsvr/optional.h" #include "langsvr/traits.h" namespace langsvr::lsp { template <typename T> Result<SuccessType> Decode(const json::Value& v, Optional<T>& out); template <typename T> Result<SuccessType> Decode(const json::Value& v, std::vector<T>& out); template <typename... TYPES> Result<SuccessType> Decode(const json::Value& v, std::tuple<TYPES...>& out); template <typename V> Result<SuccessType> Decode(const json::Value& v, std::unordered_map<std::string, V>& out); template <typename... TYPES> Result<SuccessType> Decode(const json::Value& v, OneOf<TYPES...>& out); } namespace langsvr::lsp { Result<SuccessType> Decode(const json::Value& v, Null& out); Result<SuccessType> Decode(const json::Value& v, Boolean& out); Result<SuccessType> Decode(const json::Value& v, Integer& out); Result<SuccessType> Decode(const json::Value& v, Uinteger& out); Result<SuccessType> Decode(const json::Value& v, Decimal& out); Result<SuccessType> Decode(const json::Value& v, String& out); template <typename T> Result<SuccessType> Decode(const json::Value& v, Optional<T>& out) { return Decode(v, *out); } template <typename T> Result<SuccessType> Decode(const json::Value& v, std::vector<T>& out) { if (v.Kind() != json::Kind::kArray) { return Failure{"JSON value is not an array"}; } out.resize(v.Count()); for (size_t i = 0, n = out.size(); i < n; i++) { auto element = v.Get(i); if (element != Success) { return element.Failure(); } if (auto res = Decode(*element.Get(), out[i]); res != Success) { return res.Failure(); } } return Success; } template <typename... TYPES> Result<SuccessType> Decode(const json::Value& v, std::tuple<TYPES...>& out) { if (v.Kind() != json::Kind::kArray) { return Failure{"JSON value is not an array"}; } if (v.Count() != sizeof...(TYPES)) { return Failure{"JSON array does not match tuple length"}; } std::string error; size_t idx = 0; auto decode = [&](auto& el) { auto element = v.Get(idx); if (element != Success) { error = std::move(element.Failure().reason); return false; } if (auto res = Decode(*element.Get(), el); res != Success) { error = std::move(res.Failure().reason); return false; } idx++; return true; }; std::apply([&](auto&... elements) { (decode(elements) && ...); }, out); if (error.empty()) { return Success; } return Failure{std::move(error)}; } template <typename V> Result<SuccessType> Decode(const json::Value& v, std::unordered_map<std::string, V>& out) { if (v.Kind() != json::Kind::kObject) { return Failure{"JSON value is not an object"}; } auto names = v.MemberNames(); if (names != Success) { return names.Failure(); } out.reserve(names->size()); for (auto& name : names.Get()) { auto element = v.Get(name); if (element != Success) { return element.Failure(); } if (auto res = Decode(*element.Get(), out[name]); res != Success) { return res.Failure(); } } return Success; } template <typename... TYPES> Result<SuccessType> Decode(const json::Value& v, OneOf<TYPES...>& out) { auto try_type = [&](auto* p) { using T = std::remove_pointer_t<decltype(p)>; T val; if (auto res = Decode(v, val); res == Success) { out = std::move(val); return true; } return false; }; bool ok = (try_type(static_cast<TYPES*>(nullptr)) || ...); if (ok) { return Success; } return Failure{"no types matched the OneOf"}; } } #endif #include "langsvr/lsp/decode.h" namespace langsvr::lsp { Result<SuccessType> Decode(const json::Value& v, Null&) { return v.Null(); } Result<SuccessType> Decode(const json::Value& v, Boolean& out) { auto res = v.Bool(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, Integer& out) { auto res = v.I64(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, Uinteger& out) { auto res = v.U64(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, Decimal& out) { auto res = v.F64(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, String& out) { auto res = v.String(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } }
#include "langsvr/json/builder.h" #include "langsvr/lsp/lsp.h" #include "langsvr/lsp/printer.h" #include "gmock/gmock.h" namespace langsvr::lsp { namespace { TEST(DecodeTest, ShowDocumentParams) { auto b = json::Builder::Create(); auto parse_res = b->Parse( R"({"selection":{"end":{"character":4,"line":3},"start":{"character":2,"line":1}},"uri":"file.txt"})"); EXPECT_EQ(parse_res, Success); ShowDocumentParams got; auto decode_res = Decode(*parse_res.Get(), got); EXPECT_EQ(decode_res, Success); ShowDocumentParams expected; expected.uri = "file.txt"; expected.selection = Range{{1, 2}, {3, 4}}; EXPECT_EQ(got, expected); } TEST(DecodeTest, ErrNullStruct) { auto b = json::Builder::Create(); auto parse_res = b->Parse("null"); EXPECT_EQ(parse_res, Success); SemanticTokensFullDelta got; auto decode_res = Decode(*parse_res.Get(), got); EXPECT_NE(decode_res, Success); } TEST(DecodeTest, ErrNumberStruct) { auto b = json::Builder::Create(); auto parse_res = b->Parse("42"); EXPECT_EQ(parse_res, Success); SemanticTokensFullDelta got; auto decode_res = Decode(*parse_res.Get(), got); EXPECT_NE(decode_res, Success); } } }
177
cpp
pytorch/pytorch
inline_container
caffe2/serialize/inline_container.cc
caffe2/serialize/inline_container_test.cc
#pragma once #include <cerrno> #include <cstdio> #include <cstring> #include <fstream> #include <istream> #include <mutex> #include <ostream> #include <unordered_set> #include <c10/core/Allocator.h> #include <c10/core/Backend.h> #include "caffe2/serialize/istream_adapter.h" #include "caffe2/serialize/read_adapter_interface.h" #include "caffe2/serialize/versions.h" extern "C" { typedef struct mz_zip_archive mz_zip_archive; } namespace caffe2 { namespace serialize { static constexpr const char* kSerializationIdRecordName = ".data/serialization_id"; struct MzZipReaderIterWrapper; class TORCH_API ChunkRecordIterator { public: ~ChunkRecordIterator(); size_t next(void* buf); size_t recordSize() const { return recordSize_; } private: ChunkRecordIterator( size_t recordSize, size_t chunkSize, std::unique_ptr<MzZipReaderIterWrapper> iter); const size_t recordSize_; const size_t chunkSize_; size_t offset_; std::unique_ptr<MzZipReaderIterWrapper> iter_; friend class PyTorchStreamReader; }; class TORCH_API PyTorchStreamReader final { public: explicit PyTorchStreamReader(const std::string& file_name); explicit PyTorchStreamReader(std::istream* in); explicit PyTorchStreamReader(std::shared_ptr<ReadAdapterInterface> in); std::tuple<at::DataPtr, size_t> getRecord(const std::string& name); std::tuple<at::DataPtr, size_t> getRecord(const std::string& name, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders); size_t getRecord(const std::string& name, void* dst, size_t n); size_t getRecord(const std::string& name, void* dst, size_t n, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders); size_t getRecord( const std::string& name, void* dst, size_t n, size_t chunk_size, void* buf, const std::function<void(void*, const void*, size_t)>& memcpy_func = nullptr); size_t getRecordMultiReaders(const std::string& name, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders, void *dst, size_t n); size_t getRecordSize(const std::string& name); size_t getRecordOffset(const std::string& name); bool hasRecord(const std::string& name); std::vector<std::string> getAllRecords(); ChunkRecordIterator createChunkReaderIter( const std::string& name, const size_t recordSize, const size_t chunkSize); ~PyTorchStreamReader(); uint64_t version() const { return version_; } const std::string& serializationId() { return serialization_id_; } void setShouldLoadDebugSymbol(bool should_load_debug_symbol) { load_debug_symbol_ = should_load_debug_symbol; } void setAdditionalReaderSizeThreshold(const size_t& size){ additional_reader_size_threshold_ = size; } private: void init(); size_t read(uint64_t pos, char* buf, size_t n); void valid(const char* what, const char* info = ""); size_t getRecordID(const std::string& name); friend size_t istream_read_func(void* pOpaque, uint64_t file_ofs, void* pBuf, size_t n); std::unique_ptr<mz_zip_archive> ar_; std::string archive_name_; std::string archive_name_plus_slash_; std::shared_ptr<ReadAdapterInterface> in_; int64_t version_; std::mutex reader_lock_; bool load_debug_symbol_ = true; std::string serialization_id_; size_t additional_reader_size_threshold_; }; class TORCH_API PyTorchStreamWriter final { public: explicit PyTorchStreamWriter(const std::string& archive_name); explicit PyTorchStreamWriter( const std::function<size_t(const void*, size_t)> writer_func); void setMinVersion(const uint64_t version); void writeRecord( const std::string& name, const void* data, size_t size, bool compress = false); void writeEndOfFile(); const std::unordered_set<std::string>& getAllWrittenRecords(); bool finalized() const { return finalized_; } const std::string& archiveName() { return archive_name_; } const std::string& serializationId() { return serialization_id_; } ~PyTorchStreamWriter(); private: void setup(const std::string& file_name); void valid(const char* what, const char* info = ""); void writeSerializationId(); size_t current_pos_ = 0; std::unordered_set<std::string> files_written_; std::unique_ptr<mz_zip_archive> ar_; std::string archive_name_; std::string archive_name_plus_slash_; std::string padding_; std::ofstream file_stream_; std::function<size_t(const void*, size_t)> writer_func_; uint64_t combined_uncomp_crc32_ = 0; std::string serialization_id_; uint64_t version_ = kMinProducedFileFormatVersion; bool finalized_ = false; bool err_seen_ = false; friend size_t ostream_write_func( void* pOpaque, uint64_t file_ofs, const void* pBuf, size_t n); }; namespace detail { constexpr uint64_t kFieldAlignment = 64; size_t getPadding( size_t cursor, size_t filename_size, size_t size, std::string& padding_buf); } } } #include <cstdio> #include <cstring> #include <cerrno> #include <istream> #include <ostream> #include <fstream> #include <algorithm> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <thread> #include <c10/core/Allocator.h> #include <c10/core/Backend.h> #include <c10/core/CPUAllocator.h> #include <c10/core/Backend.h> #include <c10/util/Exception.h> #include <c10/util/Logging.h> #include <c10/util/hash.h> #include "caffe2/core/common.h" #include "caffe2/serialize/file_adapter.h" #include "caffe2/serialize/inline_container.h" #include "caffe2/serialize/istream_adapter.h" #include "caffe2/serialize/read_adapter_interface.h" #include "caffe2/serialize/versions.h" #include "miniz.h" namespace caffe2 { namespace serialize { constexpr c10::string_view kDebugPklSuffix(".debug_pkl"); struct MzZipReaderIterWrapper { MzZipReaderIterWrapper(mz_zip_reader_extract_iter_state* iter) : impl(iter) {} mz_zip_reader_extract_iter_state* impl; }; ChunkRecordIterator::ChunkRecordIterator( size_t recordSize, size_t chunkSize, std::unique_ptr<MzZipReaderIterWrapper> iter) : recordSize_(recordSize), chunkSize_(chunkSize), offset_(0), iter_(std::move(iter)) {} ChunkRecordIterator::~ChunkRecordIterator() { mz_zip_reader_extract_iter_free(iter_->impl); } size_t ChunkRecordIterator::next(void* buf){ size_t want_size = std::min(chunkSize_, recordSize_ - offset_); if (want_size == 0) { return 0; } size_t read_size = mz_zip_reader_extract_iter_read(iter_->impl, buf, want_size); TORCH_CHECK(read_size > 0, "Read bytes should be larger than 0"); offset_ += read_size; return read_size; } size_t istream_read_func(void* pOpaque, mz_uint64 file_ofs, void* pBuf, size_t n) { auto self = static_cast<PyTorchStreamReader*>(pOpaque); return self->read(file_ofs, static_cast<char*>(pBuf), n); } static std::string basename(const std::string& name) { size_t start = 0; for(size_t i = 0; i < name.size(); ++i) { if (name[i] == '\\' || name[i] == '/') { start = i + 1; } } if (start >= name.size()) { return ""; } size_t end = name.size(); for(size_t i = end; i > start; --i) { if (name[i - 1] == '.') { end = i - 1; break; } } return name.substr(start, end - start); } static std::string parentdir(const std::string& name) { size_t end = name.find_last_of('/'); if (end == std::string::npos) { end = name.find_last_of('\\'); } #ifdef WIN32 if (end != std::string::npos && end > 1 && name[end - 1] == ':') { end++; } #endif if (end == std::string::npos) { return ""; } return name.substr(0, end); } size_t PyTorchStreamReader::read(uint64_t pos, char* buf, size_t n) { return in_->read(pos, buf, n, "reading file"); } PyTorchStreamReader::PyTorchStreamReader(const std::string& file_name) : ar_(std::make_unique<mz_zip_archive>()), in_(std::make_unique<FileAdapter>(file_name)) { init(); } PyTorchStreamReader::PyTorchStreamReader(std::istream* in) : ar_(std::make_unique<mz_zip_archive>()), in_(std::make_unique<IStreamAdapter>(in)) { init(); } PyTorchStreamReader::PyTorchStreamReader( std::shared_ptr<ReadAdapterInterface> in) : ar_(std::make_unique<mz_zip_archive>()), in_(std::move(in)) { init(); } void PyTorchStreamReader::init() { AT_ASSERT(in_ != nullptr); AT_ASSERT(ar_ != nullptr); memset(ar_.get(), 0, sizeof(mz_zip_archive)); size_t size = in_->size(); constexpr size_t kMagicValueLength = 8; if (size > kMagicValueLength) { char buf[kMagicValueLength]; read(0, buf, kMagicValueLength); valid("checking magic number"); AT_ASSERTM( memcmp("PYTORCH1", buf, kMagicValueLength) != 0, "File is an unsupported archive format from the preview release."); } ar_->m_pIO_opaque = this; ar_->m_pRead = istream_read_func; mz_zip_reader_init(ar_.get(), size, 0); valid("reading zip archive"); mz_uint n = mz_zip_reader_get_num_files(ar_.get()); if (n == 0) { CAFFE_THROW("archive does not contain any files"); } size_t name_size = mz_zip_reader_get_filename(ar_.get(), 0, nullptr, 0); valid("getting filename"); std::string buf(name_size, '\0'); mz_zip_reader_get_filename(ar_.get(), 0, &buf[0], name_size); valid("getting filename"); auto pos = buf.find_first_of('/'); if (pos == std::string::npos) { CAFFE_THROW("file in archive is not in a subdirectory: ", buf); } archive_name_ = buf.substr(0, pos); archive_name_plus_slash_ = archive_name_ + "/"; if (hasRecord(kSerializationIdRecordName)) { at::DataPtr serialization_id_ptr; size_t serialization_id_size = 0; std::tie(serialization_id_ptr, serialization_id_size) = getRecord(kSerializationIdRecordName); serialization_id_.assign( static_cast<const char*>(serialization_id_ptr.get()), serialization_id_size); } c10::LogAPIUsageMetadata( "pytorch.stream.reader.metadata", {{"serialization_id", serialization_id_}, {"file_name", archive_name_}, {"file_size", str(mz_zip_get_archive_size(ar_.get()))}}); at::DataPtr version_ptr; size_t version_size; if (hasRecord(".data/version")) { std::tie(version_ptr, version_size) = getRecord(".data/version"); } else { TORCH_CHECK(hasRecord("version")) std::tie(version_ptr, version_size) = getRecord("version"); } std::string version(static_cast<const char*>(version_ptr.get()), version_size); try { version_ = std::stoull(version); } catch (const std::invalid_argument& e) { CAFFE_THROW("Couldn't parse the version ", version, " as Long Long."); } if (version_ < static_cast<decltype(version_)>(kMinSupportedFileFormatVersion)) { CAFFE_THROW( "Attempted to read a PyTorch file with version ", c10::to_string(version_), ", but the minimum supported version for reading is ", c10::to_string(kMinSupportedFileFormatVersion), ". Your PyTorch script module file is too old. Please regenerate it", " with latest version of PyTorch to mitigate this issue."); } if (version_ > static_cast<decltype(version_)>(kMaxSupportedFileFormatVersion)) { CAFFE_THROW( "Attempted to read a PyTorch file with version ", version_, ", but the maximum supported version for reading is ", kMaxSupportedFileFormatVersion, ". The version of your PyTorch installation may be too old, ", "please upgrade PyTorch to latest version to mitigate this issue."); } } void PyTorchStreamReader::valid(const char* what, const char* info) { const auto err = mz_zip_get_last_error(ar_.get()); TORCH_CHECK( err == MZ_ZIP_NO_ERROR, "PytorchStreamReader failed ", what, info, ": ", mz_zip_get_error_string(err)); } constexpr int MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30; constexpr int MZ_ZIP_LDH_FILENAME_LEN_OFS = 26; constexpr int MZ_ZIP_LDH_EXTRA_LEN_OFS = 28; constexpr int MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50; namespace detail { size_t getPadding( size_t cursor, size_t filename_size, size_t size, std::string& padding_buf) { size_t start = cursor + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + filename_size + sizeof(mz_uint16) * 2; if (size >= MZ_UINT32_MAX || cursor >= MZ_UINT32_MAX) { start += sizeof(mz_uint16) * 2; if (size >= MZ_UINT32_MAX) { start += 2 * sizeof(mz_uint64); } if (cursor >= MZ_UINT32_MAX) { start += sizeof(mz_uint64); } } size_t mod = start % kFieldAlignment; size_t next_offset = (mod == 0) ? start : (start + kFieldAlignment - mod); size_t padding_size = next_offset - start; size_t padding_size_plus_fbxx = padding_size + 4; if (padding_buf.size() < padding_size_plus_fbxx) { padding_buf.append(padding_size_plus_fbxx - padding_buf.size(), 'Z'); } padding_buf[0] = 'F'; padding_buf[1] = 'B'; padding_buf[2] = (uint8_t)padding_size; padding_buf[3] = (uint8_t)(padding_size >> 8); return padding_size_plus_fbxx; } } bool PyTorchStreamReader::hasRecord(const std::string& name) { std::lock_guard<std::mutex> guard(reader_lock_); if ((!load_debug_symbol_) && c10::string_view(name).ends_with(kDebugPklSuffix)) { return false; } std::string ss = archive_name_plus_slash_ + name; mz_zip_reader_locate_file(ar_.get(), ss.c_str(), nullptr, 0); const mz_zip_error err = mz_zip_get_last_error(ar_.get()); if (err == MZ_ZIP_NO_ERROR) { return true; } else if (err == MZ_ZIP_FILE_NOT_FOUND) { return false; } else { valid("attempting to locate file ", name.c_str()); } TORCH_INTERNAL_ASSERT(false, "should not reach here"); } std::vector<std::string> PyTorchStreamReader::getAllRecords() { std::lock_guard<std::mutex> guard(reader_lock_); mz_uint num_files = mz_zip_reader_get_num_files(ar_.get()); std::vector<std::string> out; char buf[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; for (size_t i = 0; i < num_files; i++) { mz_zip_reader_get_filename(ar_.get(), i, buf, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE); if (strncmp( buf, archive_name_plus_slash_.data(), archive_name_plus_slash_.size()) != 0) { CAFFE_THROW( "file in archive is not in a subdirectory ", archive_name_plus_slash_, ": ", buf); } if ((load_debug_symbol_) || (!c10::string_view(buf + archive_name_plus_slash_.size()).ends_with(kDebugPklSuffix))) { out.push_back(buf + archive_name_plus_slash_.size()); } } return out; } const std::unordered_set<std::string>& PyTorchStreamWriter::getAllWrittenRecords() { return files_written_; } size_t PyTorchStreamReader::getRecordID(const std::string& name) { std::string ss = archive_name_plus_slash_ + name; size_t result = mz_zip_reader_locate_file(ar_.get(), ss.c_str(), nullptr, 0); valid("locating file ", name.c_str()); return result; } std::tuple<at::DataPtr, size_t> PyTorchStreamReader::getRecord(const std::string& name) { std::lock_guard<std::mutex> guard(reader_lock_); if ((!load_debug_symbol_) && c10::string_view(name).ends_with(kDebugPklSuffix)) { at::DataPtr retval; return std::make_tuple(std::move(retval), 0); } size_t key = getRecordID(name); mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), key, &stat); valid("retrieving file meta-data for ", name.c_str()); at::DataPtr retval = c10::GetCPUAllocator()->allocate(stat.m_uncomp_size); mz_zip_reader_extract_to_mem(ar_.get(), key, retval.get(), stat.m_uncomp_size, 0); valid("reading file ", name.c_str()); return std::make_tuple(std::move(retval), stat.m_uncomp_size); } size_t PyTorchStreamReader::getRecordMultiReaders(const std::string& name, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders, void *dst, size_t n){ size_t nthread = additionalReaders.size()+1; size_t recordOff = getRecordOffset(name); std::vector<std::thread> loaderThreads; size_t perThreadSize = (n+nthread-1)/nthread; std::vector<size_t> readSizes(nthread, 0); std::lock_guard<std::mutex> guard(reader_lock_); for(size_t i = 0; i < nthread ; i++){ loaderThreads.emplace_back([this, name, i, n, recordOff, perThreadSize, dst, &additionalReaders, &readSizes]{ size_t startPos = i*perThreadSize; size_t endPos = std::min((i+1)*perThreadSize,n); if (startPos < endPos){ size_t threadReadSize = endPos - startPos; size_t size = 0; if (i==0){ size = read(recordOff+startPos, (char *)dst+startPos, threadReadSize); }else{ auto reader = additionalReaders[i-1]; size = reader->read(recordOff+startPos, (char *)dst+startPos, threadReadSize); } readSizes[i] = size; LOG(INFO) << "Thread " << i << " read [" << startPos << "-" << endPos << "] " << "from " << name << " of size " << n; TORCH_CHECK( threadReadSize == size, "record size ", threadReadSize, " mismatch with read size ", size); } }); } for (auto& thread : loaderThreads) { thread.join(); } loaderThreads.clear(); size_t total_read_n = 0; for (auto& r : readSizes){ total_read_n += r; } TORCH_CHECK( n == total_read_n, "Multi reader total read size ", total_read_n, " mismatch with dst size ", n); return total_read_n; } std::tuple<at::DataPtr, size_t> PyTorchStreamReader::getRecord(const std::string& name, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders) { if(additionalReaders.empty()){ return getRecord(name); } if ((!load_debug_symbol_) && c10::string_view(name).ends_with(kDebugPklSuffix)) { at::DataPtr retval; return std::make_tuple(std::move(retval), 0); } size_t key = getRecordID(name); mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), key, &stat); auto n = stat.m_uncomp_size; valid("retrieving file meta-data for ", name.c_str()); if(n < additional_reader_size_threshold_){ return getRecord(name); } at::DataPtr retval = c10::GetCPUAllocator()->allocate(stat.m_uncomp_size); void* dst = retval.get(); PyTorchStreamReader::getRecordMultiReaders(name, additionalReaders, dst, n); return std::make_tuple(std::move(retval), stat.m_uncomp_size); } size_t PyTorchStreamReader::getRecord(const std::string& name, void* dst, size_t n) { std::lock_guard<std::mutex> guard(reader_lock_); if ((!load_debug_symbol_) && c10::string_view(name).ends_with(kDebugPklSuffix)) { return 0; } size_t key = getRecordID(name); mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), key, &stat); TORCH_CHECK( n == stat.m_uncomp_size, "record size ", stat.m_uncomp_size, " mismatch with dst size ", n); valid("retrieving file meta-data for ", name.c_str()); mz_zip_reader_extract_to_mem(ar_.get(), key, dst, stat.m_uncomp_size, 0); valid("reading file ", name.c_str()); return stat.m_uncomp_size; } size_t PyTorchStreamReader::getRecord(const std::string& name, void* dst, size_t n, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders) { if(additionalReaders.empty()){ return getRecord(name, dst, n); } if ((!load_debug_symbol_) && c10::string_view(name).ends_with(kDebugPklSuffix)) { return 0; } size_t key = getRecordID(name); mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), key, &stat); TORCH_CHECK( n == stat.m_uncomp_size, "record size ", stat.m_uncomp_size, " mismatch with dst size ", n); valid("retrieving file meta-data for ", name.c_str()); if(n < additional_reader_size_threshold_){ return getRecord(name, dst, n); } PyTorchStreamReader::getRecordMultiReaders(name, additionalReaders, dst, n); return stat.m_uncomp_size; } size_t PyTorchStreamReader::getRecord( const std::string& name, void* dst, size_t n, size_t chunk_size, void* buf, const std::function<void(void*, const void*, size_t)>& memcpy_func) { std::lock_guard<std::mutex> guard(reader_lock_); if ((!load_debug_symbol_) && c10::string_view(name).ends_with(kDebugPklSuffix)) { return 0; } if (chunk_size <= 0) { chunk_size = n; } size_t key = getRecordID(name); mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), key, &stat); TORCH_CHECK( n == stat.m_uncomp_size, "record size ", stat.m_uncomp_size, " mismatch with dst size ", n); valid("retrieving file meta-data for ", name.c_str()); std::vector<uint8_t> buffer; if (buf == nullptr) { buffer.resize(chunk_size); buf = buffer.data(); } auto chunkIterator = createChunkReaderIter(name, (size_t)stat.m_uncomp_size, chunk_size); while (auto readSize = chunkIterator.next(buf)) { memcpy_func((char*)dst + chunkIterator.offset_ - readSize, buf, readSize); } valid("reading file ", name.c_str()); return stat.m_uncomp_size; } ChunkRecordIterator PyTorchStreamReader::createChunkReaderIter( const std::string& name, const size_t recordSize, const size_t chunkSize) { size_t key = getRecordID(name); mz_zip_reader_extract_iter_state* zipReaderIter = mz_zip_reader_extract_iter_new(ar_.get(), key, 0); TORCH_CHECK( zipReaderIter != nullptr, "Failed to create zip reader iter: ", mz_zip_get_error_string(mz_zip_get_last_error(ar_.get()))); return ChunkRecordIterator( recordSize, chunkSize, std::make_unique<MzZipReaderIterWrapper>(zipReaderIter)); } static int64_t read_le_16(uint8_t* buf) { return buf[0] + (buf[1] << 8); } size_t PyTorchStreamReader::getRecordOffset(const std::string& name) { std::lock_guard<std::mutex> guard(reader_lock_); mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), getRecordID(name), &stat); valid("retrieving file meta-data for ", name.c_str()); uint8_t local_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; in_->read( stat.m_local_header_ofs, local_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE, "reading file header"); size_t filename_len = read_le_16(local_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); size_t extra_len = read_le_16(local_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); return stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + filename_len + extra_len; } size_t PyTorchStreamReader::getRecordSize(const std::string& name) { mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(ar_.get(), getRecordID(name), &stat); return stat.m_uncomp_size; } PyTorchStreamReader::~PyTorchStreamReader() { mz_zip_clear_last_error(ar_.get()); mz_zip_reader_end(ar_.get()); valid("closing reader for archive ", archive_name_.c_str()); } size_t ostream_write_func( void* pOpaque, mz_uint64 file_ofs, const void* pBuf, size_t n) { auto self = static_cast<PyTorchStreamWriter*>(pOpaque); if (self->current_pos_ != file_ofs) { CAFFE_THROW("unexpected pos ", self->current_pos_, " vs ", file_ofs); } size_t ret = self->writer_func_(pBuf, n); if (n != ret) { self->err_seen_ = true; } self->current_pos_ += ret; if (pBuf && n >= 8 && MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) { const int8_t* pInt8Buf = (const int8_t*)pBuf; const uint32_t uncomp_crc32 = MZ_READ_LE32(pInt8Buf + 4); self->combined_uncomp_crc32_ = c10::hash_combine(self->combined_uncomp_crc32_, uncomp_crc32); } return ret; } PyTorchStreamWriter::PyTorchStreamWriter(const std::string& file_name) : archive_name_(basename(file_name)) { setup(file_name); } PyTorchStreamWriter::PyTorchStreamWriter( const std::function<size_t(const void*, size_t)> writer_func) : archive_name_("archive"), writer_func_(writer_func) { setup(archive_name_); } void PyTorchStreamWriter::setup(const string& file_name) { ar_ = std::make_unique<mz_zip_archive>(); memset(ar_.get(), 0, sizeof(mz_zip_archive)); archive_name_plus_slash_ = archive_name_ + "/"; if (archive_name_.size() == 0) { CAFFE_THROW("invalid file name: ", file_name); } if (!writer_func_) { file_stream_.open( file_name, std::ofstream::out | std::ofstream::trunc | std::ofstream::binary); valid("opening archive ", file_name.c_str()); const std::string dir_name = parentdir(file_name); if(!dir_name.empty()) { struct stat st; bool dir_exists = (stat(dir_name.c_str(), &st) == 0 && (st.st_mode & S_IFDIR)); TORCH_CHECK(dir_exists, "Parent directory ", dir_name, " does not exist."); } TORCH_CHECK(file_stream_, "File ", file_name, " cannot be opened."); writer_func_ = [this](const void* buf, size_t nbytes) -> size_t { if (!buf) { file_stream_.seekp(nbytes, std::ios_base::cur); } else { file_stream_.write(static_cast<const char*>(buf), nbytes); } return !file_stream_ ? 0 : nbytes; }; } ar_->m_pIO_opaque = this; ar_->m_pWrite = ostream_write_func; mz_zip_writer_init_v2(ar_.get(), 0, MZ_ZIP_FLAG_WRITE_ZIP64); valid("initializing archive ", file_name.c_str()); } void PyTorchStreamWriter::setMinVersion(const uint64_t version) { version_ = std::max(version, version_); } void PyTorchStreamWriter::writeRecord( const std::string& name, const void* data, size_t size, bool compress) { AT_ASSERT(!finalized_); AT_ASSERT(!archive_name_plus_slash_.empty()); TORCH_INTERNAL_ASSERT( files_written_.count(name) == 0, "Tried to serialize file twice: ", name); if (name == kSerializationIdRecordName && serialization_id_.empty()) { return; } std::string full_name = archive_name_plus_slash_ + name; size_t padding_size = detail::getPadding(ar_->m_archive_size, full_name.size(), size, padding_); uint32_t flags = compress ? MZ_BEST_COMPRESSION : 0; mz_zip_writer_add_mem_ex_v2( ar_.get(), full_na
#include <array> #include <cstdio> #include <cstring> #include <string> #include <gtest/gtest.h> #include "caffe2/serialize/inline_container.h" #include <c10/util/Logging.h> #include "c10/util/irange.h" namespace caffe2 { namespace serialize { namespace { TEST(PyTorchStreamWriterAndReader, SaveAndLoad) { int64_t kFieldAlignment = 64L; std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); std::array<char, 127> data1; std::vector<uint8_t> buf(data1.size()); for (auto i : c10::irange(data1.size())) { data1[i] = data1.size() - i; } writer.writeRecord("key1", data1.data(), data1.size()); std::array<char, 64> data2; for (auto i : c10::irange(data2.size())) { data2[i] = data2.size() - i; } writer.writeRecord("key2", data2.data(), data2.size()); const std::unordered_set<std::string>& written_records = writer.getAllWrittenRecords(); ASSERT_EQ(written_records.size(), 2); ASSERT_EQ(written_records.count("key1"), 1); ASSERT_EQ(written_records.count("key2"), 1); writer.writeEndOfFile(); ASSERT_EQ(written_records.count(kSerializationIdRecordName), 1); std::string the_file = oss.str(); const char* file_name = "output.zip"; std::ofstream foo(file_name); foo.write(the_file.c_str(), the_file.size()); foo.close(); std::istringstream iss(the_file); PyTorchStreamReader reader(&iss); ASSERT_TRUE(reader.hasRecord("key1")); ASSERT_TRUE(reader.hasRecord("key2")); ASSERT_FALSE(reader.hasRecord("key2000")); at::DataPtr data_ptr; int64_t size; std::tie(data_ptr, size) = reader.getRecord("key1"); size_t off1 = reader.getRecordOffset("key1"); ASSERT_EQ(size, data1.size()); ASSERT_EQ(memcmp(data_ptr.get(), data1.data(), data1.size()), 0); ASSERT_EQ(memcmp(the_file.c_str() + off1, data1.data(), data1.size()), 0); ASSERT_EQ(off1 % kFieldAlignment, 0); std::vector<uint8_t> dst(size); size_t ret = reader.getRecord("key1", dst.data(), size); ASSERT_EQ(ret, size); ASSERT_EQ(memcmp(dst.data(), data1.data(), size), 0); ret = reader.getRecord( "key1", dst.data(), size, 3, buf.data(), [](void* dst, const void* src, size_t n) { memcpy(dst, src, n); }); ASSERT_EQ(ret, size); ASSERT_EQ(memcmp(dst.data(), data1.data(), size), 0); std::tie(data_ptr, size) = reader.getRecord("key2"); size_t off2 = reader.getRecordOffset("key2"); ASSERT_EQ(off2 % kFieldAlignment, 0); ASSERT_EQ(size, data2.size()); ASSERT_EQ(memcmp(data_ptr.get(), data2.data(), data2.size()), 0); ASSERT_EQ(memcmp(the_file.c_str() + off2, data2.data(), data2.size()), 0); dst.resize(size); ret = reader.getRecord("key2", dst.data(), size); ASSERT_EQ(ret, size); ASSERT_EQ(memcmp(dst.data(), data2.data(), size), 0); ret = reader.getRecord( "key2", dst.data(), size, 3, buf.data(), [](void* dst, const void* src, size_t n) { memcpy(dst, src, n); }); ASSERT_EQ(ret, size); ASSERT_EQ(memcmp(dst.data(), data2.data(), size), 0); remove(file_name); } TEST(PyTorchStreamWriterAndReader, LoadWithMultiThreads) { std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); std::array<char, 127> data1; std::array<char, 64> data2; for (auto i : c10::irange(data1.size())) { data1[i] = data1.size() - i; } writer.writeRecord("key1", data1.data(), data1.size()); for (auto i : c10::irange(data2.size())) { data2[i] = data2.size() - i; } writer.writeRecord("key2", data2.data(), data2.size()); const std::unordered_set<std::string>& written_records = writer.getAllWrittenRecords(); ASSERT_EQ(written_records.size(), 2); ASSERT_EQ(written_records.count("key1"), 1); ASSERT_EQ(written_records.count("key2"), 1); writer.writeEndOfFile(); ASSERT_EQ(written_records.count(kSerializationIdRecordName), 1); std::string the_file = oss.str(); const char* file_name = "output.zip"; std::ofstream foo(file_name); foo.write(the_file.c_str(), the_file.size()); foo.close(); std::istringstream iss(the_file); PyTorchStreamReader reader(&iss); reader.setAdditionalReaderSizeThreshold(0); int64_t size1, size2, ret; at::DataPtr data_ptr; std::tie(data_ptr, size1) = reader.getRecord("key1"); std::tie(data_ptr, size2) = reader.getRecord("key2"); std::vector<std::shared_ptr<ReadAdapterInterface>> additionalReader; for(int i=0; i<10; ++i){ std::tie(data_ptr, ret) = reader.getRecord("key1", additionalReader); ASSERT_EQ(ret, size1); ASSERT_EQ(memcmp(data_ptr.get(), data1.data(), size1), 0); std::tie(data_ptr, ret) = reader.getRecord("key2", additionalReader); ASSERT_EQ(ret, size2); ASSERT_EQ(memcmp(data_ptr.get(), data2.data(), size2), 0); } additionalReader.clear(); std::vector<uint8_t> dst1(size1), dst2(size2); for(int i=0; i<10; ++i){ additionalReader.push_back(std::make_unique<IStreamAdapter>(&iss)); ret = reader.getRecord("key1", dst1.data(), size1, additionalReader); ASSERT_EQ(ret, size1); ASSERT_EQ(memcmp(dst1.data(), data1.data(), size1), 0); ret = reader.getRecord("key2", dst2.data(), size2, additionalReader); ASSERT_EQ(ret, size2); ASSERT_EQ(memcmp(dst2.data(), data2.data(), size2), 0); } remove(file_name); } TEST(PytorchStreamWriterAndReader, GetNonexistentRecordThrows) { std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); std::array<char, 127> data1; std::vector<uint8_t> buf; for (auto i : c10::irange(data1.size())) { data1[i] = data1.size() - i; } writer.writeRecord("key1", data1.data(), data1.size()); std::array<char, 64> data2; for (auto i : c10::irange(data2.size())) { data2[i] = data2.size() - i; } writer.writeRecord("key2", data2.data(), data2.size()); const std::unordered_set<std::string>& written_records = writer.getAllWrittenRecords(); ASSERT_EQ(written_records.size(), 2); ASSERT_EQ(written_records.count("key1"), 1); ASSERT_EQ(written_records.count("key2"), 1); writer.writeEndOfFile(); ASSERT_EQ(written_records.count(kSerializationIdRecordName), 1); std::string the_file = oss.str(); const char* file_name = "output2.zip"; std::ofstream foo(file_name); foo.write(the_file.c_str(), the_file.size()); foo.close(); std::istringstream iss(the_file); PyTorchStreamReader reader(&iss); EXPECT_THROW(reader.getRecord("key3"), c10::Error); std::vector<uint8_t> dst(data1.size()); EXPECT_THROW(reader.getRecord("key3", dst.data(), data1.size()), c10::Error); EXPECT_THROW( reader.getRecord( "key3", dst.data(), data1.size(), 3, buf.data(), [](void* dst, const void* src, size_t n) { memcpy(dst, src, n); }), c10::Error); EXPECT_TRUE(reader.hasRecord("key1")); remove(file_name); } TEST(PytorchStreamWriterAndReader, SkipDebugRecords) { std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); std::array<char, 127> data1; std::vector<uint8_t> buf(data1.size()); for (auto i : c10::irange(data1.size())) { data1[i] = data1.size() - i; } writer.writeRecord("key1.debug_pkl", data1.data(), data1.size()); std::array<char, 64> data2; for (auto i : c10::irange(data2.size())) { data2[i] = data2.size() - i; } writer.writeRecord("key2.debug_pkl", data2.data(), data2.size()); const std::unordered_set<std::string>& written_records = writer.getAllWrittenRecords(); ASSERT_EQ(written_records.size(), 2); ASSERT_EQ(written_records.count("key1.debug_pkl"), 1); ASSERT_EQ(written_records.count("key2.debug_pkl"), 1); writer.writeEndOfFile(); ASSERT_EQ(written_records.count(kSerializationIdRecordName), 1); std::string the_file = oss.str(); const char* file_name = "output3.zip"; std::ofstream foo(file_name); foo.write(the_file.c_str(), the_file.size()); foo.close(); std::istringstream iss(the_file); PyTorchStreamReader reader(&iss); reader.setShouldLoadDebugSymbol(false); EXPECT_FALSE(reader.hasRecord("key1.debug_pkl")); at::DataPtr ptr; size_t size; std::tie(ptr, size) = reader.getRecord("key1.debug_pkl"); EXPECT_EQ(size, 0); std::vector<uint8_t> dst(data1.size()); size_t ret = reader.getRecord("key1.debug_pkl", dst.data(), data1.size()); EXPECT_EQ(ret, 0); ret = reader.getRecord( "key1.debug_pkl", dst.data(), data1.size(), 3, buf.data(), [](void* dst, const void* src, size_t n) { memcpy(dst, src, n); }); EXPECT_EQ(ret, 0); remove(file_name); } TEST(PytorchStreamWriterAndReader, ValidSerializationId) { std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); std::array<char, 127> data1; for (auto i: c10::irange(data1.size())) { data1[i] = data1.size() - i; } writer.writeRecord("key1.debug_pkl", data1.data(), data1.size()); writer.writeEndOfFile(); auto writer_serialization_id = writer.serializationId(); std::string the_file = oss.str(); std::istringstream iss(the_file); PyTorchStreamReader reader(&iss); EXPECT_EQ(reader.serializationId(), writer_serialization_id); PyTorchStreamWriter writer2([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); writer2.writeRecord("key1.debug_pkl", data1.data(), data1.size()); writer2.writeEndOfFile(); auto writer2_serialization_id = writer2.serializationId(); EXPECT_EQ(writer_serialization_id, writer2_serialization_id); } TEST(PytorchStreamWriterAndReader, SkipDuplicateSerializationIdRecords) { std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); std::string dup_serialization_id = "dup-serialization-id"; writer.writeRecord(kSerializationIdRecordName, dup_serialization_id.c_str(), dup_serialization_id.size()); const std::unordered_set<std::string>& written_records = writer.getAllWrittenRecords(); ASSERT_EQ(written_records.size(), 0); writer.writeEndOfFile(); ASSERT_EQ(written_records.count(kSerializationIdRecordName), 1); auto writer_serialization_id = writer.serializationId(); std::string the_file = oss.str(); const char* file_name = "output4.zip"; std::ofstream foo(file_name); foo.write(the_file.c_str(), the_file.size()); foo.close(); std::istringstream iss(the_file); PyTorchStreamReader reader(&iss); EXPECT_EQ(reader.serializationId(), writer_serialization_id); remove(file_name); } TEST(PytorchStreamWriterAndReader, LogAPIUsageMetadata) { std::map<std::string, std::map<std::string, std::string>> logs; SetAPIUsageMetadataLogger( [&](const std::string& context, const std::map<std::string, std::string>& metadata_map) { logs.insert({context, metadata_map}); }); std::ostringstream oss; PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); writer.writeEndOfFile(); std::istringstream iss(oss.str()); PyTorchStreamReader reader(&iss); ASSERT_EQ(logs.size(), 2); std::map<std::string, std::map<std::string, std::string>> expected_logs = { {"pytorch.stream.writer.metadata", {{"serialization_id", writer.serializationId()}, {"file_name", "archive"}, {"file_size", str(oss.str().length())}}}, {"pytorch.stream.reader.metadata", {{"serialization_id", writer.serializationId()}, {"file_name", "archive"}, {"file_size", str(iss.str().length())}}} }; ASSERT_EQ(expected_logs, logs); SetAPIUsageMetadataLogger( [&](const std::string& context, const std::map<std::string, std::string>& metadata_map) {}); } class ChunkRecordIteratorTest : public ::testing::TestWithParam<int64_t> {}; INSTANTIATE_TEST_SUITE_P( ChunkRecordIteratorTestGroup, ChunkRecordIteratorTest, testing::Values(100, 150, 1010)); TEST_P(ChunkRecordIteratorTest, ChunkRead) { auto chunkSize = GetParam(); std::string zipFileName = "output_chunk_" + std::to_string(chunkSize) + ".zip"; const char* fileName = zipFileName.c_str(); const std::string recordName = "key1"; const size_t tensorDataSizeInBytes = 1000; std::ostringstream oss(std::ios::binary); PyTorchStreamWriter writer([&](const void* b, size_t n) -> size_t { oss.write(static_cast<const char*>(b), n); return oss ? n : 0; }); auto tensorData = std::vector<uint8_t>(tensorDataSizeInBytes, 1); auto dataPtr = tensorData.data(); writer.writeRecord(recordName, dataPtr, tensorDataSizeInBytes); const std::unordered_set<std::string>& written_records = writer.getAllWrittenRecords(); ASSERT_EQ(written_records.size(), 1); ASSERT_EQ(written_records.count(recordName), 1); writer.writeEndOfFile(); ASSERT_EQ(written_records.count(kSerializationIdRecordName), 1); std::string the_file = oss.str(); std::ofstream foo(fileName, std::ios::binary); foo.write(the_file.c_str(), the_file.size()); foo.close(); LOG(INFO) << "Finished saving tensor into zip file " << fileName; LOG(INFO) << "Testing chunk size " << chunkSize; PyTorchStreamReader reader(fileName); ASSERT_TRUE(reader.hasRecord(recordName)); auto chunkIterator = reader.createChunkReaderIter( recordName, tensorDataSizeInBytes, chunkSize); std::vector<uint8_t> buffer(chunkSize); size_t totalReadSize = 0; while (auto readSize = chunkIterator.next(buffer.data())) { auto expectedData = std::vector<uint8_t>(readSize, 1); ASSERT_EQ(memcmp(expectedData.data(), buffer.data(), readSize), 0); totalReadSize += readSize; } ASSERT_EQ(totalReadSize, tensorDataSizeInBytes); remove(fileName); } } } }
178
cpp
google/quiche
quiche_text_utils
quiche/common/quiche_text_utils.cc
quiche/common/quiche_text_utils_test.cc
#ifndef QUICHE_COMMON_QUICHE_TEXT_UTILS_H_ #define QUICHE_COMMON_QUICHE_TEXT_UTILS_H_ #include <optional> #include <string> #include "absl/hash/hash.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" namespace quiche { struct QUICHE_EXPORT StringPieceCaseHash { size_t operator()(absl::string_view data) const { std::string lower = absl::AsciiStrToLower(data); absl::Hash<absl::string_view> hasher; return hasher(lower); } }; struct QUICHE_EXPORT StringPieceCaseEqual { bool operator()(absl::string_view piece1, absl::string_view piece2) const { return absl::EqualsIgnoreCase(piece1, piece2); } }; class QUICHE_EXPORT QuicheTextUtils { public: static std::string ToLower(absl::string_view data) { return absl::AsciiStrToLower(data); } static void RemoveLeadingAndTrailingWhitespace(absl::string_view* data) { *data = absl::StripAsciiWhitespace(*data); } static void Base64Encode(const uint8_t* data, size_t data_len, std::string* output); static std::optional<std::string> Base64Decode(absl::string_view input); static std::string HexDump(absl::string_view binary_data); static bool ContainsUpperCase(absl::string_view data) { return std::any_of(data.begin(), data.end(), absl::ascii_isupper); } static bool IsAllDigits(absl::string_view data) { return std::all_of(data.begin(), data.end(), absl::ascii_isdigit); } }; } #endif #include "quiche/common/quiche_text_utils.h" #include <algorithm> #include <optional> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" namespace quiche { void QuicheTextUtils::Base64Encode(const uint8_t* data, size_t data_len, std::string* output) { absl::Base64Escape(std::string(reinterpret_cast<const char*>(data), data_len), output); size_t len = output->size(); if (len >= 2) { if ((*output)[len - 1] == '=') { len--; if ((*output)[len - 1] == '=') { len--; } output->resize(len); } } } std::optional<std::string> QuicheTextUtils::Base64Decode( absl::string_view input) { std::string output; if (!absl::Base64Unescape(input, &output)) { return std::nullopt; } return output; } std::string QuicheTextUtils::HexDump(absl::string_view binary_data) { const int kBytesPerLine = 16; int offset = 0; const char* p = binary_data.data(); int bytes_remaining = binary_data.size(); std::string output; while (bytes_remaining > 0) { const int line_bytes = std::min(bytes_remaining, kBytesPerLine); absl::StrAppendFormat(&output, "0x%04x: ", offset); for (int i = 0; i < kBytesPerLine; ++i) { if (i < line_bytes) { absl::StrAppendFormat(&output, "%02x", static_cast<unsigned char>(p[i])); } else { absl::StrAppend(&output, " "); } if (i % 2) { absl::StrAppend(&output, " "); } } absl::StrAppend(&output, " "); for (int i = 0; i < line_bytes; ++i) { output += absl::ascii_isgraph(p[i]) ? p[i] : '.'; } bytes_remaining -= line_bytes; offset += line_bytes; p += line_bytes; absl::StrAppend(&output, "\n"); } return output; } }
#include "quiche/common/quiche_text_utils.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { TEST(QuicheTextUtilsTest, ToLower) { EXPECT_EQ("lower", quiche::QuicheTextUtils::ToLower("LOWER")); EXPECT_EQ("lower", quiche::QuicheTextUtils::ToLower("lower")); EXPECT_EQ("lower", quiche::QuicheTextUtils::ToLower("lOwEr")); EXPECT_EQ("123", quiche::QuicheTextUtils::ToLower("123")); EXPECT_EQ("", quiche::QuicheTextUtils::ToLower("")); } TEST(QuicheTextUtilsTest, RemoveLeadingAndTrailingWhitespace) { for (auto* const input : {"text", " text", " text", "text ", "text ", " text ", " text ", "\r\n\ttext", "text\n\r\t"}) { absl::string_view piece(input); quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&piece); EXPECT_EQ("text", piece); } } TEST(QuicheTextUtilsTest, HexDump) { std::string empty; ASSERT_TRUE(absl::HexStringToBytes("", &empty)); EXPECT_EQ("", quiche::QuicheTextUtils::HexDump(empty)); char packet[] = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x51, 0x55, 0x49, 0x43, 0x21, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x73, 0x68, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x65, 0x6e, 0x6f, 0x75, 0x67, 0x68, 0x20, 0x74, 0x6f, 0x20, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2e, 0x01, 0x02, 0x03, 0x00, }; EXPECT_EQ( quiche::QuicheTextUtils::HexDump(packet), "0x0000: 4865 6c6c 6f2c 2051 5549 4321 2054 6869 Hello,.QUIC!.Thi\n" "0x0010: 7320 7374 7269 6e67 2073 686f 756c 6420 s.string.should.\n" "0x0020: 6265 206c 6f6e 6720 656e 6f75 6768 2074 be.long.enough.t\n" "0x0030: 6f20 7370 616e 206d 756c 7469 706c 6520 o.span.multiple.\n" "0x0040: 6c69 6e65 7320 6f66 206f 7574 7075 742e lines.of.output.\n" "0x0050: 0102 03 ...\n"); std::string printable_and_unprintable_chars; ASSERT_TRUE( absl::HexStringToBytes("20217e7f", &printable_and_unprintable_chars)); EXPECT_EQ("0x0000: 2021 7e7f .!~.\n", quiche::QuicheTextUtils::HexDump(printable_and_unprintable_chars)); std::string large_chars; ASSERT_TRUE(absl::HexStringToBytes("90aaff", &large_chars)); EXPECT_EQ("0x0000: 90aa ff ...\n", quiche::QuicheTextUtils::HexDump(large_chars)); } TEST(QuicheTextUtilsTest, Base64Encode) { std::string output; std::string input = "Hello"; quiche::QuicheTextUtils::Base64Encode( reinterpret_cast<const uint8_t*>(input.data()), input.length(), &output); EXPECT_EQ("SGVsbG8", output); input = "Hello, QUIC! This string should be long enough to span" "multiple lines of output\n"; quiche::QuicheTextUtils::Base64Encode( reinterpret_cast<const uint8_t*>(input.data()), input.length(), &output); EXPECT_EQ( "SGVsbG8sIFFVSUMhIFRoaXMgc3RyaW5nIHNob3VsZCBiZSBsb25n" "IGVub3VnaCB0byBzcGFubXVsdGlwbGUgbGluZXMgb2Ygb3V0cHV0Cg", output); } TEST(QuicheTextUtilsTest, ContainsUpperCase) { EXPECT_FALSE(quiche::QuicheTextUtils::ContainsUpperCase("abc")); EXPECT_FALSE(quiche::QuicheTextUtils::ContainsUpperCase("")); EXPECT_FALSE(quiche::QuicheTextUtils::ContainsUpperCase("123")); EXPECT_TRUE(quiche::QuicheTextUtils::ContainsUpperCase("ABC")); EXPECT_TRUE(quiche::QuicheTextUtils::ContainsUpperCase("aBc")); } } }
179
cpp
google/quiche
simple_buffer_allocator
quiche/common/simple_buffer_allocator.cc
quiche/common/simple_buffer_allocator_test.cc
#ifndef QUICHE_COMMON_SIMPLE_BUFFER_ALLOCATOR_H_ #define QUICHE_COMMON_SIMPLE_BUFFER_ALLOCATOR_H_ #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_buffer_allocator.h" namespace quiche { class QUICHE_EXPORT SimpleBufferAllocator : public QuicheBufferAllocator { public: static SimpleBufferAllocator* Get() { static SimpleBufferAllocator* singleton = new SimpleBufferAllocator(); return singleton; } char* New(size_t size) override; char* New(size_t size, bool flag_enable) override; void Delete(char* buffer) override; }; } #endif #include "quiche/common/simple_buffer_allocator.h" namespace quiche { char* SimpleBufferAllocator::New(size_t size) { return new char[size]; } char* SimpleBufferAllocator::New(size_t size, bool ) { return New(size); } void SimpleBufferAllocator::Delete(char* buffer) { delete[] buffer; } }
#include "quiche/common/simple_buffer_allocator.h" #include <utility> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { TEST(SimpleBufferAllocatorTest, NewDelete) { SimpleBufferAllocator alloc; char* buf = alloc.New(4); EXPECT_NE(nullptr, buf); alloc.Delete(buf); } TEST(SimpleBufferAllocatorTest, DeleteNull) { SimpleBufferAllocator alloc; alloc.Delete(nullptr); } TEST(SimpleBufferAllocatorTest, MoveBuffersConstructor) { SimpleBufferAllocator alloc; QuicheBuffer buffer1(&alloc, 16); EXPECT_NE(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 16u); QuicheBuffer buffer2(std::move(buffer1)); EXPECT_EQ(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 0u); EXPECT_NE(buffer2.data(), nullptr); EXPECT_EQ(buffer2.size(), 16u); } TEST(SimpleBufferAllocatorTest, MoveBuffersAssignment) { SimpleBufferAllocator alloc; QuicheBuffer buffer1(&alloc, 16); QuicheBuffer buffer2; EXPECT_NE(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 16u); EXPECT_EQ(buffer2.data(), nullptr); EXPECT_EQ(buffer2.size(), 0u); buffer2 = std::move(buffer1); EXPECT_EQ(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 0u); EXPECT_NE(buffer2.data(), nullptr); EXPECT_EQ(buffer2.size(), 16u); } TEST(SimpleBufferAllocatorTest, CopyBuffer) { SimpleBufferAllocator alloc; const absl::string_view original = "Test string"; QuicheBuffer copy = QuicheBuffer::Copy(&alloc, original); EXPECT_EQ(copy.AsStringView(), original); } } }
180
cpp
google/quiche
quiche_data_writer
quiche/common/quiche_data_writer.cc
quiche/common/quiche_data_writer_test.cc
#ifndef QUICHE_COMMON_QUICHE_DATA_WRITER_H_ #define QUICHE_COMMON_QUICHE_DATA_WRITER_H_ #include <cstddef> #include <cstdint> #include <cstring> #include <limits> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_endian.h" namespace quiche { enum : uint64_t { kVarInt62MaxValue = UINT64_C(0x3fffffffffffffff), }; enum : uint64_t { kVarInt62ErrorMask = UINT64_C(0xc000000000000000), kVarInt62Mask8Bytes = UINT64_C(0x3fffffffc0000000), kVarInt62Mask4Bytes = UINT64_C(0x000000003fffc000), kVarInt62Mask2Bytes = UINT64_C(0x0000000000003fc0), }; class QUICHE_EXPORT QuicheDataWriter { public: QuicheDataWriter(size_t size, char* buffer); QuicheDataWriter(size_t size, char* buffer, quiche::Endianness endianness); QuicheDataWriter(const QuicheDataWriter&) = delete; QuicheDataWriter& operator=(const QuicheDataWriter&) = delete; ~QuicheDataWriter(); size_t length() const { return length_; } char* data(); bool WriteUInt8(uint8_t value); bool WriteUInt16(uint16_t value); bool WriteUInt32(uint32_t value); bool WriteUInt64(uint64_t value); bool WriteBytesToUInt64(size_t num_bytes, uint64_t value); bool WriteStringPiece(absl::string_view val); bool WriteStringPiece16(absl::string_view val); bool WriteBytes(const void* data, size_t data_len); bool WriteRepeatedByte(uint8_t byte, size_t count); void WritePadding(); bool WritePaddingBytes(size_t count); bool WriteTag(uint32_t tag); bool WriteVarInt62(uint64_t value); bool WriteVarInt62WithForcedLength( uint64_t value, QuicheVariableLengthIntegerLength write_length); bool WriteStringPieceVarInt62(const absl::string_view& string_piece); static QuicheVariableLengthIntegerLength GetVarInt62Len(uint64_t value); bool Seek(size_t length); size_t capacity() const { return capacity_; } size_t remaining() const { return capacity_ - length_; } std::string DebugString() const; protected: char* BeginWrite(size_t length); quiche::Endianness endianness() const { return endianness_; } char* buffer() const { return buffer_; } void IncreaseLength(size_t delta) { QUICHE_DCHECK_LE(length_, std::numeric_limits<size_t>::max() - delta); QUICHE_DCHECK_LE(length_, capacity_ - delta); length_ += delta; } private: char* buffer_; size_t capacity_; size_t length_; quiche::Endianness endianness_; }; } #endif #include "quiche/common/quiche_data_writer.h" #include <algorithm> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/quiche_endian.h" namespace quiche { QuicheDataWriter::QuicheDataWriter(size_t size, char* buffer) : QuicheDataWriter(size, buffer, quiche::NETWORK_BYTE_ORDER) {} QuicheDataWriter::QuicheDataWriter(size_t size, char* buffer, quiche::Endianness endianness) : buffer_(buffer), capacity_(size), length_(0), endianness_(endianness) {} QuicheDataWriter::~QuicheDataWriter() {} char* QuicheDataWriter::data() { return buffer_; } bool QuicheDataWriter::WriteUInt8(uint8_t value) { return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteUInt16(uint16_t value) { if (endianness_ == quiche::NETWORK_BYTE_ORDER) { value = quiche::QuicheEndian::HostToNet16(value); } return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteUInt32(uint32_t value) { if (endianness_ == quiche::NETWORK_BYTE_ORDER) { value = quiche::QuicheEndian::HostToNet32(value); } return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteUInt64(uint64_t value) { if (endianness_ == quiche::NETWORK_BYTE_ORDER) { value = quiche::QuicheEndian::HostToNet64(value); } return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteBytesToUInt64(size_t num_bytes, uint64_t value) { if (num_bytes > sizeof(value)) { return false; } if (endianness_ == quiche::HOST_BYTE_ORDER) { return WriteBytes(&value, num_bytes); } value = quiche::QuicheEndian::HostToNet64(value); return WriteBytes(reinterpret_cast<char*>(&value) + sizeof(value) - num_bytes, num_bytes); } bool QuicheDataWriter::WriteStringPiece16(absl::string_view val) { if (val.size() > std::numeric_limits<uint16_t>::max()) { return false; } if (!WriteUInt16(static_cast<uint16_t>(val.size()))) { return false; } return WriteBytes(val.data(), val.size()); } bool QuicheDataWriter::WriteStringPiece(absl::string_view val) { return WriteBytes(val.data(), val.size()); } char* QuicheDataWriter::BeginWrite(size_t length) { if (length_ > capacity_) { return nullptr; } if (capacity_ - length_ < length) { return nullptr; } #ifdef ARCH_CPU_64_BITS QUICHE_DCHECK_LE(length, std::numeric_limits<uint32_t>::max()); #endif return buffer_ + length_; } bool QuicheDataWriter::WriteBytes(const void* data, size_t data_len) { char* dest = BeginWrite(data_len); if (!dest) { return false; } std::copy(static_cast<const char*>(data), static_cast<const char*>(data) + data_len, dest); length_ += data_len; return true; } bool QuicheDataWriter::WriteRepeatedByte(uint8_t byte, size_t count) { char* dest = BeginWrite(count); if (!dest) { return false; } std::fill(dest, dest + count, byte); length_ += count; return true; } void QuicheDataWriter::WritePadding() { QUICHE_DCHECK_LE(length_, capacity_); if (length_ > capacity_) { return; } std::fill(buffer_ + length_, buffer_ + capacity_, 0x00); length_ = capacity_; } bool QuicheDataWriter::WritePaddingBytes(size_t count) { return WriteRepeatedByte(0x00, count); } bool QuicheDataWriter::WriteTag(uint32_t tag) { return WriteBytes(&tag, sizeof(tag)); } bool QuicheDataWriter::WriteVarInt62(uint64_t value) { QUICHE_DCHECK_EQ(endianness(), quiche::NETWORK_BYTE_ORDER); size_t remaining_bytes = remaining(); char* next = buffer() + length(); if ((value & kVarInt62ErrorMask) == 0) { if ((value & kVarInt62Mask8Bytes) != 0) { if (remaining_bytes >= 8) { *(next + 0) = ((value >> 56) & 0x3f) + 0xc0; *(next + 1) = (value >> 48) & 0xff; *(next + 2) = (value >> 40) & 0xff; *(next + 3) = (value >> 32) & 0xff; *(next + 4) = (value >> 24) & 0xff; *(next + 5) = (value >> 16) & 0xff; *(next + 6) = (value >> 8) & 0xff; *(next + 7) = value & 0xff; IncreaseLength(8); return true; } return false; } if ((value & kVarInt62Mask4Bytes) != 0) { if (remaining_bytes >= 4) { *(next + 0) = ((value >> 24) & 0x3f) + 0x80; *(next + 1) = (value >> 16) & 0xff; *(next + 2) = (value >> 8) & 0xff; *(next + 3) = value & 0xff; IncreaseLength(4); return true; } return false; } if ((value & kVarInt62Mask2Bytes) != 0) { if (remaining_bytes >= 2) { *(next + 0) = ((value >> 8) & 0x3f) + 0x40; *(next + 1) = (value)&0xff; IncreaseLength(2); return true; } return false; } if (remaining_bytes >= 1) { *next = (value & 0x3f); IncreaseLength(1); return true; } return false; } return false; } bool QuicheDataWriter::WriteStringPieceVarInt62( const absl::string_view& string_piece) { if (!WriteVarInt62(string_piece.size())) { return false; } if (!string_piece.empty()) { if (!WriteBytes(string_piece.data(), string_piece.size())) { return false; } } return true; } QuicheVariableLengthIntegerLength QuicheDataWriter::GetVarInt62Len( uint64_t value) { if ((value & kVarInt62ErrorMask) != 0) { QUICHE_BUG(invalid_varint) << "Attempted to encode a value, " << value << ", that is too big for VarInt62"; return VARIABLE_LENGTH_INTEGER_LENGTH_0; } if ((value & kVarInt62Mask8Bytes) != 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_8; } if ((value & kVarInt62Mask4Bytes) != 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_4; } if ((value & kVarInt62Mask2Bytes) != 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_2; } return VARIABLE_LENGTH_INTEGER_LENGTH_1; } bool QuicheDataWriter::WriteVarInt62WithForcedLength( uint64_t value, QuicheVariableLengthIntegerLength write_length) { QUICHE_DCHECK_EQ(endianness(), NETWORK_BYTE_ORDER); size_t remaining_bytes = remaining(); if (remaining_bytes < write_length) { return false; } const QuicheVariableLengthIntegerLength min_length = GetVarInt62Len(value); if (write_length < min_length) { QUICHE_BUG(invalid_varint_forced) << "Cannot write value " << value << " with write_length " << write_length; return false; } if (write_length == min_length) { return WriteVarInt62(value); } if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_2) { return WriteUInt8(0b01000000) && WriteUInt8(value); } if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_4) { return WriteUInt8(0b10000000) && WriteUInt8(0) && WriteUInt16(value); } if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_8) { return WriteUInt8(0b11000000) && WriteUInt8(0) && WriteUInt16(0) && WriteUInt32(value); } QUICHE_BUG(invalid_write_length) << "Invalid write_length " << static_cast<int>(write_length); return false; } bool QuicheDataWriter::Seek(size_t length) { if (!BeginWrite(length)) { return false; } length_ += length; return true; } std::string QuicheDataWriter::DebugString() const { return absl::StrCat(" { capacity: ", capacity_, ", length: ", length_, " }"); } }
#include "quiche/common/quiche_data_writer.h" #include <cstdint> #include <cstring> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { char* AsChars(unsigned char* data) { return reinterpret_cast<char*>(data); } struct TestParams { explicit TestParams(quiche::Endianness endianness) : endianness(endianness) {} quiche::Endianness endianness; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( (p.endianness == quiche::NETWORK_BYTE_ORDER ? "Network" : "Host"), "ByteOrder"); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (quiche::Endianness endianness : {quiche::NETWORK_BYTE_ORDER, quiche::HOST_BYTE_ORDER}) { params.push_back(TestParams(endianness)); } return params; } class QuicheDataWriterTest : public QuicheTestWithParam<TestParams> {}; INSTANTIATE_TEST_SUITE_P(QuicheDataWriterTests, QuicheDataWriterTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicheDataWriterTest, Write16BitUnsignedIntegers) { char little_endian16[] = {0x22, 0x11}; char big_endian16[] = {0x11, 0x22}; char buffer16[2]; { uint16_t in_memory16 = 0x1122; QuicheDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteUInt16(in_memory16); test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint16_t read_number16; QuicheDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadUInt16(&read_number16); EXPECT_EQ(in_memory16, read_number16); } { uint64_t in_memory16 = 0x0000000000001122; QuicheDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteBytesToUInt64(2, in_memory16); test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint64_t read_number16; QuicheDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadBytesToUInt64(2, &read_number16); EXPECT_EQ(in_memory16, read_number16); } } TEST_P(QuicheDataWriterTest, Write24BitUnsignedIntegers) { char little_endian24[] = {0x33, 0x22, 0x11}; char big_endian24[] = {0x11, 0x22, 0x33}; char buffer24[3]; uint64_t in_memory24 = 0x0000000000112233; QuicheDataWriter writer(3, buffer24, GetParam().endianness); writer.WriteBytesToUInt64(3, in_memory24); test::CompareCharArraysWithHexError( "uint24", buffer24, 3, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian24 : little_endian24, 3); uint64_t read_number24; QuicheDataReader reader(buffer24, 3, GetParam().endianness); reader.ReadBytesToUInt64(3, &read_number24); EXPECT_EQ(in_memory24, read_number24); } TEST_P(QuicheDataWriterTest, Write32BitUnsignedIntegers) { char little_endian32[] = {0x44, 0x33, 0x22, 0x11}; char big_endian32[] = {0x11, 0x22, 0x33, 0x44}; char buffer32[4]; { uint32_t in_memory32 = 0x11223344; QuicheDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteUInt32(in_memory32); test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint32_t read_number32; QuicheDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadUInt32(&read_number32); EXPECT_EQ(in_memory32, read_number32); } { uint64_t in_memory32 = 0x11223344; QuicheDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteBytesToUInt64(4, in_memory32); test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint64_t read_number32; QuicheDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadBytesToUInt64(4, &read_number32); EXPECT_EQ(in_memory32, read_number32); } } TEST_P(QuicheDataWriterTest, Write40BitUnsignedIntegers) { uint64_t in_memory40 = 0x0000001122334455; char little_endian40[] = {0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian40[] = {0x11, 0x22, 0x33, 0x44, 0x55}; char buffer40[5]; QuicheDataWriter writer(5, buffer40, GetParam().endianness); writer.WriteBytesToUInt64(5, in_memory40); test::CompareCharArraysWithHexError( "uint40", buffer40, 5, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian40 : little_endian40, 5); uint64_t read_number40; QuicheDataReader reader(buffer40, 5, GetParam().endianness); reader.ReadBytesToUInt64(5, &read_number40); EXPECT_EQ(in_memory40, read_number40); } TEST_P(QuicheDataWriterTest, Write48BitUnsignedIntegers) { uint64_t in_memory48 = 0x0000112233445566; char little_endian48[] = {0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian48[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; char buffer48[6]; QuicheDataWriter writer(6, buffer48, GetParam().endianness); writer.WriteBytesToUInt64(6, in_memory48); test::CompareCharArraysWithHexError( "uint48", buffer48, 6, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian48 : little_endian48, 6); uint64_t read_number48; QuicheDataReader reader(buffer48, 6, GetParam().endianness); reader.ReadBytesToUInt64(6., &read_number48); EXPECT_EQ(in_memory48, read_number48); } TEST_P(QuicheDataWriterTest, Write56BitUnsignedIntegers) { uint64_t in_memory56 = 0x0011223344556677; char little_endian56[] = {0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian56[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; char buffer56[7]; QuicheDataWriter writer(7, buffer56, GetParam().endianness); writer.WriteBytesToUInt64(7, in_memory56); test::CompareCharArraysWithHexError( "uint56", buffer56, 7, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian56 : little_endian56, 7); uint64_t read_number56; QuicheDataReader reader(buffer56, 7, GetParam().endianness); reader.ReadBytesToUInt64(7, &read_number56); EXPECT_EQ(in_memory56, read_number56); } TEST_P(QuicheDataWriterTest, Write64BitUnsignedIntegers) { uint64_t in_memory64 = 0x1122334455667788; unsigned char little_endian64[] = {0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; unsigned char big_endian64[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; char buffer64[8]; QuicheDataWriter writer(8, buffer64, GetParam().endianness); writer.WriteBytesToUInt64(8, in_memory64); test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); uint64_t read_number64; QuicheDataReader reader(buffer64, 8, GetParam().endianness); reader.ReadBytesToUInt64(8, &read_number64); EXPECT_EQ(in_memory64, read_number64); QuicheDataWriter writer2(8, buffer64, GetParam().endianness); writer2.WriteUInt64(in_memory64); test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); read_number64 = 0u; QuicheDataReader reader2(buffer64, 8, GetParam().endianness); reader2.ReadUInt64(&read_number64); EXPECT_EQ(in_memory64, read_number64); } TEST_P(QuicheDataWriterTest, WriteIntegers) { char buf[43]; uint8_t i8 = 0x01; uint16_t i16 = 0x0123; uint32_t i32 = 0x01234567; uint64_t i64 = 0x0123456789ABCDEF; QuicheDataWriter writer(46, buf, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { switch (i) { case 0u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 1u: EXPECT_TRUE(writer.WriteUInt8(i8)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 2u: EXPECT_TRUE(writer.WriteUInt16(i16)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 3u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 4u: EXPECT_TRUE(writer.WriteUInt32(i32)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 5u: case 6u: case 7u: case 8u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; default: EXPECT_FALSE(writer.WriteBytesToUInt64(i, i64)); } } QuicheDataReader reader(buf, 46, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { uint8_t read8; uint16_t read16; uint32_t read32; uint64_t read64; switch (i) { case 0u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0u, read64); break; case 1u: EXPECT_TRUE(reader.ReadUInt8(&read8)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i8, read8); EXPECT_EQ(0xEFu, read64); break; case 2u: EXPECT_TRUE(reader.ReadUInt16(&read16)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i16, read16); EXPECT_EQ(0xCDEFu, read64); break; case 3u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0xABCDEFu, read64); break; case 4u: EXPECT_TRUE(reader.ReadUInt32(&read32)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i32, read32); EXPECT_EQ(0x89ABCDEFu, read64); break; case 5u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x6789ABCDEFu, read64); break; case 6u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x456789ABCDEFu, read64); break; case 7u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x23456789ABCDEFu, read64); break; case 8u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x0123456789ABCDEFu, read64); break; default: EXPECT_FALSE(reader.ReadBytesToUInt64(i, &read64)); } } } TEST_P(QuicheDataWriterTest, WriteBytes) { char bytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; char buf[ABSL_ARRAYSIZE(bytes)]; QuicheDataWriter writer(ABSL_ARRAYSIZE(buf), buf, GetParam().endianness); EXPECT_TRUE(writer.WriteBytes(bytes, ABSL_ARRAYSIZE(bytes))); for (unsigned int i = 0; i < ABSL_ARRAYSIZE(bytes); ++i) { EXPECT_EQ(bytes[i], buf[i]); } } const int kVarIntBufferLength = 1024; bool EncodeDecodeValue(uint64_t value_in, char* buffer, size_t size_of_buffer) { memset(buffer, 0, size_of_buffer); QuicheDataWriter writer(size_of_buffer, buffer, quiche::Endianness::NETWORK_BYTE_ORDER); if (writer.WriteVarInt62(value_in) != true) { return false; } size_t expected_length = 0; if (value_in <= 0x3f) { expected_length = 1; } else if (value_in <= 0x3fff) { expected_length = 2; } else if (value_in <= 0x3fffffff) { expected_length = 4; } else { expected_length = 8; } if (writer.length() != expected_length) { return false; } QuicheDataReader reader(buffer, expected_length, quiche::Endianness::NETWORK_BYTE_ORDER); uint64_t value_out; if (reader.ReadVarInt62(&value_out) == false) { return false; } if (value_in != value_out) { return false; } return reader.IsDoneReading(); } TEST_P(QuicheDataWriterTest, VarInt8Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142f3e4d5c6b7a8))); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), (0x31 + 0xc0)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 1)), 0x42); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 2)), 0xf3); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 3)), 0xe4); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 4)), 0xd5); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 5)), 0xc6); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 6)), 0xb7); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 7)), 0xa8); } TEST_P(QuicheDataWriterTest, VarInt4Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(0x3243f4e5)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), (0x32 + 0x80)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 1)), 0x43); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 2)), 0xf4); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 3)), 0xe5); } TEST_P(QuicheDataWriterTest, VarInt2Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(0x3647)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), (0x36 + 0x40)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 1)), 0x47); } TEST_P(QuicheDataWriterTest, VarInt1Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(0x3f)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), 0x3f); } TEST_P(QuicheDataWriterTest, VarIntGoodTargetedValues) { char buffer[kVarIntBufferLength]; uint64_t passing_values[] = { 0, 1, 0x3e, 0x3f, 0x40, 0x41, 0x3ffe, 0x3fff, 0x4000, 0x4001, 0x3ffffffe, 0x3fffffff, 0x40000000, 0x40000001, 0x3ffffffffffffffe, 0x3fffffffffffffff, 0xfe, 0xff, 0x100, 0x101, 0xfffe, 0xffff, 0x10000, 0x10001, 0xfffffe, 0xffffff, 0x1000000, 0x1000001, 0xfffffffe, 0xffffffff, 0x100000000, 0x100000001, 0xfffffffffe, 0xffffffffff, 0x10000000000, 0x10000000001, 0xfffffffffffe, 0xffffffffffff, 0x1000000000000, 0x1000000000001, 0xfffffffffffffe, 0xffffffffffffff, 0x100000000000000, 0x100000000000001, }; for (uint64_t test_val : passing_values) { EXPECT_TRUE( EncodeDecodeValue(test_val, static_cast<char*>(buffer), sizeof(buffer))) << " encode/decode of " << test_val << " failed"; } } TEST_P(QuicheDataWriterTest, VarIntBadTargetedValues) { char buffer[kVarIntBufferLength]; uint64_t failing_values[] = { 0x4000000000000000, 0x4000000000000001, 0xfffffffffffffffe, 0xffffffffffffffff, }; for (uint64_t test_val : failing_values) { EXPECT_FALSE( EncodeDecodeValue(test_val, static_cast<char*>(buffer), sizeof(buffer))) << " encode/decode of " << test_val << " succeeded, but was an " << "invalid value"; } } TEST_P(QuicheDataWriterTest, WriteVarInt62WithForcedLength) { char buffer[90]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer)); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_1); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_1); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(64, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(64, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(64, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(16383, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(16383, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(16383, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(16384, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(16384, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(1073741823, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(1073741823, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(1073741824, VARIABLE_LENGTH_INTEGER_LENGTH_8); QuicheDataReader reader(buffer, sizeof(buffer)); uint64_t test_val = 0; for (int i = 0; i < 4; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 1u); } for (int i = 0; i < 4; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 63u); } for (int i = 0; i < 3; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 64u); } for (int i = 0; i < 3; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 16383u); } for (int i = 0; i < 2; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 16384u); } for (int i = 0; i < 2; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 1073741823u); } EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 1073741824u); EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } const int kMultiVarCount = 1000; TEST_P(QuicheDataWriterTest, MultiVarInt8) { uint64_t test_val; char buffer[8 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142f3e4d5c6b7a8) + i)); } EXPECT_EQ(writer.length(), 8u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x3142f3e4d5c6b7a8))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x3142f3e4d5c6b7a8) + i)); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, MultiVarInt4) { uint64_t test_val; char buffer[4 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142f3e4) + i)); } EXPECT_EQ(writer.length(), 4u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x3142f3e4))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x3142f3e4) + i)); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, MultiVarInt2) { uint64_t test_val; char buffer[2 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142) + i)); } EXPECT_EQ(writer.length(), 2u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x3142))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x3142) + i)); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, MultiVarInt1) { uint64_t test_val; char buffer[1 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x30) + (i & 0xf))); } EXPECT_EQ(writer.length(), 1u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x31))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x30) + (i & 0xf))); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, Seek) { char buffer[3] = {}; QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUInt8(42)); EXPECT_TRUE(writer.Seek(1)); EXPECT_TRUE(writer.WriteUInt8(3)); char expected[] = {42, 0, 3}; for (size_t i = 0; i < ABSL_ARRAYSIZE(expected); ++i) { EXPECT_EQ(buffer[i], expected[i]); } } TEST_P(QuicheDataWriterTest, SeekTooFarFails) { char buffer[20]; { QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(20)); EXPECT_FALSE(writer.Seek(1)); } { QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_FALSE(writer.Seek(100)); } { QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(10)); EXPECT_FALSE(writer.Seek(std::numeric_limits<size_t>::max())); } } TEST_P(QuicheDataWriterTest, PayloadReads) { char buffer[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; char expected_first_read[4] = {1, 2, 3, 4}; char expected_remaining[12] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; QuicheDataReader reader(buffer, sizeof(buffer)); absl::string_view previously_read_payload1 = reader.PreviouslyReadPayload(); EXPECT_TRUE(previously_read_payload1.empty()); char first_read_buffer[4] = {}; EXPECT_TRUE(reader.ReadBytes(first_read_buffer, sizeof(first_read_buffer))); test::CompareCharArraysWithHexError( "first read", first_read_buffer, sizeof(first_read_buffer), expected_first_read, sizeof(expected_first_read)); absl::string_view peeked_remaining_payload = reader.PeekRemainingPayload(); test::CompareCharArraysWithHexError( "peeked_remaining_payload", peeked_remaining_payload.data(), peeked_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); absl::string_view full_payload = reader.FullPayload(); test::CompareCharArraysWithHexError("full_payload", full_payload.data(), full_payload.length(), buffer, sizeof(buffer)); absl::string_view previously_read_payload2 = reader.PreviouslyReadPayload(); test::CompareCharArraysWithHexError( "previously_read_payload2", previously_read_payload2.data(), previously_read_payload2.length(), first_read_buffer, sizeof(first_read_buffer)); absl::string_view read_remaining_payload = reader.ReadRemainingPayload(); test::CompareCharArraysWithHexError( "read_remaining_payload", read_remaining_payload.data(), read_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); EXPECT_TRUE(reader.IsDoneReading()); absl::string_view full_payload2 = reader.FullPayload(); test::CompareCharArraysWithHexError("full_payload2", full_payload2.data(), full_payload2.length(), buffer, sizeof(buffer)); absl::string_view previously_read_payload3 = reader.PreviouslyReadPayload(); test::CompareCharArraysWithHexError( "previously_read_payload3", previously_read_payload3.data(), previously_read_payload3.length(), buffer, sizeof(buffer)); } } } }
181
cpp
google/quiche
quiche_ip_address
quiche/common/quiche_ip_address.cc
quiche/common/quiche_ip_address_test.cc
#ifndef QUICHE_COMMON_QUICHE_IP_ADDRESS_H_ #define QUICHE_COMMON_QUICHE_IP_ADDRESS_H_ #include <cstdint> #if defined(_WIN32) #include <winsock2.h> #include <ws2tcpip.h> #else #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #endif #include <ostream> #include <string> #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_ip_address_family.h" namespace quiche { class QUICHE_EXPORT QuicheIpAddress { public: enum : size_t { kIPv4AddressSize = 32 / 8, kIPv6AddressSize = 128 / 8, kMaxAddressSize = kIPv6AddressSize, }; static QuicheIpAddress Loopback4(); static QuicheIpAddress Loopback6(); static QuicheIpAddress Any4(); static QuicheIpAddress Any6(); QuicheIpAddress(); QuicheIpAddress(const QuicheIpAddress& other) = default; explicit QuicheIpAddress(const in_addr& ipv4_address); explicit QuicheIpAddress(const in6_addr& ipv6_address); QuicheIpAddress& operator=(const QuicheIpAddress& other) = default; QuicheIpAddress& operator=(QuicheIpAddress&& other) = default; QUICHE_EXPORT friend bool operator==(QuicheIpAddress lhs, QuicheIpAddress rhs); QUICHE_EXPORT friend bool operator!=(QuicheIpAddress lhs, QuicheIpAddress rhs); bool IsInitialized() const; IpAddressFamily address_family() const; int AddressFamilyToInt() const; std::string ToPackedString() const; std::string ToString() const; QuicheIpAddress Normalized() const; QuicheIpAddress DualStacked() const; bool FromPackedString(const char* data, size_t length); bool FromString(std::string str); bool IsIPv4() const; bool IsIPv6() const; bool InSameSubnet(const QuicheIpAddress& other, int subnet_length); in_addr GetIPv4() const; in6_addr GetIPv6() const; private: union { in_addr v4; in6_addr v6; uint8_t bytes[kMaxAddressSize]; char chars[kMaxAddressSize]; } address_; IpAddressFamily family_; }; inline std::ostream& operator<<(std::ostream& os, const QuicheIpAddress address) { os << address.ToString(); return os; } class QUICHE_EXPORT QuicheIpPrefix { public: QuicheIpPrefix(); explicit QuicheIpPrefix(const QuicheIpAddress& address); explicit QuicheIpPrefix(const QuicheIpAddress& address, uint8_t prefix_length); QuicheIpAddress address() const { return address_; } uint8_t prefix_length() const { return prefix_length_; } std::string ToString() const; QuicheIpPrefix(const QuicheIpPrefix& other) = default; QuicheIpPrefix& operator=(const QuicheIpPrefix& other) = default; QuicheIpPrefix& operator=(QuicheIpPrefix&& other) = default; QUICHE_EXPORT friend bool operator==(const QuicheIpPrefix& lhs, const QuicheIpPrefix& rhs); QUICHE_EXPORT friend bool operator!=(const QuicheIpPrefix& lhs, const QuicheIpPrefix& rhs); private: QuicheIpAddress address_; uint8_t prefix_length_; }; inline std::ostream& operator<<(std::ostream& os, const QuicheIpPrefix prefix) { os << prefix.ToString(); return os; } } #endif #include "quiche/common/quiche_ip_address.h" #include <algorithm> #include <cstdint> #include <cstring> #include <string> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_ip_address_family.h" namespace quiche { QuicheIpAddress QuicheIpAddress::Loopback4() { QuicheIpAddress result; result.family_ = IpAddressFamily::IP_V4; result.address_.bytes[0] = 127; result.address_.bytes[1] = 0; result.address_.bytes[2] = 0; result.address_.bytes[3] = 1; return result; } QuicheIpAddress QuicheIpAddress::Loopback6() { QuicheIpAddress result; result.family_ = IpAddressFamily::IP_V6; uint8_t* bytes = result.address_.bytes; memset(bytes, 0, 15); bytes[15] = 1; return result; } QuicheIpAddress QuicheIpAddress::Any4() { in_addr address; memset(&address, 0, sizeof(address)); return QuicheIpAddress(address); } QuicheIpAddress QuicheIpAddress::Any6() { in6_addr address; memset(&address, 0, sizeof(address)); return QuicheIpAddress(address); } QuicheIpAddress::QuicheIpAddress() : family_(IpAddressFamily::IP_UNSPEC) {} QuicheIpAddress::QuicheIpAddress(const in_addr& ipv4_address) : family_(IpAddressFamily::IP_V4) { address_.v4 = ipv4_address; } QuicheIpAddress::QuicheIpAddress(const in6_addr& ipv6_address) : family_(IpAddressFamily::IP_V6) { address_.v6 = ipv6_address; } bool operator==(QuicheIpAddress lhs, QuicheIpAddress rhs) { if (lhs.family_ != rhs.family_) { return false; } switch (lhs.family_) { case IpAddressFamily::IP_V4: return std::equal(lhs.address_.bytes, lhs.address_.bytes + QuicheIpAddress::kIPv4AddressSize, rhs.address_.bytes); case IpAddressFamily::IP_V6: return std::equal(lhs.address_.bytes, lhs.address_.bytes + QuicheIpAddress::kIPv6AddressSize, rhs.address_.bytes); case IpAddressFamily::IP_UNSPEC: return true; } QUICHE_BUG(quiche_bug_10126_2) << "Invalid IpAddressFamily " << static_cast<int32_t>(lhs.family_); return false; } bool operator!=(QuicheIpAddress lhs, QuicheIpAddress rhs) { return !(lhs == rhs); } bool QuicheIpAddress::IsInitialized() const { return family_ != IpAddressFamily::IP_UNSPEC; } IpAddressFamily QuicheIpAddress::address_family() const { return family_; } int QuicheIpAddress::AddressFamilyToInt() const { return ToPlatformAddressFamily(family_); } std::string QuicheIpAddress::ToPackedString() const { switch (family_) { case IpAddressFamily::IP_V4: return std::string(address_.chars, sizeof(address_.v4)); case IpAddressFamily::IP_V6: return std::string(address_.chars, sizeof(address_.v6)); case IpAddressFamily::IP_UNSPEC: return ""; } QUICHE_BUG(quiche_bug_10126_3) << "Invalid IpAddressFamily " << static_cast<int32_t>(family_); return ""; } std::string QuicheIpAddress::ToString() const { if (!IsInitialized()) { return ""; } char buffer[INET6_ADDRSTRLEN] = {0}; const char* result = inet_ntop(AddressFamilyToInt(), address_.bytes, buffer, sizeof(buffer)); QUICHE_BUG_IF(quiche_bug_10126_4, result == nullptr) << "Failed to convert an IP address to string"; return buffer; } static const uint8_t kMappedAddressPrefix[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, }; QuicheIpAddress QuicheIpAddress::Normalized() const { if (!IsIPv6()) { return *this; } if (!std::equal(std::begin(kMappedAddressPrefix), std::end(kMappedAddressPrefix), address_.bytes)) { return *this; } in_addr result; memcpy(&result, &address_.bytes[12], sizeof(result)); return QuicheIpAddress(result); } QuicheIpAddress QuicheIpAddress::DualStacked() const { if (!IsIPv4()) { return *this; } QuicheIpAddress result; result.family_ = IpAddressFamily::IP_V6; memcpy(result.address_.bytes, kMappedAddressPrefix, sizeof(kMappedAddressPrefix)); memcpy(result.address_.bytes + 12, address_.bytes, kIPv4AddressSize); return result; } bool QuicheIpAddress::FromPackedString(const char* data, size_t length) { switch (length) { case kIPv4AddressSize: family_ = IpAddressFamily::IP_V4; break; case kIPv6AddressSize: family_ = IpAddressFamily::IP_V6; break; default: return false; } memcpy(address_.chars, data, length); return true; } bool QuicheIpAddress::FromString(std::string str) { for (IpAddressFamily family : {IpAddressFamily::IP_V6, IpAddressFamily::IP_V4}) { int result = inet_pton(ToPlatformAddressFamily(family), str.c_str(), address_.bytes); if (result > 0) { family_ = family; return true; } } return false; } bool QuicheIpAddress::IsIPv4() const { return family_ == IpAddressFamily::IP_V4; } bool QuicheIpAddress::IsIPv6() const { return family_ == IpAddressFamily::IP_V6; } bool QuicheIpAddress::InSameSubnet(const QuicheIpAddress& other, int subnet_length) { if (!IsInitialized()) { QUICHE_BUG(quiche_bug_10126_5) << "Attempting to do subnet matching on undefined address"; return false; } if ((IsIPv4() && subnet_length > 32) || (IsIPv6() && subnet_length > 128)) { QUICHE_BUG(quiche_bug_10126_6) << "Subnet mask is out of bounds"; return false; } int bytes_to_check = subnet_length / 8; int bits_to_check = subnet_length % 8; const uint8_t* const lhs = address_.bytes; const uint8_t* const rhs = other.address_.bytes; if (!std::equal(lhs, lhs + bytes_to_check, rhs)) { return false; } if (bits_to_check == 0) { return true; } QUICHE_DCHECK_LT(static_cast<size_t>(bytes_to_check), sizeof(address_.bytes)); int mask = (~0u) << (8u - bits_to_check); return (lhs[bytes_to_check] & mask) == (rhs[bytes_to_check] & mask); } in_addr QuicheIpAddress::GetIPv4() const { QUICHE_DCHECK(IsIPv4()); return address_.v4; } in6_addr QuicheIpAddress::GetIPv6() const { QUICHE_DCHECK(IsIPv6()); return address_.v6; } QuicheIpPrefix::QuicheIpPrefix() : prefix_length_(0) {} QuicheIpPrefix::QuicheIpPrefix(const QuicheIpAddress& address) : address_(address) { if (address_.IsIPv6()) { prefix_length_ = QuicheIpAddress::kIPv6AddressSize * 8; } else if (address_.IsIPv4()) { prefix_length_ = QuicheIpAddress::kIPv4AddressSize * 8; } else { prefix_length_ = 0; } } QuicheIpPrefix::QuicheIpPrefix(const QuicheIpAddress& address, uint8_t prefix_length) : address_(address), prefix_length_(prefix_length) { QUICHE_DCHECK(prefix_length <= QuicheIpPrefix(address).prefix_length()) << "prefix_length cannot be longer than the size of the IP address"; } std::string QuicheIpPrefix::ToString() const { return absl::StrCat(address_.ToString(), "/", prefix_length_); } bool operator==(const QuicheIpPrefix& lhs, const QuicheIpPrefix& rhs) { return lhs.address_ == rhs.address_ && lhs.prefix_length_ == rhs.prefix_length_; } bool operator!=(const QuicheIpPrefix& lhs, const QuicheIpPrefix& rhs) { return !(lhs == rhs); } }
#include "quiche/common/quiche_ip_address.h" #include <cstdint> #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_ip_address_family.h" namespace quiche { namespace test { namespace { TEST(QuicheIpAddressTest, IPv4) { QuicheIpAddress ip_address; EXPECT_FALSE(ip_address.IsInitialized()); EXPECT_TRUE(ip_address.FromString("127.0.52.223")); EXPECT_TRUE(ip_address.IsInitialized()); EXPECT_EQ(IpAddressFamily::IP_V4, ip_address.address_family()); EXPECT_TRUE(ip_address.IsIPv4()); EXPECT_FALSE(ip_address.IsIPv6()); EXPECT_EQ("127.0.52.223", ip_address.ToString()); const in_addr v4_address = ip_address.GetIPv4(); const uint8_t* const v4_address_ptr = reinterpret_cast<const uint8_t*>(&v4_address); EXPECT_EQ(127u, *(v4_address_ptr + 0)); EXPECT_EQ(0u, *(v4_address_ptr + 1)); EXPECT_EQ(52u, *(v4_address_ptr + 2)); EXPECT_EQ(223u, *(v4_address_ptr + 3)); } TEST(QuicheIpAddressTest, IPv6) { QuicheIpAddress ip_address; EXPECT_FALSE(ip_address.IsInitialized()); EXPECT_TRUE(ip_address.FromString("fe80::1ff:fe23:4567")); EXPECT_TRUE(ip_address.IsInitialized()); EXPECT_EQ(IpAddressFamily::IP_V6, ip_address.address_family()); EXPECT_FALSE(ip_address.IsIPv4()); EXPECT_TRUE(ip_address.IsIPv6()); EXPECT_EQ("fe80::1ff:fe23:4567", ip_address.ToString()); const in6_addr v6_address = ip_address.GetIPv6(); const uint16_t* const v6_address_ptr = reinterpret_cast<const uint16_t*>(&v6_address); EXPECT_EQ(0x80feu, *(v6_address_ptr + 0)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 1)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 2)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 3)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 4)); EXPECT_EQ(0xff01u, *(v6_address_ptr + 5)); EXPECT_EQ(0x23feu, *(v6_address_ptr + 6)); EXPECT_EQ(0x6745u, *(v6_address_ptr + 7)); EXPECT_EQ(ip_address, ip_address.Normalized()); EXPECT_EQ(ip_address, ip_address.DualStacked()); } TEST(QuicheIpAddressTest, FromPackedString) { QuicheIpAddress loopback4, loopback6; const char loopback4_packed[] = "\x7f\0\0\x01"; const char loopback6_packed[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"; EXPECT_TRUE(loopback4.FromPackedString(loopback4_packed, 4)); EXPECT_TRUE(loopback6.FromPackedString(loopback6_packed, 16)); EXPECT_EQ(loopback4, QuicheIpAddress::Loopback4()); EXPECT_EQ(loopback6, QuicheIpAddress::Loopback6()); } TEST(QuicheIpAddressTest, MappedAddress) { QuicheIpAddress ipv4_address; QuicheIpAddress mapped_address; EXPECT_TRUE(ipv4_address.FromString("127.0.0.1")); EXPECT_TRUE(mapped_address.FromString("::ffff:7f00:1")); EXPECT_EQ(mapped_address, ipv4_address.DualStacked()); EXPECT_EQ(ipv4_address, mapped_address.Normalized()); } TEST(QuicheIpAddressTest, Subnets) { struct { const char* address1; const char* address2; int subnet_size; bool same_subnet; } test_cases[] = { {"127.0.0.1", "127.0.0.2", 24, true}, {"8.8.8.8", "127.0.0.1", 24, false}, {"8.8.8.8", "127.0.0.1", 16, false}, {"8.8.8.8", "127.0.0.1", 8, false}, {"8.8.8.8", "127.0.0.1", 2, false}, {"8.8.8.8", "127.0.0.1", 1, true}, {"127.0.0.1", "127.0.0.128", 24, true}, {"127.0.0.1", "127.0.0.128", 25, false}, {"127.0.0.1", "127.0.0.127", 25, true}, {"127.0.0.1", "127.0.0.0", 30, true}, {"127.0.0.1", "127.0.0.1", 30, true}, {"127.0.0.1", "127.0.0.2", 30, true}, {"127.0.0.1", "127.0.0.3", 30, true}, {"127.0.0.1", "127.0.0.4", 30, false}, {"127.0.0.1", "127.0.0.2", 31, false}, {"127.0.0.1", "127.0.0.0", 31, true}, {"::1", "fe80::1", 8, false}, {"::1", "fe80::1", 1, false}, {"::1", "fe80::1", 0, true}, {"fe80::1", "fe80::2", 126, true}, {"fe80::1", "fe80::2", 127, false}, }; for (const auto& test_case : test_cases) { QuicheIpAddress address1, address2; ASSERT_TRUE(address1.FromString(test_case.address1)); ASSERT_TRUE(address2.FromString(test_case.address2)); EXPECT_EQ(test_case.same_subnet, address1.InSameSubnet(address2, test_case.subnet_size)) << "Addresses: " << test_case.address1 << ", " << test_case.address2 << "; subnet: /" << test_case.subnet_size; } } TEST(QuicheIpAddress, LoopbackAddresses) { QuicheIpAddress loopback4; QuicheIpAddress loopback6; ASSERT_TRUE(loopback4.FromString("127.0.0.1")); ASSERT_TRUE(loopback6.FromString("::1")); EXPECT_EQ(loopback4, QuicheIpAddress::Loopback4()); EXPECT_EQ(loopback6, QuicheIpAddress::Loopback6()); } } } }
182
cpp
google/quiche
quiche_buffer_allocator
quiche/common/quiche_buffer_allocator.cc
quiche/common/quiche_buffer_allocator_test.cc
#ifndef QUICHE_COMMON_QUICHE_BUFFER_ALLOCATOR_H_ #define QUICHE_COMMON_QUICHE_BUFFER_ALLOCATOR_H_ #include <stddef.h> #include <memory> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_iovec.h" namespace quiche { class QUICHE_EXPORT QuicheBufferAllocator { public: virtual ~QuicheBufferAllocator() = default; virtual char* New(size_t size) = 0; virtual char* New(size_t size, bool flag_enable) = 0; virtual void Delete(char* buffer) = 0; virtual void MarkAllocatorIdle() {} }; class QUICHE_EXPORT QuicheBufferDeleter { public: explicit QuicheBufferDeleter(QuicheBufferAllocator* allocator) : allocator_(allocator) {} QuicheBufferAllocator* allocator() { return allocator_; } void operator()(char* buffer) { allocator_->Delete(buffer); } private: QuicheBufferAllocator* allocator_; }; using QuicheUniqueBufferPtr = std::unique_ptr<char[], QuicheBufferDeleter>; inline QuicheUniqueBufferPtr MakeUniqueBuffer(QuicheBufferAllocator* allocator, size_t size) { return QuicheUniqueBufferPtr(allocator->New(size), QuicheBufferDeleter(allocator)); } class QUICHE_EXPORT QuicheBuffer { public: QuicheBuffer() : buffer_(nullptr, QuicheBufferDeleter(nullptr)), size_(0) {} QuicheBuffer(QuicheBufferAllocator* allocator, size_t size) : buffer_(MakeUniqueBuffer(allocator, size)), size_(size) {} QuicheBuffer(QuicheUniqueBufferPtr buffer, size_t size) : buffer_(std::move(buffer)), size_(size) {} QuicheBuffer(QuicheBuffer&& other) : buffer_(std::move(other.buffer_)), size_(other.size_) { other.buffer_ = nullptr; other.size_ = 0; } QuicheBuffer& operator=(QuicheBuffer&& other) { buffer_ = std::move(other.buffer_); size_ = other.size_; other.buffer_ = nullptr; other.size_ = 0; return *this; } static QuicheBuffer Copy(QuicheBufferAllocator* allocator, absl::string_view data) { QuicheBuffer buffer(allocator, data.size()); memcpy(buffer.data(), data.data(), data.size()); return buffer; } static QuicheBuffer CopyFromIovec(QuicheBufferAllocator* allocator, const struct iovec* iov, int iov_count, size_t iov_offset, size_t buffer_length); const char* data() const { return buffer_.get(); } char* data() { return buffer_.get(); } size_t size() const { return size_; } bool empty() const { return size_ == 0; } absl::string_view AsStringView() const { return absl::string_view(data(), size()); } QuicheUniqueBufferPtr Release() { size_ = 0; return std::move(buffer_); } private: QuicheUniqueBufferPtr buffer_; size_t size_; }; } #endif #include "quiche/common/quiche_buffer_allocator.h" #include <algorithm> #include <cstring> #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_prefetch.h" namespace quiche { QuicheBuffer QuicheBuffer::CopyFromIovec(QuicheBufferAllocator* allocator, const struct iovec* iov, int iov_count, size_t iov_offset, size_t buffer_length) { if (buffer_length == 0) { return {}; } int iovnum = 0; while (iovnum < iov_count && iov_offset >= iov[iovnum].iov_len) { iov_offset -= iov[iovnum].iov_len; ++iovnum; } QUICHE_DCHECK_LE(iovnum, iov_count); if (iovnum >= iov_count) { QUICHE_BUG(quiche_bug_10839_1) << "iov_offset larger than iovec total size."; return {}; } QUICHE_DCHECK_LE(iov_offset, iov[iovnum].iov_len); const size_t iov_available = iov[iovnum].iov_len - iov_offset; size_t copy_len = std::min(buffer_length, iov_available); if (copy_len == iov_available && iovnum + 1 < iov_count) { char* next_base = static_cast<char*>(iov[iovnum + 1].iov_base); quiche::QuichePrefetchT0(next_base); if (iov[iovnum + 1].iov_len >= 64) { quiche::QuichePrefetchT0(next_base + ABSL_CACHELINE_SIZE); } } QuicheBuffer buffer(allocator, buffer_length); const char* src = static_cast<char*>(iov[iovnum].iov_base) + iov_offset; char* dst = buffer.data(); while (true) { memcpy(dst, src, copy_len); buffer_length -= copy_len; dst += copy_len; if (buffer_length == 0 || ++iovnum >= iov_count) { break; } src = static_cast<char*>(iov[iovnum].iov_base); copy_len = std::min(buffer_length, iov[iovnum].iov_len); } QUICHE_BUG_IF(quiche_bug_10839_2, buffer_length > 0) << "iov_offset + buffer_length larger than iovec total size."; return buffer; } }
#include "quiche/common/quiche_buffer_allocator.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { TEST(QuicheBuffer, CopyFromEmpty) { SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::Copy(&allocator, ""); EXPECT_TRUE(buffer.empty()); } TEST(QuicheBuffer, Copy) { SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::Copy(&allocator, "foobar"); EXPECT_EQ("foobar", buffer.AsStringView()); } TEST(QuicheBuffer, CopyFromIovecZeroBytes) { const int buffer_length = 0; SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::CopyFromIovec( &allocator, nullptr, 0, 0, buffer_length); EXPECT_TRUE(buffer.empty()); constexpr absl::string_view kData("foobar"); iovec iov = MakeIOVector(kData); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 0, buffer_length); EXPECT_TRUE(buffer.empty()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 3, buffer_length); EXPECT_TRUE(buffer.empty()); } TEST(QuicheBuffer, CopyFromIovecSimple) { constexpr absl::string_view kData("foobar"); iovec iov = MakeIOVector(kData); SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 0, 6); EXPECT_EQ("foobar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 0, 3); EXPECT_EQ("foo", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 3, 3); EXPECT_EQ("bar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 1, 4); EXPECT_EQ("ooba", buffer.AsStringView()); } TEST(QuicheBuffer, CopyFromIovecMultiple) { constexpr absl::string_view kData1("foo"); constexpr absl::string_view kData2("bar"); iovec iov[] = {MakeIOVector(kData1), MakeIOVector(kData2)}; SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 0, 6); EXPECT_EQ("foobar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 0, 3); EXPECT_EQ("foo", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 3, 3); EXPECT_EQ("bar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 1, 4); EXPECT_EQ("ooba", buffer.AsStringView()); } TEST(QuicheBuffer, CopyFromIovecOffsetTooLarge) { constexpr absl::string_view kData1("foo"); constexpr absl::string_view kData2("bar"); iovec iov[] = {MakeIOVector(kData1), MakeIOVector(kData2)}; SimpleBufferAllocator allocator; EXPECT_QUICHE_BUG( QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 10, 6), "iov_offset larger than iovec total size"); } TEST(QuicheBuffer, CopyFromIovecTooManyBytesRequested) { constexpr absl::string_view kData1("foo"); constexpr absl::string_view kData2("bar"); iovec iov[] = {MakeIOVector(kData1), MakeIOVector(kData2)}; SimpleBufferAllocator allocator; EXPECT_QUICHE_BUG( QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 2, 10), R"(iov_offset \+ buffer_length larger than iovec total size)"); } } } }
183
cpp
google/quiche
capsule
quiche/common/capsule.cc
quiche/common/capsule_test.cc
#ifndef QUICHE_COMMON_CAPSULE_H_ #define QUICHE_COMMON_CAPSULE_H_ #include <cstdint> #include <optional> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/web_transport/web_transport.h" namespace quiche { enum class CapsuleType : uint64_t { DATAGRAM = 0x00, LEGACY_DATAGRAM = 0xff37a0, LEGACY_DATAGRAM_WITHOUT_CONTEXT = 0xff37a5, CLOSE_WEBTRANSPORT_SESSION = 0x2843, DRAIN_WEBTRANSPORT_SESSION = 0x78ae, ADDRESS_ASSIGN = 0x1ECA6A00, ADDRESS_REQUEST = 0x1ECA6A01, ROUTE_ADVERTISEMENT = 0x1ECA6A02, WT_RESET_STREAM = 0x190b4d39, WT_STOP_SENDING = 0x190b4d3a, WT_STREAM = 0x190b4d3b, WT_STREAM_WITH_FIN = 0x190b4d3c, WT_MAX_STREAM_DATA = 0x190b4d3e, WT_MAX_STREAMS_BIDI = 0x190b4d3f, WT_MAX_STREAMS_UNIDI = 0x190b4d40, }; QUICHE_EXPORT std::string CapsuleTypeToString(CapsuleType capsule_type); QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const CapsuleType& capsule_type); struct QUICHE_EXPORT DatagramCapsule { absl::string_view http_datagram_payload; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::DATAGRAM; } bool operator==(const DatagramCapsule& other) const { return http_datagram_payload == other.http_datagram_payload; } }; struct QUICHE_EXPORT LegacyDatagramCapsule { absl::string_view http_datagram_payload; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::LEGACY_DATAGRAM; } bool operator==(const LegacyDatagramCapsule& other) const { return http_datagram_payload == other.http_datagram_payload; } }; struct QUICHE_EXPORT LegacyDatagramWithoutContextCapsule { absl::string_view http_datagram_payload; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT; } bool operator==(const LegacyDatagramWithoutContextCapsule& other) const { return http_datagram_payload == other.http_datagram_payload; } }; struct QUICHE_EXPORT CloseWebTransportSessionCapsule { webtransport::SessionErrorCode error_code; absl::string_view error_message; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::CLOSE_WEBTRANSPORT_SESSION; } bool operator==(const CloseWebTransportSessionCapsule& other) const { return error_code == other.error_code && error_message == other.error_message; } }; struct QUICHE_EXPORT DrainWebTransportSessionCapsule { std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::DRAIN_WEBTRANSPORT_SESSION; } bool operator==(const DrainWebTransportSessionCapsule&) const { return true; } }; struct QUICHE_EXPORT PrefixWithId { uint64_t request_id; quiche::QuicheIpPrefix ip_prefix; bool operator==(const PrefixWithId& other) const; }; struct QUICHE_EXPORT IpAddressRange { quiche::QuicheIpAddress start_ip_address; quiche::QuicheIpAddress end_ip_address; uint8_t ip_protocol; bool operator==(const IpAddressRange& other) const; }; struct QUICHE_EXPORT AddressAssignCapsule { std::vector<PrefixWithId> assigned_addresses; bool operator==(const AddressAssignCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::ADDRESS_ASSIGN; } }; struct QUICHE_EXPORT AddressRequestCapsule { std::vector<PrefixWithId> requested_addresses; bool operator==(const AddressRequestCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::ADDRESS_REQUEST; } }; struct QUICHE_EXPORT RouteAdvertisementCapsule { std::vector<IpAddressRange> ip_address_ranges; bool operator==(const RouteAdvertisementCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::ROUTE_ADVERTISEMENT; } }; struct QUICHE_EXPORT UnknownCapsule { uint64_t type; absl::string_view payload; std::string ToString() const; CapsuleType capsule_type() const { return static_cast<CapsuleType>(type); } bool operator==(const UnknownCapsule& other) const { return type == other.type && payload == other.payload; } }; struct QUICHE_EXPORT WebTransportStreamDataCapsule { webtransport::StreamId stream_id; absl::string_view data; bool fin; bool operator==(const WebTransportStreamDataCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return fin ? CapsuleType::WT_STREAM_WITH_FIN : CapsuleType::WT_STREAM; } }; struct QUICHE_EXPORT WebTransportResetStreamCapsule { webtransport::StreamId stream_id; uint64_t error_code; bool operator==(const WebTransportResetStreamCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::WT_RESET_STREAM; } }; struct QUICHE_EXPORT WebTransportStopSendingCapsule { webtransport::StreamId stream_id; uint64_t error_code; bool operator==(const WebTransportStopSendingCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::WT_STOP_SENDING; } }; struct QUICHE_EXPORT WebTransportMaxStreamDataCapsule { webtransport::StreamId stream_id; uint64_t max_stream_data; bool operator==(const WebTransportMaxStreamDataCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return CapsuleType::WT_MAX_STREAM_DATA; } }; struct QUICHE_EXPORT WebTransportMaxStreamsCapsule { webtransport::StreamType stream_type; uint64_t max_stream_count; bool operator==(const WebTransportMaxStreamsCapsule& other) const; std::string ToString() const; CapsuleType capsule_type() const { return stream_type == webtransport::StreamType::kBidirectional ? CapsuleType::WT_MAX_STREAMS_BIDI : CapsuleType::WT_MAX_STREAMS_UNIDI; } }; class QUICHE_EXPORT Capsule { public: static Capsule Datagram( absl::string_view http_datagram_payload = absl::string_view()); static Capsule LegacyDatagram( absl::string_view http_datagram_payload = absl::string_view()); static Capsule LegacyDatagramWithoutContext( absl::string_view http_datagram_payload = absl::string_view()); static Capsule CloseWebTransportSession( webtransport::SessionErrorCode error_code = 0, absl::string_view error_message = ""); static Capsule AddressRequest(); static Capsule AddressAssign(); static Capsule RouteAdvertisement(); static Capsule Unknown( uint64_t capsule_type, absl::string_view unknown_capsule_data = absl::string_view()); template <typename CapsuleStruct> explicit Capsule(CapsuleStruct capsule) : capsule_(std::move(capsule)) {} bool operator==(const Capsule& other) const; std::string ToString() const; friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const Capsule& capsule); CapsuleType capsule_type() const { return absl::visit( [](const auto& capsule) { return capsule.capsule_type(); }, capsule_); } DatagramCapsule& datagram_capsule() { return absl::get<DatagramCapsule>(capsule_); } const DatagramCapsule& datagram_capsule() const { return absl::get<DatagramCapsule>(capsule_); } LegacyDatagramCapsule& legacy_datagram_capsule() { return absl::get<LegacyDatagramCapsule>(capsule_); } const LegacyDatagramCapsule& legacy_datagram_capsule() const { return absl::get<LegacyDatagramCapsule>(capsule_); } LegacyDatagramWithoutContextCapsule& legacy_datagram_without_context_capsule() { return absl::get<LegacyDatagramWithoutContextCapsule>(capsule_); } const LegacyDatagramWithoutContextCapsule& legacy_datagram_without_context_capsule() const { return absl::get<LegacyDatagramWithoutContextCapsule>(capsule_); } CloseWebTransportSessionCapsule& close_web_transport_session_capsule() { return absl::get<CloseWebTransportSessionCapsule>(capsule_); } const CloseWebTransportSessionCapsule& close_web_transport_session_capsule() const { return absl::get<CloseWebTransportSessionCapsule>(capsule_); } AddressRequestCapsule& address_request_capsule() { return absl::get<AddressRequestCapsule>(capsule_); } const AddressRequestCapsule& address_request_capsule() const { return absl::get<AddressRequestCapsule>(capsule_); } AddressAssignCapsule& address_assign_capsule() { return absl::get<AddressAssignCapsule>(capsule_); } const AddressAssignCapsule& address_assign_capsule() const { return absl::get<AddressAssignCapsule>(capsule_); } RouteAdvertisementCapsule& route_advertisement_capsule() { return absl::get<RouteAdvertisementCapsule>(capsule_); } const RouteAdvertisementCapsule& route_advertisement_capsule() const { return absl::get<RouteAdvertisementCapsule>(capsule_); } WebTransportStreamDataCapsule& web_transport_stream_data() { return absl::get<WebTransportStreamDataCapsule>(capsule_); } const WebTransportStreamDataCapsule& web_transport_stream_data() const { return absl::get<WebTransportStreamDataCapsule>(capsule_); } WebTransportResetStreamCapsule& web_transport_reset_stream() { return absl::get<WebTransportResetStreamCapsule>(capsule_); } const WebTransportResetStreamCapsule& web_transport_reset_stream() const { return absl::get<WebTransportResetStreamCapsule>(capsule_); } WebTransportStopSendingCapsule& web_transport_stop_sending() { return absl::get<WebTransportStopSendingCapsule>(capsule_); } const WebTransportStopSendingCapsule& web_transport_stop_sending() const { return absl::get<WebTransportStopSendingCapsule>(capsule_); } WebTransportMaxStreamDataCapsule& web_transport_max_stream_data() { return absl::get<WebTransportMaxStreamDataCapsule>(capsule_); } const WebTransportMaxStreamDataCapsule& web_transport_max_stream_data() const { return absl::get<WebTransportMaxStreamDataCapsule>(capsule_); } WebTransportMaxStreamsCapsule& web_transport_max_streams() { return absl::get<WebTransportMaxStreamsCapsule>(capsule_); } const WebTransportMaxStreamsCapsule& web_transport_max_streams() const { return absl::get<WebTransportMaxStreamsCapsule>(capsule_); } UnknownCapsule& unknown_capsule() { return absl::get<UnknownCapsule>(capsule_); } const UnknownCapsule& unknown_capsule() const { return absl::get<UnknownCapsule>(capsule_); } private: absl::variant<DatagramCapsule, LegacyDatagramCapsule, LegacyDatagramWithoutContextCapsule, CloseWebTransportSessionCapsule, DrainWebTransportSessionCapsule, AddressRequestCapsule, AddressAssignCapsule, RouteAdvertisementCapsule, WebTransportStreamDataCapsule, WebTransportResetStreamCapsule, WebTransportStopSendingCapsule, WebTransportMaxStreamsCapsule, WebTransportMaxStreamDataCapsule, UnknownCapsule> capsule_; }; namespace test { class CapsuleParserPeer; } class QUICHE_EXPORT CapsuleParser { public: class QUICHE_EXPORT Visitor { public: virtual ~Visitor() {} virtual bool OnCapsule(const Capsule& capsule) = 0; virtual void OnCapsuleParseFailure(absl::string_view error_message) = 0; }; explicit CapsuleParser(Visitor* visitor); bool IngestCapsuleFragment(absl::string_view capsule_fragment); void ErrorIfThereIsRemainingBufferedData(); friend class test::CapsuleParserPeer; private: absl::StatusOr<size_t> AttemptParseCapsule(); void ReportParseFailure(absl::string_view error_message); bool parsing_error_occurred_ = false; Visitor* visitor_; std::string buffered_data_; }; QUICHE_EXPORT quiche::QuicheBuffer SerializeCapsule( const Capsule& capsule, quiche::QuicheBufferAllocator* allocator); QUICHE_EXPORT QuicheBuffer SerializeDatagramCapsuleHeader( uint64_t datagram_size, QuicheBufferAllocator* allocator); QUICHE_EXPORT QuicheBuffer SerializeWebTransportStreamCapsuleHeader( webtransport::StreamId stream_id, bool fin, uint64_t write_size, QuicheBufferAllocator* allocator); } #endif #include "quiche/common/capsule.h" #include <cstddef> #include <cstdint> #include <limits> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/quiche_status_utils.h" #include "quiche/common/wire_serialization.h" #include "quiche/web_transport/web_transport.h" namespace quiche { std::string CapsuleTypeToString(CapsuleType capsule_type) { switch (capsule_type) { case CapsuleType::DATAGRAM: return "DATAGRAM"; case CapsuleType::LEGACY_DATAGRAM: return "LEGACY_DATAGRAM"; case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT: return "LEGACY_DATAGRAM_WITHOUT_CONTEXT"; case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: return "CLOSE_WEBTRANSPORT_SESSION"; case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: return "DRAIN_WEBTRANSPORT_SESSION"; case CapsuleType::ADDRESS_REQUEST: return "ADDRESS_REQUEST"; case CapsuleType::ADDRESS_ASSIGN: return "ADDRESS_ASSIGN"; case CapsuleType::ROUTE_ADVERTISEMENT: return "ROUTE_ADVERTISEMENT"; case CapsuleType::WT_STREAM: return "WT_STREAM"; case CapsuleType::WT_STREAM_WITH_FIN: return "WT_STREAM_WITH_FIN"; case CapsuleType::WT_RESET_STREAM: return "WT_RESET_STREAM"; case CapsuleType::WT_STOP_SENDING: return "WT_STOP_SENDING"; case CapsuleType::WT_MAX_STREAM_DATA: return "WT_MAX_STREAM_DATA"; case CapsuleType::WT_MAX_STREAMS_BIDI: return "WT_MAX_STREAMS_BIDI"; case CapsuleType::WT_MAX_STREAMS_UNIDI: return "WT_MAX_STREAMS_UNIDI"; } return absl::StrCat("Unknown(", static_cast<uint64_t>(capsule_type), ")"); } std::ostream& operator<<(std::ostream& os, const CapsuleType& capsule_type) { os << CapsuleTypeToString(capsule_type); return os; } Capsule Capsule::Datagram(absl::string_view http_datagram_payload) { return Capsule(DatagramCapsule{http_datagram_payload}); } Capsule Capsule::LegacyDatagram(absl::string_view http_datagram_payload) { return Capsule(LegacyDatagramCapsule{http_datagram_payload}); } Capsule Capsule::LegacyDatagramWithoutContext( absl::string_view http_datagram_payload) { return Capsule(LegacyDatagramWithoutContextCapsule{http_datagram_payload}); } Capsule Capsule::CloseWebTransportSession( webtransport::SessionErrorCode error_code, absl::string_view error_message) { return Capsule(CloseWebTransportSessionCapsule({error_code, error_message})); } Capsule Capsule::AddressRequest() { return Capsule(AddressRequestCapsule()); } Capsule Capsule::AddressAssign() { return Capsule(AddressAssignCapsule()); } Capsule Capsule::RouteAdvertisement() { return Capsule(RouteAdvertisementCapsule()); } Capsule Capsule::Unknown(uint64_t capsule_type, absl::string_view unknown_capsule_data) { return Capsule(UnknownCapsule{capsule_type, unknown_capsule_data}); } bool Capsule::operator==(const Capsule& other) const { return capsule_ == other.capsule_; } std::string DatagramCapsule::ToString() const { return absl::StrCat("DATAGRAM[", absl::BytesToHexString(http_datagram_payload), "]"); } std::string LegacyDatagramCapsule::ToString() const { return absl::StrCat("LEGACY_DATAGRAM[", absl::BytesToHexString(http_datagram_payload), "]"); } std::string LegacyDatagramWithoutContextCapsule::ToString() const { return absl::StrCat("LEGACY_DATAGRAM_WITHOUT_CONTEXT[", absl::BytesToHexString(http_datagram_payload), "]"); } std::string CloseWebTransportSessionCapsule::ToString() const { return absl::StrCat("CLOSE_WEBTRANSPORT_SESSION(error_code=", error_code, ",error_message=\"", error_message, "\")"); } std::string DrainWebTransportSessionCapsule::ToString() const { return "DRAIN_WEBTRANSPORT_SESSION()"; } std::string AddressRequestCapsule::ToString() const { std::string rv = "ADDRESS_REQUEST["; for (auto requested_address : requested_addresses) { absl::StrAppend(&rv, "(", requested_address.request_id, "-", requested_address.ip_prefix.ToString(), ")"); } absl::StrAppend(&rv, "]"); return rv; } std::string AddressAssignCapsule::ToString() const { std::string rv = "ADDRESS_ASSIGN["; for (auto assigned_address : assigned_addresses) { absl::StrAppend(&rv, "(", assigned_address.request_id, "-", assigned_address.ip_prefix.ToString(), ")"); } absl::StrAppend(&rv, "]"); return rv; } std::string RouteAdvertisementCapsule::ToString() const { std::string rv = "ROUTE_ADVERTISEMENT["; for (auto ip_address_range : ip_address_ranges) { absl::StrAppend(&rv, "(", ip_address_range.start_ip_address.ToString(), "-", ip_address_range.end_ip_address.ToString(), "-", static_cast<int>(ip_address_range.ip_protocol), ")"); } absl::StrAppend(&rv, "]"); return rv; } std::string UnknownCapsule::ToString() const { return absl::StrCat("Unknown(", type, ") [", absl::BytesToHexString(payload), "]"); } std::string WebTransportStreamDataCapsule::ToString() const { return absl::StrCat(CapsuleTypeToString(capsule_type()), " [stream_id=", stream_id, ", data=", absl::BytesToHexString(data), "]"); } std::string WebTransportResetStreamCapsule::ToString() const { return absl::StrCat("WT_RESET_STREAM(stream_id=", stream_id, ", error_code=", error_code, ")"); } std::string WebTransportStopSendingCapsule::ToString() const { return absl::StrCat("WT_STOP_SENDING(stream_id=", stream_id, ", error_code=", error_code, ")"); } std::string WebTransportMaxStreamDataCapsule::ToString() const { return absl::StrCat("WT_MAX_STREAM_DATA (stream_id=", stream_id, ", max_stream_data=", max_stream_data, ")"); } std::string WebTransportMaxStreamsCapsule::ToString() const { return absl::StrCat(CapsuleTypeToString(capsule_type()), " (max_streams=", max_stream_count, ")"); } std::string Capsule::ToString() const { return absl::visit([](const auto& capsule) { return capsule.ToString(); }, capsule_); } std::ostream& operator<<(std::ostream& os, const Capsule& capsule) { os << capsule.ToString(); return os; } CapsuleParser::CapsuleParser(Visitor* visitor) : visitor_(visitor) { QUICHE_DCHECK_NE(visitor_, nullptr); } class WirePrefixWithId { public: using DataType = PrefixWithId; WirePrefixWithId(const PrefixWithId& prefix) : prefix_(prefix) {} size_t GetLengthOnWire() { return ComputeLengthOnWire( WireVarInt62(prefix_.request_id), WireUint8(prefix_.ip_prefix.address().IsIPv4() ? 4 : 6), WireBytes(prefix_.ip_prefix.address().ToPackedString()), WireUint8(prefix_.ip_prefix.prefix_length())); } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) { return AppendToStatus( quiche::SerializeIntoWriter( writer, WireVarInt62(prefix_.request_id), WireUint8(prefix_.ip_prefix.address().IsIPv4() ? 4 : 6), WireBytes(prefix_.ip_prefix.address().ToPackedString()), WireUint8(prefix_.ip_prefix.prefix_length())), " while serializing a PrefixWithId"); } private: const PrefixWithId& prefix_; }; class WireIpAddressRange { public: using DataType = IpAddressRange; explicit WireIpAddressRange(const IpAddressRange& range) : range_(range) {} size_t GetLengthOnWire() { return ComputeLengthOnWire( WireUint8(range_.start_ip_address.IsIPv4() ? 4 : 6), WireBytes(range_.start_ip_address.ToPackedString()), WireBytes(range_.end_ip_address.ToPackedString()), WireUint8(range_.ip_protocol)); } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) { return AppendToStatus( ::quiche::SerializeIntoWriter( writer, WireUint8(range_.start_ip_address.IsIPv4() ? 4 : 6), WireBytes(range_.start_ip_address.ToPackedString()), WireBytes(range_.end_ip_address.ToPackedString()), WireUint8(range_.ip_protocol)), " while serializing an IpAddressRange"); } private: const IpAddressRange& range_; }; template <typename... T> absl::StatusOr<quiche::QuicheBuffer> SerializeCapsuleFields( CapsuleType type, QuicheBufferAllocator* allocator, T... fields) { size_t capsule_payload_size = ComputeLengthOnWire(fields...); return SerializeIntoBuffer(allocator, WireVarInt62(type), WireVarInt62(capsule_payload_size), fields...); } absl::StatusOr<quiche::QuicheBuffer> SerializeCapsuleWithStatus( const Capsule& capsule, quiche::QuicheBufferAllocator* allocator) { switch (capsule.capsule_type()) { case CapsuleType::DATAGRAM: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.datagram_capsule().http_datagram_payload)); case CapsuleType::LEGACY_DATAGRAM: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.legacy_datagram_capsule().http_datagram_payload)); case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.legacy_datagram_without_context_capsule() .http_datagram_payload)); case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireUint32(capsule.close_web_transport_session_capsule().error_code), WireBytes( capsule.close_web_transport_session_capsule().error_message)); case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: return SerializeCapsuleFields(capsule.capsule_type(), allocator); case CapsuleType::ADDRESS_REQUEST: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireSpan<WirePrefixWithId>(absl::MakeConstSpan( capsule.address_request_capsule().requested_addresses))); case CapsuleType::ADDRESS_ASSIGN: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireSpan<WirePrefixWithId>(absl::MakeConstSpan( capsule.address_assign_capsule().assigned_addresses))); case CapsuleType::ROUTE_ADVERTISEMENT: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireSpan<WireIpAddressRange>(absl::MakeConstSpan( capsule.route_advertisement_capsule().ip_address_ranges))); case CapsuleType::WT_STREAM: case CapsuleType::WT_STREAM_WITH_FIN: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_stream_data().stream_id), WireBytes(capsule.web_transport_stream_data().data)); case CapsuleType::WT_RESET_STREAM: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_reset_stream().stream_id), WireVarInt62(capsule.web_transport_reset_stream().error_code)); case CapsuleType::WT_STOP_SENDING: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_stop_sending().stream_id), WireVarInt62(capsule.web_transport_stop_sending().error_code)); case CapsuleType::WT_MAX_STREAM_DATA: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_max_stream_data().stream_id), WireVarInt62( capsule.web_transport_max_stream_data().max_stream_data)); case CapsuleType::WT_MAX_STREAMS_BIDI: case CapsuleType::WT_MAX_STREAMS_UNIDI: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_max_streams().max_stream_count)); default: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.unknown_capsule().payload)); } } QuicheBuffer SerializeDatagramCapsuleHeader(uint64_t datagram_size, QuicheBufferAllocator* allocator) { absl::StatusOr<QuicheBuffer> buffer = SerializeIntoBuffer(allocator, WireVarInt62(CapsuleType::DATAGRAM), WireVarInt62(datagram_size)); if (!buffer.ok()) { return QuicheBuffer(); } return *std::move(buffer); } QUICHE_EXPORT QuicheBuffer SerializeWebTransportStreamCapsuleHeader( webtransport::StreamId stream_id, bool fin, uint64_t write_size, QuicheBufferAllocator* allocator) { absl::StatusOr<QuicheBuffer> buffer = SerializeIntoBuffer( allocator, WireVarInt62(fin ? CapsuleType::WT_STREAM_WITH_FIN : CapsuleType::WT_STREAM), WireVarInt62(write_size + QuicheDataWriter::GetVarInt62Len(stream_id)), WireVarInt62(stream_id)); if (!buffer.ok()) { return QuicheBuffer(); } return *std::move(buffer); } QuicheBuffer SerializeCapsule(const Capsule& capsule, quiche::QuicheBufferAllocator* allocator) { absl::StatusOr<QuicheBuffer> serialized = SerializeCapsuleWithStatus(capsule, allocator); if (!serialized.ok()) { QUICHE_BUG(capsule_serialization_failed) << "Failed to serialize the following capsule:\n" << capsule << "Serialization error: " << serialized.status(); return QuicheBuffer(); } return *std::move(serialized); } bool CapsuleParser::IngestCapsuleFragment(absl::string_view capsule_fragment) { if (parsing_error_occurred_) { return false; } absl::StrAppend(&buffered_data_, capsule_fragment); while (true) { const absl::StatusOr<size_t> buffered_data_read = AttemptParseCapsule(); if (!buffered_data_read.ok()) { ReportParseFailure(buffered_data_read.status().message()); buffered_data_.clear(); return false; } if (*buffered_data_read == 0) { break; } buffered_data_.erase(0, *buffered_data_read); } static constexpr size_t kMaxCapsuleBufferSize = 1024 * 1024; if (buffered_data_.size() > kMaxCapsuleBufferSize) { buffered_data_.clear(); ReportParseFailure("Refusing to buffer too much capsule data"); return false; } return true; } namespace { absl::Status ReadWebTransportStreamId(QuicheDataReader& reader, webtransport::StreamId& id) { uint64_t raw_id; if (!reader.ReadVarInt62(&raw_id)) { return absl::InvalidArgumentError("Failed to read WebTransport Stream ID"); } if (raw_id > std::numeric_limits<uint32_t>::max()) { return absl::InvalidArgumentError("Stream ID does not fit into a uint32_t"); } id = static_cast<webtransport::StreamId>(raw_id); return absl::OkStatus(); } absl::StatusOr<Capsule> ParseCapsulePayload(QuicheDataReader& reader, CapsuleType type) { switch (type) { case CapsuleType::DATAGRAM: return Capsule::Datagram(reader.ReadRemainingPayload()); case CapsuleType::LEGACY_DATAGRAM: return Capsule::LegacyDatagram(reader.ReadRemainingPayload()); case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT: return Capsule::LegacyDatagramWithoutContext( reader.ReadRemainingPayload()); case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: { CloseWebTransportSessionCapsule capsule; if (!reader.ReadUInt32(&capsule.error_code)) { return absl::InvalidArgumentError( "Unable to parse capsule CLOSE_WEBTRANSPORT_SESSION error code"); } capsule.error_message = reader.ReadRemainingPayload(); return Capsule(std::move(capsule)); } case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: return Capsule(DrainWebTransportSessionCapsule()); case CapsuleType::ADDRESS_REQUEST: { AddressRequestCapsule capsule; while (!reader.IsDoneReading()) { PrefixWithId requested_address; if (!reader.ReadVarInt62(&requested_address.request_id)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_REQUEST request ID"); } uint8_t address_family; if (!reader.ReadUInt8(&address_family)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_REQUEST family"); } if (address_family != 4 && address_family != 6) { return absl::InvalidArgumentError("Bad ADDRESS_REQUEST family"); }
#include "quiche/common/capsule.h" #include <cstddef> #include <deque> #include <string> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/web_transport/web_transport.h" using ::testing::_; using ::testing::InSequence; using ::testing::Return; using ::webtransport::StreamType; namespace quiche { namespace test { class CapsuleParserPeer { public: static std::string* buffered_data(CapsuleParser* capsule_parser) { return &capsule_parser->buffered_data_; } }; namespace { class MockCapsuleParserVisitor : public CapsuleParser::Visitor { public: MockCapsuleParserVisitor() { ON_CALL(*this, OnCapsule(_)).WillByDefault(Return(true)); } ~MockCapsuleParserVisitor() override = default; MOCK_METHOD(bool, OnCapsule, (const Capsule& capsule), (override)); MOCK_METHOD(void, OnCapsuleParseFailure, (absl::string_view error_message), (override)); }; class CapsuleTest : public QuicheTest { public: CapsuleTest() : capsule_parser_(&visitor_) {} void ValidateParserIsEmpty() { EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); EXPECT_CALL(visitor_, OnCapsuleParseFailure(_)).Times(0); capsule_parser_.ErrorIfThereIsRemainingBufferedData(); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } void TestSerialization(const Capsule& capsule, const std::string& expected_bytes) { quiche::QuicheBuffer serialized_capsule = SerializeCapsule(capsule, SimpleBufferAllocator::Get()); quiche::test::CompareCharArraysWithHexError( "Serialized capsule", serialized_capsule.data(), serialized_capsule.size(), expected_bytes.data(), expected_bytes.size()); } ::testing::StrictMock<MockCapsuleParserVisitor> visitor_; CapsuleParser capsule_parser_; }; TEST_F(CapsuleTest, DatagramCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); Capsule expected_capsule = Capsule::Datagram(datagram_payload); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, DatagramCapsuleViaHeader) { std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); quiche::QuicheBuffer expected_capsule = SerializeCapsule( Capsule::Datagram(datagram_payload), SimpleBufferAllocator::Get()); quiche::QuicheBuffer actual_header = SerializeDatagramCapsuleHeader( datagram_payload.size(), SimpleBufferAllocator::Get()); EXPECT_EQ(expected_capsule.AsStringView(), absl::StrCat(actual_header.AsStringView(), datagram_payload)); } TEST_F(CapsuleTest, LegacyDatagramCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("80ff37a0" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); Capsule expected_capsule = Capsule::LegacyDatagram(datagram_payload); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, LegacyDatagramWithoutContextCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "80ff37a5" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); Capsule expected_capsule = Capsule::LegacyDatagramWithoutContext(datagram_payload); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, CloseWebTransportStreamCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("6843" "09" "00001234" "68656c6c6f", &capsule_fragment)); Capsule expected_capsule = Capsule::CloseWebTransportSession( 0x1234, "hello"); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, DrainWebTransportStreamCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "800078ae" "00", &capsule_fragment)); Capsule expected_capsule = Capsule(DrainWebTransportSessionCapsule()); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, AddressAssignCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "9ECA6A00" "1A" "00" "04" "C000022A" "1F" "01" "06" "20010db8123456780000000000000000" "40", &capsule_fragment)); Capsule expected_capsule = Capsule::AddressAssign(); quiche::QuicheIpAddress ip_address1; ip_address1.FromString("192.0.2.42"); PrefixWithId assigned_address1; assigned_address1.request_id = 0; assigned_address1.ip_prefix = quiche::QuicheIpPrefix(ip_address1, 31); expected_capsule.address_assign_capsule().assigned_addresses.push_back( assigned_address1); quiche::QuicheIpAddress ip_address2; ip_address2.FromString("2001:db8:1234:5678::"); PrefixWithId assigned_address2; assigned_address2.request_id = 1; assigned_address2.ip_prefix = quiche::QuicheIpPrefix(ip_address2, 64); expected_capsule.address_assign_capsule().assigned_addresses.push_back( assigned_address2); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, AddressRequestCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "9ECA6A01" "1A" "00" "04" "C000022A" "1F" "01" "06" "20010db8123456780000000000000000" "40", &capsule_fragment)); Capsule expected_capsule = Capsule::AddressRequest(); quiche::QuicheIpAddress ip_address1; ip_address1.FromString("192.0.2.42"); PrefixWithId requested_address1; requested_address1.request_id = 0; requested_address1.ip_prefix = quiche::QuicheIpPrefix(ip_address1, 31); expected_capsule.address_request_capsule().requested_addresses.push_back( requested_address1); quiche::QuicheIpAddress ip_address2; ip_address2.FromString("2001:db8:1234:5678::"); PrefixWithId requested_address2; requested_address2.request_id = 1; requested_address2.ip_prefix = quiche::QuicheIpPrefix(ip_address2, 64); expected_capsule.address_request_capsule().requested_addresses.push_back( requested_address2); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, RouteAdvertisementCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "9ECA6A02" "2C" "04" "C0000218" "C000022A" "00" "06" "00000000000000000000000000000000" "ffffffffffffffffffffffffffffffff" "01", &capsule_fragment)); Capsule expected_capsule = Capsule::RouteAdvertisement(); IpAddressRange ip_address_range1; ip_address_range1.start_ip_address.FromString("192.0.2.24"); ip_address_range1.end_ip_address.FromString("192.0.2.42"); ip_address_range1.ip_protocol = 0; expected_capsule.route_advertisement_capsule().ip_address_ranges.push_back( ip_address_range1); IpAddressRange ip_address_range2; ip_address_range2.start_ip_address.FromString("::"); ip_address_range2.end_ip_address.FromString( "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); ip_address_range2.ip_protocol = 1; expected_capsule.route_advertisement_capsule().ip_address_ranges.push_back( ip_address_range2); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportStreamData) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3b" "04" "17" "abcdef", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportStreamDataCapsule()); expected_capsule.web_transport_stream_data().stream_id = 0x17; expected_capsule.web_transport_stream_data().data = "\xab\xcd\xef"; expected_capsule.web_transport_stream_data().fin = false; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportStreamDataHeader) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "990b4d3b" "04" "17", &capsule_fragment)); QuicheBufferAllocator* allocator = SimpleBufferAllocator::Get(); QuicheBuffer capsule_header = quiche::SerializeWebTransportStreamCapsuleHeader(0x17, false, 3, allocator); EXPECT_EQ(capsule_header.AsStringView(), capsule_fragment); } TEST_F(CapsuleTest, WebTransportStreamDataWithFin) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3c" "04" "17" "abcdef", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportStreamDataCapsule()); expected_capsule.web_transport_stream_data().stream_id = 0x17; expected_capsule.web_transport_stream_data().data = "\xab\xcd\xef"; expected_capsule.web_transport_stream_data().fin = true; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportResetStream) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d39" "02" "17" "07", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportResetStreamCapsule()); expected_capsule.web_transport_reset_stream().stream_id = 0x17; expected_capsule.web_transport_reset_stream().error_code = 0x07; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportStopSending) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3a" "02" "17" "07", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportStopSendingCapsule()); expected_capsule.web_transport_stop_sending().stream_id = 0x17; expected_capsule.web_transport_stop_sending().error_code = 0x07; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportMaxStreamData) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3e" "02" "17" "10", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportMaxStreamDataCapsule()); expected_capsule.web_transport_max_stream_data().stream_id = 0x17; expected_capsule.web_transport_max_stream_data().max_stream_data = 0x10; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportMaxStreamsBi) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3f" "01" "17", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportMaxStreamsCapsule()); expected_capsule.web_transport_max_streams().stream_type = StreamType::kBidirectional; expected_capsule.web_transport_max_streams().max_stream_count = 0x17; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportMaxStreamsUni) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d40" "01" "17", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportMaxStreamsCapsule()); expected_capsule.web_transport_max_streams().stream_type = StreamType::kUnidirectional; expected_capsule.web_transport_max_streams().max_stream_count = 0x17; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, UnknownCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("17" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string unknown_capsule_data; ASSERT_TRUE( absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &unknown_capsule_data)); Capsule expected_capsule = Capsule::Unknown(0x17, unknown_capsule_data); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, TwoCapsules) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4a5a6a7a8" "00" "08" "b1b2b3b4b5b6b7b8", &capsule_fragment)); std::string datagram_payload1; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload1)); std::string datagram_payload2; ASSERT_TRUE(absl::HexStringToBytes("b1b2b3b4b5b6b7b8", &datagram_payload2)); Capsule expected_capsule1 = Capsule::Datagram(datagram_payload1); Capsule expected_capsule2 = Capsule::Datagram(datagram_payload2); { InSequence s; EXPECT_CALL(visitor_, OnCapsule(expected_capsule1)); EXPECT_CALL(visitor_, OnCapsule(expected_capsule2)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); } TEST_F(CapsuleTest, TwoCapsulesPartialReads) { std::string capsule_fragment1; ASSERT_TRUE(absl::HexStringToBytes( "00" "08" "a1a2a3a4", &capsule_fragment1)); std::string capsule_fragment2; ASSERT_TRUE(absl::HexStringToBytes( "a5a6a7a8" "00", &capsule_fragment2)); std::string capsule_fragment3; ASSERT_TRUE(absl::HexStringToBytes( "08" "b1b2b3b4b5b6b7b8", &capsule_fragment3)); capsule_parser_.ErrorIfThereIsRemainingBufferedData(); std::string datagram_payload1; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload1)); std::string datagram_payload2; ASSERT_TRUE(absl::HexStringToBytes("b1b2b3b4b5b6b7b8", &datagram_payload2)); Capsule expected_capsule1 = Capsule::Datagram(datagram_payload1); Capsule expected_capsule2 = Capsule::Datagram(datagram_payload2); { InSequence s; EXPECT_CALL(visitor_, OnCapsule(expected_capsule1)); EXPECT_CALL(visitor_, OnCapsule(expected_capsule2)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment1)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment2)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment3)); } ValidateParserIsEmpty(); } TEST_F(CapsuleTest, TwoCapsulesOneByteAtATime) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4a5a6a7a8" "00" "08" "b1b2b3b4b5b6b7b8", &capsule_fragment)); std::string datagram_payload1; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload1)); std::string datagram_payload2; ASSERT_TRUE(absl::HexStringToBytes("b1b2b3b4b5b6b7b8", &datagram_payload2)); Capsule expected_capsule1 = Capsule::Datagram(datagram_payload1); Capsule expected_capsule2 = Capsule::Datagram(datagram_payload2); for (size_t i = 0; i < capsule_fragment.size(); i++) { if (i < capsule_fragment.size() / 2 - 1) { EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); } else if (i == capsule_fragment.size() / 2 - 1) { EXPECT_CALL(visitor_, OnCapsule(expected_capsule1)); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } else if (i < capsule_fragment.size() - 1) { EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); } else { EXPECT_CALL(visitor_, OnCapsule(expected_capsule2)); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } } capsule_parser_.ErrorIfThereIsRemainingBufferedData(); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } TEST_F(CapsuleTest, PartialCapsuleThenError) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4", &capsule_fragment)); EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); { EXPECT_CALL(visitor_, OnCapsuleParseFailure(_)).Times(0); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } { EXPECT_CALL(visitor_, OnCapsuleParseFailure( "Incomplete capsule left at the end of the stream")); capsule_parser_.ErrorIfThereIsRemainingBufferedData(); } } TEST_F(CapsuleTest, RejectOverlyLongCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("17" "80123456", &capsule_fragment)); absl::StrAppend(&capsule_fragment, std::string(1111111, '?')); EXPECT_CALL(visitor_, OnCapsuleParseFailure( "Refusing to buffer too much capsule data")); EXPECT_FALSE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } } } }
184
cpp
google/quiche
quiche_random
quiche/common/quiche_random.cc
quiche/common/quiche_random_test.cc
#ifndef QUICHE_COMMON_QUICHE_RANDOM_H_ #define QUICHE_COMMON_QUICHE_RANDOM_H_ #include <cstddef> #include <cstdint> #include "quiche/common/platform/api/quiche_export.h" namespace quiche { class QUICHE_EXPORT QuicheRandom { public: virtual ~QuicheRandom() {} static QuicheRandom* GetInstance(); virtual void RandBytes(void* data, size_t len) = 0; virtual uint64_t RandUint64() = 0; virtual void InsecureRandBytes(void* data, size_t len) = 0; virtual uint64_t InsecureRandUint64() = 0; }; } #endif #include "quiche/common/quiche_random.h" #include <cstdint> #include <cstring> #include "openssl/rand.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { inline uint64_t Xoshiro256InitializeRngStateMember() { uint64_t result; RAND_bytes(reinterpret_cast<uint8_t*>(&result), sizeof(result)); return result; } inline uint64_t Xoshiro256PlusPlusRotLeft(uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } uint64_t Xoshiro256PlusPlus() { static thread_local uint64_t rng_state[4] = { Xoshiro256InitializeRngStateMember(), Xoshiro256InitializeRngStateMember(), Xoshiro256InitializeRngStateMember(), Xoshiro256InitializeRngStateMember()}; const uint64_t result = Xoshiro256PlusPlusRotLeft(rng_state[0] + rng_state[3], 23) + rng_state[0]; const uint64_t t = rng_state[1] << 17; rng_state[2] ^= rng_state[0]; rng_state[3] ^= rng_state[1]; rng_state[1] ^= rng_state[2]; rng_state[0] ^= rng_state[3]; rng_state[2] ^= t; rng_state[3] = Xoshiro256PlusPlusRotLeft(rng_state[3], 45); return result; } class DefaultQuicheRandom : public QuicheRandom { public: DefaultQuicheRandom() {} DefaultQuicheRandom(const DefaultQuicheRandom&) = delete; DefaultQuicheRandom& operator=(const DefaultQuicheRandom&) = delete; ~DefaultQuicheRandom() override {} void RandBytes(void* data, size_t len) override; uint64_t RandUint64() override; void InsecureRandBytes(void* data, size_t len) override; uint64_t InsecureRandUint64() override; }; void DefaultQuicheRandom::RandBytes(void* data, size_t len) { RAND_bytes(reinterpret_cast<uint8_t*>(data), len); } uint64_t DefaultQuicheRandom::RandUint64() { uint64_t value; RandBytes(&value, sizeof(value)); return value; } void DefaultQuicheRandom::InsecureRandBytes(void* data, size_t len) { while (len >= sizeof(uint64_t)) { uint64_t random_bytes64 = Xoshiro256PlusPlus(); memcpy(data, &random_bytes64, sizeof(uint64_t)); data = reinterpret_cast<char*>(data) + sizeof(uint64_t); len -= sizeof(uint64_t); } if (len > 0) { QUICHE_DCHECK_LT(len, sizeof(uint64_t)); uint64_t random_bytes64 = Xoshiro256PlusPlus(); memcpy(data, &random_bytes64, len); } } uint64_t DefaultQuicheRandom::InsecureRandUint64() { return Xoshiro256PlusPlus(); } } QuicheRandom* QuicheRandom::GetInstance() { static DefaultQuicheRandom* random = new DefaultQuicheRandom(); return random; } }
#include "quiche/common/quiche_random.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { TEST(QuicheRandom, RandBytes) { unsigned char buf1[16]; unsigned char buf2[16]; memset(buf1, 0xaf, sizeof(buf1)); memset(buf2, 0xaf, sizeof(buf2)); ASSERT_EQ(0, memcmp(buf1, buf2, sizeof(buf1))); auto rng = QuicheRandom::GetInstance(); rng->RandBytes(buf1, sizeof(buf1)); EXPECT_NE(0, memcmp(buf1, buf2, sizeof(buf1))); } TEST(QuicheRandom, RandUint64) { auto rng = QuicheRandom::GetInstance(); uint64_t value1 = rng->RandUint64(); uint64_t value2 = rng->RandUint64(); EXPECT_NE(value1, value2); } TEST(QuicheRandom, InsecureRandBytes) { unsigned char buf1[16]; unsigned char buf2[16]; memset(buf1, 0xaf, sizeof(buf1)); memset(buf2, 0xaf, sizeof(buf2)); ASSERT_EQ(0, memcmp(buf1, buf2, sizeof(buf1))); auto rng = QuicheRandom::GetInstance(); rng->InsecureRandBytes(buf1, sizeof(buf1)); EXPECT_NE(0, memcmp(buf1, buf2, sizeof(buf1))); } TEST(QuicheRandom, InsecureRandUint64) { auto rng = QuicheRandom::GetInstance(); uint64_t value1 = rng->InsecureRandUint64(); uint64_t value2 = rng->InsecureRandUint64(); EXPECT_NE(value1, value2); } } }
185
cpp
google/quiche
quiche_simple_arena
quiche/common/quiche_simple_arena.cc
quiche/common/quiche_simple_arena_test.cc
#ifndef QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_ #define QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_ #include <memory> #include <vector> #include "quiche/common/platform/api/quiche_export.h" namespace quiche { class QUICHE_EXPORT QuicheSimpleArena { public: class QUICHE_EXPORT Status { private: friend class QuicheSimpleArena; size_t bytes_allocated_; public: Status() : bytes_allocated_(0) {} size_t bytes_allocated() const { return bytes_allocated_; } }; explicit QuicheSimpleArena(size_t block_size); ~QuicheSimpleArena(); QuicheSimpleArena() = delete; QuicheSimpleArena(const QuicheSimpleArena&) = delete; QuicheSimpleArena& operator=(const QuicheSimpleArena&) = delete; QuicheSimpleArena(QuicheSimpleArena&& other); QuicheSimpleArena& operator=(QuicheSimpleArena&& other); char* Alloc(size_t size); char* Realloc(char* original, size_t oldsize, size_t newsize); char* Memdup(const char* data, size_t size); void Free(char* data, size_t size); void Reset(); Status status() const { return status_; } private: struct QUICHE_EXPORT Block { std::unique_ptr<char[]> data; size_t size = 0; size_t used = 0; explicit Block(size_t s); ~Block(); Block(Block&& other); Block& operator=(Block&& other); }; void Reserve(size_t additional_space); void AllocBlock(size_t size); size_t block_size_; std::vector<Block> blocks_; Status status_; }; } #endif #include "quiche/common/quiche_simple_arena.h" #include <algorithm> #include <cstring> #include <utility> #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { QuicheSimpleArena::QuicheSimpleArena(size_t block_size) : block_size_(block_size) {} QuicheSimpleArena::~QuicheSimpleArena() = default; QuicheSimpleArena::QuicheSimpleArena(QuicheSimpleArena&& other) = default; QuicheSimpleArena& QuicheSimpleArena::operator=(QuicheSimpleArena&& other) = default; char* QuicheSimpleArena::Alloc(size_t size) { Reserve(size); Block& b = blocks_.back(); QUICHE_DCHECK_GE(b.size, b.used + size); char* out = b.data.get() + b.used; b.used += size; return out; } char* QuicheSimpleArena::Realloc(char* original, size_t oldsize, size_t newsize) { QUICHE_DCHECK(!blocks_.empty()); Block& last = blocks_.back(); if (last.data.get() <= original && original < last.data.get() + last.size) { QUICHE_DCHECK_GE(last.data.get() + last.used, original + oldsize); if (original + oldsize == last.data.get() + last.used) { if (original + newsize < last.data.get() + last.size) { last.used += newsize - oldsize; return original; } } } char* out = Alloc(newsize); memcpy(out, original, oldsize); return out; } char* QuicheSimpleArena::Memdup(const char* data, size_t size) { char* out = Alloc(size); memcpy(out, data, size); return out; } void QuicheSimpleArena::Free(char* data, size_t size) { if (blocks_.empty()) { return; } Block& b = blocks_.back(); if (size <= b.used && data + size == b.data.get() + b.used) { b.used -= size; } } void QuicheSimpleArena::Reset() { blocks_.clear(); status_.bytes_allocated_ = 0; } void QuicheSimpleArena::Reserve(size_t additional_space) { if (blocks_.empty()) { AllocBlock(std::max(additional_space, block_size_)); } else { const Block& last = blocks_.back(); if (last.size < last.used + additional_space) { AllocBlock(std::max(additional_space, block_size_)); } } } void QuicheSimpleArena::AllocBlock(size_t size) { blocks_.push_back(Block(size)); status_.bytes_allocated_ += size; } QuicheSimpleArena::Block::Block(size_t s) : data(new char[s]), size(s), used(0) {} QuicheSimpleArena::Block::~Block() = default; QuicheSimpleArena::Block::Block(QuicheSimpleArena::Block&& other) : size(other.size), used(other.used) { data = std::move(other.data); } QuicheSimpleArena::Block& QuicheSimpleArena::Block::operator=( QuicheSimpleArena::Block&& other) { size = other.size; used = other.used; data = std::move(other.data); return *this; } }
#include "quiche/common/quiche_simple_arena.h" #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { size_t kDefaultBlockSize = 2048; const char kTestString[] = "This is a decently long test string."; TEST(QuicheSimpleArenaTest, NoAllocationOnConstruction) { QuicheSimpleArena arena(kDefaultBlockSize); EXPECT_EQ(0u, arena.status().bytes_allocated()); } TEST(QuicheSimpleArenaTest, Memdup) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c = arena.Memdup(kTestString, length); EXPECT_NE(nullptr, c); EXPECT_NE(c, kTestString); EXPECT_EQ(absl::string_view(c, length), kTestString); } TEST(QuicheSimpleArenaTest, MemdupLargeString) { QuicheSimpleArena arena(10 ); const size_t length = strlen(kTestString); char* c = arena.Memdup(kTestString, length); EXPECT_NE(nullptr, c); EXPECT_NE(c, kTestString); EXPECT_EQ(absl::string_view(c, length), kTestString); } TEST(QuicheSimpleArenaTest, MultipleBlocks) { QuicheSimpleArena arena(40 ); std::vector<std::string> strings = { "One decently long string.", "Another string.", "A third string that will surely go in a different block."}; std::vector<absl::string_view> copies; for (const std::string& s : strings) { absl::string_view sp(arena.Memdup(s.data(), s.size()), s.size()); copies.push_back(sp); } EXPECT_EQ(strings.size(), copies.size()); for (size_t i = 0; i < strings.size(); ++i) { EXPECT_EQ(copies[i], strings[i]); } } TEST(QuicheSimpleArenaTest, UseAfterReset) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c = arena.Memdup(kTestString, length); arena.Reset(); c = arena.Memdup(kTestString, length); EXPECT_NE(nullptr, c); EXPECT_NE(c, kTestString); EXPECT_EQ(absl::string_view(c, length), kTestString); } TEST(QuicheSimpleArenaTest, Free) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); arena.Free(const_cast<char*>(kTestString), length); char* c1 = arena.Memdup("Foo", 3); char* c2 = arena.Memdup(kTestString, length); arena.Free(const_cast<char*>(kTestString), length); char* c3 = arena.Memdup("Bar", 3); char* c4 = arena.Memdup(kTestString, length); EXPECT_NE(c1, c2); EXPECT_NE(c1, c3); EXPECT_NE(c1, c4); EXPECT_NE(c2, c3); EXPECT_NE(c2, c4); EXPECT_NE(c3, c4); arena.Free(c4, length); arena.Free(c2, length); char* c5 = arena.Memdup("Baz", 3); EXPECT_EQ(c4, c5); } TEST(QuicheSimpleArenaTest, Alloc) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c1 = arena.Alloc(length); char* c2 = arena.Alloc(2 * length); char* c3 = arena.Alloc(3 * length); char* c4 = arena.Memdup(kTestString, length); EXPECT_EQ(c1 + length, c2); EXPECT_EQ(c2 + 2 * length, c3); EXPECT_EQ(c3 + 3 * length, c4); EXPECT_EQ(absl::string_view(c4, length), kTestString); } TEST(QuicheSimpleArenaTest, Realloc) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c1 = arena.Memdup(kTestString, length); char* c2 = arena.Realloc(c1, length, 2 * length); EXPECT_TRUE(c1); EXPECT_EQ(c1, c2); EXPECT_EQ(absl::string_view(c1, length), kTestString); char* c3 = arena.Memdup(kTestString, length); EXPECT_EQ(c2 + 2 * length, c3); EXPECT_EQ(absl::string_view(c3, length), kTestString); char* c4 = arena.Realloc(c3, length, 2 * length); EXPECT_EQ(c3, c4); EXPECT_EQ(absl::string_view(c4, length), kTestString); char* c5 = arena.Realloc(c4, 2 * length, 3 * length); EXPECT_EQ(c4, c5); EXPECT_EQ(absl::string_view(c5, length), kTestString); char* c6 = arena.Memdup(kTestString, length); EXPECT_EQ(c5 + 3 * length, c6); EXPECT_EQ(absl::string_view(c6, length), kTestString); char* c7 = arena.Realloc(c6, length, kDefaultBlockSize); EXPECT_EQ(absl::string_view(c7, length), kTestString); arena.Free(c7, kDefaultBlockSize); char* c8 = arena.Memdup(kTestString, length); EXPECT_NE(c6, c7); EXPECT_EQ(c7, c8); EXPECT_EQ(absl::string_view(c8, length), kTestString); } } }
186
cpp
google/quiche
quiche_mem_slice_storage
quiche/common/quiche_mem_slice_storage.cc
quiche/common/quiche_mem_slice_storage_test.cc
#ifndef QUICHE_COMMON_QUICHE_MEM_SLICE_STORAGE_H_ #define QUICHE_COMMON_QUICHE_MEM_SLICE_STORAGE_H_ #include <vector> #include "absl/types/span.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_iovec.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_buffer_allocator.h" namespace quiche { class QUICHE_EXPORT QuicheMemSliceStorage { public: QuicheMemSliceStorage(const struct iovec* iov, int iov_count, QuicheBufferAllocator* allocator, const quic::QuicByteCount max_slice_len); QuicheMemSliceStorage(const QuicheMemSliceStorage& other) = delete; QuicheMemSliceStorage& operator=(const QuicheMemSliceStorage& other) = delete; QuicheMemSliceStorage(QuicheMemSliceStorage&& other) = default; QuicheMemSliceStorage& operator=(QuicheMemSliceStorage&& other) = default; ~QuicheMemSliceStorage() = default; absl::Span<QuicheMemSlice> ToSpan() { return absl::MakeSpan(storage_); } private: std::vector<QuicheMemSlice> storage_; }; } #endif #include "quiche/common/quiche_mem_slice_storage.h" #include <algorithm> #include <utility> #include "quiche/quic/core/quic_utils.h" namespace quiche { QuicheMemSliceStorage::QuicheMemSliceStorage( const struct iovec* iov, int iov_count, QuicheBufferAllocator* allocator, const quic::QuicByteCount max_slice_len) { if (iov == nullptr) { return; } quic::QuicByteCount write_len = 0; for (int i = 0; i < iov_count; ++i) { write_len += iov[i].iov_len; } QUICHE_DCHECK_LT(0u, write_len); size_t io_offset = 0; while (write_len > 0) { size_t slice_len = std::min(write_len, max_slice_len); QuicheBuffer buffer = QuicheBuffer::CopyFromIovec(allocator, iov, iov_count, io_offset, slice_len); storage_.push_back(QuicheMemSlice(std::move(buffer))); write_len -= slice_len; io_offset += slice_len; } } }
#include "quiche/common/quiche_mem_slice_storage.h" #include <string> #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/simple_buffer_allocator.h" namespace quiche { namespace test { namespace { class QuicheMemSliceStorageImplTest : public QuicheTest { public: QuicheMemSliceStorageImplTest() = default; }; TEST_F(QuicheMemSliceStorageImplTest, EmptyIov) { QuicheMemSliceStorage storage(nullptr, 0, nullptr, 1024); EXPECT_TRUE(storage.ToSpan().empty()); } TEST_F(QuicheMemSliceStorageImplTest, SingleIov) { SimpleBufferAllocator allocator; std::string body(3, 'c'); struct iovec iov = {const_cast<char*>(body.data()), body.length()}; QuicheMemSliceStorage storage(&iov, 1, &allocator, 1024); auto span = storage.ToSpan(); EXPECT_EQ("ccc", span[0].AsStringView()); EXPECT_NE(static_cast<const void*>(span[0].data()), body.data()); } TEST_F(QuicheMemSliceStorageImplTest, MultipleIovInSingleSlice) { SimpleBufferAllocator allocator; std::string body1(3, 'a'); std::string body2(4, 'b'); struct iovec iov[] = {{const_cast<char*>(body1.data()), body1.length()}, {const_cast<char*>(body2.data()), body2.length()}}; QuicheMemSliceStorage storage(iov, 2, &allocator, 1024); auto span = storage.ToSpan(); EXPECT_EQ("aaabbbb", span[0].AsStringView()); } TEST_F(QuicheMemSliceStorageImplTest, MultipleIovInMultipleSlice) { SimpleBufferAllocator allocator; std::string body1(4, 'a'); std::string body2(4, 'b'); struct iovec iov[] = {{const_cast<char*>(body1.data()), body1.length()}, {const_cast<char*>(body2.data()), body2.length()}}; QuicheMemSliceStorage storage(iov, 2, &allocator, 4); auto span = storage.ToSpan(); EXPECT_EQ("aaaa", span[0].AsStringView()); EXPECT_EQ("bbbb", span[1].AsStringView()); } } } }
187
cpp
google/quiche
structured_headers
quiche/common/structured_headers.cc
quiche/common/structured_headers_test.cc
#ifndef QUICHE_COMMON_STRUCTURED_HEADERS_H_ #define QUICHE_COMMON_STRUCTURED_HEADERS_H_ #include <cstddef> #include <cstdint> #include <map> #include <optional> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace structured_headers { class QUICHE_EXPORT Item { public: enum ItemType { kNullType, kIntegerType, kDecimalType, kStringType, kTokenType, kByteSequenceType, kBooleanType }; Item(); explicit Item(int64_t value); explicit Item(double value); explicit Item(bool value); Item(const char* value, Item::ItemType type = kStringType); Item(std::string value, Item::ItemType type = kStringType); QUICHE_EXPORT friend bool operator==(const Item& lhs, const Item& rhs); inline friend bool operator!=(const Item& lhs, const Item& rhs) { return !(lhs == rhs); } bool is_null() const { return Type() == kNullType; } bool is_integer() const { return Type() == kIntegerType; } bool is_decimal() const { return Type() == kDecimalType; } bool is_string() const { return Type() == kStringType; } bool is_token() const { return Type() == kTokenType; } bool is_byte_sequence() const { return Type() == kByteSequenceType; } bool is_boolean() const { return Type() == kBooleanType; } int64_t GetInteger() const { const auto* value = absl::get_if<int64_t>(&value_); QUICHE_CHECK(value); return *value; } double GetDecimal() const { const auto* value = absl::get_if<double>(&value_); QUICHE_CHECK(value); return *value; } bool GetBoolean() const { const auto* value = absl::get_if<bool>(&value_); QUICHE_CHECK(value); return *value; } const std::string& GetString() const { struct Visitor { const std::string* operator()(const absl::monostate&) { return nullptr; } const std::string* operator()(const int64_t&) { return nullptr; } const std::string* operator()(const double&) { return nullptr; } const std::string* operator()(const std::string& value) { return &value; } const std::string* operator()(const bool&) { return nullptr; } }; const std::string* value = absl::visit(Visitor(), value_); QUICHE_CHECK(value); return *value; } std::string TakeString() && { struct Visitor { std::string* operator()(absl::monostate&) { return nullptr; } std::string* operator()(int64_t&) { return nullptr; } std::string* operator()(double&) { return nullptr; } std::string* operator()(std::string& value) { return &value; } std::string* operator()(bool&) { return nullptr; } }; std::string* value = absl::visit(Visitor(), value_); QUICHE_CHECK(value); return std::move(*value); } ItemType Type() const { return static_cast<ItemType>(value_.index()); } private: absl::variant<absl::monostate, int64_t, double, std::string, std::string, std::string, bool> value_; }; QUICHE_EXPORT absl::string_view ItemTypeToString(Item::ItemType type); QUICHE_EXPORT bool IsValidToken(absl::string_view str); struct QUICHE_EXPORT ParameterisedIdentifier { using Parameters = std::map<std::string, Item>; Item identifier; Parameters params; ParameterisedIdentifier(); ParameterisedIdentifier(const ParameterisedIdentifier&); ParameterisedIdentifier& operator=(const ParameterisedIdentifier&); ParameterisedIdentifier(Item, Parameters); ~ParameterisedIdentifier(); }; inline bool operator==(const ParameterisedIdentifier& lhs, const ParameterisedIdentifier& rhs) { return std::tie(lhs.identifier, lhs.params) == std::tie(rhs.identifier, rhs.params); } using Parameters = std::vector<std::pair<std::string, Item>>; struct QUICHE_EXPORT ParameterizedItem { Item item; Parameters params; ParameterizedItem(); ParameterizedItem(const ParameterizedItem&); ParameterizedItem& operator=(const ParameterizedItem&); ParameterizedItem(Item, Parameters); ~ParameterizedItem(); }; inline bool operator==(const ParameterizedItem& lhs, const ParameterizedItem& rhs) { return std::tie(lhs.item, lhs.params) == std::tie(rhs.item, rhs.params); } inline bool operator!=(const ParameterizedItem& lhs, const ParameterizedItem& rhs) { return !(lhs == rhs); } struct QUICHE_EXPORT ParameterizedMember { std::vector<ParameterizedItem> member; bool member_is_inner_list = false; Parameters params; ParameterizedMember(); ParameterizedMember(const ParameterizedMember&); ParameterizedMember& operator=(const ParameterizedMember&); ParameterizedMember(std::vector<ParameterizedItem>, bool member_is_inner_list, Parameters); ParameterizedMember(std::vector<ParameterizedItem>, Parameters); ParameterizedMember(Item, Parameters); ~ParameterizedMember(); }; inline bool operator==(const ParameterizedMember& lhs, const ParameterizedMember& rhs) { return std::tie(lhs.member, lhs.member_is_inner_list, lhs.params) == std::tie(rhs.member, rhs.member_is_inner_list, rhs.params); } using DictionaryMember = std::pair<std::string, ParameterizedMember>; class QUICHE_EXPORT Dictionary { public: using iterator = std::vector<DictionaryMember>::iterator; using const_iterator = std::vector<DictionaryMember>::const_iterator; Dictionary(); Dictionary(const Dictionary&); Dictionary(Dictionary&&); explicit Dictionary(std::vector<DictionaryMember> members); ~Dictionary(); Dictionary& operator=(const Dictionary&) = default; Dictionary& operator=(Dictionary&&) = default; iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; ParameterizedMember& operator[](std::size_t idx); const ParameterizedMember& operator[](std::size_t idx) const; ParameterizedMember& at(std::size_t idx); const ParameterizedMember& at(std::size_t idx) const; ParameterizedMember& operator[](absl::string_view key); ParameterizedMember& at(absl::string_view key); const ParameterizedMember& at(absl::string_view key) const; const_iterator find(absl::string_view key) const; iterator find(absl::string_view key); void clear(); bool empty() const; std::size_t size() const; bool contains(absl::string_view key) const; friend bool operator==(const Dictionary& lhs, const Dictionary& rhs); friend bool operator!=(const Dictionary& lhs, const Dictionary& rhs); private: std::vector<DictionaryMember> members_; }; inline bool operator==(const Dictionary& lhs, const Dictionary& rhs) { return lhs.members_ == rhs.members_; } inline bool operator!=(const Dictionary& lhs, const Dictionary& rhs) { return !(lhs == rhs); } using ParameterisedList = std::vector<ParameterisedIdentifier>; using ListOfLists = std::vector<std::vector<Item>>; using List = std::vector<ParameterizedMember>; QUICHE_EXPORT std::optional<ParameterizedItem> ParseItem(absl::string_view str); QUICHE_EXPORT std::optional<Item> ParseBareItem(absl::string_view str); QUICHE_EXPORT std::optional<ParameterisedList> ParseParameterisedList( absl::string_view str); QUICHE_EXPORT std::optional<ListOfLists> ParseListOfLists( absl::string_view str); QUICHE_EXPORT std::optional<List> ParseList(absl::string_view str); QUICHE_EXPORT std::optional<Dictionary> ParseDictionary(absl::string_view str); QUICHE_EXPORT std::optional<std::string> SerializeItem(const Item& value); QUICHE_EXPORT std::optional<std::string> SerializeItem( const ParameterizedItem& value); QUICHE_EXPORT std::optional<std::string> SerializeList(const List& value); QUICHE_EXPORT std::optional<std::string> SerializeDictionary( const Dictionary& value); } } #endif #include "quiche/common/structured_headers.h" #include <cmath> #include <cstddef> #include <cstdint> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace structured_headers { namespace { #define DIGIT "0123456789" #define LCALPHA "abcdefghijklmnopqrstuvwxyz" #define UCALPHA "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define TCHAR DIGIT LCALPHA UCALPHA "!#$%&'*+-.^_`|~" constexpr char kTokenChars09[] = DIGIT UCALPHA LCALPHA "_-.:%*/"; constexpr char kTokenChars[] = TCHAR ":/"; constexpr char kKeyChars09[] = DIGIT LCALPHA "_-"; constexpr char kKeyChars[] = DIGIT LCALPHA "_-.*"; constexpr char kSP[] = " "; constexpr char kOWS[] = " \t"; #undef DIGIT #undef LCALPHA #undef UCALPHA constexpr int64_t kMaxInteger = 999'999'999'999'999L; constexpr int64_t kMinInteger = -999'999'999'999'999L; constexpr double kTooLargeDecimal = 1e12 - 0.0005; void StripLeft(absl::string_view& s, absl::string_view remove) { size_t i = s.find_first_not_of(remove); if (i == absl::string_view::npos) { i = s.size(); } s.remove_prefix(i); } class StructuredHeaderParser { public: enum DraftVersion { kDraft09, kFinal, }; explicit StructuredHeaderParser(absl::string_view str, DraftVersion version) : input_(str), version_(version) { SkipWhitespaces(); } StructuredHeaderParser(const StructuredHeaderParser&) = delete; StructuredHeaderParser& operator=(const StructuredHeaderParser&) = delete; bool FinishParsing() { SkipWhitespaces(); return input_.empty(); } std::optional<ListOfLists> ReadListOfLists() { QUICHE_CHECK_EQ(version_, kDraft09); ListOfLists result; while (true) { std::vector<Item> inner_list; while (true) { std::optional<Item> item(ReadBareItem()); if (!item) return std::nullopt; inner_list.push_back(std::move(*item)); SkipWhitespaces(); if (!ConsumeChar(';')) break; SkipWhitespaces(); } result.push_back(std::move(inner_list)); SkipWhitespaces(); if (!ConsumeChar(',')) break; SkipWhitespaces(); } return result; } std::optional<List> ReadList() { QUICHE_CHECK_EQ(version_, kFinal); List members; while (!input_.empty()) { std::optional<ParameterizedMember> member(ReadItemOrInnerList()); if (!member) return std::nullopt; members.push_back(std::move(*member)); SkipOWS(); if (input_.empty()) break; if (!ConsumeChar(',')) return std::nullopt; SkipOWS(); if (input_.empty()) return std::nullopt; } return members; } std::optional<ParameterizedItem> ReadItem() { std::optional<Item> item = ReadBareItem(); if (!item) return std::nullopt; std::optional<Parameters> parameters = ReadParameters(); if (!parameters) return std::nullopt; return ParameterizedItem(std::move(*item), std::move(*parameters)); } std::optional<Item> ReadBareItem() { if (input_.empty()) { QUICHE_DVLOG(1) << "ReadBareItem: unexpected EOF"; return std::nullopt; } switch (input_.front()) { case '"': return ReadString(); case '*': if (version_ == kDraft09) return ReadByteSequence(); return ReadToken(); case ':': if (version_ == kFinal) return ReadByteSequence(); return std::nullopt; case '?': return ReadBoolean(); default: if (input_.front() == '-' || absl::ascii_isdigit(input_.front())) return ReadNumber(); if (absl::ascii_isalpha(input_.front())) return ReadToken(); return std::nullopt; } } std::optional<Dictionary> ReadDictionary() { QUICHE_CHECK_EQ(version_, kFinal); Dictionary members; while (!input_.empty()) { std::optional<std::string> key(ReadKey()); if (!key) return std::nullopt; std::optional<ParameterizedMember> member; if (ConsumeChar('=')) { member = ReadItemOrInnerList(); if (!member) return std::nullopt; } else { std::optional<Parameters> parameters = ReadParameters(); if (!parameters) return std::nullopt; member = ParameterizedMember{Item(true), std::move(*parameters)}; } members[*key] = std::move(*member); SkipOWS(); if (input_.empty()) break; if (!ConsumeChar(',')) return std::nullopt; SkipOWS(); if (input_.empty()) return std::nullopt; } return members; } std::optional<ParameterisedList> ReadParameterisedList() { QUICHE_CHECK_EQ(version_, kDraft09); ParameterisedList items; while (true) { std::optional<ParameterisedIdentifier> item = ReadParameterisedIdentifier(); if (!item) return std::nullopt; items.push_back(std::move(*item)); SkipWhitespaces(); if (!ConsumeChar(',')) return items; SkipWhitespaces(); } } private: std::optional<ParameterisedIdentifier> ReadParameterisedIdentifier() { QUICHE_CHECK_EQ(version_, kDraft09); std::optional<Item> primary_identifier = ReadToken(); if (!primary_identifier) return std::nullopt; ParameterisedIdentifier::Parameters parameters; SkipWhitespaces(); while (ConsumeChar(';')) { SkipWhitespaces(); std::optional<std::string> name = ReadKey(); if (!name) return std::nullopt; Item value; if (ConsumeChar('=')) { auto item = ReadBareItem(); if (!item) return std::nullopt; value = std::move(*item); } if (!parameters.emplace(*name, std::move(value)).second) { QUICHE_DVLOG(1) << "ReadParameterisedIdentifier: duplicated parameter: " << *name; return std::nullopt; } SkipWhitespaces(); } return ParameterisedIdentifier(std::move(*primary_identifier), std::move(parameters)); } std::optional<ParameterizedMember> ReadItemOrInnerList() { QUICHE_CHECK_EQ(version_, kFinal); bool member_is_inner_list = (!input_.empty() && input_.front() == '('); if (member_is_inner_list) { return ReadInnerList(); } else { auto item = ReadItem(); if (!item) return std::nullopt; return ParameterizedMember(std::move(item->item), std::move(item->params)); } } std::optional<Parameters> ReadParameters() { Parameters parameters; absl::flat_hash_set<std::string> keys; while (ConsumeChar(';')) { SkipWhitespaces(); std::optional<std::string> name = ReadKey(); if (!name) return std::nullopt; bool is_duplicate_key = !keys.insert(*name).second; Item value{true}; if (ConsumeChar('=')) { auto item = ReadBareItem(); if (!item) return std::nullopt; value = std::move(*item); } if (is_duplicate_key) { for (auto& param : parameters) { if (param.first == name) { param.second = std::move(value); break; } } } else { parameters.emplace_back(std::move(*name), std::move(value)); } } return parameters; } std::optional<ParameterizedMember> ReadInnerList() { QUICHE_CHECK_EQ(version_, kFinal); if (!ConsumeChar('(')) return std::nullopt; std::vector<ParameterizedItem> inner_list; while (true) { SkipWhitespaces(); if (ConsumeChar(')')) { std::optional<Parameters> parameters = ReadParameters(); if (!parameters) return std::nullopt; return ParameterizedMember(std::move(inner_list), true, std::move(*parameters)); } auto item = ReadItem(); if (!item) return std::nullopt; inner_list.push_back(std::move(*item)); if (input_.empty() || (input_.front() != ' ' && input_.front() != ')')) return std::nullopt; } QUICHE_NOTREACHED(); return std::nullopt; } std::optional<std::string> ReadKey() { if (version_ == kDraft09) { if (input_.empty() || !absl::ascii_islower(input_.front())) { LogParseError("ReadKey", "lcalpha"); return std::nullopt; } } else { if (input_.empty() || (!absl::ascii_islower(input_.front()) && input_.front() != '*')) { LogParseError("ReadKey", "lcalpha | *"); return std::nullopt; } } const char* allowed_chars = (version_ == kDraft09 ? kKeyChars09 : kKeyChars); size_t len = input_.find_first_not_of(allowed_chars); if (len == absl::string_view::npos) len = input_.size(); std::string key(input_.substr(0, len)); input_.remove_prefix(len); return key; } std::optional<Item> ReadToken() { if (input_.empty() || !(absl::ascii_isalpha(input_.front()) || input_.front() == '*')) { LogParseError("ReadToken", "ALPHA"); return std::nullopt; } size_t len = input_.find_first_not_of(version_ == kDraft09 ? kTokenChars09 : kTokenChars); if (len == absl::string_view::npos) len = input_.size(); std::string token(input_.substr(0, len)); input_.remove_prefix(len); return Item(std::move(token), Item::kTokenType); } std::optional<Item> ReadNumber() { bool is_negative = ConsumeChar('-'); bool is_decimal = false; size_t decimal_position = 0; size_t i = 0; for (; i < input_.size(); ++i) { if (i > 0 && input_[i] == '.' && !is_decimal) { is_decimal = true; decimal_position = i; continue; } if (!absl::ascii_isdigit(input_[i])) break; } if (i == 0) { LogParseError("ReadNumber", "DIGIT"); return std::nullopt; } if (!is_decimal) { if (version_ == kFinal && i > 15) { LogParseError("ReadNumber", "integer too long"); return std::nullopt; } } else { if (version_ != kFinal && i > 16) { LogParseError("ReadNumber", "float too long"); return std::nullopt; } if (version_ == kFinal && decimal_position > 12) { LogParseError("ReadNumber", "decimal too long"); return std::nullopt; } if (i - decimal_position > (version_ == kFinal ? 4 : 7)) { LogParseError("ReadNumber", "too many digits after decimal"); return std::nullopt; } if (i == decimal_position) { LogParseError("ReadNumber", "no digits after decimal"); return std::nullopt; } } std::string output_number_string(input_.substr(0, i)); input_.remove_prefix(i); if (is_decimal) { double f; if (!absl::SimpleAtod(output_number_string, &f)) return std::nullopt; return Item(is_negative ? -f : f); } else { int64_t n; if (!absl::SimpleAtoi(output_number_string, &n)) return std::nullopt; QUICHE_CHECK(version_ != kFinal || (n <= kMaxInteger && n >= kMinInteger)); return Item(is_negative ? -n : n); } } std::optional<Item> ReadString() { std::string s; if (!ConsumeChar('"')) { LogParseError("ReadString", "'\"'"); return std::nullopt; } while (!ConsumeChar('"')) { size_t i = 0; for (; i < input_.size(); ++i) { if (!absl::ascii_isprint(input_[i])) { QUICHE_DVLOG(1) << "ReadString: non printable-ASCII character"; return std::nullopt; } if (input_[i] == '"' || input_[i] == '\\') break; } if (i == input_.size()) { QUICHE_DVLOG(1) << "ReadString: missing closing '\"'"; return std::nullopt; } s.append(std::string(input_.substr(0, i))); input_.remove_prefix(i); if (ConsumeChar('\\')) { if (input_.empty()) { QUICHE_DVLOG(1) << "ReadString: backslash at string end"; return std::nullopt; } if (input_[0] != '"' && input_[0] != '\\') { QUICHE_DVLOG(1) << "ReadString: invalid escape"; return std::nullopt; } s.push_back(input_.front()); input_.remove_prefix(1); } } return s; } std::optional<Item> ReadByteSequence() { char delimiter = (version_ == kDraft09 ? '*' : ':'); if (!ConsumeChar(delimiter)) { LogParseError("ReadByteSequence", "delimiter"); return std::nullopt; } size_t len = input_.find(delimiter); if (len == absl::string_view::npos) { QUICHE_DVLOG(1) << "ReadByteSequence: missing closing delimiter"; return std::nullopt; } std::string base64(input_.substr(0, len)); base64.resize((base64.size() + 3) / 4 * 4, '='); std::string binary; if (!absl::Base64Unescape(base64, &binary)) { QUICHE_DVLOG(1) << "ReadByteSequence: failed to decode base64: " << base64; return std::nullopt; } input_.remove_prefix(len); ConsumeChar(delimiter); return Item(std::move(binary), Item::kByteSequenceType); } std::optional<Item> ReadBoolean() { if (!ConsumeChar('?')) { LogParseError("ReadBoolean", "'?'"); return std::nullopt; } if (ConsumeChar('1')) { return Item(true); } if (ConsumeChar('0')) { return Item(false); } return std::nullopt; } void SkipWhitespaces() { if (version_ == kDraft09) { StripLeft(input_, kOWS); } else { StripLeft(input_, kSP); } } void SkipOWS() { StripLeft(input_, kOWS); } bool ConsumeChar(char expected) { if (!input_.empty() && input_.front() == expected) { input_.remove_prefix(1); return true; } return false; } void LogParseError(const char* func, const char* expected) { QUICHE_DVLOG(1) << func << ": " << expected << " expected, got " << (input_.empty() ? "EOS" : "'" + std::string(input_.substr(0, 1)) + "'"); } absl::string_view input_; DraftVersion version_; }; class StructuredHeaderSerializer { public: StructuredHeaderSerializer() = default; ~StructuredHeaderSerializer() = default; StructuredHeaderSerializer(const StructuredHeaderSerializer&) = delete; StructuredHeaderSerializer& operator=(const StructuredHeaderSerializer&) = delete; std::string Output() { return output_.str(); } bool WriteList(const List& value) { bool first = true; for (const auto& member : value) { if (!first) output_ << ", "; if (!WriteParameterizedMember(member)) return false; first = false; } return true; } bool WriteItem(const ParameterizedItem& value) { if (!WriteBareItem(value.item)) return false; return WriteParameters(value.params); } bool WriteBareItem(const Item& value) { if (value.is_string()) { output_ << "\""; for (const char& c : value.GetString()) { if (!absl::ascii_isprint(c)) return false; if (c == '\\' || c == '\"') output_ << "\\"; output_ << c; } output_ << "\""; return true; } if (value.is_token()) { if (!IsValidToken(value.GetString())) { return false; } output_ << value.GetString(); return true; } if (value.is_byte_sequence()) { output_ << ":"; output_ << absl::Base64Escape(value.GetString()); output_ << ":"; return true; } if (value.is_integer()) { if (value.GetInteger() > kMaxInteger || value.GetInteger() < kMinInteger) return false; output_ << value.GetInteger(); return true; } if (value.is_decimal()) {
#include "quiche/common/structured_headers.h" #include <math.h> #include <limits> #include <optional> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace structured_headers { namespace { Item Token(std::string value) { return Item(value, Item::kTokenType); } Item Integer(int64_t value) { return Item(value); } std::pair<std::string, Item> NullParam(std::string key) { return std::make_pair(key, Item()); } std::pair<std::string, Item> BooleanParam(std::string key, bool value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> DoubleParam(std::string key, double value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> Param(std::string key, int64_t value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> Param(std::string key, std::string value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> ByteSequenceParam(std::string key, std::string value) { return std::make_pair(key, Item(value, Item::kByteSequenceType)); } std::pair<std::string, Item> TokenParam(std::string key, std::string value) { return std::make_pair(key, Token(value)); } const struct ItemTestCase { const char* name; const char* raw; const std::optional<Item> expected; const char* canonical; } item_test_cases[] = { {"bad token - item", "abc$@%!", std::nullopt, nullptr}, {"leading whitespace", " foo", Token("foo"), "foo"}, {"trailing whitespace", "foo ", Token("foo"), "foo"}, {"leading asterisk", "*foo", Token("*foo"), nullptr}, {"long integer", "999999999999999", Integer(999999999999999L), nullptr}, {"long negative integer", "-999999999999999", Integer(-999999999999999L), nullptr}, {"too long integer", "1000000000000000", std::nullopt, nullptr}, {"negative too long integer", "-1000000000000000", std::nullopt, nullptr}, {"integral decimal", "1.0", Item(1.0), nullptr}, {"basic string", "\"foo\"", Item("foo"), nullptr}, {"non-ascii string", "\"f\xC3\xBC\xC3\xBC\"", std::nullopt, nullptr}, {"valid quoting containing \\n", "\"\\\\n\"", Item("\\n"), nullptr}, {"valid quoting containing \\t", "\"\\\\t\"", Item("\\t"), nullptr}, {"valid quoting containing \\x", "\"\\\\x61\"", Item("\\x61"), nullptr}, {"c-style hex escape in string", "\"\\x61\"", std::nullopt, nullptr}, {"valid quoting containing \\u", "\"\\\\u0061\"", Item("\\u0061"), nullptr}, {"c-style unicode escape in string", "\"\\u0061\"", std::nullopt, nullptr}, }; const ItemTestCase sh09_item_test_cases[] = { {"large integer", "9223372036854775807", Integer(9223372036854775807L), nullptr}, {"large negative integer", "-9223372036854775807", Integer(-9223372036854775807L), nullptr}, {"too large integer", "9223372036854775808", std::nullopt, nullptr}, {"too large negative integer", "-9223372036854775808", std::nullopt, nullptr}, {"basic binary", "*aGVsbG8=*", Item("hello", Item::kByteSequenceType), nullptr}, {"empty binary", "**", Item("", Item::kByteSequenceType), nullptr}, {"bad paddding", "*aGVsbG8*", Item("hello", Item::kByteSequenceType), "*aGVsbG8=*"}, {"bad end delimiter", "*aGVsbG8=", std::nullopt, nullptr}, {"extra whitespace", "*aGVsb G8=*", std::nullopt, nullptr}, {"extra chars", "*aGVsbG!8=*", std::nullopt, nullptr}, {"suffix chars", "*aGVsbG8=!*", std::nullopt, nullptr}, {"non-zero pad bits", "*iZ==*", Item("\x89", Item::kByteSequenceType), "*iQ==*"}, {"non-ASCII binary", "*/+Ah*", Item("\xFF\xE0!", Item::kByteSequenceType), nullptr}, {"base64url binary", "*_-Ah*", std::nullopt, nullptr}, {"token with leading asterisk", "*foo", std::nullopt, nullptr}, }; const struct ParameterizedItemTestCase { const char* name; const char* raw; const std::optional<ParameterizedItem> expected; const char* canonical; } parameterized_item_test_cases[] = { {"single parameter item", "text/html;q=1.0", {{Token("text/html"), {DoubleParam("q", 1)}}}, nullptr}, {"missing parameter value item", "text/html;a;q=1.0", {{Token("text/html"), {BooleanParam("a", true), DoubleParam("q", 1)}}}, nullptr}, {"missing terminal parameter value item", "text/html;q=1.0;a", {{Token("text/html"), {DoubleParam("q", 1), BooleanParam("a", true)}}}, nullptr}, {"duplicate parameter keys with different value", "text/html;a=1;b=2;a=3.0", {{Token("text/html"), {DoubleParam("a", 3), Param("b", 2L)}}}, "text/html;a=3.0;b=2"}, {"multiple duplicate parameter keys at different position", "text/html;c=1;a=2;b;b=3.0;a", {{Token("text/html"), {Param("c", 1L), BooleanParam("a", true), DoubleParam("b", 3)}}}, "text/html;c=1;a;b=3.0"}, {"duplicate parameter keys with missing value", "text/html;a;a=1", {{Token("text/html"), {Param("a", 1L)}}}, "text/html;a=1"}, {"whitespace before = parameterised item", "text/html, text/plain;q =0.5", std::nullopt, nullptr}, {"whitespace after = parameterised item", "text/html, text/plain;q= 0.5", std::nullopt, nullptr}, {"whitespace before ; parameterised item", "text/html, text/plain ;q=0.5", std::nullopt, nullptr}, {"whitespace after ; parameterised item", "text/plain; q=0.5", {{Token("text/plain"), {DoubleParam("q", 0.5)}}}, "text/plain;q=0.5"}, {"extra whitespace parameterised item", "text/plain; q=0.5; charset=utf-8", {{Token("text/plain"), {DoubleParam("q", 0.5), TokenParam("charset", "utf-8")}}}, "text/plain;q=0.5;charset=utf-8"}, }; const struct ListTestCase { const char* name; const char* raw; const std::optional<List> expected; const char* canonical; } list_test_cases[] = { {"extra whitespace list of lists", "(1 42)", {{{{{Integer(1L), {}}, {Integer(42L), {}}}, {}}}}, "(1 42)"}, {"basic parameterised list", "abc_123;a=1;b=2; cdef_456, ghi;q=\"9\";r=\"+w\"", {{{Token("abc_123"), {Param("a", 1), Param("b", 2), BooleanParam("cdef_456", true)}}, {Token("ghi"), {Param("q", "9"), Param("r", "+w")}}}}, "abc_123;a=1;b=2;cdef_456, ghi;q=\"9\";r=\"+w\""}, {"parameterised basic list of lists", "(1;a=1.0 2), (42 43)", {{{{{Integer(1L), {DoubleParam("a", 1.0)}}, {Integer(2L), {}}}, {}}, {{{Integer(42L), {}}, {Integer(43L), {}}}, {}}}}, nullptr}, {"parameters on inner members", "(1;a=1.0 2;b=c), (42;d=?0 43;e=:Zmdo:)", {{{{{Integer(1L), {DoubleParam("a", 1.0)}}, {Integer(2L), {TokenParam("b", "c")}}}, {}}, {{{Integer(42L), {BooleanParam("d", false)}}, {Integer(43L), {ByteSequenceParam("e", "fgh")}}}, {}}}}, nullptr}, {"parameters on inner lists", "(1 2);a=1.0, (42 43);b=?0", {{{{{Integer(1L), {}}, {Integer(2L), {}}}, {DoubleParam("a", 1.0)}}, {{{Integer(42L), {}}, {Integer(43L), {}}}, {BooleanParam("b", false)}}}}, nullptr}, {"default true values for parameters on inner list members", "(1;a 2), (42 43;b)", {{{{{Integer(1L), {BooleanParam("a", true)}}, {Integer(2L), {}}}, {}}, {{{Integer(42L), {}}, {Integer(43L), {BooleanParam("b", true)}}}, {}}}}, nullptr}, {"default true values for parameters on inner lists", "(1 2);a, (42 43);b", {{{{{Integer(1L), {}}, {Integer(2L), {}}}, {BooleanParam("a", true)}}, {{{Integer(42L), {}}, {Integer(43L), {}}}, {BooleanParam("b", true)}}}}, nullptr}, {"extra whitespace before semicolon in parameters on inner list member", "(a;b ;c b)", std::nullopt, nullptr}, {"extra whitespace between parameters on inner list member", "(a;b; c b)", {{{{{Token("a"), {BooleanParam("b", true), BooleanParam("c", true)}}, {Token("b"), {}}}, {}}}}, "(a;b;c b)"}, {"extra whitespace before semicolon in parameters on inner list", "(a b);c ;d, (e)", std::nullopt, nullptr}, {"extra whitespace between parameters on inner list", "(a b);c; d, (e)", {{{{{Token("a"), {}}, {Token("b"), {}}}, {BooleanParam("c", true), BooleanParam("d", true)}}, {{{Token("e"), {}}}, {}}}}, "(a b);c;d, (e)"}, }; const struct DictionaryTestCase { const char* name; const char* raw; const std::optional<Dictionary> expected; const char* canonical; } dictionary_test_cases[] = { {"basic dictionary", "en=\"Applepie\", da=:aGVsbG8=:", {Dictionary{{{"en", {Item("Applepie"), {}}}, {"da", {Item("hello", Item::kByteSequenceType), {}}}}}}, nullptr}, {"tab separated dictionary", "a=1\t,\tb=2", {Dictionary{{{"a", {Integer(1L), {}}}, {"b", {Integer(2L), {}}}}}}, "a=1, b=2"}, {"missing value with params dictionary", "a=1, b;foo=9, c=3", {Dictionary{{{"a", {Integer(1L), {}}}, {"b", {Item(true), {Param("foo", 9)}}}, {"c", {Integer(3L), {}}}}}}, nullptr}, {"parameterised inner list member dict", "a=(\"1\";b=1;c=?0 \"2\");d=\"e\"", {Dictionary{{{"a", {{{Item("1"), {Param("b", 1), BooleanParam("c", false)}}, {Item("2"), {}}}, {Param("d", "e")}}}}}}, nullptr}, {"explicit true value with parameter", "a=?1;b=1", {Dictionary{{{"a", {Item(true), {Param("b", 1)}}}}}}, "a;b=1"}, {"implicit true value with parameter", "a;b=1", {Dictionary{{{"a", {Item(true), {Param("b", 1)}}}}}}, nullptr}, {"implicit true value with implicitly-valued parameter", "a;b", {Dictionary{{{"a", {Item(true), {BooleanParam("b", true)}}}}}}, nullptr}, }; } TEST(StructuredHeaderTest, ParseBareItem) { for (const auto& c : item_test_cases) { SCOPED_TRACE(c.name); std::optional<Item> result = ParseBareItem(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, ParseItem) { for (const auto& c : parameterized_item_test_cases) { SCOPED_TRACE(c.name); std::optional<ParameterizedItem> result = ParseItem(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, ParseSH09Item) { for (const auto& c : sh09_item_test_cases) { SCOPED_TRACE(c.name); std::optional<ListOfLists> result = ParseListOfLists(c.raw); if (c.expected.has_value()) { EXPECT_TRUE(result.has_value()); EXPECT_EQ(result->size(), 1UL); EXPECT_EQ((*result)[0].size(), 1UL); EXPECT_EQ((*result)[0][0], c.expected); } else { EXPECT_FALSE(result.has_value()); } } } TEST(StructuredHeaderTest, SH09HighPrecisionFloats) { std::optional<ListOfLists> result = ParseListOfLists("1.03125;-1.03125;12345678901234.5;-12345678901234.5"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(*result, (ListOfLists{{Item(1.03125), Item(-1.03125), Item(12345678901234.5), Item(-12345678901234.5)}})); result = ParseListOfLists("123456789012345.0"); EXPECT_FALSE(result.has_value()); result = ParseListOfLists("-123456789012345.0"); EXPECT_FALSE(result.has_value()); } TEST(StructuredHeaderTest, ParseListOfLists) { static const struct TestCase { const char* name; const char* raw; ListOfLists expected; } cases[] = { {"basic list of lists", "1;2, 42;43", {{Integer(1L), Integer(2L)}, {Integer(42L), Integer(43L)}}}, {"empty list of lists", "", {}}, {"single item list of lists", "42", {{Integer(42L)}}}, {"no whitespace list of lists", "1,42", {{Integer(1L)}, {Integer(42L)}}}, {"no inner whitespace list of lists", "1;2, 42;43", {{Integer(1L), Integer(2L)}, {Integer(42L), Integer(43L)}}}, {"extra whitespace list of lists", "1 , 42", {{Integer(1L)}, {Integer(42L)}}}, {"extra inner whitespace list of lists", "1 ; 2,42 ; 43", {{Integer(1L), Integer(2L)}, {Integer(42L), Integer(43L)}}}, {"trailing comma list of lists", "1;2, 42,", {}}, {"trailing semicolon list of lists", "1;2, 42;43;", {}}, {"leading comma list of lists", ",1;2, 42", {}}, {"leading semicolon list of lists", ";1;2, 42;43", {}}, {"empty item list of lists", "1,,42", {}}, {"empty inner item list of lists", "1;;2,42", {}}, }; for (const auto& c : cases) { SCOPED_TRACE(c.name); std::optional<ListOfLists> result = ParseListOfLists(c.raw); if (!c.expected.empty()) { EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, c.expected); } else { EXPECT_FALSE(result.has_value()); } } } TEST(StructuredHeaderTest, ParseParameterisedList) { static const struct TestCase { const char* name; const char* raw; ParameterisedList expected; } cases[] = { {"basic param-list", "abc_123;a=1;b=2; cdef_456, ghi;q=\"9\";r=\"w\"", { {Token("abc_123"), {Param("a", 1), Param("b", 2), NullParam("cdef_456")}}, {Token("ghi"), {Param("q", "9"), Param("r", "w")}}, }}, {"empty param-list", "", {}}, {"single item param-list", "text/html;q=1", {{Token("text/html"), {Param("q", 1)}}}}, {"empty param-list", "", {}}, {"no whitespace param-list", "text/html,text/plain;q=1", {{Token("text/html"), {}}, {Token("text/plain"), {Param("q", 1)}}}}, {"whitespace before = param-list", "text/html, text/plain;q =1", {}}, {"whitespace after = param-list", "text/html, text/plain;q= 1", {}}, {"extra whitespace param-list", "text/html , text/plain ; q=1", {{Token("text/html"), {}}, {Token("text/plain"), {Param("q", 1)}}}}, {"duplicate key", "abc;a=1;b=2;a=1", {}}, {"numeric key", "abc;a=1;1b=2;c=1", {}}, {"uppercase key", "abc;a=1;B=2;c=1", {}}, {"bad key", "abc;a=1;b!=2;c=1", {}}, {"another bad key", "abc;a=1;b==2;c=1", {}}, {"empty key name", "abc;a=1;=2;c=1", {}}, {"empty parameter", "abc;a=1;;c=1", {}}, {"empty list item", "abc;a=1,,def;b=1", {}}, {"extra semicolon", "abc;a=1;b=1;", {}}, {"extra comma", "abc;a=1,def;b=1,", {}}, {"leading semicolon", ";abc;a=1", {}}, {"leading comma", ",abc;a=1", {}}, }; for (const auto& c : cases) { SCOPED_TRACE(c.name); std::optional<ParameterisedList> result = ParseParameterisedList(c.raw); if (c.expected.empty()) { EXPECT_FALSE(result.has_value()); continue; } EXPECT_TRUE(result.has_value()); EXPECT_EQ(result->size(), c.expected.size()); if (result->size() == c.expected.size()) { for (size_t i = 0; i < c.expected.size(); ++i) { EXPECT_EQ((*result)[i], c.expected[i]); } } } } TEST(StructuredHeaderTest, ParseList) { for (const auto& c : list_test_cases) { SCOPED_TRACE(c.name); std::optional<List> result = ParseList(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, ParseDictionary) { for (const auto& c : dictionary_test_cases) { SCOPED_TRACE(c.name); std::optional<Dictionary> result = ParseDictionary(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, SerializeItem) { for (const auto& c : item_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeItem(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, SerializeParameterizedItem) { for (const auto& c : parameterized_item_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeItem(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, UnserializableItems) { EXPECT_FALSE(SerializeItem(Item()).has_value()); } TEST(StructuredHeaderTest, UnserializableTokens) { static const struct UnserializableString { const char* name; const char* value; } bad_tokens[] = { {"empty token", ""}, {"contains high ascii", "a\xff"}, {"contains nonprintable character", "a\x7f"}, {"contains C0", "a\x01"}, {"UTF-8 encoded", "a\xc3\xa9"}, {"contains TAB", "a\t"}, {"contains LF", "a\n"}, {"contains CR", "a\r"}, {"contains SP", "a "}, {"begins with digit", "9token"}, {"begins with hyphen", "-token"}, {"begins with LF", "\ntoken"}, {"begins with SP", " token"}, {"begins with colon", ":token"}, {"begins with percent", "%token"}, {"begins with period", ".token"}, {"begins with slash", "/token"}, }; for (const auto& bad_token : bad_tokens) { SCOPED_TRACE(bad_token.name); std::optional<std::string> serialization = SerializeItem(Token(bad_token.value)); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, UnserializableKeys) { static const struct UnserializableString { const char* name; const char* value; } bad_keys[] = { {"empty key", ""}, {"contains high ascii", "a\xff"}, {"contains nonprintable character", "a\x7f"}, {"contains C0", "a\x01"}, {"UTF-8 encoded", "a\xc3\xa9"}, {"contains TAB", "a\t"}, {"contains LF", "a\n"}, {"contains CR", "a\r"}, {"contains SP", "a "}, {"begins with uppercase", "Atoken"}, {"begins with digit", "9token"}, {"begins with hyphen", "-token"}, {"begins with LF", "\ntoken"}, {"begins with SP", " token"}, {"begins with colon", ":token"}, {"begins with percent", "%token"}, {"begins with period", ".token"}, {"begins with slash", "/token"}, }; for (const auto& bad_key : bad_keys) { SCOPED_TRACE(bad_key.name); std::optional<std::string> serialization = SerializeItem(ParameterizedItem("a", {{bad_key.value, "a"}})); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, UnserializableStrings) { static const struct UnserializableString { const char* name; const char* value; } bad_strings[] = { {"contains high ascii", "a\xff"}, {"contains nonprintable character", "a\x7f"}, {"UTF-8 encoded", "a\xc3\xa9"}, {"contains TAB", "a\t"}, {"contains LF", "a\n"}, {"contains CR", "a\r"}, {"contains C0", "a\x01"}, }; for (const auto& bad_string : bad_strings) { SCOPED_TRACE(bad_string.name); std::optional<std::string> serialization = SerializeItem(Item(bad_string.value)); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, UnserializableIntegers) { EXPECT_FALSE(SerializeItem(Integer(1e15L)).has_value()); EXPECT_FALSE(SerializeItem(Integer(-1e15L)).has_value()); } TEST(StructuredHeaderTest, UnserializableDecimals) { for (double value : {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(), 1e12, 1e12 - 0.0001, 1e12 - 0.0005, -1e12, -1e12 + 0.0001, -1e12 + 0.0005}) { auto x = SerializeItem(Item(value)); EXPECT_FALSE(SerializeItem(Item(value)).has_value()); } } TEST(StructuredHeaderTest, SerializeUnparseableDecimals) { struct UnparseableDecimal { const char* name; double value; const char* canonical; } float_test_cases[] = { {"negative 0", -0.0, "0.0"}, {"0.0001", 0.0001, "0.0"}, {"0.0000001", 0.0000001, "0.0"}, {"1.0001", 1.0001, "1.0"}, {"1.0009", 1.0009, "1.001"}, {"round positive odd decimal", 0.0015, "0.002"}, {"round positive even decimal", 0.0025, "0.002"}, {"round negative odd decimal", -0.0015, "-0.002"}, {"round negative even decimal", -0.0025, "-0.002"}, {"round decimal up to integer part", 9.9995, "10.0"}, {"subnormal numbers", std::numeric_limits<double>::denorm_min(), "0.0"}, {"round up to 10 digits", 1e9 - 0.0000001, "1000000000.0"}, {"round up to 11 digits", 1e10 - 0.000001, "10000000000.0"}, {"round up to 12 digits", 1e11 - 0.00001, "100000000000.0"}, {"largest serializable float", nextafter(1e12 - 0.0005, 0), "999999999999.999"}, {"largest serializable negative float", -nextafter(1e12 - 0.0005, 0), "-999999999999.999"}, {"float rounds up to next int", 3.9999999, "4.0"}, {"don't double round", 3.99949, "3.999"}, {"don't double round", 123456789.99949, "123456789.999"}, }; for (const auto& test_case : float_test_cases) { SCOPED_TRACE(test_case.name); std::optional<std::string> serialization = SerializeItem(Item(test_case.value)); EXPECT_TRUE(serialization.has_value()); EXPECT_EQ(*serialization, test_case.canonical); } } TEST(StructuredHeaderTest, SerializeList) { for (const auto& c : list_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeList(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, UnserializableLists) { static const struct UnserializableList { const char* name; const List value; } bad_lists[] = { {"Null item as member", {{Item(), {}}}}, {"Unserializable item as member", {{Token("\n"), {}}}}, {"Key is empty", {{Token("abc"), {Param("", 1)}}}}, {"Key containswhitespace", {{Token("abc"), {Param("a\n", 1)}}}}, {"Key contains UTF8", {{Token("abc"), {Param("a\xc3\xa9", 1)}}}}, {"Key contains unprintable characters", {{Token("abc"), {Param("a\x7f", 1)}}}}, {"Key contains disallowed characters", {{Token("abc"), {Param("a:", 1)}}}}, {"Param value is unserializable", {{Token("abc"), {{"a", Token("\n")}}}}}, {"Inner list contains unserializable item", {{std::vector<ParameterizedItem>{{Token("\n"), {}}}, {}}}}, }; for (const auto& bad_list : bad_lists) { SCOPED_TRACE(bad_list.name); std::optional<std::string> serialization = SerializeList(bad_list.value); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, SerializeDictionary) { for (const auto& c : dictionary_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeDictionary(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, DictionaryConstructors) { const std::string key0 = "key0"; const std::string key1 = "key1"; const ParameterizedMember member0{Item("Applepie"), {}}; const ParameterizedMember member1{Item("hello", Item::kByteSequenceType), {}}; Dictionary dict; EXPECT_TRUE(dict.empty()); EXPECT_EQ(0U, dict.size()); dict[key0] = member0; EXPECT_FALSE(dict.empty()); EXPECT_EQ(1U, dict.size()); const Dictionary dict_copy = dict; EXPECT_FALSE(dict_copy.empty()); EXPECT_EQ(1U, dict_copy.size()); EXPECT_EQ(dict, dict_copy); const Dictionary dict_init{{{key0, member0}, {key1, member1}}}; EXPECT_FALSE(dict_init.empty()); EXPECT_EQ(2U, dict_init.size()); EXPECT_EQ(member0, dict_init.at(key0)); EXPECT_EQ(member1, dict_init.at(key1)); } TEST(StructuredHeaderTest, DictionaryClear) { const std::string key0 = "key0"; const ParameterizedMember member0{Item("Applepie"), {}}; Dictionary dict({{key0, member0}}); EXPECT_EQ(1U, dict.size()); EXPECT_FALSE(dict.empty()); EXPECT_TRUE(dict.contains(key0)); dict.clear(); EXPECT_EQ(0U, dict.size()); EXPECT_TRUE(dict.empty()); EXPECT_FALSE(dict.contains(key0)); } TEST(StructuredHeaderTest, DictionaryAccessors) { const std::string key0 = "key0"; const std::string key1 = "key1"; const ParameterizedMember nonempty_member0{Item("Applepie"), {}}; const ParameterizedMember nonempty_member1{ Item("hello", Item::kByteSequenceType), {}}; const ParameterizedMember empty_member; Dictionary dict{{{key0, nonempty_member0}}}; EXPECT_TRUE(dict.contains(key0)); EXPECT_EQ(nonempty_member0, dict[key0]); EXPECT_EQ(&dict[key0], &dict.at(key0)); EXPECT_EQ(&dict[key0], &dict[0]); EXPECT_EQ(&dict[key0], &dict.at(0)); { auto it = dict.find(key0); ASSERT_TRUE(it != dict.end()); EXPECT_EQ(it->first, key0); EXPECT_EQ(it->second, nonempty_member0); } ASSERT_FALSE(dict.contains(key1)); EXPECT_TRUE(dict.find(key1) == dict.end()); ParameterizedMember& member1 = dict[key1]; EXPECT_TRUE(dict.contains(key1)); EXPECT_EQ(empty_member, member1); EXPECT_EQ(&member1, &dict[key1]); EXPECT_EQ(&member1, &dict.at(key1)); EXPECT_EQ(&member1, &dict[1]); EXPECT_EQ(&member1, &dict.at(1)); member1 = nonempty_member1; EXPECT_EQ(nonempty_member1, dict[key1]); EXPECT_EQ(&dict[key1], &dict.at(key1)); EXPECT_EQ(&dict[key1], &dict[1]); EXPECT_EQ(&dict[key1], &dict.at(1)); const Dictionary& dict_ref = dict; EXPECT_EQ(&member1, &dict_ref.at(key1)); EXPECT_EQ(&member1, &dict_ref[1]); EXPECT_EQ(&member1, &dict_ref.at(1)); } TEST(StructuredHeaderTest, UnserializableDictionary) { static const struct UnserializableDictionary { const char* name; const Dictionary value; } bad_dictionaries[] = { {"Unserializable dict key", Dictionary{{{"ABC", {Token("abc"), {}}}}}}, {"Dictionary item is unserializable", Dictionary{{{"abc", {Token("abc="), {}}}}}}, {"Param value is unserializable", Dictionary{{{"abc", {Token("abc"), {{"a", Token("\n")}}}}}}}, {"Dictionary inner-list contains unserializable item", Dictionary{ {{"abc", {std::vector<ParameterizedItem>{{Token("abc="), {}}}, {}}}}}}, }; for (const auto& bad_dictionary : bad_dictionaries) { SCOPED_TRACE(bad_dictionary.name); std::optional<std::string> serialization = SerializeDictionary(bad_dictionary.value); EXPECT_FALSE(serialization.has_value()) << *serialization; } } } }
188
cpp
google/quiche
quiche_data_reader
quiche/common/quiche_data_reader.cc
quiche/common/quiche_data_reader_test.cc
#ifndef QUICHE_COMMON_QUICHE_DATA_READER_H_ #define QUICHE_COMMON_QUICHE_DATA_READER_H_ #include <cstddef> #include <cstdint> #include <limits> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_endian.h" namespace quiche { class QUICHE_EXPORT QuicheDataReader { public: explicit QuicheDataReader(absl::string_view data); QuicheDataReader(const char* data, const size_t len); QuicheDataReader(const char* data, const size_t len, quiche::Endianness endianness); QuicheDataReader(const QuicheDataReader&) = delete; QuicheDataReader& operator=(const QuicheDataReader&) = delete; ~QuicheDataReader() {} bool ReadUInt8(uint8_t* result); bool ReadUInt16(uint16_t* result); bool ReadUInt24(uint32_t* result); bool ReadUInt32(uint32_t* result); bool ReadUInt64(uint64_t* result); bool ReadBytesToUInt64(size_t num_bytes, uint64_t* result); bool ReadStringPiece16(absl::string_view* result); bool ReadStringPiece8(absl::string_view* result); bool ReadStringPiece(absl::string_view* result, size_t size); bool ReadTag(uint32_t* tag); bool ReadDecimal64(size_t num_digits, uint64_t* result); QuicheVariableLengthIntegerLength PeekVarInt62Length(); bool ReadVarInt62(uint64_t* result); bool ReadStringPieceVarInt62(absl::string_view* result); bool ReadStringVarInt62(std::string& result); absl::string_view ReadRemainingPayload(); absl::string_view PeekRemainingPayload() const; absl::string_view FullPayload() const; absl::string_view PreviouslyReadPayload() const; bool ReadBytes(void* result, size_t size); bool Seek(size_t size); bool IsDoneReading() const; size_t BytesRemaining() const; bool TruncateRemaining(size_t truncation_length); uint8_t PeekByte() const; std::string DebugString() const; protected: bool CanRead(size_t bytes) const; void OnFailure(); const char* data() const { return data_; } size_t pos() const { return pos_; } void AdvancePos(size_t amount) { QUICHE_DCHECK_LE(pos_, std::numeric_limits<size_t>::max() - amount); QUICHE_DCHECK_LE(pos_, len_ - amount); pos_ += amount; } quiche::Endianness endianness() const { return endianness_; } private: const char* data_; size_t len_; size_t pos_; quiche::Endianness endianness_; }; } #endif #include "quiche/common/quiche_data_reader.h" #include <cstring> #include <string> #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_endian.h" namespace quiche { QuicheDataReader::QuicheDataReader(absl::string_view data) : QuicheDataReader(data.data(), data.length(), quiche::NETWORK_BYTE_ORDER) { } QuicheDataReader::QuicheDataReader(const char* data, const size_t len) : QuicheDataReader(data, len, quiche::NETWORK_BYTE_ORDER) {} QuicheDataReader::QuicheDataReader(const char* data, const size_t len, quiche::Endianness endianness) : data_(data), len_(len), pos_(0), endianness_(endianness) {} bool QuicheDataReader::ReadUInt8(uint8_t* result) { return ReadBytes(result, sizeof(*result)); } bool QuicheDataReader::ReadUInt16(uint16_t* result) { if (!ReadBytes(result, sizeof(*result))) { return false; } if (endianness_ == quiche::NETWORK_BYTE_ORDER) { *result = quiche::QuicheEndian::NetToHost16(*result); } return true; } bool QuicheDataReader::ReadUInt24(uint32_t* result) { if (endianness_ != quiche::NETWORK_BYTE_ORDER) { QUICHE_BUG(QuicheDataReader_ReadUInt24_NotImplemented); return false; } *result = 0; if (!ReadBytes(reinterpret_cast<char*>(result) + 1, 3u)) { return false; } *result = quiche::QuicheEndian::NetToHost32(*result); return true; } bool QuicheDataReader::ReadUInt32(uint32_t* result) { if (!ReadBytes(result, sizeof(*result))) { return false; } if (endianness_ == quiche::NETWORK_BYTE_ORDER) { *result = quiche::QuicheEndian::NetToHost32(*result); } return true; } bool QuicheDataReader::ReadUInt64(uint64_t* result) { if (!ReadBytes(result, sizeof(*result))) { return false; } if (endianness_ == quiche::NETWORK_BYTE_ORDER) { *result = quiche::QuicheEndian::NetToHost64(*result); } return true; } bool QuicheDataReader::ReadBytesToUInt64(size_t num_bytes, uint64_t* result) { *result = 0u; if (num_bytes > sizeof(*result)) { return false; } if (endianness_ == quiche::HOST_BYTE_ORDER) { return ReadBytes(result, num_bytes); } if (!ReadBytes(reinterpret_cast<char*>(result) + sizeof(*result) - num_bytes, num_bytes)) { return false; } *result = quiche::QuicheEndian::NetToHost64(*result); return true; } bool QuicheDataReader::ReadStringPiece16(absl::string_view* result) { uint16_t result_len; if (!ReadUInt16(&result_len)) { return false; } return ReadStringPiece(result, result_len); } bool QuicheDataReader::ReadStringPiece8(absl::string_view* result) { uint8_t result_len; if (!ReadUInt8(&result_len)) { return false; } return ReadStringPiece(result, result_len); } bool QuicheDataReader::ReadStringPiece(absl::string_view* result, size_t size) { if (!CanRead(size)) { OnFailure(); return false; } *result = absl::string_view(data_ + pos_, size); pos_ += size; return true; } bool QuicheDataReader::ReadTag(uint32_t* tag) { return ReadBytes(tag, sizeof(*tag)); } bool QuicheDataReader::ReadDecimal64(size_t num_digits, uint64_t* result) { absl::string_view digits; if (!ReadStringPiece(&digits, num_digits)) { return false; } return absl::SimpleAtoi(digits, result); } QuicheVariableLengthIntegerLength QuicheDataReader::PeekVarInt62Length() { QUICHE_DCHECK_EQ(endianness(), NETWORK_BYTE_ORDER); const unsigned char* next = reinterpret_cast<const unsigned char*>(data() + pos()); if (BytesRemaining() == 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_0; } return static_cast<QuicheVariableLengthIntegerLength>( 1 << ((*next & 0b11000000) >> 6)); } bool QuicheDataReader::ReadVarInt62(uint64_t* result) { QUICHE_DCHECK_EQ(endianness(), quiche::NETWORK_BYTE_ORDER); size_t remaining = BytesRemaining(); const unsigned char* next = reinterpret_cast<const unsigned char*>(data() + pos()); if (remaining != 0) { switch (*next & 0xc0) { case 0xc0: if (remaining >= 8) { *result = (static_cast<uint64_t>((*(next)) & 0x3f) << 56) + (static_cast<uint64_t>(*(next + 1)) << 48) + (static_cast<uint64_t>(*(next + 2)) << 40) + (static_cast<uint64_t>(*(next + 3)) << 32) + (static_cast<uint64_t>(*(next + 4)) << 24) + (static_cast<uint64_t>(*(next + 5)) << 16) + (static_cast<uint64_t>(*(next + 6)) << 8) + (static_cast<uint64_t>(*(next + 7)) << 0); AdvancePos(8); return true; } return false; case 0x80: if (remaining >= 4) { *result = (((*(next)) & 0x3f) << 24) + (((*(next + 1)) << 16)) + (((*(next + 2)) << 8)) + (((*(next + 3)) << 0)); AdvancePos(4); return true; } return false; case 0x40: if (remaining >= 2) { *result = (((*(next)) & 0x3f) << 8) + (*(next + 1)); AdvancePos(2); return true; } return false; case 0x00: *result = (*next) & 0x3f; AdvancePos(1); return true; } } return false; } bool QuicheDataReader::ReadStringPieceVarInt62(absl::string_view* result) { uint64_t result_length; if (!ReadVarInt62(&result_length)) { return false; } return ReadStringPiece(result, result_length); } bool QuicheDataReader::ReadStringVarInt62(std::string& result) { absl::string_view result_view; bool success = ReadStringPieceVarInt62(&result_view); result = std::string(result_view); return success; } absl::string_view QuicheDataReader::ReadRemainingPayload() { absl::string_view payload = PeekRemainingPayload(); pos_ = len_; return payload; } absl::string_view QuicheDataReader::PeekRemainingPayload() const { return absl::string_view(data_ + pos_, len_ - pos_); } absl::string_view QuicheDataReader::FullPayload() const { return absl::string_view(data_, len_); } absl::string_view QuicheDataReader::PreviouslyReadPayload() const { return absl::string_view(data_, pos_); } bool QuicheDataReader::ReadBytes(void* result, size_t size) { if (!CanRead(size)) { OnFailure(); return false; } memcpy(result, data_ + pos_, size); pos_ += size; return true; } bool QuicheDataReader::Seek(size_t size) { if (!CanRead(size)) { OnFailure(); return false; } pos_ += size; return true; } bool QuicheDataReader::IsDoneReading() const { return len_ == pos_; } size_t QuicheDataReader::BytesRemaining() const { if (pos_ > len_) { QUICHE_BUG(quiche_reader_pos_out_of_bound) << "QUIC reader pos out of bound: " << pos_ << ", len: " << len_; return 0; } return len_ - pos_; } bool QuicheDataReader::TruncateRemaining(size_t truncation_length) { if (truncation_length > BytesRemaining()) { return false; } len_ = pos_ + truncation_length; return true; } bool QuicheDataReader::CanRead(size_t bytes) const { return bytes <= (len_ - pos_); } void QuicheDataReader::OnFailure() { pos_ = len_; } uint8_t QuicheDataReader::PeekByte() const { if (pos_ >= len_) { QUICHE_LOG(FATAL) << "Reading is done, cannot peek next byte. Tried to read pos = " << pos_ << " buffer length = " << len_; return 0; } return data_[pos_]; } std::string QuicheDataReader::DebugString() const { return absl::StrCat(" { length: ", len_, ", position: ", pos_, " }"); } #undef ENDPOINT }
#include "quiche/common/quiche_data_reader.h" #include <cstdint> #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_endian.h" namespace quiche { TEST(QuicheDataReaderTest, ReadUInt16) { const uint16_t kData[] = { QuicheEndian::HostToNet16(1), QuicheEndian::HostToNet16(1 << 15), }; QuicheDataReader reader(reinterpret_cast<const char*>(kData), sizeof(kData)); EXPECT_FALSE(reader.IsDoneReading()); uint16_t uint16_val; EXPECT_TRUE(reader.ReadUInt16(&uint16_val)); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ(1, uint16_val); EXPECT_TRUE(reader.ReadUInt16(&uint16_val)); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ(1 << 15, uint16_val); } TEST(QuicheDataReaderTest, ReadUInt32) { const uint32_t kData[] = { QuicheEndian::HostToNet32(1), QuicheEndian::HostToNet32(0x80000000), }; QuicheDataReader reader(reinterpret_cast<const char*>(kData), ABSL_ARRAYSIZE(kData) * sizeof(uint32_t)); EXPECT_FALSE(reader.IsDoneReading()); uint32_t uint32_val; EXPECT_TRUE(reader.ReadUInt32(&uint32_val)); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ(1u, uint32_val); EXPECT_TRUE(reader.ReadUInt32(&uint32_val)); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ(1u << 31, uint32_val); } TEST(QuicheDataReaderTest, ReadStringPiece16) { const char kData[] = { 0x00, 0x02, 0x48, 0x69, 0x00, 0x10, 0x54, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2c, 0x20, 0x31, 0x2c, 0x20, 0x32, 0x2c, 0x20, 0x33, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); absl::string_view stringpiece_val; EXPECT_TRUE(reader.ReadStringPiece16(&stringpiece_val)); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ(0, stringpiece_val.compare("Hi")); EXPECT_TRUE(reader.ReadStringPiece16(&stringpiece_val)); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ(0, stringpiece_val.compare("Testing, 1, 2, 3")); } TEST(QuicheDataReaderTest, ReadUInt16WithBufferTooSmall) { const char kData[] = { 0x00, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadUInt32WithBufferTooSmall) { const char kData[] = { 0x00, 0x00, 0x00, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); uint32_t uint32_val; EXPECT_FALSE(reader.ReadUInt32(&uint32_val)); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadStringPiece16WithBufferTooSmall) { const char kData[] = { 0x00, 0x03, 0x48, 0x69, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); absl::string_view stringpiece_val; EXPECT_FALSE(reader.ReadStringPiece16(&stringpiece_val)); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadStringPiece16WithBufferWayTooSmall) { const char kData[] = { 0x00, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); absl::string_view stringpiece_val; EXPECT_FALSE(reader.ReadStringPiece16(&stringpiece_val)); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadBytes) { const char kData[] = { 0x66, 0x6f, 0x6f, 0x48, 0x69, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); char dest1[3] = {}; EXPECT_TRUE(reader.ReadBytes(&dest1, ABSL_ARRAYSIZE(dest1))); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ("foo", absl::string_view(dest1, ABSL_ARRAYSIZE(dest1))); char dest2[2] = {}; EXPECT_TRUE(reader.ReadBytes(&dest2, ABSL_ARRAYSIZE(dest2))); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ("Hi", absl::string_view(dest2, ABSL_ARRAYSIZE(dest2))); } TEST(QuicheDataReaderTest, ReadBytesWithBufferTooSmall) { const char kData[] = { 0x01, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); char dest[ABSL_ARRAYSIZE(kData) + 2] = {}; EXPECT_FALSE(reader.ReadBytes(&dest, ABSL_ARRAYSIZE(kData) + 1)); EXPECT_STREQ("", dest); } }
189
cpp
google/quiche
quiche_file_utils
quiche/common/platform/api/quiche_file_utils.cc
quiche/common/platform/api/quiche_file_utils_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_FILE_UTILS_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_FILE_UTILS_H_ #include <optional> #include <string> #include <vector> #include "absl/strings/string_view.h" namespace quiche { std::string JoinPath(absl::string_view a, absl::string_view b); std::optional<std::string> ReadFileContents(absl::string_view file); bool EnumerateDirectory(absl::string_view path, std::vector<std::string>& directories, std::vector<std::string>& files); bool EnumerateDirectoryRecursively(absl::string_view path, std::vector<std::string>& files); } #endif #include "quiche/common/platform/api/quiche_file_utils.h" #include <optional> #include <string> #include <vector> #include "quiche_platform_impl/quiche_file_utils_impl.h" namespace quiche { std::string JoinPath(absl::string_view a, absl::string_view b) { return JoinPathImpl(a, b); } std::optional<std::string> ReadFileContents(absl::string_view file) { return ReadFileContentsImpl(file); } bool EnumerateDirectory(absl::string_view path, std::vector<std::string>& directories, std::vector<std::string>& files) { return EnumerateDirectoryImpl(path, directories, files); } bool EnumerateDirectoryRecursivelyInner(absl::string_view path, int recursion_limit, std::vector<std::string>& files) { if (recursion_limit < 0) { return false; } std::vector<std::string> local_files; std::vector<std::string> directories; if (!EnumerateDirectory(path, directories, local_files)) { return false; } for (const std::string& directory : directories) { if (!EnumerateDirectoryRecursivelyInner(JoinPath(path, directory), recursion_limit - 1, files)) { return false; } } for (const std::string& file : local_files) { files.push_back(JoinPath(path, file)); } return true; } bool EnumerateDirectoryRecursively(absl::string_view path, std::vector<std::string>& files) { constexpr int kRecursionLimit = 20; return EnumerateDirectoryRecursivelyInner(path, kRecursionLimit, files); } }
#include "quiche/common/platform/api/quiche_file_utils.h" #include <optional> #include <string> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/str_cat.h" #include "absl/strings/strip.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { using testing::UnorderedElementsAre; using testing::UnorderedElementsAreArray; TEST(QuicheFileUtilsTest, ReadFileContents) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/testfile"); std::optional<std::string> contents = ReadFileContents(path); ASSERT_TRUE(contents.has_value()); EXPECT_EQ(*contents, "This is a test file."); } TEST(QuicheFileUtilsTest, ReadFileContentsFileNotFound) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/file-that-does-not-exist"); std::optional<std::string> contents = ReadFileContents(path); EXPECT_FALSE(contents.has_value()); } TEST(QuicheFileUtilsTest, EnumerateDirectory) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir"); std::vector<std::string> dirs; std::vector<std::string> files; bool success = EnumerateDirectory(path, dirs, files); EXPECT_TRUE(success); EXPECT_THAT(files, UnorderedElementsAre("testfile", "README.md")); EXPECT_THAT(dirs, UnorderedElementsAre("a")); } TEST(QuicheFileUtilsTest, EnumerateDirectoryNoSuchDirectory) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/no-such-directory"); std::vector<std::string> dirs; std::vector<std::string> files; bool success = EnumerateDirectory(path, dirs, files); EXPECT_FALSE(success); } TEST(QuicheFileUtilsTest, EnumerateDirectoryNotADirectory) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/testfile"); std::vector<std::string> dirs; std::vector<std::string> files; bool success = EnumerateDirectory(path, dirs, files); EXPECT_FALSE(success); } TEST(QuicheFileUtilsTest, EnumerateDirectoryRecursively) { std::vector<std::string> expected_paths = {"a/b/c/d/e", "a/subdir/testfile", "a/z", "testfile", "README.md"}; std::string root_path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir"); for (std::string& path : expected_paths) { if (JoinPath("a", "b") == "a\\b") { absl::c_replace(path, '/', '\\'); } path = JoinPath(root_path, path); } std::vector<std::string> files; bool success = EnumerateDirectoryRecursively(root_path, files); EXPECT_TRUE(success); EXPECT_THAT(files, UnorderedElementsAreArray(expected_paths)); } } } }
190
cpp
google/quiche
quiche_hostname_utils
quiche/common/platform/api/quiche_hostname_utils.cc
quiche/common/platform/api/quiche_hostname_utils_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_HOSTNAME_UTILS_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_HOSTNAME_UTILS_H_ #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" namespace quiche { class QUICHE_EXPORT QuicheHostnameUtils { public: QuicheHostnameUtils() = delete; static bool IsValidSNI(absl::string_view sni); static std::string NormalizeHostname(absl::string_view hostname); }; } #endif #include "quiche/common/platform/api/quiche_hostname_utils.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { std::string CanonicalizeHost(absl::string_view host, url::CanonHostInfo* host_info) { const url::Component raw_host_component(0, static_cast<int>(host.length())); std::string canon_host; url::StdStringCanonOutput canon_host_output(&canon_host); url::CanonicalizeHostVerbose(host.data(), raw_host_component, &canon_host_output, host_info); if (host_info->out_host.is_nonempty() && host_info->family != url::CanonHostInfo::BROKEN) { canon_host_output.Complete(); QUICHE_DCHECK_EQ(host_info->out_host.len, static_cast<int>(canon_host.length())); } else { canon_host.clear(); } return canon_host; } bool IsHostCharAlphanumeric(char c) { return ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')); } bool IsCanonicalizedHostCompliant(const std::string& host) { if (host.empty()) { return false; } bool in_component = false; bool most_recent_component_started_alphanumeric = false; for (char c : host) { if (!in_component) { most_recent_component_started_alphanumeric = IsHostCharAlphanumeric(c); if (!most_recent_component_started_alphanumeric && (c != '-') && (c != '_')) { return false; } in_component = true; } else if (c == '.') { in_component = false; } else if (!IsHostCharAlphanumeric(c) && (c != '-') && (c != '_')) { return false; } } return most_recent_component_started_alphanumeric; } } bool QuicheHostnameUtils::IsValidSNI(absl::string_view sni) { url::CanonHostInfo host_info; std::string canonicalized_host = CanonicalizeHost(sni, &host_info); return !host_info.IsIPAddress() && IsCanonicalizedHostCompliant(canonicalized_host); } std::string QuicheHostnameUtils::NormalizeHostname(absl::string_view hostname) { url::CanonHostInfo host_info; std::string host = CanonicalizeHost(hostname, &host_info); size_t host_end = host.length(); while (host_end != 0 && host[host_end - 1] == '.') { host_end--; } if (host_end != host.length()) { host.erase(host_end, host.length() - host_end); } return host; } }
#include "quiche/common/platform/api/quiche_hostname_utils.h" #include <string> #include "absl/base/macros.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { class QuicheHostnameUtilsTest : public QuicheTest {}; TEST_F(QuicheHostnameUtilsTest, IsValidSNI) { EXPECT_FALSE(QuicheHostnameUtils::IsValidSNI("192.168.0.1")); EXPECT_TRUE(QuicheHostnameUtils::IsValidSNI("somedomain")); EXPECT_TRUE(QuicheHostnameUtils::IsValidSNI("some_domain.com")); EXPECT_FALSE(QuicheHostnameUtils::IsValidSNI("")); EXPECT_TRUE(QuicheHostnameUtils::IsValidSNI("test.google.com")); } TEST_F(QuicheHostnameUtilsTest, NormalizeHostname) { struct { const char *input, *expected; } tests[] = { { "www.google.com", "www.google.com", }, { "WWW.GOOGLE.COM", "www.google.com", }, { "www.google.com.", "www.google.com", }, { "www.google.COM.", "www.google.com", }, { "www.google.com..", "www.google.com", }, { "www.google.com........", "www.google.com", }, { "", "", }, { ".", "", }, { "........", "", }, }; for (size_t i = 0; i < ABSL_ARRAYSIZE(tests); ++i) { EXPECT_EQ(std::string(tests[i].expected), QuicheHostnameUtils::NormalizeHostname(tests[i].input)); } if (GoogleUrlSupportsIdnaForTest()) { EXPECT_EQ("xn--54q.google.com", QuicheHostnameUtils::NormalizeHostname( "\xe5\x85\x89.google.com")); } else { EXPECT_EQ( "", QuicheHostnameUtils::NormalizeHostname("\xe5\x85\x89.google.com")); } } } } }
191
cpp
google/quiche
http_header_block
quiche/common/http/http_header_block.cc
quiche/common/http/http_header_block_test.cc
#ifndef QUICHE_COMMON_HTTP_HTTP_HEADER_BLOCK_H_ #define QUICHE_COMMON_HTTP_HTTP_HEADER_BLOCK_H_ #include <stddef.h> #include <functional> #include <list> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/container/inlined_vector.h" #include "absl/strings/string_view.h" #include "quiche/common/http/http_header_storage.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_linked_hash_map.h" #include "quiche/common/quiche_text_utils.h" namespace quiche { namespace test { class HttpHeaderBlockPeer; class ValueProxyPeer; } #ifndef SPDY_HEADER_DEBUG #if !defined(NDEBUG) || defined(ADDRESS_SANITIZER) #define SPDY_HEADER_DEBUG 1 #else #define SPDY_HEADER_DEBUG 0 #endif #endif class QUICHE_EXPORT HttpHeaderBlock { private: class QUICHE_EXPORT HeaderValue { public: HeaderValue(HttpHeaderStorage* storage, absl::string_view key, absl::string_view initial_value); HeaderValue(HeaderValue&& other); HeaderValue& operator=(HeaderValue&& other); void set_storage(HttpHeaderStorage* storage); HeaderValue(const HeaderValue& other) = delete; HeaderValue& operator=(const HeaderValue& other) = delete; ~HeaderValue(); void Append(absl::string_view fragment); absl::string_view value() const { return as_pair().second; } const std::pair<absl::string_view, absl::string_view>& as_pair() const; size_t SizeEstimate() const { return size_; } private: absl::string_view ConsolidatedValue() const; mutable HttpHeaderStorage* storage_; mutable Fragments fragments_; mutable std::pair<absl::string_view, absl::string_view> pair_; size_t size_ = 0; size_t separator_size_ = 0; }; typedef quiche::QuicheLinkedHashMap<absl::string_view, HeaderValue, quiche::StringPieceCaseHash, quiche::StringPieceCaseEqual> MapType; public: typedef std::pair<absl::string_view, absl::string_view> value_type; enum class InsertResult { kInserted, kReplaced, }; class QUICHE_EXPORT iterator { public: typedef std::pair<absl::string_view, absl::string_view> value_type; typedef value_type& reference; typedef value_type* pointer; typedef std::forward_iterator_tag iterator_category; typedef MapType::iterator::difference_type difference_type; typedef const value_type& const_reference; typedef const value_type* const_pointer; explicit iterator(MapType::const_iterator it); iterator(const iterator& other); ~iterator(); const_reference operator*() const { #if SPDY_HEADER_DEBUG QUICHE_CHECK(!dereference_forbidden_); #endif return it_->second.as_pair(); } const_pointer operator->() const { return &(this->operator*()); } bool operator==(const iterator& it) const { return it_ == it.it_; } bool operator!=(const iterator& it) const { return !(*this == it); } iterator& operator++() { it_++; return *this; } iterator operator++(int) { auto ret = *this; this->operator++(); return ret; } #if SPDY_HEADER_DEBUG void forbid_dereference() { dereference_forbidden_ = true; } #endif private: MapType::const_iterator it_; #if SPDY_HEADER_DEBUG bool dereference_forbidden_ = false; #endif }; typedef iterator const_iterator; HttpHeaderBlock(); HttpHeaderBlock(const HttpHeaderBlock& other) = delete; HttpHeaderBlock(HttpHeaderBlock&& other); ~HttpHeaderBlock(); HttpHeaderBlock& operator=(const HttpHeaderBlock& other) = delete; HttpHeaderBlock& operator=(HttpHeaderBlock&& other); HttpHeaderBlock Clone() const; bool operator==(const HttpHeaderBlock& other) const; bool operator!=(const HttpHeaderBlock& other) const; std::string DebugString() const; iterator begin() { return wrap_iterator(map_.begin()); } iterator end() { return wrap_iterator(map_.end()); } const_iterator begin() const { return wrap_const_iterator(map_.begin()); } const_iterator end() const { return wrap_const_iterator(map_.end()); } bool empty() const { return map_.empty(); } size_t size() const { return map_.size(); } iterator find(absl::string_view key) { return wrap_iterator(map_.find(key)); } const_iterator find(absl::string_view key) const { return wrap_const_iterator(map_.find(key)); } bool contains(absl::string_view key) const { return find(key) != end(); } void erase(absl::string_view key); void clear(); InsertResult insert(const value_type& value); void AppendValueOrAddHeader(const absl::string_view key, const absl::string_view value); class QUICHE_EXPORT ValueProxy { public: ~ValueProxy(); ValueProxy(ValueProxy&& other); ValueProxy& operator=(ValueProxy&& other); ValueProxy(const ValueProxy& other) = delete; ValueProxy& operator=(const ValueProxy& other) = delete; ValueProxy& operator=(absl::string_view value); bool operator==(absl::string_view value) const; std::string as_string() const; private: friend class HttpHeaderBlock; friend class test::ValueProxyPeer; ValueProxy(HttpHeaderBlock* block, HttpHeaderBlock::MapType::iterator lookup_result, const absl::string_view key, size_t* spdy_header_block_value_size); HttpHeaderBlock* block_; HttpHeaderBlock::MapType::iterator lookup_result_; absl::string_view key_; size_t* spdy_header_block_value_size_; bool valid_; }; ABSL_MUST_USE_RESULT ValueProxy operator[](const absl::string_view key); size_t TotalBytesUsed() const { return key_size_ + value_size_; } private: friend class test::HttpHeaderBlockPeer; inline iterator wrap_iterator(MapType::const_iterator inner_iterator) const { #if SPDY_HEADER_DEBUG iterator outer_iterator(inner_iterator); if (inner_iterator == map_.end()) { outer_iterator.forbid_dereference(); } return outer_iterator; #else return iterator(inner_iterator); #endif } inline const_iterator wrap_const_iterator( MapType::const_iterator inner_iterator) const { #if SPDY_HEADER_DEBUG const_iterator outer_iterator(inner_iterator); if (inner_iterator == map_.end()) { outer_iterator.forbid_dereference(); } return outer_iterator; #else return iterator(inner_iterator); #endif } void AppendHeader(const absl::string_view key, const absl::string_view value); absl::string_view WriteKey(const absl::string_view key); size_t bytes_allocated() const; MapType map_; HttpHeaderStorage storage_; size_t key_size_ = 0; size_t value_size_ = 0; }; inline bool operator==(absl::string_view lhs, const HttpHeaderBlock::ValueProxy& rhs) { return rhs == lhs; } } #endif #include "quiche/common/http/http_header_block.h" #include <string.h> #include <algorithm> #include <ios> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { const size_t kInitialMapBuckets = 11; const char kCookieKey[] = "cookie"; const char kNullSeparator = 0; absl::string_view SeparatorForKey(absl::string_view key) { if (key == kCookieKey) { static absl::string_view cookie_separator = "; "; return cookie_separator; } else { return absl::string_view(&kNullSeparator, 1); } } } HttpHeaderBlock::HeaderValue::HeaderValue(HttpHeaderStorage* storage, absl::string_view key, absl::string_view initial_value) : storage_(storage), fragments_({initial_value}), pair_({key, {}}), size_(initial_value.size()), separator_size_(SeparatorForKey(key).size()) {} HttpHeaderBlock::HeaderValue::HeaderValue(HeaderValue&& other) : storage_(other.storage_), fragments_(std::move(other.fragments_)), pair_(std::move(other.pair_)), size_(other.size_), separator_size_(other.separator_size_) {} HttpHeaderBlock::HeaderValue& HttpHeaderBlock::HeaderValue::operator=( HeaderValue&& other) { storage_ = other.storage_; fragments_ = std::move(other.fragments_); pair_ = std::move(other.pair_); size_ = other.size_; separator_size_ = other.separator_size_; return *this; } void HttpHeaderBlock::HeaderValue::set_storage(HttpHeaderStorage* storage) { storage_ = storage; } HttpHeaderBlock::HeaderValue::~HeaderValue() = default; absl::string_view HttpHeaderBlock::HeaderValue::ConsolidatedValue() const { if (fragments_.empty()) { return absl::string_view(); } if (fragments_.size() > 1) { fragments_ = { storage_->WriteFragments(fragments_, SeparatorForKey(pair_.first))}; } return fragments_[0]; } void HttpHeaderBlock::HeaderValue::Append(absl::string_view fragment) { size_ += (fragment.size() + separator_size_); fragments_.push_back(fragment); } const std::pair<absl::string_view, absl::string_view>& HttpHeaderBlock::HeaderValue::as_pair() const { pair_.second = ConsolidatedValue(); return pair_; } HttpHeaderBlock::iterator::iterator(MapType::const_iterator it) : it_(it) {} HttpHeaderBlock::iterator::iterator(const iterator& other) = default; HttpHeaderBlock::iterator::~iterator() = default; HttpHeaderBlock::ValueProxy::ValueProxy( HttpHeaderBlock* block, HttpHeaderBlock::MapType::iterator lookup_result, const absl::string_view key, size_t* spdy_header_block_value_size) : block_(block), lookup_result_(lookup_result), key_(key), spdy_header_block_value_size_(spdy_header_block_value_size), valid_(true) {} HttpHeaderBlock::ValueProxy::ValueProxy(ValueProxy&& other) : block_(other.block_), lookup_result_(other.lookup_result_), key_(other.key_), spdy_header_block_value_size_(other.spdy_header_block_value_size_), valid_(true) { other.valid_ = false; } HttpHeaderBlock::ValueProxy& HttpHeaderBlock::ValueProxy::operator=( HttpHeaderBlock::ValueProxy&& other) { block_ = other.block_; lookup_result_ = other.lookup_result_; key_ = other.key_; valid_ = true; other.valid_ = false; spdy_header_block_value_size_ = other.spdy_header_block_value_size_; return *this; } HttpHeaderBlock::ValueProxy::~ValueProxy() { if (valid_ && lookup_result_ == block_->map_.end()) { block_->storage_.Rewind(key_); } } HttpHeaderBlock::ValueProxy& HttpHeaderBlock::ValueProxy::operator=( absl::string_view value) { *spdy_header_block_value_size_ += value.size(); HttpHeaderStorage* storage = &block_->storage_; if (lookup_result_ == block_->map_.end()) { QUICHE_DVLOG(1) << "Inserting: (" << key_ << ", " << value << ")"; lookup_result_ = block_->map_ .emplace(std::make_pair( key_, HeaderValue(storage, key_, storage->Write(value)))) .first; } else { QUICHE_DVLOG(1) << "Updating key: " << key_ << " with value: " << value; *spdy_header_block_value_size_ -= lookup_result_->second.SizeEstimate(); lookup_result_->second = HeaderValue(storage, key_, storage->Write(value)); } return *this; } bool HttpHeaderBlock::ValueProxy::operator==(absl::string_view value) const { if (lookup_result_ == block_->map_.end()) { return false; } else { return value == lookup_result_->second.value(); } } std::string HttpHeaderBlock::ValueProxy::as_string() const { if (lookup_result_ == block_->map_.end()) { return ""; } else { return std::string(lookup_result_->second.value()); } } HttpHeaderBlock::HttpHeaderBlock() : map_(kInitialMapBuckets) {} HttpHeaderBlock::HttpHeaderBlock(HttpHeaderBlock&& other) : map_(kInitialMapBuckets) { map_.swap(other.map_); storage_ = std::move(other.storage_); for (auto& p : map_) { p.second.set_storage(&storage_); } key_size_ = other.key_size_; value_size_ = other.value_size_; } HttpHeaderBlock::~HttpHeaderBlock() = default; HttpHeaderBlock& HttpHeaderBlock::operator=(HttpHeaderBlock&& other) { map_.swap(other.map_); storage_ = std::move(other.storage_); for (auto& p : map_) { p.second.set_storage(&storage_); } key_size_ = other.key_size_; value_size_ = other.value_size_; return *this; } HttpHeaderBlock HttpHeaderBlock::Clone() const { HttpHeaderBlock copy; for (const auto& p : *this) { copy.AppendHeader(p.first, p.second); } return copy; } bool HttpHeaderBlock::operator==(const HttpHeaderBlock& other) const { return size() == other.size() && std::equal(begin(), end(), other.begin()); } bool HttpHeaderBlock::operator!=(const HttpHeaderBlock& other) const { return !(operator==(other)); } std::string HttpHeaderBlock::DebugString() const { if (empty()) { return "{}"; } std::string output = "\n{\n"; for (auto it = begin(); it != end(); ++it) { absl::StrAppend(&output, " ", it->first, " ", it->second, "\n"); } absl::StrAppend(&output, "}\n"); return output; } void HttpHeaderBlock::erase(absl::string_view key) { auto iter = map_.find(key); if (iter != map_.end()) { QUICHE_DVLOG(1) << "Erasing header with name: " << key; key_size_ -= key.size(); value_size_ -= iter->second.SizeEstimate(); map_.erase(iter); } } void HttpHeaderBlock::clear() { key_size_ = 0; value_size_ = 0; map_.clear(); storage_.Clear(); } HttpHeaderBlock::InsertResult HttpHeaderBlock::insert( const HttpHeaderBlock::value_type& value) { value_size_ += value.second.size(); auto iter = map_.find(value.first); if (iter == map_.end()) { QUICHE_DVLOG(1) << "Inserting: (" << value.first << ", " << value.second << ")"; AppendHeader(value.first, value.second); return InsertResult::kInserted; } else { QUICHE_DVLOG(1) << "Updating key: " << iter->first << " with value: " << value.second; value_size_ -= iter->second.SizeEstimate(); iter->second = HeaderValue(&storage_, iter->first, storage_.Write(value.second)); return InsertResult::kReplaced; } } HttpHeaderBlock::ValueProxy HttpHeaderBlock::operator[]( const absl::string_view key) { QUICHE_DVLOG(2) << "Operator[] saw key: " << key; absl::string_view out_key; auto iter = map_.find(key); if (iter == map_.end()) { out_key = WriteKey(key); QUICHE_DVLOG(2) << "Key written as: " << std::hex << static_cast<const void*>(key.data()) << ", " << std::dec << key.size(); } else { out_key = iter->first; } return ValueProxy(this, iter, out_key, &value_size_); } void HttpHeaderBlock::AppendValueOrAddHeader(const absl::string_view key, const absl::string_view value) { value_size_ += value.size(); auto iter = map_.find(key); if (iter == map_.end()) { QUICHE_DVLOG(1) << "Inserting: (" << key << ", " << value << ")"; AppendHeader(key, value); return; } QUICHE_DVLOG(1) << "Updating key: " << iter->first << "; appending value: " << value; value_size_ += SeparatorForKey(key).size(); iter->second.Append(storage_.Write(value)); } void HttpHeaderBlock::AppendHeader(const absl::string_view key, const absl::string_view value) { auto backed_key = WriteKey(key); map_.emplace(std::make_pair( backed_key, HeaderValue(&storage_, backed_key, storage_.Write(value)))); } absl::string_view HttpHeaderBlock::WriteKey(const absl::string_view key) { key_size_ += key.size(); return storage_.Write(key); } size_t HttpHeaderBlock::bytes_allocated() const { return storage_.bytes_allocated(); } }
#include "quiche/common/http/http_header_block.h" #include <memory> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_test.h" #include "quiche/spdy/test_tools/spdy_test_utils.h" using ::testing::ElementsAre; namespace quiche { namespace test { class ValueProxyPeer { public: static absl::string_view key(HttpHeaderBlock::ValueProxy* p) { return p->key_; } }; std::pair<absl::string_view, absl::string_view> Pair(absl::string_view k, absl::string_view v) { return std::make_pair(k, v); } TEST(HttpHeaderBlockTest, EmptyBlock) { HttpHeaderBlock block; EXPECT_TRUE(block.empty()); EXPECT_EQ(0u, block.size()); EXPECT_EQ(block.end(), block.find("foo")); EXPECT_FALSE(block.contains("foo")); EXPECT_TRUE(block.end() == block.begin()); block.erase("bar"); } TEST(HttpHeaderBlockTest, KeyMemoryReclaimedOnLookup) { HttpHeaderBlock block; absl::string_view copied_key1; { auto proxy1 = block["some key name"]; copied_key1 = ValueProxyPeer::key(&proxy1); } absl::string_view copied_key2; { auto proxy2 = block["some other key name"]; copied_key2 = ValueProxyPeer::key(&proxy2); } EXPECT_EQ(copied_key1.data(), copied_key2.data()); { auto proxy1 = block["some key name"]; block["some other key name"] = "some value"; } block["key"] = "value"; EXPECT_EQ("value", block["key"]); EXPECT_EQ("some value", block["some other key name"]); EXPECT_TRUE(block.find("some key name") == block.end()); } TEST(HttpHeaderBlockTest, AddHeaders) { HttpHeaderBlock block; block["foo"] = std::string(300, 'x'); block["bar"] = "baz"; block["qux"] = "qux1"; block["qux"] = "qux2"; block.insert(std::make_pair("key", "value")); EXPECT_EQ(Pair("foo", std::string(300, 'x')), *block.find("foo")); EXPECT_EQ("baz", block["bar"]); std::string qux("qux"); EXPECT_EQ("qux2", block[qux]); ASSERT_NE(block.end(), block.find("key")); ASSERT_TRUE(block.contains("key")); EXPECT_EQ(Pair("key", "value"), *block.find("key")); block.erase("key"); EXPECT_EQ(block.end(), block.find("key")); } TEST(HttpHeaderBlockTest, CopyBlocks) { HttpHeaderBlock block1; block1["foo"] = std::string(300, 'x'); block1["bar"] = "baz"; block1.insert(std::make_pair("qux", "qux1")); HttpHeaderBlock block2 = block1.Clone(); HttpHeaderBlock block3(block1.Clone()); EXPECT_EQ(block1, block2); EXPECT_EQ(block1, block3); } TEST(HttpHeaderBlockTest, Equality) { HttpHeaderBlock block1; block1["foo"] = "bar"; HttpHeaderBlock block2; block2["foo"] = "bar"; HttpHeaderBlock block3; block3["baz"] = "qux"; EXPECT_EQ(block1, block2); EXPECT_NE(block1, block3); block2["baz"] = "qux"; EXPECT_NE(block1, block2); } HttpHeaderBlock ReturnTestHeaderBlock() { HttpHeaderBlock block; block["foo"] = "bar"; block.insert(std::make_pair("foo2", "baz")); return block; } TEST(HttpHeaderBlockTest, MovedFromIsValid) { HttpHeaderBlock block1; block1["foo"] = "bar"; HttpHeaderBlock block2(std::move(block1)); EXPECT_THAT(block2, ElementsAre(Pair("foo", "bar"))); block1["baz"] = "qux"; HttpHeaderBlock block3(std::move(block1)); block1["foo"] = "bar"; HttpHeaderBlock block4(std::move(block1)); block1.clear(); EXPECT_TRUE(block1.empty()); block1["foo"] = "bar"; EXPECT_THAT(block1, ElementsAre(Pair("foo", "bar"))); HttpHeaderBlock block5 = ReturnTestHeaderBlock(); block5.AppendValueOrAddHeader("foo", "bar2"); EXPECT_THAT(block5, ElementsAre(Pair("foo", std::string("bar\0bar2", 8)), Pair("foo2", "baz"))); } TEST(HttpHeaderBlockTest, AppendHeaders) { HttpHeaderBlock block; block["foo"] = "foo"; block.AppendValueOrAddHeader("foo", "bar"); EXPECT_EQ(Pair("foo", std::string("foo\0bar", 7)), *block.find("foo")); block.insert(std::make_pair("foo", "baz")); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(Pair("foo", "baz"), *block.find("foo")); block["cookie"] = "key1=value1"; block.AppendValueOrAddHeader("h1", "h1v1"); block.insert(std::make_pair("h2", "h2v1")); block.AppendValueOrAddHeader("h3", "h3v2"); block.AppendValueOrAddHeader("h2", "h2v2"); block.AppendValueOrAddHeader("h1", "h1v2"); block.AppendValueOrAddHeader("cookie", "key2=value2"); block.AppendValueOrAddHeader("cookie", "key3=value3"); block.AppendValueOrAddHeader("h1", "h1v3"); block.AppendValueOrAddHeader("h2", "h2v3"); block.AppendValueOrAddHeader("h3", "h3v3"); block.AppendValueOrAddHeader("h4", "singleton"); block.AppendValueOrAddHeader("set-cookie", "yummy"); block.AppendValueOrAddHeader("set-cookie", "scrumptious"); EXPECT_EQ("key1=value1; key2=value2; key3=value3", block["cookie"]); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(std::string("h1v1\0h1v2\0h1v3", 14), block["h1"]); EXPECT_EQ(std::string("h2v1\0h2v2\0h2v3", 14), block["h2"]); EXPECT_EQ(std::string("h3v2\0h3v3", 9), block["h3"]); EXPECT_EQ("singleton", block["h4"]); EXPECT_EQ(std::string("yummy\0scrumptious", 17), block["set-cookie"]); } TEST(HttpHeaderBlockTest, CompareValueToStringPiece) { HttpHeaderBlock block; block["foo"] = "foo"; block.AppendValueOrAddHeader("foo", "bar"); const auto& val = block["foo"]; const char expected[] = "foo\0bar"; EXPECT_TRUE(absl::string_view(expected, 7) == val); EXPECT_TRUE(val == absl::string_view(expected, 7)); EXPECT_FALSE(absl::string_view(expected, 3) == val); EXPECT_FALSE(val == absl::string_view(expected, 3)); const char not_expected[] = "foo\0barextra"; EXPECT_FALSE(absl::string_view(not_expected, 12) == val); EXPECT_FALSE(val == absl::string_view(not_expected, 12)); const auto& val2 = block["foo2"]; EXPECT_FALSE(absl::string_view(expected, 7) == val2); EXPECT_FALSE(val2 == absl::string_view(expected, 7)); EXPECT_FALSE(absl::string_view("") == val2); EXPECT_FALSE(val2 == absl::string_view("")); } TEST(HttpHeaderBlockTest, UpperCaseNames) { HttpHeaderBlock block; block["Foo"] = "foo"; block.AppendValueOrAddHeader("Foo", "bar"); EXPECT_NE(block.end(), block.find("foo")); EXPECT_EQ(Pair("Foo", std::string("foo\0bar", 7)), *block.find("Foo")); block.AppendValueOrAddHeader("foo", "baz"); EXPECT_THAT(block, ElementsAre(Pair("Foo", std::string("foo\0bar\0baz", 11)))); } namespace { size_t HttpHeaderBlockSize(const HttpHeaderBlock& block) { size_t size = 0; for (const auto& pair : block) { size += pair.first.size() + pair.second.size(); } return size; } } TEST(HttpHeaderBlockTest, TotalBytesUsed) { HttpHeaderBlock block; const size_t value_size = 300; block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); size_t block_size = block.TotalBytesUsed(); HttpHeaderBlock block_copy = std::move(block); EXPECT_EQ(block_size, block_copy.TotalBytesUsed()); block_copy.erase("foo"); EXPECT_EQ(block_copy.TotalBytesUsed(), HttpHeaderBlockSize(block_copy)); block_copy.erase("key"); EXPECT_EQ(block_copy.TotalBytesUsed(), HttpHeaderBlockSize(block_copy)); block_copy.erase("abc"); EXPECT_EQ(block_copy.TotalBytesUsed(), HttpHeaderBlockSize(block_copy)); } TEST(HttpHeaderBlockTest, OrderPreserved) { HttpHeaderBlock block; block[":method"] = "GET"; block["foo"] = "bar"; block[":path"] = "/"; EXPECT_THAT(block, ElementsAre(Pair(":method", "GET"), Pair("foo", "bar"), Pair(":path", "/"))); } TEST(HttpHeaderBlockTest, InsertReturnValue) { HttpHeaderBlock block; EXPECT_EQ(HttpHeaderBlock::InsertResult::kInserted, block.insert({"foo", "bar"})); EXPECT_EQ(HttpHeaderBlock::InsertResult::kReplaced, block.insert({"foo", "baz"})); } } }
192
cpp
google/quiche
http_header_storage
quiche/common/http/http_header_storage.cc
quiche/common/http/http_header_storage_test.cc
#ifndef QUICHE_COMMON_HTTP_HTTP_HEADER_STORAGE_H_ #define QUICHE_COMMON_HTTP_HTTP_HEADER_STORAGE_H_ #include "absl/container/inlined_vector.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_simple_arena.h" namespace quiche { using Fragments = absl::InlinedVector<absl::string_view, 1>; class QUICHE_EXPORT HttpHeaderStorage { public: HttpHeaderStorage(); HttpHeaderStorage(const HttpHeaderStorage&) = delete; HttpHeaderStorage& operator=(const HttpHeaderStorage&) = delete; HttpHeaderStorage(HttpHeaderStorage&& other) = default; HttpHeaderStorage& operator=(HttpHeaderStorage&& other) = default; absl::string_view Write(absl::string_view s); void Rewind(absl::string_view s); void Clear() { arena_.Reset(); } absl::string_view WriteFragments(const Fragments& fragments, absl::string_view separator); size_t bytes_allocated() const { return arena_.status().bytes_allocated(); } private: QuicheSimpleArena arena_; }; QUICHE_EXPORT size_t Join(char* dst, const Fragments& fragments, absl::string_view separator); } #endif #include "quiche/common/http/http_header_storage.h" #include <cstring> #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { const size_t kDefaultStorageBlockSize = 2048; } HttpHeaderStorage::HttpHeaderStorage() : arena_(kDefaultStorageBlockSize) {} absl::string_view HttpHeaderStorage::Write(const absl::string_view s) { return absl::string_view(arena_.Memdup(s.data(), s.size()), s.size()); } void HttpHeaderStorage::Rewind(const absl::string_view s) { arena_.Free(const_cast<char*>(s.data()), s.size()); } absl::string_view HttpHeaderStorage::WriteFragments( const Fragments& fragments, absl::string_view separator) { if (fragments.empty()) { return absl::string_view(); } size_t total_size = separator.size() * (fragments.size() - 1); for (const absl::string_view& fragment : fragments) { total_size += fragment.size(); } char* dst = arena_.Alloc(total_size); size_t written = Join(dst, fragments, separator); QUICHE_DCHECK_EQ(written, total_size); return absl::string_view(dst, total_size); } size_t Join(char* dst, const Fragments& fragments, absl::string_view separator) { if (fragments.empty()) { return 0; } auto* original_dst = dst; auto it = fragments.begin(); memcpy(dst, it->data(), it->size()); dst += it->size(); for (++it; it != fragments.end(); ++it) { memcpy(dst, separator.data(), separator.size()); dst += separator.size(); memcpy(dst, it->data(), it->size()); dst += it->size(); } return dst - original_dst; } }
#include "quiche/common/http/http_header_storage.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { TEST(JoinTest, JoinEmpty) { Fragments empty; absl::string_view separator = ", "; char buf[10] = ""; size_t written = Join(buf, empty, separator); EXPECT_EQ(0u, written); } TEST(JoinTest, JoinOne) { Fragments v = {"one"}; absl::string_view separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(3u, written); EXPECT_EQ("one", absl::string_view(buf, written)); } TEST(JoinTest, JoinMultiple) { Fragments v = {"one", "two", "three"}; absl::string_view separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(15u, written); EXPECT_EQ("one, two, three", absl::string_view(buf, written)); } } }
193
cpp
google/quiche
connect_udp_datagram_payload
quiche/common/masque/connect_udp_datagram_payload.cc
quiche/common/masque/connect_udp_datagram_payload_test.cc
#ifndef QUICHE_COMMON_MASQUE_CONNECT_UDP_DATAGRAM_PAYLOAD_H_ #define QUICHE_COMMON_MASQUE_CONNECT_UDP_DATAGRAM_PAYLOAD_H_ #include <cstdint> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { class QUICHE_EXPORT ConnectUdpDatagramPayload { public: using ContextId = uint64_t; enum class Type { kUdpPacket, kUnknown }; static std::unique_ptr<ConnectUdpDatagramPayload> Parse( absl::string_view datagram_payload); ConnectUdpDatagramPayload() = default; ConnectUdpDatagramPayload(const ConnectUdpDatagramPayload&) = delete; ConnectUdpDatagramPayload& operator=(const ConnectUdpDatagramPayload&) = delete; virtual ~ConnectUdpDatagramPayload() = default; virtual ContextId GetContextId() const = 0; virtual Type GetType() const = 0; virtual absl::string_view GetUdpProxyingPayload() const = 0; virtual size_t SerializedLength() const = 0; virtual bool SerializeTo(QuicheDataWriter& writer) const = 0; std::string Serialize() const; }; class QUICHE_EXPORT ConnectUdpDatagramUdpPacketPayload final : public ConnectUdpDatagramPayload { public: static constexpr ContextId kContextId = 0; explicit ConnectUdpDatagramUdpPacketPayload(absl::string_view udp_packet); ContextId GetContextId() const override; Type GetType() const override; absl::string_view GetUdpProxyingPayload() const override; size_t SerializedLength() const override; bool SerializeTo(QuicheDataWriter& writer) const override; absl::string_view udp_packet() const { return udp_packet_; } private: absl::string_view udp_packet_; }; class QUICHE_EXPORT ConnectUdpDatagramUnknownPayload final : public ConnectUdpDatagramPayload { public: ConnectUdpDatagramUnknownPayload(ContextId context_id, absl::string_view udp_proxying_payload); ContextId GetContextId() const override; Type GetType() const override; absl::string_view GetUdpProxyingPayload() const override; size_t SerializedLength() const override; bool SerializeTo(QuicheDataWriter& writer) const override; private: ContextId context_id_; absl::string_view udp_proxying_payload_; }; } #endif #include "quiche/common/masque/connect_udp_datagram_payload.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { std::unique_ptr<ConnectUdpDatagramPayload> ConnectUdpDatagramPayload::Parse( absl::string_view datagram_payload) { QuicheDataReader data_reader(datagram_payload); uint64_t context_id; if (!data_reader.ReadVarInt62(&context_id)) { QUICHE_DVLOG(1) << "Could not parse malformed UDP proxy payload"; return nullptr; } if (ContextId{context_id} == ConnectUdpDatagramUdpPacketPayload::kContextId) { return std::make_unique<ConnectUdpDatagramUdpPacketPayload>( data_reader.ReadRemainingPayload()); } else { return std::make_unique<ConnectUdpDatagramUnknownPayload>( ContextId{context_id}, data_reader.ReadRemainingPayload()); } } std::string ConnectUdpDatagramPayload::Serialize() const { std::string buffer(SerializedLength(), '\0'); QuicheDataWriter writer(buffer.size(), buffer.data()); bool result = SerializeTo(writer); QUICHE_DCHECK(result); QUICHE_DCHECK_EQ(writer.remaining(), 0u); return buffer; } ConnectUdpDatagramUdpPacketPayload::ConnectUdpDatagramUdpPacketPayload( absl::string_view udp_packet) : udp_packet_(udp_packet) {} ConnectUdpDatagramPayload::ContextId ConnectUdpDatagramUdpPacketPayload::GetContextId() const { return kContextId; } ConnectUdpDatagramPayload::Type ConnectUdpDatagramUdpPacketPayload::GetType() const { return Type::kUdpPacket; } absl::string_view ConnectUdpDatagramUdpPacketPayload::GetUdpProxyingPayload() const { return udp_packet_; } size_t ConnectUdpDatagramUdpPacketPayload::SerializedLength() const { return udp_packet_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{kContextId}); } bool ConnectUdpDatagramUdpPacketPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{kContextId})) { return false; } if (!writer.WriteStringPiece(udp_packet_)) { return false; } return true; } ConnectUdpDatagramUnknownPayload::ConnectUdpDatagramUnknownPayload( ContextId context_id, absl::string_view udp_proxying_payload) : context_id_(context_id), udp_proxying_payload_(udp_proxying_payload) { if (context_id == ConnectUdpDatagramUdpPacketPayload::kContextId) { QUICHE_BUG(udp_proxy_unknown_payload_udp_context) << "ConnectUdpDatagramUnknownPayload created with UDP packet context " "type (0). Should instead create a " "ConnectUdpDatagramUdpPacketPayload."; } } ConnectUdpDatagramPayload::ContextId ConnectUdpDatagramUnknownPayload::GetContextId() const { return context_id_; } ConnectUdpDatagramPayload::Type ConnectUdpDatagramUnknownPayload::GetType() const { return Type::kUnknown; } absl::string_view ConnectUdpDatagramUnknownPayload::GetUdpProxyingPayload() const { return udp_proxying_payload_; } size_t ConnectUdpDatagramUnknownPayload::SerializedLength() const { return udp_proxying_payload_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{context_id_}); } bool ConnectUdpDatagramUnknownPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{context_id_})) { return false; } if (!writer.WriteStringPiece(udp_proxying_payload_)) { return false; } return true; } }
#include "quiche/common/masque/connect_udp_datagram_payload.h" #include <memory> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { TEST(ConnectUdpDatagramPayloadTest, ParseUdpPacket) { static constexpr char kDatagramPayload[] = "\x00packet"; std::unique_ptr<ConnectUdpDatagramPayload> parsed = ConnectUdpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), ConnectUdpDatagramUdpPacketPayload::kContextId); EXPECT_EQ(parsed->GetType(), ConnectUdpDatagramPayload::Type::kUdpPacket); EXPECT_EQ(parsed->GetUdpProxyingPayload(), "packet"); } TEST(ConnectUdpDatagramPayloadTest, SerializeUdpPacket) { static constexpr absl::string_view kUdpPacket = "packet"; ConnectUdpDatagramUdpPacketPayload payload(kUdpPacket); EXPECT_EQ(payload.GetUdpProxyingPayload(), kUdpPacket); EXPECT_EQ(payload.Serialize(), std::string("\x00packet", 7)); } TEST(ConnectUdpDatagramPayloadTest, ParseUnknownPacket) { static constexpr char kDatagramPayload[] = "\x05packet"; std::unique_ptr<ConnectUdpDatagramPayload> parsed = ConnectUdpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), 5); EXPECT_EQ(parsed->GetType(), ConnectUdpDatagramPayload::Type::kUnknown); EXPECT_EQ(parsed->GetUdpProxyingPayload(), "packet"); } TEST(ConnectUdpDatagramPayloadTest, SerializeUnknownPacket) { static constexpr absl::string_view kInnerUdpProxyingPayload = "packet"; ConnectUdpDatagramUnknownPayload payload(4u, kInnerUdpProxyingPayload); EXPECT_EQ(payload.GetUdpProxyingPayload(), kInnerUdpProxyingPayload); EXPECT_EQ(payload.Serialize(), std::string("\x04packet", 7)); } } }
194
cpp
google/quiche
connect_ip_datagram_payload
quiche/common/masque/connect_ip_datagram_payload.cc
quiche/common/masque/connect_ip_datagram_payload_test.cc
#ifndef QUICHE_COMMON_MASQUE_CONNECT_IP_DATAGRAM_PAYLOAD_H_ #define QUICHE_COMMON_MASQUE_CONNECT_IP_DATAGRAM_PAYLOAD_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { class QUICHE_EXPORT ConnectIpDatagramPayload { public: using ContextId = uint64_t; enum class Type { kIpPacket, kUnknown }; static std::unique_ptr<ConnectIpDatagramPayload> Parse( absl::string_view datagram_payload); ConnectIpDatagramPayload() = default; ConnectIpDatagramPayload(const ConnectIpDatagramPayload&) = delete; ConnectIpDatagramPayload& operator=(const ConnectIpDatagramPayload&) = delete; virtual ~ConnectIpDatagramPayload() = default; virtual ContextId GetContextId() const = 0; virtual Type GetType() const = 0; virtual absl::string_view GetIpProxyingPayload() const = 0; virtual size_t SerializedLength() const = 0; virtual bool SerializeTo(QuicheDataWriter& writer) const = 0; std::string Serialize() const; }; class QUICHE_EXPORT ConnectIpDatagramIpPacketPayload final : public ConnectIpDatagramPayload { public: static constexpr ContextId kContextId = 0; explicit ConnectIpDatagramIpPacketPayload(absl::string_view ip_packet); ContextId GetContextId() const override; Type GetType() const override; absl::string_view GetIpProxyingPayload() const override; size_t SerializedLength() const override; bool SerializeTo(QuicheDataWriter& writer) const override; absl::string_view ip_packet() const { return ip_packet_; } private: absl::string_view ip_packet_; }; class QUICHE_EXPORT ConnectIpDatagramUnknownPayload final : public ConnectIpDatagramPayload { public: ConnectIpDatagramUnknownPayload(ContextId context_id, absl::string_view ip_proxying_payload); ContextId GetContextId() const override; Type GetType() const override; absl::string_view GetIpProxyingPayload() const override; size_t SerializedLength() const override; bool SerializeTo(QuicheDataWriter& writer) const override; private: ContextId context_id_; absl::string_view ip_proxying_payload_; }; } #endif #include "quiche/common/masque/connect_ip_datagram_payload.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { std::unique_ptr<ConnectIpDatagramPayload> ConnectIpDatagramPayload::Parse( absl::string_view datagram_payload) { QuicheDataReader data_reader(datagram_payload); uint64_t context_id; if (!data_reader.ReadVarInt62(&context_id)) { QUICHE_DVLOG(1) << "Could not parse malformed IP proxy payload"; return nullptr; } if (ContextId{context_id} == ConnectIpDatagramIpPacketPayload::kContextId) { return std::make_unique<ConnectIpDatagramIpPacketPayload>( data_reader.ReadRemainingPayload()); } else { return std::make_unique<ConnectIpDatagramUnknownPayload>( ContextId{context_id}, data_reader.ReadRemainingPayload()); } } std::string ConnectIpDatagramPayload::Serialize() const { std::string buffer(SerializedLength(), '\0'); QuicheDataWriter writer(buffer.size(), buffer.data()); bool result = SerializeTo(writer); QUICHE_DCHECK(result); QUICHE_DCHECK_EQ(writer.remaining(), 0u); return buffer; } ConnectIpDatagramIpPacketPayload::ConnectIpDatagramIpPacketPayload( absl::string_view ip_packet) : ip_packet_(ip_packet) {} ConnectIpDatagramPayload::ContextId ConnectIpDatagramIpPacketPayload::GetContextId() const { return kContextId; } ConnectIpDatagramPayload::Type ConnectIpDatagramIpPacketPayload::GetType() const { return Type::kIpPacket; } absl::string_view ConnectIpDatagramIpPacketPayload::GetIpProxyingPayload() const { return ip_packet_; } size_t ConnectIpDatagramIpPacketPayload::SerializedLength() const { return ip_packet_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{kContextId}); } bool ConnectIpDatagramIpPacketPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{kContextId})) { return false; } if (!writer.WriteStringPiece(ip_packet_)) { return false; } return true; } ConnectIpDatagramUnknownPayload::ConnectIpDatagramUnknownPayload( ContextId context_id, absl::string_view ip_proxying_payload) : context_id_(context_id), ip_proxying_payload_(ip_proxying_payload) { if (context_id == ConnectIpDatagramIpPacketPayload::kContextId) { QUICHE_BUG(ip_proxy_unknown_payload_ip_context) << "ConnectIpDatagramUnknownPayload created with IP packet context " "ID (0). Should instead create a " "ConnectIpDatagramIpPacketPayload."; } } ConnectIpDatagramPayload::ContextId ConnectIpDatagramUnknownPayload::GetContextId() const { return context_id_; } ConnectIpDatagramPayload::Type ConnectIpDatagramUnknownPayload::GetType() const { return Type::kUnknown; } absl::string_view ConnectIpDatagramUnknownPayload::GetIpProxyingPayload() const { return ip_proxying_payload_; } size_t ConnectIpDatagramUnknownPayload::SerializedLength() const { return ip_proxying_payload_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{context_id_}); } bool ConnectIpDatagramUnknownPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{context_id_})) { return false; } if (!writer.WriteStringPiece(ip_proxying_payload_)) { return false; } return true; } }
#include "quiche/common/masque/connect_ip_datagram_payload.h" #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { TEST(ConnectIpDatagramPayloadTest, ParseIpPacket) { static constexpr char kDatagramPayload[] = "\x00packet"; std::unique_ptr<ConnectIpDatagramPayload> parsed = ConnectIpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), ConnectIpDatagramIpPacketPayload::kContextId); EXPECT_EQ(parsed->GetType(), ConnectIpDatagramPayload::Type::kIpPacket); EXPECT_EQ(parsed->GetIpProxyingPayload(), "packet"); } TEST(ConnectIpDatagramPayloadTest, SerializeIpPacket) { static constexpr absl::string_view kIpPacket = "packet"; ConnectIpDatagramIpPacketPayload payload(kIpPacket); EXPECT_EQ(payload.GetIpProxyingPayload(), kIpPacket); EXPECT_EQ(payload.Serialize(), std::string("\x00packet", 7)); } TEST(ConnectIpDatagramPayloadTest, ParseUnknownPacket) { static constexpr char kDatagramPayload[] = "\x05packet"; std::unique_ptr<ConnectIpDatagramPayload> parsed = ConnectIpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), 5); EXPECT_EQ(parsed->GetType(), ConnectIpDatagramPayload::Type::kUnknown); EXPECT_EQ(parsed->GetIpProxyingPayload(), "packet"); } TEST(ConnectIpDatagramPayloadTest, SerializeUnknownPacket) { static constexpr absl::string_view kInnerIpProxyingPayload = "packet"; ConnectIpDatagramUnknownPayload payload(4u, kInnerIpProxyingPayload); EXPECT_EQ(payload.GetIpProxyingPayload(), kInnerIpProxyingPayload); EXPECT_EQ(payload.Serialize(), std::string("\x04packet", 7)); } } }
195
cpp
google/quiche
quiche_test_utils
quiche/common/test_tools/quiche_test_utils.cc
quiche/common/test_tools/quiche_test_utils_test.cc
#ifndef QUICHE_COMMON_TEST_TOOLS_QUICHE_TEST_UTILS_H_ #define QUICHE_COMMON_TEST_TOOLS_QUICHE_TEST_UTILS_H_ #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_iovec.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { void CompareCharArraysWithHexError(const std::string& description, const char* actual, const int actual_len, const char* expected, const int expected_len); iovec MakeIOVector(absl::string_view str); bool GoogleUrlSupportsIdnaForTest(); inline const absl::Status& ExtractStatus(const absl::Status& status) { return status; } template <typename T> const absl::Status& ExtractStatus(const absl::StatusOr<T>& status_or) { return status_or.status(); } MATCHER(IsOk, "Checks if an instance of absl::Status is ok.") { if (arg.ok()) { return true; } *result_listener << "Expected status OK, got " << ExtractStatus(arg); return false; } MATCHER_P(IsOkAndHolds, matcher, "Matcher against the inner value of absl::StatusOr") { if (!arg.ok()) { *result_listener << "Expected status OK, got " << arg.status(); return false; } return ::testing::ExplainMatchResult(matcher, arg.value(), result_listener); } MATCHER_P(StatusIs, code, "Matcher against only a specific status code") { if (ExtractStatus(arg).code() != code) { *result_listener << "Expected status " << absl::StatusCodeToString(code) << ", got " << ExtractStatus(arg); return false; } return true; } MATCHER_P2(StatusIs, code, matcher, "Matcher against a specific status code") { if (ExtractStatus(arg).code() != code) { *result_listener << "Expected status " << absl::StatusCodeToString(code) << ", got " << ExtractStatus(arg); return false; } return ::testing::ExplainMatchResult(matcher, ExtractStatus(arg).message(), result_listener); } #define QUICHE_EXPECT_OK(arg) EXPECT_THAT((arg), ::quiche::test::IsOk()) #define QUICHE_ASSERT_OK(arg) ASSERT_THAT((arg), ::quiche::test::IsOk()) } } #endif #include "quiche/common/test_tools/quiche_test_utils.h" #include <algorithm> #include <memory> #include <string> #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace { std::string HexDumpWithMarks(const char* data, int length, const bool* marks, int mark_length) { static const char kHexChars[] = "0123456789abcdef"; static const int kColumns = 4; const int kSizeLimit = 1024; if (length > kSizeLimit || mark_length > kSizeLimit) { QUICHE_LOG(ERROR) << "Only dumping first " << kSizeLimit << " bytes."; length = std::min(length, kSizeLimit); mark_length = std::min(mark_length, kSizeLimit); } std::string hex; for (const char* row = data; length > 0; row += kColumns, length -= kColumns) { for (const char* p = row; p < row + 4; ++p) { if (p < row + length) { const bool mark = (marks && (p - data) < mark_length && marks[p - data]); hex += mark ? '*' : ' '; hex += kHexChars[(*p & 0xf0) >> 4]; hex += kHexChars[*p & 0x0f]; hex += mark ? '*' : ' '; } else { hex += " "; } } hex = hex + " "; for (const char* p = row; p < row + 4 && p < row + length; ++p) { hex += (*p >= 0x20 && *p < 0x7f) ? (*p) : '.'; } hex = hex + '\n'; } return hex; } } namespace quiche { namespace test { void CompareCharArraysWithHexError(const std::string& description, const char* actual, const int actual_len, const char* expected, const int expected_len) { EXPECT_EQ(actual_len, expected_len); const int min_len = std::min(actual_len, expected_len); const int max_len = std::max(actual_len, expected_len); std::unique_ptr<bool[]> marks(new bool[max_len]); bool identical = (actual_len == expected_len); for (int i = 0; i < min_len; ++i) { if (actual[i] != expected[i]) { marks[i] = true; identical = false; } else { marks[i] = false; } } for (int i = min_len; i < max_len; ++i) { marks[i] = true; } if (identical) return; ADD_FAILURE() << "Description:\n" << description << "\n\nExpected:\n" << HexDumpWithMarks(expected, expected_len, marks.get(), max_len) << "\nActual:\n" << HexDumpWithMarks(actual, actual_len, marks.get(), max_len); } iovec MakeIOVector(absl::string_view str) { return iovec{const_cast<char*>(str.data()), static_cast<size_t>(str.size())}; } bool GoogleUrlSupportsIdnaForTest() { const std::string kTestInput = "https: const std::string kExpectedOutput = "https: GURL url(kTestInput); bool valid = url.is_valid() && url.spec() == kExpectedOutput; QUICHE_CHECK(valid || !url.is_valid()) << url.spec(); return valid; } } }
#include "quiche/common/test_tools/quiche_test_utils.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { using ::testing::HasSubstr; using ::testing::Not; TEST(QuicheTestUtilsTest, StatusMatchers) { const absl::Status ok = absl::OkStatus(); QUICHE_EXPECT_OK(ok); QUICHE_ASSERT_OK(ok); EXPECT_THAT(ok, IsOk()); const absl::StatusOr<int> ok_with_value = 2023; QUICHE_EXPECT_OK(ok_with_value); QUICHE_ASSERT_OK(ok_with_value); EXPECT_THAT(ok_with_value, IsOk()); EXPECT_THAT(ok_with_value, IsOkAndHolds(2023)); const absl::Status err = absl::InternalError("test error"); EXPECT_THAT(err, Not(IsOk())); EXPECT_THAT(err, StatusIs(absl::StatusCode::kInternal, HasSubstr("test"))); const absl::StatusOr<int> err_with_value = absl::InternalError("test error"); EXPECT_THAT(err_with_value, Not(IsOk())); EXPECT_THAT(err_with_value, Not(IsOkAndHolds(2023))); EXPECT_THAT(err_with_value, StatusIs(absl::StatusCode::kInternal, HasSubstr("test"))); } } }
196
cpp
google/quiche
load_balancer_decoder
quiche/quic/load_balancer/load_balancer_decoder.cc
quiche/quic/load_balancer/load_balancer_decoder_test.cc
#ifndef QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_DECODER_H_ #define QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_DECODER_H_ #include <cstdint> #include <optional> #include "absl/base/attributes.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUIC_EXPORT_PRIVATE LoadBalancerDecoder { public: bool AddConfig(const LoadBalancerConfig& config); void DeleteConfig(uint8_t config_id); const LoadBalancerConfig* GetConfig(const uint8_t config_id) const { if (config_id >= kNumLoadBalancerConfigs || !config_[config_id].has_value()) { return nullptr; } return &*config_[config_id]; } ABSL_MUST_USE_RESULT bool GetServerId(const QuicConnectionId& connection_id, LoadBalancerServerId& server_id) const; static std::optional<uint8_t> GetConfigId( const QuicConnectionId& connection_id); static std::optional<uint8_t> GetConfigId(uint8_t connection_id_first_byte); private: std::optional<LoadBalancerConfig> config_[kNumLoadBalancerConfigs]; }; } #endif #include "quiche/quic/load_balancer/load_balancer_decoder.h" #include <cstdint> #include <cstring> #include <optional> #include "absl/types/span.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { bool LoadBalancerDecoder::AddConfig(const LoadBalancerConfig& config) { if (config_[config.config_id()].has_value()) { return false; } config_[config.config_id()] = config; return true; } void LoadBalancerDecoder::DeleteConfig(uint8_t config_id) { if (config_id >= kNumLoadBalancerConfigs) { QUIC_BUG(quic_bug_438896865_01) << "Decoder deleting config with invalid config_id " << static_cast<int>(config_id); return; } config_[config_id].reset(); } bool LoadBalancerDecoder::GetServerId(const QuicConnectionId& connection_id, LoadBalancerServerId& server_id) const { std::optional<uint8_t> config_id = GetConfigId(connection_id); if (!config_id.has_value()) { return false; } std::optional<LoadBalancerConfig> config = config_[*config_id]; if (!config.has_value()) { return false; } if (connection_id.length() < config->total_len()) { return false; } const uint8_t* data = reinterpret_cast<const uint8_t*>(connection_id.data()) + 1; uint8_t server_id_len = config->server_id_len(); server_id.set_length(server_id_len); if (!config->IsEncrypted()) { memcpy(server_id.mutable_data(), connection_id.data() + 1, server_id_len); return true; } if (config->plaintext_len() == kLoadBalancerBlockSize) { return config->BlockDecrypt(data, server_id.mutable_data()); } return config->FourPassDecrypt( absl::MakeConstSpan(data, connection_id.length() - 1), server_id); } std::optional<uint8_t> LoadBalancerDecoder::GetConfigId( const QuicConnectionId& connection_id) { if (connection_id.IsEmpty()) { return std::optional<uint8_t>(); } return GetConfigId(*reinterpret_cast<const uint8_t*>(connection_id.data())); } std::optional<uint8_t> LoadBalancerDecoder::GetConfigId( const uint8_t connection_id_first_byte) { uint8_t codepoint = (connection_id_first_byte >> kConnectionIdLengthBits); if (codepoint < kNumLoadBalancerConfigs) { return codepoint; } return std::optional<uint8_t>(); } }
#include "quiche/quic/load_balancer/load_balancer_decoder.h" #include <cstdint> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class LoadBalancerDecoderTest : public QuicTest {}; inline LoadBalancerServerId MakeServerId(const uint8_t array[], const uint8_t length) { return LoadBalancerServerId(absl::Span<const uint8_t>(array, length)); } constexpr char kRawKey[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; constexpr absl::string_view kKey(kRawKey, kLoadBalancerKeyLen); constexpr uint8_t kServerId[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xab, 0x65, 0xba, 0x04, 0xc3, 0x33, 0x0a}; struct LoadBalancerDecoderTestCase { LoadBalancerConfig config; QuicConnectionId connection_id; LoadBalancerServerId server_id; }; TEST_F(LoadBalancerDecoderTest, UnencryptedConnectionIdTestVectors) { const struct LoadBalancerDecoderTestCase test_vectors[2] = { { *LoadBalancerConfig::CreateUnencrypted(0, 3, 4), QuicConnectionId({0x07, 0xed, 0x79, 0x3a, 0x80, 0x49, 0x71, 0x8a}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::CreateUnencrypted(1, 8, 5), QuicConnectionId({0x2d, 0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x15, 0xda, 0x27, 0xc4}), MakeServerId(kServerId, 8), }}; for (const auto& test : test_vectors) { LoadBalancerDecoder decoder; LoadBalancerServerId answer; EXPECT_TRUE(decoder.AddConfig(test.config)); EXPECT_TRUE(decoder.GetServerId(test.connection_id, answer)); EXPECT_EQ(answer, test.server_id); } } TEST_F(LoadBalancerDecoderTest, DecoderTestVectors) { const struct LoadBalancerDecoderTestCase test_vectors[4] = { { *LoadBalancerConfig::Create(0, 3, 4, kKey), QuicConnectionId({0x07, 0x20, 0xb1, 0xd0, 0x7b, 0x35, 0x9d, 0x3c}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::Create(1, 10, 5, kKey), QuicConnectionId({0x2f, 0xcc, 0x38, 0x1b, 0xc7, 0x4c, 0xb4, 0xfb, 0xad, 0x28, 0x23, 0xa3, 0xd1, 0xf8, 0xfe, 0xd2}), MakeServerId(kServerId, 10), }, { *LoadBalancerConfig::Create(2, 8, 8, kKey), QuicConnectionId({0x50, 0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}), MakeServerId(kServerId, 8), }, { *LoadBalancerConfig::Create(0, 9, 9, kKey), QuicConnectionId({0x12, 0x57, 0x79, 0xc9, 0xcc, 0x86, 0xbe, 0xb3, 0xa3, 0xa4, 0xa3, 0xca, 0x96, 0xfc, 0xe4, 0xbf, 0xe0, 0xcd, 0xbc}), MakeServerId(kServerId, 9), }, }; for (const auto& test : test_vectors) { LoadBalancerDecoder decoder; EXPECT_TRUE(decoder.AddConfig(test.config)); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId(test.connection_id, answer)); EXPECT_EQ(answer, test.server_id); } } TEST_F(LoadBalancerDecoderTest, InvalidConfigId) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(1, 3, 4))); QuicConnectionId wrong_config_id( {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, UnroutableCodepoint) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(1, 3, 4))); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0xe0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, UnroutableCodepointAnyLength) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(1, 3, 4))); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId(QuicConnectionId({0xff}), answer)); } TEST_F(LoadBalancerDecoderTest, ConnectionIdTooShort) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(0, 3, 4))); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), answer)); } TEST_F(LoadBalancerDecoderTest, ConnectionIdTooLongIsOK) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(0, 3, 4))); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}), answer)); EXPECT_EQ(answer, server_id); } TEST_F(LoadBalancerDecoderTest, DeleteConfigBadId) { LoadBalancerDecoder decoder; decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(2, 3, 4)); decoder.DeleteConfig(0); EXPECT_QUIC_BUG(decoder.DeleteConfig(7), "Decoder deleting config with invalid config_id 7"); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x40, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, DeleteConfigGoodId) { LoadBalancerDecoder decoder; decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(2, 3, 4)); decoder.DeleteConfig(2); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0x40, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, TwoServerIds) { LoadBalancerServerId server_id1({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id1.IsValid()); LoadBalancerServerId server_id2({0x04, 0x05, 0x06}); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(0, 3, 4))); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); EXPECT_EQ(answer, server_id1); EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x00, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a}), answer)); EXPECT_EQ(answer, server_id2); } TEST_F(LoadBalancerDecoderTest, GetConfigId) { EXPECT_FALSE( LoadBalancerDecoder::GetConfigId(QuicConnectionId()).has_value()); for (uint8_t i = 0; i < kNumLoadBalancerConfigs; i++) { const QuicConnectionId connection_id( {static_cast<unsigned char>(i << kConnectionIdLengthBits)}); auto config_id = LoadBalancerDecoder::GetConfigId(connection_id); EXPECT_EQ(config_id, LoadBalancerDecoder::GetConfigId(connection_id.data()[0])); EXPECT_TRUE(config_id.has_value()); EXPECT_EQ(*config_id, i); } EXPECT_FALSE( LoadBalancerDecoder::GetConfigId(QuicConnectionId({0xe0})).has_value()); } TEST_F(LoadBalancerDecoderTest, GetConfig) { LoadBalancerDecoder decoder; decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(2, 3, 4)); EXPECT_EQ(decoder.GetConfig(0), nullptr); EXPECT_EQ(decoder.GetConfig(1), nullptr); EXPECT_EQ(decoder.GetConfig(3), nullptr); EXPECT_EQ(decoder.GetConfig(4), nullptr); const LoadBalancerConfig* config = decoder.GetConfig(2); ASSERT_NE(config, nullptr); EXPECT_EQ(config->server_id_len(), 3); EXPECT_EQ(config->nonce_len(), 4); EXPECT_FALSE(config->IsEncrypted()); } TEST_F(LoadBalancerDecoderTest, OnePassIgnoreAdditionalBytes) { uint8_t ptext[] = {0x00, 0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x08, 0x0d, 0xbf, 0x48, 0xc0, 0xd1, 0xe5, 0xda, 0x41}; uint8_t ctext[] = {0x00, 0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3, 0xda, 0x41}; LoadBalancerDecoder decoder; decoder.AddConfig( *LoadBalancerConfig::Create(0, 8, 8, absl::string_view(kRawKey, 16))); LoadBalancerServerId original_server_id(absl::Span<uint8_t>(&ptext[1], 8)); QuicConnectionId cid(absl::Span<uint8_t>(ctext, sizeof(ctext))); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId(cid, answer)); EXPECT_EQ(answer, original_server_id); } } } }
197
cpp
google/quiche
load_balancer_encoder
quiche/quic/load_balancer/load_balancer_encoder.cc
quiche/quic/load_balancer/load_balancer_encoder_test.cc
#ifndef QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_ENCODER_H_ #define QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_ENCODER_H_ #include <algorithm> #include <cstdint> #include <optional> #include "absl/numeric/int128.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" namespace quic { namespace test { class LoadBalancerEncoderPeer; } inline constexpr uint8_t kLoadBalancerUnroutableLen = 8; constexpr uint8_t kLoadBalancerLengthMask = (1 << kConnectionIdLengthBits) - 1; constexpr uint8_t kLoadBalancerConfigIdMask = ~kLoadBalancerLengthMask; constexpr uint8_t kLoadBalancerUnroutableConfigId = kNumLoadBalancerConfigs; constexpr uint8_t kLoadBalancerUnroutablePrefix = kLoadBalancerUnroutableConfigId << kConnectionIdLengthBits; class QUIC_EXPORT_PRIVATE LoadBalancerEncoderVisitorInterface { public: virtual ~LoadBalancerEncoderVisitorInterface() {} virtual void OnConfigAdded(uint8_t config_id) = 0; virtual void OnConfigChanged(uint8_t old_config_id, uint8_t new_config_id) = 0; virtual void OnConfigDeleted(uint8_t config_id) = 0; }; class QUIC_EXPORT_PRIVATE LoadBalancerEncoder : public ConnectionIdGeneratorInterface { public: LoadBalancerEncoder(QuicRandom& random, LoadBalancerEncoderVisitorInterface* const visitor, const bool len_self_encoded) : LoadBalancerEncoder(random, visitor, len_self_encoded, kLoadBalancerUnroutableLen) {} ~LoadBalancerEncoder() override {} static std::optional<LoadBalancerEncoder> Create( QuicRandom& random, LoadBalancerEncoderVisitorInterface* visitor, bool len_self_encoded, uint8_t unroutable_connection_id_len = kLoadBalancerUnroutableLen); bool UpdateConfig(const LoadBalancerConfig& config, LoadBalancerServerId server_id); virtual void DeleteConfig(); absl::uint128 num_nonces_left() const { return num_nonces_left_; } virtual bool IsEncoding() const { return config_.has_value(); } virtual bool IsEncrypted() const { return config_.has_value() && config_->IsEncrypted(); } virtual bool len_self_encoded() const { return len_self_encoded_; } QuicConnectionId GenerateConnectionId(); std::optional<QuicConnectionId> GenerateNextConnectionId( const QuicConnectionId& original) override; std::optional<QuicConnectionId> MaybeReplaceConnectionId( const QuicConnectionId& original, const ParsedQuicVersion& version) override; uint8_t ConnectionIdLength(uint8_t first_byte) const override; protected: LoadBalancerEncoder(QuicRandom& random, LoadBalancerEncoderVisitorInterface* const visitor, const bool len_self_encoded, const uint8_t unroutable_connection_id_len) : random_(random), len_self_encoded_(len_self_encoded), visitor_(visitor) { std::fill_n(connection_id_lengths_, kNumLoadBalancerConfigs + 1, unroutable_connection_id_len); } private: friend class test::LoadBalancerEncoderPeer; QuicConnectionId MakeUnroutableConnectionId(uint8_t first_byte); QuicRandom& random_; const bool len_self_encoded_; LoadBalancerEncoderVisitorInterface* const visitor_; std::optional<LoadBalancerConfig> config_; absl::uint128 seed_, num_nonces_left_ = 0; std::optional<LoadBalancerServerId> server_id_; uint8_t connection_id_lengths_[kNumLoadBalancerConfigs + 1]; }; } #endif #include "quiche/quic/load_balancer/load_balancer_encoder.h" #include <cstdint> #include <cstring> #include <optional> #include "absl/cleanup/cleanup.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { absl::uint128 NumberOfNonces(uint8_t nonce_len) { return (static_cast<absl::uint128>(1) << (nonce_len * 8)); } bool WriteUint128(const absl::uint128 in, uint8_t size, QuicDataWriter &out) { if (out.remaining() < size) { QUIC_BUG(quic_bug_435375038_05) << "Call to WriteUint128() does not have enough space in |out|"; return false; } uint64_t num64 = absl::Uint128Low64(in); if (size <= sizeof(num64)) { out.WriteBytes(&num64, size); } else { out.WriteBytes(&num64, sizeof(num64)); num64 = absl::Uint128High64(in); out.WriteBytes(&num64, size - sizeof(num64)); } return true; } } std::optional<LoadBalancerEncoder> LoadBalancerEncoder::Create( QuicRandom &random, LoadBalancerEncoderVisitorInterface *const visitor, const bool len_self_encoded, const uint8_t unroutable_connection_id_len) { if (unroutable_connection_id_len == 0 || unroutable_connection_id_len > kQuicMaxConnectionIdWithLengthPrefixLength) { QUIC_BUG(quic_bug_435375038_01) << "Invalid unroutable_connection_id_len = " << static_cast<int>(unroutable_connection_id_len); return std::optional<LoadBalancerEncoder>(); } return LoadBalancerEncoder(random, visitor, len_self_encoded, unroutable_connection_id_len); } bool LoadBalancerEncoder::UpdateConfig(const LoadBalancerConfig &config, const LoadBalancerServerId server_id) { if (config_.has_value() && config_->config_id() == config.config_id()) { QUIC_BUG(quic_bug_435375038_02) << "Attempting to change config with same ID"; return false; } if (server_id.length() != config.server_id_len()) { QUIC_BUG(quic_bug_435375038_03) << "Server ID length " << static_cast<int>(server_id.length()) << " does not match configured value of " << static_cast<int>(config.server_id_len()); return false; } if (visitor_ != nullptr) { if (config_.has_value()) { visitor_->OnConfigChanged(config_->config_id(), config.config_id()); } else { visitor_->OnConfigAdded(config.config_id()); } } config_ = config; server_id_ = server_id; seed_ = absl::MakeUint128(random_.RandUint64(), random_.RandUint64()) % NumberOfNonces(config.nonce_len()); num_nonces_left_ = NumberOfNonces(config.nonce_len()); connection_id_lengths_[config.config_id()] = config.total_len(); return true; } void LoadBalancerEncoder::DeleteConfig() { if (visitor_ != nullptr && config_.has_value()) { visitor_->OnConfigDeleted(config_->config_id()); } config_.reset(); server_id_.reset(); num_nonces_left_ = 0; } QuicConnectionId LoadBalancerEncoder::GenerateConnectionId() { absl::Cleanup cleanup = [&] { if (num_nonces_left_ == 0) { DeleteConfig(); } }; uint8_t config_id = config_.has_value() ? config_->config_id() : kLoadBalancerUnroutableConfigId; uint8_t shifted_config_id = config_id << kConnectionIdLengthBits; uint8_t length = connection_id_lengths_[config_id]; if (config_.has_value() != server_id_.has_value()) { QUIC_BUG(quic_bug_435375038_04) << "Existence of config and server_id are out of sync"; return QuicConnectionId(); } uint8_t first_byte; if (len_self_encoded_) { first_byte = shifted_config_id | (length - 1); } else { random_.RandBytes(static_cast<void *>(&first_byte), 1); first_byte = shifted_config_id | (first_byte & kLoadBalancerLengthMask); } if (!config_.has_value()) { return MakeUnroutableConnectionId(first_byte); } uint8_t result[kQuicMaxConnectionIdWithLengthPrefixLength]; QuicDataWriter writer(length, reinterpret_cast<char *>(result), quiche::HOST_BYTE_ORDER); writer.WriteUInt8(first_byte); absl::uint128 next_nonce = (seed_ + num_nonces_left_--) % NumberOfNonces(config_->nonce_len()); writer.WriteBytes(server_id_->data().data(), server_id_->length()); if (!WriteUint128(next_nonce, config_->nonce_len(), writer)) { return QuicConnectionId(); } if (!config_->IsEncrypted()) { absl::uint128 nonce_hash = QuicUtils::FNV1a_128_Hash(absl::string_view( reinterpret_cast<char *>(result), config_->total_len())); const uint64_t lo = absl::Uint128Low64(nonce_hash); if (config_->nonce_len() <= sizeof(uint64_t)) { memcpy(&result[1 + config_->server_id_len()], &lo, config_->nonce_len()); return QuicConnectionId(reinterpret_cast<char *>(result), config_->total_len()); } memcpy(&result[1 + config_->server_id_len()], &lo, sizeof(uint64_t)); const uint64_t hi = absl::Uint128High64(nonce_hash); memcpy(&result[1 + config_->server_id_len() + sizeof(uint64_t)], &hi, config_->nonce_len() - sizeof(uint64_t)); return QuicConnectionId(reinterpret_cast<char *>(result), config_->total_len()); } if (config_->plaintext_len() == kLoadBalancerBlockSize) { if (!config_->BlockEncrypt(&result[1], &result[1])) { return QuicConnectionId(); } return (QuicConnectionId(reinterpret_cast<char *>(result), config_->total_len())); } return config_->FourPassEncrypt( absl::Span<uint8_t>(result, config_->total_len())); } std::optional<QuicConnectionId> LoadBalancerEncoder::GenerateNextConnectionId( [[maybe_unused]] const QuicConnectionId &original) { return (IsEncoding() && !IsEncrypted()) ? std::optional<QuicConnectionId>() : GenerateConnectionId(); } std::optional<QuicConnectionId> LoadBalancerEncoder::MaybeReplaceConnectionId( const QuicConnectionId &original, const ParsedQuicVersion &version) { uint8_t needed_length = config_.has_value() ? config_->total_len() : connection_id_lengths_[kNumLoadBalancerConfigs]; return (!version.HasIetfQuicFrames() && original.length() == needed_length) ? std::optional<QuicConnectionId>() : GenerateConnectionId(); } uint8_t LoadBalancerEncoder::ConnectionIdLength(uint8_t first_byte) const { if (len_self_encoded()) { return (first_byte &= kLoadBalancerLengthMask) + 1; } return connection_id_lengths_[first_byte >> kConnectionIdLengthBits]; } QuicConnectionId LoadBalancerEncoder::MakeUnroutableConnectionId( uint8_t first_byte) { QuicConnectionId id; uint8_t target_length = connection_id_lengths_[kLoadBalancerUnroutableConfigId]; id.set_length(target_length); id.mutable_data()[0] = first_byte; random_.RandBytes(&id.mutable_data()[1], target_length - 1); return id; } }
#include "quiche/quic/load_balancer/load_balancer_encoder.h" #include <cstddef> #include <cstdint> #include <cstring> #include <optional> #include <queue> #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class LoadBalancerEncoderPeer { public: static void SetNumNoncesLeft(LoadBalancerEncoder &encoder, uint64_t nonces_remaining) { encoder.num_nonces_left_ = absl::uint128(nonces_remaining); } }; namespace { class TestLoadBalancerEncoderVisitor : public LoadBalancerEncoderVisitorInterface { public: ~TestLoadBalancerEncoderVisitor() override {} void OnConfigAdded(const uint8_t config_id) override { num_adds_++; current_config_id_ = config_id; } void OnConfigChanged(const uint8_t old_config_id, const uint8_t new_config_id) override { num_adds_++; num_deletes_++; EXPECT_EQ(old_config_id, current_config_id_); current_config_id_ = new_config_id; } void OnConfigDeleted(const uint8_t config_id) override { EXPECT_EQ(config_id, current_config_id_); current_config_id_.reset(); num_deletes_++; } uint32_t num_adds() const { return num_adds_; } uint32_t num_deletes() const { return num_deletes_; } private: uint32_t num_adds_ = 0, num_deletes_ = 0; std::optional<uint8_t> current_config_id_ = std::optional<uint8_t>(); }; class TestRandom : public QuicRandom { public: uint64_t RandUint64() override { if (next_values_.empty()) { return base_; } uint64_t value = next_values_.front(); next_values_.pop(); return value; } void RandBytes(void *data, size_t len) override { size_t written = 0; uint8_t *ptr = static_cast<uint8_t *>(data); while (written < len) { uint64_t result = RandUint64(); size_t to_write = (len - written > sizeof(uint64_t)) ? sizeof(uint64_t) : (len - written); memcpy(ptr + written, &result, to_write); written += to_write; } } void InsecureRandBytes(void *data, size_t len) override { RandBytes(data, len); } uint64_t InsecureRandUint64() override { return RandUint64(); } void AddNextValues(uint64_t hi, uint64_t lo) { next_values_.push(hi); next_values_.push(lo); } private: std::queue<uint64_t> next_values_; uint64_t base_ = 0xDEADBEEFDEADBEEF; }; class LoadBalancerEncoderTest : public QuicTest { public: TestRandom random_; }; LoadBalancerServerId MakeServerId(const uint8_t array[], const uint8_t length) { return LoadBalancerServerId(absl::Span<const uint8_t>(array, length)); } constexpr char kRawKey[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; constexpr absl::string_view kKey(kRawKey, kLoadBalancerKeyLen); constexpr uint64_t kNonceLow = 0xe5d1c048bf0d08ee; constexpr uint64_t kNonceHigh = 0x9321e7e34dde525d; constexpr uint8_t kServerId[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xab, 0x65, 0xba, 0x04, 0xc3, 0x33, 0x0a}; TEST_F(LoadBalancerEncoderTest, BadUnroutableLength) { EXPECT_QUIC_BUG( EXPECT_FALSE( LoadBalancerEncoder::Create(random_, nullptr, false, 0).has_value()), "Invalid unroutable_connection_id_len = 0"); EXPECT_QUIC_BUG( EXPECT_FALSE( LoadBalancerEncoder::Create(random_, nullptr, false, 21).has_value()), "Invalid unroutable_connection_id_len = 21"); } TEST_F(LoadBalancerEncoderTest, BadServerIdLength) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::CreateUnencrypted(1, 3, 4); ASSERT_TRUE(config.has_value()); EXPECT_QUIC_BUG( EXPECT_FALSE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 4))), "Server ID length 4 does not match configured value of 3"); EXPECT_FALSE(encoder->IsEncoding()); } TEST_F(LoadBalancerEncoderTest, FailToUpdateConfigWithSameId) { TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::CreateUnencrypted(1, 3, 4); ASSERT_TRUE(config.has_value()); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); EXPECT_EQ(visitor.num_adds(), 1u); EXPECT_QUIC_BUG( EXPECT_FALSE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))), "Attempting to change config with same ID"); EXPECT_EQ(visitor.num_adds(), 1u); } struct LoadBalancerEncoderTestCase { LoadBalancerConfig config; QuicConnectionId connection_id; LoadBalancerServerId server_id; }; TEST_F(LoadBalancerEncoderTest, UnencryptedConnectionIdTestVectors) { const struct LoadBalancerEncoderTestCase test_vectors[2] = { { *LoadBalancerConfig::CreateUnencrypted(0, 3, 4), QuicConnectionId({0x07, 0xed, 0x79, 0x3a, 0x80, 0x49, 0x71, 0x8a}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::CreateUnencrypted(1, 8, 5), QuicConnectionId({0x2d, 0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0x8e, 0x98, 0x53, 0xfe, 0x93}), MakeServerId(kServerId, 8), }, }; for (const auto &test : test_vectors) { random_.AddNextValues(kNonceHigh, kNonceLow); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 8); EXPECT_TRUE(encoder->UpdateConfig(test.config, test.server_id)); absl::uint128 nonces_left = encoder->num_nonces_left(); EXPECT_EQ(encoder->GenerateConnectionId(), test.connection_id); EXPECT_EQ(encoder->num_nonces_left(), nonces_left - 1); } } TEST_F(LoadBalancerEncoderTest, FollowSpecExample) { const uint8_t config_id = 0, server_id_len = 3, nonce_len = 4; const uint8_t raw_server_id[] = { 0x31, 0x44, 0x1a, }; const char raw_key[] = { 0xfd, 0xf7, 0x26, 0xa9, 0x89, 0x3e, 0xc0, 0x5c, 0x06, 0x32, 0xd3, 0x95, 0x66, 0x80, 0xba, 0xf0, }; random_.AddNextValues(0, 0x75c2699c); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 8); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::Create(config_id, server_id_len, nonce_len, absl::string_view(raw_key)); ASSERT_TRUE(config.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config, LoadBalancerServerId(raw_server_id))); EXPECT_TRUE(encoder->IsEncoding()); const char raw_connection_id[] = {0x07, 0x67, 0x94, 0x7d, 0x29, 0xbe, 0x05, 0x4a}; auto expected = QuicConnectionId(raw_connection_id, 1 + server_id_len + nonce_len); EXPECT_EQ(encoder->GenerateConnectionId(), expected); } TEST_F(LoadBalancerEncoderTest, EncoderTestVectors) { const LoadBalancerEncoderTestCase test_vectors[4] = { { *LoadBalancerConfig::Create(0, 3, 4, kKey), QuicConnectionId({0x07, 0x20, 0xb1, 0xd0, 0x7b, 0x35, 0x9d, 0x3c}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::Create(1, 10, 5, kKey), QuicConnectionId({0x2f, 0xcc, 0x38, 0x1b, 0xc7, 0x4c, 0xb4, 0xfb, 0xad, 0x28, 0x23, 0xa3, 0xd1, 0xf8, 0xfe, 0xd2}), MakeServerId(kServerId, 10), }, { *LoadBalancerConfig::Create(2, 8, 8, kKey), QuicConnectionId({0x50, 0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}), MakeServerId(kServerId, 8), }, { *LoadBalancerConfig::Create(0, 9, 9, kKey), QuicConnectionId({0x12, 0x57, 0x79, 0xc9, 0xcc, 0x86, 0xbe, 0xb3, 0xa3, 0xa4, 0xa3, 0xca, 0x96, 0xfc, 0xe4, 0xbf, 0xe0, 0xcd, 0xbc}), MakeServerId(kServerId, 9), }, }; for (const auto &test : test_vectors) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 8); ASSERT_TRUE(encoder.has_value()); random_.AddNextValues(kNonceHigh, kNonceLow); EXPECT_TRUE(encoder->UpdateConfig(test.config, test.server_id)); EXPECT_EQ(encoder->GenerateConnectionId(), test.connection_id); } } TEST_F(LoadBalancerEncoderTest, RunOutOfNonces) { const uint8_t server_id_len = 3; TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true, 8); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::Create(0, server_id_len, 4, kKey); ASSERT_TRUE(config.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config, MakeServerId(kServerId, server_id_len))); EXPECT_EQ(visitor.num_adds(), 1u); LoadBalancerEncoderPeer::SetNumNoncesLeft(*encoder, 2); EXPECT_EQ(encoder->num_nonces_left(), 2); EXPECT_EQ(encoder->GenerateConnectionId(), QuicConnectionId({0x07, 0x29, 0xd8, 0xc2, 0x17, 0xce, 0x2d, 0x92})); EXPECT_EQ(encoder->num_nonces_left(), 1); encoder->GenerateConnectionId(); EXPECT_EQ(encoder->IsEncoding(), false); EXPECT_EQ(visitor.num_deletes(), 1u); } TEST_F(LoadBalancerEncoderTest, UnroutableConnectionId) { random_.AddNextValues(0x83, kNonceHigh); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); EXPECT_EQ(encoder->num_nonces_left(), 0); auto connection_id = encoder->GenerateConnectionId(); QuicConnectionId expected({0xe3, 0x5d, 0x52, 0xde, 0x4d, 0xe3, 0xe7, 0x21}); EXPECT_EQ(expected, connection_id); } TEST_F(LoadBalancerEncoderTest, NonDefaultUnroutableConnectionIdLength) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 9); ASSERT_TRUE(encoder.has_value()); QuicConnectionId connection_id = encoder->GenerateConnectionId(); EXPECT_EQ(connection_id.length(), 9); } TEST_F(LoadBalancerEncoderTest, DeleteConfigWhenNoConfigExists) { TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); ASSERT_TRUE(encoder.has_value()); encoder->DeleteConfig(); EXPECT_EQ(visitor.num_deletes(), 0u); } TEST_F(LoadBalancerEncoderTest, AddConfig) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); EXPECT_EQ(visitor.num_adds(), 1u); absl::uint128 left = encoder->num_nonces_left(); EXPECT_EQ(left, (0x1ull << 32)); EXPECT_TRUE(encoder->IsEncoding()); EXPECT_FALSE(encoder->IsEncrypted()); encoder->GenerateConnectionId(); EXPECT_EQ(encoder->num_nonces_left(), left - 1); EXPECT_EQ(visitor.num_deletes(), 0u); } TEST_F(LoadBalancerEncoderTest, UpdateConfig) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); config = LoadBalancerConfig::Create(1, 4, 4, kKey); ASSERT_TRUE(config.has_value()); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 4))); EXPECT_EQ(visitor.num_adds(), 2u); EXPECT_EQ(visitor.num_deletes(), 1u); EXPECT_TRUE(encoder->IsEncoding()); EXPECT_TRUE(encoder->IsEncrypted()); } TEST_F(LoadBalancerEncoderTest, DeleteConfig) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); encoder->DeleteConfig(); EXPECT_EQ(visitor.num_adds(), 1u); EXPECT_EQ(visitor.num_deletes(), 1u); EXPECT_FALSE(encoder->IsEncoding()); EXPECT_FALSE(encoder->IsEncrypted()); EXPECT_EQ(encoder->num_nonces_left(), 0); } TEST_F(LoadBalancerEncoderTest, DeleteConfigNoVisitor) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); encoder->DeleteConfig(); EXPECT_FALSE(encoder->IsEncoding()); EXPECT_FALSE(encoder->IsEncrypted()); EXPECT_EQ(encoder->num_nonces_left(), 0); } TEST_F(LoadBalancerEncoderTest, MaybeReplaceConnectionIdReturnsNoChange) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); EXPECT_EQ(encoder->MaybeReplaceConnectionId(TestConnectionId(1), ParsedQuicVersion::Q046()), std::nullopt); } TEST_F(LoadBalancerEncoderTest, MaybeReplaceConnectionIdReturnsChange) { random_.AddNextValues(0x83, kNonceHigh); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); QuicConnectionId expected({0xe3, 0x5d, 0x52, 0xde, 0x4d, 0xe3, 0xe7, 0x21}); EXPECT_EQ(*encoder->MaybeReplaceConnectionId(TestConnectionId(1), ParsedQuicVersion::RFCv1()), expected); } TEST_F(LoadBalancerEncoderTest, GenerateNextConnectionIdReturnsNoChange) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); EXPECT_EQ(encoder->GenerateNextConnectionId(TestConnectionId(1)), std::nullopt); } TEST_F(LoadBalancerEncoderTest, GenerateNextConnectionIdReturnsChange) { random_.AddNextValues(0x83, kNonceHigh); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); QuicConnectionId expected({0xe3, 0x5d, 0x52, 0xde, 0x4d, 0xe3, 0xe7, 0x21}); EXPECT_EQ(*encoder->GenerateNextConnectionId(TestConnectionId(1)), expected); } TEST_F(LoadBalancerEncoderTest, ConnectionIdLengthsEncoded) { auto len_encoder = LoadBalancerEncoder::Create(random_, nullptr, true); ASSERT_TRUE(len_encoder.has_value()); EXPECT_EQ(len_encoder->ConnectionIdLength(0xe8), 9); EXPECT_EQ(len_encoder->ConnectionIdLength(0x4a), 11); EXPECT_EQ(len_encoder->ConnectionIdLength(0x09), 10); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x4a), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x09), kQuicDefaultConnectionIdLength); uint8_t config_id = 0; uint8_t server_id_len = 3; uint8_t nonce_len = 6; uint8_t config_0_len = server_id_len + nonce_len + 1; auto config0 = LoadBalancerConfig::CreateUnencrypted(config_id, server_id_len, nonce_len); ASSERT_TRUE(config0.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config0, MakeServerId(kServerId, server_id_len))); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x4a), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x09), config_0_len); config_id = 1; nonce_len++; uint8_t config_1_len = server_id_len + nonce_len + 1; auto config1 = LoadBalancerConfig::CreateUnencrypted(config_id, server_id_len, nonce_len); ASSERT_TRUE(config1.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config1, MakeServerId(kServerId, server_id_len))); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x2a), config_1_len); EXPECT_EQ(encoder->ConnectionIdLength(0x09), config_0_len); encoder->DeleteConfig(); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x2a), config_1_len); EXPECT_EQ(encoder->ConnectionIdLength(0x09), config_0_len); } } } }
198
cpp
google/quiche
load_balancer_config
quiche/quic/load_balancer/load_balancer_config.cc
quiche/quic/load_balancer/load_balancer_config_test.cc
#ifndef QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_CONFIG_H_ #define QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_CONFIG_H_ #include <cstdint> #include <optional> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "openssl/aes.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class LoadBalancerConfigPeer; } inline constexpr uint8_t kConfigIdBits = 3; inline constexpr uint8_t kConnectionIdLengthBits = 8 - kConfigIdBits; inline constexpr uint8_t kNumLoadBalancerConfigs = (1 << kConfigIdBits) - 1; inline constexpr uint8_t kLoadBalancerKeyLen = 16; inline constexpr uint8_t kLoadBalancerMaxNonceLen = 16; inline constexpr uint8_t kLoadBalancerMinNonceLen = 4; inline constexpr uint8_t kNumLoadBalancerCryptoPasses = 4; class QUIC_EXPORT_PRIVATE LoadBalancerConfig { public: static std::optional<LoadBalancerConfig> Create(uint8_t config_id, uint8_t server_id_len, uint8_t nonce_len, absl::string_view key); static std::optional<LoadBalancerConfig> CreateUnencrypted( uint8_t config_id, uint8_t server_id_len, uint8_t nonce_len); bool FourPassDecrypt(absl::Span<const uint8_t> ciphertext, LoadBalancerServerId& server_id) const; QuicConnectionId FourPassEncrypt(absl::Span<uint8_t> plaintext) const; ABSL_MUST_USE_RESULT bool BlockEncrypt( const uint8_t plaintext[kLoadBalancerBlockSize], uint8_t ciphertext[kLoadBalancerBlockSize]) const; ABSL_MUST_USE_RESULT bool BlockDecrypt( const uint8_t ciphertext[kLoadBalancerBlockSize], uint8_t plaintext[kLoadBalancerBlockSize]) const; uint8_t config_id() const { return config_id_; } uint8_t server_id_len() const { return server_id_len_; } uint8_t nonce_len() const { return nonce_len_; } uint8_t plaintext_len() const { return server_id_len_ + nonce_len_; } uint8_t total_len() const { return server_id_len_ + nonce_len_ + 1; } bool IsEncrypted() const { return key_.has_value(); } private: friend class test::LoadBalancerConfigPeer; LoadBalancerConfig(uint8_t config_id, uint8_t server_id_len, uint8_t nonce_len, absl::string_view key); bool InitializeFourPass(const uint8_t* input, uint8_t* left, uint8_t* right, uint8_t* half_len) const; void EncryptionPass(uint8_t index, uint8_t half_len, bool is_length_odd, uint8_t* left, uint8_t* right) const; uint8_t config_id_; uint8_t server_id_len_; uint8_t nonce_len_; std::optional<AES_KEY> key_; std::optional<AES_KEY> block_decrypt_key_; }; } #endif #include "quiche/quic/load_balancer/load_balancer_config.h" #include <cstdint> #include <cstring> #include <optional> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "openssl/aes.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { namespace { bool CommonValidation(const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len) { if (config_id >= kNumLoadBalancerConfigs || server_id_len == 0 || nonce_len < kLoadBalancerMinNonceLen || nonce_len > kLoadBalancerMaxNonceLen || server_id_len > (kQuicMaxConnectionIdWithLengthPrefixLength - nonce_len - 1)) { QUIC_BUG(quic_bug_433862549_01) << "Invalid LoadBalancerConfig " << "Config ID " << static_cast<int>(config_id) << " Server ID Length " << static_cast<int>(server_id_len) << " Nonce Length " << static_cast<int>(nonce_len); return false; } return true; } std::optional<AES_KEY> BuildKey(absl::string_view key, bool encrypt) { if (key.empty()) { return std::optional<AES_KEY>(); } AES_KEY raw_key; if (encrypt) { if (AES_set_encrypt_key(reinterpret_cast<const uint8_t *>(key.data()), key.size() * 8, &raw_key) < 0) { return std::optional<AES_KEY>(); } } else if (AES_set_decrypt_key(reinterpret_cast<const uint8_t *>(key.data()), key.size() * 8, &raw_key) < 0) { return std::optional<AES_KEY>(); } return raw_key; } } std::optional<LoadBalancerConfig> LoadBalancerConfig::Create( const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len, const absl::string_view key) { if (key.size() != kLoadBalancerKeyLen) { QUIC_BUG(quic_bug_433862549_02) << "Invalid LoadBalancerConfig Key Length: " << key.size(); return std::optional<LoadBalancerConfig>(); } if (!CommonValidation(config_id, server_id_len, nonce_len)) { return std::optional<LoadBalancerConfig>(); } auto new_config = LoadBalancerConfig(config_id, server_id_len, nonce_len, key); if (!new_config.IsEncrypted()) { QUIC_BUG(quic_bug_433862549_03) << "Something went wrong in initializing " "the load balancing key."; return std::optional<LoadBalancerConfig>(); } return new_config; } std::optional<LoadBalancerConfig> LoadBalancerConfig::CreateUnencrypted( const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len) { return CommonValidation(config_id, server_id_len, nonce_len) ? LoadBalancerConfig(config_id, server_id_len, nonce_len, "") : std::optional<LoadBalancerConfig>(); } bool LoadBalancerConfig::FourPassDecrypt( absl::Span<const uint8_t> ciphertext, LoadBalancerServerId& server_id) const { if (ciphertext.size() < plaintext_len()) { QUIC_BUG(quic_bug_599862571_02) << "Called FourPassDecrypt with a short Connection ID"; return false; } if (!key_.has_value()) { return false; } uint8_t* left = server_id.mutable_data(); uint8_t right[kLoadBalancerBlockSize]; uint8_t half_len; bool is_length_odd = InitializeFourPass(ciphertext.data(), left, right, &half_len); uint8_t end_index = (server_id_len_ > nonce_len_) ? 1 : 2; for (uint8_t index = kNumLoadBalancerCryptoPasses; index >= end_index; --index) { EncryptionPass(index, half_len, is_length_odd, left, right); } if (server_id_len_ < half_len || (server_id_len_ == half_len && !is_length_odd)) { return true; } if (is_length_odd) { right[0] |= *(left + --half_len); } memcpy(server_id.mutable_data() + half_len, right, server_id_len_ - half_len); return true; } QuicConnectionId LoadBalancerConfig::FourPassEncrypt( absl::Span<uint8_t> plaintext) const { if (plaintext.size() < total_len()) { QUIC_BUG(quic_bug_599862571_03) << "Called FourPassEncrypt with a short Connection ID"; return QuicConnectionId(); } if (!key_.has_value()) { return QuicConnectionId(); } uint8_t left[kLoadBalancerBlockSize]; uint8_t right[kLoadBalancerBlockSize]; uint8_t half_len; bool is_length_odd = InitializeFourPass(plaintext.data() + 1, left, right, &half_len); for (uint8_t index = 1; index <= kNumLoadBalancerCryptoPasses; ++index) { EncryptionPass(index, half_len, is_length_odd, left, right); } if (is_length_odd) { right[0] |= left[--half_len]; } memcpy(plaintext.data() + 1, left, half_len); memcpy(plaintext.data() + half_len + 1, right, plaintext_len() - half_len); return QuicConnectionId(reinterpret_cast<char*>(plaintext.data()), total_len()); } bool LoadBalancerConfig::BlockEncrypt( const uint8_t plaintext[kLoadBalancerBlockSize], uint8_t ciphertext[kLoadBalancerBlockSize]) const { if (!key_.has_value()) { return false; } AES_encrypt(plaintext, ciphertext, &*key_); return true; } bool LoadBalancerConfig::BlockDecrypt( const uint8_t ciphertext[kLoadBalancerBlockSize], uint8_t plaintext[kLoadBalancerBlockSize]) const { if (!block_decrypt_key_.has_value()) { return false; } AES_decrypt(ciphertext, plaintext, &*block_decrypt_key_); return true; } LoadBalancerConfig::LoadBalancerConfig(const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len, const absl::string_view key) : config_id_(config_id), server_id_len_(server_id_len), nonce_len_(nonce_len), key_(BuildKey(key, true)), block_decrypt_key_((server_id_len + nonce_len == kLoadBalancerBlockSize) ? BuildKey(key, false) : std::optional<AES_KEY>()) {} bool LoadBalancerConfig::InitializeFourPass(const uint8_t* input, uint8_t* left, uint8_t* right, uint8_t* half_len) const { *half_len = plaintext_len() / 2; bool is_length_odd; if (plaintext_len() % 2 == 1) { ++(*half_len); is_length_odd = true; } else { is_length_odd = false; } memset(left, 0, kLoadBalancerBlockSize); memset(right, 0, kLoadBalancerBlockSize); left[kLoadBalancerBlockSize - 2] = plaintext_len(); right[kLoadBalancerBlockSize - 2] = plaintext_len(); memcpy(left, input, *half_len); memcpy(right, input + (plaintext_len() / 2), *half_len); if (is_length_odd) { left[*half_len - 1] &= 0xf0; right[0] &= 0x0f; } return is_length_odd; } void LoadBalancerConfig::EncryptionPass(uint8_t index, uint8_t half_len, bool is_length_odd, uint8_t* left, uint8_t* right) const { uint8_t ciphertext[kLoadBalancerBlockSize]; if (index % 2 == 0) { right[kLoadBalancerBlockSize - 1] = index; AES_encrypt(right, ciphertext, &*key_); for (int i = 0; i < half_len; ++i) { left[i] ^= ciphertext[i]; } if (is_length_odd) { left[half_len - 1] &= 0xf0; } return; } left[kLoadBalancerBlockSize - 1] = index; AES_encrypt(left, ciphertext, &*key_); for (int i = 0; i < half_len; ++i) { right[i] ^= ciphertext[i]; } if (is_length_odd) { right[0] &= 0x0f; } } }
#include "quiche/quic/load_balancer/load_balancer_config.h" #include <array> #include <cstdint> #include <cstring> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class LoadBalancerConfigPeer { public: static bool InitializeFourPass(LoadBalancerConfig& config, const uint8_t* input, uint8_t* left, uint8_t* right, uint8_t* half_len) { return config.InitializeFourPass(input, left, right, half_len); } static void EncryptionPass(LoadBalancerConfig& config, uint8_t index, uint8_t half_len, bool is_length_odd, uint8_t* left, uint8_t* right) { config.EncryptionPass(index, half_len, is_length_odd, left, right); } }; namespace { constexpr char raw_key[] = { 0xfd, 0xf7, 0x26, 0xa9, 0x89, 0x3e, 0xc0, 0x5c, 0x06, 0x32, 0xd3, 0x95, 0x66, 0x80, 0xba, 0xf0, }; class LoadBalancerConfigTest : public QuicTest {}; TEST_F(LoadBalancerConfigTest, InvalidParams) { EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(7, 4, 10).has_value()), "Invalid LoadBalancerConfig Config ID 7 Server ID Length 4 " "Nonce Length 10"); EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerConfig::Create( 2, 0, 10, absl::string_view(raw_key, 16)) .has_value()), "Invalid LoadBalancerConfig Config ID 2 Server ID Length 0 " "Nonce Length 10"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(6, 16, 4).has_value()), "Invalid LoadBalancerConfig Config ID 6 Server ID Length 16 " "Nonce Length 4"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(6, 4, 2).has_value()), "Invalid LoadBalancerConfig Config ID 6 Server ID Length 4 " "Nonce Length 2"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(6, 1, 17).has_value()), "Invalid LoadBalancerConfig Config ID 6 Server ID Length 1 " "Nonce Length 17"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::Create(2, 3, 4, "").has_value()), "Invalid LoadBalancerConfig Key Length: 0"); EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerConfig::Create( 2, 3, 4, absl::string_view(raw_key, 10)) .has_value()), "Invalid LoadBalancerConfig Key Length: 10"); EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerConfig::Create( 0, 3, 4, absl::string_view(raw_key, 17)) .has_value()), "Invalid LoadBalancerConfig Key Length: 17"); } TEST_F(LoadBalancerConfigTest, ValidParams) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); EXPECT_TRUE(config.has_value()); EXPECT_EQ(config->config_id(), 0); EXPECT_EQ(config->server_id_len(), 3); EXPECT_EQ(config->nonce_len(), 4); EXPECT_EQ(config->plaintext_len(), 7); EXPECT_EQ(config->total_len(), 8); EXPECT_FALSE(config->IsEncrypted()); auto config2 = LoadBalancerConfig::Create(2, 6, 7, absl::string_view(raw_key, 16)); EXPECT_TRUE(config.has_value()); EXPECT_EQ(config2->config_id(), 2); EXPECT_EQ(config2->server_id_len(), 6); EXPECT_EQ(config2->nonce_len(), 7); EXPECT_EQ(config2->plaintext_len(), 13); EXPECT_EQ(config2->total_len(), 14); EXPECT_TRUE(config2->IsEncrypted()); } TEST_F(LoadBalancerConfigTest, TestEncryptionPassExample) { auto config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); EXPECT_TRUE(config.has_value()); EXPECT_TRUE(config->IsEncrypted()); uint8_t input[] = {0x07, 0x31, 0x44, 0x1a, 0x9c, 0x69, 0xc2, 0x75}; std::array<uint8_t, kLoadBalancerBlockSize> left, right; uint8_t half_len; bool is_length_odd = LoadBalancerConfigPeer::InitializeFourPass( *config, input + 1, left.data(), right.data(), &half_len); EXPECT_TRUE(is_length_odd); std::array<std::array<uint8_t, kLoadBalancerBlockSize>, kNumLoadBalancerCryptoPasses + 1> expected_left = {{ {0x31, 0x44, 0x1a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00}, {0x31, 0x44, 0x1a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01}, {0xd4, 0xa0, 0x48, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01}, {0xd4, 0xa0, 0x48, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x03}, {0x67, 0x94, 0x7d, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x03}, }}; std::array<std::array<uint8_t, kLoadBalancerBlockSize>, kNumLoadBalancerCryptoPasses + 1> expected_right = {{ {0x0c, 0x69, 0xc2, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00}, {0x0e, 0x3c, 0x1f, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00}, {0x0e, 0x3c, 0x1f, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x02}, {0x09, 0xbe, 0x05, 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x02}, {0x09, 0xbe, 0x05, 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x04}, }}; EXPECT_EQ(left, expected_left[0]); EXPECT_EQ(right, expected_right[0]); for (int i = 1; i <= kNumLoadBalancerCryptoPasses; ++i) { LoadBalancerConfigPeer::EncryptionPass(*config, i, half_len, is_length_odd, left.data(), right.data()); EXPECT_EQ(left, expected_left[i]); EXPECT_EQ(right, expected_right[i]); } } TEST_F(LoadBalancerConfigTest, EncryptionPassesAreReversible) { auto config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); std::array<uint8_t, kLoadBalancerBlockSize> start_left = { 0x31, 0x44, 0x1a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, }; std::array<uint8_t, kLoadBalancerBlockSize> start_right = { 0x0c, 0x69, 0xc2, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, }; std::array<uint8_t, kLoadBalancerBlockSize> left = start_left, right = start_right; LoadBalancerConfigPeer::EncryptionPass(*config, 1, 4, true, left.data(), right.data()); LoadBalancerConfigPeer::EncryptionPass(*config, 2, 4, true, left.data(), right.data()); LoadBalancerConfigPeer::EncryptionPass(*config, 2, 4, true, left.data(), right.data()); LoadBalancerConfigPeer::EncryptionPass(*config, 1, 4, true, left.data(), right.data()); left[15] = 0; right[15] = 0; EXPECT_EQ(left, start_left); EXPECT_EQ(right, start_right); } TEST_F(LoadBalancerConfigTest, InvalidBlockEncryption) { uint8_t pt[kLoadBalancerBlockSize + 1], ct[kLoadBalancerBlockSize]; auto pt_config = LoadBalancerConfig::CreateUnencrypted(0, 8, 8); ASSERT_TRUE(pt_config.has_value()); EXPECT_FALSE(pt_config->BlockEncrypt(pt, ct)); EXPECT_FALSE(pt_config->BlockDecrypt(ct, pt)); EXPECT_TRUE(pt_config->FourPassEncrypt(absl::Span<uint8_t>(pt, sizeof(pt))) .IsEmpty()); LoadBalancerServerId answer; EXPECT_FALSE(pt_config->FourPassDecrypt( absl::Span<uint8_t>(pt, sizeof(pt) - 1), answer)); auto small_cid_config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); ASSERT_TRUE(small_cid_config.has_value()); EXPECT_TRUE(small_cid_config->BlockEncrypt(pt, ct)); EXPECT_FALSE(small_cid_config->BlockDecrypt(ct, pt)); auto block_config = LoadBalancerConfig::Create(0, 8, 8, absl::string_view(raw_key, 16)); ASSERT_TRUE(block_config.has_value()); EXPECT_TRUE(block_config->BlockEncrypt(pt, ct)); EXPECT_TRUE(block_config->BlockDecrypt(ct, pt)); } TEST_F(LoadBalancerConfigTest, BlockEncryptionExample) { const uint8_t ptext[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x08, 0x0d, 0xbf, 0x48, 0xc0, 0xd1, 0xe5}; const uint8_t ctext[] = {0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}; const char key[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; uint8_t result[sizeof(ptext)]; auto config = LoadBalancerConfig::Create(0, 8, 8, absl::string_view(key, 16)); EXPECT_TRUE(config->BlockEncrypt(ptext, result)); EXPECT_EQ(memcmp(result, ctext, sizeof(ctext)), 0); EXPECT_TRUE(config->BlockDecrypt(ctext, result)); EXPECT_EQ(memcmp(result, ptext, sizeof(ptext)), 0); } TEST_F(LoadBalancerConfigTest, ConfigIsCopyable) { const uint8_t ptext[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x08, 0x0d, 0xbf, 0x48, 0xc0, 0xd1, 0xe5}; const uint8_t ctext[] = {0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}; const char key[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; uint8_t result[sizeof(ptext)]; auto config = LoadBalancerConfig::Create(0, 8, 8, absl::string_view(key, 16)); auto config2 = config; EXPECT_TRUE(config->BlockEncrypt(ptext, result)); EXPECT_EQ(memcmp(result, ctext, sizeof(ctext)), 0); EXPECT_TRUE(config2->BlockEncrypt(ptext, result)); EXPECT_EQ(memcmp(result, ctext, sizeof(ctext)), 0); } TEST_F(LoadBalancerConfigTest, FourPassInputTooShort) { auto config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); uint8_t input[] = {0x0d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9}; LoadBalancerServerId answer; bool decrypt_result; EXPECT_QUIC_BUG( decrypt_result = config->FourPassDecrypt( absl::Span<const uint8_t>(input, sizeof(input) - 1), answer), "Called FourPassDecrypt with a short Connection ID"); EXPECT_FALSE(decrypt_result); QuicConnectionId encrypt_result; EXPECT_QUIC_BUG(encrypt_result = config->FourPassEncrypt( absl::Span<uint8_t>(input, sizeof(input))), "Called FourPassEncrypt with a short Connection ID"); EXPECT_TRUE(encrypt_result.IsEmpty()); } } } }
199
cpp
google/quiche
load_balancer_server_id
quiche/quic/load_balancer/load_balancer_server_id.cc
quiche/quic/load_balancer/load_balancer_server_id_test.cc
#ifndef QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_SERVER_ID_H_ #define QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_SERVER_ID_H_ #include <array> #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { inline constexpr uint8_t kLoadBalancerMaxServerIdLen = 15; inline constexpr uint8_t kLoadBalancerBlockSize = 16; static_assert(kLoadBalancerMaxServerIdLen <= kLoadBalancerBlockSize, "LoadBalancerServerId array not large enough to hold Server ID"); class QUIC_EXPORT_PRIVATE LoadBalancerServerId { public: LoadBalancerServerId() : length_(0) {} explicit LoadBalancerServerId(absl::Span<const uint8_t> data); explicit LoadBalancerServerId(absl::string_view data); bool operator<(const LoadBalancerServerId& other) const { return data() < other.data(); } bool operator==(const LoadBalancerServerId& other) const { return data() == other.data(); } template <typename H> friend H AbslHashValue(H h, const LoadBalancerServerId& server_id) { return H::combine_contiguous(std::move(h), server_id.data().data(), server_id.length()); } absl::Span<const uint8_t> data() const { return absl::MakeConstSpan(data_.data(), length_); } uint8_t* mutable_data() { return data_.data(); } uint8_t length() const { return length_; } void set_length(uint8_t length); std::string ToString() const; bool IsValid() { return length_ != 0; } private: std::array<uint8_t, kLoadBalancerBlockSize> data_; uint8_t length_; }; } #endif #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include <array> #include <cstdint> #include <cstring> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { LoadBalancerServerId::LoadBalancerServerId(absl::string_view data) : LoadBalancerServerId(absl::MakeSpan( reinterpret_cast<const uint8_t*>(data.data()), data.length())) {} LoadBalancerServerId::LoadBalancerServerId(absl::Span<const uint8_t> data) : length_(data.length()) { if (length_ == 0 || length_ > kLoadBalancerMaxServerIdLen) { QUIC_BUG(quic_bug_433312504_02) << "Attempted to create LoadBalancerServerId with length " << static_cast<int>(length_); length_ = 0; return; } memcpy(data_.data(), data.data(), data.length()); } void LoadBalancerServerId::set_length(uint8_t length) { QUIC_BUG_IF(quic_bug_599862571_01, length == 0 || length > kLoadBalancerMaxServerIdLen) << "Attempted to set LoadBalancerServerId length to " << static_cast<int>(length); length_ = length; } std::string LoadBalancerServerId::ToString() const { return absl::BytesToHexString( absl::string_view(reinterpret_cast<const char*>(data_.data()), length_)); } }
#include "quiche/quic/load_balancer/load_balancer_server_id.h" #include <cstdint> #include <cstring> #include "absl/hash/hash_testing.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class LoadBalancerServerIdTest : public QuicTest {}; constexpr uint8_t kRawServerId[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; TEST_F(LoadBalancerServerIdTest, CreateReturnsNullIfTooLong) { EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerServerId( absl::Span<const uint8_t>(kRawServerId, 16)) .IsValid()), "Attempted to create LoadBalancerServerId with length 16"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerServerId(absl::Span<const uint8_t>()).IsValid()), "Attempted to create LoadBalancerServerId with length 0"); } TEST_F(LoadBalancerServerIdTest, CompareIdenticalExceptLength) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15)); ASSERT_TRUE(server_id.IsValid()); EXPECT_EQ(server_id.length(), 15); LoadBalancerServerId shorter_server_id( absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(shorter_server_id.IsValid()); EXPECT_EQ(shorter_server_id.length(), 5); EXPECT_TRUE(shorter_server_id < server_id); EXPECT_FALSE(server_id < shorter_server_id); EXPECT_FALSE(shorter_server_id == server_id); } TEST_F(LoadBalancerServerIdTest, AccessorFunctions) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 5)); EXPECT_TRUE(server_id.IsValid()); EXPECT_EQ(server_id.length(), 5); EXPECT_EQ(memcmp(server_id.data().data(), kRawServerId, 5), 0); EXPECT_EQ(server_id.ToString(), "0001020304"); } TEST_F(LoadBalancerServerIdTest, CompareDifferentServerIds) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(server_id.IsValid()); LoadBalancerServerId reverse({0x0f, 0x0e, 0x0d, 0x0c, 0x0b}); ASSERT_TRUE(reverse.IsValid()); EXPECT_TRUE(server_id < reverse); LoadBalancerServerId long_server_id( absl::Span<const uint8_t>(kRawServerId, 15)); EXPECT_TRUE(long_server_id < reverse); } TEST_F(LoadBalancerServerIdTest, EqualityOperators) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15)); ASSERT_TRUE(server_id.IsValid()); LoadBalancerServerId shorter_server_id( absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(shorter_server_id.IsValid()); EXPECT_FALSE(server_id == shorter_server_id); LoadBalancerServerId server_id2 = server_id; EXPECT_TRUE(server_id == server_id2); } TEST_F(LoadBalancerServerIdTest, SupportsHash) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15)); ASSERT_TRUE(server_id.IsValid()); LoadBalancerServerId shorter_server_id( absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(shorter_server_id.IsValid()); LoadBalancerServerId different_server_id({0x0f, 0x0e, 0x0d, 0x0c, 0x0b}); ASSERT_TRUE(different_server_id.IsValid()); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ server_id, shorter_server_id, different_server_id, })); } TEST_F(LoadBalancerServerIdTest, SetLengthInvalid) { LoadBalancerServerId server_id; EXPECT_QUIC_BUG(server_id.set_length(16), "Attempted to set LoadBalancerServerId length to 16"); EXPECT_QUIC_BUG(server_id.set_length(0), "Attempted to set LoadBalancerServerId length to 0"); server_id.set_length(1); EXPECT_EQ(server_id.length(), 1); server_id.set_length(15); EXPECT_EQ(server_id.length(), 15); } } } }