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