| 1 | // Copyright 2018 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Package checker defines functions to type-checked a parsed expression |
| 16 | // against a set of identifier and function declarations. |
| 17 | package checker |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "reflect" |
| 22 | "slices" |
| 23 | "strings" |
| 24 | |
| 25 | "github.com/google/cel-go/common" |
| 26 | "github.com/google/cel-go/common/ast" |
| 27 | "github.com/google/cel-go/common/containers" |
| 28 | "github.com/google/cel-go/common/decls" |
| 29 | "github.com/google/cel-go/common/operators" |
| 30 | "github.com/google/cel-go/common/types" |
| 31 | "github.com/google/cel-go/common/types/ref" |
| 32 | ) |
| 33 | |
| 34 | type checker struct { |
| 35 | *ast.AST |
| 36 | ast.ExprFactory |
| 37 | env *Env |
| 38 | errors *typeErrors |
| 39 | mappings *mapping |
| 40 | freeTypeVarCounter int |
| 41 | } |
| 42 | |
| 43 | // Check performs type checking, giving a typed AST. |
| 44 | // |
| 45 | // The input is a parsed AST and an env which encapsulates type binding of variables, |
| 46 | // declarations of built-in functions, descriptions of protocol buffers, and a registry for |
| 47 | // errors. |
| 48 | // |
| 49 | // Returns a type-checked AST, which might not be usable if there are errors in the error |
| 50 | // registry. |
| 51 | func Check(parsed *ast.AST, source common.Source, env *Env) (*ast.AST, *common.Errors) { |
| 52 | errs := common.NewErrors(source) |
| 53 | typeMap := make(map[int64]*types.Type) |
| 54 | refMap := make(map[int64]*ast.ReferenceInfo) |
| 55 | c := checker{ |
| 56 | AST: ast.NewCheckedAST(parsed, typeMap, refMap), |
| 57 | ExprFactory: ast.NewExprFactory(), |
| 58 | env: env, |
| 59 | errors: &typeErrors{errs: errs}, |
| 60 | mappings: newMapping(), |
| 61 | freeTypeVarCounter: 0, |
| 62 | } |
| 63 | c.check(c.Expr()) |
| 64 | |
| 65 | // Walk over the final type map substituting any type parameters either by their bound value |
| 66 | // or by DYN. |
| 67 | for id, t := range c.TypeMap() { |
| 68 | c.SetType(id, substitute(c.mappings, t, true)) |
| 69 | } |
| 70 | // Remove source info for IDs without a corresponding AST node. This can happen because |
| 71 | // check() deletes some nodes while rewriting the AST. For example the Select operand is |
| 72 | // deleted when a variable reference is replaced with a Ident expression. |
| 73 | c.AST.ClearUnusedIDs() |
| 74 | return c.AST, errs |
| 75 | } |
| 76 | |
| 77 | func (c *checker) check(e ast.Expr) { |
| 78 | if e == nil { |
| 79 | return |
| 80 | } |
| 81 | switch e.Kind() { |
| 82 | case ast.LiteralKind: |
| 83 | literal := ref.Val(e.AsLiteral()) |
| 84 | switch literal.Type() { |
| 85 | case types.BoolType, types.BytesType, types.DoubleType, types.IntType, |
| 86 | types.NullType, types.StringType, types.UintType: |
| 87 | c.setType(e, literal.Type().(*types.Type)) |
| 88 | default: |
| 89 | c.errors.unexpectedASTType(e.ID(), c.location(e), "literal", literal.Type().TypeName()) |
| 90 | } |
| 91 | case ast.IdentKind: |
| 92 | c.checkIdent(e) |
| 93 | case ast.SelectKind: |
| 94 | c.checkSelect(e) |
| 95 | case ast.CallKind: |
| 96 | c.checkCall(e) |
| 97 | case ast.ListKind: |
| 98 | c.checkCreateList(e) |
| 99 | case ast.MapKind: |
| 100 | c.checkCreateMap(e) |
| 101 | case ast.StructKind: |
| 102 | c.checkCreateStruct(e) |
| 103 | case ast.ComprehensionKind: |
| 104 | c.checkComprehension(e) |
| 105 | default: |
| 106 | c.errors.unexpectedASTType(e.ID(), c.location(e), "unspecified", reflect.TypeOf(e).Name()) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | func (c *checker) checkIdent(e ast.Expr) { |
| 111 | identName := e.AsIdent() |
| 112 | // Check to see if the identifier is declared. |
| 113 | if ident := c.env.resolveSimpleIdent(identName); ident != nil { |
| 114 | name := strings.TrimPrefix(ident.Name(), ".") |
| 115 | if ident.requiresDisambiguation { |
| 116 | name = "." + name |
| 117 | } |
| 118 | c.setType(e, ident.Type()) |
| 119 | c.setReference(e, ast.NewIdentReference(name, ident.Value())) |
| 120 | // Overwrite the identifier with its fully qualified name. |
| 121 | e.SetKindCase(c.NewIdent(e.ID(), name)) |
| 122 | return |
| 123 | } |
| 124 | |
| 125 | c.setType(e, types.ErrorType) |
| 126 | c.errors.undeclaredReference(e.ID(), c.location(e), c.env.container.Name(), identName) |
| 127 | } |
| 128 | |
| 129 | func (c *checker) checkSelect(e ast.Expr) { |
| 130 | sel := e.AsSelect() |
| 131 | // Before traversing down the tree, try to interpret as qualified name. |
| 132 | qualifiers, found := c.computeQualifiers(e) |
| 133 | if found { |
| 134 | ident := c.env.resolveQualifiedIdent(qualifiers...) |
| 135 | if ident != nil { |
| 136 | // We don't check for a TestOnly expression here since the `found` result is |
| 137 | // always going to be false for TestOnly expressions. |
| 138 | |
| 139 | // Rewrite the node to be a variable reference to the resolved fully-qualified |
| 140 | // variable name. |
| 141 | name := ident.Name() |
| 142 | if ident.requiresDisambiguation { |
| 143 | name = "." + name |
| 144 | } |
| 145 | c.setType(e, ident.Type()) |
| 146 | c.setReference(e, ast.NewIdentReference(name, ident.Value())) |
| 147 | e.SetKindCase(c.NewIdent(e.ID(), name)) |
| 148 | return |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | resultType := c.checkSelectField(e, sel.Operand(), sel.FieldName(), false) |
| 153 | if sel.IsTestOnly() { |
| 154 | resultType = types.BoolType |
| 155 | } |
| 156 | c.setType(e, substitute(c.mappings, resultType, false)) |
| 157 | } |
| 158 | |
| 159 | // computeQualifiers computes the qualified names parts of a select expression. |
| 160 | func (c *checker) computeQualifiers(e ast.Expr) ([]string, bool) { |
| 161 | var qualifiers []string |
| 162 | for e.Kind() == ast.SelectKind { |
| 163 | sel := e.AsSelect() |
| 164 | // test only expressions are not considered for qualified name selection. |
| 165 | if sel.IsTestOnly() { |
| 166 | return qualifiers, false |
| 167 | } |
| 168 | // otherwise append the select field name to the qualifier list (reverse order) |
| 169 | qualifiers = append(qualifiers, sel.FieldName()) |
| 170 | e = sel.Operand() |
| 171 | // If the next operand is an identifier, then append it, reverse the name sequence |
| 172 | // and return it to the caller.s |
| 173 | if e.Kind() == ast.IdentKind { |
| 174 | qualifiers = append(qualifiers, e.AsIdent()) |
| 175 | slices.Reverse(qualifiers) |
| 176 | return qualifiers, true |
| 177 | } |
| 178 | } |
| 179 | return qualifiers, false |
| 180 | } |
| 181 | |
| 182 | func (c *checker) checkOptSelect(e ast.Expr) { |
| 183 | // Collect metadata related to the opt select call packaged by the parser. |
| 184 | call := e.AsCall() |
| 185 | if len(call.Args()) != 2 || call.IsMemberFunction() { |
| 186 | t := "" |
| 187 | if call.IsMemberFunction() { |
| 188 | t = " member call with" |
| 189 | } |
| 190 | c.errors.notAnOptionalFieldSelectionCall(e.ID(), c.location(e), |
| 191 | fmt.Sprintf( |
| 192 | "incorrect signature.%s argument count: %d", t, len(call.Args()))) |
| 193 | return |
| 194 | } |
| 195 | |
| 196 | operand := call.Args()[0] |
| 197 | field := call.Args()[1] |
| 198 | fieldName, isString := maybeUnwrapString(field) |
| 199 | if !isString { |
| 200 | c.errors.notAnOptionalFieldSelection(field.ID(), c.location(field), field) |
| 201 | return |
| 202 | } |
| 203 | |
| 204 | // Perform type-checking using the field selection logic. |
| 205 | resultType := c.checkSelectField(e, operand, fieldName, true) |
| 206 | c.setType(e, substitute(c.mappings, resultType, false)) |
| 207 | c.setReference(e, ast.NewFunctionReference("select_optional_field")) |
| 208 | } |
| 209 | |
| 210 | func (c *checker) checkSelectField(e, operand ast.Expr, field string, optional bool) *types.Type { |
| 211 | // Interpret as field selection, first traversing down the operand. |
| 212 | c.check(operand) |
| 213 | operandType := substitute(c.mappings, c.getType(operand), false) |
| 214 | |
| 215 | // If the target type is 'optional', unwrap it for the sake of this check. |
| 216 | targetType, isOpt := maybeUnwrapOptional(operandType) |
| 217 | |
| 218 | // Assume error type by default as most types do not support field selection. |
| 219 | resultType := types.ErrorType |
| 220 | switch targetType.Kind() { |
| 221 | case types.MapKind: |
| 222 | // Maps yield their value type as the selection result type. |
| 223 | resultType = targetType.Parameters()[1] |
| 224 | case types.StructKind: |
| 225 | // Objects yield their field type declaration as the selection result type, but only if |
| 226 | // the field is defined. |
| 227 | messageType := targetType |
| 228 | if fieldType, found := c.lookupFieldType(e.ID(), messageType.TypeName(), field); found { |
| 229 | resultType = fieldType |
| 230 | } |
| 231 | case types.TypeParamKind: |
| 232 | // Set the operand type to DYN to prevent assignment to a potentially incorrect type |
| 233 | // at a later point in type-checking. The isAssignable call will update the type |
| 234 | // substitutions for the type param under the covers. |
| 235 | c.isAssignable(types.DynType, targetType) |
| 236 | // Also, set the result type to DYN. |
| 237 | resultType = types.DynType |
| 238 | default: |
| 239 | // Dynamic / error values are treated as DYN type. Errors are handled this way as well |
| 240 | // in order to allow forward progress on the check. |
| 241 | if !isDynOrError(targetType) { |
| 242 | c.errors.typeDoesNotSupportFieldSelection(e.ID(), c.location(e), targetType) |
| 243 | } |
| 244 | resultType = types.DynType |
| 245 | } |
| 246 | |
| 247 | // If the target type was optional coming in, then the result must be optional going out. |
| 248 | if isOpt || optional { |
| 249 | return types.NewOptionalType(resultType) |
| 250 | } |
| 251 | return resultType |
| 252 | } |
| 253 | |
| 254 | func (c *checker) checkCall(e ast.Expr) { |
| 255 | // Note: similar logic exists within the `interpreter/planner.go`. If making changes here |
| 256 | // please consider the impact on planner.go and consolidate implementations or mirror code |
| 257 | // as appropriate. |
| 258 | call := e.AsCall() |
| 259 | fnName := call.FunctionName() |
| 260 | if fnName == operators.OptSelect { |
| 261 | c.checkOptSelect(e) |
| 262 | return |
| 263 | } |
| 264 | |
| 265 | args := call.Args() |
| 266 | // Traverse arguments. |
| 267 | for _, arg := range args { |
| 268 | c.check(arg) |
| 269 | } |
| 270 | |
| 271 | // Regular static call with simple name. |
| 272 | if !call.IsMemberFunction() { |
| 273 | // Check for the existence of the function. |
| 274 | fn := c.env.lookupFunction(fnName) |
| 275 | if fn == nil { |
| 276 | c.errors.undeclaredReference(e.ID(), c.location(e), c.env.container.Name(), fnName) |
| 277 | c.setType(e, types.ErrorType) |
| 278 | return |
| 279 | } |
| 280 | // Overwrite the function name with its fully qualified resolved name. |
| 281 | e.SetKindCase(c.NewCall(e.ID(), fn.Name(), args...)) |
| 282 | // Check to see whether the overload resolves. |
| 283 | c.resolveOverloadOrError(e, fn, nil, args) |
| 284 | return |
| 285 | } |
| 286 | |
| 287 | // If a receiver 'target' is present, it may either be a receiver function, or a namespaced |
| 288 | // function, but not both. Given a.b.c() either a.b.c is a function or c is a function with |
| 289 | // target a.b. |
| 290 | // |
| 291 | // Check whether the target is a namespaced function name. |
| 292 | target := call.Target() |
| 293 | qualifiedPrefix, maybeQualified := containers.ToQualifiedName(target) |
| 294 | if maybeQualified { |
| 295 | maybeQualifiedName := qualifiedPrefix + "." + fnName |
| 296 | fn := c.env.lookupFunction(maybeQualifiedName) |
| 297 | if fn != nil { |
| 298 | // The function name is namespaced and so preserving the target operand would |
| 299 | // be an inaccurate representation of the desired evaluation behavior. |
| 300 | // Overwrite with fully-qualified resolved function name sans receiver target. |
| 301 | e.SetKindCase(c.NewCall(e.ID(), fn.Name(), args...)) |
| 302 | c.resolveOverloadOrError(e, fn, nil, args) |
| 303 | return |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | // Regular instance call. |
| 308 | c.check(target) |
| 309 | fn := c.env.lookupFunction(fnName) |
| 310 | // Function found, attempt overload resolution. |
| 311 | if fn != nil { |
| 312 | c.resolveOverloadOrError(e, fn, target, args) |
| 313 | return |
| 314 | } |
| 315 | // Function name not declared, record error. |
| 316 | c.setType(e, types.ErrorType) |
| 317 | c.errors.undeclaredReference(e.ID(), c.location(e), c.env.container.Name(), fnName) |
| 318 | } |
| 319 | |
| 320 | func (c *checker) resolveOverloadOrError( |
| 321 | e ast.Expr, fn *decls.FunctionDecl, target ast.Expr, args []ast.Expr) { |
| 322 | // Attempt to resolve the overload. |
| 323 | resolution := c.resolveOverload(e, fn, target, args) |
| 324 | // No such overload, error noted in the resolveOverload call, type recorded here. |
| 325 | if resolution == nil { |
| 326 | c.setType(e, types.ErrorType) |
| 327 | return |
| 328 | } |
| 329 | // Overload found. |
| 330 | c.setType(e, resolution.Type) |
| 331 | c.setReference(e, resolution.Reference) |
| 332 | } |
| 333 | |
| 334 | func (c *checker) resolveOverload( |
| 335 | call ast.Expr, fn *decls.FunctionDecl, target ast.Expr, args []ast.Expr) *overloadResolution { |
| 336 | |
| 337 | var argTypes []*types.Type |
| 338 | if target != nil { |
| 339 | argTypes = append(argTypes, c.getType(target)) |
| 340 | } |
| 341 | for _, arg := range args { |
| 342 | argTypes = append(argTypes, c.getType(arg)) |
| 343 | } |
| 344 | |
| 345 | var resultType *types.Type |
| 346 | var checkedRef *ast.ReferenceInfo |
| 347 | for _, overload := range fn.OverloadDecls() { |
| 348 | // Determine whether the overload is currently considered. |
| 349 | if c.env.isOverloadDisabled(overload.ID()) { |
| 350 | continue |
| 351 | } |
| 352 | |
| 353 | // Ensure the call style for the overload matches. |
| 354 | if (target == nil && overload.IsMemberFunction()) || |
| 355 | (target != nil && !overload.IsMemberFunction()) { |
| 356 | // not a compatible call style. |
| 357 | continue |
| 358 | } |
| 359 | |
| 360 | // Alternative type-checking behavior when the logical operators are compacted into |
| 361 | // variadic AST representations. |
| 362 | if fn.Name() == operators.LogicalAnd || fn.Name() == operators.LogicalOr { |
| 363 | checkedRef = ast.NewFunctionReference(overload.ID()) |
| 364 | for i, argType := range argTypes { |
| 365 | if !c.isAssignable(argType, types.BoolType) { |
| 366 | c.errors.typeMismatch( |
| 367 | args[i].ID(), |
| 368 | c.locationByID(args[i].ID()), |
| 369 | types.BoolType, |
| 370 | argType) |
| 371 | resultType = types.ErrorType |
| 372 | } |
| 373 | } |
| 374 | if isError(resultType) { |
| 375 | return nil |
| 376 | } |
| 377 | return newResolution(checkedRef, types.BoolType) |
| 378 | } |
| 379 | |
| 380 | overloadType := newFunctionType(overload.ResultType(), overload.ArgTypes()...) |
| 381 | typeParams := overload.TypeParams() |
| 382 | if len(typeParams) != 0 { |
| 383 | // Instantiate overload's type with fresh type variables. |
| 384 | substitutions := newMapping() |
| 385 | for _, typePar := range typeParams { |
| 386 | substitutions.add(types.NewTypeParamType(typePar), c.newTypeVar()) |
| 387 | } |
| 388 | overloadType = substitute(substitutions, overloadType, false) |
| 389 | } |
| 390 | |
| 391 | candidateArgTypes := overloadType.Parameters()[1:] |
| 392 | if c.isAssignableList(argTypes, candidateArgTypes) { |
| 393 | if checkedRef == nil { |
| 394 | checkedRef = ast.NewFunctionReference(overload.ID()) |
| 395 | } else { |
| 396 | checkedRef.AddOverload(overload.ID()) |
| 397 | } |
| 398 | |
| 399 | // First matching overload, determines result type. |
| 400 | fnResultType := substitute(c.mappings, overloadType.Parameters()[0], false) |
| 401 | if resultType == nil { |
| 402 | resultType = fnResultType |
| 403 | } else if !isDyn(resultType) && !fnResultType.IsExactType(resultType) { |
| 404 | resultType = types.DynType |
| 405 | } |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | if resultType == nil { |
| 410 | for i, argType := range argTypes { |
| 411 | argTypes[i] = substitute(c.mappings, argType, true) |
| 412 | } |
| 413 | c.errors.noMatchingOverload(call.ID(), c.location(call), fn.Name(), argTypes, target != nil) |
| 414 | return nil |
| 415 | } |
| 416 | |
| 417 | return newResolution(checkedRef, resultType) |
| 418 | } |
| 419 | |
| 420 | func (c *checker) checkCreateList(e ast.Expr) { |
| 421 | create := e.AsList() |
| 422 | var elemsType *types.Type |
| 423 | optionalIndices := create.OptionalIndices() |
| 424 | optionals := make(map[int32]bool, len(optionalIndices)) |
| 425 | for _, optInd := range optionalIndices { |
| 426 | optionals[optInd] = true |
| 427 | } |
| 428 | for i, e := range create.Elements() { |
| 429 | c.check(e) |
| 430 | elemType := c.getType(e) |
| 431 | if optionals[int32(i)] { |
| 432 | var isOptional bool |
| 433 | elemType, isOptional = maybeUnwrapOptional(elemType) |
| 434 | if !isOptional && !isDyn(elemType) { |
| 435 | c.errors.typeMismatch(e.ID(), c.location(e), types.NewOptionalType(elemType), elemType) |
| 436 | } |
| 437 | } |
| 438 | elemsType = c.joinTypes(e, elemsType, elemType) |
| 439 | } |
| 440 | if elemsType == nil { |
| 441 | // If the list is empty, assign free type var to elem type. |
| 442 | elemsType = c.newTypeVar() |
| 443 | } |
| 444 | c.setType(e, types.NewListType(elemsType)) |
| 445 | } |
| 446 | |
| 447 | func (c *checker) checkCreateMap(e ast.Expr) { |
| 448 | mapVal := e.AsMap() |
| 449 | var mapKeyType *types.Type |
| 450 | var mapValueType *types.Type |
| 451 | for _, e := range mapVal.Entries() { |
| 452 | entry := e.AsMapEntry() |
| 453 | key := entry.Key() |
| 454 | c.check(key) |
| 455 | mapKeyType = c.joinTypes(key, mapKeyType, c.getType(key)) |
| 456 | |
| 457 | val := entry.Value() |
| 458 | c.check(val) |
| 459 | valType := c.getType(val) |
| 460 | if entry.IsOptional() { |
| 461 | var isOptional bool |
| 462 | valType, isOptional = maybeUnwrapOptional(valType) |
| 463 | if !isOptional && !isDyn(valType) { |
| 464 | c.errors.typeMismatch(val.ID(), c.location(val), types.NewOptionalType(valType), valType) |
| 465 | } |
| 466 | } |
| 467 | mapValueType = c.joinTypes(val, mapValueType, valType) |
| 468 | } |
| 469 | if mapKeyType == nil { |
| 470 | // If the map is empty, assign free type variables to typeKey and value type. |
| 471 | mapKeyType = c.newTypeVar() |
| 472 | mapValueType = c.newTypeVar() |
| 473 | } |
| 474 | c.setType(e, types.NewMapType(mapKeyType, mapValueType)) |
| 475 | } |
| 476 | |
| 477 | func (c *checker) checkCreateStruct(e ast.Expr) { |
| 478 | msgVal := e.AsStruct() |
| 479 | // Determine the type of the message. |
| 480 | resultType := types.ErrorType |
| 481 | ident := c.env.resolveTypeIdent(msgVal.TypeName()) |
| 482 | if ident == nil { |
| 483 | c.errors.undeclaredReference( |
| 484 | e.ID(), c.location(e), c.env.container.Name(), msgVal.TypeName()) |
| 485 | c.setType(e, types.ErrorType) |
| 486 | return |
| 487 | } |
| 488 | // Ensure the type name is fully qualified in the AST. |
| 489 | typeName := ident.Name() |
| 490 | if msgVal.TypeName() != typeName { |
| 491 | e.SetKindCase(c.NewStruct(e.ID(), typeName, msgVal.Fields())) |
| 492 | msgVal = e.AsStruct() |
| 493 | } |
| 494 | c.setReference(e, ast.NewIdentReference(typeName, nil)) |
| 495 | identKind := ident.Type().Kind() |
| 496 | if identKind != types.ErrorKind { |
| 497 | if identKind != types.TypeKind { |
| 498 | c.errors.notAType(e.ID(), c.location(e), ident.Type().DeclaredTypeName()) |
| 499 | } else { |
| 500 | resultType = ident.Type().Parameters()[0] |
| 501 | // Backwards compatibility test between well-known types and message types |
| 502 | // In this context, the type is being instantiated by its protobuf name which |
| 503 | // is not ideal or recommended, but some users expect this to work. |
| 504 | if isWellKnownType(resultType) { |
| 505 | typeName = getWellKnownTypeName(resultType) |
| 506 | } else if resultType.Kind() == types.StructKind { |
| 507 | typeName = resultType.DeclaredTypeName() |
| 508 | } else { |
| 509 | c.errors.notAMessageType(e.ID(), c.location(e), resultType.DeclaredTypeName()) |
| 510 | resultType = types.ErrorType |
| 511 | } |
| 512 | } |
| 513 | } |
| 514 | c.setType(e, resultType) |
| 515 | |
| 516 | // Check the field initializers. |
| 517 | for _, f := range msgVal.Fields() { |
| 518 | field := f.AsStructField() |
| 519 | fieldName := field.Name() |
| 520 | value := field.Value() |
| 521 | c.check(value) |
| 522 | |
| 523 | fieldType := types.ErrorType |
| 524 | ft, found := c.lookupFieldType(f.ID(), typeName, fieldName) |
| 525 | if found { |
| 526 | fieldType = ft |
| 527 | } |
| 528 | |
| 529 | valType := c.getType(value) |
| 530 | if field.IsOptional() { |
| 531 | var isOptional bool |
| 532 | valType, isOptional = maybeUnwrapOptional(valType) |
| 533 | if !isOptional && !isDyn(valType) { |
| 534 | c.errors.typeMismatch(value.ID(), c.location(value), types.NewOptionalType(valType), valType) |
| 535 | } |
| 536 | } |
| 537 | if !c.isAssignable(fieldType, valType) { |
| 538 | c.errors.fieldTypeMismatch(f.ID(), c.locationByID(f.ID()), fieldName, fieldType, valType) |
| 539 | } |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | func (c *checker) checkComprehension(e ast.Expr) { |
| 544 | comp := e.AsComprehension() |
| 545 | c.check(comp.IterRange()) |
| 546 | c.check(comp.AccuInit()) |
| 547 | rangeType := substitute(c.mappings, c.getType(comp.IterRange()), false) |
| 548 | |
| 549 | // Create a scope for the comprehension since it has a local accumulation variable. |
| 550 | // This scope will contain the accumulation variable used to compute the result. |
| 551 | accuType := c.getType(comp.AccuInit()) |
| 552 | c.env = c.env.enterScope() |
| 553 | c.env.AddIdents(decls.NewVariable(comp.AccuVar(), accuType)) |
| 554 | |
| 555 | var varType, var2Type *types.Type |
| 556 | switch rangeType.Kind() { |
| 557 | case types.ListKind: |
| 558 | // varType represents the list element type for one-variable comprehensions. |
| 559 | varType = rangeType.Parameters()[0] |
| 560 | if comp.HasIterVar2() { |
| 561 | // varType represents the list index (int) for two-variable comprehensions, |
| 562 | // and var2Type represents the list element type. |
| 563 | var2Type = varType |
| 564 | varType = types.IntType |
| 565 | } |
| 566 | case types.MapKind: |
| 567 | // varType represents the map entry key for all comprehension types. |
| 568 | varType = rangeType.Parameters()[0] |
| 569 | if comp.HasIterVar2() { |
| 570 | // var2Type represents the map entry value for two-variable comprehensions. |
| 571 | var2Type = rangeType.Parameters()[1] |
| 572 | } |
| 573 | case types.DynKind, types.ErrorKind, types.TypeParamKind: |
| 574 | // Set the range type to DYN to prevent assignment to a potentially incorrect type |
| 575 | // at a later point in type-checking. The isAssignable call will update the type |
| 576 | // substitutions for the type param under the covers. |
| 577 | c.isAssignable(types.DynType, rangeType) |
| 578 | // Set the range iteration variable to type DYN as well. |
| 579 | varType = types.DynType |
| 580 | if comp.HasIterVar2() { |
| 581 | var2Type = types.DynType |
| 582 | } |
| 583 | default: |
| 584 | c.errors.notAComprehensionRange(comp.IterRange().ID(), c.location(comp.IterRange()), rangeType) |
| 585 | varType = types.ErrorType |
| 586 | if comp.HasIterVar2() { |
| 587 | var2Type = types.ErrorType |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | // Create a block scope for the loop. |
| 592 | c.env = c.env.enterScope() |
| 593 | c.env.AddIdents(decls.NewVariable(comp.IterVar(), varType)) |
| 594 | if comp.HasIterVar2() { |
| 595 | c.env.AddIdents(decls.NewVariable(comp.IterVar2(), var2Type)) |
| 596 | } |
| 597 | // Check the variable references in the condition and step. |
| 598 | c.check(comp.LoopCondition()) |
| 599 | c.assertType(comp.LoopCondition(), types.BoolType) |
| 600 | c.check(comp.LoopStep()) |
| 601 | c.assertType(comp.LoopStep(), accuType) |
| 602 | // Exit the loop's block scope before checking the result. |
| 603 | c.env = c.env.exitScope() |
| 604 | c.check(comp.Result()) |
| 605 | // Exit the comprehension scope. |
| 606 | c.env = c.env.exitScope() |
| 607 | c.setType(e, substitute(c.mappings, c.getType(comp.Result()), false)) |
| 608 | } |
| 609 | |
| 610 | // Checks compatibility of joined types, and returns the most general common type. |
| 611 | func (c *checker) joinTypes(e ast.Expr, previous, current *types.Type) *types.Type { |
| 612 | if previous == nil { |
| 613 | return current |
| 614 | } |
| 615 | if c.isAssignable(previous, current) { |
| 616 | return mostGeneral(previous, current) |
| 617 | } |
| 618 | if c.dynAggregateLiteralElementTypesEnabled() { |
| 619 | return types.DynType |
| 620 | } |
| 621 | c.errors.typeMismatch(e.ID(), c.location(e), previous, current) |
| 622 | return types.ErrorType |
| 623 | } |
| 624 | |
| 625 | func (c *checker) dynAggregateLiteralElementTypesEnabled() bool { |
| 626 | return c.env.aggLitElemType == dynElementType |
| 627 | } |
| 628 | |
| 629 | func (c *checker) newTypeVar() *types.Type { |
| 630 | id := c.freeTypeVarCounter |
| 631 | c.freeTypeVarCounter++ |
| 632 | return types.NewTypeParamType(fmt.Sprintf("_var%d", id)) |
| 633 | } |
| 634 | |
| 635 | func (c *checker) isAssignable(t1, t2 *types.Type) bool { |
| 636 | subs := isAssignable(c.mappings, t1, t2) |
| 637 | if subs != nil { |
| 638 | c.mappings = subs |
| 639 | return true |
| 640 | } |
| 641 | |
| 642 | return false |
| 643 | } |
| 644 | |
| 645 | func (c *checker) isAssignableList(l1, l2 []*types.Type) bool { |
| 646 | subs := isAssignableList(c.mappings, l1, l2) |
| 647 | if subs != nil { |
| 648 | c.mappings = subs |
| 649 | return true |
| 650 | } |
| 651 | |
| 652 | return false |
| 653 | } |
| 654 | |
| 655 | func maybeUnwrapString(e ast.Expr) (string, bool) { |
| 656 | switch e.Kind() { |
| 657 | case ast.LiteralKind: |
| 658 | literal := e.AsLiteral() |
| 659 | switch v := literal.(type) { |
| 660 | case types.String: |
| 661 | return string(v), true |
| 662 | } |
| 663 | } |
| 664 | return "", false |
| 665 | } |
| 666 | |
| 667 | func (c *checker) setType(e ast.Expr, t *types.Type) { |
| 668 | if old, found := c.TypeMap()[e.ID()]; found && !old.IsExactType(t) { |
| 669 | c.errors.incompatibleType(e.ID(), c.location(e), e, old, t) |
| 670 | return |
| 671 | } |
| 672 | c.SetType(e.ID(), t) |
| 673 | } |
| 674 | |
| 675 | func (c *checker) getType(e ast.Expr) *types.Type { |
| 676 | return c.TypeMap()[e.ID()] |
| 677 | } |
| 678 | |
| 679 | func (c *checker) setReference(e ast.Expr, r *ast.ReferenceInfo) { |
| 680 | if old, found := c.ReferenceMap()[e.ID()]; found && !old.Equals(r) { |
| 681 | c.errors.referenceRedefinition(e.ID(), c.location(e), e, old, r) |
| 682 | return |
| 683 | } |
| 684 | c.SetReference(e.ID(), r) |
| 685 | } |
| 686 | |
| 687 | func (c *checker) assertType(e ast.Expr, t *types.Type) { |
| 688 | if !c.isAssignable(t, c.getType(e)) { |
| 689 | c.errors.typeMismatch(e.ID(), c.location(e), t, c.getType(e)) |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | type overloadResolution struct { |
| 694 | Type *types.Type |
| 695 | Reference *ast.ReferenceInfo |
| 696 | } |
| 697 | |
| 698 | func newResolution(r *ast.ReferenceInfo, t *types.Type) *overloadResolution { |
| 699 | return &overloadResolution{ |
| 700 | Reference: r, |
| 701 | Type: t, |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | func (c *checker) location(e ast.Expr) common.Location { |
| 706 | return c.locationByID(e.ID()) |
| 707 | } |
| 708 | |
| 709 | func (c *checker) locationByID(id int64) common.Location { |
| 710 | return c.SourceInfo().GetStartLocation(id) |
| 711 | } |
| 712 | |
| 713 | func (c *checker) lookupFieldType(exprID int64, structType, fieldName string) (*types.Type, bool) { |
| 714 | if _, found := c.env.provider.FindStructType(structType); !found { |
| 715 | // This should not happen, anyway, report an error. |
| 716 | c.errors.unexpectedFailedResolution(exprID, c.locationByID(exprID), structType) |
| 717 | return nil, false |
| 718 | } |
| 719 | |
| 720 | if ft, found := c.env.provider.FindStructFieldType(structType, fieldName); found { |
| 721 | return ft.Type, found |
| 722 | } |
| 723 | |
| 724 | c.errors.undefinedField(exprID, c.locationByID(exprID), fieldName) |
| 725 | return nil, false |
| 726 | } |
| 727 | |
| 728 | func isWellKnownType(t *types.Type) bool { |
| 729 | switch t.Kind() { |
| 730 | case types.AnyKind, types.TimestampKind, types.DurationKind, types.DynKind, types.NullTypeKind: |
| 731 | return true |
| 732 | case types.BoolKind, types.BytesKind, types.DoubleKind, types.IntKind, types.StringKind, types.UintKind: |
| 733 | return t.IsAssignableType(types.NullType) |
| 734 | case types.ListKind: |
| 735 | return t.Parameters()[0] == types.DynType |
| 736 | case types.MapKind: |
| 737 | return t.Parameters()[0] == types.StringType && t.Parameters()[1] == types.DynType |
| 738 | } |
| 739 | return false |
| 740 | } |
| 741 | |
| 742 | func getWellKnownTypeName(t *types.Type) string { |
| 743 | if name, found := wellKnownTypes[t.Kind()]; found { |
| 744 | return name |
| 745 | } |
| 746 | return "" |
| 747 | } |
| 748 | |
| 749 | var ( |
| 750 | wellKnownTypes = map[types.Kind]string{ |
| 751 | types.AnyKind: "google.protobuf.Any", |
| 752 | types.BoolKind: "google.protobuf.BoolValue", |
| 753 | types.BytesKind: "google.protobuf.BytesValue", |
| 754 | types.DoubleKind: "google.protobuf.DoubleValue", |
| 755 | types.DurationKind: "google.protobuf.Duration", |
| 756 | types.DynKind: "google.protobuf.Value", |
| 757 | types.IntKind: "google.protobuf.Int64Value", |
| 758 | types.ListKind: "google.protobuf.ListValue", |
| 759 | types.NullTypeKind: "google.protobuf.NullValue", |
| 760 | types.MapKind: "google.protobuf.Struct", |
| 761 | types.StringKind: "google.protobuf.StringValue", |
| 762 | types.TimestampKind: "google.protobuf.Timestamp", |
| 763 | types.UintKind: "google.protobuf.UInt64Value", |
| 764 | } |
| 765 | ) |