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"
17 // ident type-checks identifier e and initializes x with the value or type of e.
18 // If an error occurred, x.mode is set to invalid.
19 // For the meaning of def, see Checker.definedType, below.
20 // If wantType is set, the identifier e is expected to denote a type.
21 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
25 // Note that we cannot use check.lookup here because the returned scope
26 // may be different from obj.Parent(). See also Scope.LookupParent doc.
27 scope, obj := check.scope.LookupParent(e.Name, check.pos)
31 // Blank identifiers are never declared, but the current identifier may
32 // be a placeholder for a receiver type parameter. In this case we can
33 // resolve its type and object from Checker.recvTParamMap.
34 if tpar := check.recvTParamMap[e]; tpar != nil {
38 check.error(e, _InvalidBlank, "cannot use _ as value or type")
41 check.errorf(e, _UndeclaredName, "undefined: %s", e.Name)
44 case universeAny, universeComparable:
45 if !check.allowVersion(check.pkg, 1, 18) {
46 check.versionErrorf(e, "go1.18", "predeclared %s", e.Name)
47 return // avoid follow-on errors
50 check.recordUse(e, obj)
52 // Type-check the object.
53 // Only call Checker.objDecl if the object doesn't have a type yet
54 // (in which case we must actually determine it) or the object is a
55 // TypeName and we also want a type (in which case we might detect
56 // a cycle which needs to be reported). Otherwise we can skip the
57 // call and avoid a possible cycle error in favor of the more
58 // informative "not a type/value" error that this function's caller
59 // will issue (see issue #25790).
61 if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
62 check.objDecl(obj, def)
63 typ = obj.Type() // type must have been assigned by Checker.objDecl
67 // The object may have been dot-imported.
68 // If so, mark the respective package as used.
69 // (This code is only needed for dot-imports. Without them,
70 // we only have to mark variables, see *Var case below).
71 if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
75 switch obj := obj.(type) {
77 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
82 if typ == Typ[Invalid] {
85 if obj == universeIota {
86 if check.iota == nil {
87 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
98 if check.isBrokenAlias(obj) {
99 check.errorf(e, _InvalidDeclCycle, "invalid use of type alias %s in recursive type (see issue #50729)", obj.name)
105 // It's ok to mark non-local variables, but ignore variables
106 // from other packages to avoid potential race conditions with
107 // dot-imported variables.
108 if obj.pkg == check.pkg {
111 check.addDeclDep(obj)
112 if typ == Typ[Invalid] {
118 check.addDeclDep(obj)
135 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
136 // The type must not be an (uninstantiated) generic type.
137 func (check *Checker) typ(e ast.Expr) Type {
138 return check.definedType(e, nil)
141 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
142 // The type must not be an (uninstantiated) generic type and it must not be a
143 // constraint interface.
144 func (check *Checker) varType(e ast.Expr) Type {
145 typ := check.definedType(e, nil)
146 check.validVarType(e, typ)
150 // validVarType reports an error if typ is a constraint interface.
151 // The expression e is used for error reporting, if any.
152 func (check *Checker) validVarType(e ast.Expr, typ Type) {
153 // If we have a type parameter there's nothing to do.
154 if isTypeParam(typ) {
158 // We don't want to call under() or complete interfaces while we are in
159 // the middle of type-checking parameter declarations that might belong
160 // to interface methods. Delay this check to the end of type-checking.
162 if t, _ := under(typ).(*Interface); t != nil {
163 tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
164 if !tset.IsMethodSet() {
166 check.softErrorf(e, _MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface is (or embeds) comparable", typ)
168 check.softErrorf(e, _MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface contains type constraints", typ)
172 }).describef(e, "check var type %s", typ)
175 // definedType is like typ but also accepts a type name def.
176 // If def != nil, e is the type specification for the defined type def, declared
177 // in a type declaration, and def.underlying will be set to the type of e before
178 // any components of e are type-checked.
179 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
180 typ := check.typInternal(e, def)
183 check.errorf(e, _WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
186 check.recordTypeAndValue(e, typexpr, typ, nil)
190 // genericType is like typ but the type must be an (uninstantiated) generic
191 // type. If cause is non-nil and the type expression was a valid type but not
192 // generic, cause will be populated with a message describing the error.
193 func (check *Checker) genericType(e ast.Expr, cause *string) Type {
194 typ := check.typInternal(e, nil)
196 if typ != Typ[Invalid] && !isGeneric(typ) {
198 *cause = check.sprintf("%s is not a generic type", typ)
202 // TODO(gri) what is the correct call below?
203 check.recordTypeAndValue(e, typexpr, typ, nil)
207 // goTypeName returns the Go type name for typ and
208 // removes any occurrences of "types." from that name.
209 func goTypeName(typ Type) string {
210 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
213 // typInternal drives type checking of types.
214 // Must only be called by definedType or genericType.
215 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
217 check.trace(e0.Pos(), "-- type %s", e0)
223 // Calling under() here may lead to endless instantiations.
224 // Test case: type T[P any] *T[P]
225 under = safeUnderlying(T)
228 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
230 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
235 switch e := e0.(type) {
237 // ignore - error reported before
241 check.ident(&x, e, def, true)
246 def.setUnderlying(typ)
249 // ignore - error reported before
251 check.errorf(&x, _NotAType, "%s used as type", &x)
253 check.errorf(&x, _NotAType, "%s is not a type", &x)
256 case *ast.SelectorExpr:
258 check.selector(&x, e, def)
263 def.setUnderlying(typ)
266 // ignore - error reported before
268 check.errorf(&x, _NotAType, "%s used as type", &x)
270 check.errorf(&x, _NotAType, "%s is not a type", &x)
273 case *ast.IndexExpr, *ast.IndexListExpr:
274 ix := typeparams.UnpackIndexExpr(e)
275 if !check.allowVersion(check.pkg, 1, 18) {
276 check.softErrorf(inNode(e, ix.Lbrack), _UnsupportedFeature, "type instantiation requires go1.18 or later")
278 return check.instantiatedType(ix, def)
281 // Generic types must be instantiated before they can be used in any form.
282 // Consequently, generic types cannot be parenthesized.
283 return check.definedType(e.X, def)
288 def.setUnderlying(typ)
289 typ.elem = check.varType(e.Elt)
294 def.setUnderlying(typ)
295 // Provide a more specific error when encountering a [...] array
296 // rather than leaving it to the handling of the ... expression.
297 if _, ok := e.Len.(*ast.Ellipsis); ok {
298 check.error(e.Len, _BadDotDotDotSyntax, "invalid use of [...] array (outside a composite literal)")
301 typ.len = check.arrayLength(e.Len)
303 typ.elem = check.varType(e.Elt)
307 // report error if we encountered [...]
310 // dots are handled explicitly where they are legal
311 // (array composite literals and parameter lists)
312 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
315 case *ast.StructType:
317 def.setUnderlying(typ)
318 check.structType(typ, e)
323 typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
324 def.setUnderlying(typ)
325 typ.base = check.varType(e.X)
329 typ := new(Signature)
330 def.setUnderlying(typ)
331 check.funcType(typ, nil, e)
334 case *ast.InterfaceType:
335 typ := check.newInterface()
336 def.setUnderlying(typ)
337 check.interfaceType(typ, e, def)
342 def.setUnderlying(typ)
344 typ.key = check.varType(e.Key)
345 typ.elem = check.varType(e.Value)
347 // spec: "The comparison operators == and != must be fully defined
348 // for operands of the key type; thus the key type must not be a
349 // function, map, or slice."
351 // Delay this check because it requires fully setup types;
352 // it is safe to continue in any case (was issue 6667).
354 if !Comparable(typ.key) {
356 if isTypeParam(typ.key) {
357 why = " (missing comparable constraint)"
359 check.errorf(e.Key, _IncomparableMapKey, "invalid map key type %s%s", typ.key, why)
361 }).describef(e.Key, "check map key %s", typ.key)
367 def.setUnderlying(typ)
371 case ast.SEND | ast.RECV:
378 check.invalidAST(e, "unknown channel direction %d", e.Dir)
383 typ.elem = check.varType(e.Value)
387 check.errorf(e0, _NotAType, "%s is not a type", e0)
392 def.setUnderlying(typ)
396 func (check *Checker) instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type) {
398 check.trace(ix.Pos(), "-- instantiating type %s with %s", ix.X, ix.Indices)
402 // Don't format the underlying here. It will always be nil.
403 check.trace(ix.Pos(), "=> %s", res)
408 gtyp := check.genericType(ix.X, &cause)
410 check.invalidOp(ix.Orig, _NotAGenericType, "%s (%s)", ix.Orig, cause)
412 if gtyp == Typ[Invalid] {
413 return gtyp // error already reported
416 orig, _ := gtyp.(*Named)
418 panic(fmt.Sprintf("%v: cannot instantiate %v", ix.Pos(), gtyp))
421 // evaluate arguments
422 targs := check.typeList(ix.Indices)
424 def.setUnderlying(Typ[Invalid]) // avoid errors later due to lazy instantiation
428 // create the instance
429 inst := check.instance(ix.Pos(), orig, targs, nil, check.context()).(*Named)
430 def.setUnderlying(inst)
432 // orig.tparams may not be set up, so we need to do expansion later.
434 // This is an instance from the source, not from recursive substitution,
435 // and so it must be resolved during type-checking so that we can report
437 check.recordInstance(ix.Orig, inst.TypeArgs().list(), inst)
439 if check.validateTArgLen(ix.Pos(), inst.TypeParams().Len(), inst.TypeArgs().Len()) {
440 if i, err := check.verify(ix.Pos(), inst.TypeParams().list(), inst.TypeArgs().list(), check.context()); err != nil {
441 // best position for error reporting
443 if i < len(ix.Indices) {
444 pos = ix.Indices[i].Pos()
446 check.softErrorf(atPos(pos), _InvalidTypeArg, err.Error())
448 check.mono.recordInstance(check.pkg, ix.Pos(), inst.TypeParams().list(), inst.TypeArgs().list(), ix.Indices)
452 // TODO(rfindley): remove this call: we don't need to call validType here,
453 // as cycles can only occur for types used inside a Named type declaration,
454 // and so it suffices to call validType from declared types.
455 check.validType(inst)
456 }).describef(ix, "resolve instance %s", inst)
461 // arrayLength type-checks the array length expression e
462 // and returns the constant length >= 0, or a value < 0
463 // to indicate an error (and thus an unknown length).
464 func (check *Checker) arrayLength(e ast.Expr) int64 {
465 // If e is an identifier, the array declaration might be an
466 // attempt at a parameterized type declaration with missing
467 // constraint. Provide an error message that mentions array
469 if name, _ := e.(*ast.Ident); name != nil {
470 obj := check.lookup(name.Name)
472 check.errorf(name, _InvalidArrayLen, "undefined %s for array length", name.Name)
475 if _, ok := obj.(*Const); !ok {
476 check.errorf(name, _InvalidArrayLen, "invalid array length %s", name.Name)
483 if x.mode != constant_ {
484 if x.mode != invalid {
485 check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
490 if isUntyped(x.typ) || isInteger(x.typ) {
491 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
492 if representableConst(val, check, Typ[Int], nil) {
493 if n, ok := constant.Int64Val(val); ok && n >= 0 {
496 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
502 check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
506 // typeList provides the list of types corresponding to the incoming expression list.
507 // If an error occurred, the result is nil, but all list elements were type-checked.
508 func (check *Checker) typeList(list []ast.Expr) []Type {
509 res := make([]Type, len(list)) // res != nil even if len(list) == 0
510 for i, x := range list {
511 t := check.varType(x)
512 if t == Typ[Invalid] {