]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
cmd/compile, go/types: allow `any` anywhere (as a type)
[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 // avoid follow-on errors
42                 }
43         }
44         check.recordUse(e, obj)
45
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).
54         typ := obj.Type()
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
58         }
59         assert(typ != nil)
60
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 {
66                 pkgName.used = true
67         }
68
69         switch obj := obj.(type) {
70         case *PkgName:
71                 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
72                 return
73
74         case *Const:
75                 check.addDeclDep(obj)
76                 if typ == Typ[Invalid] {
77                         return
78                 }
79                 if obj == universeIota {
80                         if check.iota == nil {
81                                 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
82                                 return
83                         }
84                         x.val = check.iota
85                 } else {
86                         x.val = obj.val
87                 }
88                 assert(x.val != nil)
89                 x.mode = constant_
90
91         case *TypeName:
92                 x.mode = typexpr
93
94         case *Var:
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 {
99                         obj.used = true
100                 }
101                 check.addDeclDep(obj)
102                 if typ == Typ[Invalid] {
103                         return
104                 }
105                 x.mode = variable
106
107         case *Func:
108                 check.addDeclDep(obj)
109                 x.mode = value
110
111         case *Builtin:
112                 x.id = obj.id
113                 x.mode = builtin
114
115         case *Nil:
116                 x.mode = value
117
118         default:
119                 unreachable()
120         }
121
122         x.typ = typ
123 }
124
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)
129 }
130
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.
139         check.later(func() {
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() {
143                                 if tset.comparable {
144                                         check.softErrorf(e, _Todo, "interface is (or embeds) comparable")
145                                 } else {
146                                         check.softErrorf(e, _Todo, "interface contains type constraints")
147                                 }
148                         }
149                 }
150         })
151
152         return typ
153 }
154
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.
159 //
160 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
161         typ := check.typInternal(e, def)
162         assert(isTyped(typ))
163         if isGeneric(typ) {
164                 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
165                 typ = Typ[Invalid]
166         }
167         check.recordTypeAndValue(e, typexpr, typ, nil)
168         return typ
169 }
170
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)
174         assert(isTyped(typ))
175         if typ != Typ[Invalid] && !isGeneric(typ) {
176                 if reportErr {
177                         check.errorf(e, _Todo, "%s is not a generic type", typ)
178                 }
179                 typ = Typ[Invalid]
180         }
181         // TODO(gri) what is the correct call below?
182         check.recordTypeAndValue(e, typexpr, typ, nil)
183         return typ
184 }
185
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.", "")
190 }
191
192 // typInternal drives type checking of types.
193 // Must only be called by definedType or genericType.
194 //
195 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
196         if trace {
197                 check.trace(e0.Pos(), "type %s", e0)
198                 check.indent++
199                 defer func() {
200                         check.indent--
201                         var under Type
202                         if T != nil {
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)
208                         }
209                         if T == under {
210                                 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
211                         } else {
212                                 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
213                         }
214                 }()
215         }
216
217         switch e := e0.(type) {
218         case *ast.BadExpr:
219                 // ignore - error reported before
220
221         case *ast.Ident:
222                 var x operand
223                 check.ident(&x, e, def, true)
224
225                 switch x.mode {
226                 case typexpr:
227                         typ := x.typ
228                         def.setUnderlying(typ)
229                         return typ
230                 case invalid:
231                         // ignore - error reported before
232                 case novalue:
233                         check.errorf(&x, _NotAType, "%s used as type", &x)
234                 default:
235                         check.errorf(&x, _NotAType, "%s is not a type", &x)
236                 }
237
238         case *ast.SelectorExpr:
239                 var x operand
240                 check.selector(&x, e)
241
242                 switch x.mode {
243                 case typexpr:
244                         typ := x.typ
245                         def.setUnderlying(typ)
246                         return typ
247                 case invalid:
248                         // ignore - error reported before
249                 case novalue:
250                         check.errorf(&x, _NotAType, "%s used as type", &x)
251                 default:
252                         check.errorf(&x, _NotAType, "%s is not a type", &x)
253                 }
254
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")
259                 }
260                 // TODO(rfindley): type instantiation should require go1.18
261                 return check.instantiatedType(ix.X, ix.Indices, def)
262
263         case *ast.ParenExpr:
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)
267
268         case *ast.ArrayType:
269                 if e.Len != nil {
270                         typ := new(Array)
271                         def.setUnderlying(typ)
272                         typ.len = check.arrayLength(e.Len)
273                         typ.elem = check.varType(e.Elt)
274                         return typ
275                 }
276
277                 typ := new(Slice)
278                 def.setUnderlying(typ)
279                 typ.elem = check.varType(e.Elt)
280                 return typ
281
282         case *ast.Ellipsis:
283                 // dots are handled explicitly where they are legal
284                 // (array composite literals and parameter lists)
285                 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
286                 check.use(e.Elt)
287
288         case *ast.StructType:
289                 typ := new(Struct)
290                 def.setUnderlying(typ)
291                 check.structType(typ, e)
292                 return typ
293
294         case *ast.StarExpr:
295                 typ := new(Pointer)
296                 def.setUnderlying(typ)
297                 typ.base = check.varType(e.X)
298                 return typ
299
300         case *ast.FuncType:
301                 typ := new(Signature)
302                 def.setUnderlying(typ)
303                 check.funcType(typ, nil, e)
304                 return typ
305
306         case *ast.InterfaceType:
307                 typ := new(Interface)
308                 def.setUnderlying(typ)
309                 if def != nil {
310                         typ.obj = def.obj
311                 }
312                 check.interfaceType(typ, e, def)
313                 return typ
314
315         case *ast.MapType:
316                 typ := new(Map)
317                 def.setUnderlying(typ)
318
319                 typ.key = check.varType(e.Key)
320                 typ.elem = check.varType(e.Value)
321
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."
325                 //
326                 // Delay this check because it requires fully setup types;
327                 // it is safe to continue in any case (was issue 6667).
328                 check.later(func() {
329                         if !Comparable(typ.key) {
330                                 var why string
331                                 if asTypeParam(typ.key) != nil {
332                                         why = " (missing comparable constraint)"
333                                 }
334                                 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
335                         }
336                 })
337
338                 return typ
339
340         case *ast.ChanType:
341                 typ := new(Chan)
342                 def.setUnderlying(typ)
343
344                 dir := SendRecv
345                 switch e.Dir {
346                 case ast.SEND | ast.RECV:
347                         // nothing to do
348                 case ast.SEND:
349                         dir = SendOnly
350                 case ast.RECV:
351                         dir = RecvOnly
352                 default:
353                         check.invalidAST(e, "unknown channel direction %d", e.Dir)
354                         // ok to continue
355                 }
356
357                 typ.dir = dir
358                 typ.elem = check.varType(e.Value)
359                 return typ
360
361         default:
362                 check.errorf(e0, _NotAType, "%s is not a type", e0)
363         }
364
365         typ := Typ[Invalid]
366         def.setUnderlying(typ)
367         return typ
368 }
369
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
374         }
375         base, _ := gtyp.(*Named)
376         if base == nil {
377                 panic(fmt.Sprintf("%v: cannot instantiate %v", x.Pos(), gtyp))
378         }
379
380         // evaluate arguments
381         targs := check.typeList(targsx)
382         if targs == nil {
383                 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
384                 return Typ[Invalid]
385         }
386
387         // determine argument positions
388         posList := make([]token.Pos, len(targs))
389         for i, arg := range targsx {
390                 posList[i] = arg.Pos()
391         }
392
393         typ := check.instantiate(x.Pos(), base, targs, posList)
394         def.setUnderlying(typ)
395         check.recordInstance(x, targs, typ)
396
397         // make sure we check instantiation works at least once
398         // and that the resulting type is valid
399         check.later(func() {
400                 check.validType(typ, nil)
401         })
402
403         return typ
404 }
405
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)
415                 return -1
416         }
417
418         var x operand
419         check.expr(&x, e)
420         if x.mode != constant_ {
421                 if x.mode != invalid {
422                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
423                 }
424                 return -1
425         }
426
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 {
431                                         return n
432                                 }
433                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
434                                 return -1
435                         }
436                 }
437         }
438
439         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
440         return -1
441 }
442
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] {
450                         res = nil
451                 }
452                 if res != nil {
453                         res[i] = t
454                 }
455         }
456         return res
457 }