Debian Codegraph @

src/cmd/compile/internal/types2/typexpr.go

raw
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // This file implements type-checking of identifiers and type expressions.
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 // ident type-checks identifier e and initializes x with the value or type of e.
18 // If an error occurred, x.mode is set to invalid.
19 // For the meaning of def, see Checker.definedType, below.
20 // If wantType is set, the identifier e is expected to denote a type.
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 // avoid follow-on errors
37 }
38 }
39 // Because the representation of any depends on gotypesalias, we don't check
40 // pointer identity here.
41 if obj.Name() == "any" && obj.Parent() == Universe {
42 if !check.verifyVersionf(e, go1_18, "predeclared %s", e.Value) {
43 return // avoid follow-on errors
44 }
45 }
46
47 check.recordUse(e, obj)
48
49 // If we want a type but don't have one, stop right here and avoid potential problems
50 // with missing underlying types. This also gives better error messages in some cases
51 // (see go.dev/issue/65344).
52 _, gotType := obj.(*TypeName)
53 if !gotType && wantType {
54 check.errorf(e, NotAType, "%s is not a type", obj.Name())
55 // avoid "declared but not used" errors
56 // (don't use Checker.use - we don't want to evaluate too much)
57 if v, _ := obj.(*Var); v != nil && v.pkg == check.pkg /* see Checker.use1 */ {
58 check.usedVars[v] = true
59 }
60 return
61 }
62
63 // Type-check the object.
64 // Only call Checker.objDecl if the object doesn't have a type yet
65 // (in which case we must actually determine it) or the object is a
66 // TypeName from the current package and we also want a type (in which case
67 // we might detect a cycle which needs to be reported). Otherwise we can skip
68 // the call and avoid a possible cycle error in favor of the more informative
69 // "not a type/value" error that this function's caller will issue (see
70 // go.dev/issue/25790).
71 //
72 // Note that it is important to avoid calling objDecl on objects from other
73 // packages, to avoid races: see issue #69912.
74 typ := obj.Type()
75 if typ == nil || (gotType && wantType && obj.Pkg() == check.pkg) {
76 check.objDecl(obj, def)
77 typ = obj.Type() // type must have been assigned by Checker.objDecl
78 }
79 assert(typ != nil)
80
81 // The object may have been dot-imported.
82 // If so, mark the respective package as used.
83 // (This code is only needed for dot-imports. Without them,
84 // we only have to mark variables, see *Var case below).
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 // It's ok to mark non-local variables, but ignore variables
120 // from other packages to avoid potential race conditions with
121 // dot-imported variables.
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 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
150 // The type must not be an (uninstantiated) generic type.
151 func (check *Checker) typ(e syntax.Expr) Type {
152 return check.definedType(e, nil)
153 }
154
155 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
156 // The type must not be an (uninstantiated) generic type and it must not be a
157 // constraint interface.
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 // validVarType reports an error if typ is a constraint interface.
165 // The expression e is used for error reporting, if any.
166 func (check *Checker) validVarType(e syntax.Expr, typ Type) {
167 // If we have a type parameter there's nothing to do.
168 if isTypeParam(typ) {
169 return
170 }
171
172 // We don't want to call under() or complete interfaces while we are in
173 // the middle of type-checking parameter declarations that might belong
174 // to interface methods. Delay this check to the end of type-checking.
175 check.later(func() {
176 if t, _ := under(typ).(*Interface); t != nil {
177 pos := syntax.StartPos(e)
178 tset := computeInterfaceTypeSet(check, pos, t) // TODO(gri) is this the correct position?
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 // definedType is like typ but also accepts a type name def.
191 // If def != nil, e is the type specification for the type named def, declared
192 // in a type declaration, and def.typ.underlying will be set to the type of e
193 // before any components of e are type-checked.
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 // genericType is like typ but the type must be an (uninstantiated) generic
206 // type. If cause is non-nil and the type expression was a valid type but not
207 // generic, cause will be populated with a message describing the error.
208 //
209 // Note: If the type expression was invalid and an error was reported before,
210 // cause will not be populated; thus cause alone cannot be used to determine
211 // if an error occurred.
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 // TODO(gri) what is the correct call below?
222 check.recordTypeAndValue(e, typexpr, typ, nil)
223 return typ
224 }
225
226 // goTypeName returns the Go type name for typ and
227 // removes any occurrences of "types2." from that name.
228 func goTypeName(typ Type) string {
229 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types2.", "")
230 }
231
232 // typInternal drives type checking of types.
233 // Must only be called by definedType or genericType.
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 // Calling under() here may lead to endless instantiations.
243 // Test case: type T[P any] *T[P]
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 // ignore - error reported before
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 // ignore - error reported before
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 // ignore - error reported before
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 // Generic types must be instantiated before they can be used in any form.
298 // Consequently, generic types cannot be parenthesized.
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 // [...]array
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 // report error if we encountered [...]
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 // dots are handled explicitly where they are valid
325 check.error(e, InvalidSyntaxTree, "invalid use of ...")
326
327 case *syntax.StructType:
328 typ := new(Struct)
329 setDefType(def, typ)
330 check.structType(typ, e)
331 return typ
332
333 case *syntax.Operation:
334 if e.Op == syntax.Mul && e.Y == nil {
335 typ := new(Pointer)
336 typ.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
337 setDefType(def, typ)
338 typ.base = check.varType(e.X)
339 // If typ.base is invalid, it's unlikely that *base is particularly
340 // useful - even a valid dereferenciation will lead to an invalid
341 // type again, and in some cases we get unexpected follow-on errors
342 // (e.g., go.dev/issue/49005). Return an invalid type instead.
343 if !isValid(typ.base) {
344 return Typ[Invalid]
345 }
346 return typ
347 }
348
349 check.errorf(e0, NotAType, "%s is not a type", e0)
350 check.use(e0)
351
352 case *syntax.FuncType:
353 typ := new(Signature)
354 setDefType(def, typ)
355 check.funcType(typ, nil, nil, e)
356 return typ
357
358 case *syntax.InterfaceType:
359 typ := check.newInterface()
360 setDefType(def, typ)
361 check.interfaceType(typ, e, def)
362 return typ
363
364 case *syntax.MapType:
365 typ := new(Map)
366 setDefType(def, typ)
367
368 typ.key = check.varType(e.Key)
369 typ.elem = check.varType(e.Value)
370
371 // spec: "The comparison operators == and != must be fully defined
372 // for operands of the key type; thus the key type must not be a
373 // function, map, or slice."
374 //
375 // Delay this check because it requires fully setup types;
376 // it is safe to continue in any case (was go.dev/issue/6667).
377 check.later(func() {
378 if !Comparable(typ.key) {
379 var why string
380 if isTypeParam(typ.key) {
381 why = " (missing comparable constraint)"
382 }
383 check.errorf(e.Key, IncomparableMapKey, "invalid map key type %s%s", typ.key, why)
384 }
385 }).describef(e.Key, "check map key %s", typ.key)
386
387 return typ
388
389 case *syntax.ChanType:
390 typ := new(Chan)
391 setDefType(def, typ)
392
393 dir := SendRecv
394 switch e.Dir {
395 case 0:
396 // nothing to do
397 case syntax.SendOnly:
398 dir = SendOnly
399 case syntax.RecvOnly:
400 dir = RecvOnly
401 default:
402 check.errorf(e, InvalidSyntaxTree, "unknown channel direction %d", e.Dir)
403 // ok to continue
404 }
405
406 typ.dir = dir
407 typ.elem = check.varType(e.Elem)
408 return typ
409
410 default:
411 check.errorf(e0, NotAType, "%s is not a type", e0)
412 check.use(e0)
413 }
414
415 typ := Typ[Invalid]
416 setDefType(def, typ)
417 return typ
418 }
419
420 func setDefType(def *TypeName, typ Type) {
421 if def != nil {
422 switch t := def.typ.(type) {
423 case *Alias:
424 t.fromRHS = typ
425 case *Basic:
426 assert(t == Typ[Invalid])
427 case *Named:
428 t.underlying = typ
429 default:
430 panic(fmt.Sprintf("unexpected type %T", t))
431 }
432 }
433 }
434
435 func (check *Checker) instantiatedType(x syntax.Expr, xlist []syntax.Expr, def *TypeName) (res Type) {
436 if check.conf.Trace {
437 check.trace(x.Pos(), "-- instantiating type %s with %s", x, xlist)
438 check.indent++
439 defer func() {
440 check.indent--
441 // Don't format the underlying here. It will always be nil.
442 check.trace(x.Pos(), "=> %s", res)
443 }()
444 }
445
446 defer func() {
447 setDefType(def, res)
448 }()
449
450 var cause string
451 typ := check.genericType(x, &cause)
452 if cause != "" {
453 check.errorf(x, NotAGenericType, invalidOp+"%s%s (%s)", x, xlist, cause)
454 }
455 if !isValid(typ) {
456 return typ // error already reported
457 }
458 // typ must be a generic Alias or Named type (but not a *Signature)
459 if _, ok := typ.(*Signature); ok {
460 panic("unexpected generic signature")
461 }
462 gtyp := typ.(genericType)
463
464 // evaluate arguments
465 targs := check.typeList(xlist)
466 if targs == nil {
467 return Typ[Invalid]
468 }
469
470 // create instance
471 // The instance is not generic anymore as it has type arguments, but unless
472 // instantiation failed, it still satisfies the genericType interface because
473 // it has type parameters, too.
474 ityp := check.instance(x.Pos(), gtyp, targs, nil, check.context())
475 inst, _ := ityp.(genericType)
476 if inst == nil {
477 return Typ[Invalid]
478 }
479
480 // For Named types, orig.tparams may not be set up, so we need to do expansion later.
481 check.later(func() {
482 // This is an instance from the source, not from recursive substitution,
483 // and so it must be resolved during type-checking so that we can report
484 // errors.
485 check.recordInstance(x, targs, inst)
486
487 name := inst.(interface{ Obj() *TypeName }).Obj().name
488 tparams := inst.TypeParams().list()
489 if check.validateTArgLen(x.Pos(), name, len(tparams), len(targs)) {
490 // check type constraints
491 if i, err := check.verify(x.Pos(), inst.TypeParams().list(), targs, check.context()); err != nil {
492 // best position for error reporting
493 pos := x.Pos()
494 if i < len(xlist) {
495 pos = syntax.StartPos(xlist[i])
496 }
497 check.softErrorf(pos, InvalidTypeArg, "%s", err)
498 } else {
499 check.mono.recordInstance(check.pkg, x.Pos(), tparams, targs, xlist)
500 }
501 }
502 }).describef(x, "verify instantiation %s", inst)
503
504 return inst
505 }
506
507 // arrayLength type-checks the array length expression e
508 // and returns the constant length >= 0, or a value < 0
509 // to indicate an error (and thus an unknown length).
510 func (check *Checker) arrayLength(e syntax.Expr) int64 {
511 // If e is an identifier, the array declaration might be an
512 // attempt at a parameterized type declaration with missing
513 // constraint. Provide an error message that mentions array
514 // length.
515 if name, _ := e.(*syntax.Name); name != nil {
516 obj := check.lookup(name.Value)
517 if obj == nil {
518 check.errorf(name, InvalidArrayLen, "undefined array length %s or missing type constraint", name.Value)
519 return -1
520 }
521 if _, ok := obj.(*Const); !ok {
522 check.errorf(name, InvalidArrayLen, "invalid array length %s", name.Value)
523 return -1
524 }
525 }
526
527 var x operand
528 check.expr(nil, &x, e)
529 if x.mode != constant_ {
530 if x.mode != invalid {
531 check.errorf(&x, InvalidArrayLen, "array length %s must be constant", &x)
532 }
533 return -1
534 }
535
536 if isUntyped(x.typ) || isInteger(x.typ) {
537 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
538 if representableConst(val, check, Typ[Int], nil) {
539 if n, ok := constant.Int64Val(val); ok && n >= 0 {
540 return n
541 }
542 }
543 }
544 }
545
546 var msg string
547 if isInteger(x.typ) {
548 msg = "invalid array length %s"
549 } else {
550 msg = "array length %s must be integer"
551 }
552 check.errorf(&x, InvalidArrayLen, msg, &x)
553 return -1
554 }
555
556 // typeList provides the list of types corresponding to the incoming expression list.
557 // If an error occurred, the result is nil, but all list elements were type-checked.
558 func (check *Checker) typeList(list []syntax.Expr) []Type {
559 res := make([]Type, len(list)) // res != nil even if len(list) == 0
560 for i, x := range list {
561 t := check.varType(x)
562 if !isValid(t) {
563 res = nil
564 }
565 if res != nil {
566 res[i] = t
567 }
568 }
569 return res
570 }