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 if !check.allowVersion(check.pkg, 1, 18) {
40 check.errorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
41 return // avoid follow-on errors
44 check.recordUse(e, obj)
46 // Type-check the object.
47 // Only call Checker.objDecl if the object doesn't have a type yet
48 // (in which case we must actually determine it) or the object is a
49 // TypeName and we also want a type (in which case we might detect
50 // a cycle which needs to be reported). Otherwise we can skip the
51 // call and avoid a possible cycle error in favor of the more
52 // informative "not a type/value" error that this function's caller
53 // will issue (see issue #25790).
55 if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
56 check.objDecl(obj, def)
57 typ = obj.Type() // type must have been assigned by Checker.objDecl
61 // The object may have been dot-imported.
62 // If so, mark the respective package as used.
63 // (This code is only needed for dot-imports. Without them,
64 // we only have to mark variables, see *Var case below).
65 if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
69 switch obj := obj.(type) {
71 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
76 if typ == Typ[Invalid] {
79 if obj == universeIota {
80 if check.iota == nil {
81 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
95 // It's ok to mark non-local variables, but ignore variables
96 // from other packages to avoid potential race conditions with
97 // dot-imported variables.
98 if obj.pkg == check.pkg {
101 check.addDeclDep(obj)
102 if typ == Typ[Invalid] {
108 check.addDeclDep(obj)
125 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
126 // The type must not be an (uninstantiated) generic type.
127 func (check *Checker) typ(e ast.Expr) Type {
128 return check.definedType(e, nil)
131 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
132 // The type must not be an (uninstantiated) generic type and it must not be a
133 // constraint interface.
134 func (check *Checker) varType(e ast.Expr) Type {
135 typ := check.definedType(e, nil)
136 // We don't want to call under() (via asInterface) or complete interfaces while we
137 // are in the middle of type-checking parameter declarations that might belong to
138 // interface methods. Delay this check to the end of type-checking.
140 if t := asInterface(typ); t != nil {
141 tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
142 if tset.IsConstraint() {
144 check.softErrorf(e, _Todo, "interface is (or embeds) comparable")
146 check.softErrorf(e, _Todo, "interface contains type constraints")
155 // definedType is like typ but also accepts a type name def.
156 // If def != nil, e is the type specification for the defined type def, declared
157 // in a type declaration, and def.underlying will be set to the type of e before
158 // any components of e are type-checked.
160 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
161 typ := check.typInternal(e, def)
164 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
167 check.recordTypeAndValue(e, typexpr, typ, nil)
171 // genericType is like typ but the type must be an (uninstantiated) generic type.
172 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
173 typ := check.typInternal(e, nil)
175 if typ != Typ[Invalid] && !isGeneric(typ) {
177 check.errorf(e, _Todo, "%s is not a generic type", typ)
181 // TODO(gri) what is the correct call below?
182 check.recordTypeAndValue(e, typexpr, typ, nil)
186 // goTypeName returns the Go type name for typ and
187 // removes any occurrences of "types." from that name.
188 func goTypeName(typ Type) string {
189 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
192 // typInternal drives type checking of types.
193 // Must only be called by definedType or genericType.
195 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
197 check.trace(e0.Pos(), "type %s", e0)
203 // Calling under() here may lead to endless instantiations.
204 // Test case: type T[P any] *T[P]
205 // TODO(gri) investigate if that's a bug or to be expected
206 // (see also analogous comment in Checker.instantiate).
207 under = safeUnderlying(T)
210 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
212 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
217 switch e := e0.(type) {
219 // ignore - error reported before
223 check.ident(&x, e, def, true)
228 def.setUnderlying(typ)
231 // ignore - error reported before
233 check.errorf(&x, _NotAType, "%s used as type", &x)
235 check.errorf(&x, _NotAType, "%s is not a type", &x)
238 case *ast.SelectorExpr:
240 check.selector(&x, e)
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.IndexExpr, *ast.IndexListExpr:
256 ix := typeparams.UnpackIndexExpr(e)
257 if !check.allowVersion(check.pkg, 1, 18) {
258 check.softErrorf(inNode(e, ix.Lbrack), _Todo, "type instantiation requires go1.18 or later")
260 // TODO(rfindley): type instantiation should require go1.18
261 return check.instantiatedType(ix.X, ix.Indices, def)
264 // Generic types must be instantiated before they can be used in any form.
265 // Consequently, generic types cannot be parenthesized.
266 return check.definedType(e.X, def)
271 def.setUnderlying(typ)
272 typ.len = check.arrayLength(e.Len)
273 typ.elem = check.varType(e.Elt)
278 def.setUnderlying(typ)
279 typ.elem = check.varType(e.Elt)
283 // dots are handled explicitly where they are legal
284 // (array composite literals and parameter lists)
285 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
288 case *ast.StructType:
290 def.setUnderlying(typ)
291 check.structType(typ, e)
296 def.setUnderlying(typ)
297 typ.base = check.varType(e.X)
301 typ := new(Signature)
302 def.setUnderlying(typ)
303 check.funcType(typ, nil, e)
306 case *ast.InterfaceType:
307 typ := new(Interface)
308 def.setUnderlying(typ)
312 check.interfaceType(typ, e, def)
317 def.setUnderlying(typ)
319 typ.key = check.varType(e.Key)
320 typ.elem = check.varType(e.Value)
322 // spec: "The comparison operators == and != must be fully defined
323 // for operands of the key type; thus the key type must not be a
324 // function, map, or slice."
326 // Delay this check because it requires fully setup types;
327 // it is safe to continue in any case (was issue 6667).
329 if !Comparable(typ.key) {
331 if asTypeParam(typ.key) != nil {
332 why = " (missing comparable constraint)"
334 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
342 def.setUnderlying(typ)
346 case ast.SEND | ast.RECV:
353 check.invalidAST(e, "unknown channel direction %d", e.Dir)
358 typ.elem = check.varType(e.Value)
362 check.errorf(e0, _NotAType, "%s is not a type", e0)
366 def.setUnderlying(typ)
370 func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) Type {
371 gtyp := check.genericType(x, true)
372 if gtyp == Typ[Invalid] {
373 return gtyp // error already reported
375 base, _ := gtyp.(*Named)
377 panic(fmt.Sprintf("%v: cannot instantiate %v", x.Pos(), gtyp))
380 // evaluate arguments
381 targs := check.typeList(targsx)
383 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
387 // determine argument positions
388 posList := make([]token.Pos, len(targs))
389 for i, arg := range targsx {
390 posList[i] = arg.Pos()
393 typ := check.instantiate(x.Pos(), base, targs, posList)
394 def.setUnderlying(typ)
395 check.recordInstance(x, targs, typ)
397 // make sure we check instantiation works at least once
398 // and that the resulting type is valid
400 check.validType(typ, nil)
406 // arrayLength type-checks the array length expression e
407 // and returns the constant length >= 0, or a value < 0
408 // to indicate an error (and thus an unknown length).
409 func (check *Checker) arrayLength(e ast.Expr) int64 {
410 // If e is an undeclared identifier, the array declaration might be an
411 // attempt at a parameterized type declaration with missing constraint.
412 // Provide a better error message than just "undeclared name: X".
413 if name, _ := e.(*ast.Ident); name != nil && check.lookup(name.Name) == nil {
414 check.errorf(name, _InvalidArrayLen, "undeclared name %s for array length", name.Name)
420 if x.mode != constant_ {
421 if x.mode != invalid {
422 check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
427 if isUntyped(x.typ) || isInteger(x.typ) {
428 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
429 if representableConst(val, check, Typ[Int], nil) {
430 if n, ok := constant.Int64Val(val); ok && n >= 0 {
433 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
439 check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
443 // typeList provides the list of types corresponding to the incoming expression list.
444 // If an error occurred, the result is nil, but all list elements were type-checked.
445 func (check *Checker) typeList(list []ast.Expr) []Type {
446 res := make([]Type, len(list)) // res != nil even if len(list) == 0
447 for i, x := range list {
448 t := check.varType(x)
449 if t == Typ[Invalid] {