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/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..efe4ddc51 100644 --- a/env/BUILD +++ b/env/BUILD @@ -52,19 +52,27 @@ cc_library( deps = [ ":config", "//checker:type_checker_builder", + "//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/functional:any_invocable", + "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", "@com_google_protobuf//:protobuf", diff --git a/env/env.cc b/env/env.cc index dd71323d5..00a252943 100644 --- a/env/env.cc +++ b/env/env.cc @@ -14,20 +14,32 @@ #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/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.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 +130,221 @@ absl::StatusOr MakeStdlibSubset( return subset; } +// 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_; +}; + +// 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 whether `type` is an instance of `pattern`, i.e. whether it is equal +// to `pattern` with its type parameters substituted by arbitrary types. +bool MatchesTypePattern(const Type& pattern, const Type& type) { + if (pattern.IsTypeParam()) { + return true; + } + 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])) { + 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 or custom 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, unless the latter is a type parameter (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). +// +// 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, + google::protobuf::Arena* absl_nonnull arena) { + if (type_spec.has_list_type()) { + return ValidateTypeSpecParameters(type_spec.list_type().elem_type(), + type_introspector, arena); + } + if (type_spec.has_map_type()) { + CEL_RETURN_IF_ERROR(ValidateTypeSpecParameters( + type_spec.map_type().key_type(), type_introspector, arena)); + return ValidateTypeSpecParameters(type_spec.map_type().value_type(), + type_introspector, arena); + } + if (type_spec.has_function()) { + CEL_RETURN_IF_ERROR(ValidateTypeSpecParameters( + type_spec.function().result_type(), type_introspector, arena)); + for (const TypeSpec& arg_type : type_spec.function().arg_types()) { + CEL_RETURN_IF_ERROR( + ValidateTypeSpecParameters(arg_type, type_introspector, arena)); + } + return absl::OkStatus(); + } + if (type_spec.has_type()) { + return ValidateTypeSpecParameters(type_spec.type(), type_introspector, + arena); + } + 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, arena)); + } + 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())); + } + for (size_t i = 0; i < param_specs.size(); ++i) { + if (declared_params[i].IsTypeParam()) { + continue; + } + CEL_ASSIGN_OR_RETURN( + Type param, + ConvertTypeSpecToType(param_specs[i], type_introspector, arena)); + if (!MatchesTypePattern(declared_params[i], param)) { + return absl::InvalidArgumentError( + absl::StrCat("Type '", name, "' expects type parameter ", i + 1, + " to be '", FormatTypeName(declared_params[i]), + "', got '", FormatTypeName(param), "'")); + } + } + return absl::OkStatus(); +} + +// Resolves a type from the config against `type_introspector`. +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, arena)); + 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; +} + absl::StatusOr FunctionConfigToFunctionDecl( - const Config::FunctionConfig& function_config, google::protobuf::Arena* arena, - const google::protobuf::DescriptorPool* descriptor_pool) { + const Config::FunctionConfig& function_config, + const TypeIntrospector& type_introspector, + google::protobuf::Arena* absl_nonnull arena) { FunctionDecl function_decl; function_decl.set_name(function_config.name); for (const Config::FunctionOverloadConfig& overload_config : @@ -128,14 +352,21 @@ 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_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_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 +421,27 @@ absl::StatusOr> Env::NewCompilerBuilder() } google::protobuf::Arena* arena = checker_builder.arena(); + + // Variable and function types are resolved against the protobuf types first + // and then against the custom type introspector (if set). 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_); + } + 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_ASSIGN_OR_RETURN( + Type type, ResolveTypeInfoWithContext( + variable_config.type_info, *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); @@ -207,11 +452,19 @@ 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())); + FunctionConfigToFunctionDecl( + function_config, *type_introspector, arena)); CEL_RETURN_IF_ERROR(checker_builder.AddFunction(function_decl)); } + // Register the custom type introspector (if set) with the type checker so its + // types are available in expressions (e.g. as type literals) and remain alive + // for the lifetime of the built type checker. + if (type_introspector_ != nullptr) { + checker_builder.AddTypeProvider( + std::make_unique(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_test.cc b/env/env_test.cc index 822f1507f..2e1aeb396 100644 --- a/env/env_test.cc +++ b/env/env_test.cc @@ -15,6 +15,7 @@ #include "env/env.h" #include +#include #include #include #include @@ -34,6 +35,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 +57,7 @@ namespace cel { namespace { using ::absl_testing::IsOk; +using ::absl_testing::StatusIs; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Property; @@ -698,5 +701,343 @@ std::vector GetFunctionConfigTestCases() { INSTANTIATE_TEST_SUITE_P(FunctionConfigTest, FunctionConfigTest, ::testing::ValuesIn(GetFunctionConfigTestCases())); +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_; +}; + +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/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,