]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/typexpr.go
go/types: underlying type of a type parameter is its constraint interface
[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                         // Blank identifiers are never declared, but the current identifier may
34                         // be a placeholder for a receiver type parameter. In this case we can
35                         // resolve its type and object from Checker.recvTParamMap.
36                         if tpar := check.recvTParamMap[e]; tpar != nil {
37                                 x.mode = typexpr
38                                 x.typ = tpar
39                         } else {
40                                 check.error(e, _InvalidBlank, "cannot use _ as value or type")
41                         }
42                 } else {
43                         check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
44                 }
45                 return
46         case universeAny, universeComparable:
47                 if !check.allowVersion(check.pkg, 1, 18) {
48                         check.errorf(e, _UndeclaredName, "undeclared name: %s (requires version go1.18 or later)", e.Name)
49                         return // avoid follow-on errors
50                 }
51         }
52         check.recordUse(e, obj)
53
54         // Type-check the object.
55         // Only call Checker.objDecl if the object doesn't have a type yet
56         // (in which case we must actually determine it) or the object is a
57         // TypeName and we also want a type (in which case we might detect
58         // a cycle which needs to be reported). Otherwise we can skip the
59         // call and avoid a possible cycle error in favor of the more
60         // informative "not a type/value" error that this function's caller
61         // will issue (see issue #25790).
62         typ := obj.Type()
63         if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
64                 check.objDecl(obj, def)
65                 typ = obj.Type() // type must have been assigned by Checker.objDecl
66         }
67         assert(typ != nil)
68
69         // The object may have been dot-imported.
70         // If so, mark the respective package as used.
71         // (This code is only needed for dot-imports. Without them,
72         // we only have to mark variables, see *Var case below).
73         if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
74                 pkgName.used = true
75         }
76
77         switch obj := obj.(type) {
78         case *PkgName:
79                 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
80                 return
81
82         case *Const:
83                 check.addDeclDep(obj)
84                 if typ == Typ[Invalid] {
85                         return
86                 }
87                 if obj == universeIota {
88                         if check.iota == nil {
89                                 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
90                                 return
91                         }
92                         x.val = check.iota
93                 } else {
94                         x.val = obj.val
95                 }
96                 assert(x.val != nil)
97                 x.mode = constant_
98
99         case *TypeName:
100                 x.mode = typexpr
101
102         case *Var:
103                 // It's ok to mark non-local variables, but ignore variables
104                 // from other packages to avoid potential race conditions with
105                 // dot-imported variables.
106                 if obj.pkg == check.pkg {
107                         obj.used = true
108                 }
109                 check.addDeclDep(obj)
110                 if typ == Typ[Invalid] {
111                         return
112                 }
113                 x.mode = variable
114
115         case *Func:
116                 check.addDeclDep(obj)
117                 x.mode = value
118
119         case *Builtin:
120                 x.id = obj.id
121                 x.mode = builtin
122
123         case *Nil:
124                 x.mode = value
125
126         default:
127                 unreachable()
128         }
129
130         x.typ = typ
131 }
132
133 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
134 // The type must not be an (uninstantiated) generic type.
135 func (check *Checker) typ(e ast.Expr) Type {
136         return check.definedType(e, nil)
137 }
138
139 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
140 // The type must not be an (uninstantiated) generic type and it must not be a
141 // constraint interface.
142 func (check *Checker) varType(e ast.Expr) Type {
143         typ := check.definedType(e, nil)
144
145         // If we have a type parameter there's nothing to do.
146         if isTypeParam(typ) {
147                 return typ
148         }
149
150         // We don't want to call under() or complete interfaces while we are in
151         // the middle of type-checking parameter declarations that might belong
152         // to interface methods. Delay this check to the end of type-checking.
153         check.later(func() {
154                 if t, _ := under(typ).(*Interface); t != nil {
155                         tset := computeInterfaceTypeSet(check, e.Pos(), t) // TODO(gri) is this the correct position?
156                         if !tset.IsMethodSet() {
157                                 if tset.comparable {
158                                         check.softErrorf(e, _MisplacedConstraintIface, "interface is (or embeds) comparable")
159                                 } else {
160                                         check.softErrorf(e, _MisplacedConstraintIface, "interface contains type constraints")
161                                 }
162                         }
163                 }
164         })
165
166         return typ
167 }
168
169 // definedType is like typ but also accepts a type name def.
170 // If def != nil, e is the type specification for the defined type def, declared
171 // in a type declaration, and def.underlying will be set to the type of e before
172 // any components of e are type-checked.
173 //
174 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
175         typ := check.typInternal(e, def)
176         assert(isTyped(typ))
177         if isGeneric(typ) {
178                 check.errorf(e, _WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
179                 typ = Typ[Invalid]
180         }
181         check.recordTypeAndValue(e, typexpr, typ, nil)
182         return typ
183 }
184
185 // genericType is like typ but the type must be an (uninstantiated) generic
186 // type. If reason is non-nil and the type expression was a valid type but not
187 // generic, reason will be populated with a message describing the error.
188 func (check *Checker) genericType(e ast.Expr, reason *string) Type {
189         typ := check.typInternal(e, nil)
190         assert(isTyped(typ))
191         if typ != Typ[Invalid] && !isGeneric(typ) {
192                 if reason != nil {
193                         *reason = check.sprintf("%s is not a generic type", typ)
194                 }
195                 typ = Typ[Invalid]
196         }
197         // TODO(gri) what is the correct call below?
198         check.recordTypeAndValue(e, typexpr, typ, nil)
199         return typ
200 }
201
202 // goTypeName returns the Go type name for typ and
203 // removes any occurrences of "types." from that name.
204 func goTypeName(typ Type) string {
205         return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
206 }
207
208 // typInternal drives type checking of types.
209 // Must only be called by definedType or genericType.
210 //
211 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
212         if trace {
213                 check.trace(e0.Pos(), "type %s", e0)
214                 check.indent++
215                 defer func() {
216                         check.indent--
217                         var under Type
218                         if T != nil {
219                                 // Calling under() here may lead to endless instantiations.
220                                 // Test case: type T[P any] *T[P]
221                                 under = safeUnderlying(T)
222                         }
223                         if T == under {
224                                 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
225                         } else {
226                                 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
227                         }
228                 }()
229         }
230
231         switch e := e0.(type) {
232         case *ast.BadExpr:
233                 // ignore - error reported before
234
235         case *ast.Ident:
236                 var x operand
237                 check.ident(&x, e, def, true)
238
239                 switch x.mode {
240                 case typexpr:
241                         typ := x.typ
242                         def.setUnderlying(typ)
243                         return typ
244                 case invalid:
245                         // ignore - error reported before
246                 case novalue:
247                         check.errorf(&x, _NotAType, "%s used as type", &x)
248                 default:
249                         check.errorf(&x, _NotAType, "%s is not a type", &x)
250                 }
251
252         case *ast.SelectorExpr:
253                 var x operand
254                 check.selector(&x, e)
255
256                 switch x.mode {
257                 case typexpr:
258                         typ := x.typ
259                         def.setUnderlying(typ)
260                         return typ
261                 case invalid:
262                         // ignore - error reported before
263                 case novalue:
264                         check.errorf(&x, _NotAType, "%s used as type", &x)
265                 default:
266                         check.errorf(&x, _NotAType, "%s is not a type", &x)
267                 }
268
269         case *ast.IndexExpr, *ast.IndexListExpr:
270                 ix := typeparams.UnpackIndexExpr(e)
271                 if !check.allowVersion(check.pkg, 1, 18) {
272                         check.softErrorf(inNode(e, ix.Lbrack), _UnsupportedFeature, "type instantiation requires go1.18 or later")
273                 }
274                 return check.instantiatedType(ix, def)
275
276         case *ast.ParenExpr:
277                 // Generic types must be instantiated before they can be used in any form.
278                 // Consequently, generic types cannot be parenthesized.
279                 return check.definedType(e.X, def)
280
281         case *ast.ArrayType:
282                 if e.Len == nil {
283                         typ := new(Slice)
284                         def.setUnderlying(typ)
285                         typ.elem = check.varType(e.Elt)
286                         return typ
287                 }
288
289                 typ := new(Array)
290                 def.setUnderlying(typ)
291                 typ.len = check.arrayLength(e.Len)
292                 typ.elem = check.varType(e.Elt)
293                 if typ.len >= 0 {
294                         return typ
295                 }
296
297         case *ast.Ellipsis:
298                 // dots are handled explicitly where they are legal
299                 // (array composite literals and parameter lists)
300                 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
301                 check.use(e.Elt)
302
303         case *ast.StructType:
304                 typ := new(Struct)
305                 def.setUnderlying(typ)
306                 check.structType(typ, e)
307                 return typ
308
309         case *ast.StarExpr:
310                 typ := new(Pointer)
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         // determine argument positions
419         posList := make([]token.Pos, len(targs))
420         for i, arg := range ix.Indices {
421                 posList[i] = arg.Pos()
422         }
423
424         // create the instance
425         ctxt := check.bestContext(nil)
426         h := ctxt.instanceHash(orig, targs)
427         // targs may be incomplete, and require inference. In any case we should de-duplicate.
428         inst, _ := ctxt.lookup(h, orig, targs).(*Named)
429         // If inst is non-nil, we can't just return here. Inst may have been
430         // constructed via recursive substitution, in which case we wouldn't do the
431         // validation below. Ensure that the validation (and resulting errors) runs
432         // for each instantiated type in the source.
433         if inst == nil {
434                 tname := NewTypeName(ix.X.Pos(), orig.obj.pkg, orig.obj.name, nil)
435                 inst = check.newNamed(tname, orig, nil, nil, nil) // underlying, methods and tparams are set when named is resolved
436                 inst.targs = NewTypeList(targs)
437                 inst = ctxt.update(h, orig, targs, inst).(*Named)
438         }
439         def.setUnderlying(inst)
440
441         inst.resolver = func(ctxt *Context, n *Named) (*TypeParamList, Type, []*Func) {
442                 tparams := orig.TypeParams().list()
443
444                 inferred := targs
445                 if len(targs) < len(tparams) {
446                         // If inference fails, len(inferred) will be 0, and inst.underlying will
447                         // be set to Typ[Invalid] in expandNamed.
448                         inferred = check.infer(ix.Orig, tparams, targs, nil, nil)
449                         if len(inferred) > len(targs) {
450                                 inst.targs = NewTypeList(inferred)
451                         }
452                 }
453
454                 check.recordInstance(ix.Orig, inferred, inst)
455                 return expandNamed(ctxt, n, pos)
456         }
457
458         // orig.tparams may not be set up, so we need to do expansion later.
459         check.later(func() {
460                 // This is an instance from the source, not from recursive substitution,
461                 // and so it must be resolved during type-checking so that we can report
462                 // errors.
463                 inst.resolve(ctxt)
464                 // Since check is non-nil, we can still mutate inst. Unpinning the resolver
465                 // frees some memory.
466                 inst.resolver = nil
467
468                 if check.validateTArgLen(pos, inst.tparams.Len(), inst.targs.Len()) {
469                         if i, err := check.verify(pos, inst.tparams.list(), inst.targs.list()); err != nil {
470                                 // best position for error reporting
471                                 pos := ix.Pos()
472                                 if i < len(posList) {
473                                         pos = posList[i]
474                                 }
475                                 check.softErrorf(atPos(pos), _InvalidTypeArg, err.Error())
476                         } else {
477                                 check.mono.recordInstance(check.pkg, pos, inst.tparams.list(), inst.targs.list(), posList)
478                         }
479                 }
480
481                 check.validType(inst, nil)
482         })
483
484         return inst
485 }
486
487 // arrayLength type-checks the array length expression e
488 // and returns the constant length >= 0, or a value < 0
489 // to indicate an error (and thus an unknown length).
490 func (check *Checker) arrayLength(e ast.Expr) int64 {
491         // If e is an undeclared identifier, the array declaration might be an
492         // attempt at a parameterized type declaration with missing constraint.
493         // Provide a better error message than just "undeclared name: X".
494         if name, _ := e.(*ast.Ident); name != nil && check.lookup(name.Name) == nil {
495                 check.errorf(name, _InvalidArrayLen, "undeclared name %s for array length", name.Name)
496                 return -1
497         }
498
499         var x operand
500         check.expr(&x, e)
501         if x.mode != constant_ {
502                 if x.mode != invalid {
503                         check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
504                 }
505                 return -1
506         }
507
508         if isUntyped(x.typ) || isInteger(x.typ) {
509                 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
510                         if representableConst(val, check, Typ[Int], nil) {
511                                 if n, ok := constant.Int64Val(val); ok && n >= 0 {
512                                         return n
513                                 }
514                                 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
515                                 return -1
516                         }
517                 }
518         }
519
520         check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
521         return -1
522 }
523
524 // typeList provides the list of types corresponding to the incoming expression list.
525 // If an error occurred, the result is nil, but all list elements were type-checked.
526 func (check *Checker) typeList(list []ast.Expr) []Type {
527         res := make([]Type, len(list)) // res != nil even if len(list) == 0
528         for i, x := range list {
529                 t := check.varType(x)
530                 if t == Typ[Invalid] {
531                         res = nil
532                 }
533                 if res != nil {
534                         res[i] = t
535                 }
536         }
537         return res
538 }