]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
go/types: rename IsMethodSet to IsConstraint (cleanup)
[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 but keep going
40                 if !check.allowVersion(check.pkg, 1, 18) {
41                         check.softErrorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
42                 } else if obj == universeAny {
43                         // If we allow "any" for general use, this if-statement can be removed (issue #33232).
44                         check.softErrorf(e, _Todo, "cannot use any outside constraint position")
45                 }
46         }
47         check.recordUse(e, obj)
48
49         // Type-check the object.
50         // Only call Checker.objDecl if the object doesn't have a type yet
51         // (in which case we must actually determine it) or the object is a
52         // TypeName and we also want a type (in which case we might detect
53         // a cycle which needs to be reported). Otherwise we can skip the
54         // call and avoid a possible cycle error in favor of the more
55         // informative "not a type/value" error that this function's caller
56         // will issue (see issue #25790).
57         typ := obj.Type()
58         if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
59                 check.objDecl(obj, def)
60                 typ = obj.Type() // type must have been assigned by Checker.objDecl
61         }
62         assert(typ != nil)
63
64         // The object may have been dot-imported.
65         // If so, mark the respective package as used.
66         // (This code is only needed for dot-imports. Without them,
67         // we only have to mark variables, see *Var case below).
68         if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
69                 pkgName.used = true
70         }
71
72         switch obj := obj.(type) {
73         case *PkgName:
74                 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
75                 return
76
77         case *Const:
78                 check.addDeclDep(obj)
79                 if typ == Typ[Invalid] {
80                         return
81                 }
82                 if obj == universeIota {
83                         if check.iota == nil {
84                                 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
85                                 return
86                         }
87                         x.val = check.iota
88                 } else {
89                         x.val = obj.val
90                 }
91                 assert(x.val != nil)
92                 x.mode = constant_
93
94         case *TypeName:
95                 x.mode = typexpr
96
97         case *Var:
98                 // It's ok to mark non-local variables, but ignore variables
99                 // from other packages to avoid potential race conditions with
100                 // dot-imported variables.
101                 if obj.pkg == check.pkg {
102                         obj.used = true
103                 }
104                 check.addDeclDep(obj)
105                 if typ == Typ[Invalid] {
106                         return
107                 }
108                 x.mode = variable
109
110         case *Func:
111                 check.addDeclDep(obj)
112                 x.mode = value
113
114         case *Builtin:
115                 x.id = obj.id
116                 x.mode = builtin
117
118         case *Nil:
119                 x.mode = value
120
121         default:
122                 unreachable()
123         }
124
125         x.typ = typ
126 }
127
128 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
129 // The type must not be an (uninstantiated) generic type.
130 func (check *Checker) typ(e ast.Expr) Type {
131         return check.definedType(e, nil)
132 }
133
134 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
135 // The type must not be an (uninstantiated) generic type and it must be ordinary
136 // (see ordinaryType).
137 func (check *Checker) varType(e ast.Expr) Type {
138         typ := check.definedType(e, nil)
139         check.ordinaryType(e, typ)
140         return typ
141 }
142
143 // ordinaryType reports an error if typ is an interface type containing
144 // type lists or is (or embeds) the predeclared type comparable.
145 func (check *Checker) ordinaryType(pos positioner, typ Type) {
146         // We don't want to call under() (via asInterface) or complete interfaces while we
147         // are in the middle of type-checking parameter declarations that might belong to
148         // interface methods. Delay this check to the end of type-checking.
149         check.later(func() {
150                 if t := asInterface(typ); t != nil {
151                         tset := computeInterfaceTypeSet(check, pos.Pos(), t) // TODO(gri) is this the correct position?
152                         if tset.IsConstraint() {
153                                 if tset.comparable {
154                                         check.softErrorf(pos, _Todo, "interface is (or embeds) comparable")
155                                 } else {
156                                         check.softErrorf(pos, _Todo, "interface contains type constraints")
157                                 }
158                         }
159                 }
160         })
161 }
162
163 // anyType type-checks the type expression e and returns its type, or Typ[Invalid].
164 // The type may be generic or instantiated.
165 func (check *Checker) anyType(e ast.Expr) Type {
166         typ := check.typInternal(e, nil)
167         assert(isTyped(typ))
168         check.recordTypeAndValue(e, typexpr, typ, nil)
169         return typ
170 }
171
172 // definedType is like typ but also accepts a type name def.
173 // If def != nil, e is the type specification for the defined type def, declared
174 // in a type declaration, and def.underlying will be set to the type of e before
175 // any components of e are type-checked.
176 //
177 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
178         typ := check.typInternal(e, def)
179         assert(isTyped(typ))
180         if isGeneric(typ) {
181                 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
182                 typ = Typ[Invalid]
183         }
184         check.recordTypeAndValue(e, typexpr, typ, nil)
185         return typ
186 }
187
188 // genericType is like typ but the type must be an (uninstantiated) generic type.
189 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
190         typ := check.typInternal(e, nil)
191         assert(isTyped(typ))
192         if typ != Typ[Invalid] && !isGeneric(typ) {
193                 if reportErr {
194                         check.errorf(e, _Todo, "%s is not a generic type", typ)
195                 }
196                 typ = Typ[Invalid]
197         }
198         // TODO(gri) what is the correct call below?
199         check.recordTypeAndValue(e, typexpr, typ, nil)
200         return typ
201 }
202
203 // goTypeName returns the Go type name for typ and
204 // removes any occurrences of "types." from that name.
205 func goTypeName(typ Type) string {
206         return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
207 }
208
209 // typInternal drives type checking of types.
210 // Must only be called by definedType or genericType.
211 //
212 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
213         if trace {
214                 check.trace(e0.Pos(), "type %s", e0)
215                 check.indent++
216                 defer func() {
217                         check.indent--
218                         var under Type
219                         if T != nil {
220                                 // Calling under() here may lead to endless instantiations.
221                                 // Test case: type T[P any] *T[P]
222                                 // TODO(gri) investigate if that's a bug or to be expected
223                                 // (see also analogous comment in Checker.instantiate).
224                                 under = safeUnderlying(T)
225                         }
226                         if T == under {
227                                 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
228                         } else {
229                                 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
230                         }
231                 }()
232         }
233
234         switch e := e0.(type) {
235         case *ast.BadExpr:
236                 // ignore - error reported before
237
238         case *ast.Ident:
239                 var x operand
240                 check.ident(&x, e, def, true)
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.SelectorExpr:
256                 var x operand
257                 check.selector(&x, e)
258
259                 switch x.mode {
260                 case typexpr:
261                         typ := x.typ
262                         def.setUnderlying(typ)
263                         return typ
264                 case invalid:
265                         // ignore - error reported before
266                 case novalue:
267                         check.errorf(&x, _NotAType, "%s used as type", &x)
268                 default:
269                         check.errorf(&x, _NotAType, "%s is not a type", &x)
270                 }
271
272         case *ast.IndexExpr, *ast.MultiIndexExpr:
273                 ix := typeparams.UnpackIndexExpr(e)
274                 if !check.allowVersion(check.pkg, 1, 18) {
275                         check.softErrorf(inNode(e, ix.Lbrack), _Todo, "type instantiation requires go1.18 or later")
276                 }
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 func (check *Checker) instantiatedType(x ast.Expr, targsx []ast.Expr, def *Named) Type {
388         gtyp := check.genericType(x, true)
389         if gtyp == Typ[Invalid] {
390                 return gtyp // error already reported
391         }
392         base, _ := gtyp.(*Named)
393         if base == nil {
394                 panic(fmt.Sprintf("%v: cannot instantiate %v", x.Pos(), gtyp))
395         }
396
397         // evaluate arguments
398         targs := check.typeList(targsx)
399         if targs == nil {
400                 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
401                 return Typ[Invalid]
402         }
403
404         // determine argument positions
405         posList := make([]token.Pos, len(targs))
406         for i, arg := range targsx {
407                 posList[i] = arg.Pos()
408         }
409
410         typ := check.instantiate(x.Pos(), base, targs, posList)
411         def.setUnderlying(typ)
412
413         // make sure we check instantiation works at least once
414         // and that the resulting type is valid
415         check.later(func() {
416                 check.validType(typ, nil)
417         })
418
419         return typ
420 }
421
422 // arrayLength type-checks the array length expression e
423 // and returns the constant length >= 0, or a value < 0
424 // to indicate an error (and thus an unknown length).
425 func (check *Checker) arrayLength(e ast.Expr) int64 {
426         var x operand
427         check.expr(&x, e)
428         if x.mode != constant_ {
429                 if x.mode != invalid {
430                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
431                 }
432                 return -1
433         }
434         if isUntyped(x.typ) || isInteger(x.typ) {
435                 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
436                         if representableConst(val, check, Typ[Int], nil) {
437                                 if n, ok := constant.Int64Val(val); ok && n >= 0 {
438                                         return n
439                                 }
440                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
441                                 return -1
442                         }
443                 }
444         }
445         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
446         return -1
447 }
448
449 // typeList provides the list of types corresponding to the incoming expression list.
450 // If an error occurred, the result is nil, but all list elements were type-checked.
451 func (check *Checker) typeList(list []ast.Expr) []Type {
452         res := make([]Type, len(list)) // res != nil even if len(list) == 0
453         for i, x := range list {
454                 t := check.varType(x)
455                 if t == Typ[Invalid] {
456                         res = nil
457                 }
458                 if res != nil {
459                         res[i] = t
460                 }
461         }
462         return res
463 }