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 v.used = 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 pkgName.used = 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 obj.used = 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 func (check *Checker) genericType(e ast.Expr, cause *string) Type {
207 typ := check.typInternal(e, nil)
208 assert(isTyped(typ))
209 if isValid(typ) && !isGeneric(typ) {
210 if cause != nil {
211 *cause = check.sprintf("%s is not a generic type", typ)
212 }
213 typ = Typ[Invalid]
214 }
215
216 check.recordTypeAndValue(e, typexpr, typ, nil)
217 return typ
218 }
219
220
221
222 func goTypeName(typ Type) string {
223 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
224 }
225
226
227
228 func (check *Checker) typInternal(e0 ast.Expr, def *TypeName) (T Type) {
229 if check.conf._Trace {
230 check.trace(e0.Pos(), "-- type %s", e0)
231 check.indent++
232 defer func() {
233 check.indent--
234 var under Type
235 if T != nil {
236
237
238 under = safeUnderlying(T)
239 }
240 if T == under {
241 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
242 } else {
243 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
244 }
245 }()
246 }
247
248 switch e := e0.(type) {
249 case *ast.BadExpr:
250
251
252 case *ast.Ident:
253 var x operand
254 check.ident(&x, e, def, true)
255
256 switch x.mode {
257 case typexpr:
258 typ := x.typ
259 setDefType(def, typ)
260 return typ
261 case invalid:
262
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.SelectorExpr:
270 var x operand
271 check.selector(&x, e, def, true)
272
273 switch x.mode {
274 case typexpr:
275 typ := x.typ
276 setDefType(def, typ)
277 return typ
278 case invalid:
279
280 case novalue:
281 check.errorf(&x, NotAType, "%s used as type", &x)
282 default:
283 check.errorf(&x, NotAType, "%s is not a type", &x)
284 }
285
286 case *ast.IndexExpr, *ast.IndexListExpr:
287 ix := unpackIndexedExpr(e)
288 check.verifyVersionf(inNode(e, ix.lbrack), go1_18, "type instantiation")
289 return check.instantiatedType(ix, def)
290
291 case *ast.ParenExpr:
292
293
294 return check.definedType(e.X, def)
295
296 case *ast.ArrayType:
297 if e.Len == nil {
298 typ := new(Slice)
299 setDefType(def, typ)
300 typ.elem = check.varType(e.Elt)
301 return typ
302 }
303
304 typ := new(Array)
305 setDefType(def, typ)
306
307
308 if _, ok := e.Len.(*ast.Ellipsis); ok {
309 check.error(e.Len, BadDotDotDotSyntax, "invalid use of [...] array (outside a composite literal)")
310 typ.len = -1
311 } else {
312 typ.len = check.arrayLength(e.Len)
313 }
314 typ.elem = check.varType(e.Elt)
315 if typ.len >= 0 {
316 return typ
317 }
318
319
320 case *ast.Ellipsis:
321
322
323 check.error(e, InvalidDotDotDot, "invalid use of '...'")
324 check.use(e.Elt)
325
326 case *ast.StructType:
327 typ := new(Struct)
328 setDefType(def, typ)
329 check.structType(typ, e)
330 return typ
331
332 case *ast.StarExpr:
333 typ := new(Pointer)
334 typ.base = Typ[Invalid]
335 setDefType(def, typ)
336 typ.base = check.varType(e.X)
337
338
339
340
341 if !isValid(typ.base) {
342 return Typ[Invalid]
343 }
344 return typ
345
346 case *ast.FuncType:
347 typ := new(Signature)
348 setDefType(def, typ)
349 check.funcType(typ, nil, e)
350 return typ
351
352 case *ast.InterfaceType:
353 typ := check.newInterface()
354 setDefType(def, typ)
355 check.interfaceType(typ, e, def)
356 return typ
357
358 case *ast.MapType:
359 typ := new(Map)
360 setDefType(def, typ)
361
362 typ.key = check.varType(e.Key)
363 typ.elem = check.varType(e.Value)
364
365
366
367
368
369
370
371 check.later(func() {
372 if !Comparable(typ.key) {
373 var why string
374 if isTypeParam(typ.key) {
375 why = " (missing comparable constraint)"
376 }
377 check.errorf(e.Key, IncomparableMapKey, "invalid map key type %s%s", typ.key, why)
378 }
379 }).describef(e.Key, "check map key %s", typ.key)
380
381 return typ
382
383 case *ast.ChanType:
384 typ := new(Chan)
385 setDefType(def, typ)
386
387 dir := SendRecv
388 switch e.Dir {
389 case ast.SEND | ast.RECV:
390
391 case ast.SEND:
392 dir = SendOnly
393 case ast.RECV:
394 dir = RecvOnly
395 default:
396 check.errorf(e, InvalidSyntaxTree, "unknown channel direction %d", e.Dir)
397
398 }
399
400 typ.dir = dir
401 typ.elem = check.varType(e.Value)
402 return typ
403
404 default:
405 check.errorf(e0, NotAType, "%s is not a type", e0)
406 check.use(e0)
407 }
408
409 typ := Typ[Invalid]
410 setDefType(def, typ)
411 return typ
412 }
413
414 func setDefType(def *TypeName, typ Type) {
415 if def != nil {
416 switch t := def.typ.(type) {
417 case *Alias:
418
419
420 if t.fromRHS != Typ[Invalid] && t.fromRHS != typ {
421 panic(sprintf(nil, nil, true, "t.fromRHS = %s, typ = %s\n", t.fromRHS, typ))
422 }
423 t.fromRHS = typ
424 case *Basic:
425 assert(t == Typ[Invalid])
426 case *Named:
427 t.underlying = typ
428 default:
429 panic(fmt.Sprintf("unexpected type %T", t))
430 }
431 }
432 }
433
434 func (check *Checker) instantiatedType(ix *indexedExpr, def *TypeName) (res Type) {
435 if check.conf._Trace {
436 check.trace(ix.Pos(), "-- instantiating type %s with %s", ix.x, ix.indices)
437 check.indent++
438 defer func() {
439 check.indent--
440
441 check.trace(ix.Pos(), "=> %s", res)
442 }()
443 }
444
445 defer func() {
446 setDefType(def, res)
447 }()
448
449 var cause string
450 typ := check.genericType(ix.x, &cause)
451 if cause != "" {
452 check.errorf(ix.orig, NotAGenericType, invalidOp+"%s (%s)", ix.orig, cause)
453 }
454 if !isValid(typ) {
455 return typ
456 }
457
458 if _, ok := typ.(*Signature); ok {
459 panic("unexpected generic signature")
460 }
461 gtyp := typ.(genericType)
462
463
464 targs := check.typeList(ix.indices)
465 if targs == nil {
466 return Typ[Invalid]
467 }
468
469
470
471
472 inst := check.instance(ix.Pos(), gtyp, targs, nil, check.context()).(genericType)
473
474
475 check.later(func() {
476
477
478
479 check.recordInstance(ix.orig, targs, inst)
480
481 name := inst.(interface{ Obj() *TypeName }).Obj().name
482 tparams := inst.TypeParams().list()
483 if check.validateTArgLen(ix.Pos(), name, len(tparams), len(targs)) {
484
485 if i, err := check.verify(ix.Pos(), inst.TypeParams().list(), targs, check.context()); err != nil {
486
487 pos := ix.Pos()
488 if i < len(ix.indices) {
489 pos = ix.indices[i].Pos()
490 }
491 check.softErrorf(atPos(pos), InvalidTypeArg, "%v", err)
492 } else {
493 check.mono.recordInstance(check.pkg, ix.Pos(), tparams, targs, ix.indices)
494 }
495 }
496 }).describef(ix, "verify instantiation %s", inst)
497
498 return inst
499 }
500
501
502
503
504 func (check *Checker) arrayLength(e ast.Expr) int64 {
505
506
507
508
509 if name, _ := e.(*ast.Ident); name != nil {
510 obj := check.lookup(name.Name)
511 if obj == nil {
512 check.errorf(name, InvalidArrayLen, "undefined array length %s or missing type constraint", name.Name)
513 return -1
514 }
515 if _, ok := obj.(*Const); !ok {
516 check.errorf(name, InvalidArrayLen, "invalid array length %s", name.Name)
517 return -1
518 }
519 }
520
521 var x operand
522 check.expr(nil, &x, e)
523 if x.mode != constant_ {
524 if x.mode != invalid {
525 check.errorf(&x, InvalidArrayLen, "array length %s must be constant", &x)
526 }
527 return -1
528 }
529
530 if isUntyped(x.typ) || isInteger(x.typ) {
531 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
532 if representableConst(val, check, Typ[Int], nil) {
533 if n, ok := constant.Int64Val(val); ok && n >= 0 {
534 return n
535 }
536 }
537 }
538 }
539
540 var msg string
541 if isInteger(x.typ) {
542 msg = "invalid array length %s"
543 } else {
544 msg = "array length %s must be integer"
545 }
546 check.errorf(&x, InvalidArrayLen, msg, &x)
547 return -1
548 }
549
550
551
552 func (check *Checker) typeList(list []ast.Expr) []Type {
553 res := make([]Type, len(list))
554 for i, x := range list {
555 t := check.varType(x)
556 if !isValid(t) {
557 res = nil
558 }
559 if res != nil {
560 res[i] = t
561 }
562 }
563 return res
564 }
565
View as plain text