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 check.error(e, _InvalidBlank, "cannot use _ as value or type")
35 check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
38 case universeAny, universeComparable:
39 // complain if necessary but keep going
40 if !check.allowVersion(check.pkg, 1, 18) {
41 check.softErrorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
42 } else if obj == universeAny {
43 // If we allow "any" for general use, this if-statement can be removed (issue #33232).
44 check.softErrorf(e, _Todo, "cannot use any outside constraint position")
47 check.recordUse(e, obj)
49 // Type-check the object.
50 // Only call Checker.objDecl if the object doesn't have a type yet
51 // (in which case we must actually determine it) or the object is a
52 // TypeName and we also want a type (in which case we might detect
53 // a cycle which needs to be reported). Otherwise we can skip the
54 // call and avoid a possible cycle error in favor of the more
55 // informative "not a type/value" error that this function's caller
56 // will issue (see issue #25790).
58 if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
59 check.objDecl(obj, def)
60 typ = obj.Type() // type must have been assigned by Checker.objDecl
64 // The object may have been dot-imported.
65 // If so, mark the respective package as used.
66 // (This code is only needed for dot-imports. Without them,
67 // we only have to mark variables, see *Var case below).
68 if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
72 switch obj := obj.(type) {
74 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
79 if typ == Typ[Invalid] {
82 if obj == universeIota {
83 if check.iota == nil {
84 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
98 // It's ok to mark non-local variables, but ignore variables
99 // from other packages to avoid potential race conditions with
100 // dot-imported variables.
101 if obj.pkg == check.pkg {
104 check.addDeclDep(obj)
105 if typ == Typ[Invalid] {
111 check.addDeclDep(obj)
128 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
129 // The type must not be an (uninstantiated) generic type.
130 func (check *Checker) typ(e ast.Expr) Type {
131 return check.definedType(e, nil)
134 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
135 // The type must not be an (uninstantiated) generic type and it must be ordinary
136 // (see ordinaryType).
137 func (check *Checker) varType(e ast.Expr) Type {
138 typ := check.definedType(e, nil)
139 check.ordinaryType(e, typ)
143 // ordinaryType reports an error if typ is an interface type containing
144 // type lists or is (or embeds) the predeclared type comparable.
145 func (check *Checker) ordinaryType(pos positioner, typ Type) {
146 // We don't want to call under() (via asInterface) or complete interfaces while we
147 // are in the middle of type-checking parameter declarations that might belong to
148 // interface methods. Delay this check to the end of type-checking.
150 if t := asInterface(typ); t != nil {
151 tset := computeInterfaceTypeSet(check, pos.Pos(), t) // TODO(gri) is this the correct position?
152 if tset.IsConstraint() {
154 check.softErrorf(pos, _Todo, "interface is (or embeds) comparable")
156 check.softErrorf(pos, _Todo, "interface contains type constraints")
163 // anyType type-checks the type expression e and returns its type, or Typ[Invalid].
164 // The type may be generic or instantiated.
165 func (check *Checker) anyType(e ast.Expr) Type {
166 typ := check.typInternal(e, nil)
168 check.recordTypeAndValue(e, typexpr, typ, nil)
172 // definedType is like typ but also accepts a type name def.
173 // If def != nil, e is the type specification for the defined type def, declared
174 // in a type declaration, and def.underlying will be set to the type of e before
175 // any components of e are type-checked.
177 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
178 typ := check.typInternal(e, def)
181 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
184 check.recordTypeAndValue(e, typexpr, typ, nil)
188 // genericType is like typ but the type must be an (uninstantiated) generic type.
189 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
190 typ := check.typInternal(e, nil)
192 if typ != Typ[Invalid] && !isGeneric(typ) {
194 check.errorf(e, _Todo, "%s is not a generic type", typ)
198 // TODO(gri) what is the correct call below?
199 check.recordTypeAndValue(e, typexpr, typ, nil)
203 // goTypeName returns the Go type name for typ and
204 // removes any occurrences of "types." from that name.
205 func goTypeName(typ Type) string {
206 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
209 // typInternal drives type checking of types.
210 // Must only be called by definedType or genericType.
212 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
214 check.trace(e0.Pos(), "type %s", e0)
220 // Calling under() here may lead to endless instantiations.
221 // Test case: type T[P any] *T[P]
222 // TODO(gri) investigate if that's a bug or to be expected
223 // (see also analogous comment in Checker.instantiate).
224 under = safeUnderlying(T)
227 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
229 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
234 switch e := e0.(type) {
236 // ignore - error reported before
240 check.ident(&x, e, def, true)
245 def.setUnderlying(typ)
248 // ignore - error reported before
250 check.errorf(&x, _NotAType, "%s used as type", &x)
252 check.errorf(&x, _NotAType, "%s is not a type", &x)
255 case *ast.SelectorExpr:
257 check.selector(&x, e)
262 def.setUnderlying(typ)
265 // ignore - error reported before
267 check.errorf(&x, _NotAType, "%s used as type", &x)
269 check.errorf(&x, _NotAType, "%s is not a type", &x)
272 case *ast.IndexExpr, *ast.MultiIndexExpr:
273 ix := typeparams.UnpackIndexExpr(e)
274 if !check.allowVersion(check.pkg, 1, 18) {
275 check.softErrorf(inNode(e, ix.Lbrack), _Todo, "type instantiation requires go1.18 or later")
277 // TODO(rfindley): type instantiation should require go1.18
278 return check.instantiatedType(ix.X, ix.Indices, 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.len = check.arrayLength(e.Len)
290 typ.elem = check.varType(e.Elt)
295 def.setUnderlying(typ)
296 typ.elem = check.varType(e.Elt)
300 // dots are handled explicitly where they are legal
301 // (array composite literals and parameter lists)
302 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
305 case *ast.StructType:
307 def.setUnderlying(typ)
308 check.structType(typ, e)
313 def.setUnderlying(typ)
314 typ.base = check.varType(e.X)
318 typ := new(Signature)
319 def.setUnderlying(typ)
320 check.funcType(typ, nil, e)
323 case *ast.InterfaceType:
324 typ := new(Interface)
325 def.setUnderlying(typ)
329 check.interfaceType(typ, e, def)
334 def.setUnderlying(typ)
336 typ.key = check.varType(e.Key)
337 typ.elem = check.varType(e.Value)
339 // spec: "The comparison operators == and != must be fully defined
340 // for operands of the key type; thus the key type must not be a
341 // function, map, or slice."
343 // Delay this check because it requires fully setup types;
344 // it is safe to continue in any case (was issue 6667).
346 if !Comparable(typ.key) {
348 if asTypeParam(typ.key) != nil {
349 why = " (missing comparable constraint)"
351 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
359 def.setUnderlying(typ)
363 case ast.SEND | ast.RECV:
370 check.invalidAST(e, "unknown channel direction %d", e.Dir)
375 typ.elem = check.varType(e.Value)
379 check.errorf(e0, _NotAType, "%s is not a type", e0)
383 def.setUnderlying(typ)
387 func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) Type {
388 gtyp := check.genericType(x, true)
389 if gtyp == Typ[Invalid] {
390 return gtyp // error already reported
392 base, _ := gtyp.(*Named)
394 panic(fmt.Sprintf("%v: cannot instantiate %v", x.Pos(), gtyp))
397 // evaluate arguments
398 targs := check.typeList(targsx)
400 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
404 // determine argument positions
405 posList := make([]token.Pos, len(targs))
406 for i, arg := range targsx {
407 posList[i] = arg.Pos()
410 typ := check.instantiate(x.Pos(), base, targs, posList)
411 def.setUnderlying(typ)
413 // make sure we check instantiation works at least once
414 // and that the resulting type is valid
416 check.validType(typ, nil)
422 // arrayLength type-checks the array length expression e
423 // and returns the constant length >= 0, or a value < 0
424 // to indicate an error (and thus an unknown length).
425 func (check *Checker) arrayLength(e ast.Expr) int64 {
428 if x.mode != constant_ {
429 if x.mode != invalid {
430 check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
434 if isUntyped(x.typ) || isInteger(x.typ) {
435 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
436 if representableConst(val, check, Typ[Int], nil) {
437 if n, ok := constant.Int64Val(val); ok && n >= 0 {
440 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
445 check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
449 // typeList provides the list of types corresponding to the incoming expression list.
450 // If an error occurred, the result is nil, but all list elements were type-checked.
451 func (check *Checker) typeList(list []ast.Expr) []Type {
452 res := make([]Type, len(list)) // res != nil even if len(list) == 0
453 for i, x := range list {
454 t := check.varType(x)
455 if t == Typ[Invalid] {