1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements type-checking of identifiers and type expressions.
13 "go/internal/typeparams"
18 // ident type-checks identifier e and initializes x with the value or type of e.
19 // If an error occurred, x.mode is set to invalid.
20 // For the meaning of def, see Checker.definedType, below.
21 // If wantType is set, the identifier e is expected to denote a type.
23 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
27 // Note that we cannot use check.lookup here because the returned scope
28 // may be different from obj.Parent(). See also Scope.LookupParent doc.
29 scope, obj := check.scope.LookupParent(e.Name, check.pos)
33 // Blank identifiers are never declared, but the current identifier may
34 // be a placeholder for a receiver type parameter. In this case we can
35 // resolve its type and object from Checker.recvTParamMap.
36 if tpar := check.recvTParamMap[e]; tpar != nil {
40 check.error(e, _InvalidBlank, "cannot use _ as value or type")
43 check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
46 case universeAny, universeComparable:
47 if !check.allowVersion(check.pkg, 1, 18) {
48 check.errorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
49 return // avoid follow-on errors
52 check.recordUse(e, obj)
54 // Type-check the object.
55 // Only call Checker.objDecl if the object doesn't have a type yet
56 // (in which case we must actually determine it) or the object is a
57 // TypeName and we also want a type (in which case we might detect
58 // a cycle which needs to be reported). Otherwise we can skip the
59 // call and avoid a possible cycle error in favor of the more
60 // informative "not a type/value" error that this function's caller
61 // will issue (see issue #25790).
63 if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
64 check.objDecl(obj, def)
65 typ = obj.Type() // type must have been assigned by Checker.objDecl
69 // The object may have been dot-imported.
70 // If so, mark the respective package as used.
71 // (This code is only needed for dot-imports. Without them,
72 // we only have to mark variables, see *Var case below).
73 if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
77 switch obj := obj.(type) {
79 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
84 if typ == Typ[Invalid] {
87 if obj == universeIota {
88 if check.iota == nil {
89 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
103 // It's ok to mark non-local variables, but ignore variables
104 // from other packages to avoid potential race conditions with
105 // dot-imported variables.
106 if obj.pkg == check.pkg {
109 check.addDeclDep(obj)
110 if typ == Typ[Invalid] {
116 check.addDeclDep(obj)
133 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
134 // The type must not be an (uninstantiated) generic type.
135 func (check *Checker) typ(e ast.Expr) Type {
136 return check.definedType(e, nil)
139 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
140 // The type must not be an (uninstantiated) generic type and it must not be a
141 // constraint interface.
142 func (check *Checker) varType(e ast.Expr) Type {
143 typ := check.definedType(e, nil)
144 // We don't want to call under() (via toInterface) or complete interfaces while we
145 // are in the middle of type-checking parameter declarations that might belong to
146 // interface methods. Delay this check to the end of type-checking.
148 if t := asInterface(typ); t != nil {
149 tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
150 if !tset.IsMethodSet() {
152 check.softErrorf(e, _Todo, "interface is (or embeds) comparable")
154 check.softErrorf(e, _Todo, "interface contains type constraints")
163 // definedType is like typ but also accepts a type name def.
164 // If def != nil, e is the type specification for the defined type def, declared
165 // in a type declaration, and def.underlying will be set to the type of e before
166 // any components of e are type-checked.
168 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
169 typ := check.typInternal(e, def)
172 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
175 check.recordTypeAndValue(e, typexpr, typ, nil)
179 // genericType is like typ but the type must be an (uninstantiated) generic type.
180 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
181 typ := check.typInternal(e, nil)
183 if typ != Typ[Invalid] && !isGeneric(typ) {
185 check.errorf(e, _Todo, "%s is not a generic type", typ)
189 // TODO(gri) what is the correct call below?
190 check.recordTypeAndValue(e, typexpr, typ, nil)
194 // goTypeName returns the Go type name for typ and
195 // removes any occurrences of "types." from that name.
196 func goTypeName(typ Type) string {
197 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
200 // typInternal drives type checking of types.
201 // Must only be called by definedType or genericType.
203 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
205 check.trace(e0.Pos(), "type %s", e0)
211 // Calling under() here may lead to endless instantiations.
212 // Test case: type T[P any] *T[P]
213 under = safeUnderlying(T)
216 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
218 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
223 switch e := e0.(type) {
225 // ignore - error reported before
229 check.ident(&x, e, def, true)
234 def.setUnderlying(typ)
237 // ignore - error reported before
239 check.errorf(&x, _NotAType, "%s used as type", &x)
241 check.errorf(&x, _NotAType, "%s is not a type", &x)
244 case *ast.SelectorExpr:
246 check.selector(&x, e)
251 def.setUnderlying(typ)
254 // ignore - error reported before
256 check.errorf(&x, _NotAType, "%s used as type", &x)
258 check.errorf(&x, _NotAType, "%s is not a type", &x)
261 case *ast.IndexExpr, *ast.IndexListExpr:
262 ix := typeparams.UnpackIndexExpr(e)
263 if !check.allowVersion(check.pkg, 1, 18) {
264 check.softErrorf(inNode(e, ix.Lbrack), _Todo, "type instantiation requires go1.18 or later")
266 return check.instantiatedType(ix.X, ix.Indices, def)
269 // Generic types must be instantiated before they can be used in any form.
270 // Consequently, generic types cannot be parenthesized.
271 return check.definedType(e.X, def)
276 def.setUnderlying(typ)
277 typ.elem = check.varType(e.Elt)
282 def.setUnderlying(typ)
283 typ.len = check.arrayLength(e.Len)
284 typ.elem = check.varType(e.Elt)
290 // dots are handled explicitly where they are legal
291 // (array composite literals and parameter lists)
292 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
295 case *ast.StructType:
297 def.setUnderlying(typ)
298 check.structType(typ, e)
303 def.setUnderlying(typ)
304 typ.base = check.varType(e.X)
308 typ := new(Signature)
309 def.setUnderlying(typ)
310 check.funcType(typ, nil, e)
313 case *ast.InterfaceType:
314 typ := new(Interface)
315 def.setUnderlying(typ)
319 check.interfaceType(typ, e, def)
324 def.setUnderlying(typ)
326 typ.key = check.varType(e.Key)
327 typ.elem = check.varType(e.Value)
329 // spec: "The comparison operators == and != must be fully defined
330 // for operands of the key type; thus the key type must not be a
331 // function, map, or slice."
333 // Delay this check because it requires fully setup types;
334 // it is safe to continue in any case (was issue 6667).
336 if !Comparable(typ.key) {
338 if asTypeParam(typ.key) != nil {
339 why = " (missing comparable constraint)"
341 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
349 def.setUnderlying(typ)
353 case ast.SEND | ast.RECV:
360 check.invalidAST(e, "unknown channel direction %d", e.Dir)
365 typ.elem = check.varType(e.Value)
369 check.errorf(e0, _NotAType, "%s is not a type", e0)
373 def.setUnderlying(typ)
377 func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) (res Type) {
379 check.trace(x.Pos(), "-- instantiating %s with %s", x, targsx)
383 // Don't format the underlying here. It will always be nil.
384 check.trace(x.Pos(), "=> %s", res)
388 gtyp := check.genericType(x, true)
389 if gtyp == Typ[Invalid] {
390 return gtyp // error already reported
393 origin, _ := gtyp.(*Named)
395 panic(fmt.Sprintf("%v: cannot instantiate %v", x.Pos(), gtyp))
398 // evaluate arguments
399 targs := check.typeList(targsx)
401 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
405 // determine argument positions
406 posList := make([]token.Pos, len(targs))
407 for i, arg := range targsx {
408 posList[i] = arg.Pos()
411 // create the instance
412 h := check.conf.Context.typeHash(origin, targs)
413 // targs may be incomplete, and require inference. In any case we should de-duplicate.
414 inst := check.conf.Context.typeForHash(h, nil)
415 // If inst is non-nil, we can't just return here. Inst may have been
416 // constructed via recursive substitution, in which case we wouldn't do the
417 // validation below. Ensure that the validation (and resulting errors) runs
418 // for each instantiated type in the source.
420 tname := NewTypeName(x.Pos(), origin.obj.pkg, origin.obj.name, nil)
421 inst = check.newNamed(tname, origin, nil, nil, nil) // underlying, methods and tparams are set when named is resolved
422 inst.targs = NewTypeList(targs)
423 inst = check.conf.Context.typeForHash(h, inst)
425 def.setUnderlying(inst)
427 inst.resolver = func(ctxt *Context, n *Named) (*TypeParamList, Type, []*Func) {
428 tparams := origin.TypeParams().list()
431 if len(targs) < len(tparams) {
432 // If inference fails, len(inferred) will be 0, and inst.underlying will
433 // be set to Typ[Invalid] in expandNamed.
434 inferred = check.infer(x, tparams, targs, nil, nil)
435 if len(inferred) > len(targs) {
436 inst.targs = NewTypeList(inferred)
440 check.recordInstance(x, inferred, inst)
441 return expandNamed(ctxt, n, x.Pos())
444 // origin.tparams may not be set up, so we need to do expansion later.
446 // This is an instance from the source, not from recursive substitution,
447 // and so it must be resolved during type-checking so that we can report
449 inst.resolve(check.conf.Context)
450 // Since check is non-nil, we can still mutate inst. Unpinning the resolver
451 // frees some memory.
454 if check.validateTArgLen(x.Pos(), inst.tparams.Len(), inst.targs.Len()) {
455 if i, err := check.verify(x.Pos(), inst.tparams.list(), inst.targs.list()); err != nil {
456 // best position for error reporting
458 if i < len(posList) {
461 check.softErrorf(atPos(pos), _Todo, err.Error())
463 check.mono.recordInstance(check.pkg, x.Pos(), inst.tparams.list(), inst.targs.list(), posList)
467 check.validType(inst, nil)
473 // arrayLength type-checks the array length expression e
474 // and returns the constant length >= 0, or a value < 0
475 // to indicate an error (and thus an unknown length).
476 func (check *Checker) arrayLength(e ast.Expr) int64 {
477 // If e is an undeclared identifier, the array declaration might be an
478 // attempt at a parameterized type declaration with missing constraint.
479 // Provide a better error message than just "undeclared name: X".
480 if name, _ := e.(*ast.Ident); name != nil && check.lookup(name.Name) == nil {
481 check.errorf(name, _InvalidArrayLen, "undeclared name %s for array length", name.Name)
487 if x.mode != constant_ {
488 if x.mode != invalid {
489 check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
494 if isUntyped(x.typ) || isInteger(x.typ) {
495 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
496 if representableConst(val, check, Typ[Int], nil) {
497 if n, ok := constant.Int64Val(val); ok && n >= 0 {
500 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
506 check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
510 // typeList provides the list of types corresponding to the incoming expression list.
511 // If an error occurred, the result is nil, but all list elements were type-checked.
512 func (check *Checker) typeList(list []ast.Expr) []Type {
513 res := make([]Type, len(list)) // res != nil even if len(list) == 0
514 for i, x := range list {
515 t := check.varType(x)
516 if t == Typ[Invalid] {