Source file
src/go/types/typexpr.go
1
2
3
4
5
6
7 package types
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 . "internal/types/errors"
14 "strings"
15 )
16
17
18
19
20
21 func (check *Checker) ident(x *operand, e *ast.Ident, def *TypeName, wantType bool) {
22 x.mode = invalid
23 x.expr = e
24
25 scope, obj := check.lookupScope(e.Name)
26 switch obj {
27 case nil:
28 if e.Name == "_" {
29 check.error(e, InvalidBlank, "cannot use _ as value or type")
30 } else if isValidName(e.Name) {
31 check.errorf(e, UndeclaredName, "undefined: %s", e.Name)
32 }
33 return
34 case universeComparable:
35 if !check.verifyVersionf(e, go1_18, "predeclared %s", e.Name) {
36 return
37 }
38 }
39
40
41 if obj.Name() == "any" && obj.Parent() == Universe {
42 if !check.verifyVersionf(e, go1_18, "predeclared %s", e.Name) {
43 return
44 }
45 }
46 check.recordUse(e, obj)
47
48
49
50
51 _, gotType := obj.(*TypeName)
52 if !gotType && wantType {
53 check.errorf(e, NotAType, "%s is not a type", obj.Name())
54
55
56 if v, _ := obj.(*Var); v != nil && v.pkg == check.pkg {
57 check.usedVars[v] = true
58 }
59 return
60 }
61
62
63
64
65
66
67
68
69
70
71
72
73 typ := obj.Type()
74 if typ == nil || (gotType && wantType && obj.Pkg() == check.pkg) {
75 check.objDecl(obj, def)
76 typ = obj.Type()
77 }
78 assert(typ != nil)
79
80
81
82
83
84 if pkgName := check.dotImportMap[dotImportKey{scope, obj.Name()}]; pkgName != nil {
85 check.usedPkgNames[pkgName] = true
86 }
87
88 switch obj := obj.(type) {
89 case *PkgName:
90 check.errorf(e, InvalidPkgUse, "use of package %s not in selector", obj.name)
91 return
92
93 case *Const:
94 check.addDeclDep(obj)
95 if !isValid(typ) {
96 return
97 }
98 if obj == universeIota {
99 if check.iota == nil {
100 check.error(e, InvalidIota, "cannot use iota outside constant declaration")
101 return
102 }
103 x.val = check.iota
104 } else {
105 x.val = obj.val
106 }
107 assert(x.val != nil)
108 x.mode = constant_
109
110 case *TypeName:
111 if !check.conf._EnableAlias && check.isBrokenAlias(obj) {
112 check.errorf(e, InvalidDeclCycle, "invalid use of type alias %s in recursive type (see go.dev/issue/50729)", obj.name)
113 return
114 }
115 x.mode = typexpr
116
117 case *Var:
118
119
120
121 if obj.pkg == check.pkg {
122 check.usedVars[obj] = true
123 }
124 check.addDeclDep(obj)
125 if !isValid(typ) {
126 return
127 }
128 x.mode = variable
129
130 case *Func:
131 check.addDeclDep(obj)
132 x.mode = value
133
134 case *Builtin:
135 x.id = obj.id
136 x.mode = builtin
137
138 case *Nil:
139 x.mode = value
140
141 default:
142 panic("unreachable")
143 }
144
145 x.typ = typ
146 }
147
148
149
150 func (check *Checker) typ(e ast.Expr) Type {
151 return check.definedType(e, nil)
152 }
153
154
155
156
157 func (check *Checker) varType(e ast.Expr) Type {
158 typ := check.definedType(e, nil)
159 check.validVarType(e, typ)
160 return typ
161 }
162
163
164
165 func (check *Checker) validVarType(e ast.Expr, typ Type) {
166
167 if isTypeParam(typ) {
168 return
169 }
170
171
172
173
174 check.later(func() {
175 if t, _ := under(typ).(*Interface); t != nil {
176 tset := computeInterfaceTypeSet(check, e.Pos(), t)
177 if !tset.IsMethodSet() {
178 if tset.comparable {
179 check.softErrorf(e, MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface is (or embeds) comparable", typ)
180 } else {
181 check.softErrorf(e, MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface contains type constraints", typ)
182 }
183 }
184 }
185 }).describef(e, "check var type %s", typ)
186 }
187
188
189
190
191
192 func (check *Checker) definedType(e ast.Expr, def *TypeName) Type {
193 typ := check.typInternal(e, def)
194 assert(isTyped(typ))
195 if isGeneric(typ) {
196 check.errorf(e, WrongTypeArgCount, "cannot use generic type %s without instantiation", typ)
197 typ = Typ[Invalid]
198 }
199 check.recordTypeAndValue(e, typexpr, typ, nil)
200 return typ
201 }
202
203
204
205
206
207
208
209
210 func (check *Checker) genericType(e ast.Expr, cause *string) Type {
211 typ := check.typInternal(e, nil)
212 assert(isTyped(typ))
213 if isValid(typ) && !isGeneric(typ) {
214 if cause != nil {
215 *cause = check.sprintf("%s is not a generic type", typ)
216 }
217 typ = Typ[Invalid]
218 }
219
220 check.recordTypeAndValue(e, typexpr, typ, nil)
221 return typ
222 }
223
224
225
226 func goTypeName(typ Type) string {
227 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
228 }
229
230
231
232 func (check *Checker) typInternal(e0 ast.Expr, def *TypeName) (T Type) {
233 if check.conf._Trace {
234 check.trace(e0.Pos(), "-- type %s", e0)
235 check.indent++
236 defer func() {
237 check.indent--
238 var under Type
239 if T != nil {
240
241
242 under = safeUnderlying(T)
243 }
244 if T == under {
245 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
246 } else {
247 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
248 }
249 }()
250 }
251
252 switch e := e0.(type) {
253 case *ast.BadExpr:
254
255
256 case *ast.Ident:
257 var x operand
258 check.ident(&x, e, def, true)
259
260 switch x.mode {
261 case typexpr:
262 typ := x.typ
263 setDefType(def, typ)
264 return typ
265 case invalid:
266
267 case novalue:
268 check.errorf(&x, NotAType, "%s used as type", &x)
269 default:
270 check.errorf(&x, NotAType, "%s is not a type", &x)
271 }
272
273 case *ast.SelectorExpr:
274 var x operand
275 check.selector(&x, e, def, true)
276
277 switch x.mode {
278 case typexpr:
279 typ := x.typ
280 setDefType(def, typ)
281 return typ
282 case invalid:
283
284 case novalue:
285 check.errorf(&x, NotAType, "%s used as type", &x)
286 default:
287 check.errorf(&x, NotAType, "%s is not a type", &x)
288 }
289
290 case *ast.IndexExpr, *ast.IndexListExpr:
291 ix := unpackIndexedExpr(e)
292 check.verifyVersionf(inNode(e, ix.lbrack), go1_18, "type instantiation")
293 return check.instantiatedType(ix, def)
294
295 case *ast.ParenExpr:
296
297
298 return check.definedType(e.X, def)
299
300 case *ast.ArrayType:
301 if e.Len == nil {
302 typ := new(Slice)
303 setDefType(def, typ)
304 typ.elem = check.varType(e.Elt)
305 return typ
306 }
307
308 typ := new(Array)
309 setDefType(def, typ)
310
311
312 if _, ok := e.Len.(*ast.Ellipsis); ok {
313 check.error(e.Len, BadDotDotDotSyntax, "invalid use of [...] array (outside a composite literal)")
314 typ.len = -1
315 } else {
316 typ.len = check.arrayLength(e.Len)
317 }
318 typ.elem = check.varType(e.Elt)
319 if typ.len >= 0 {
320 return typ
321 }
322
323
324 case *ast.Ellipsis:
325
326 check.error(e, InvalidSyntaxTree, "invalid use of ...")
327
328 case *ast.StructType:
329 typ := new(Struct)
330 setDefType(def, typ)
331 check.structType(typ, e)
332 return typ
333
334 case *ast.StarExpr:
335 typ := new(Pointer)
336 typ.base = Typ[Invalid]
337 setDefType(def, typ)
338 typ.base = check.varType(e.X)
339
340
341
342
343 if !isValid(typ.base) {
344 return Typ[Invalid]
345 }
346 return typ
347
348 case *ast.FuncType:
349 typ := new(Signature)
350 setDefType(def, typ)
351 check.funcType(typ, nil, e)
352 return typ
353
354 case *ast.InterfaceType:
355 typ := check.newInterface()
356 setDefType(def, typ)
357 check.interfaceType(typ, e, def)
358 return typ
359
360 case *ast.MapType:
361 typ := new(Map)
362 setDefType(def, typ)
363
364 typ.key = check.varType(e.Key)
365 typ.elem = check.varType(e.Value)
366
367
368
369
370
371
372
373 check.later(func() {
374 if !Comparable(typ.key) {
375 var why string
376 if isTypeParam(typ.key) {
377 why = " (missing comparable constraint)"
378 }
379 check.errorf(e.Key, IncomparableMapKey, "invalid map key type %s%s", typ.key, why)
380 }
381 }).describef(e.Key, "check map key %s", typ.key)
382
383 return typ
384
385 case *ast.ChanType:
386 typ := new(Chan)
387 setDefType(def, typ)
388
389 dir := SendRecv
390 switch e.Dir {
391 case ast.SEND | ast.RECV:
392
393 case ast.SEND:
394 dir = SendOnly
395 case ast.RECV:
396 dir = RecvOnly
397 default:
398 check.errorf(e, InvalidSyntaxTree, "unknown channel direction %d", e.Dir)
399
400 }
401
402 typ.dir = dir
403 typ.elem = check.varType(e.Value)
404 return typ
405
406 default:
407 check.errorf(e0, NotAType, "%s is not a type", e0)
408 check.use(e0)
409 }
410
411 typ := Typ[Invalid]
412 setDefType(def, typ)
413 return typ
414 }
415
416 func setDefType(def *TypeName, typ Type) {
417 if def != nil {
418 switch t := def.typ.(type) {
419 case *Alias:
420 t.fromRHS = typ
421 case *Basic:
422 assert(t == Typ[Invalid])
423 case *Named:
424 t.underlying = typ
425 default:
426 panic(fmt.Sprintf("unexpected type %T", t))
427 }
428 }
429 }
430
431 func (check *Checker) instantiatedType(ix *indexedExpr, def *TypeName) (res Type) {
432 if check.conf._Trace {
433 check.trace(ix.Pos(), "-- instantiating type %s with %s", ix.x, ix.indices)
434 check.indent++
435 defer func() {
436 check.indent--
437
438 check.trace(ix.Pos(), "=> %s", res)
439 }()
440 }
441
442 defer func() {
443 setDefType(def, res)
444 }()
445
446 var cause string
447 typ := check.genericType(ix.x, &cause)
448 if cause != "" {
449 check.errorf(ix.orig, NotAGenericType, invalidOp+"%s (%s)", ix.orig, cause)
450 }
451 if !isValid(typ) {
452 return typ
453 }
454
455 if _, ok := typ.(*Signature); ok {
456 panic("unexpected generic signature")
457 }
458 gtyp := typ.(genericType)
459
460
461 targs := check.typeList(ix.indices)
462 if targs == nil {
463 return Typ[Invalid]
464 }
465
466
467
468
469
470 ityp := check.instance(ix.Pos(), gtyp, targs, nil, check.context())
471 inst, _ := ityp.(genericType)
472 if inst == nil {
473 return Typ[Invalid]
474 }
475
476
477 check.later(func() {
478
479
480
481 check.recordInstance(ix.orig, targs, inst)
482
483 name := inst.(interface{ Obj() *TypeName }).Obj().name
484 tparams := inst.TypeParams().list()
485 if check.validateTArgLen(ix.Pos(), name, len(tparams), len(targs)) {
486
487 if i, err := check.verify(ix.Pos(), inst.TypeParams().list(), targs, check.context()); err != nil {
488
489 pos := ix.Pos()
490 if i < len(ix.indices) {
491 pos = ix.indices[i].Pos()
492 }
493 check.softErrorf(atPos(pos), InvalidTypeArg, "%v", err)
494 } else {
495 check.mono.recordInstance(check.pkg, ix.Pos(), tparams, targs, ix.indices)
496 }
497 }
498 }).describef(ix, "verify instantiation %s", inst)
499
500 return inst
501 }
502
503
504
505
506 func (check *Checker) arrayLength(e ast.Expr) int64 {
507
508
509
510
511 if name, _ := e.(*ast.Ident); name != nil {
512 obj := check.lookup(name.Name)
513 if obj == nil {
514 check.errorf(name, InvalidArrayLen, "undefined array length %s or missing type constraint", name.Name)
515 return -1
516 }
517 if _, ok := obj.(*Const); !ok {
518 check.errorf(name, InvalidArrayLen, "invalid array length %s", name.Name)
519 return -1
520 }
521 }
522
523 var x operand
524 check.expr(nil, &x, e)
525 if x.mode != constant_ {
526 if x.mode != invalid {
527 check.errorf(&x, InvalidArrayLen, "array length %s must be constant", &x)
528 }
529 return -1
530 }
531
532 if isUntyped(x.typ) || isInteger(x.typ) {
533 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
534 if representableConst(val, check, Typ[Int], nil) {
535 if n, ok := constant.Int64Val(val); ok && n >= 0 {
536 return n
537 }
538 }
539 }
540 }
541
542 var msg string
543 if isInteger(x.typ) {
544 msg = "invalid array length %s"
545 } else {
546 msg = "array length %s must be integer"
547 }
548 check.errorf(&x, InvalidArrayLen, msg, &x)
549 return -1
550 }
551
552
553
554 func (check *Checker) typeList(list []ast.Expr) []Type {
555 res := make([]Type, len(list))
556 for i, x := range list {
557 t := check.varType(x)
558 if !isValid(t) {
559 res = nil
560 }
561 if res != nil {
562 res[i] = t
563 }
564 }
565 return res
566 }
567
View as plain text