]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
go/types, types2: types in type switch cases must be instantiated
[gostls13.git] / src / go / types / typexpr.go
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.
4
5 // This file implements type-checking of identifiers and type expressions.
6
7 package types
8
9 import (
10         "fmt"
11         "go/ast"
12         "go/constant"
13         "go/internal/typeparams"
14         "go/token"
15         "strings"
16 )
17
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 //
23 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
24         x.mode = invalid
25         x.expr = e
26
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)
30         switch obj {
31         case nil:
32                 if e.Name == "_" {
33                         check.error(e, _InvalidBlank, "cannot use _ as value or type")
34                 } else {
35                         check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
36                 }
37                 return
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
42                 }
43                 // If we allow "any" for general use, this if-statement can be removed (issue #33232).
44                 if obj == universeAny {
45                         check.error(e, _Todo, "cannot use any outside constraint position")
46                         return
47                 }
48         }
49         check.recordUse(e, obj)
50
51         // Type-check the object.
52         // Only call Checker.objDecl if the object doesn't have a type yet
53         // (in which case we must actually determine it) or the object is a
54         // TypeName and we also want a type (in which case we might detect
55         // a cycle which needs to be reported). Otherwise we can skip the
56         // call and avoid a possible cycle error in favor of the more
57         // informative "not a type/value" error that this function's caller
58         // will issue (see issue #25790).
59         typ := obj.Type()
60         if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
61                 check.objDecl(obj, def)
62                 typ = obj.Type() // type must have been assigned by Checker.objDecl
63         }
64         assert(typ != nil)
65
66         // The object may have been dot-imported.
67         // If so, mark the respective package as used.
68         // (This code is only needed for dot-imports. Without them,
69         // we only have to mark variables, see *Var case below).
70         if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
71                 pkgName.used = true
72         }
73
74         switch obj := obj.(type) {
75         case *PkgName:
76                 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
77                 return
78
79         case *Const:
80                 check.addDeclDep(obj)
81                 if typ == Typ[Invalid] {
82                         return
83                 }
84                 if obj == universeIota {
85                         if check.iota == nil {
86                                 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
87                                 return
88                         }
89                         x.val = check.iota
90                 } else {
91                         x.val = obj.val
92                 }
93                 assert(x.val != nil)
94                 x.mode = constant_
95
96         case *TypeName:
97                 x.mode = typexpr
98
99         case *Var:
100                 // It's ok to mark non-local variables, but ignore variables
101                 // from other packages to avoid potential race conditions with
102                 // dot-imported variables.
103                 if obj.pkg == check.pkg {
104                         obj.used = true
105                 }
106                 check.addDeclDep(obj)
107                 if typ == Typ[Invalid] {
108                         return
109                 }
110                 x.mode = variable
111
112         case *Func:
113                 check.addDeclDep(obj)
114                 x.mode = value
115
116         case *Builtin:
117                 x.id = obj.id
118                 x.mode = builtin
119
120         case *Nil:
121                 x.mode = value
122
123         default:
124                 unreachable()
125         }
126
127         x.typ = typ
128 }
129
130 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
131 // The type must not be an (uninstantiated) generic type.
132 func (check *Checker) typ(e ast.Expr) Type {
133         return check.definedType(e, nil)
134 }
135
136 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
137 // The type must not be an (uninstantiated) generic type and it must be ordinary
138 // (see ordinaryType).
139 func (check *Checker) varType(e ast.Expr) Type {
140         typ := check.definedType(e, nil)
141         check.ordinaryType(e, typ)
142         return typ
143 }
144
145 // ordinaryType reports an error if typ is an interface type containing
146 // type lists or is (or embeds) the predeclared type comparable.
147 func (check *Checker) ordinaryType(pos positioner, typ Type) {
148         // We don't want to call under() (via asInterface) or complete interfaces while we
149         // are in the middle of type-checking parameter declarations that might belong to
150         // interface methods. Delay this check to the end of type-checking.
151         check.later(func() {
152                 if t := asInterface(typ); t != nil {
153                         tset := computeInterfaceTypeSet(check, pos.Pos(), t) // TODO(gri) is this the correct position?
154                         if !tset.IsMethodSet() {
155                                 if tset.comparable {
156                                         check.softErrorf(pos, _Todo, "interface is (or embeds) comparable")
157                                 } else {
158                                         check.softErrorf(pos, _Todo, "interface contains type constraints")
159                                 }
160                         }
161                 }
162         })
163 }
164
165 // anyType type-checks the type expression e and returns its type, or Typ[Invalid].
166 // The type may be generic or instantiated.
167 func (check *Checker) anyType(e ast.Expr) Type {
168         typ := check.typInternal(e, nil)
169         assert(isTyped(typ))
170         check.recordTypeAndValue(e, typexpr, typ, nil)
171         return typ
172 }
173
174 // definedType is like typ but also accepts a type name def.
175 // If def != nil, e is the type specification for the defined type def, declared
176 // in a type declaration, and def.underlying will be set to the type of e before
177 // any components of e are type-checked.
178 //
179 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
180         typ := check.typInternal(e, def)
181         assert(isTyped(typ))
182         if isGeneric(typ) {
183                 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
184                 typ = Typ[Invalid]
185         }
186         check.recordTypeAndValue(e, typexpr, typ, nil)
187         return typ
188 }
189
190 // genericType is like typ but the type must be an (uninstantiated) generic type.
191 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
192         typ := check.typInternal(e, nil)
193         assert(isTyped(typ))
194         if typ != Typ[Invalid] && !isGeneric(typ) {
195                 if reportErr {
196                         check.errorf(e, _Todo, "%s is not a generic type", typ)
197                 }
198                 typ = Typ[Invalid]
199         }
200         // TODO(gri) what is the correct call below?
201         check.recordTypeAndValue(e, typexpr, typ, nil)
202         return typ
203 }
204
205 // goTypeName returns the Go type name for typ and
206 // removes any occurrences of "types." from that name.
207 func goTypeName(typ Type) string {
208         return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
209 }
210
211 // typInternal drives type checking of types.
212 // Must only be called by definedType or genericType.
213 //
214 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
215         if trace {
216                 check.trace(e0.Pos(), "type %s", e0)
217                 check.indent++
218                 defer func() {
219                         check.indent--
220                         var under Type
221                         if T != nil {
222                                 // Calling under() here may lead to endless instantiations.
223                                 // Test case: type T[P any] *T[P]
224                                 // TODO(gri) investigate if that's a bug or to be expected
225                                 // (see also analogous comment in Checker.instantiate).
226                                 under = safeUnderlying(T)
227                         }
228                         if T == under {
229                                 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
230                         } else {
231                                 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
232                         }
233                 }()
234         }
235
236         switch e := e0.(type) {
237         case *ast.BadExpr:
238                 // ignore - error reported before
239
240         case *ast.Ident:
241                 var x operand
242                 check.ident(&x, e, def, true)
243
244                 switch x.mode {
245                 case typexpr:
246                         typ := x.typ
247                         def.setUnderlying(typ)
248                         return typ
249                 case invalid:
250                         // ignore - error reported before
251                 case novalue:
252                         check.errorf(&x, _NotAType, "%s used as type", &x)
253                 default:
254                         check.errorf(&x, _NotAType, "%s is not a type", &x)
255                 }
256
257         case *ast.SelectorExpr:
258                 var x operand
259                 check.selector(&x, e)
260
261                 switch x.mode {
262                 case typexpr:
263                         typ := x.typ
264                         def.setUnderlying(typ)
265                         return typ
266                 case invalid:
267                         // ignore - error reported before
268                 case novalue:
269                         check.errorf(&x, _NotAType, "%s used as type", &x)
270                 default:
271                         check.errorf(&x, _NotAType, "%s is not a type", &x)
272                 }
273
274         case *ast.IndexExpr, *ast.MultiIndexExpr:
275                 ix := typeparams.UnpackIndexExpr(e)
276                 // TODO(rfindley): type instantiation should require go1.18
277                 return check.instantiatedType(ix.X, ix.Indices, def)
278
279         case *ast.ParenExpr:
280                 // Generic types must be instantiated before they can be used in any form.
281                 // Consequently, generic types cannot be parenthesized.
282                 return check.definedType(e.X, def)
283
284         case *ast.ArrayType:
285                 if e.Len != nil {
286                         typ := new(Array)
287                         def.setUnderlying(typ)
288                         typ.len = check.arrayLength(e.Len)
289                         typ.elem = check.varType(e.Elt)
290                         return typ
291                 }
292
293                 typ := new(Slice)
294                 def.setUnderlying(typ)
295                 typ.elem = check.varType(e.Elt)
296                 return typ
297
298         case *ast.Ellipsis:
299                 // dots are handled explicitly where they are legal
300                 // (array composite literals and parameter lists)
301                 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
302                 check.use(e.Elt)
303
304         case *ast.StructType:
305                 typ := new(Struct)
306                 def.setUnderlying(typ)
307                 check.structType(typ, e)
308                 return typ
309
310         case *ast.StarExpr:
311                 typ := new(Pointer)
312                 def.setUnderlying(typ)
313                 typ.base = check.varType(e.X)
314                 return typ
315
316         case *ast.FuncType:
317                 typ := new(Signature)
318                 def.setUnderlying(typ)
319                 check.funcType(typ, nil, e)
320                 return typ
321
322         case *ast.InterfaceType:
323                 typ := new(Interface)
324                 def.setUnderlying(typ)
325                 if def != nil {
326                         typ.obj = def.obj
327                 }
328                 check.interfaceType(typ, e, def)
329                 return typ
330
331         case *ast.MapType:
332                 typ := new(Map)
333                 def.setUnderlying(typ)
334
335                 typ.key = check.varType(e.Key)
336                 typ.elem = check.varType(e.Value)
337
338                 // spec: "The comparison operators == and != must be fully defined
339                 // for operands of the key type; thus the key type must not be a
340                 // function, map, or slice."
341                 //
342                 // Delay this check because it requires fully setup types;
343                 // it is safe to continue in any case (was issue 6667).
344                 check.later(func() {
345                         if !Comparable(typ.key) {
346                                 var why string
347                                 if asTypeParam(typ.key) != nil {
348                                         why = " (missing comparable constraint)"
349                                 }
350                                 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
351                         }
352                 })
353
354                 return typ
355
356         case *ast.ChanType:
357                 typ := new(Chan)
358                 def.setUnderlying(typ)
359
360                 dir := SendRecv
361                 switch e.Dir {
362                 case ast.SEND | ast.RECV:
363                         // nothing to do
364                 case ast.SEND:
365                         dir = SendOnly
366                 case ast.RECV:
367                         dir = RecvOnly
368                 default:
369                         check.invalidAST(e, "unknown channel direction %d", e.Dir)
370                         // ok to continue
371                 }
372
373                 typ.dir = dir
374                 typ.elem = check.varType(e.Value)
375                 return typ
376
377         default:
378                 check.errorf(e0, _NotAType, "%s is not a type", e0)
379         }
380
381         typ := Typ[Invalid]
382         def.setUnderlying(typ)
383         return typ
384 }
385
386 func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) Type {
387         gtyp := check.genericType(x, true)
388         if gtyp == Typ[Invalid] {
389                 return gtyp // error already reported
390         }
391         base, _ := gtyp.(*Named)
392         if base == nil {
393                 panic(fmt.Sprintf("%v: cannot instantiate %v", x.Pos(), gtyp))
394         }
395
396         // evaluate arguments
397         targs := check.typeList(targsx)
398         if targs == nil {
399                 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
400                 return Typ[Invalid]
401         }
402
403         // determine argument positions
404         posList := make([]token.Pos, len(targs))
405         for i, arg := range targsx {
406                 posList[i] = arg.Pos()
407         }
408
409         typ := check.instantiate(x.Pos(), base, targs, posList)
410         def.setUnderlying(typ)
411
412         // make sure we check instantiation works at least once
413         // and that the resulting type is valid
414         check.later(func() {
415                 check.validType(typ, nil)
416         })
417
418         return typ
419 }
420
421 // arrayLength type-checks the array length expression e
422 // and returns the constant length >= 0, or a value < 0
423 // to indicate an error (and thus an unknown length).
424 func (check *Checker) arrayLength(e ast.Expr) int64 {
425         var x operand
426         check.expr(&x, e)
427         if x.mode != constant_ {
428                 if x.mode != invalid {
429                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
430                 }
431                 return -1
432         }
433         if isUntyped(x.typ) || isInteger(x.typ) {
434                 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
435                         if representableConst(val, check, Typ[Int], nil) {
436                                 if n, ok := constant.Int64Val(val); ok && n >= 0 {
437                                         return n
438                                 }
439                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
440                                 return -1
441                         }
442                 }
443         }
444         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
445         return -1
446 }
447
448 // typeList provides the list of types corresponding to the incoming expression list.
449 // If an error occurred, the result is nil, but all list elements were type-checked.
450 func (check *Checker) typeList(list []ast.Expr) []Type {
451         res := make([]Type, len(list)) // res != nil even if len(list) == 0
452         for i, x := range list {
453                 t := check.varType(x)
454                 if t == Typ[Invalid] {
455                         res = nil
456                 }
457                 if res != nil {
458                         res[i] = t
459                 }
460         }
461         return res
462 }