]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
[dev.typeparams] all: merge master (798ec73) into dev.typeparams
[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
149         // while we are in the middle of type-checking parameter declarations that
150         // might belong to interface methods. Delay this check to the end of
151         // type-checking.
152         check.later(func() {
153                 if t := asInterface(typ); t != nil {
154                         tset := computeTypeSet(check, pos.Pos(), t) // TODO(gri) is this the correct position?
155                         if tset.types != nil {
156                                 check.softErrorf(pos, _Todo, "interface contains type constraints (%s)", tset.types)
157                                 return
158                         }
159                         if tset.IsComparable() {
160                                 check.softErrorf(pos, _Todo, "interface is (or embeds) comparable")
161                         }
162                 }
163         })
164 }
165
166 // anyType type-checks the type expression e and returns its type, or Typ[Invalid].
167 // The type may be generic or instantiated.
168 func (check *Checker) anyType(e ast.Expr) Type {
169         typ := check.typInternal(e, nil)
170         assert(isTyped(typ))
171         check.recordTypeAndValue(e, typexpr, typ, nil)
172         return typ
173 }
174
175 // definedType is like typ but also accepts a type name def.
176 // If def != nil, e is the type specification for the defined type def, declared
177 // in a type declaration, and def.underlying will be set to the type of e before
178 // any components of e are type-checked.
179 //
180 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
181         typ := check.typInternal(e, def)
182         assert(isTyped(typ))
183         if isGeneric(typ) {
184                 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
185                 typ = Typ[Invalid]
186         }
187         check.recordTypeAndValue(e, typexpr, typ, nil)
188         return typ
189 }
190
191 // genericType is like typ but the type must be an (uninstantiated) generic type.
192 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
193         typ := check.typInternal(e, nil)
194         assert(isTyped(typ))
195         if typ != Typ[Invalid] && !isGeneric(typ) {
196                 if reportErr {
197                         check.errorf(e, _Todo, "%s is not a generic type", typ)
198                 }
199                 typ = Typ[Invalid]
200         }
201         // TODO(gri) what is the correct call below?
202         check.recordTypeAndValue(e, typexpr, typ, nil)
203         return typ
204 }
205
206 // goTypeName returns the Go type name for typ and
207 // removes any occurrences of "types." from that name.
208 func goTypeName(typ Type) string {
209         return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
210 }
211
212 // typInternal drives type checking of types.
213 // Must only be called by definedType or genericType.
214 //
215 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
216         if trace {
217                 check.trace(e0.Pos(), "type %s", e0)
218                 check.indent++
219                 defer func() {
220                         check.indent--
221                         var under Type
222                         if T != nil {
223                                 // Calling under() here may lead to endless instantiations.
224                                 // Test case: type T[P any] *T[P]
225                                 // TODO(gri) investigate if that's a bug or to be expected
226                                 // (see also analogous comment in Checker.instantiate).
227                                 under = T.Underlying()
228                         }
229                         if T == under {
230                                 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
231                         } else {
232                                 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
233                         }
234                 }()
235         }
236
237         switch e := e0.(type) {
238         case *ast.BadExpr:
239                 // ignore - error reported before
240
241         case *ast.Ident:
242                 var x operand
243                 check.ident(&x, e, def, true)
244
245                 switch x.mode {
246                 case typexpr:
247                         typ := x.typ
248                         def.setUnderlying(typ)
249                         return typ
250                 case invalid:
251                         // ignore - error reported before
252                 case novalue:
253                         check.errorf(&x, _NotAType, "%s used as type", &x)
254                 default:
255                         check.errorf(&x, _NotAType, "%s is not a type", &x)
256                 }
257
258         case *ast.SelectorExpr:
259                 var x operand
260                 check.selector(&x, e)
261
262                 switch x.mode {
263                 case typexpr:
264                         typ := x.typ
265                         def.setUnderlying(typ)
266                         return typ
267                 case invalid:
268                         // ignore - error reported before
269                 case novalue:
270                         check.errorf(&x, _NotAType, "%s used as type", &x)
271                 default:
272                         check.errorf(&x, _NotAType, "%s is not a type", &x)
273                 }
274
275         case *ast.IndexExpr, *ast.MultiIndexExpr:
276                 ix := typeparams.UnpackIndexExpr(e)
277                 // TODO(rfindley): type instantiation should require go1.18
278                 return check.instantiatedType(ix.X, ix.Indices, def)
279
280         case *ast.ParenExpr:
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)
284
285         case *ast.ArrayType:
286                 if e.Len != nil {
287                         typ := new(Array)
288                         def.setUnderlying(typ)
289                         typ.len = check.arrayLength(e.Len)
290                         typ.elem = check.varType(e.Elt)
291                         return typ
292                 }
293
294                 typ := new(Slice)
295                 def.setUnderlying(typ)
296                 typ.elem = check.varType(e.Elt)
297                 return typ
298
299         case *ast.Ellipsis:
300                 // dots are handled explicitly where they are legal
301                 // (array composite literals and parameter lists)
302                 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
303                 check.use(e.Elt)
304
305         case *ast.StructType:
306                 typ := new(Struct)
307                 def.setUnderlying(typ)
308                 check.structType(typ, e)
309                 return typ
310
311         case *ast.StarExpr:
312                 typ := new(Pointer)
313                 def.setUnderlying(typ)
314                 typ.base = check.varType(e.X)
315                 return typ
316
317         case *ast.FuncType:
318                 typ := new(Signature)
319                 def.setUnderlying(typ)
320                 check.funcType(typ, nil, e)
321                 return typ
322
323         case *ast.InterfaceType:
324                 typ := new(Interface)
325                 def.setUnderlying(typ)
326                 if def != nil {
327                         typ.obj = def.obj
328                 }
329                 check.interfaceType(typ, e, def)
330                 return typ
331
332         case *ast.MapType:
333                 typ := new(Map)
334                 def.setUnderlying(typ)
335
336                 typ.key = check.varType(e.Key)
337                 typ.elem = check.varType(e.Value)
338
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."
342                 //
343                 // Delay this check because it requires fully setup types;
344                 // it is safe to continue in any case (was issue 6667).
345                 check.later(func() {
346                         if !Comparable(typ.key) {
347                                 var why string
348                                 if asTypeParam(typ.key) != nil {
349                                         why = " (missing comparable constraint)"
350                                 }
351                                 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
352                         }
353                 })
354
355                 return typ
356
357         case *ast.ChanType:
358                 typ := new(Chan)
359                 def.setUnderlying(typ)
360
361                 dir := SendRecv
362                 switch e.Dir {
363                 case ast.SEND | ast.RECV:
364                         // nothing to do
365                 case ast.SEND:
366                         dir = SendOnly
367                 case ast.RECV:
368                         dir = RecvOnly
369                 default:
370                         check.invalidAST(e, "unknown channel direction %d", e.Dir)
371                         // ok to continue
372                 }
373
374                 typ.dir = dir
375                 typ.elem = check.varType(e.Value)
376                 return typ
377
378         default:
379                 check.errorf(e0, _NotAType, "%s is not a type", e0)
380         }
381
382         typ := Typ[Invalid]
383         def.setUnderlying(typ)
384         return typ
385 }
386
387 // typeOrNil type-checks the type expression (or nil value) e
388 // and returns the type of e, or nil. If e is a type, it must
389 // not be an (uninstantiated) generic type.
390 // If e is neither a type nor nil, typeOrNil returns Typ[Invalid].
391 // TODO(gri) should we also disallow non-var types?
392 func (check *Checker) typeOrNil(e ast.Expr) Type {
393         var x operand
394         check.rawExpr(&x, e, nil)
395         switch x.mode {
396         case invalid:
397                 // ignore - error reported before
398         case novalue:
399                 check.errorf(&x, _NotAType, "%s used as type", &x)
400         case typexpr:
401                 check.instantiatedOperand(&x)
402                 return x.typ
403         case value:
404                 if x.isNil() {
405                         return nil
406                 }
407                 fallthrough
408         default:
409                 check.errorf(&x, _NotAType, "%s is not a type", &x)
410         }
411         return Typ[Invalid]
412 }
413
414 func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) Type {
415         base := check.genericType(x, true)
416         if base == Typ[Invalid] {
417                 return base // error already reported
418         }
419
420         // evaluate arguments
421         targs := check.typeList(targsx)
422         if targs == nil {
423                 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
424                 return Typ[Invalid]
425         }
426
427         // determine argument positions
428         posList := make([]token.Pos, len(targs))
429         for i, arg := range targsx {
430                 posList[i] = arg.Pos()
431         }
432
433         typ := check.InstantiateLazy(x.Pos(), base, targs, posList, true)
434         def.setUnderlying(typ)
435
436         // make sure we check instantiation works at least once
437         // and that the resulting type is valid
438         check.later(func() {
439                 t := expand(typ)
440                 check.validType(t, nil)
441         })
442
443         return typ
444 }
445
446 // arrayLength type-checks the array length expression e
447 // and returns the constant length >= 0, or a value < 0
448 // to indicate an error (and thus an unknown length).
449 func (check *Checker) arrayLength(e ast.Expr) int64 {
450         var x operand
451         check.expr(&x, e)
452         if x.mode != constant_ {
453                 if x.mode != invalid {
454                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
455                 }
456                 return -1
457         }
458         if isUntyped(x.typ) || isInteger(x.typ) {
459                 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
460                         if representableConst(val, check, Typ[Int], nil) {
461                                 if n, ok := constant.Int64Val(val); ok && n >= 0 {
462                                         return n
463                                 }
464                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
465                                 return -1
466                         }
467                 }
468         }
469         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
470         return -1
471 }
472
473 // typeList provides the list of types corresponding to the incoming expression list.
474 // If an error occurred, the result is nil, but all list elements were type-checked.
475 func (check *Checker) typeList(list []ast.Expr) []Type {
476         res := make([]Type, len(list)) // res != nil even if len(list) == 0
477         for i, x := range list {
478                 t := check.varType(x)
479                 if t == Typ[Invalid] {
480                         res = nil
481                 }
482                 if res != nil {
483                         res[i] = t
484                 }
485         }
486         return res
487 }