]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
go/types, types2: consider type parameters for cycle detection
[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                 x.mode = typexpr
100
101         case *Var:
102                 // It's ok to mark non-local variables, but ignore variables
103                 // from other packages to avoid potential race conditions with
104                 // dot-imported variables.
105                 if obj.pkg == check.pkg {
106                         obj.used = true
107                 }
108                 check.addDeclDep(obj)
109                 if typ == Typ[Invalid] {
110                         return
111                 }
112                 x.mode = variable
113
114         case *Func:
115                 check.addDeclDep(obj)
116                 x.mode = value
117
118         case *Builtin:
119                 x.id = obj.id
120                 x.mode = builtin
121
122         case *Nil:
123                 x.mode = value
124
125         default:
126                 unreachable()
127         }
128
129         x.typ = typ
130 }
131
132 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
133 // The type must not be an (uninstantiated) generic type.
134 func (check *Checker) typ(e ast.Expr) Type {
135         return check.definedType(e, nil)
136 }
137
138 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
139 // The type must not be an (uninstantiated) generic type and it must not be a
140 // constraint interface.
141 func (check *Checker) varType(e ast.Expr) Type {
142         typ := check.definedType(e, nil)
143
144         // If we have a type parameter there's nothing to do.
145         if isTypeParam(typ) {
146                 return typ
147         }
148
149         // We don't want to call under() or complete interfaces while we are in
150         // the middle of type-checking parameter declarations that might belong
151         // to interface methods. Delay this check to the end of type-checking.
152         check.later(func() {
153                 if t, _ := under(typ).(*Interface); t != nil {
154                         tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
155                         if !tset.IsMethodSet() {
156                                 if tset.comparable {
157                                         check.softErrorf(e, _MisplacedConstraintIface, "interface is (or embeds) comparable")
158                                 } else {
159                                         check.softErrorf(e, _MisplacedConstraintIface, "interface contains type constraints")
160                                 }
161                         }
162                 }
163         })
164
165         return typ
166 }
167
168 // definedType is like typ but also accepts a type name def.
169 // If def != nil, e is the type specification for the defined type def, declared
170 // in a type declaration, and def.underlying will be set to the type of e before
171 // any components of e are type-checked.
172 //
173 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
174         typ := check.typInternal(e, def)
175         assert(isTyped(typ))
176         if isGeneric(typ) {
177                 check.errorf(e, _WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
178                 typ = Typ[Invalid]
179         }
180         check.recordTypeAndValue(e, typexpr, typ, nil)
181         return typ
182 }
183
184 // genericType is like typ but the type must be an (uninstantiated) generic
185 // type. If reason is non-nil and the type expression was a valid type but not
186 // generic, reason will be populated with a message describing the error.
187 func (check *Checker) genericType(e ast.Expr, reason *string) Type {
188         typ := check.typInternal(e, nil)
189         assert(isTyped(typ))
190         if typ != Typ[Invalid] && !isGeneric(typ) {
191                 if reason != nil {
192                         *reason = check.sprintf("%s is not a generic type", typ)
193                 }
194                 typ = Typ[Invalid]
195         }
196         // TODO(gri) what is the correct call below?
197         check.recordTypeAndValue(e, typexpr, typ, nil)
198         return typ
199 }
200
201 // goTypeName returns the Go type name for typ and
202 // removes any occurrences of "types." from that name.
203 func goTypeName(typ Type) string {
204         return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
205 }
206
207 // typInternal drives type checking of types.
208 // Must only be called by definedType or genericType.
209 //
210 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
211         if trace {
212                 check.trace(e0.Pos(), "type %s", e0)
213                 check.indent++
214                 defer func() {
215                         check.indent--
216                         var under Type
217                         if T != nil {
218                                 // Calling under() here may lead to endless instantiations.
219                                 // Test case: type T[P any] *T[P]
220                                 under = safeUnderlying(T)
221                         }
222                         if T == under {
223                                 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
224                         } else {
225                                 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
226                         }
227                 }()
228         }
229
230         switch e := e0.(type) {
231         case *ast.BadExpr:
232                 // ignore - error reported before
233
234         case *ast.Ident:
235                 var x operand
236                 check.ident(&x, e, def, true)
237
238                 switch x.mode {
239                 case typexpr:
240                         typ := x.typ
241                         def.setUnderlying(typ)
242                         return typ
243                 case invalid:
244                         // ignore - error reported before
245                 case novalue:
246                         check.errorf(&x, _NotAType, "%s used as type", &x)
247                 default:
248                         check.errorf(&x, _NotAType, "%s is not a type", &x)
249                 }
250
251         case *ast.SelectorExpr:
252                 var x operand
253                 check.selector(&x, e)
254
255                 switch x.mode {
256                 case typexpr:
257                         typ := x.typ
258                         def.setUnderlying(typ)
259                         return typ
260                 case invalid:
261                         // ignore - error reported before
262                 case novalue:
263                         check.errorf(&x, _NotAType, "%s used as type", &x)
264                 default:
265                         check.errorf(&x, _NotAType, "%s is not a type", &x)
266                 }
267
268         case *ast.IndexExpr, *ast.IndexListExpr:
269                 ix := typeparams.UnpackIndexExpr(e)
270                 if !check.allowVersion(check.pkg, 1, 18) {
271                         check.softErrorf(inNode(e, ix.Lbrack), _UnsupportedFeature, "type instantiation requires go1.18 or later")
272                 }
273                 return check.instantiatedType(ix, def)
274
275         case *ast.ParenExpr:
276                 // Generic types must be instantiated before they can be used in any form.
277                 // Consequently, generic types cannot be parenthesized.
278                 return check.definedType(e.X, def)
279
280         case *ast.ArrayType:
281                 if e.Len == nil {
282                         typ := new(Slice)
283                         def.setUnderlying(typ)
284                         typ.elem = check.varType(e.Elt)
285                         return typ
286                 }
287
288                 typ := new(Array)
289                 def.setUnderlying(typ)
290                 typ.len = check.arrayLength(e.Len)
291                 typ.elem = check.varType(e.Elt)
292                 if typ.len >= 0 {
293                         return typ
294                 }
295
296         case *ast.Ellipsis:
297                 // dots are handled explicitly where they are legal
298                 // (array composite literals and parameter lists)
299                 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
300                 check.use(e.Elt)
301
302         case *ast.StructType:
303                 typ := new(Struct)
304                 def.setUnderlying(typ)
305                 check.structType(typ, e)
306                 return typ
307
308         case *ast.StarExpr:
309                 typ := new(Pointer)
310                 typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
311                 def.setUnderlying(typ)
312                 typ.base = check.varType(e.X)
313                 return typ
314
315         case *ast.FuncType:
316                 typ := new(Signature)
317                 def.setUnderlying(typ)
318                 check.funcType(typ, nil, e)
319                 return typ
320
321         case *ast.InterfaceType:
322                 typ := new(Interface)
323                 def.setUnderlying(typ)
324                 if def != nil {
325                         typ.obj = def.obj
326                 }
327                 check.interfaceType(typ, e, def)
328                 return typ
329
330         case *ast.MapType:
331                 typ := new(Map)
332                 def.setUnderlying(typ)
333
334                 typ.key = check.varType(e.Key)
335                 typ.elem = check.varType(e.Value)
336
337                 // spec: "The comparison operators == and != must be fully defined
338                 // for operands of the key type; thus the key type must not be a
339                 // function, map, or slice."
340                 //
341                 // Delay this check because it requires fully setup types;
342                 // it is safe to continue in any case (was issue 6667).
343                 check.later(func() {
344                         if !Comparable(typ.key) {
345                                 var why string
346                                 if isTypeParam(typ.key) {
347                                         why = " (missing comparable constraint)"
348                                 }
349                                 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
350                         }
351                 })
352
353                 return typ
354
355         case *ast.ChanType:
356                 typ := new(Chan)
357                 def.setUnderlying(typ)
358
359                 dir := SendRecv
360                 switch e.Dir {
361                 case ast.SEND | ast.RECV:
362                         // nothing to do
363                 case ast.SEND:
364                         dir = SendOnly
365                 case ast.RECV:
366                         dir = RecvOnly
367                 default:
368                         check.invalidAST(e, "unknown channel direction %d", e.Dir)
369                         // ok to continue
370                 }
371
372                 typ.dir = dir
373                 typ.elem = check.varType(e.Value)
374                 return typ
375
376         default:
377                 check.errorf(e0, _NotAType, "%s is not a type", e0)
378         }
379
380         typ := Typ[Invalid]
381         def.setUnderlying(typ)
382         return typ
383 }
384
385 func (check *Checker) instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type) {
386         pos := ix.X.Pos()
387         if trace {
388                 check.trace(pos, "-- instantiating %s with %s", ix.X, ix.Indices)
389                 check.indent++
390                 defer func() {
391                         check.indent--
392                         // Don't format the underlying here. It will always be nil.
393                         check.trace(pos, "=> %s", res)
394                 }()
395         }
396
397         var reason string
398         gtyp := check.genericType(ix.X, &reason)
399         if reason != "" {
400                 check.invalidOp(ix.Orig, _NotAGenericType, "%s (%s)", ix.Orig, reason)
401         }
402         if gtyp == Typ[Invalid] {
403                 return gtyp // error already reported
404         }
405
406         orig, _ := gtyp.(*Named)
407         if orig == nil {
408                 panic(fmt.Sprintf("%v: cannot instantiate %v", ix.Pos(), gtyp))
409         }
410
411         // evaluate arguments
412         targs := check.typeList(ix.Indices)
413         if targs == nil {
414                 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
415                 return Typ[Invalid]
416         }
417
418         // create the instance
419         ctxt := check.bestContext(nil)
420         h := ctxt.instanceHash(orig, targs)
421         // targs may be incomplete, and require inference. In any case we should de-duplicate.
422         inst, _ := ctxt.lookup(h, orig, targs).(*Named)
423         // If inst is non-nil, we can't just return here. Inst may have been
424         // constructed via recursive substitution, in which case we wouldn't do the
425         // validation below. Ensure that the validation (and resulting errors) runs
426         // for each instantiated type in the source.
427         if inst == nil {
428                 // x may be a selector for an imported type; use its start pos rather than x.Pos().
429                 tname := NewTypeName(ix.Pos(), orig.obj.pkg, orig.obj.name, nil)
430                 inst = check.newNamed(tname, orig, nil, nil, nil) // underlying, methods and tparams are set when named is resolved
431                 inst.targs = newTypeList(targs)
432                 inst = ctxt.update(h, orig, targs, inst).(*Named)
433         }
434         def.setUnderlying(inst)
435
436         inst.resolver = func(ctxt *Context, n *Named) (*TypeParamList, Type, []*Func) {
437                 tparams := orig.TypeParams().list()
438
439                 inferred := targs
440                 if len(targs) < len(tparams) {
441                         // If inference fails, len(inferred) will be 0, and inst.underlying will
442                         // be set to Typ[Invalid] in expandNamed.
443                         inferred = check.infer(ix.Orig, tparams, targs, nil, nil)
444                         if len(inferred) > len(targs) {
445                                 inst.targs = newTypeList(inferred)
446                         }
447                 }
448
449                 check.recordInstance(ix.Orig, inferred, inst)
450                 return expandNamed(ctxt, n, pos)
451         }
452
453         // orig.tparams may not be set up, so we need to do expansion later.
454         check.later(func() {
455                 // This is an instance from the source, not from recursive substitution,
456                 // and so it must be resolved during type-checking so that we can report
457                 // errors.
458                 inst.resolve(ctxt)
459                 // Since check is non-nil, we can still mutate inst. Unpinning the resolver
460                 // frees some memory.
461                 inst.resolver = nil
462
463                 if check.validateTArgLen(pos, inst.tparams.Len(), inst.targs.Len()) {
464                         if i, err := check.verify(pos, inst.tparams.list(), inst.targs.list()); err != nil {
465                                 // best position for error reporting
466                                 pos := ix.Pos()
467                                 if i < len(ix.Indices) {
468                                         pos = ix.Indices[i].Pos()
469                                 }
470                                 check.softErrorf(atPos(pos), _InvalidTypeArg, err.Error())
471                         } else {
472                                 check.mono.recordInstance(check.pkg, pos, inst.tparams.list(), inst.targs.list(), ix.Indices)
473                         }
474                 }
475
476                 check.validType(inst)
477         })
478
479         return inst
480 }
481
482 // arrayLength type-checks the array length expression e
483 // and returns the constant length >= 0, or a value < 0
484 // to indicate an error (and thus an unknown length).
485 func (check *Checker) arrayLength(e ast.Expr) int64 {
486         // If e is an undeclared identifier, the array declaration might be an
487         // attempt at a parameterized type declaration with missing constraint.
488         // Provide a better error message than just "undeclared name: X".
489         if name, _ := e.(*ast.Ident); name != nil && check.lookup(name.Name) == nil {
490                 check.errorf(name, _InvalidArrayLen, "undeclared name %s for array length", name.Name)
491                 return -1
492         }
493
494         var x operand
495         check.expr(&x, e)
496         if x.mode != constant_ {
497                 if x.mode != invalid {
498                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
499                 }
500                 return -1
501         }
502
503         if isUntyped(x.typ) || isInteger(x.typ) {
504                 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
505                         if representableConst(val, check, Typ[Int], nil) {
506                                 if n, ok := constant.Int64Val(val); ok && n >= 0 {
507                                         return n
508                                 }
509                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
510                                 return -1
511                         }
512                 }
513         }
514
515         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
516         return -1
517 }
518
519 // typeList provides the list of types corresponding to the incoming expression list.
520 // If an error occurred, the result is nil, but all list elements were type-checked.
521 func (check *Checker) typeList(list []ast.Expr) []Type {
522         res := make([]Type, len(list)) // res != nil even if len(list) == 0
523         for i, x := range list {
524                 t := check.varType(x)
525                 if t == Typ[Invalid] {
526                         res = nil
527                 }
528                 if res != nil {
529                         res[i] = t
530                 }
531         }
532         return res
533 }