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