From 82d23c853d5d83867079805641800404d582bbfa Mon Sep 17 00:00:00 2001 From: Dmitri Plotnikov Date: Wed, 25 Nov 2026 18:04:03 -0800 Subject: [PATCH] Add support for declared opaque and abstract types in CEL env config Adds `types` declarations (`opaque` and `abstract`) to `cel::Env` config, YAML serialization/deserialization, type checking, and `EnvRuntime` evaluation. Type checking: - Declared types are resolved in dependency order with cycle detection, conflict checks (against protobuf, custom, built-in, well-known, variable, and container-qualified names), and an expanded type node limit to prevent exponential expansion. - Declared types are registered with the type checker so they can be used as type literals and resolved in variable and function declarations. Name segments may be CEL reserved words, which must be backtick-escaped in expressions. - Extracts `ValidateTypeForDeclaration` into `checker/internal/type_validation` so checker and env share the same validation logic. Runtime: - `EnvRuntime` registers declared types as type-erased opaque types (owned by the runtime) and enables qualified type identifiers so expressions such as `type(x) == foo.Bar` evaluate. PiperOrigin-RevId: 1030307027 --- checker/internal/BUILD | 16 +- checker/internal/type_checker_builder_impl.cc | 75 +- checker/internal/type_validation.cc | 97 ++ checker/internal/type_validation.h | 38 + common/BUILD | 3 + common/signature.cc | 12 +- common/type_spec_resolver.cc | 41 +- common/type_spec_resolver.h | 9 + common/type_spec_resolver_test.cc | 156 ++- env/BUILD | 26 +- env/config.cc | 173 +++ env/config.h | 51 + env/config_test.cc | 354 +++++- env/env.cc | 690 +++++++++- env/env.h | 35 + env/env_runtime.cc | 64 + env/env_runtime.h | 17 + env/env_runtime_test.cc | 309 +++++ env/env_test.cc | 1114 +++++++++++++++++ env/env_yaml.cc | 130 +- env/env_yaml_test.cc | 220 ++++ env/type_info.cc | 44 +- env/type_info.h | 4 + env/type_info_test.cc | 77 +- 24 files changed, 3638 insertions(+), 117 deletions(-) create mode 100644 checker/internal/type_validation.cc create mode 100644 checker/internal/type_validation.h diff --git a/checker/internal/BUILD b/checker/internal/BUILD index 608081563..46fca2918 100644 --- a/checker/internal/BUILD +++ b/checker/internal/BUILD @@ -135,6 +135,7 @@ cc_library( ":proto_type_mask", ":type_check_env", ":type_inference_context", + ":type_validation", "//checker:checker_options", "//checker:type_check_issue", "//checker:type_checker", @@ -153,7 +154,6 @@ cc_library( "//common:standard_definitions", "//common:type", "//common:type_kind", - "//internal:lexis", "//internal:status_macros", "//parser:macro", "@com_google_absl//absl/base:no_destructor", @@ -240,6 +240,20 @@ cc_test( ], ) +cc_library( + name = "type_validation", + srcs = ["type_validation.cc"], + hdrs = ["type_validation.h"], + deps = [ + "//common:type", + "//common:type_kind", + "//internal:lexis", + "//internal:status_macros", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + ], +) + cc_library( name = "type_inference_context", srcs = ["type_inference_context.cc"], diff --git a/checker/internal/type_checker_builder_impl.cc b/checker/internal/type_checker_builder_impl.cc index ab0caa713..f8cc284c7 100644 --- a/checker/internal/type_checker_builder_impl.cc +++ b/checker/internal/type_checker_builder_impl.cc @@ -36,14 +36,13 @@ #include "checker/internal/proto_type_mask.h" #include "checker/internal/type_check_env.h" #include "checker/internal/type_checker_impl.h" +#include "checker/internal/type_validation.h" #include "checker/type_checker.h" #include "checker/type_checker_builder.h" #include "common/container.h" #include "common/decl.h" #include "common/type.h" #include "common/type_introspector.h" -#include "common/type_kind.h" -#include "internal/lexis.h" #include "internal/status_macros.h" #include "parser/macro.h" #include "google/protobuf/descriptor.h" @@ -204,77 +203,15 @@ std::optional FilterDecl(FunctionDecl decl, return filtered; } -absl::Status ValidateType(const Type& t, bool check_type_param_name, - int depth_limit, int remaining_depth) { - if (remaining_depth-- <= 0) { - return absl::InvalidArgumentError( - absl::StrCat("type nesting limit of ", depth_limit, " exceeded")); - } - switch (t.kind()) { - case TypeKind::kTypeParam: { - if (!check_type_param_name) { - return absl::OkStatus(); - } - const TypeParamType& type_param = t.GetTypeParam(); - if (!internal::LexisIsIdentifier(type_param.name())) { - return absl::InvalidArgumentError( - absl::StrCat("type parameter name '", type_param.name(), - "' is not a valid identifier")); - } - return absl::OkStatus(); - } - case TypeKind::kList: { - Type element_type = t.AsList()->GetElement(); - return ValidateType(element_type, check_type_param_name, depth_limit, - remaining_depth); - } - case TypeKind::kMap: { - Type key_type = t.AsMap()->GetKey(); - Type value_type = t.AsMap()->GetValue(); - CEL_RETURN_IF_ERROR(ValidateType(key_type, check_type_param_name, - depth_limit, remaining_depth)); - return ValidateType(value_type, check_type_param_name, depth_limit, - remaining_depth); - } - case TypeKind::kStruct: { - auto message_type = t.AsMessage(); - if (message_type.has_value() && !static_cast(*message_type)) { - return absl::InvalidArgumentError( - "an empty message type cannot be used in a type declaration"); - } - return absl::OkStatus(); - } - case TypeKind::kOpaque: { - OpaqueType opaque_type = t.GetOpaque(); - for (Type type_param : opaque_type.GetParameters()) { - CEL_RETURN_IF_ERROR(ValidateType(type_param, check_type_param_name, - depth_limit, remaining_depth)); - } - return absl::OkStatus(); - } - case TypeKind::kType: { - TypeType type_type = t.GetType(); - for (Type type_param : type_type.GetParameters()) { - CEL_RETURN_IF_ERROR(ValidateType(type_param, check_type_param_name, - depth_limit, remaining_depth)); - } - return absl::OkStatus(); - } - default: - break; - } - return absl::OkStatus(); -} - absl::Status ValidateFunctionDecl(const FunctionDecl& decl, bool check_type_param_name, int depth_limit) { CEL_RETURN_IF_ERROR(CheckStdMacroOverlap(decl)); for (const auto& ovl : decl.overloads()) { - CEL_RETURN_IF_ERROR(ValidateType(ovl.result(), check_type_param_name, - depth_limit, depth_limit)); + CEL_RETURN_IF_ERROR(ValidateTypeForDeclaration( + ovl.result(), check_type_param_name, depth_limit)); for (const auto& arg : ovl.args()) { CEL_RETURN_IF_ERROR( - ValidateType(arg, check_type_param_name, depth_limit, depth_limit)); + ValidateTypeForDeclaration(arg, check_type_param_name, depth_limit)); } } return absl::OkStatus(); @@ -282,8 +219,8 @@ absl::Status ValidateFunctionDecl(const FunctionDecl& decl, absl::Status ValidateVariableDecl(const VariableDecl& decl, bool check_type_param_name, int depth_limit) { - return ValidateType(decl.type(), check_type_param_name, depth_limit, - depth_limit); + return ValidateTypeForDeclaration(decl.type(), check_type_param_name, + depth_limit); } } // namespace diff --git a/checker/internal/type_validation.cc b/checker/internal/type_validation.cc new file mode 100644 index 000000000..ad66c1572 --- /dev/null +++ b/checker/internal/type_validation.cc @@ -0,0 +1,97 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "checker/internal/type_validation.h" + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "common/type.h" +#include "common/type_kind.h" +#include "internal/lexis.h" +#include "internal/status_macros.h" + +namespace cel::checker_internal { +namespace { + +absl::Status ValidateType(const Type& t, bool check_type_param_name, + int depth_limit, int remaining_depth) { + if (remaining_depth-- <= 0) { + return absl::InvalidArgumentError( + absl::StrCat("type nesting limit of ", depth_limit, " exceeded")); + } + switch (t.kind()) { + case TypeKind::kTypeParam: { + if (!check_type_param_name) { + return absl::OkStatus(); + } + const TypeParamType& type_param = t.GetTypeParam(); + if (!internal::LexisIsIdentifier(type_param.name())) { + return absl::InvalidArgumentError( + absl::StrCat("type parameter name '", type_param.name(), + "' is not a valid identifier")); + } + return absl::OkStatus(); + } + case TypeKind::kList: { + Type element_type = t.AsList()->GetElement(); + return ValidateType(element_type, check_type_param_name, depth_limit, + remaining_depth); + } + case TypeKind::kMap: { + Type key_type = t.AsMap()->GetKey(); + Type value_type = t.AsMap()->GetValue(); + CEL_RETURN_IF_ERROR(ValidateType(key_type, check_type_param_name, + depth_limit, remaining_depth)); + return ValidateType(value_type, check_type_param_name, depth_limit, + remaining_depth); + } + case TypeKind::kStruct: { + auto message_type = t.AsMessage(); + if (message_type.has_value() && !static_cast(*message_type)) { + return absl::InvalidArgumentError( + "an empty message type cannot be used in a type declaration"); + } + return absl::OkStatus(); + } + case TypeKind::kOpaque: { + OpaqueType opaque_type = t.GetOpaque(); + for (Type type_param : opaque_type.GetParameters()) { + CEL_RETURN_IF_ERROR(ValidateType(type_param, check_type_param_name, + depth_limit, remaining_depth)); + } + return absl::OkStatus(); + } + case TypeKind::kType: { + TypeType type_type = t.GetType(); + for (Type type_param : type_type.GetParameters()) { + CEL_RETURN_IF_ERROR(ValidateType(type_param, check_type_param_name, + depth_limit, remaining_depth)); + } + return absl::OkStatus(); + } + default: + break; + } + return absl::OkStatus(); +} + +} // namespace + +absl::Status ValidateTypeForDeclaration(const Type& type, + bool check_type_param_name, + int depth_limit) { + return ValidateType(type, check_type_param_name, depth_limit, depth_limit); +} + +} // namespace cel::checker_internal diff --git a/checker/internal/type_validation.h b/checker/internal/type_validation.h new file mode 100644 index 000000000..7c17174d4 --- /dev/null +++ b/checker/internal/type_validation.h @@ -0,0 +1,38 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef THIRD_PARTY_CEL_CPP_CHECKER_INTERNAL_TYPE_VALIDATION_H_ +#define THIRD_PARTY_CEL_CPP_CHECKER_INTERNAL_TYPE_VALIDATION_H_ + +#include "absl/status/status.h" +#include "common/type.h" + +namespace cel::checker_internal { + +// Validates a type used in a declaration (e.g. of a variable, a function +// overload or a custom type). +// +// Returns an error if `type` is nested deeper than `depth_limit`, if +// `check_type_param_name` is true and a type parameter name is not a valid +// identifier, or if `type` contains an empty message type. +// +// The validation walks `type` as a tree, so callers must bound the expanded +// size of types that share nested type handles. +absl::Status ValidateTypeForDeclaration(const Type& type, + bool check_type_param_name, + int depth_limit); + +} // namespace cel::checker_internal + +#endif // THIRD_PARTY_CEL_CPP_CHECKER_INTERNAL_TYPE_VALIDATION_H_ diff --git a/common/BUILD b/common/BUILD index f5ca6251f..62a26dd4a 100644 --- a/common/BUILD +++ b/common/BUILD @@ -110,6 +110,9 @@ cc_test( "@com_google_absl//absl/base:no_destructor", "@com_google_absl//absl/status", "@com_google_absl//absl/status:status_matchers", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings:string_view", + "@com_google_absl//absl/types:optional", "@com_google_protobuf//:protobuf", ], ) diff --git a/common/signature.cc b/common/signature.cc index 7d89129d0..f79aaa785 100644 --- a/common/signature.cc +++ b/common/signature.cc @@ -451,7 +451,14 @@ absl::StatusOr> SplitTypeList( return SignatureScanner(params, "Invalid type signature").SplitTopLevel(','); } -absl::StatusOr ParseTypeSignature(std::string_view signature) { +constexpr int kMaxTypeSignatureDepth = 128; + +absl::StatusOr ParseTypeSignature( + std::string_view signature, int remaining_depth = kMaxTypeSignatureDepth) { + if (remaining_depth <= 0) { + return absl::InvalidArgumentError( + "Invalid type signature: nesting depth exceeds maximum"); + } if (signature.empty()) { return absl::InvalidArgumentError("Empty type signature"); } @@ -498,7 +505,8 @@ absl::StatusOr ParseTypeSignature(std::string_view signature) { } CEL_ASSIGN_OR_RETURN(auto param_list, SplitTypeList(params_str)); for (std::string_view param_str : param_list) { - CEL_ASSIGN_OR_RETURN(auto param, ParseTypeSignature(param_str)); + CEL_ASSIGN_OR_RETURN(auto param, + ParseTypeSignature(param_str, remaining_depth - 1)); params.push_back(std::move(param)); } } else { diff --git a/common/type_spec_resolver.cc b/common/type_spec_resolver.cc index c3b4bc171..d97ad5de4 100644 --- a/common/type_spec_resolver.cc +++ b/common/type_spec_resolver.cc @@ -36,7 +36,6 @@ #undef GetMessage namespace cel { -namespace { absl::StatusOr> ResolveNamedType( absl::string_view name, const TypeIntrospector& type_introspector) { @@ -47,11 +46,6 @@ absl::StatusOr> ResolveNamedType( return type_introspector.FindType(name); } -bool TypeAcceptsParameters(const Type& type) { - return type.IsOpaque() || type.IsType() || type.IsList() || type.IsMap(); -} -} // namespace - absl::StatusOr ConvertTypeSpecToType( const TypeSpec& type_spec, const TypeIntrospector& type_introspector, google::protobuf::Arena* arena) { @@ -174,29 +168,50 @@ absl::StatusOr ConvertTypeSpecToType( if (type_spec.has_abstract_type()) { const std::string& name = type_spec.abstract_type().name(); + const auto& param_specs = type_spec.abstract_type().parameter_types(); CEL_ASSIGN_OR_RETURN(absl::optional type, ResolveNamedType(name, type_introspector)); if (type.has_value()) { - if (!TypeAcceptsParameters(*type) && - !type_spec.abstract_type().parameter_types().empty()) { + if (param_specs.empty()) { + return *type; + } + if (!type->IsOpaque()) { return absl::InvalidArgumentError( absl::StrCat("Type '", name, "' cannot have type parameters")); } - return *type; + if (!type->GetParameters().empty() && + param_specs.size() != type->GetParameters().size()) { + return absl::InvalidArgumentError(absl::StrCat( + "Type '", name, "' expects ", type->GetParameters().size(), + " type parameter(s), got ", param_specs.size())); + } + // A resolved opaque type with type parameters at the use site is + // instantiated with those parameters below, consistent with cel-go and + // cel-java. + // + // The resolution is intentionally lenient: it accepts type parameters + // for opaque types registered without any, and it does not check that + // the use-site parameters match the registered ones beyond their count. + // This function is also used at evaluation time (e.g. to resolve type + // literals), where type parameterization is erased. Callers that + // resolve type declarations, such as `cel::Env`, enforce stricter + // checks. } // Otherwise fallback to OpaqueType std::vector params; - params.reserve(type_spec.abstract_type().parameter_types().size()); - for (const auto& param_spec : type_spec.abstract_type().parameter_types()) { + params.reserve(param_specs.size()); + for (const auto& param_spec : param_specs) { CEL_ASSIGN_OR_RETURN( auto param, ConvertTypeSpecToType(param_spec, type_introspector, arena)); params.push_back(std::move(param)); } - auto* allocated_name = google::protobuf::Arena::Create(arena, name); - return Type(OpaqueType(arena, absl::string_view(*allocated_name), params)); + absl::string_view resolved_name = type.has_value() ? type->name() : name; + return Type(OpaqueType( + arena, *google::protobuf::Arena::Create(arena, resolved_name), + params)); } if (type_spec.has_type()) { diff --git a/common/type_spec_resolver.h b/common/type_spec_resolver.h index 17fbf27de..e7a7377eb 100644 --- a/common/type_spec_resolver.h +++ b/common/type_spec_resolver.h @@ -16,6 +16,8 @@ #define THIRD_PARTY_CEL_CPP_COMMON_TYPE_SPEC_RESOLVER_H_ #include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "absl/types/optional.h" #include "common/ast.h" #include "common/type.h" #include "common/type_introspector.h" @@ -33,6 +35,13 @@ absl::StatusOr ConvertTypeSpecToType( const TypeSpec& type_spec, const cel::TypeIntrospector& type_introspector, google::protobuf::Arena* arena); +// Resolves a named type the same way as `ConvertTypeSpecToType` resolves +// message and abstract type names: well-known and built-in type names (e.g. +// `google.protobuf.Struct` or `list`) are resolved first, followed by +// `type_introspector`. Returns `std::nullopt` if the name is not found. +absl::StatusOr> ResolveNamedType( + absl::string_view name, const cel::TypeIntrospector& type_introspector); + // Convenience overload for type resolution using only a descriptor pool. absl::StatusOr ConvertTypeSpecToType(const TypeSpec& type_spec, const google::protobuf::DescriptorPool& pool, diff --git a/common/type_spec_resolver_test.cc b/common/type_spec_resolver_test.cc index 056ba8f67..db0cd813a 100644 --- a/common/type_spec_resolver_test.cc +++ b/common/type_spec_resolver_test.cc @@ -23,6 +23,9 @@ #include "absl/base/no_destructor.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "absl/types/optional.h" #include "common/ast.h" #include "common/type.h" #include "common/type_introspector.h" @@ -39,8 +42,8 @@ using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::cel::internal::GetTestingDescriptorPool; using ::testing::HasSubstr; +using ::testing::SizeIs; using ::testing::TestWithParam; -using ::testing::Values; google::protobuf::Arena* GetTestArena() { static absl::NoDestructor arena; @@ -330,6 +333,157 @@ TEST(TypeSpecResolverTest, WellKnownTypeIntrospector) { HasSubstr("Message type 'custom.UnknownMessage' not found"))); } +// Serves the opaque types `foo.Baz<~K,string>` (also under alias +// `foo.BazAlias`) and `foo.Unparameterized`, and list type `custom.IntList`. +class OpaqueTypeIntrospector : public TypeIntrospector { + private: + absl::StatusOr> FindTypeImpl( + absl::string_view name) const override { + if (name == "foo.Baz" || name == "foo.BazAlias") { + return Type(OpaqueType(GetTestArena(), "foo.Baz", + {Type(TypeParamType("K")), Type(StringType())})); + } + if (name == "foo.Unparameterized") { + return Type(OpaqueType(GetTestArena(), "foo.Unparameterized", {})); + } + if (name == "custom.IntList") { + return Type(ListType(GetTestArena(), IntType())); + } + return absl::nullopt; + } +}; + +TEST(TypeSpecResolverTest, ResolvedOpaqueTypeWithoutParams) { + OpaqueTypeIntrospector introspector; + TypeSpec spec(AbstractType("foo.Baz", /*params=*/{})); + ASSERT_OK_AND_ASSIGN( + Type t, ConvertTypeSpecToType(spec, introspector, GetTestArena())); + ASSERT_TRUE(t.IsOpaque()); + EXPECT_EQ(t.name(), "foo.Baz"); + ASSERT_THAT(t.GetParameters(), SizeIs(2)); + ASSERT_TRUE(t.GetParameters()[0].IsTypeParam()); + EXPECT_EQ(t.GetParameters()[0].GetTypeParam().name(), "K"); + EXPECT_TRUE(t.GetParameters()[1].IsString()); +} + +TEST(TypeSpecResolverTest, ResolvedOpaqueTypeKeepsUseSiteParams) { + OpaqueTypeIntrospector introspector; + TypeSpec spec(AbstractType("foo.Baz", {TypeSpec(PrimitiveType::kInt64), + TypeSpec(PrimitiveType::kBytes)})); + ASSERT_OK_AND_ASSIGN( + Type t, ConvertTypeSpecToType(spec, introspector, GetTestArena())); + ASSERT_TRUE(t.IsOpaque()); + EXPECT_EQ(t.name(), "foo.Baz"); + ASSERT_THAT(t.GetParameters(), SizeIs(2)); + EXPECT_TRUE(t.GetParameters()[0].IsInt()); + EXPECT_TRUE(t.GetParameters()[1].IsBytes()); +} + +TEST(TypeSpecResolverTest, ResolvedOpaqueTypeUsesCanonicalName) { + OpaqueTypeIntrospector introspector; + TypeSpec spec(AbstractType( + "foo.BazAlias", + {TypeSpec(PrimitiveType::kInt64), TypeSpec(PrimitiveType::kBytes)})); + ASSERT_OK_AND_ASSIGN( + Type t, ConvertTypeSpecToType(spec, introspector, GetTestArena())); + ASSERT_TRUE(t.IsOpaque()); + EXPECT_EQ(t.name(), "foo.Baz"); + ASSERT_THAT(t.GetParameters(), SizeIs(2)); + EXPECT_TRUE(t.GetParameters()[0].IsInt()); + EXPECT_TRUE(t.GetParameters()[1].IsBytes()); +} + +TEST(TypeSpecResolverTest, + ResolvedUnparameterizedOpaqueTypeAcceptsUseSiteParams) { + OpaqueTypeIntrospector introspector; + TypeSpec spec( + AbstractType("foo.Unparameterized", {TypeSpec(PrimitiveType::kInt64)})); + ASSERT_OK_AND_ASSIGN( + Type t, ConvertTypeSpecToType(spec, introspector, GetTestArena())); + ASSERT_TRUE(t.IsOpaque()); + EXPECT_EQ(t.name(), "foo.Unparameterized"); + ASSERT_THAT(t.GetParameters(), SizeIs(1)); + EXPECT_TRUE(t.GetParameters()[0].IsInt()); +} + +TEST(TypeSpecResolverTest, ResolvedOpaqueTypeTooFewParamsError) { + OpaqueTypeIntrospector introspector; + EXPECT_THAT( + ConvertTypeSpecToType( + TypeSpec(AbstractType("foo.Baz", {TypeSpec(PrimitiveType::kInt64)})), + introspector, GetTestArena()), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'foo.Baz' expects 2 type parameter(s), got 1"))); +} + +TEST(TypeSpecResolverTest, ResolvedOpaqueTypeTooManyParamsError) { + OpaqueTypeIntrospector introspector; + EXPECT_THAT( + ConvertTypeSpecToType( + TypeSpec(AbstractType("foo.Baz", {TypeSpec(PrimitiveType::kInt64), + TypeSpec(PrimitiveType::kString), + TypeSpec(PrimitiveType::kBool)})), + introspector, GetTestArena()), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'foo.Baz' expects 2 type parameter(s), got 3"))); +} + +TEST(TypeSpecResolverTest, ResolvedListTypeWithParamsError) { + OpaqueTypeIntrospector introspector; + EXPECT_THAT( + ConvertTypeSpecToType( + TypeSpec(AbstractType("custom.IntList", + {TypeSpec(PrimitiveType::kString)})), + introspector, GetTestArena()), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'custom.IntList' cannot have type parameters"))); +} + +TEST(TypeSpecResolverTest, ResolvedWellKnownTypeWithParamsError) { + OpaqueTypeIntrospector introspector; + EXPECT_THAT( + ConvertTypeSpecToType( + TypeSpec(AbstractType("google.protobuf.ListValue", + {TypeSpec(PrimitiveType::kInt64)})), + introspector, GetTestArena()), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'google.protobuf.ListValue' cannot have type " + "parameters"))); +} + +TEST(TypeSpecResolverTest, ResolvedOpaqueTypeAsMessageTypeSpec) { + OpaqueTypeIntrospector introspector; + TypeSpec spec(MessageTypeSpec("foo.Baz")); + ASSERT_OK_AND_ASSIGN( + Type t, ConvertTypeSpecToType(spec, introspector, GetTestArena())); + ASSERT_TRUE(t.IsOpaque()); + EXPECT_THAT(t.GetParameters(), SizeIs(2)); +} + +TEST(TypeSpecResolverTest, ResolveNamedTypePrefersWellKnownTypes) { + OpaqueTypeIntrospector introspector; + ASSERT_OK_AND_ASSIGN( + absl::optional type, + ResolveNamedType("google.protobuf.Struct", introspector)); + ASSERT_TRUE(type.has_value()); + EXPECT_TRUE(type->IsMap()); +} + +TEST(TypeSpecResolverTest, ResolveNamedTypeFallsBackToIntrospector) { + OpaqueTypeIntrospector introspector; + ASSERT_OK_AND_ASSIGN(absl::optional type, + ResolveNamedType("foo.BazAlias", introspector)); + ASSERT_TRUE(type.has_value()); + ASSERT_TRUE(type->IsOpaque()); + EXPECT_EQ(type->name(), "foo.Baz"); +} + +TEST(TypeSpecResolverTest, ResolveNamedTypeNotFound) { + OpaqueTypeIntrospector introspector; + EXPECT_THAT(ResolveNamedType("foo.Unknown", introspector), + IsOkAndHolds(absl::nullopt)); +} + TEST(TypeSpecResolverTest, UnknownTypeSpecKindError) { TypeSpec spec; auto t = diff --git a/env/BUILD b/env/BUILD index 1529cd11b..eebc3ef54 100644 --- a/env/BUILD +++ b/env/BUILD @@ -32,7 +32,9 @@ cc_library( "//common:constant", "//common:type", "//common:type_kind", + "//internal:lexis", "//internal:status_macros", + "@com_google_absl//absl/algorithm:container", "@com_google_absl//absl/base:no_destructor", "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/container:flat_hash_set", @@ -51,20 +53,31 @@ cc_library( hdrs = ["env.h"], deps = [ ":config", + "//checker:checker_options", "//checker:type_checker_builder", + "//checker/internal:type_validation", + "//common:ast", "//common:constant", "//common:container", "//common:decl", + "//common:descriptor_pool_type_introspector", + "//common:format_type_name", "//common:signature", "//common:type", + "//common:type_kind", + "//common:type_spec_resolver", "//compiler", "//compiler:compiler_factory", "//compiler:standard_library", "//env/internal:ext_registry", "//internal:status_macros", "//parser:macro", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/base:nullability", "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:flat_hash_set", "@com_google_absl//absl/functional:any_invocable", + "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", "@com_google_protobuf//:protobuf", @@ -77,7 +90,10 @@ cc_library( hdrs = ["env_runtime.h"], deps = [ ":config", + "//common:native_type", + "//common:type", "//env/internal:runtime_ext_registry", + "//internal:casts", "//internal:status_macros", "//runtime", "//runtime:reference_resolver", @@ -85,10 +101,12 @@ cc_library( "//runtime:runtime_builder_factory", "//runtime:runtime_options", "//runtime:standard_functions", + "//runtime/internal:runtime_friend_access", + "//runtime/internal:runtime_impl", "@com_google_absl//absl/functional:any_invocable", "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings:string_view", + "@com_google_absl//absl/strings", "@com_google_protobuf//:protobuf", ], ) @@ -175,6 +193,7 @@ cc_test( "//internal:testing", "@com_google_absl//absl/status", "@com_google_absl//absl/status:status_matchers", + "@com_google_absl//absl/strings:string_view", ], ) @@ -226,6 +245,7 @@ cc_test( "@com_google_absl//absl/status", "@com_google_absl//absl/status:status_matchers", "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/time", "@com_google_absl//absl/types:span", @@ -245,7 +265,9 @@ cc_test( ":runtime_std_extensions", "//checker:validation_result", "//common:ast", + "//common:native_type", "//common:source", + "//common:type", "//common:value", "//compiler", "//extensions:math_ext", @@ -255,8 +277,10 @@ cc_test( "//runtime:activation", "//runtime:runtime_builder", "//runtime:runtime_options", + "@com_google_absl//absl/base:nullability", "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings:string_view", "@com_google_protobuf//:protobuf", ], ) diff --git a/env/config.cc b/env/config.cc index 89120b5cb..3159c7474 100644 --- a/env/config.cc +++ b/env/config.cc @@ -21,14 +21,23 @@ #include #include +#include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/overload.h" #include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" +#include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" +#include "common/ast.h" #include "common/constant.h" +#include "common/type.h" +#include "common/type_introspector.h" +#include "env/type_info.h" +#include "internal/lexis.h" #include "internal/status_macros.h" namespace cel { @@ -55,6 +64,120 @@ const char* ConstantKindToTypeName(const ConstantKind& kind) { }, kind); } + +bool IsBuiltinOrWellKnownTypeName(absl::string_view name) { + if (name == OptionalType::kName || name == "function" || + FindWellKnownType(name).has_value()) { + return true; + } + absl::StatusOr type_spec = + TypeInfoToTypeSpec(Config::TypeInfo{.name = std::string(name)}); + return type_spec.ok() && !type_spec->has_abstract_type(); +} + +// Returns true if `text` matches `[A-Za-z_][A-Za-z0-9_]*`. +// +// Unlike `internal::LexisIsIdentifier`, CEL reserved words (e.g. `in` or +// `package`) are accepted: protobuf packages, messages and fields may use them +// and they can be referenced in CEL expressions by escaping them with +// backticks. +bool IsIdentifierSyntax(absl::string_view text) { + if (text.empty()) { + return false; + } + if (!absl::ascii_isalpha(text.front()) && text.front() != '_') { + return false; + } + return absl::c_all_of( + text, [](char c) { return absl::ascii_isalnum(c) || c == '_'; }); +} + +bool IsValidQualifiedTypeName(absl::string_view name) { + if (name.empty()) { + return false; + } + for (absl::string_view segment : absl::StrSplit(name, '.')) { + if (!IsIdentifierSyntax(segment)) { + return false; + } + } + return true; +} + +// Returns an error if `type_info` refers to a built-in or well-known type with +// a number of type parameters that the type does not support. +absl::Status ValidateBuiltinTypeArity(const Config::TypeInfo& type_info) { + absl::string_view name = type_info.name; + const size_t num_params = type_info.params.size(); + if (name == "list" || name == "type") { + if (num_params > 1) { + return absl::InvalidArgumentError(absl::StrCat( + "Type '", name, "' expects at most 1 type parameter, got ", + num_params, ".")); + } + return absl::OkStatus(); + } + if (name == "map") { + if (num_params != 0 && num_params != 2) { + return absl::InvalidArgumentError(absl::StrCat( + "Type 'map' expects 0 or 2 type parameters, got ", num_params, ".")); + } + return absl::OkStatus(); + } + if (name == OptionalType::kName) { + if (num_params != 1) { + return absl::InvalidArgumentError(absl::StrCat( + "Type '", name, "' expects 1 type parameter, got ", num_params, ".")); + } + return absl::OkStatus(); + } + if (name == "function") { + return absl::InvalidArgumentError( + "Type 'function' cannot be used as a type argument."); + } + if (num_params != 0 && IsBuiltinOrWellKnownTypeName(name)) { + return absl::InvalidArgumentError( + absl::StrCat("Type '", name, "' cannot have type parameters.")); + } + return absl::OkStatus(); +} + +constexpr int kMaxTypeInfoDepth = 128; + +absl::Status ValidateTypeParamInfo(const Config::TypeInfo& param, + int remaining_depth) { + if (remaining_depth <= 0) { + return absl::InvalidArgumentError(absl::StrCat( + "Type nesting depth exceeds maximum of ", kMaxTypeInfoDepth, ".")); + } + if (param.is_type_param) { + if (param.name.empty()) { + return absl::InvalidArgumentError("Type parameter name is empty."); + } + if (!internal::LexisIsIdentifier(param.name)) { + return absl::InvalidArgumentError(absl::StrCat( + "Type parameter '", param.name, "' is not a valid identifier.")); + } + if (!param.params.empty()) { + return absl::InvalidArgumentError(absl::StrCat( + "Type parameter '", param.name, "' cannot have type parameters.")); + } + return absl::OkStatus(); + } + if (param.name.empty()) { + return absl::InvalidArgumentError("Type argument name is empty."); + } + if (!IsValidQualifiedTypeName(param.name)) { + return absl::InvalidArgumentError(absl::StrCat( + "Type argument '", param.name, "' is not a valid type name.")); + } + CEL_RETURN_IF_ERROR(ValidateBuiltinTypeArity(param)); + for (const Config::TypeInfo& nested : param.params) { + CEL_RETURN_IF_ERROR(ValidateTypeParamInfo(nested, remaining_depth - 1)); + } + return absl::OkStatus(); +} + } // namespace absl::Status Config::AddExtensionConfig(std::string name, int version) { @@ -123,6 +246,56 @@ absl::Status Config::SetStandardLibraryConfig( return absl::OkStatus(); } +absl::Status Config::AddTypeConfig(const TypeConfig& type_config) { + const TypeInfo& type_info = type_config.type_info; + if (type_info.name.empty()) { + return absl::InvalidArgumentError("Declared type name is empty."); + } + if (type_info.is_type_param) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", type_info.name, "' cannot be a type parameter.")); + } + if (IsBuiltinOrWellKnownTypeName(type_info.name)) { + return absl::InvalidArgumentError(absl::StrCat( + "Built-in type '", type_info.name, "' cannot be declared.")); + } + if (!IsValidQualifiedTypeName(type_info.name)) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", type_info.name, "' is not a valid type name.")); + } + switch (type_config.kind) { + case TypeConfig::Kind::kOpaque: + if (!type_info.params.empty()) { + return absl::InvalidArgumentError( + absl::StrCat("Opaque type '", type_info.name, + "' cannot have type parameters. Declare it as an " + "abstract type instead.")); + } + break; + case TypeConfig::Kind::kAbstract: + if (type_info.params.empty()) { + return absl::InvalidArgumentError( + absl::StrCat("Abstract type '", type_info.name, + "' must have type parameters. Declare it as an " + "opaque type instead.")); + } + break; + default: + return absl::InvalidArgumentError("Unsupported type declaration kind."); + } + for (const TypeInfo& param : type_info.params) { + CEL_RETURN_IF_ERROR(ValidateTypeParamInfo(param, kMaxTypeInfoDepth)); + } + for (const TypeConfig& existing_type_config : type_configs_) { + if (existing_type_config.type_info.name == type_info.name) { + return absl::AlreadyExistsError( + absl::StrCat("Type '", type_info.name, "' is already declared.")); + } + } + type_configs_.push_back(type_config); + return absl::OkStatus(); +} + absl::Status Config::AddVariableConfig(const VariableConfig& variable_config) { for (const VariableConfig& existing_variable_config : variable_configs_) { if (existing_variable_config.name == variable_config.name) { diff --git a/env/config.h b/env/config.h index f8b1dfb3b..157390a22 100644 --- a/env/config.h +++ b/env/config.h @@ -117,6 +117,56 @@ class Config { bool is_type_param = false; }; + // A custom type declared in the environment. Declared types are available to + // the type checker by name, e.g. as type literals in expressions or when + // resolving variable and function types. + struct TypeConfig { + enum class Kind { + // A type without type parameters, e.g. `foo.Bar`. + kOpaque, + // A type with type parameters, e.g. `foo.Bar<~K,string>`. + kAbstract, + }; + + Kind kind = Kind::kOpaque; + // The name and type parameters of the declared type. + TypeInfo type_info; + }; + + // Adds a declared type to the environment. + // + // The name of a declared type is a dot-separated qualified name, e.g. + // `com.example.Foo`, where each segment matches `[A-Za-z_][A-Za-z0-9_]*`. + // Segments may be CEL reserved words (e.g. `com.example.package.Foo`), since + // protobuf packages and messages may use them; non-leading reserved-word + // segments must be escaped with backticks when referenced in CEL expressions + // (e.g. ``com.example.`package`.Foo``). Leading reserved-word segments cannot + // be referenced directly as type literals in CEL expressions. + // + // Returns an InvalidArgument error if: + // - the type name is empty; + // - the type is a type parameter (`type_info.is_type_param` is set); + // - the type name is the name of a built-in or well-known type, e.g. + // `int`, `list`, `optional_type` or `google.protobuf.Any`; + // - the type name is not a valid qualified name (see above); + // - an opaque type has type parameters; + // - an abstract type has no type parameters; + // - a type parameter is invalid: type parameter names (`~T`) must be valid + // CEL identifiers (not reserved words) without type parameters of their + // own, type argument names must be valid qualified names, and built-in + // type arguments must have a supported number of type parameters (e.g. at + // most 1 for `list`, 0 or 2 for `map`, exactly 1 for `optional_type`, + // none for `int`), or the type nesting depth exceeds the limit. + // + // Returns an AlreadyExists error if a type with the same name was already + // declared. + absl::Status AddTypeConfig(const TypeConfig& type_config); + + // Returns the declared types in the order in which they were added. + const std::vector& GetTypeConfigs() const { + return type_configs_; + } + struct VariableConfig { std::string name; std::string description; @@ -162,6 +212,7 @@ class Config { ContainerConfig container_config_; std::vector extension_configs_; StandardLibraryConfig standard_library_config_; + std::vector type_configs_; std::vector variable_configs_; std::vector function_configs_; diff --git a/env/config_test.cc b/env/config_test.cc index ade83fac2..fe0b04661 100644 --- a/env/config_test.cc +++ b/env/config_test.cc @@ -15,9 +15,12 @@ #include "env/config.h" #include +#include +#include #include "absl/status/status.h" #include "absl/status/status_matchers.h" +#include "absl/strings/string_view.h" #include "common/constant.h" #include "internal/testing.h" @@ -30,7 +33,10 @@ using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Field; using ::testing::HasSubstr; +using ::testing::IsEmpty; +using ::testing::SizeIs; using ::testing::UnorderedElementsAre; +using ::testing::Values; TEST(EnvConfigTest, ExtensionConfigs) { Config config; @@ -105,7 +111,7 @@ TEST_P(StandardLibraryConfigTest, StandardLibraryConfig) { INSTANTIATE_TEST_SUITE_P( StandardLibraryConfigTest, StandardLibraryConfigTest, - ::testing::Values( + Values( StandardLibraryConfigTestCase{ .standard_library_config = {}, }, @@ -199,6 +205,352 @@ INSTANTIATE_TEST_SUITE_P( "specific overload 'add(int,int)'", })); +TEST(TypeConfigTest, AddOpaqueAndAbstractTypes) { + Config config; + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}), + IsOk()); + + ASSERT_THAT(config.GetTypeConfigs(), SizeIs(2)); + EXPECT_EQ(config.GetTypeConfigs()[0].kind, Config::TypeConfig::Kind::kOpaque); + EXPECT_EQ(config.GetTypeConfigs()[0].type_info.name, "foo.Bar"); + EXPECT_THAT(config.GetTypeConfigs()[0].type_info.params, IsEmpty()); + + EXPECT_EQ(config.GetTypeConfigs()[1].kind, + Config::TypeConfig::Kind::kAbstract); + EXPECT_EQ(config.GetTypeConfigs()[1].type_info.name, "foo.Baz"); + ASSERT_THAT(config.GetTypeConfigs()[1].type_info.params, SizeIs(2)); + EXPECT_EQ(config.GetTypeConfigs()[1].type_info.params[0].name, "K"); + EXPECT_TRUE(config.GetTypeConfigs()[1].type_info.params[0].is_type_param); + EXPECT_EQ(config.GetTypeConfigs()[1].type_info.params[1].name, "string"); + EXPECT_FALSE(config.GetTypeConfigs()[1].type_info.params[1].is_type_param); +} + +Config::TypeConfig OpaqueTypeConfig(std::string name) { + return Config::TypeConfig{.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = std::move(name)}}; +} + +Config::TypeConfig AbstractTypeConfig(std::string name, + std::vector params) { + return Config::TypeConfig{ + .kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = std::move(name), .params = std::move(params)}}; +} + +Config::TypeInfo TypeParam(std::string name) { + return Config::TypeInfo{.name = std::move(name), .is_type_param = true}; +} + +struct InvalidTypeConfigTestCase { + std::string test_name; + Config::TypeConfig type_config; + std::string expected_error; +}; + +class InvalidTypeConfigTest + : public testing::TestWithParam {}; + +TEST_P(InvalidTypeConfigTest, AddTypeConfig) { + const InvalidTypeConfigTestCase& param = GetParam(); + Config config; + EXPECT_THAT(config.AddTypeConfig(param.type_config), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr(param.expected_error))); + EXPECT_THAT(config.GetTypeConfigs(), IsEmpty()); +} + +INSTANTIATE_TEST_SUITE_P( + InvalidTypeConfigTest, InvalidTypeConfigTest, + Values( + InvalidTypeConfigTestCase{ + .test_name = "EmptyName", + .type_config = OpaqueTypeConfig(""), + .expected_error = "Declared type name is empty", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeParam", + .type_config = {.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = TypeParam("T")}, + .expected_error = "cannot be a type parameter", + }, + InvalidTypeConfigTestCase{ + .test_name = "OpaqueWithParams", + .type_config = {.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar", + .params = {{.name = "int"}}}}, + .expected_error = "cannot have type parameters", + }, + InvalidTypeConfigTestCase{ + .test_name = "AbstractWithoutParams", + .type_config = AbstractTypeConfig("foo.Bar", {}), + .expected_error = "must have type parameters", + }, + InvalidTypeConfigTestCase{ + .test_name = "EmptyTypeParamName", + .type_config = AbstractTypeConfig("foo.Baz", {TypeParam("")}), + .expected_error = "Type parameter name is empty", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeParamWithParams", + .type_config = AbstractTypeConfig("foo.Baz", + {{.name = "T", + .params = {{.name = "int"}}, + .is_type_param = true}}), + .expected_error = "Type parameter 'T' cannot have type parameters", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeParamStartsWithDigit", + .type_config = AbstractTypeConfig("foo.Baz", {TypeParam("1x")}), + .expected_error = "Type parameter '1x' is not a valid identifier", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeParamWithComma", + .type_config = AbstractTypeConfig("foo.Baz", {TypeParam("a,b")}), + .expected_error = "Type parameter 'a,b' is not a valid identifier", + }, + InvalidTypeConfigTestCase{ + .test_name = "QualifiedTypeParam", + .type_config = AbstractTypeConfig("foo.Baz", {TypeParam("a.b")}), + .expected_error = "Type parameter 'a.b' is not a valid identifier", + }, + InvalidTypeConfigTestCase{ + .test_name = "NestedInvalidTypeParam", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "list", .params = {TypeParam("1x")}}}), + .expected_error = "Type parameter '1x' is not a valid identifier", + }, + InvalidTypeConfigTestCase{ + .test_name = "EmptyTypeArgName", + .type_config = AbstractTypeConfig("foo.Baz", {{.name = ""}}), + .expected_error = "Type argument name is empty", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeArgWithComma", + .type_config = AbstractTypeConfig("foo.Baz", {{.name = "a,b"}}), + .expected_error = "Type argument 'a,b' is not a valid type name", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeArgWithEmptySegment", + .type_config = AbstractTypeConfig("foo.Baz", + {{.name = "foo..Bar"}}), + .expected_error = + "Type argument 'foo..Bar' is not a valid type name", + }, + InvalidTypeConfigTestCase{ + .test_name = "PrimitiveWithParams", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "int", .params = {{.name = "string"}}}}), + .expected_error = "Type 'int' cannot have type parameters", + }, + InvalidTypeConfigTestCase{ + .test_name = "NestedPrimitiveWithParams", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "list", + .params = {{.name = "int", + .params = {{.name = "string"}}}}}}), + .expected_error = "Type 'int' cannot have type parameters", + }, + InvalidTypeConfigTestCase{ + .test_name = "WellKnownTypeWithParams", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "google.protobuf.Struct", + .params = {{.name = "int"}}}}), + .expected_error = + "Type 'google.protobuf.Struct' cannot have type parameters", + }, + InvalidTypeConfigTestCase{ + .test_name = "ListWithTwoParams", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "list", + .params = {{.name = "int"}, {.name = "int"}}}}), + .expected_error = "Type 'list' expects at most 1 type parameter, " + "got 2", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeWithTwoParams", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "type", + .params = {{.name = "int"}, {.name = "int"}}}}), + .expected_error = "Type 'type' expects at most 1 type parameter, " + "got 2", + }, + InvalidTypeConfigTestCase{ + .test_name = "MapWithOneParam", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "map", .params = {{.name = "int"}}}}), + .expected_error = + "Type 'map' expects 0 or 2 type parameters, got 1", + }, + InvalidTypeConfigTestCase{ + .test_name = "MapWithThreeParams", + .type_config = AbstractTypeConfig("foo.Baz", + {{.name = "map", + .params = {{.name = "int"}, + {.name = "int"}, + {.name = "int"}}}}), + .expected_error = + "Type 'map' expects 0 or 2 type parameters, got 3", + }, + InvalidTypeConfigTestCase{ + .test_name = "OptionalWithoutParams", + .type_config = AbstractTypeConfig("foo.Baz", + {{.name = "optional_type"}}), + .expected_error = + "Type 'optional_type' expects 1 type parameter, got 0", + }, + InvalidTypeConfigTestCase{ + .test_name = "OptionalWithTwoParams", + .type_config = AbstractTypeConfig( + "foo.Baz", {{.name = "optional_type", + .params = {{.name = "int"}, {.name = "int"}}}}), + .expected_error = + "Type 'optional_type' expects 1 type parameter, got 2", + }, + InvalidTypeConfigTestCase{ + .test_name = "TypeParamReservedWord", + .type_config = AbstractTypeConfig("foo.Baz", {TypeParam("in")}), + .expected_error = "Type parameter 'in' is not a valid identifier", + }, + InvalidTypeConfigTestCase{ + .test_name = "UnsupportedTypeKind", + .type_config = {.kind = static_cast(99), + .type_info = {.name = "foo.Bar"}}, + .expected_error = "Unsupported type declaration kind", + }, + InvalidTypeConfigTestCase{ + .test_name = "FunctionTypeArg", + .type_config = AbstractTypeConfig("foo.Baz", + {{.name = "function"}}), + .expected_error = + "Type 'function' cannot be used as a type argument", + }), + [](const testing::TestParamInfo& info) { + return info.param.test_name; + }); + +class BuiltinTypeNameTest : public testing::TestWithParam {}; + +TEST_P(BuiltinTypeNameTest, RejectsBuiltinAndWellKnownTypeNames) { + Config config; + EXPECT_THAT(config.AddTypeConfig(OpaqueTypeConfig(std::string(GetParam()))), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("cannot be declared"))); +} + +INSTANTIATE_TEST_SUITE_P( + BuiltinTypeNameTest, BuiltinTypeNameTest, + Values("int", "string", "dyn", "null", "null_type", "any", "timestamp", + "duration", "bool_wrapper", "int_wrapper", "uint_wrapper", + "double_wrapper", "string_wrapper", "bytes_wrapper", "list", "map", + "type", "function", "optional_type", "google.protobuf.Timestamp", + "google.protobuf.Any", "google.protobuf.ListValue")); + +class InvalidTypeNameTest : public testing::TestWithParam {}; + +TEST_P(InvalidTypeNameTest, RejectsInvalidTypeNames) { + Config config; + EXPECT_THAT(config.AddTypeConfig(OpaqueTypeConfig(std::string(GetParam()))), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("is not a valid type name"))); +} + +INSTANTIATE_TEST_SUITE_P(InvalidTypeNameTest, InvalidTypeNameTest, + Values(".foo.Bar", "foo.Bar.", "foo..Bar", "123", + "foo.123", "foo,bar", "foo(bar)", "foo", + "foo-bar", "foo.`bar`", "foo bar")); + +class ValidTypeNameTest : public testing::TestWithParam {}; + +// Names whose segments are CEL reserved words are accepted. Such names must be +// escaped with backticks when they are referenced in CEL expressions. +TEST_P(ValidTypeNameTest, AcceptsValidTypeNames) { + Config config; + ASSERT_THAT(config.AddTypeConfig(OpaqueTypeConfig(std::string(GetParam()))), + IsOk()); + ASSERT_THAT(config.GetTypeConfigs(), SizeIs(1)); + EXPECT_EQ(config.GetTypeConfigs()[0].type_info.name, GetParam()); +} + +INSTANTIATE_TEST_SUITE_P(ValidTypeNameTest, ValidTypeNameTest, + Values("Foo", "_foo", "foo.Bar_1", + "com.example.package.Foo", "a.namespace.B", + "foo.in", "foo.true", "in.Foo")); + +struct ValidTypeParamTestCase { + std::string test_name; + Config::TypeInfo param; +}; + +class ValidTypeParamTest + : public testing::TestWithParam {}; + +TEST_P(ValidTypeParamTest, AcceptsValidTypeParams) { + Config config; + EXPECT_THAT( + config.AddTypeConfig(AbstractTypeConfig("foo.Baz", {GetParam().param})), + IsOk()); +} + +INSTANTIATE_TEST_SUITE_P( + ValidTypeParamTest, ValidTypeParamTest, + Values( + ValidTypeParamTestCase{"TypeParam", TypeParam("_T1")}, + ValidTypeParamTestCase{"Primitive", {.name = "int"}}, + ValidTypeParamTestCase{"ListWithoutParams", {.name = "list"}}, + ValidTypeParamTestCase{"List", + {.name = "list", .params = {{.name = "int"}}}}, + ValidTypeParamTestCase{"MapWithoutParams", {.name = "map"}}, + ValidTypeParamTestCase{ + "Map", + {.name = "map", .params = {{.name = "string"}, TypeParam("V")}}}, + ValidTypeParamTestCase{"TypeWithoutParams", {.name = "type"}}, + ValidTypeParamTestCase{"Type", + {.name = "type", .params = {{.name = "int"}}}}, + ValidTypeParamTestCase{ + "Optional", {.name = "optional_type", .params = {{.name = "int"}}}}, + ValidTypeParamTestCase{"WellKnownType", + {.name = "google.protobuf.Struct"}}, + ValidTypeParamTestCase{ + "AbstractType", {.name = "foo.Bar", .params = {{.name = "int"}}}}, + ValidTypeParamTestCase{"ReservedWordSegment", + {.name = "com.example.package.Foo"}}), + [](const testing::TestParamInfo& info) { + return info.param.test_name; + }); + +TEST(TypeConfigTest, DuplicateTypeConfigReturnsAlreadyExists) { + Config config; + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + EXPECT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Bar", .params = {{.name = "int"}}}}), + StatusIs(absl::StatusCode::kAlreadyExists, + HasSubstr("Type 'foo.Bar' is already declared"))); +} + +TEST(TypeConfigTest, DeeplyNestedTypeParamReturnsInvalidArgument) { + Config::TypeInfo nested = {.name = "int"}; + for (int i = 0; i < 150; ++i) { + nested = {.name = "list", .params = {std::move(nested)}}; + } + Config config; + EXPECT_THAT( + config.AddTypeConfig(AbstractTypeConfig("foo.Deep", {std::move(nested)})), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type nesting depth exceeds maximum"))); +} + TEST(VariableConfigTest, VariableConfig) { Config config; Config::VariableConfig variable_config{ diff --git a/env/env.cc b/env/env.cc index dd71323d5..dfcab3b6b 100644 --- a/env/env.cc +++ b/env/env.cc @@ -14,20 +14,35 @@ #include "env/env.h" +#include #include +#include #include #include #include +#include "absl/base/attributes.h" +#include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include "checker/checker_options.h" +#include "checker/internal/type_validation.h" #include "checker/type_checker_builder.h" +#include "common/ast.h" #include "common/constant.h" #include "common/container.h" #include "common/decl.h" +#include "common/descriptor_pool_type_introspector.h" +#include "common/format_type_name.h" #include "common/signature.h" #include "common/type.h" +#include "common/type_introspector.h" +#include "common/type_kind.h" +#include "common/type_spec_resolver.h" #include "compiler/compiler.h" #include "compiler/compiler_factory.h" #include "compiler/standard_library.h" @@ -118,9 +133,602 @@ absl::StatusOr MakeStdlibSubset( return subset; } -absl::StatusOr FunctionConfigToFunctionDecl( - const Config::FunctionConfig& function_config, google::protobuf::Arena* arena, +// Adapts a shared `TypeIntrospector` for `TypeCheckerBuilder::AddTypeProvider`. +class SharedTypeIntrospector : public TypeIntrospector { + public: + explicit SharedTypeIntrospector( + std::shared_ptr delegate) + : delegate_(std::move(delegate)) {} + + private: + absl::StatusOr> FindTypeImpl( + absl::string_view name) const override { + return delegate_->FindType(name); + } + + absl::StatusOr> FindEnumConstantImpl( + absl::string_view type, absl::string_view value) const override { + return delegate_->FindEnumConstant(type, value); + } + + absl::StatusOr> FindStructTypeFieldByNameImpl( + absl::string_view type, absl::string_view name) const override { + return delegate_->FindStructTypeFieldByName(type, name); + } + + absl::StatusOr>> + ListFieldsForStructTypeImpl(absl::string_view type) const override { + return delegate_->ListFieldsForStructType(type); + } + + std::shared_ptr delegate_; +}; + +// The maximum number of nodes in the expanded tree of a type resolved from the +// config, e.g. `map>` has 4 nodes. +// +// Declared types may reference other declared types, and the resulting +// `cel::Type` values share the handles of the referenced types. Without a +// limit, a small config could describe types whose expanded trees grow +// exponentially with the number of declarations (e.g. `foo.T1`, +// `foo.T2`, ...), while type validation and the type checker +// walk types as trees. The limit is far above what practical declarations +// need. +constexpr int kMaxTypeNodeCount = 1000; + +// Serves the types declared in the environment config. +class DeclaredTypeIntrospector : public TypeIntrospector { + public: + // Adds `type`, which must be backed by memory that outlives this object. + // `node_count` is the number of nodes in the expanded tree of `type`. + void AddType(const Type& type, int node_count) { + types_.insert_or_assign(std::string(type.name()), + DeclaredType{type, node_count}); + } + + // Returns the number of nodes in the expanded tree of the declared type + // `name`, if any. + std::optional FindNodeCount(absl::string_view name) const { + if (auto it = types_.find(name); it != types_.end()) { + return it->second.node_count; + } + return std::nullopt; + } + + bool empty() const { return types_.empty(); } + + private: + struct DeclaredType { + Type type; + int node_count; + }; + + absl::StatusOr> FindTypeImpl( + absl::string_view name) const override { + if (auto it = types_.find(name); it != types_.end()) { + return it->second.type; + } + return std::nullopt; + } + + absl::flat_hash_map types_; +}; + +// Resolves type names with `primary` first and then with `secondary`. +// +// Only type name lookups (`FindType`) are chained: enum constant and struct +// field lookups use the `TypeIntrospector` defaults. This is sufficient for +// resolving the types referenced by the config with `ConvertTypeSpecToType`, +// which is the only intended use. +class ChainedTypeIntrospector : public TypeIntrospector { + public: + ChainedTypeIntrospector( + const TypeIntrospector& primary ABSL_ATTRIBUTE_LIFETIME_BOUND, + const TypeIntrospector& secondary ABSL_ATTRIBUTE_LIFETIME_BOUND) + : primary_(primary), secondary_(secondary) {} + + private: + absl::StatusOr> FindTypeImpl( + absl::string_view name) const override { + CEL_ASSIGN_OR_RETURN(std::optional type, primary_.FindType(name)); + if (type.has_value()) { + return type; + } + return secondary_.FindType(name); + } + + const TypeIntrospector& primary_; + const TypeIntrospector& secondary_; +}; + +// Returns the number of nodes in the expanded tree of the type described by +// `type_info`, saturating at `kMaxTypeNodeCount + 1`. A reference to a declared +// type without type parameters counts as the expanded size of the declared +// type, which is memoized in `declared_types`, so this never walks shared type +// handles. Uses an explicit heap stack to avoid overflowing small fiber stacks +// on deeply nested types. +int CountTypeNodes(const Config::TypeInfo& type_info, + const DeclaredTypeIntrospector& declared_types) { + int count = 0; + std::vector stack = {&type_info}; + while (!stack.empty()) { + const Config::TypeInfo* current = stack.back(); + stack.pop_back(); + int self_cost = 1; + if (!current->is_type_param && current->params.empty()) { + if (std::optional declared_count = + declared_types.FindNodeCount(current->name); + declared_count.has_value()) { + self_cost = *declared_count; + } + } + count += self_cost; + if (count > kMaxTypeNodeCount) { + return kMaxTypeNodeCount + 1; + } + for (const Config::TypeInfo& param : current->params) { + stack.push_back(¶m); + } + } + return count; +} + +// Returns an error if the expanded tree of the type described by `type_info` +// exceeds `kMaxTypeNodeCount` nodes. `context` describes where the type is +// used. +absl::Status CheckTypeNodeCount(const Config::TypeInfo& type_info, + const DeclaredTypeIntrospector& declared_types, + absl::string_view context, + absl::string_view name) { + if (CountTypeNodes(type_info, declared_types) > kMaxTypeNodeCount) { + return absl::InvalidArgumentError( + absl::StrCat(context, " '", name, "' exceeds the maximum of ", + kMaxTypeNodeCount, " nodes in its expanded type")); + } + return absl::OkStatus(); +} + +// Returns whether `type` is an instance of `pattern`, i.e. whether it is equal +// to `pattern` with its type parameters consistently substituted according to +// `bindings`. +bool MatchesTypePattern( + const Type& pattern, const Type& type, + absl::flat_hash_map& bindings) { + if (pattern.IsTypeParam()) { + absl::string_view param_name = pattern.name(); + auto [it, inserted] = bindings.emplace(param_name, type); + return inserted || it->second == type; + } + if (pattern.kind() != type.kind()) { + return false; + } + switch (pattern.kind()) { + case TypeKind::kList: + case TypeKind::kMap: + case TypeKind::kOpaque: + case TypeKind::kType: { + if (pattern.name() != type.name()) { + return false; + } + const auto pattern_params = pattern.GetParameters(); + const auto params = type.GetParameters(); + if (pattern_params.size() != params.size()) { + return false; + } + for (size_t i = 0; i < params.size(); ++i) { + if (!MatchesTypePattern(pattern_params[i], params[i], bindings)) { + return false; + } + } + return true; + } + default: + return pattern == type; + } +} + +// Validates the type parameters of the types referenced by `type_spec` against +// the registered types (e.g. protobuf, custom or declared types). +// +// `ConvertTypeSpecToType` is intentionally lenient with type parameters because +// it is also used at evaluation time, where type parameterization is erased. +// Type declarations in the config are held to a stricter standard: a use of a +// registered opaque type must provide exactly the declared number of type +// parameters, and each parameter must match the corresponding declared +// parameter, with repeated type parameters unified consistently (e.g. given +// `foo.Baz<~K, string>`, `foo.Baz` and `foo.Baz<~T, string>` are +// valid while `foo.Baz`, `foo.Baz` and `foo.Baz` are not; +// given `foo.Pair<~T, ~T>`, `foo.Pair` is valid while +// `foo.Pair` is not). +// +// Names that do not resolve to a registered type are accepted as undeclared +// opaque types with any type parameters. +absl::Status ValidateTypeSpecParameters( + const TypeSpec& type_spec, const TypeIntrospector& type_introspector) { + if (type_spec.has_list_type()) { + return ValidateTypeSpecParameters(type_spec.list_type().elem_type(), + type_introspector); + } + if (type_spec.has_map_type()) { + CEL_RETURN_IF_ERROR(ValidateTypeSpecParameters( + type_spec.map_type().key_type(), type_introspector)); + return ValidateTypeSpecParameters(type_spec.map_type().value_type(), + type_introspector); + } + if (type_spec.has_function()) { + CEL_RETURN_IF_ERROR(ValidateTypeSpecParameters( + type_spec.function().result_type(), type_introspector)); + for (const TypeSpec& arg_type : type_spec.function().arg_types()) { + CEL_RETURN_IF_ERROR( + ValidateTypeSpecParameters(arg_type, type_introspector)); + } + return absl::OkStatus(); + } + if (type_spec.has_type()) { + return ValidateTypeSpecParameters(type_spec.type(), type_introspector); + } + if (!type_spec.has_abstract_type()) { + return absl::OkStatus(); + } + + const std::string& name = type_spec.abstract_type().name(); + const std::vector& param_specs = + type_spec.abstract_type().parameter_types(); + for (const TypeSpec& param_spec : param_specs) { + CEL_RETURN_IF_ERROR( + ValidateTypeSpecParameters(param_spec, type_introspector)); + } + CEL_ASSIGN_OR_RETURN(std::optional registered_type, + ResolveNamedType(name, type_introspector)); + if (!registered_type.has_value() || !registered_type->IsOpaque()) { + // Undeclared names and non-opaque types are handled by + // `ConvertTypeSpecToType`. + return absl::OkStatus(); + } + const auto declared_params = registered_type->GetParameters(); + if (declared_params.empty()) { + if (!param_specs.empty()) { + return absl::InvalidArgumentError( + absl::StrCat("Type '", name, "' cannot have type parameters")); + } + return absl::OkStatus(); + } + if (param_specs.size() != declared_params.size()) { + return absl::InvalidArgumentError( + absl::StrCat("Type '", name, "' expects ", declared_params.size(), + " type parameter(s), got ", param_specs.size())); + } + // Use a temporary arena so discarded pattern-check conversions do not + // accumulate on the long-lived checker arena. + google::protobuf::Arena temp_arena; + absl::flat_hash_map type_param_bindings; + for (size_t i = 0; i < param_specs.size(); ++i) { + CEL_ASSIGN_OR_RETURN( + Type param, + ConvertTypeSpecToType(param_specs[i], type_introspector, &temp_arena)); + if (!MatchesTypePattern(declared_params[i], param, type_param_bindings)) { + Type expected_type = declared_params[i]; + if (expected_type.IsTypeParam()) { + if (auto it = type_param_bindings.find(expected_type.name()); + it != type_param_bindings.end()) { + expected_type = it->second; + } + } + return absl::InvalidArgumentError( + absl::StrCat("Type '", name, "' expects type parameter ", i + 1, + " to be '", FormatTypeName(expected_type), "', got '", + FormatTypeName(param), "'")); + } + } + return absl::OkStatus(); +} + +// Resolves a type from the config against `type_introspector`. Callers must +// check the expanded size of the type with `CheckTypeNodeCount` first. +absl::StatusOr ResolveTypeInfo(const Config::TypeInfo& type_info, + const TypeIntrospector& type_introspector, + google::protobuf::Arena* absl_nonnull arena) { + CEL_ASSIGN_OR_RETURN(TypeSpec type_spec, TypeInfoToTypeSpec(type_info)); + CEL_RETURN_IF_ERROR(ValidateTypeSpecParameters(type_spec, type_introspector)); + return ConvertTypeSpecToType(type_spec, type_introspector, arena); +} + +// Returns `status` with its message prefixed by `context`, so that errors +// identify the config declaration they originate from. +absl::Status AddErrorContext(const absl::Status& status, + absl::string_view context) { + return absl::Status(status.code(), + absl::StrCat(context, ": ", status.message())); +} + +// Like `ResolveTypeInfo`, but prefixes errors with `context`. +absl::StatusOr ResolveTypeInfoWithContext( + const Config::TypeInfo& type_info, + const TypeIntrospector& type_introspector, + google::protobuf::Arena* absl_nonnull arena, absl::string_view context) { + absl::StatusOr type = + ResolveTypeInfo(type_info, type_introspector, arena); + if (!type.ok()) { + return AddErrorContext(type.status(), context); + } + return type; +} + +// Returns the container that encloses `container`, e.g. `foo` for `foo.bar`, +// or an empty string for a top-level container. +absl::string_view ParentContainer(absl::string_view container) { + size_t pos = container.rfind('.'); + return pos == absl::string_view::npos ? absl::string_view() + : container.substr(0, pos); +} + +// Returns the last dot-separated segment of `qualified_name`. +absl::string_view LastSegment(absl::string_view qualified_name) { + size_t pos = qualified_name.rfind('.'); + return pos == absl::string_view::npos ? qualified_name + : qualified_name.substr(pos + 1); +} + +// Returns an error if the name of a type declared in `config` conflicts with +// an existing type in `type_introspector` (e.g. a protobuf or custom type), +// with a variable declared in `config` (including fields of `context_type` or +// a variable shadowing a namespace prefix of the declared type), with a +// container abbreviation or alias, or if the name is ambiguous because +// qualifying it with the config container (or one of its parents) yields the +// name of another type or variable. +absl::Status CheckDeclaredTypeNameConflicts( + const Config& config, const TypeIntrospector& type_introspector, const google::protobuf::DescriptorPool* descriptor_pool) { + // Built-in and well-known type names are rejected by + // `Config::AddTypeConfig`. + absl::flat_hash_set declared_type_names; + for (const Config::TypeConfig& type_config : config.GetTypeConfigs()) { + declared_type_names.insert(type_config.type_info.name); + } + absl::flat_hash_set variable_names; + for (const Config::VariableConfig& variable_config : + config.GetVariableConfigs()) { + variable_names.insert(variable_config.name); + } + if (!config.GetContextType().empty() && descriptor_pool != nullptr) { + if (const google::protobuf::Descriptor* context_desc = + descriptor_pool->FindMessageTypeByName(config.GetContextType()); + context_desc != nullptr) { + for (int i = 0; i < context_desc->field_count(); ++i) { + variable_names.insert(context_desc->field(i)->name()); + } + } + } + const Config::ContainerConfig& container_config = config.GetContainerConfig(); + absl::string_view container = container_config.name; + absl::flat_hash_map + container_abbreviations; + for (const std::string& abbr : container_config.abbreviations) { + container_abbreviations.emplace(LastSegment(abbr), abbr); + } + for (const Config::ContainerConfig::Alias& alias : container_config.aliases) { + container_abbreviations.emplace(alias.alias, alias.qualified_name); + } + + for (const Config::TypeConfig& type_config : config.GetTypeConfigs()) { + absl::string_view name = type_config.type_info.name; + CEL_ASSIGN_OR_RETURN(std::optional existing_type, + type_introspector.FindType(name)); + if (existing_type.has_value()) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", name, "' conflicts with an existing type")); + } + if (variable_names.contains(name)) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", name, "' conflicts with variable '", name, "'")); + } + for (absl::string_view var_prefix = ParentContainer(name); + !var_prefix.empty(); var_prefix = ParentContainer(var_prefix)) { + if (variable_names.contains(var_prefix)) { + return absl::InvalidArgumentError( + absl::StrCat("Declared type '", name, "' conflicts with variable '", + var_prefix, "'")); + } + } + absl::string_view first_segment = name.substr(0, name.find('.')); + if (auto it = container_abbreviations.find(first_segment); + it != container_abbreviations.end() && it->second != name) { + return absl::InvalidArgumentError( + absl::StrCat("Declared type '", name, + "' is ambiguous with container abbreviation or alias " + "for '", + it->second, "'")); + } + for (absl::string_view prefix = container; !prefix.empty(); + prefix = ParentContainer(prefix)) { + std::string qualified_name = absl::StrCat(prefix, ".", name); + CEL_ASSIGN_OR_RETURN(existing_type, + type_introspector.FindType(qualified_name)); + if (existing_type.has_value() || + declared_type_names.contains(qualified_name)) { + return absl::InvalidArgumentError( + absl::StrCat("Declared type '", name, "' is ambiguous with type '", + qualified_name, "' in container '", container, "'")); + } + if (variable_names.contains(qualified_name)) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", name, "' is ambiguous with variable '", + qualified_name, "' in container '", container, "'")); + } + if (name.size() > prefix.size() + 1 && + name.substr(0, prefix.size()) == prefix && + name[prefix.size()] == '.') { + absl::string_view unqualified = name.substr(prefix.size() + 1); + if (variable_names.contains(unqualified)) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", name, "' is ambiguous with variable '", + unqualified, "' in container '", container, "'")); + } + } + } + } + return absl::OkStatus(); +} + +// Resolves the types declared in a config in dependency order, detects +// circular references and adds the resolved types to `declared_types`. +// +// Type parameters of declared types are resolved against `base_introspector` +// and the declared types resolved so far. Type parameterization only applies +// to type checking: at evaluation time type parameters are erased, so type +// literals such as `foo.Baz` in expressions refer to the erased type and remain +// valid, while type declarations in the config must provide valid type +// parameters (see `ValidateTypeSpecParameters`). +class DeclaredTypeResolver { + public: + DeclaredTypeResolver( + const Config& config ABSL_ATTRIBUTE_LIFETIME_BOUND, + const TypeIntrospector& base_introspector ABSL_ATTRIBUTE_LIFETIME_BOUND, + const CheckerOptions& checker_options ABSL_ATTRIBUTE_LIFETIME_BOUND, + google::protobuf::Arena* absl_nonnull arena, + DeclaredTypeIntrospector& declared_types ABSL_ATTRIBUTE_LIFETIME_BOUND) + : config_(config), + checker_options_(checker_options), + arena_(arena), + declared_types_(declared_types), + chained_introspector_(base_introspector, declared_types) { + for (const Config::TypeConfig& type_config : config.GetTypeConfigs()) { + configs_by_name_.emplace(type_config.type_info.name, &type_config); + } + } + + absl::Status ResolveAll() const { + absl::flat_hash_map visit_state; + visit_state.reserve(configs_by_name_.size()); + for (const Config::TypeConfig& type_config : config_.GetTypeConfigs()) { + CEL_RETURN_IF_ERROR(Resolve(type_config, visit_state)); + } + return absl::OkStatus(); + } + + private: + enum class VisitState { kVisiting, kVisited }; + + // Collects all declared types referenced anywhere in `params` in + // left-to-right pre-order using an explicit heap stack. + void CollectReferencedDeclaredTypes( + const std::vector& params, + std::vector& deps) const { + std::vector stack; + stack.reserve(params.size()); + for (auto it = params.rbegin(); it != params.rend(); ++it) { + stack.push_back(&*it); + } + while (!stack.empty()) { + const Config::TypeInfo* info = stack.back(); + stack.pop_back(); + if (info->is_type_param) { + continue; + } + if (auto it = configs_by_name_.find(info->name); + it != configs_by_name_.end()) { + deps.push_back(it->second); + } + for (auto it = info->params.rbegin(); it != info->params.rend(); ++it) { + stack.push_back(&*it); + } + } + } + + absl::Status Resolve( + const Config::TypeConfig& root_config, + absl::flat_hash_map& visit_state) const { + struct Frame { + const Config::TypeConfig* config; + bool expanded; + }; + std::vector stack = {{&root_config, /*expanded=*/false}}; + while (!stack.empty()) { + Frame frame = stack.back(); + stack.pop_back(); + const Config::TypeConfig& type_config = *frame.config; + absl::string_view name = type_config.type_info.name; + + if (!frame.expanded) { + auto [it, inserted] = + visit_state.try_emplace(name, VisitState::kVisiting); + if (!inserted) { + if (it->second == VisitState::kVisited) { + continue; + } + return absl::InvalidArgumentError(absl::StrCat( + "Circular type dependency involving declared type '", name, "'")); + } + stack.push_back({&type_config, /*expanded=*/true}); + std::vector deps; + CollectReferencedDeclaredTypes(type_config.type_info.params, deps); + for (auto it = deps.rbegin(); it != deps.rend(); ++it) { + stack.push_back({*it, /*expanded=*/false}); + } + continue; + } + + // Check the expanded size before resolving the type parameters, which may + // walk the types they reference. + int node_count = CountTypeNodes(type_config.type_info, declared_types_); + if (node_count > kMaxTypeNodeCount) { + return absl::InvalidArgumentError( + absl::StrCat("Declared type '", name, "' exceeds the maximum of ", + kMaxTypeNodeCount, " nodes in its expanded type")); + } + + const std::string context = absl::StrCat("declared type '", name, "'"); + std::vector params; + params.reserve(type_config.type_info.params.size()); + for (const Config::TypeInfo& param : type_config.type_info.params) { + CEL_ASSIGN_OR_RETURN(Type param_type, ResolveTypeInfoWithContext( + param, chained_introspector_, + arena_, context)); + params.push_back(std::move(param_type)); + } + auto* allocated_name = google::protobuf::Arena::Create(arena_, name); + Type declared_type = OpaqueType(arena_, *allocated_name, params); + if (absl::Status status = checker_internal::ValidateTypeForDeclaration( + declared_type, + checker_options_.enable_type_parameter_name_validation, + checker_options_.max_type_decl_nesting); + !status.ok()) { + return AddErrorContext(status, context); + } + declared_types_.AddType(declared_type, node_count); + visit_state[name] = VisitState::kVisited; + } + return absl::OkStatus(); + } + + const Config& config_; + const CheckerOptions& checker_options_; + google::protobuf::Arena* absl_nonnull arena_; + DeclaredTypeIntrospector& declared_types_; + ChainedTypeIntrospector chained_introspector_; + absl::flat_hash_map + configs_by_name_; +}; + +// Creates a `cel::Type` for each type declared in `config`, allocated on +// `arena`. +absl::StatusOr> ResolveDeclaredTypes( + const Config& config, const TypeIntrospector& base_introspector, + const CheckerOptions& checker_options, google::protobuf::Arena* absl_nonnull arena) { + auto declared_types = std::make_unique(); + { + DeclaredTypeResolver resolver(config, base_introspector, checker_options, + arena, *declared_types); + CEL_RETURN_IF_ERROR(resolver.ResolveAll()); + } + return declared_types; +} + +absl::StatusOr FunctionConfigToFunctionDecl( + const Config::FunctionConfig& function_config, + const TypeIntrospector& type_introspector, + const DeclaredTypeIntrospector& declared_types, + google::protobuf::Arena* absl_nonnull arena) { FunctionDecl function_decl; function_decl.set_name(function_config.name); for (const Config::FunctionOverloadConfig& overload_config : @@ -128,14 +736,27 @@ absl::StatusOr FunctionConfigToFunctionDecl( OverloadDecl overload_decl; overload_decl.set_id(overload_config.overload_id); overload_decl.set_member(overload_config.is_member_function); - for (const Config::TypeInfo& parameter : overload_config.parameters) { - CEL_ASSIGN_OR_RETURN(Type parameter_type, - TypeInfoToType(parameter, descriptor_pool, arena)); + const std::string overload_context = + absl::StrCat("function '", function_config.name, "' overload '", + overload_config.overload_id, "'"); + for (size_t i = 0; i < overload_config.parameters.size(); ++i) { + CEL_RETURN_IF_ERROR(CheckTypeNodeCount( + overload_config.parameters[i], declared_types, + "Parameter type of overload", overload_config.overload_id)); + CEL_ASSIGN_OR_RETURN( + Type parameter_type, + ResolveTypeInfoWithContext( + overload_config.parameters[i], type_introspector, arena, + absl::StrCat(overload_context, " parameter ", i + 1))); overload_decl.mutable_args().push_back(parameter_type); } - CEL_ASSIGN_OR_RETURN( - Type return_type, - TypeInfoToType(overload_config.return_type, descriptor_pool, arena)); + CEL_RETURN_IF_ERROR(CheckTypeNodeCount( + overload_config.return_type, declared_types, "Return type of overload", + overload_config.overload_id)); + CEL_ASSIGN_OR_RETURN(Type return_type, + ResolveTypeInfoWithContext( + overload_config.return_type, type_introspector, + arena, absl::StrCat(overload_context, " result"))); overload_decl.set_result(return_type); CEL_RETURN_IF_ERROR(function_decl.AddOverload(overload_decl)); } @@ -190,13 +811,40 @@ absl::StatusOr> Env::NewCompilerBuilder() } google::protobuf::Arena* arena = checker_builder.arena(); + + // Variable and function types are resolved against the protobuf types first, + // then against the custom type introspector (if set) and finally against the + // types declared in the config. Names that are not found are treated as + // opaque types. + DescriptorPoolTypeIntrospector proto_type_introspector( + checker_builder.descriptor_pool()); + std::optional proto_and_custom_type_introspector; + const TypeIntrospector* type_introspector = &proto_type_introspector; + if (type_introspector_ != nullptr) { + type_introspector = &proto_and_custom_type_introspector.emplace( + proto_type_introspector, *type_introspector_); + } + CEL_RETURN_IF_ERROR(CheckDeclaredTypeNameConflicts( + config_, *type_introspector, checker_builder.descriptor_pool())); + CEL_ASSIGN_OR_RETURN( + std::unique_ptr declared_type_introspector, + ResolveDeclaredTypes(config_, *type_introspector, + checker_builder.options(), arena)); + ChainedTypeIntrospector chained_type_introspector( + *type_introspector, *declared_type_introspector); + for (const Config::VariableConfig& variable_config : config_.GetVariableConfigs()) { VariableDecl variable_decl; variable_decl.set_name(variable_config.name); - CEL_ASSIGN_OR_RETURN(Type type, - TypeInfoToType(variable_config.type_info, - descriptor_pool_.get(), arena)); + CEL_RETURN_IF_ERROR(CheckTypeNodeCount( + variable_config.type_info, *declared_type_introspector, + "Type of variable", variable_config.name)); + CEL_ASSIGN_OR_RETURN( + Type type, + ResolveTypeInfoWithContext( + variable_config.type_info, chained_type_introspector, arena, + absl::StrCat("variable '", variable_config.name, "'"))); variable_decl.set_type(type); if (variable_config.value.has_value()) { variable_decl.set_value(variable_config.value); @@ -206,12 +854,26 @@ absl::StatusOr> Env::NewCompilerBuilder() for (const Config::FunctionConfig& function_config : config_.GetFunctionConfigs()) { - CEL_ASSIGN_OR_RETURN(FunctionDecl function_decl, - FunctionConfigToFunctionDecl(function_config, arena, - descriptor_pool_.get())); + CEL_ASSIGN_OR_RETURN( + FunctionDecl function_decl, + FunctionConfigToFunctionDecl(function_config, chained_type_introspector, + *declared_type_introspector, arena)); CEL_RETURN_IF_ERROR(checker_builder.AddFunction(function_decl)); } + // Register the custom type introspector (if set) and declared types with the + // type checker so they are available in expressions (e.g. as type literals) + // and remain alive for the lifetime of the built type checker. Declared types + // are allocated on the checker builder's arena, which is transferred to the + // type checker on Build(). + if (type_introspector_ != nullptr) { + checker_builder.AddTypeProvider( + std::make_unique(type_introspector_)); + } + if (!declared_type_introspector->empty()) { + checker_builder.AddTypeProvider(std::move(declared_type_introspector)); + } + return compiler_builder; } diff --git a/env/env.h b/env/env.h index c4a23e2cb..7f31c5c02 100644 --- a/env/env.h +++ b/env/env.h @@ -20,9 +20,11 @@ #include #include +#include "absl/base/nullability.h" #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" +#include "common/type_introspector.h" #include "compiler/compiler.h" #include "env/config.h" #include "env/internal/ext_registry.h" @@ -57,6 +59,38 @@ class Env { return descriptor_pool_.get(); } + // Sets a type introspector used to resolve custom types both in the config + // (variable and function declarations) and in expressions compiled by the + // resulting type checker (e.g. as type literals). Type names are resolved + // against the well-known types and the descriptor pool first, and then + // against `type_introspector`; protobuf types therefore cannot be shadowed by + // `type_introspector`. Names that are not found are treated as opaque types. + // + // Type references in the config are validated against opaque types returned + // by `type_introspector`: a use of such a type must provide exactly the + // declared number of type parameters, and each parameter must match the + // declared one unless the latter is a type parameter (e.g. given + // `foo.Baz<~K, string>`, `foo.Baz` is valid while `foo.Baz`, + // `foo.Baz` and `foo.Baz` are not). Violations are reported + // by `NewCompilerBuilder` and `NewCompiler`. + // + // `type_introspector` must be thread-safe: it is shared with every compiler + // built from this `Env` and with the type checkers those compilers build, + // which may use it concurrently. + // + // Note: `type_introspector` only affects compilation. `EnvRuntime` does not + // yet register custom types for evaluation, so expressions that depend on + // runtime type identity (e.g. `type(x) == custom.Type`) are not yet + // supported at evaluation time; runtime support is planned as a follow-up. + void SetTypeIntrospector( + std::shared_ptr absl_nullable type_introspector) { + type_introspector_ = std::move(type_introspector); + } + + const TypeIntrospector* absl_nullable GetTypeIntrospector() const { + return type_introspector_.get(); + } + void SetConfig(const Config& config) { config_ = config; } CompilerOptions& GetCompilerOptions() { return compiler_options_; } @@ -69,6 +103,7 @@ class Env { private: cel::env_internal::ExtensionRegistry extension_registry_; std::shared_ptr descriptor_pool_; + std::shared_ptr type_introspector_; CompilerOptions compiler_options_; Config config_; }; diff --git a/env/env_runtime.cc b/env/env_runtime.cc index 420f21764..946db7c62 100644 --- a/env/env_runtime.cc +++ b/env/env_runtime.cc @@ -15,24 +15,82 @@ #include "env/env_runtime.h" #include +#include #include #include #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include "common/native_type.h" +#include "common/type.h" #include "env/config.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/reference_resolver.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_builder_factory.h" #include "runtime/runtime_options.h" #include "runtime/standard_functions.h" +#include "google/protobuf/arena.h" +#include "google/protobuf/descriptor.h" namespace cel { +namespace { + +using internal::down_cast; +using runtime_internal::RuntimeFriendAccess; +using runtime_internal::RuntimeImpl; + +// Registers the types declared in `config` with the runtime type registry so +// that they can be referenced by name in expressions, e.g. `type(x) == +// foo.Bar`. +// +// Type parameters are not tracked during evaluation, so declared types are +// registered as type-erased opaque types: an abstract type `foo.Baz` is +// registered as `foo.Baz`. +absl::Status RegisterDeclaredTypes(const Config& config, + RuntimeBuilder& runtime_builder) { + if (config.GetTypeConfigs().empty()) { + return absl::OkStatus(); + } + Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(runtime_builder); + if (RuntimeFriendAccess::RuntimeTypeId(runtime) != + NativeTypeId::For()) { + return absl::UnimplementedError( + "declared types are only supported on the default cel::Runtime " + "implementation"); + } + const google::protobuf::DescriptorPool* descriptor_pool = runtime.GetDescriptorPool(); + // `TypeRegistry` references, but does not own, the names and data of the + // registered types, so they are allocated on an arena owned by the runtime + // environment, which outlives its type registry. + auto arena = std::make_shared(); + down_cast(&runtime)->environment().KeepAlive(arena); + for (const Config::TypeConfig& type_config : config.GetTypeConfigs()) { + absl::string_view type_name = type_config.type_info.name; + if (descriptor_pool != nullptr && + (descriptor_pool->FindMessageTypeByName(type_name) != nullptr || + descriptor_pool->FindEnumTypeByName(type_name) != nullptr)) { + return absl::InvalidArgumentError(absl::StrCat( + "Declared type '", type_name, "' conflicts with an existing type")); + } + const std::string* name = + google::protobuf::Arena::Create(arena.get(), type_name); + CEL_RETURN_IF_ERROR(runtime_builder.type_registry().RegisterType( + OpaqueType(arena.get(), *name, /*parameters=*/{}))); + } + return absl::OkStatus(); +} + +} // namespace + void EnvRuntime::RegisterExtensionFunctions( absl::string_view name, absl::string_view alias, int version, absl::AnyInvocable EnvRuntime::CreateRuntimeBuilder() const { absl::StatusOr EnvRuntime::CreateRuntimeBuilder( const RuntimeOptions& options) const { RuntimeOptions runtime_options = options; + // Declared types are referenced by their qualified names (e.g. `foo.Bar`), + // which are only resolved to types if qualified type identifiers are enabled. + if (!config_.GetTypeConfigs().empty()) { + runtime_options.enable_qualified_type_identifiers = true; + } const std::vector& extension_configs = config_.GetExtensionConfigs(); const Config::ExtensionConfig* optional_extension_config = nullptr; @@ -65,6 +128,7 @@ absl::StatusOr EnvRuntime::CreateRuntimeBuilder( cel::CreateRuntimeBuilder(descriptor_pool_, runtime_options)); CEL_RETURN_IF_ERROR(EnableReferenceResolver( runtime_builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); + CEL_RETURN_IF_ERROR(RegisterDeclaredTypes(config_, runtime_builder)); if (!config_.GetStandardLibraryConfig().disable) { CEL_RETURN_IF_ERROR(RegisterStandardFunctions( diff --git a/env/env_runtime.h b/env/env_runtime.h index f8a80eb12..be2f4bc4d 100644 --- a/env/env_runtime.h +++ b/env/env_runtime.h @@ -62,6 +62,23 @@ class EnvRuntime { RuntimeOptions& mutable_runtime_options() { return runtime_options_; } + // Creates a runtime builder configured according to the config. + // + // Types declared in the config (`Config::GetTypeConfigs()`) are registered + // with the runtime type registry so that they can be referenced by name in + // expressions, e.g. `type(x) == foo.Bar`, and qualified type identifiers are + // enabled. Type parameters are not tracked during evaluation, so declared + // types are registered as type-erased opaque types without type parameters: + // an abstract type `foo.Baz` is registered as `foo.Baz`. Accordingly, + // `cel::OpaqueValue`s of declared types should report the erased type (e.g. + // `foo.Baz`) as their runtime type for such comparisons to hold. + // + // Unlike `Env`, `EnvRuntime` does not support custom type introspectors, + // because the runtime type registry only accepts concrete types. Custom + // types (e.g. those provided to `Env::SetTypeIntrospector`) must be + // registered with the `type_registry()` of the returned builder, and + // referencing them by qualified name requires + // `RuntimeOptions::enable_qualified_type_identifiers`. absl::StatusOr CreateRuntimeBuilder() const; absl::StatusOr CreateRuntimeBuilder( const RuntimeOptions& options) const; diff --git a/env/env_runtime_test.cc b/env/env_runtime_test.cc index 7e9006846..a9ef0b828 100644 --- a/env/env_runtime_test.cc +++ b/env/env_runtime_test.cc @@ -15,15 +15,21 @@ #include "env/env_runtime.h" #include +#include #include #include #include +#include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/string_view.h" #include "checker/validation_result.h" #include "common/ast.h" +#include "common/native_type.h" #include "common/source.h" +#include "common/type.h" +#include "common/type_introspector.h" #include "common/value.h" #include "compiler/compiler.h" #include "env/config.h" @@ -39,12 +45,15 @@ #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" +#include "google/protobuf/descriptor.h" +#include "google/protobuf/message.h" namespace cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; +using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::ValuesIn; @@ -204,5 +213,305 @@ TEST(EnvRuntimeTest, RegisterExtensionFunctions) { ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(&arena, activation)); EXPECT_TRUE(value.GetBool()); } + +// An opaque value whose runtime type is the type-erased (unparameterized) +// opaque type named `type_name`. +class TestOpaqueValue final : public OpaqueValueInterface { + public: + TestOpaqueValue(google::protobuf::Arena* absl_nonnull arena, + absl::string_view type_name) + : type_name_(type_name), runtime_type_(arena, type_name_, {}) {} + + private: + std::string DebugString() const override { return type_name_; } + + absl::string_view GetTypeName() const override { return type_name_; } + + OpaqueType GetRuntimeType() const override { return runtime_type_; } + + absl::Status Equal(const OpaqueValue& other, + const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool, + google::protobuf::MessageFactory* absl_nonnull message_factory, + google::protobuf::Arena* absl_nonnull arena, + Value* absl_nonnull result) const override { + *result = BoolValue(false); + return absl::OkStatus(); + } + + OpaqueValue Clone(google::protobuf::Arena* absl_nonnull arena) const override { + return OpaqueValue(this, arena); + } + + NativeTypeId GetNativeTypeId() const override { + return NativeTypeId::For(); + } + + const std::string type_name_; + const OpaqueType runtime_type_; +}; + +Config MakeDeclaredTypesConfig() { + Config config; + EXPECT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + EXPECT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}), + IsOk()); + EXPECT_THAT(config.AddVariableConfig( + {.name = "bar", .type_info = {.name = "foo.Bar"}}), + IsOk()); + EXPECT_THAT( + config.AddVariableConfig( + {.name = "baz", + .type_info = {.name = "foo.Baz", + .params = {{.name = "int"}, {.name = "string"}}}}), + IsOk()); + return config; +} + +class DeclaredTypesTest : public testing::TestWithParam {}; + +TEST_P(DeclaredTypesTest, EndToEnd) { + const std::string& expr = GetParam(); + auto descriptor_pool = cel::internal::GetSharedTestingDescriptorPool(); + Config config = MakeDeclaredTypesConfig(); + + Env env; + env.SetDescriptorPool(descriptor_pool); + env.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult result, compiler->Compile(expr)); + ASSERT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr ast, result.ReleaseAst()); + + EnvRuntime env_runtime; + env_runtime.SetDescriptorPool(descriptor_pool); + env_runtime.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr runtime, + env_runtime.NewRuntime()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr program, + runtime->CreateProgram(std::move(ast))); + + google::protobuf::Arena arena; + TestOpaqueValue bar(&arena, "foo.Bar"); + TestOpaqueValue baz(&arena, "foo.Baz"); + Activation activation; + activation.InsertOrAssignValue("bar", OpaqueValue(&bar, &arena)); + activation.InsertOrAssignValue("baz", OpaqueValue(&baz, &arena)); + ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(&arena, activation)); + ASSERT_TRUE(value.IsBool()) << " expr: " << expr << " value: " << value; + EXPECT_TRUE(value.GetBool()) << " expr: " << expr; +} + +INSTANTIATE_TEST_SUITE_P( + DeclaredTypesTest, DeclaredTypesTest, + testing::Values("type(bar) == foo.Bar", "type(baz) == foo.Baz", + "type(bar) != foo.Baz", "type(baz) != foo.Bar", + "foo.Bar == foo.Bar", "foo.Bar != foo.Baz", + "type(foo.Bar) == type", "type(foo.Baz) == type")); + +TEST(DeclaredTypesTest, RuntimeOutlivesEnvRuntime) { + auto descriptor_pool = cel::internal::GetSharedTestingDescriptorPool(); + std::unique_ptr runtime; + std::unique_ptr other_runtime; + { + EnvRuntime env_runtime; + env_runtime.SetDescriptorPool(descriptor_pool); + env_runtime.SetConfig(MakeDeclaredTypesConfig()); + // Each runtime owns its own copy of the declared types. + ASSERT_OK_AND_ASSIGN(runtime, env_runtime.NewRuntime()); + ASSERT_OK_AND_ASSIGN(other_runtime, env_runtime.NewRuntime()); + } + other_runtime.reset(); + + Env env; + env.SetDescriptorPool(descriptor_pool); + env.SetConfig(MakeDeclaredTypesConfig()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult result, + compiler->Compile("foo.Bar == foo.Bar && " + "foo.Bar != foo.Baz")); + ASSERT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr ast, result.ReleaseAst()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr program, + runtime->CreateProgram(std::move(ast))); + + google::protobuf::Arena arena; + Activation activation; + ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(&arena, activation)); + ASSERT_TRUE(value.IsBool()) << value; + EXPECT_TRUE(value.GetBool()); +} + +// Dotted variable names must keep resolving to variables regardless of +// whether declared types enable qualified type identifiers. +class DottedVariableTest : public testing::TestWithParam {}; + +TEST_P(DottedVariableTest, ResolvesVariable) { + const bool with_declared_types = GetParam(); + auto descriptor_pool = cel::internal::GetSharedTestingDescriptorPool(); + Config config; + if (with_declared_types) { + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + } + ASSERT_THAT(config.AddVariableConfig( + {.name = "foo.qux", .type_info = {.name = "int"}}), + IsOk()); + + Env env; + env.SetDescriptorPool(descriptor_pool); + env.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult result, + compiler->Compile("foo.qux == 1")); + ASSERT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr ast, result.ReleaseAst()); + + EnvRuntime env_runtime; + env_runtime.SetDescriptorPool(descriptor_pool); + env_runtime.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr runtime, + env_runtime.NewRuntime()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr program, + runtime->CreateProgram(std::move(ast))); + + google::protobuf::Arena arena; + Activation activation; + activation.InsertOrAssignValue("foo.qux", IntValue(1)); + ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(&arena, activation)); + ASSERT_TRUE(value.IsBool()) << value; + EXPECT_TRUE(value.GetBool()); +} + +INSTANTIATE_TEST_SUITE_P(DottedVariableTest, DottedVariableTest, + testing::Bool()); + +// Serves the opaque type `my.Custom`. +class CustomTypeIntrospector : public TypeIntrospector { + public: + explicit CustomTypeIntrospector(OpaqueType type) : type_(type) {} + + private: + absl::StatusOr> FindTypeImpl( + absl::string_view name) const override { + if (name == type_.name()) { + return Type(type_); + } + return std::nullopt; + } + + OpaqueType type_; +}; + +TEST(EnvRuntimeTest, CustomTypeRegisteredWithRuntimeBuilder) { + auto descriptor_pool = cel::internal::GetSharedTestingDescriptorPool(); + // Outlives the runtime, which references the custom type. + google::protobuf::Arena type_arena; + const OpaqueType custom_type(&type_arena, "my.Custom", {}); + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "c", .type_info = {.name = "my.Custom"}}), + IsOk()); + + Env env; + env.SetDescriptorPool(descriptor_pool); + env.SetTypeIntrospector( + std::make_shared(custom_type)); + env.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult result, + compiler->Compile("type(c) == my.Custom")); + ASSERT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr ast, result.ReleaseAst()); + + EnvRuntime env_runtime; + env_runtime.SetDescriptorPool(descriptor_pool); + env_runtime.SetConfig(config); + env_runtime.mutable_runtime_options().enable_qualified_type_identifiers = + true; + ASSERT_OK_AND_ASSIGN(RuntimeBuilder runtime_builder, + env_runtime.CreateRuntimeBuilder()); + ASSERT_THAT(runtime_builder.type_registry().RegisterType(custom_type), + IsOk()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr runtime, + std::move(runtime_builder).Build()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr program, + runtime->CreateProgram(std::move(ast))); + + google::protobuf::Arena arena; + TestOpaqueValue c(&arena, "my.Custom"); + Activation activation; + activation.InsertOrAssignValue("c", OpaqueValue(&c, &arena)); + ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(&arena, activation)); + ASSERT_TRUE(value.IsBool()) << value; + EXPECT_TRUE(value.GetBool()); +} + +TEST(EnvRuntimeTest, DeclaredTypeWithReservedWordSegmentEvaluates) { + auto descriptor_pool = cel::internal::GetSharedTestingDescriptorPool(); + Config config; + ASSERT_THAT( + config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "com.example.package.Foo"}}), + IsOk()); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "x", .type_info = {.name = "com.example.package.Foo"}}), + IsOk()); + + Env env; + env.SetDescriptorPool(descriptor_pool); + env.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN( + ValidationResult result, + compiler->Compile("type(x) == com.example.`package`.Foo")); + ASSERT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr ast, result.ReleaseAst()); + + EnvRuntime env_runtime; + env_runtime.SetDescriptorPool(descriptor_pool); + env_runtime.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr runtime, + env_runtime.NewRuntime()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr program, + runtime->CreateProgram(std::move(ast))); + + google::protobuf::Arena arena; + TestOpaqueValue x(&arena, "com.example.package.Foo"); + Activation activation; + activation.InsertOrAssignValue("x", OpaqueValue(&x, &arena)); + ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(&arena, activation)); + ASSERT_TRUE(value.IsBool()) << value; + EXPECT_TRUE(value.GetBool()); +} + +TEST(EnvRuntimeTest, DeclaredTypeConflictingWithProtoMessageErrors) { + auto descriptor_pool = cel::internal::GetSharedTestingDescriptorPool(); + Config config; + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "cel.expr.conformance.proto3.TestAllTypes"}}), + IsOk()); + + EnvRuntime env_runtime; + env_runtime.SetDescriptorPool(descriptor_pool); + env_runtime.SetConfig(config); + EXPECT_THAT( + env_runtime.NewRuntime(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Declared type " + "'cel.expr.conformance.proto3.TestAllTypes' conflicts " + "with an existing type"))); +} + } // namespace } // namespace cel diff --git a/env/env_test.cc b/env/env_test.cc index 822f1507f..e98dd458d 100644 --- a/env/env_test.cc +++ b/env/env_test.cc @@ -15,6 +15,7 @@ #include "env/env.h" #include +#include #include #include #include @@ -23,6 +24,7 @@ #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/span.h" @@ -34,6 +36,7 @@ #include "common/decl.h" #include "common/expr.h" #include "common/type.h" +#include "common/type_introspector.h" #include "common/value.h" #include "compiler/compiler.h" #include "env/config.h" @@ -55,6 +58,7 @@ namespace cel { namespace { using ::absl_testing::IsOk; +using ::absl_testing::StatusIs; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Property; @@ -415,6 +419,821 @@ TEST(ContextVariableConfigTest, Basic) { EXPECT_THAT(result_invalid.GetIssues(), Not(IsEmpty())); } +Config MakeTypeConfigTestConfig() { + Config config; + EXPECT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + EXPECT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}), + IsOk()); + EXPECT_THAT(config.AddVariableConfig( + {.name = "bar", .type_info = {.name = "foo.Bar"}}), + IsOk()); + EXPECT_THAT( + config.AddVariableConfig( + {.name = "baz", + .type_info = {.name = "foo.Baz", + .params = {{.name = "int"}, {.name = "string"}}}}), + IsOk()); + EXPECT_THAT( + config.AddFunctionConfig( + {.name = "key", + .overload_configs = {{ + .overload_id = "key_foo_baz", + .parameters = {{.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}, + .return_type = {.name = "K", .is_type_param = true}, + }}}), + IsOk()); + return config; +} + +struct TypeConfigCompileTestCase { + std::string expr; + std::string expected_error; +}; + +class TypeConfigCompileTest + : public testing::TestWithParam {}; + +TEST_P(TypeConfigCompileTest, Compile) { + const TypeConfigCompileTestCase& param = GetParam(); + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + env.SetConfig(MakeTypeConfigTestConfig()); + + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult result, compiler->Compile(param.expr)); + if (param.expected_error.empty()) { + EXPECT_THAT(result.GetIssues(), IsEmpty()) + << " expr: " << param.expr << " error: " << result.FormatError(); + } else { + EXPECT_THAT(result.FormatError(), HasSubstr(param.expected_error)) + << " expr: " << param.expr; + } +} + +INSTANTIATE_TEST_SUITE_P( + TypeConfigCompileTest, TypeConfigCompileTest, + Values(TypeConfigCompileTestCase{.expr = "type(bar) == foo.Bar"}, + // Type parameters are erased at evaluation time, so the type literal + // `foo.Baz` refers to the erased type and remains valid in + // expressions, unlike in type declarations. + TypeConfigCompileTestCase{.expr = "type(baz) == foo.Baz"}, + TypeConfigCompileTestCase{.expr = "key(baz) == 1"}, + TypeConfigCompileTestCase{ + .expr = "key(baz) == 'one'", + .expected_error = "found no matching overload for '_==_'", + }, + TypeConfigCompileTestCase{ + .expr = "key(bar)", + .expected_error = "found no matching overload for 'key'", + }, + TypeConfigCompileTestCase{ + .expr = "foo.Bar{}", + .expected_error = + "type 'foo.Bar' does not support message creation", + }, + TypeConfigCompileTestCase{ + .expr = "foo.Qux", + .expected_error = "undeclared reference to 'foo.Qux'", + })); + +TEST(TypeConfigTest, UndeclaredTypeIsNotATypeLiteral) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "bar", .type_info = {.name = "foo.Bar"}}), + IsOk()); + env.SetConfig(config); + + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + // Undeclared opaque types are still accepted in variable declarations. + ASSERT_OK_AND_ASSIGN(ValidationResult result, compiler->Compile("bar")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); + // But they are not available as type literals. + ASSERT_OK_AND_ASSIGN(result, compiler->Compile("type(bar) == foo.Bar")); + EXPECT_THAT(result.FormatError(), + HasSubstr("undeclared reference to 'foo.Bar'")); +} + +constexpr absl::string_view kTestAllTypes = + "cel.expr.conformance.proto3.TestAllTypes"; + +// Resolves: +// - `custom.Int` to `int`; +// - `custom.Opaque` to an opaque type without type parameters; +// - `custom.Parameterized` to `custom.Parameterized<~K, string>`; +// - `cel.expr.conformance.proto3.TestAllTypes` to `int`, which must be shadowed +// by the protobuf message type of the same name; +// - `custom.Error` to an internal error. +// +// The opaque types are allocated on an arena owned by +// the introspector, so its types are only valid while it is alive. +class CustomTypeIntrospector : public TypeIntrospector { + public: + CustomTypeIntrospector() + : custom_opaque_(OpaqueType(&arena_, "custom.Opaque", {})), + custom_param_(OpaqueType(&arena_, "custom.Parameterized", + {TypeParamType("K"), StringType()})) {} + + private: + absl::StatusOr> FindTypeImpl( + absl::string_view name) const override { + if (name == "custom.Int" || name == kTestAllTypes) { + return IntType(); + } + if (name == "custom.Opaque") { + return custom_opaque_; + } + if (name == "custom.Parameterized") { + return custom_param_; + } + if (name == "custom.Error") { + return absl::InternalError("custom type lookup failed"); + } + return std::nullopt; + } + + google::protobuf::Arena arena_; + Type custom_opaque_; + Type custom_param_; +}; + +TEST(TypeConfigTest, CustomTypeIntrospectorChainedWithProtoAndDeclaredTypes) { + auto custom_introspector = std::make_shared(); + std::unique_ptr compiler; + { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "x", .type_info = {.name = "custom.Int"}}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "c", .type_info = {.name = "custom.Opaque"}}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "bar", .type_info = {.name = "foo.Bar"}}), + IsOk()); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "msg", + .type_info = {.name = + "cel.expr.conformance.proto3.TestAllTypes"}}), + IsOk()); + env.SetConfig(config); + + env.SetTypeIntrospector(custom_introspector); + EXPECT_EQ(env.GetTypeIntrospector(), custom_introspector.get()); + ASSERT_OK_AND_ASSIGN(compiler, env.NewCompiler()); + } + // Drop our reference so the compiler must keep `custom_introspector` alive. + custom_introspector.reset(); + + ASSERT_OK_AND_ASSIGN( + ValidationResult result, + compiler->Compile("x + 1 == 2 && type(c) == custom.Opaque && " + "type(bar) == foo.Bar && msg.single_int64 == x")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); +} + +struct DeclaredTypeNameConflictTestCase { + std::string container; + std::vector abbreviations; + std::vector aliases; + std::string context_type; + std::vector opaque_type_names; + std::vector variable_names; + bool use_custom_type_introspector = false; + std::string expected_error; +}; + +class DeclaredTypeNameConflictTest + : public testing::TestWithParam {}; + +TEST_P(DeclaredTypeNameConflictTest, NewCompilerFails) { + const DeclaredTypeNameConflictTestCase& param = GetParam(); + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + if (param.use_custom_type_introspector) { + env.SetTypeIntrospector(std::make_shared()); + } + Config config; + config.SetContainerConfig({.name = param.container, + .abbreviations = param.abbreviations, + .aliases = param.aliases}); + if (!param.context_type.empty()) { + config.SetContextType(param.context_type); + } + for (const std::string& name : param.opaque_type_names) { + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = name}}), + IsOk()); + } + for (const std::string& name : param.variable_names) { + ASSERT_THAT( + config.AddVariableConfig({.name = name, .type_info = {.name = "int"}}), + IsOk()); + } + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr(param.expected_error))); +} + +INSTANTIATE_TEST_SUITE_P( + DeclaredTypeNameConflictTest, DeclaredTypeNameConflictTest, + Values( + DeclaredTypeNameConflictTestCase{ + .opaque_type_names = {"cel.expr.conformance.proto3.TestAllTypes"}, + .expected_error = "Declared type " + "'cel.expr.conformance.proto3.TestAllTypes' " + "conflicts with an existing type", + }, + DeclaredTypeNameConflictTestCase{ + .opaque_type_names = + {"cel.expr.conformance.proto3.TestAllTypes.NestedEnum"}, + .expected_error = + "Declared type " + "'cel.expr.conformance.proto3.TestAllTypes.NestedEnum' " + "conflicts with an existing type", + }, + DeclaredTypeNameConflictTestCase{ + .opaque_type_names = {"custom.Int"}, + .use_custom_type_introspector = true, + .expected_error = + "Declared type 'custom.Int' conflicts with an existing type", + }, + DeclaredTypeNameConflictTestCase{ + .opaque_type_names = {"foo.Bar"}, + .variable_names = {"foo.Bar"}, + .expected_error = + "Declared type 'foo.Bar' conflicts with variable 'foo.Bar'", + }, + DeclaredTypeNameConflictTestCase{ + .opaque_type_names = {"foo.Bar"}, + .variable_names = {"foo"}, + .expected_error = + "Declared type 'foo.Bar' conflicts with variable 'foo'", + }, + DeclaredTypeNameConflictTestCase{ + .context_type = "cel.expr.conformance.proto3.TestAllTypes", + .opaque_type_names = {"single_int64"}, + .expected_error = + "Declared type 'single_int64' conflicts with variable " + "'single_int64'", + }, + DeclaredTypeNameConflictTestCase{ + .container = "foo", + .opaque_type_names = {"Bar"}, + .variable_names = {"foo.Bar"}, + .expected_error = + "Declared type 'Bar' is ambiguous with variable 'foo.Bar' in " + "container 'foo'", + }, + DeclaredTypeNameConflictTestCase{ + .container = "foo", + .opaque_type_names = {"foo.Bar"}, + .variable_names = {"Bar"}, + .expected_error = + "Declared type 'foo.Bar' is ambiguous with variable 'Bar' in " + "container 'foo'", + }, + DeclaredTypeNameConflictTestCase{ + .abbreviations = {"pkg.Bar"}, + .opaque_type_names = {"Bar"}, + .expected_error = + "Declared type 'Bar' is ambiguous with container abbreviation " + "or alias for 'pkg.Bar'", + }, + DeclaredTypeNameConflictTestCase{ + .aliases = {{.alias = "f", .qualified_name = "pkg.f"}}, + .opaque_type_names = {"f.Bar"}, + .expected_error = + "Declared type 'f.Bar' is ambiguous with container " + "abbreviation or alias for 'pkg.f'", + }, + DeclaredTypeNameConflictTestCase{ + .container = "cel.expr.conformance.proto3", + .opaque_type_names = {"TestAllTypes"}, + .expected_error = + "Declared type 'TestAllTypes' is ambiguous with type " + "'cel.expr.conformance.proto3.TestAllTypes' in container " + "'cel.expr.conformance.proto3'", + }, + DeclaredTypeNameConflictTestCase{ + .container = "cel.expr.conformance.proto3.sub", + .opaque_type_names = {"TestAllTypes"}, + .expected_error = + "Declared type 'TestAllTypes' is ambiguous with type " + "'cel.expr.conformance.proto3.TestAllTypes' in container " + "'cel.expr.conformance.proto3.sub'", + }, + DeclaredTypeNameConflictTestCase{ + .container = "foo", + .opaque_type_names = {"Bar", "foo.Bar"}, + .expected_error = "Declared type 'Bar' is ambiguous with type " + "'foo.Bar' in container 'foo'", + }, + DeclaredTypeNameConflictTestCase{ + .container = "custom", + .opaque_type_names = {"Opaque"}, + .use_custom_type_introspector = true, + .expected_error = "Declared type 'Opaque' is ambiguous with type " + "'custom.Opaque' in container 'custom'", + })); + +TEST(TypeConfigTest, DeclaredTypeInContainerWithoutConflict) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + config.SetContainerConfig({.name = "cel.expr.conformance.proto3"}); + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "bar", .type_info = {.name = "foo.Bar"}}), + IsOk()); + env.SetConfig(config); + + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult result, + compiler->Compile("type(bar) == foo.Bar")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); +} + +struct DeclaredTypeUsageTestCase { + // The parameter type of a function overload using the declared types + // `foo.Bar` and `foo.Baz<~K, string>`. + Config::TypeInfo type_info; + // Empty if the type is valid. + std::string expected_error; +}; + +class DeclaredTypeUsageTest + : public testing::TestWithParam {}; + +TEST_P(DeclaredTypeUsageTest, NewCompiler) { + const DeclaredTypeUsageTestCase& param = GetParam(); + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}}), + IsOk()); + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}), + IsOk()); + ASSERT_THAT(config.AddFunctionConfig({.name = "f", + .overload_configs = {{ + .overload_id = "f_overload", + .parameters = {param.type_info}, + .return_type = {.name = "bool"}, + }}}), + IsOk()); + env.SetConfig(config); + + if (param.expected_error.empty()) { + EXPECT_THAT(env.NewCompiler(), IsOk()); + } else { + EXPECT_THAT(env.NewCompiler(), StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr(param.expected_error))); + } +} + +INSTANTIATE_TEST_SUITE_P( + DeclaredTypeUsageTest, DeclaredTypeUsageTest, + Values( + DeclaredTypeUsageTestCase{.type_info = {.name = "foo.Bar"}}, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Baz", + .params = {{.name = "int"}, {.name = "string"}}}}, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Baz", + .params = {{.name = "T", .is_type_param = true}, + {.name = "string"}}}}, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "map", + .params = {{.name = "string"}, + {.name = "foo.Baz", + .params = {{.name = "foo.Bar"}, + {.name = "string"}}}}}}, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Bar", .params = {{.name = "int"}}}, + .expected_error = "Type 'foo.Bar' cannot have type parameters", + }, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "list", + .params = {{.name = "foo.Bar", + .params = {{.name = "int"}}}}}, + .expected_error = "Type 'foo.Bar' cannot have type parameters", + }, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Baz"}, + .expected_error = + "Type 'foo.Baz' expects 2 type parameter(s), got 0", + }, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Baz", .params = {{.name = "int"}}}, + .expected_error = + "Type 'foo.Baz' expects 2 type parameter(s), got 1", + }, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Baz", + .params = {{.name = "int"}, {.name = "bytes"}}}, + .expected_error = "Type 'foo.Baz' expects type parameter 2 to be " + "'string', got 'bytes'", + }, + DeclaredTypeUsageTestCase{ + .type_info = {.name = "foo.Baz", + .params = {{.name = "int"}, + {.name = "T", .is_type_param = true}}}, + .expected_error = "Type 'foo.Baz' expects type parameter 2 to be " + "'string', got 'T'", + })); + +TEST(TypeConfigTest, VariableWithBareAbstractTypeErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "baz", .type_info = {.name = "foo.Baz"}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT( + env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'foo.Baz' expects 2 type parameter(s), got 0"))); +} + +TEST(TypeConfigTest, CustomOpaqueTypeWithParamsAtUseSiteErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + env.SetTypeIntrospector(std::make_shared()); + Config config; + ASSERT_THAT( + config.AddVariableConfig({.name = "c", + .type_info = {.name = "custom.Opaque", + .params = {{.name = "int"}}}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT( + env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'custom.Opaque' cannot have type parameters"))); +} + +TEST(TypeConfigTest, DeclaredTypeReferencingAnotherDeclaredTypeOutOfOrder) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + Config::TypeInfo generic_inner = { + .name = "foo.Inner", + .params = {{.name = "K", .is_type_param = true}, {.name = "string"}}}; + // Declare `foo.Outer` before `foo.Inner` (e.g., after alphabetical export). + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Outer", + .params = {generic_inner}}}), + IsOk()); + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = generic_inner}), + IsOk()); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "outer", + .type_info = {.name = "foo.Outer", + .params = {{.name = "foo.Inner", + .params = {{.name = "int"}, + {.name = "string"}}}}}}), + IsOk()); + ASSERT_THAT( + config.AddFunctionConfig( + {.name = "unwrap_key", + .overload_configs = {{ + .overload_id = "unwrap_key_outer", + .parameters = {{.name = "foo.Outer", .params = {generic_inner}}}, + .return_type = {.name = "K", .is_type_param = true}, + }}}), + IsOk()); + env.SetConfig(config); + + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN(ValidationResult ok_result, + compiler->Compile("unwrap_key(outer) == 1")); + EXPECT_THAT(ok_result.GetIssues(), IsEmpty()) << ok_result.FormatError(); + ASSERT_OK_AND_ASSIGN(ValidationResult err_result, + compiler->Compile("unwrap_key(outer) == 'one'")); + EXPECT_THAT(err_result.FormatError(), + HasSubstr("found no matching overload for '_==_'")); +} + +TEST(TypeConfigTest, DeclaredTypeWithBareAbstractTypeParamErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT( + config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Outer", + .params = {{.name = "foo.Inner"}}}}), + IsOk()); + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Inner", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("declared type 'foo.Outer': Type 'foo.Inner' " + "expects 2 type parameter(s), got 0"))); +} + +TEST(TypeConfigTest, CircularDeclaredTypesError) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.A", .params = {{.name = "foo.B"}}}}), + IsOk()); + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.B", .params = {{.name = "foo.A"}}}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Circular type dependency"))); +} + +TEST(TypeConfigTest, DeclaredTypeValidatesNesting) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + env.GetCompilerOptions().checker_options.max_type_decl_nesting = 2; + Config config; + ASSERT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Deep", + .params = {{.name = "list", + .params = {{.name = "list", + .params = {{.name = + "int"}}}}}}}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("declared type 'foo.Deep': type nesting limit " + "of 2 exceeded"))); +} + +// Declares `foo.T0` and `foo.T` with `width` bare references to +// `foo.T` for 0 < i < `count`. Since declared types share type handles, +// the expanded size of `foo.T` grows as `width^i`. +Config MakeWideChainedTypeConfig(int width, int count) { + Config config; + EXPECT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.T0"}}), + IsOk()); + for (int i = 1; i < count; ++i) { + Config::TypeInfo type_info = {.name = absl::StrCat("foo.T", i)}; + for (int j = 0; j < width; ++j) { + type_info.params.push_back({.name = absl::StrCat("foo.T", i - 1)}); + } + EXPECT_THAT( + config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = std::move(type_info)}), + IsOk()); + } + return config; +} + +TEST(TypeConfigTest, WideChainedDeclaredTypesAreRejected) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config = MakeWideChainedTypeConfig(/*width=*/8, /*count=*/13); + ASSERT_THAT( + config.AddVariableConfig({.name = "t", .type_info = {.name = "foo.T12"}}), + IsOk()); + env.SetConfig(config); + + // Bare references to abstract types are rejected before the expanded types + // are walked. + EXPECT_THAT( + env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'foo.T1' expects 8 type parameter(s), got 0"))); + EXPECT_THAT(env.NewCompilerBuilder(), + StatusIs(absl::StatusCode::kInvalidArgument)); +} + +TEST(TypeConfigTest, DeclaredTypeExceedingNodeLimitErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config::TypeInfo type_info = {.name = "foo.Wide"}; + type_info.params.resize(1000, Config::TypeInfo{.name = "int"}); + Config config; + ASSERT_THAT(config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = std::move(type_info)}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Declared type 'foo.Wide' exceeds the maximum " + "of 1000 nodes in its expanded type"))); +} + +TEST(TypeConfigTest, VariableTypeExceedingNodeLimitErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config::TypeInfo type_info = {.name = "foo.Wide"}; + type_info.params.resize(1000, Config::TypeInfo{.name = "int"}); + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "wide", .type_info = std::move(type_info)}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type of variable 'wide' exceeds the maximum " + "of 1000 nodes in its expanded type"))); +} + +TEST(TypeConfigTest, FunctionTypeExceedingNodeLimitErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config::TypeInfo type_info = {.name = "foo.Wide"}; + type_info.params.resize(1000, Config::TypeInfo{.name = "int"}); + Config config; + ASSERT_THAT( + config.AddFunctionConfig({.name = "f", + .overload_configs = {{ + .overload_id = "f_wide", + .parameters = {std::move(type_info)}, + .return_type = {.name = "bool"}, + }}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Parameter type of overload 'f_wide' exceeds " + "the maximum of 1000 nodes"))); +} + +TEST(TypeConfigTest, DeclaredTypeWithReservedWordSegmentCompilesWithBackticks) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT( + config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "com.example.package.Foo"}}), + IsOk()); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "x", .type_info = {.name = "com.example.package.Foo"}}), + IsOk()); + env.SetConfig(config); + + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + ASSERT_OK_AND_ASSIGN( + ValidationResult result, + compiler->Compile("type(x) == com.example.`package`.Foo")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); +} + +TEST(TypeConfigTest, RepeatedTypeParametersMustMatchConsistently) { + auto make_base_config = []() { + Config config; + EXPECT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Pair", + .params = {{.name = "T", .is_type_param = true}, + {.name = "T", .is_type_param = true}}}}), + IsOk()); + EXPECT_THAT( + config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Box", + .params = {{.name = "map", + .params = {{.name = "K", + .is_type_param = true}, + {.name = "K", + .is_type_param = true}}}}}}), + IsOk()); + return config; + }; + + { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config = make_base_config(); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "p", + .type_info = {.name = "foo.Pair", + .params = {{.name = "int"}, {.name = "int"}}}}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "b", + .type_info = {.name = "foo.Box", + .params = {{.name = "map", + .params = {{.name = "int"}, + {.name = "int"}}}}}}), + IsOk()); + env.SetConfig(config); + EXPECT_THAT(env.NewCompiler(), IsOk()); + } + + { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config = make_base_config(); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "p", + .type_info = {.name = "foo.Pair", + .params = {{.name = "int"}, {.name = "string"}}}}), + IsOk()); + env.SetConfig(config); + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'foo.Pair' expects type parameter 2 " + "to be 'int', got 'string'"))); + } + + { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config = make_base_config(); + ASSERT_THAT( + config.AddVariableConfig( + {.name = "b", + .type_info = {.name = "foo.Box", + .params = {{.name = "map", + .params = {{.name = "int"}, + {.name = "string"}}}}}}), + IsOk()); + env.SetConfig(config); + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type 'foo.Box' expects type parameter 1"))); + } +} + +TEST(TypeConfigTest, DeeplyNestedVariableTypeExceedingNodeLimitErrors) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config::TypeInfo nested = {.name = "int"}; + for (int i = 0; i < 1500; ++i) { + nested = {.name = "list", .params = {std::move(nested)}}; + } + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "deep", .type_info = std::move(nested)}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Type of variable 'deep' exceeds the maximum " + "of 1000 nodes in its expanded type"))); +} + struct VariableConfigWithValueTestCase { Config::VariableConfig variable_config; std::string validate_type_expr; @@ -698,5 +1517,300 @@ std::vector GetFunctionConfigTestCases() { INSTANTIATE_TEST_SUITE_P(FunctionConfigTest, FunctionConfigTest, ::testing::ValuesIn(GetFunctionConfigTestCases())); +Config::TypeInfo MakeTypeInfo(std::string name, + std::vector params = {}) { + return {.name = std::move(name), .params = std::move(params)}; +} + +Config::TypeInfo MakeTypeParam(std::string name) { + return {.name = std::move(name), .is_type_param = true}; +} + +TEST(TypeIntrospectorTest, CustomTypeIntrospectorChainedWithProtoTypes) { + auto custom_introspector = std::make_shared(); + std::unique_ptr compiler; + { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "x", .type_info = MakeTypeInfo("custom.Int")}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "c", .type_info = MakeTypeInfo("custom.Opaque")}), + IsOk()); + ASSERT_THAT(config.AddVariableConfig( + {.name = "msg", + .type_info = MakeTypeInfo(std::string(kTestAllTypes))}), + IsOk()); + env.SetConfig(config); + + env.SetTypeIntrospector(custom_introspector); + EXPECT_EQ(env.GetTypeIntrospector(), custom_introspector.get()); + ASSERT_OK_AND_ASSIGN(compiler, env.NewCompiler()); + } + // Drop our reference so the compiler must keep `custom_introspector` alive. + custom_introspector.reset(); + + // `msg.single_int64` only type checks if `msg` resolves to the protobuf + // message type rather than to the custom `int` type of the same name. + ASSERT_OK_AND_ASSIGN( + ValidationResult result, + compiler->Compile("x + 1 == 2 && type(c) == custom.Opaque && " + "msg.single_int64 == x")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); +} + +TEST(TypeIntrospectorTest, ProtoEnumResolvesToEnumType) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "e", + .type_info = MakeTypeInfo( + "cel.expr.conformance.proto3.TestAllTypes.NestedEnum")}), + IsOk()); + ASSERT_THAT(config.AddFunctionConfig( + {.name = "is_gar", + .overload_configs = {{ + .overload_id = "is_gar_global_enum", + .parameters = {MakeTypeInfo( + "cel.expr.conformance.proto3.GlobalEnum")}, + .return_type = MakeTypeInfo("bool"), + }}}), + IsOk()); + env.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + + // Enum types are assignable to and from `int`, unlike the opaque types that + // enum names used to resolve to. + ASSERT_OK_AND_ASSIGN( + ValidationResult result, + compiler->Compile( + "e == cel.expr.conformance.proto3.TestAllTypes.NestedEnum.BAR && " + "e == 1 && is_gar(cel.expr.conformance.proto3.GlobalEnum.GAR) && " + "is_gar(1)")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); +} + +TEST(TypeIntrospectorTest, CustomTypesInFunctionDeclarations) { + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + env.SetTypeIntrospector(std::make_shared()); + Config config; + ASSERT_THAT(config.AddVariableConfig( + {.name = "c", .type_info = MakeTypeInfo("custom.Opaque")}), + IsOk()); + ASSERT_THAT(config.AddFunctionConfig( + {.name = "make_param", + .overload_configs = {{ + .overload_id = "make_param_opaque_int", + .parameters = {MakeTypeInfo("custom.Opaque"), + MakeTypeInfo("custom.Int")}, + .return_type = MakeTypeInfo( + "custom.Parameterized", + {MakeTypeInfo("int"), MakeTypeInfo("string")}), + }}}), + IsOk()); + // A type parameter at the use site matches a declared type parameter. + ASSERT_THAT(config.AddFunctionConfig( + {.name = "param_key", + .overload_configs = {{ + .overload_id = "param_key_parameterized", + .parameters = {MakeTypeInfo( + "custom.Parameterized", + {MakeTypeParam("T"), MakeTypeInfo("string")})}, + .return_type = MakeTypeParam("T"), + }}}), + IsOk()); + env.SetConfig(config); + ASSERT_OK_AND_ASSIGN(std::unique_ptr compiler, env.NewCompiler()); + + ASSERT_OK_AND_ASSIGN( + ValidationResult result, + compiler->Compile("param_key(make_param(c, 1)) + 1 == 2")); + EXPECT_THAT(result.GetIssues(), IsEmpty()) << result.FormatError(); +} + +struct FunctionTypeErrorTestCase { + std::string test_name; + Config::FunctionOverloadConfig overload_config; + std::string expected_error; +}; + +using FunctionTypeErrorTest = + ::testing::TestWithParam; + +TEST_P(FunctionTypeErrorTest, ReportsErrorWithContext) { + const FunctionTypeErrorTestCase& param = GetParam(); + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + env.SetTypeIntrospector(std::make_shared()); + Config config; + ASSERT_THAT(config.AddFunctionConfig( + {.name = "fn", .overload_configs = {param.overload_config}}), + IsOk()); + env.SetConfig(config); + + EXPECT_THAT(env.NewCompiler(), StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr(param.expected_error))); +} + +INSTANTIATE_TEST_SUITE_P( + FunctionTypeErrorTest, FunctionTypeErrorTest, + ValuesIn(std::vector{ + { + .test_name = "MismatchedParameter", + .overload_config = + { + .overload_id = "fn_bytes", + .parameters = {MakeTypeInfo("int"), + MakeTypeInfo("custom.Parameterized", + {MakeTypeInfo("int"), + MakeTypeInfo("bytes")})}, + .return_type = MakeTypeInfo("bool"), + }, + .expected_error = + "function 'fn' overload 'fn_bytes' parameter 2: Type " + "'custom.Parameterized' expects type parameter 2 to be " + "'string', got 'bytes'", + }, + { + .test_name = "MismatchedResult", + .overload_config = + { + .overload_id = "fn_result", + .return_type = MakeTypeInfo("custom.Parameterized"), + }, + .expected_error = + "function 'fn' overload 'fn_result' result: Type " + "'custom.Parameterized' expects 2 type parameter(s), got 0", + }, + { + // A type parameter at the use site does not match a declared + // concrete type parameter. + .test_name = "TypeParamForConcreteParameter", + .overload_config = + { + .overload_id = "fn_type_param", + .parameters = {MakeTypeInfo("custom.Parameterized", + {MakeTypeInfo("int"), + MakeTypeParam("T")})}, + .return_type = MakeTypeInfo("bool"), + }, + .expected_error = + "function 'fn' overload 'fn_type_param' parameter 1: Type " + "'custom.Parameterized' expects type parameter 2 to be " + "'string'", + }, + }), + [](const ::testing::TestParamInfo& info) { + return info.param.test_name; + }); + +struct VariableTypeTestCase { + std::string test_name; + Config::TypeInfo type_info; + // Empty if the type is expected to resolve successfully. + std::string expected_error; + absl::StatusCode expected_code = absl::StatusCode::kInvalidArgument; +}; + +using VariableTypeTest = ::testing::TestWithParam; + +TEST_P(VariableTypeTest, ResolvesVariableType) { + const VariableTypeTestCase& param = GetParam(); + Env env; + env.SetDescriptorPool(internal::GetSharedTestingDescriptorPool()); + env.SetTypeIntrospector(std::make_shared()); + Config config; + ASSERT_THAT( + config.AddVariableConfig({.name = "v", .type_info = param.type_info}), + IsOk()); + env.SetConfig(config); + + if (param.expected_error.empty()) { + EXPECT_THAT(env.NewCompiler(), IsOk()); + } else { + EXPECT_THAT(env.NewCompiler(), + StatusIs(param.expected_code, HasSubstr(param.expected_error))); + } +} + +INSTANTIATE_TEST_SUITE_P( + VariableTypeTest, VariableTypeTest, + ValuesIn(std::vector{ + { + .test_name = "ParameterizedMatchingParameters", + .type_info = MakeTypeInfo("custom.Parameterized", + {MakeTypeInfo("int"), + MakeTypeInfo("string")}), + }, + { + .test_name = "ParameterizedMissingParameters", + .type_info = MakeTypeInfo("custom.Parameterized"), + .expected_error = "variable 'v': Type 'custom.Parameterized' " + "expects 2 type parameter(s), got 0", + }, + { + .test_name = "ParameterizedMismatchedParameter", + .type_info = MakeTypeInfo("custom.Parameterized", + {MakeTypeInfo("int"), + MakeTypeInfo("bytes")}), + .expected_error = "variable 'v': Type 'custom.Parameterized' " + "expects type parameter 2 to be 'string', got " + "'bytes'", + }, + { + .test_name = "NestedParameterizedMismatchedParameter", + .type_info = MakeTypeInfo("list", + {MakeTypeInfo("custom.Parameterized", + {MakeTypeInfo("int"), + MakeTypeInfo("bytes")})}), + .expected_error = "variable 'v': Type 'custom.Parameterized' " + "expects type parameter 2 to be 'string', got " + "'bytes'", + }, + { + .test_name = "OpaqueWithParameters", + .type_info = MakeTypeInfo("custom.Opaque", {MakeTypeInfo("int")}), + .expected_error = + "variable 'v': Type 'custom.Opaque' cannot have type " + "parameters", + }, + { + .test_name = "MessageWithParameters", + .type_info = MakeTypeInfo(std::string(kTestAllTypes), + {MakeTypeInfo("int")}), + .expected_error = "variable 'v': Type " + "'cel.expr.conformance.proto3.TestAllTypes' " + "cannot have type parameters", + }, + { + .test_name = "ListWithTooManyParameters", + .type_info = MakeTypeInfo("list", {MakeTypeInfo("int"), + MakeTypeInfo("int")}), + .expected_error = "variable 'v': Type 'list' expects at most 1 " + "type parameter(s), got 2", + }, + { + .test_name = "MapWithTooManyParameters", + .type_info = MakeTypeInfo("map", + {MakeTypeInfo("int"), MakeTypeInfo("int"), + MakeTypeInfo("int")}), + .expected_error = "variable 'v': Type 'map' expects at most 2 " + "type parameter(s), got 3", + }, + { + .test_name = "IntrospectorError", + .type_info = MakeTypeInfo("custom.Error"), + .expected_error = "variable 'v': custom type lookup failed", + .expected_code = absl::StatusCode::kInternal, + }, + }), + [](const ::testing::TestParamInfo& info) { + return info.param.test_name; + }); + } // namespace } // namespace cel diff --git a/env/env_yaml.cc b/env/env_yaml.cc index af5b3e55b..757ece563 100644 --- a/env/env_yaml.cc +++ b/env/env_yaml.cc @@ -199,8 +199,9 @@ YAML::Node GetContextNodeForKeyValue(const YAML::Node& node, // Fields handled by the parser, for each kind of map node in the config. constexpr absl::string_view kConfigFields[] = { - "name", "description", "container", "extensions", - "stdlib", "context_variable", "variables", "functions"}; + "name", "description", "container", + "extensions", "stdlib", "context_variable", + "types", "variables", "functions"}; // Fields that other CEL implementations support but cel-cpp does not. constexpr absl::string_view kUnsupportedConfigFields[] = { "imports", "limits", "validators", "features"}; @@ -214,6 +215,7 @@ constexpr absl::string_view kStandardLibraryFields[] = { constexpr absl::string_view kFunctionSelectorFields[] = {"name", "overloads"}; constexpr absl::string_view kOverloadSelectorFields[] = {"id"}; constexpr absl::string_view kContextVariableFields[] = {"type_name", "type"}; +constexpr absl::string_view kTypeDeclarationFields[] = {"opaque", "abstract"}; constexpr absl::string_view kTypeFields[] = {"type", "type_name", "is_type_param", "params"}; // A variable may specify its type inline, so the type fields are included. @@ -759,6 +761,66 @@ absl::StatusOr ParseConstantValue(absl::string_view yaml, } } +absl::Status ParseTypeConfigs(Config& config, absl::string_view yaml, + const YAML::Node& root, + UnhandledFieldReporter& reporter) { + const YAML::Node types = root["types"]; + if (!types.IsDefined()) { + return absl::OkStatus(); + } + if (!types.IsSequence()) { + return YamlError(yaml, types, "Node 'types' is not a sequence"); + } + + for (const YAML::Node& type : types) { + if (!type || !type.IsMap()) { + return YamlError(yaml, type, "Type declaration is not a map"); + } + reporter.Check(type, "type declaration", kTypeDeclarationFields); + const YAML::Node opaque = type["opaque"]; + const YAML::Node abstract = type["abstract"]; + if (opaque.IsDefined() && abstract.IsDefined()) { + return YamlError(yaml, GetContextNodeForKeyValue(type, abstract), + "Node 'opaque' and 'abstract' are mutually exclusive"); + } + if (!opaque.IsDefined() && !abstract.IsDefined()) { + return YamlError(yaml, type, + "Type declaration must specify 'opaque' or 'abstract'"); + } + + Config::TypeConfig type_config; + type_config.kind = opaque.IsDefined() ? Config::TypeConfig::Kind::kOpaque + : Config::TypeConfig::Kind::kAbstract; + const YAML::Node& signature_node = opaque.IsDefined() ? opaque : abstract; + absl::string_view key = opaque.IsDefined() ? "opaque" : "abstract"; + if (!signature_node.IsScalar()) { + return YamlError(yaml, signature_node, + absl::StrCat("Node '", key, "' is not a string")); + } + std::string signature = GetString(yaml, signature_node); + absl::StatusOr type_spec = ParseTypeSpec(signature); + if (!type_spec.ok()) { + return YamlError(yaml, signature_node, type_spec.status().message()); + } + // Built-in types such as `int` or `list<~T>` cannot be redeclared. + if (!type_spec->has_abstract_type()) { + return YamlError( + yaml, signature_node, + absl::StrCat("Type '", signature, "' cannot be declared as ", key)); + } + absl::StatusOr type_info = TypeSpecToTypeInfo(*type_spec); + if (!type_info.ok()) { + return YamlError(yaml, signature_node, type_info.status().message()); + } + type_config.type_info = *std::move(type_info); + absl::Status add_status = config.AddTypeConfig(type_config); + if (!add_status.ok()) { + return YamlError(yaml, signature_node, add_status.message()); + } + } + return absl::OkStatus(); +} + absl::Status ParseVariableConfigs(Config& config, absl::string_view yaml, const YAML::Node& root, UnhandledFieldReporter& reporter) { @@ -1240,6 +1302,68 @@ std::string FormatYamlDouble(double value) { return absl::StrFormat("%.17g", value); } +// Formats `type_info` as a type signature without escaping, e.g. +// `foo.Baz<~K,string>`. Used as a fallback when `type_info` cannot be +// converted with `MakeTypeSpecSignature`, so that type parameters are never +// dropped from the output. +std::string FormatTypeInfoSignature(const Config::TypeInfo& type_info) { + std::string signature = + absl::StrCat(type_info.is_type_param ? "~" : "", type_info.name); + if (!type_info.params.empty()) { + absl::StrAppend( + &signature, "<", + absl::StrJoin(type_info.params, ",", + [](std::string* out, const Config::TypeInfo& param) { + absl::StrAppend(out, FormatTypeInfoSignature(param)); + }), + ">"); + } + return signature; +} + +// Returns the type signature of a declared type, e.g. `foo.Baz<~K,string>`. +std::string MakeTypeConfigSignature(const Config::TypeConfig& type_config) { + // Like `EmitTypeInfo`, fall back to a representation that preserves all of + // the type parameters if the type cannot be converted to a signature. + // `Config::AddTypeConfig` validates declared types, so this is not expected. + absl::StatusOr type_spec = + TypeInfoToTypeSpec(type_config.type_info); + if (type_spec.ok()) { + absl::StatusOr signature = MakeTypeSpecSignature(*type_spec); + if (signature.ok()) { + return *std::move(signature); + } + } + return FormatTypeInfoSignature(type_config.type_info); +} + +void EmitTypeConfigs(const Config& env_config, YAML::Emitter& out) { + if (env_config.GetTypeConfigs().empty()) { + return; + } + + // Sort the declared types by name to make the output deterministic. + std::vector sorted_type_configs = + env_config.GetTypeConfigs(); + absl::c_sort(sorted_type_configs, + [](const Config::TypeConfig& a, const Config::TypeConfig& b) { + return a.type_info.name < b.type_info.name; + }); + + out << YAML::Key << "types"; + out << YAML::Value << YAML::BeginSeq; + for (const Config::TypeConfig& type_config : sorted_type_configs) { + out << YAML::BeginMap; + out << YAML::Key + << (type_config.kind == Config::TypeConfig::Kind::kOpaque ? "opaque" + : "abstract"); + out << YAML::Value << YAML::DoubleQuoted + << MakeTypeConfigSignature(type_config); + out << YAML::EndMap; + } + out << YAML::EndSeq; +} + void EmitVariableConfigs(const Config& env_config, YAML::Emitter& out, const EnvConfigToYamlOptions& options) { const auto& variable_configs = env_config.GetVariableConfigs(); @@ -1527,6 +1651,7 @@ absl::StatusOr EnvConfigFromYaml( ParseExtensionConfigs(config, yaml, root, options, reporter)); CEL_RETURN_IF_ERROR(ParseStandardLibraryConfig(config, yaml, root, reporter)); CEL_RETURN_IF_ERROR(ParseContextVariableConfig(config, yaml, root, reporter)); + CEL_RETURN_IF_ERROR(ParseTypeConfigs(config, yaml, root, reporter)); CEL_RETURN_IF_ERROR(ParseVariableConfigs(config, yaml, root, reporter)); CEL_RETURN_IF_ERROR(ParseFunctionConfigs(config, yaml, root, reporter)); @@ -1556,6 +1681,7 @@ void EnvConfigToYaml(const Config& env_config, std::ostream& os, EmitContainerConfig(env_config, out); EmitExtensionConfigs(env_config, out, options); EmitStandardLibraryConfig(env_config, out); + EmitTypeConfigs(env_config, out); EmitVariableConfigs(env_config, out, options); EmitFunctionConfigs(env_config, out, options); out << YAML::EndMap; diff --git a/env/env_yaml_test.cc b/env/env_yaml_test.cc index 00049d957..02b1c30d0 100644 --- a/env/env_yaml_test.cc +++ b/env/env_yaml_test.cc @@ -26,6 +26,7 @@ #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -283,6 +284,29 @@ TEST(EnvYamlTest, ParseVariableConfigs) { "understands from a proto perspective"); } +TEST(EnvYamlTest, ParseTypeConfigs) { + ASSERT_OK_AND_ASSIGN(Config config, EnvConfigFromYaml(R"yaml( + types: + - opaque: "foo.Bar" + - abstract: "foo.Baz<~K, string>" + )yaml")); + + ASSERT_THAT(config.GetTypeConfigs(), SizeIs(2)); + const Config::TypeConfig& opaque = config.GetTypeConfigs()[0]; + EXPECT_EQ(opaque.kind, Config::TypeConfig::Kind::kOpaque); + EXPECT_EQ(opaque.type_info.name, "foo.Bar"); + EXPECT_THAT(opaque.type_info.params, IsEmpty()); + + const Config::TypeConfig& abstract = config.GetTypeConfigs()[1]; + EXPECT_EQ(abstract.kind, Config::TypeConfig::Kind::kAbstract); + EXPECT_EQ(abstract.type_info.name, "foo.Baz"); + ASSERT_THAT(abstract.type_info.params, SizeIs(2)); + EXPECT_EQ(abstract.type_info.params[0].name, "K"); + EXPECT_TRUE(abstract.type_info.params[0].is_type_param); + EXPECT_EQ(abstract.type_info.params[1].name, "string"); + EXPECT_FALSE(abstract.type_info.params[1].is_type_param); +} + TEST(EnvYamlTest, ParseVariableConfigWithTypeParams) { ASSERT_OK_AND_ASSIGN(Config config, EnvConfigFromYaml(R"yaml( variables: @@ -832,6 +856,145 @@ TEST_P(EnvYamlParseTest, EnvYamlSyntaxError) { INSTANTIATE_TEST_SUITE_P( EnvYamlParseTest, EnvYamlParseTest, ::testing::Values( + ParseTestCase{ + .yaml = R"yaml( + types: "foo.Bar" + )yaml", + .expected_error = "2:24: Node 'types' is not a sequence", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - "foo.Bar" + )yaml", + .expected_error = "3:21: Type declaration is not a map", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "foo.Bar" + abstract: "foo.Baz<~T>" + )yaml", + .expected_error = + "4:21: Node 'opaque' and 'abstract' are mutually exclusive", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - type: "foo.Bar" + )yaml", + .expected_error = + "3:21: Type declaration must specify 'opaque' or 'abstract'", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: [] + )yaml", + .expected_error = "3:29: Node 'opaque' is not a string", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "foo.Bar<" + )yaml", + .expected_error = "3:29: Invalid type signature", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "int" + )yaml", + .expected_error = "3:29: Type 'int' cannot be declared as opaque", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - abstract: "list<~T>" + )yaml", + .expected_error = + "3:31: Type 'list<~T>' cannot be declared as abstract", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "foo.Bar" + )yaml", + .expected_error = + "3:29: Opaque type 'foo.Bar' cannot have type parameters", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - abstract: "foo.Bar" + )yaml", + .expected_error = + "3:31: Abstract type 'foo.Bar' must have type parameters", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "foo.Bar" + - abstract: "foo.Bar<~T>" + )yaml", + .expected_error = "4:31: Type 'foo.Bar' is already declared", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - abstract: "foo.Baz>" + )yaml", + .expected_error = + "3:31: FunctionType cannot be converted to TypeInfo", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "optional_type" + )yaml", + .expected_error = + "3:29: Built-in type 'optional_type' cannot be declared", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: "foo,bar" + )yaml", + .expected_error = + "3:29: Declared type 'foo,bar' is not a valid type name", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: ".foo.Bar" + )yaml", + .expected_error = + "3:29: Declared type '.foo.Bar' is not a valid type name", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - opaque: 123 + )yaml", + .expected_error = + "3:29: Declared type '123' is not a valid type name", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - abstract: "foo.Baz<~1x>" + )yaml", + .expected_error = + "3:31: Type parameter '1x' is not a valid identifier", + }, + ParseTestCase{ + .yaml = R"yaml( + types: + - abstract: "foo.Baz" + )yaml", + .expected_error = + "3:31: Type argument 'a,b' is not a valid type name", + }, ParseTestCase{ .yaml = R"yaml( invalid yaml )yaml", .expected_error = "1:2: Invalid CEL environment config YAML\n" @@ -2008,6 +2171,30 @@ std::vector GetExportTestCases() { type_name: "int" )yaml", }, + ExportTestCase{ + .config = []() -> absl::StatusOr { + Config config; + CEL_RETURN_IF_ERROR(config.AddTypeConfig( + {.kind = Config::TypeConfig::Kind::kAbstract, + .type_info = {.name = "foo.Baz", + .params = {{.name = "K", .is_type_param = true}, + {.name = "string"}}}})); + CEL_RETURN_IF_ERROR( + config.AddTypeConfig({.kind = Config::TypeConfig::Kind::kOpaque, + .type_info = {.name = "foo.Bar"}})); + return config; + }(), + .expected_yaml = R"yaml( + types: + - opaque: "foo.Bar" + - abstract: "foo.Baz<~K,string>" + )yaml", + .expected_alt_yaml = R"yaml( + types: + - opaque: "foo.Bar" + - abstract: "foo.Baz<~K,string>" + )yaml", + }, }; }; @@ -2162,6 +2349,25 @@ std::vector GetSignatureRoundTripTestCases() { - signature: "timestamp.foo(A<~B>)" return: "int" )yaml", + R"yaml( + types: + - opaque: "foo.Bar" + - abstract: "foo.Baz<~K,string>" + variables: + - name: "a" + type: "foo.Bar" + - name: "b" + type: "foo.Baz" + )yaml", + // Declared type names may contain CEL reserved words. + R"yaml( + types: + - abstract: "a.namespace.B" + - opaque: "com.example.package.Foo" + variables: + - name: "a" + type: "com.example.package.Foo" + )yaml", }; } @@ -2297,6 +2503,8 @@ INSTANTIATE_TEST_SUITE_P( " args:\n - type_name: int\n name: x\n" " return:\n type_name: int\n", "7:13: Unknown field 'name' in type"}, + {"types:\n - opaque: foo.Bar\n name: x\n", + "3:5: Unknown field 'name' in type declaration"}, })); TEST(EnvYamlTest, StrictAcceptsSupportedFields) { @@ -2344,5 +2552,17 @@ TEST(EnvYamlTest, RejectsExcessiveNodeCount) { HasSubstr("YAML node count exceeds maximum"))); } +TEST(EnvYamlTest, RejectsExcessiveTypeSignatureNestingDepth) { + std::string sig = "int"; + for (int i = 0; i < 200; ++i) { + sig = absl::StrCat("list<", sig, ">"); + } + std::string yaml = + absl::StrCat("types:\n - abstract: \"foo.Deep<", sig, ">\"\n"); + EXPECT_THAT(EnvConfigFromYaml(yaml), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("nesting depth exceeds maximum"))); +} + } // namespace } // namespace cel diff --git a/env/type_info.cc b/env/type_info.cc index c1ac65cb2..5e5a944da 100644 --- a/env/type_info.cc +++ b/env/type_info.cc @@ -14,6 +14,7 @@ #include "env/type_info.h" +#include #include #include #include @@ -23,6 +24,7 @@ #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/strings/string_view.h" #include "common/ast.h" #include "common/type.h" @@ -103,7 +105,6 @@ absl::StatusOr TypeInfoToType( return Type::Message(type); } } - // TODO(uncreated-issue/88): use a TypeIntrospector to validate opaque types std::vector parameter_types; for (const Config::TypeInfo& param : type_info.params) { CEL_ASSIGN_OR_RETURN(Type parameter_type, @@ -188,22 +189,43 @@ absl::StatusOr TypeInfoToType( } absl::StatusOr TypeInfoToTypeSpec(const Config::TypeInfo& type_info) { if (type_info.is_type_param) { + if (!type_info.params.empty()) { + return absl::InvalidArgumentError(absl::StrCat( + "Type parameter '", type_info.name, "' cannot have type parameters")); + } return TypeSpec(ParamTypeSpec(type_info.name)); } std::optional type_kind = TypeNameToTypeKind(type_info.name); if (!type_kind.has_value()) { - if (type_info.params.empty()) { - return TypeSpec(MessageTypeSpec(type_info.name)); - } else { - std::vector param_specs; - param_specs.reserve(type_info.params.size()); - for (const Config::TypeInfo& param : type_info.params) { - CEL_ASSIGN_OR_RETURN(TypeSpec param_spec, TypeInfoToTypeSpec(param)); - param_specs.push_back(std::move(param_spec)); - } - return TypeSpec(AbstractType(type_info.name, std::move(param_specs))); + // The name may refer to a message, an enum or an opaque type. These are + // distinguished when the type spec is resolved, e.g. with + // `ConvertTypeSpecToType`. + std::vector param_specs; + param_specs.reserve(type_info.params.size()); + for (const Config::TypeInfo& param : type_info.params) { + CEL_ASSIGN_OR_RETURN(TypeSpec param_spec, TypeInfoToTypeSpec(param)); + param_specs.push_back(std::move(param_spec)); } + return TypeSpec(AbstractType(type_info.name, std::move(param_specs))); + } + + size_t max_params = 0; + switch (*type_kind) { + case TypeKind::kList: + case TypeKind::kType: + max_params = 1; + break; + case TypeKind::kMap: + max_params = 2; + break; + default: + break; + } + if (type_info.params.size() > max_params) { + return absl::InvalidArgumentError( + absl::StrCat("Type '", type_info.name, "' expects at most ", max_params, + " type parameter(s), got ", type_info.params.size())); } switch (*type_kind) { diff --git a/env/type_info.h b/env/type_info.h index 3f802ce1a..c0e56830c 100644 --- a/env/type_info.h +++ b/env/type_info.h @@ -27,6 +27,10 @@ namespace cel { // Converts a Config::TypeInfo to a cel::Type. Returns an error if the type_info // cannot be converted to a known cel::Type, a list configured with more than // one parameter. +// +// Prefer `TypeInfoToTypeSpec` followed by `ConvertTypeSpecToType`, which +// resolves protobuf enum and custom types with a `TypeIntrospector`; this is +// what `cel::Env` uses. absl::StatusOr TypeInfoToType( const Config::TypeInfo& type_info, const google::protobuf::DescriptorPool* descriptor_pool, google::protobuf::Arena* arena); diff --git a/env/type_info_test.cc b/env/type_info_test.cc index 2f25ff6ca..cc08192f8 100644 --- a/env/type_info_test.cc +++ b/env/type_info_test.cc @@ -54,6 +54,8 @@ namespace { using absl_testing::IsOk; using absl_testing::StatusIs; +using testing::HasSubstr; +using testing::Values; using testing::ValuesIn; struct TestCase { @@ -218,8 +220,8 @@ std::vector GetTypeSpecTestCases() { .expected_type_info = {.name = "map"}, }, TypeSpecTestCase{ - .type_spec = TypeSpec( - MessageTypeSpec("cel.expr.conformance.proto2.TestAllTypes")), + .type_spec = TypeSpec(AbstractType( + "cel.expr.conformance.proto2.TestAllTypes", /*params=*/{})), .expected_type_info = {.name = "cel.expr.conformance.proto2.TestAllTypes"}, }, @@ -284,6 +286,15 @@ std::vector GetTypeSpecTestCases() { INSTANTIATE_TEST_SUITE_P(TypeSpecToTypeInfoTest, TypeSpecToTypeInfoTest, ValuesIn(GetTypeSpecTestCases())); +TEST(TypeSpecToTypeInfoTest, MessageType) { + ASSERT_OK_AND_ASSIGN(Config::TypeInfo type_info, + TypeSpecToTypeInfo(TypeSpec(MessageTypeSpec( + "cel.expr.conformance.proto2.TestAllTypes")))); + EXPECT_THAT(type_info, + TypeInfoEq(Config::TypeInfo{ + .name = "cel.expr.conformance.proto2.TestAllTypes"})); +} + using TypeInfoToTypeSpecTest = testing::TestWithParam; TEST_P(TypeInfoToTypeSpecTest, Convert) { @@ -296,6 +307,68 @@ TEST_P(TypeInfoToTypeSpecTest, Convert) { INSTANTIATE_TEST_SUITE_P(TypeInfoToTypeSpecTest, TypeInfoToTypeSpecTest, ValuesIn(GetTypeSpecTestCases())); +struct TypeInfoToTypeSpecErrorTestCase { + Config::TypeInfo type_info; + std::string expected_error; +}; + +using TypeInfoToTypeSpecErrorTest = + testing::TestWithParam; + +// Extra type parameters are rejected rather than silently dropped. +TEST_P(TypeInfoToTypeSpecErrorTest, TooManyParams) { + const TypeInfoToTypeSpecErrorTestCase& param = GetParam(); + EXPECT_THAT(TypeInfoToTypeSpec(param.type_info), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr(param.expected_error))); +} + +INSTANTIATE_TEST_SUITE_P( + TypeInfoToTypeSpecErrorTest, TypeInfoToTypeSpecErrorTest, + Values( + TypeInfoToTypeSpecErrorTestCase{ + .type_info = {.name = "T", + .params = {{.name = "int"}}, + .is_type_param = true}, + .expected_error = "Type parameter 'T' cannot have type parameters", + }, + TypeInfoToTypeSpecErrorTestCase{ + .type_info = {.name = "int", .params = {{.name = "string"}}}, + .expected_error = + "Type 'int' expects at most 0 type parameter(s), got 1", + }, + TypeInfoToTypeSpecErrorTestCase{ + .type_info = {.name = "dyn", .params = {{.name = "string"}}}, + .expected_error = + "Type 'dyn' expects at most 0 type parameter(s), got 1", + }, + TypeInfoToTypeSpecErrorTestCase{ + .type_info = {.name = "list", + .params = {{.name = "int"}, {.name = "int"}}}, + .expected_error = + "Type 'list' expects at most 1 type parameter(s), got 2", + }, + TypeInfoToTypeSpecErrorTestCase{ + .type_info = + {.name = "map", + .params = {{.name = "int"}, {.name = "int"}, {.name = "int"}}}, + .expected_error = + "Type 'map' expects at most 2 type parameter(s), got 3", + }, + TypeInfoToTypeSpecErrorTestCase{ + .type_info = {.name = "type", + .params = {{.name = "int"}, {.name = "int"}}}, + .expected_error = + "Type 'type' expects at most 1 type parameter(s), got 2", + }, + TypeInfoToTypeSpecErrorTestCase{ + .type_info = {.name = "list", + .params = {{.name = "int", + .params = {{.name = "string"}}}}}, + .expected_error = + "Type 'int' expects at most 0 type parameter(s), got 1", + })); + TEST(TypeSpecToTypeInfoTest, ErrorConversions) { EXPECT_THAT(TypeSpecToTypeInfo(TypeSpec(ErrorTypeSpec::kValue)), StatusIs(absl::StatusCode::kInvalidArgument,