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