]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
go/types, types2: record all type instances, even duplicates
[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         "strings"
15 )
16
17 // ident type-checks identifier e and initializes x with the value or type of e.
18 // If an error occurred, x.mode is set to invalid.
19 // For the meaning of def, see Checker.definedType, below.
20 // If wantType is set, the identifier e is expected to denote a type.
21 //
22 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
23         x.mode = invalid
24         x.expr = e
25
26         // Note that we cannot use check.lookup here because the returned scope
27         // may be different from obj.Parent(). See also Scope.LookupParent doc.
28         scope, obj := check.scope.LookupParent(e.Name, check.pos)
29         switch obj {
30         case nil:
31                 if e.Name == "_" {
32                         // Blank identifiers are never declared, but the current identifier may
33                         // be a placeholder for a receiver type parameter. In this case we can
34                         // resolve its type and object from Checker.recvTParamMap.
35                         if tpar := check.recvTParamMap[e]; tpar != nil {
36                                 x.mode = typexpr
37                                 x.typ = tpar
38                         } else {
39                                 check.error(e, _InvalidBlank, "cannot use _ as value or type")
40                         }
41                 } else {
42                         check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
43                 }
44                 return
45         case universeAny, universeComparable:
46                 if !check.allowVersion(check.pkg, 1, 18) {
47                         check.errorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
48                         return // avoid follow-on errors
49                 }
50         }
51         check.recordUse(e, obj)
52
53         // Type-check the object.
54         // Only call Checker.objDecl if the object doesn't have a type yet
55         // (in which case we must actually determine it) or the object is a
56         // TypeName and we also want a type (in which case we might detect
57         // a cycle which needs to be reported). Otherwise we can skip the
58         // call and avoid a possible cycle error in favor of the more
59         // informative "not a type/value" error that this function's caller
60         // will issue (see issue #25790).
61         typ := obj.Type()
62         if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
63                 check.objDecl(obj, def)
64                 typ = obj.Type() // type must have been assigned by Checker.objDecl
65         }
66         assert(typ != nil)
67
68         // The object may have been dot-imported.
69         // If so, mark the respective package as used.
70         // (This code is only needed for dot-imports. Without them,
71         // we only have to mark variables, see *Var case below).
72         if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
73                 pkgName.used = true
74         }
75
76         switch obj := obj.(type) {
77         case *PkgName:
78                 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
79                 return
80
81         case *Const:
82                 check.addDeclDep(obj)
83                 if typ == Typ[Invalid] {
84                         return
85                 }
86                 if obj == universeIota {
87                         if check.iota == nil {
88                                 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
89                                 return
90                         }
91                         x.val = check.iota
92                 } else {
93                         x.val = obj.val
94                 }
95                 assert(x.val != nil)
96                 x.mode = constant_
97
98         case *TypeName:
99                 if check.isBrokenAlias(obj) {
100                         check.errorf(e, _InvalidDeclCycle, "invalid use of type alias %s in recursive type (see issue #50729)", obj.name)
101                         return
102                 }
103                 x.mode = typexpr
104
105         case *Var:
106                 // It's ok to mark non-local variables, but ignore variables
107                 // from other packages to avoid potential race conditions with
108                 // dot-imported variables.
109                 if obj.pkg == check.pkg {
110                         obj.used = true
111                 }
112                 check.addDeclDep(obj)
113                 if typ == Typ[Invalid] {
114                         return
115                 }
116                 x.mode = variable
117
118         case *Func:
119                 check.addDeclDep(obj)
120                 x.mode = value
121
122         case *Builtin:
123                 x.id = obj.id
124                 x.mode = builtin
125
126         case *Nil:
127                 x.mode = value
128
129         default:
130                 unreachable()
131         }
132
133         x.typ = typ
134 }
135
136 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
137 // The type must not be an (uninstantiated) generic type.
138 func (check *Checker) typ(e ast.Expr) Type {
139         return check.definedType(e, nil)
140 }
141
142 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
143 // The type must not be an (uninstantiated) generic type and it must not be a
144 // constraint interface.
145 func (check *Checker) varType(e ast.Expr) Type {
146         typ := check.definedType(e, nil)
147
148         // If we have a type parameter there's nothing to do.
149         if isTypeParam(typ) {
150                 return typ
151         }
152
153         // We don't want to call under() or complete interfaces while we are in
154         // the middle of type-checking parameter declarations that might belong
155         // to interface methods. Delay this check to the end of type-checking.
156         check.later(func() {
157                 if t, _ := under(typ).(*Interface); t != nil {
158                         tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
159                         if !tset.IsMethodSet() {
160                                 if tset.comparable {
161                                         check.softErrorf(e, _MisplacedConstraintIface, "interface is (or embeds) comparable")
162                                 } else {
163                                         check.softErrorf(e, _MisplacedConstraintIface, "interface contains type constraints")
164                                 }
165                         }
166                 }
167         })
168
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, _WrongTypeArgCount, "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
189 // type. If reason is non-nil and the type expression was a valid type but not
190 // generic, reason will be populated with a message describing the error.
191 func (check *Checker) genericType(e ast.Expr, reason *string) Type {
192         typ := check.typInternal(e, nil)
193         assert(isTyped(typ))
194         if typ != Typ[Invalid] && !isGeneric(typ) {
195                 if reason != nil {
196                         *reason = check.sprintf("%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                                 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, def)
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.IndexListExpr:
273                 ix := typeparams.UnpackIndexExpr(e)
274                 if !check.allowVersion(check.pkg, 1, 18) {
275                         check.softErrorf(inNode(e, ix.Lbrack), _UnsupportedFeature, "type instantiation requires go1.18 or later")
276                 }
277                 return check.instantiatedType(ix, 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(Slice)
287                         def.setUnderlying(typ)
288                         typ.elem = check.varType(e.Elt)
289                         return typ
290                 }
291
292                 typ := new(Array)
293                 def.setUnderlying(typ)
294                 typ.len = check.arrayLength(e.Len)
295                 typ.elem = check.varType(e.Elt)
296                 if typ.len >= 0 {
297                         return typ
298                 }
299
300         case *ast.Ellipsis:
301                 // dots are handled explicitly where they are legal
302                 // (array composite literals and parameter lists)
303                 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
304                 check.use(e.Elt)
305
306         case *ast.StructType:
307                 typ := new(Struct)
308                 def.setUnderlying(typ)
309                 check.structType(typ, e)
310                 return typ
311
312         case *ast.StarExpr:
313                 typ := new(Pointer)
314                 typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
315                 def.setUnderlying(typ)
316                 typ.base = check.varType(e.X)
317                 return typ
318
319         case *ast.FuncType:
320                 typ := new(Signature)
321                 def.setUnderlying(typ)
322                 check.funcType(typ, nil, e)
323                 return typ
324
325         case *ast.InterfaceType:
326                 typ := check.newInterface()
327                 def.setUnderlying(typ)
328                 if def != nil {
329                         typ.obj = def.obj
330                 }
331                 check.interfaceType(typ, e, def)
332                 return typ
333
334         case *ast.MapType:
335                 typ := new(Map)
336                 def.setUnderlying(typ)
337
338                 typ.key = check.varType(e.Key)
339                 typ.elem = check.varType(e.Value)
340
341                 // spec: "The comparison operators == and != must be fully defined
342                 // for operands of the key type; thus the key type must not be a
343                 // function, map, or slice."
344                 //
345                 // Delay this check because it requires fully setup types;
346                 // it is safe to continue in any case (was issue 6667).
347                 check.later(func() {
348                         if !Comparable(typ.key) {
349                                 var why string
350                                 if isTypeParam(typ.key) {
351                                         why = " (missing comparable constraint)"
352                                 }
353                                 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
354                         }
355                 })
356
357                 return typ
358
359         case *ast.ChanType:
360                 typ := new(Chan)
361                 def.setUnderlying(typ)
362
363                 dir := SendRecv
364                 switch e.Dir {
365                 case ast.SEND | ast.RECV:
366                         // nothing to do
367                 case ast.SEND:
368                         dir = SendOnly
369                 case ast.RECV:
370                         dir = RecvOnly
371                 default:
372                         check.invalidAST(e, "unknown channel direction %d", e.Dir)
373                         // ok to continue
374                 }
375
376                 typ.dir = dir
377                 typ.elem = check.varType(e.Value)
378                 return typ
379
380         default:
381                 check.errorf(e0, _NotAType, "%s is not a type", e0)
382         }
383
384         typ := Typ[Invalid]
385         def.setUnderlying(typ)
386         return typ
387 }
388
389 func (check *Checker) instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type) {
390         pos := ix.X.Pos()
391         if trace {
392                 check.trace(pos, "-- instantiating %s with %s", ix.X, ix.Indices)
393                 check.indent++
394                 defer func() {
395                         check.indent--
396                         // Don't format the underlying here. It will always be nil.
397                         check.trace(pos, "=> %s", res)
398                 }()
399         }
400
401         var reason string
402         gtyp := check.genericType(ix.X, &reason)
403         if reason != "" {
404                 check.invalidOp(ix.Orig, _NotAGenericType, "%s (%s)", ix.Orig, reason)
405         }
406         if gtyp == Typ[Invalid] {
407                 return gtyp // error already reported
408         }
409
410         orig, _ := gtyp.(*Named)
411         if orig == nil {
412                 panic(fmt.Sprintf("%v: cannot instantiate %v", ix.Pos(), gtyp))
413         }
414
415         // evaluate arguments
416         targs := check.typeList(ix.Indices)
417         if targs == nil {
418                 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
419                 return Typ[Invalid]
420         }
421
422         // create the instance
423         ctxt := check.bestContext(nil)
424         h := ctxt.instanceHash(orig, targs)
425         // targs may be incomplete, and require inference. In any case we should de-duplicate.
426         inst, _ := ctxt.lookup(h, orig, targs).(*Named)
427         // If inst is non-nil, we can't just return here. Inst may have been
428         // constructed via recursive substitution, in which case we wouldn't do the
429         // validation below. Ensure that the validation (and resulting errors) runs
430         // for each instantiated type in the source.
431         if inst == nil {
432                 // x may be a selector for an imported type; use its start pos rather than x.Pos().
433                 tname := NewTypeName(ix.Pos(), orig.obj.pkg, orig.obj.name, nil)
434                 inst = check.newNamed(tname, orig, nil, nil, nil) // underlying, methods and tparams are set when named is resolved
435                 inst.targs = newTypeList(targs)
436                 inst = ctxt.update(h, orig, targs, inst).(*Named)
437         }
438         def.setUnderlying(inst)
439
440         inst.resolver = func(ctxt *Context, n *Named) (*TypeParamList, Type, *methodList) {
441                 tparams := orig.TypeParams().list()
442
443                 if len(targs) < len(tparams) {
444                         // If inference fails, len(inferred) will be 0, and inst.underlying will
445                         // be set to Typ[Invalid] in expandNamed.
446                         inferred := check.infer(ix.Orig, tparams, targs, nil, nil)
447                         if len(inferred) > len(targs) {
448                                 inst.targs = newTypeList(inferred)
449                         }
450                 }
451
452                 return expandNamed(ctxt, n, pos)
453         }
454
455         // orig.tparams may not be set up, so we need to do expansion later.
456         check.later(func() {
457                 // This is an instance from the source, not from recursive substitution,
458                 // and so it must be resolved during type-checking so that we can report
459                 // errors.
460                 inst.resolve(ctxt)
461                 // Since check is non-nil, we can still mutate inst. Unpinning the resolver
462                 // frees some memory.
463                 inst.resolver = nil
464                 check.recordInstance(ix.Orig, inst.TypeArgs().list(), inst)
465
466                 if check.validateTArgLen(pos, inst.tparams.Len(), inst.targs.Len()) {
467                         if i, err := check.verify(pos, inst.tparams.list(), inst.targs.list()); err != nil {
468                                 // best position for error reporting
469                                 pos := ix.Pos()
470                                 if i < len(ix.Indices) {
471                                         pos = ix.Indices[i].Pos()
472                                 }
473                                 check.softErrorf(atPos(pos), _InvalidTypeArg, err.Error())
474                         } else {
475                                 check.mono.recordInstance(check.pkg, pos, inst.tparams.list(), inst.targs.list(), ix.Indices)
476                         }
477                 }
478
479                 check.validType(inst)
480         })
481
482         return inst
483 }
484
485 // arrayLength type-checks the array length expression e
486 // and returns the constant length >= 0, or a value < 0
487 // to indicate an error (and thus an unknown length).
488 func (check *Checker) arrayLength(e ast.Expr) int64 {
489         // If e is an identifier, the array declaration might be an
490         // attempt at a parameterized type declaration with missing
491         // constraint. Provide an error message that mentions array
492         // length.
493         if name, _ := e.(*ast.Ident); name != nil {
494                 obj := check.lookup(name.Name)
495                 if obj == nil {
496                         check.errorf(name, _InvalidArrayLen, "undeclared name %s for array length", name.Name)
497                         return -1
498                 }
499                 if _, ok := obj.(*Const); !ok {
500                         check.errorf(name, _InvalidArrayLen, "invalid array length %s", name.Name)
501                         return -1
502                 }
503         }
504
505         var x operand
506         check.expr(&x, e)
507         if x.mode != constant_ {
508                 if x.mode != invalid {
509                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
510                 }
511                 return -1
512         }
513
514         if isUntyped(x.typ) || isInteger(x.typ) {
515                 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
516                         if representableConst(val, check, Typ[Int], nil) {
517                                 if n, ok := constant.Int64Val(val); ok && n >= 0 {
518                                         return n
519                                 }
520                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
521                                 return -1
522                         }
523                 }
524         }
525
526         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
527         return -1
528 }
529
530 // typeList provides the list of types corresponding to the incoming expression list.
531 // If an error occurred, the result is nil, but all list elements were type-checked.
532 func (check *Checker) typeList(list []ast.Expr) []Type {
533         res := make([]Type, len(list)) // res != nil even if len(list) == 0
534         for i, x := range list {
535                 t := check.varType(x)
536                 if t == Typ[Invalid] {
537                         res = nil
538                 }
539                 if res != nil {
540                         res[i] = t
541                 }
542         }
543         return res
544 }