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