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