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"
14 . "internal/types/errors"
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.
22 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
26 // Note that we cannot use check.lookup here because the returned scope
27 // may be different from obj.Parent(). See also Scope.LookupParent doc.
28 scope, obj := check.scope.LookupParent(e.Name, check.pos)
32 // Blank identifiers are never declared, but the current identifier may
33 // be a placeholder for a receiver type parameter. In this case we can
34 // resolve its type and object from Checker.recvTParamMap.
35 if tpar := check.recvTParamMap[e]; tpar != nil {
39 check.error(e, InvalidBlank, "cannot use _ as value or type")
42 check.errorf(e, UndeclaredName, "undefined: %s", e.Name)
45 case universeAny, universeComparable:
46 if !check.allowVersion(check.pkg, e.Pos(), 1, 18) {
47 check.versionErrorf(e, "go1.18", "predeclared %s", e.Name)
48 return // avoid follow-on errors
51 check.recordUse(e, obj)
53 // Type-check the object.
54 // Only call Checker.objDecl if the object doesn't have a type yet
55 // (in which case we must actually determine it) or the object is a
56 // TypeName and we also want a type (in which case we might detect
57 // a cycle which needs to be reported). Otherwise we can skip the
58 // call and avoid a possible cycle error in favor of the more
59 // informative "not a type/value" error that this function's caller
60 // will issue (see go.dev/issue/25790).
62 if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
63 check.objDecl(obj, def)
64 typ = obj.Type() // type must have been assigned by Checker.objDecl
68 // The object may have been dot-imported.
69 // If so, mark the respective package as used.
70 // (This code is only needed for dot-imports. Without them,
71 // we only have to mark variables, see *Var case below).
72 if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
76 switch obj := obj.(type) {
78 check.errorf(e, InvalidPkgUse, "use of package %s not in selector", obj.name)
83 if typ == Typ[Invalid] {
86 if obj == universeIota {
87 if check.iota == nil {
88 check.error(e, InvalidIota, "cannot use iota outside constant declaration")
99 if check.isBrokenAlias(obj) {
100 check.errorf(e, InvalidDeclCycle, "invalid use of type alias %s in recursive type (see go.dev/issue/50729)", obj.name)
106 // It's ok to mark non-local variables, but ignore variables
107 // from other packages to avoid potential race conditions with
108 // dot-imported variables.
109 if obj.pkg == check.pkg {
112 check.addDeclDep(obj)
113 if typ == Typ[Invalid] {
119 check.addDeclDep(obj)
136 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
137 // The type must not be an (uninstantiated) generic type.
138 func (check *Checker) typ(e ast.Expr) Type {
139 return check.definedType(e, nil)
142 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
143 // The type must not be an (uninstantiated) generic type and it must not be a
144 // constraint interface.
145 func (check *Checker) varType(e ast.Expr) Type {
146 typ := check.definedType(e, nil)
147 check.validVarType(e, typ)
151 // validVarType reports an error if typ is a constraint interface.
152 // The expression e is used for error reporting, if any.
153 func (check *Checker) validVarType(e ast.Expr, typ Type) {
154 // If we have a type parameter there's nothing to do.
155 if isTypeParam(typ) {
159 // We don't want to call under() or complete interfaces while we are in
160 // the middle of type-checking parameter declarations that might belong
161 // to interface methods. Delay this check to the end of type-checking.
163 if t, _ := under(typ).(*Interface); t != nil {
164 tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
165 if !tset.IsMethodSet() {
167 check.softErrorf(e, MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface is (or embeds) comparable", typ)
169 check.softErrorf(e, MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface contains type constraints", typ)
173 }).describef(e, "check var type %s", typ)
176 // definedType is like typ but also accepts a type name def.
177 // If def != nil, e is the type specification for the defined type def, declared
178 // in a type declaration, and def.underlying will be set to the type of e before
179 // any components of e are type-checked.
180 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
181 typ := check.typInternal(e, def)
184 check.errorf(e, WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
187 check.recordTypeAndValue(e, typexpr, typ, nil)
191 // genericType is like typ but the type must be an (uninstantiated) generic
192 // type. If cause is non-nil and the type expression was a valid type but not
193 // generic, cause will be populated with a message describing the error.
194 func (check *Checker) genericType(e ast.Expr, cause *string) Type {
195 typ := check.typInternal(e, nil)
197 if typ != Typ[Invalid] && !isGeneric(typ) {
199 *cause = check.sprintf("%s is not a generic type", typ)
203 // TODO(gri) what is the correct call below?
204 check.recordTypeAndValue(e, typexpr, typ, nil)
208 // goTypeName returns the Go type name for typ and
209 // removes any occurrences of "types." from that name.
210 func goTypeName(typ Type) string {
211 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
214 // typInternal drives type checking of types.
215 // Must only be called by definedType or genericType.
216 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
217 if check.conf._Trace {
218 check.trace(e0.Pos(), "-- type %s", e0)
224 // Calling under() here may lead to endless instantiations.
225 // Test case: type T[P any] *T[P]
226 under = safeUnderlying(T)
229 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
231 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
236 switch e := e0.(type) {
238 // ignore - error reported before
242 check.ident(&x, e, def, true)
247 def.setUnderlying(typ)
250 // ignore - error reported before
252 check.errorf(&x, NotAType, "%s used as type", &x)
254 check.errorf(&x, NotAType, "%s is not a type", &x)
257 case *ast.SelectorExpr:
259 check.selector(&x, e, def, true)
264 def.setUnderlying(typ)
267 // ignore - error reported before
269 check.errorf(&x, NotAType, "%s used as type", &x)
271 check.errorf(&x, NotAType, "%s is not a type", &x)
274 case *ast.IndexExpr, *ast.IndexListExpr:
275 ix := typeparams.UnpackIndexExpr(e)
276 if !check.allowVersion(check.pkg, e.Pos(), 1, 18) {
277 check.softErrorf(inNode(e, ix.Lbrack), UnsupportedFeature, "type instantiation requires go1.18 or later")
279 return check.instantiatedType(ix, def)
282 // Generic types must be instantiated before they can be used in any form.
283 // Consequently, generic types cannot be parenthesized.
284 return check.definedType(e.X, def)
289 def.setUnderlying(typ)
290 typ.elem = check.varType(e.Elt)
295 def.setUnderlying(typ)
296 // Provide a more specific error when encountering a [...] array
297 // rather than leaving it to the handling of the ... expression.
298 if _, ok := e.Len.(*ast.Ellipsis); ok {
299 check.error(e.Len, BadDotDotDotSyntax, "invalid use of [...] array (outside a composite literal)")
302 typ.len = check.arrayLength(e.Len)
304 typ.elem = check.varType(e.Elt)
308 // report error if we encountered [...]
311 // dots are handled explicitly where they are legal
312 // (array composite literals and parameter lists)
313 check.error(e, InvalidDotDotDot, "invalid use of '...'")
316 case *ast.StructType:
318 def.setUnderlying(typ)
319 check.structType(typ, e)
324 typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
325 def.setUnderlying(typ)
326 typ.base = check.varType(e.X)
330 typ := new(Signature)
331 def.setUnderlying(typ)
332 check.funcType(typ, nil, e)
335 case *ast.InterfaceType:
336 typ := check.newInterface()
337 def.setUnderlying(typ)
338 check.interfaceType(typ, e, def)
343 def.setUnderlying(typ)
345 typ.key = check.varType(e.Key)
346 typ.elem = check.varType(e.Value)
348 // spec: "The comparison operators == and != must be fully defined
349 // for operands of the key type; thus the key type must not be a
350 // function, map, or slice."
352 // Delay this check because it requires fully setup types;
353 // it is safe to continue in any case (was go.dev/issue/6667).
355 if !Comparable(typ.key) {
357 if isTypeParam(typ.key) {
358 why = " (missing comparable constraint)"
360 check.errorf(e.Key, IncomparableMapKey, "invalid map key type %s%s", typ.key, why)
362 }).describef(e.Key, "check map key %s", typ.key)
368 def.setUnderlying(typ)
372 case ast.SEND | ast.RECV:
379 check.errorf(e, InvalidSyntaxTree, "unknown channel direction %d", e.Dir)
384 typ.elem = check.varType(e.Value)
388 check.errorf(e0, NotAType, "%s is not a type", e0)
393 def.setUnderlying(typ)
397 func (check *Checker) instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type) {
398 if check.conf._Trace {
399 check.trace(ix.Pos(), "-- instantiating type %s with %s", ix.X, ix.Indices)
403 // Don't format the underlying here. It will always be nil.
404 check.trace(ix.Pos(), "=> %s", res)
409 gtyp := check.genericType(ix.X, &cause)
411 check.errorf(ix.Orig, NotAGenericType, invalidOp+"%s (%s)", ix.Orig, cause)
413 if gtyp == Typ[Invalid] {
414 return gtyp // error already reported
417 orig, _ := gtyp.(*Named)
419 panic(fmt.Sprintf("%v: cannot instantiate %v", ix.Pos(), gtyp))
422 // evaluate arguments
423 targs := check.typeList(ix.Indices)
425 def.setUnderlying(Typ[Invalid]) // avoid errors later due to lazy instantiation
429 // create the instance
430 inst := check.instance(ix.Pos(), orig, targs, nil, check.context()).(*Named)
431 def.setUnderlying(inst)
433 // orig.tparams may not be set up, so we need to do expansion later.
435 // This is an instance from the source, not from recursive substitution,
436 // and so it must be resolved during type-checking so that we can report
438 check.recordInstance(ix.Orig, inst.TypeArgs().list(), inst)
440 if check.validateTArgLen(ix.Pos(), inst.TypeParams().Len(), inst.TypeArgs().Len()) {
441 if i, err := check.verify(ix.Pos(), inst.TypeParams().list(), inst.TypeArgs().list(), check.context()); err != nil {
442 // best position for error reporting
444 if i < len(ix.Indices) {
445 pos = ix.Indices[i].Pos()
447 check.softErrorf(atPos(pos), InvalidTypeArg, err.Error())
449 check.mono.recordInstance(check.pkg, ix.Pos(), inst.TypeParams().list(), inst.TypeArgs().list(), ix.Indices)
453 // TODO(rfindley): remove this call: we don't need to call validType here,
454 // as cycles can only occur for types used inside a Named type declaration,
455 // and so it suffices to call validType from declared types.
456 check.validType(inst)
457 }).describef(ix, "resolve instance %s", inst)
462 // arrayLength type-checks the array length expression e
463 // and returns the constant length >= 0, or a value < 0
464 // to indicate an error (and thus an unknown length).
465 func (check *Checker) arrayLength(e ast.Expr) int64 {
466 // If e is an identifier, the array declaration might be an
467 // attempt at a parameterized type declaration with missing
468 // constraint. Provide an error message that mentions array
470 if name, _ := e.(*ast.Ident); name != nil {
471 obj := check.lookup(name.Name)
473 check.errorf(name, InvalidArrayLen, "undefined array length %s or missing type constraint", name.Name)
476 if _, ok := obj.(*Const); !ok {
477 check.errorf(name, InvalidArrayLen, "invalid array length %s", name.Name)
483 check.expr(nil, &x, e)
484 if x.mode != constant_ {
485 if x.mode != invalid {
486 check.errorf(&x, InvalidArrayLen, "array length %s must be constant", &x)
491 if isUntyped(x.typ) || isInteger(x.typ) {
492 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
493 if representableConst(val, check, Typ[Int], nil) {
494 if n, ok := constant.Int64Val(val); ok && n >= 0 {
502 if isInteger(x.typ) {
503 msg = "invalid array length %s"
505 msg = "array length %s must be integer"
507 check.errorf(&x, InvalidArrayLen, msg, &x)
511 // typeList provides the list of types corresponding to the incoming expression list.
512 // If an error occurred, the result is nil, but all list elements were type-checked.
513 func (check *Checker) typeList(list []ast.Expr) []Type {
514 res := make([]Type, len(list)) // res != nil even if len(list) == 0
515 for i, x := range list {
516 t := check.varType(x)
517 if t == Typ[Invalid] {