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 func (check *Checker) ident(x *operand, e *syntax.Name, wantType bool) {
21 x.mode = invalid
22 x.expr = e
23
24 scope, obj := check.lookupScope(e.Value)
25 switch obj {
26 case nil:
27 if e.Value == "_" {
28 check.error(e, InvalidBlank, "cannot use _ as value or type")
29 } else if isValidName(e.Value) {
30 check.errorf(e, UndeclaredName, "undefined: %s", e.Value)
31 }
32 return
33 case universeComparable:
34 if !check.verifyVersionf(e, go1_18, "predeclared %s", e.Value) {
35 return
36 }
37 }
38
39
40 if obj.Name() == "any" && obj.Parent() == Universe {
41 if !check.verifyVersionf(e, go1_18, "predeclared %s", e.Value) {
42 return
43 }
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 (%s) is not a type", obj.Name(), objectKind(obj))
54
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)
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.declaredType(e, nil)
153 }
154
155
156
157
158 func (check *Checker) varType(e syntax.Expr) Type {
159 typ := check.declaredType(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, _ := typ.Underlying().(*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) declaredType(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, true)
261
262 switch x.mode {
263 case typexpr:
264 return x.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 *syntax.SelectorExpr:
274 var x operand
275 check.selector(&x, e, true)
276
277 switch x.mode {
278 case typexpr:
279 return x.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))
291
292 case *syntax.ParenExpr:
293
294
295 return check.declaredType(e.X, def)
296
297 case *syntax.ArrayType:
298 typ := new(Array)
299 if e.Len != nil {
300 typ.len = check.arrayLength(e.Len)
301 } else {
302
303 check.error(e, BadDotDotDotSyntax, "invalid use of [...] array (outside a composite literal)")
304 typ.len = -1
305 }
306 typ.elem = check.varType(e.Elem)
307 if typ.len >= 0 {
308 return typ
309 }
310
311
312 case *syntax.SliceType:
313 typ := new(Slice)
314 typ.elem = check.varType(e.Elem)
315 return typ
316
317 case *syntax.DotsType:
318
319 check.error(e, InvalidSyntaxTree, "invalid use of ...")
320
321 case *syntax.StructType:
322 typ := new(Struct)
323 check.structType(typ, e)
324 return typ
325
326 case *syntax.Operation:
327 if e.Op == syntax.Mul && e.Y == nil {
328 typ := new(Pointer)
329 typ.base = Typ[Invalid]
330 typ.base = check.varType(e.X)
331
332
333
334
335 if !isValid(typ.base) {
336 return Typ[Invalid]
337 }
338 return typ
339 }
340
341 check.errorf(e0, NotAType, "%s is not a type", e0)
342 check.use(e0)
343
344 case *syntax.FuncType:
345 typ := new(Signature)
346 check.funcType(typ, nil, nil, e)
347 return typ
348
349 case *syntax.InterfaceType:
350 typ := check.newInterface()
351 check.interfaceType(typ, e, def)
352 return typ
353
354 case *syntax.MapType:
355 typ := new(Map)
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 *syntax.ChanType:
378 typ := new(Chan)
379
380 dir := SendRecv
381 switch e.Dir {
382 case 0:
383
384 case syntax.SendOnly:
385 dir = SendOnly
386 case syntax.RecvOnly:
387 dir = RecvOnly
388 default:
389 check.errorf(e, InvalidSyntaxTree, "unknown channel direction %d", e.Dir)
390
391 }
392
393 typ.dir = dir
394 typ.elem = check.varType(e.Elem)
395 return typ
396
397 default:
398 check.errorf(e0, NotAType, "%s is not a type", e0)
399 check.use(e0)
400 }
401
402 typ := Typ[Invalid]
403 return typ
404 }
405
406 func (check *Checker) instantiatedType(x syntax.Expr, xlist []syntax.Expr) (res Type) {
407 if check.conf.Trace {
408 check.trace(x.Pos(), "-- instantiating type %s with %s", x, xlist)
409 check.indent++
410 defer func() {
411 check.indent--
412
413 check.trace(x.Pos(), "=> %s", res)
414 }()
415 }
416
417 var cause string
418 typ := check.genericType(x, &cause)
419 if cause != "" {
420 check.errorf(x, NotAGenericType, invalidOp+"%s%s (%s)", x, xlist, cause)
421 }
422 if !isValid(typ) {
423 return typ
424 }
425
426 if _, ok := typ.(*Signature); ok {
427 panic("unexpected generic signature")
428 }
429 gtyp := typ.(genericType)
430
431
432 targs := check.typeList(xlist)
433 if targs == nil {
434 return Typ[Invalid]
435 }
436
437
438
439
440
441 ityp := check.instance(x.Pos(), gtyp, targs, nil, check.context())
442 inst, _ := ityp.(genericType)
443 if inst == nil {
444 return Typ[Invalid]
445 }
446
447
448 check.later(func() {
449
450
451
452 check.recordInstance(x, targs, inst)
453
454 name := inst.(interface{ Obj() *TypeName }).Obj().name
455 tparams := inst.TypeParams().list()
456 if check.validateTArgLen(x.Pos(), name, len(tparams), len(targs)) {
457
458 if i, err := check.verify(x.Pos(), inst.TypeParams().list(), targs, check.context()); err != nil {
459
460 pos := x.Pos()
461 if i < len(xlist) {
462 pos = syntax.StartPos(xlist[i])
463 }
464 check.softErrorf(pos, InvalidTypeArg, "%s", err)
465 } else {
466 check.mono.recordInstance(check.pkg, x.Pos(), tparams, targs, xlist)
467 }
468 }
469 }).describef(x, "verify instantiation %s", inst)
470
471 return inst
472 }
473
474
475
476
477 func (check *Checker) arrayLength(e syntax.Expr) int64 {
478
479
480
481
482 if name, _ := e.(*syntax.Name); name != nil {
483 obj := check.lookup(name.Value)
484 if obj == nil {
485 check.errorf(name, InvalidArrayLen, "undefined array length %s or missing type constraint", name.Value)
486 return -1
487 }
488 if _, ok := obj.(*Const); !ok {
489 check.errorf(name, InvalidArrayLen, "invalid array length %s", name.Value)
490 return -1
491 }
492 }
493
494 var x operand
495 check.expr(nil, &x, e)
496 if x.mode != constant_ {
497 if x.mode != invalid {
498 check.errorf(&x, InvalidArrayLen, "array length %s must be constant", &x)
499 }
500 return -1
501 }
502
503 if isUntyped(x.typ) || isInteger(x.typ) {
504 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
505 if representableConst(val, check, Typ[Int], nil) {
506 if n, ok := constant.Int64Val(val); ok && n >= 0 {
507 return n
508 }
509 }
510 }
511 }
512
513 var msg string
514 if isInteger(x.typ) {
515 msg = "invalid array length %s"
516 } else {
517 msg = "array length %s must be integer"
518 }
519 check.errorf(&x, InvalidArrayLen, msg, &x)
520 return -1
521 }
522
523
524
525 func (check *Checker) typeList(list []syntax.Expr) []Type {
526 res := make([]Type, len(list))
527 for i, x := range list {
528 t := check.varType(x)
529 if !isValid(t) {
530 res = nil
531 }
532 if res != nil {
533 res[i] = t
534 }
535 }
536 return res
537 }
538
View as plain text