1 // Copyright 2012 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 typechecking of expressions.
6 7 package types
8 9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/token"
14 . "internal/types/errors"
15 )
16 17 /*
18 Basic algorithm:
19 20 Expressions are checked recursively, top down. Expression checker functions
21 are generally of the form:
22 23 func f(x *operand, e *ast.Expr, ...)
24 25 where e is the expression to be checked, and x is the result of the check.
26 The check performed by f may fail in which case x.mode == invalid, and
27 related error messages will have been issued by f.
28 29 If a hint argument is present, it is the composite literal element type
30 of an outer composite literal; it is used to type-check composite literal
31 elements that have no explicit type specification in the source
32 (e.g.: []T{{...}, {...}}, the hint is the type T in this case).
33 34 All expressions are checked via rawExpr, which dispatches according
35 to expression kind. Upon returning, rawExpr is recording the types and
36 constant values for all expressions that have an untyped type (those types
37 may change on the way up in the expression tree). Usually these are constants,
38 but the results of comparisons or non-constant shifts of untyped constants
39 may also be untyped, but not constant.
40 41 Untyped expressions may eventually become fully typed (i.e., not untyped),
42 typically when the value is assigned to a variable, or is used otherwise.
43 The updateExprType method is used to record this final type and update
44 the recorded types: the type-checked expression tree is again traversed down,
45 and the new type is propagated as needed. Untyped constant expression values
46 that become fully typed must now be representable by the full type (constant
47 sub-expression trees are left alone except for their roots). This mechanism
48 ensures that a client sees the actual (run-time) type an untyped value would
49 have. It also permits type-checking of lhs shift operands "as if the shift
50 were not present": when updateExprType visits an untyped lhs shift operand
51 and assigns it its final type, that type must be an integer type, and a
52 constant lhs must be representable as an integer.
53 54 When an expression gets its final type, either on the way out from rawExpr,
55 on the way down in updateExprType, or at the end of the type checker run,
56 the type (and constant value, if any) is recorded via Info.Types, if present.
57 */
58 59 type opPredicates map[token.Token]func(Type) bool
60 61 var unaryOpPredicates opPredicates
62 63 func init() {
64 // Setting unaryOpPredicates in init avoids declaration cycles.
65 unaryOpPredicates = opPredicates{
66 token.ADD: allNumeric,
67 token.SUB: allNumeric,
68 token.XOR: allInteger,
69 token.NOT: allBoolean,
70 }
71 }
72 73 func (check *Checker) op(m opPredicates, x *operand, op token.Token) bool {
74 if pred := m[op]; pred != nil {
75 if !pred(x.typ) {
76 check.errorf(x, UndefinedOp, invalidOp+"operator %s not defined on %s", op, x)
77 return false
78 }
79 } else {
80 check.errorf(x, InvalidSyntaxTree, "unknown operator %s", op)
81 return false
82 }
83 return true
84 }
85 86 // opPos returns the position of the operator if x is an operation;
87 // otherwise it returns the start position of x.
88 func opPos(x ast.Expr) token.Pos {
89 switch op := x.(type) {
90 case nil:
91 return nopos // don't crash
92 case *ast.BinaryExpr:
93 return op.OpPos
94 default:
95 return x.Pos()
96 }
97 }
98 99 // opName returns the name of the operation if x is an operation
100 // that might overflow; otherwise it returns the empty string.
101 func opName(e ast.Expr) string {
102 switch e := e.(type) {
103 case *ast.BinaryExpr:
104 if int(e.Op) < len(op2str2) {
105 return op2str2[e.Op]
106 }
107 case *ast.UnaryExpr:
108 if int(e.Op) < len(op2str1) {
109 return op2str1[e.Op]
110 }
111 }
112 return ""
113 }
114 115 var op2str1 = [...]string{
116 token.XOR: "bitwise complement",
117 }
118 119 // This is only used for operations that may cause overflow.
120 var op2str2 = [...]string{
121 token.ADD: "addition",
122 token.SUB: "subtraction",
123 token.XOR: "bitwise XOR",
124 token.MUL: "multiplication",
125 token.SHL: "shift",
126 }
127 128 // The unary expression e may be nil. It's passed in for better error messages only.
129 func (check *Checker) unary(x *operand, e *ast.UnaryExpr) {
130 check.expr(nil, x, e.X)
131 if x.mode == invalid {
132 return
133 }
134 135 op := e.Op
136 switch op {
137 case token.AND:
138 // spec: "As an exception to the addressability
139 // requirement x may also be a composite literal."
140 if _, ok := ast.Unparen(e.X).(*ast.CompositeLit); !ok && x.mode != variable {
141 check.errorf(x, UnaddressableOperand, invalidOp+"cannot take address of %s", x)
142 x.mode = invalid
143 return
144 }
145 x.mode = value
146 x.typ = &Pointer{base: x.typ}
147 return
148 149 case token.ARROW:
150 if elem := check.chanElem(x, x, true); elem != nil {
151 x.mode = commaok
152 x.typ = elem
153 check.hasCallOrRecv = true
154 return
155 }
156 x.mode = invalid
157 return
158 159 case token.TILDE:
160 // Provide a better error position and message than what check.op below would do.
161 if !allInteger(x.typ) {
162 check.error(e, UndefinedOp, "cannot use ~ outside of interface or type constraint")
163 x.mode = invalid
164 return
165 }
166 check.error(e, UndefinedOp, "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)")
167 op = token.XOR
168 }
169 170 if !check.op(unaryOpPredicates, x, op) {
171 x.mode = invalid
172 return
173 }
174 175 if x.mode == constant_ {
176 if x.val.Kind() == constant.Unknown {
177 // nothing to do (and don't cause an error below in the overflow check)
178 return
179 }
180 var prec uint
181 if isUnsigned(x.typ) {
182 prec = uint(check.conf.sizeof(x.typ) * 8)
183 }
184 x.val = constant.UnaryOp(op, x.val, prec)
185 x.expr = e
186 check.overflow(x, opPos(x.expr))
187 return
188 }
189 190 x.mode = value
191 // x.typ remains unchanged
192 }
193 194 // chanElem returns the channel element type of x for a receive from x (recv == true)
195 // or send to x (recv == false) operation. If the operation is not valid, chanElem
196 // reports an error and returns nil.
197 func (check *Checker) chanElem(pos positioner, x *operand, recv bool) Type {
198 u, err := commonUnder(x.typ, func(t, u Type) *typeError {
199 if u == nil {
200 return typeErrorf("no specific channel type")
201 }
202 ch, _ := u.(*Chan)
203 if ch == nil {
204 return typeErrorf("non-channel %s", t)
205 }
206 if recv && ch.dir == SendOnly {
207 return typeErrorf("send-only channel %s", t)
208 }
209 if !recv && ch.dir == RecvOnly {
210 return typeErrorf("receive-only channel %s", t)
211 }
212 return nil
213 })
214 215 if u != nil {
216 return u.(*Chan).elem
217 }
218 219 cause := err.format(check)
220 if recv {
221 if isTypeParam(x.typ) {
222 check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s: %s", x, cause)
223 } else {
224 // In this case, only the non-channel and send-only channel error are possible.
225 check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s %s", cause, x)
226 }
227 } else {
228 if isTypeParam(x.typ) {
229 check.errorf(pos, InvalidSend, invalidOp+"cannot send to %s: %s", x, cause)
230 } else {
231 // In this case, only the non-channel and receive-only channel error are possible.
232 check.errorf(pos, InvalidSend, invalidOp+"cannot send to %s %s", cause, x)
233 }
234 }
235 return nil
236 }
237 238 func isShift(op token.Token) bool {
239 return op == token.SHL || op == token.SHR
240 }
241 242 func isComparison(op token.Token) bool {
243 // Note: tokens are not ordered well to make this much easier
244 switch op {
245 case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
246 return true
247 }
248 return false
249 }
250 251 // updateExprType updates the type of x to typ and invokes itself
252 // recursively for the operands of x, depending on expression kind.
253 // If typ is still an untyped and not the final type, updateExprType
254 // only updates the recorded untyped type for x and possibly its
255 // operands. Otherwise (i.e., typ is not an untyped type anymore,
256 // or it is the final type for x), the type and value are recorded.
257 // Also, if x is a constant, it must be representable as a value of typ,
258 // and if x is the (formerly untyped) lhs operand of a non-constant
259 // shift, it must be an integer value.
260 func (check *Checker) updateExprType(x ast.Expr, typ Type, final bool) {
261 old, found := check.untyped[x]
262 if !found {
263 return // nothing to do
264 }
265 266 // update operands of x if necessary
267 switch x := x.(type) {
268 case *ast.BadExpr,
269 *ast.FuncLit,
270 *ast.CompositeLit,
271 *ast.IndexExpr,
272 *ast.SliceExpr,
273 *ast.TypeAssertExpr,
274 *ast.StarExpr,
275 *ast.KeyValueExpr,
276 *ast.ArrayType,
277 *ast.StructType,
278 *ast.FuncType,
279 *ast.InterfaceType,
280 *ast.MapType,
281 *ast.ChanType:
282 // These expression are never untyped - nothing to do.
283 // The respective sub-expressions got their final types
284 // upon assignment or use.
285 if debug {
286 check.dump("%v: found old type(%s): %s (new: %s)", x.Pos(), x, old.typ, typ)
287 panic("unreachable")
288 }
289 return
290 291 case *ast.CallExpr:
292 // Resulting in an untyped constant (e.g., built-in complex).
293 // The respective calls take care of calling updateExprType
294 // for the arguments if necessary.
295 296 case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr:
297 // An identifier denoting a constant, a constant literal,
298 // or a qualified identifier (imported untyped constant).
299 // No operands to take care of.
300 301 case *ast.ParenExpr:
302 check.updateExprType(x.X, typ, final)
303 304 case *ast.UnaryExpr:
305 // If x is a constant, the operands were constants.
306 // The operands don't need to be updated since they
307 // never get "materialized" into a typed value. If
308 // left in the untyped map, they will be processed
309 // at the end of the type check.
310 if old.val != nil {
311 break
312 }
313 check.updateExprType(x.X, typ, final)
314 315 case *ast.BinaryExpr:
316 if old.val != nil {
317 break // see comment for unary expressions
318 }
319 if isComparison(x.Op) {
320 // The result type is independent of operand types
321 // and the operand types must have final types.
322 } else if isShift(x.Op) {
323 // The result type depends only on lhs operand.
324 // The rhs type was updated when checking the shift.
325 check.updateExprType(x.X, typ, final)
326 } else {
327 // The operand types match the result type.
328 check.updateExprType(x.X, typ, final)
329 check.updateExprType(x.Y, typ, final)
330 }
331 332 default:
333 panic("unreachable")
334 }
335 336 // If the new type is not final and still untyped, just
337 // update the recorded type.
338 if !final && isUntyped(typ) {
339 old.typ = under(typ).(*Basic)
340 check.untyped[x] = old
341 return
342 }
343 344 // Otherwise we have the final (typed or untyped type).
345 // Remove it from the map of yet untyped expressions.
346 delete(check.untyped, x)
347 348 if old.isLhs {
349 // If x is the lhs of a shift, its final type must be integer.
350 // We already know from the shift check that it is representable
351 // as an integer if it is a constant.
352 if !allInteger(typ) {
353 check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s (type %s) must be integer", x, typ)
354 return
355 }
356 // Even if we have an integer, if the value is a constant we
357 // still must check that it is representable as the specific
358 // int type requested (was go.dev/issue/22969). Fall through here.
359 }
360 if old.val != nil {
361 // If x is a constant, it must be representable as a value of typ.
362 c := operand{old.mode, x, old.typ, old.val, 0}
363 check.convertUntyped(&c, typ)
364 if c.mode == invalid {
365 return
366 }
367 }
368 369 // Everything's fine, record final type and value for x.
370 check.recordTypeAndValue(x, old.mode, typ, old.val)
371 }
372 373 // updateExprVal updates the value of x to val.
374 func (check *Checker) updateExprVal(x ast.Expr, val constant.Value) {
375 if info, ok := check.untyped[x]; ok {
376 info.val = val
377 check.untyped[x] = info
378 }
379 }
380 381 // implicitTypeAndValue returns the implicit type of x when used in a context
382 // where the target type is expected. If no such implicit conversion is
383 // possible, it returns a nil Type and non-zero error code.
384 //
385 // If x is a constant operand, the returned constant.Value will be the
386 // representation of x in this context.
387 func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, Code) {
388 if x.mode == invalid || isTyped(x.typ) || !isValid(target) {
389 return x.typ, nil, 0
390 }
391 // x is untyped
392 393 if isUntyped(target) {
394 // both x and target are untyped
395 if m := maxType(x.typ, target); m != nil {
396 return m, nil, 0
397 }
398 return nil, nil, InvalidUntypedConversion
399 }
400 401 // Moxie: untyped string → []byte implicit conversion (string=[]byte unification).
402 // For constants, return Typ[String] because slices aren't valid constant types.
403 if x.typ.(*Basic).kind == UntypedString && isByteSlice(target) {
404 if x.mode == constant_ {
405 return Typ[String], x.val, 0
406 }
407 return target, nil, 0
408 }
409 410 switch u := under(target).(type) {
411 case *Basic:
412 if x.mode == constant_ {
413 v, code := check.representation(x, u)
414 if code != 0 {
415 return nil, nil, code
416 }
417 return target, v, code
418 }
419 // Non-constant untyped values may appear as the
420 // result of comparisons (untyped bool), intermediate
421 // (delayed-checked) rhs operands of shifts, and as
422 // the value nil.
423 switch x.typ.(*Basic).kind {
424 case UntypedBool:
425 if !isBoolean(target) {
426 return nil, nil, InvalidUntypedConversion
427 }
428 case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex:
429 if !isNumeric(target) {
430 return nil, nil, InvalidUntypedConversion
431 }
432 case UntypedString:
433 // Non-constant untyped string values are not permitted by the spec and
434 // should not occur during normal typechecking passes, but this path is
435 // reachable via the AssignableTo API.
436 if !isString(target) {
437 return nil, nil, InvalidUntypedConversion
438 }
439 case UntypedNil:
440 // Unsafe.Pointer is a basic type that includes nil.
441 if !hasNil(target) {
442 return nil, nil, InvalidUntypedConversion
443 }
444 // Preserve the type of nil as UntypedNil: see go.dev/issue/13061.
445 return Typ[UntypedNil], nil, 0
446 default:
447 return nil, nil, InvalidUntypedConversion
448 }
449 case *Interface:
450 if isTypeParam(target) {
451 if !underIs(target, func(u Type) bool {
452 if u == nil {
453 return false
454 }
455 t, _, _ := check.implicitTypeAndValue(x, u)
456 return t != nil
457 }) {
458 return nil, nil, InvalidUntypedConversion
459 }
460 // keep nil untyped (was bug go.dev/issue/39755)
461 if x.isNil() {
462 return Typ[UntypedNil], nil, 0
463 }
464 break
465 }
466 // Values must have concrete dynamic types. If the value is nil,
467 // keep it untyped (this is important for tools such as go vet which
468 // need the dynamic type for argument checking of say, print
469 // functions)
470 if x.isNil() {
471 return Typ[UntypedNil], nil, 0
472 }
473 // cannot assign untyped values to non-empty interfaces
474 if !u.Empty() {
475 return nil, nil, InvalidUntypedConversion
476 }
477 return Default(x.typ), nil, 0
478 case *Pointer, *Signature, *Slice, *Map, *Chan:
479 if !x.isNil() {
480 return nil, nil, InvalidUntypedConversion
481 }
482 // Keep nil untyped - see comment for interfaces, above.
483 return Typ[UntypedNil], nil, 0
484 default:
485 return nil, nil, InvalidUntypedConversion
486 }
487 return target, nil, 0
488 }
489 490 // If switchCase is true, the operator op is ignored.
491 func (check *Checker) comparison(x, y *operand, op token.Token, switchCase bool) {
492 // Avoid spurious errors if any of the operands has an invalid type (go.dev/issue/54405).
493 if !isValid(x.typ) || !isValid(y.typ) {
494 x.mode = invalid
495 return
496 }
497 498 if switchCase {
499 op = token.EQL
500 }
501 502 errOp := x // operand for which error is reported, if any
503 cause := "" // specific error cause, if any
504 505 // spec: "In any comparison, the first operand must be assignable
506 // to the type of the second operand, or vice versa."
507 code := MismatchedTypes
508 ok, _ := x.assignableTo(check, y.typ, nil)
509 if !ok {
510 ok, _ = y.assignableTo(check, x.typ, nil)
511 }
512 if !ok {
513 // Report the error on the 2nd operand since we only
514 // know after seeing the 2nd operand whether we have
515 // a type mismatch.
516 errOp = y
517 cause = check.sprintf("mismatched types %s and %s", x.typ, y.typ)
518 goto Error
519 }
520 521 // check if comparison is defined for operands
522 code = UndefinedOp
523 switch op {
524 case token.EQL, token.NEQ:
525 // spec: "The equality operators == and != apply to operands that are comparable."
526 switch {
527 case x.isNil() || y.isNil():
528 // Comparison against nil requires that the other operand type has nil.
529 typ := x.typ
530 if x.isNil() {
531 typ = y.typ
532 }
533 if !hasNil(typ) {
534 // This case should only be possible for "nil == nil".
535 // Report the error on the 2nd operand since we only
536 // know after seeing the 2nd operand whether we have
537 // an invalid comparison.
538 errOp = y
539 goto Error
540 }
541 542 case !Comparable(x.typ):
543 errOp = x
544 cause = check.incomparableCause(x.typ)
545 goto Error
546 547 case !Comparable(y.typ):
548 errOp = y
549 cause = check.incomparableCause(y.typ)
550 goto Error
551 }
552 553 case token.LSS, token.LEQ, token.GTR, token.GEQ:
554 // spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
555 switch {
556 case !allOrdered(x.typ):
557 errOp = x
558 goto Error
559 case !allOrdered(y.typ):
560 errOp = y
561 goto Error
562 }
563 564 default:
565 panic("unreachable")
566 }
567 568 // comparison is ok
569 if x.mode == constant_ && y.mode == constant_ {
570 x.val = constant.MakeBool(constant.Compare(x.val, op, y.val))
571 // The operands are never materialized; no need to update
572 // their types.
573 } else {
574 x.mode = value
575 // The operands have now their final types, which at run-
576 // time will be materialized. Update the expression trees.
577 // If the current types are untyped, the materialized type
578 // is the respective default type.
579 check.updateExprType(x.expr, Default(x.typ), true)
580 check.updateExprType(y.expr, Default(y.typ), true)
581 }
582 583 // spec: "Comparison operators compare two operands and yield
584 // an untyped boolean value."
585 x.typ = Typ[UntypedBool]
586 return
587 588 Error:
589 // We have an offending operand errOp and possibly an error cause.
590 if cause == "" {
591 if isTypeParam(x.typ) || isTypeParam(y.typ) {
592 // TODO(gri) should report the specific type causing the problem, if any
593 if !isTypeParam(x.typ) {
594 errOp = y
595 }
596 cause = check.sprintf("type parameter %s cannot use operator %s", errOp.typ, op)
597 } else {
598 // catch-all neither x nor y is a type parameter
599 what := compositeKind(errOp.typ)
600 if what == "" {
601 what = check.sprintf("%s", errOp.typ)
602 }
603 cause = check.sprintf("operator %s not defined on %s", op, what)
604 }
605 }
606 if switchCase {
607 check.errorf(x, code, "invalid case %s in switch on %s (%s)", x.expr, y.expr, cause) // error position always at 1st operand
608 } else {
609 check.errorf(errOp, code, invalidOp+"%s %s %s (%s)", x.expr, op, y.expr, cause)
610 }
611 x.mode = invalid
612 }
613 614 // incomparableCause returns a more specific cause why typ is not comparable.
615 // If there is no more specific cause, the result is "".
616 func (check *Checker) incomparableCause(typ Type) string {
617 switch under(typ).(type) {
618 case *Slice, *Signature, *Map:
619 return compositeKind(typ) + " can only be compared to nil"
620 }
621 // see if we can extract a more specific error
622 return comparableType(typ, true, nil).format(check)
623 }
624 625 // If e != nil, it must be the shift expression; it may be nil for non-constant shifts.
626 func (check *Checker) shift(x, y *operand, e ast.Expr, op token.Token) {
627 // TODO(gri) This function seems overly complex. Revisit.
628 629 var xval constant.Value
630 if x.mode == constant_ {
631 xval = constant.ToInt(x.val)
632 }
633 634 if allInteger(x.typ) || isUntyped(x.typ) && xval != nil && xval.Kind() == constant.Int {
635 // The lhs is of integer type or an untyped constant representable
636 // as an integer. Nothing to do.
637 } else {
638 // shift has no chance
639 check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", x)
640 x.mode = invalid
641 return
642 }
643 644 // spec: "The right operand in a shift expression must have integer type
645 // or be an untyped constant representable by a value of type uint."
646 647 // Check that constants are representable by uint, but do not convert them
648 // (see also go.dev/issue/47243).
649 var yval constant.Value
650 if y.mode == constant_ {
651 // Provide a good error message for negative shift counts.
652 yval = constant.ToInt(y.val) // consider -1, 1.0, but not -1.1
653 if yval.Kind() == constant.Int && constant.Sign(yval) < 0 {
654 check.errorf(y, InvalidShiftCount, invalidOp+"negative shift count %s", y)
655 x.mode = invalid
656 return
657 }
658 659 if isUntyped(y.typ) {
660 // Caution: Check for representability here, rather than in the switch
661 // below, because isInteger includes untyped integers (was bug go.dev/issue/43697).
662 check.representable(y, Typ[Uint])
663 if y.mode == invalid {
664 x.mode = invalid
665 return
666 }
667 }
668 } else {
669 // Check that RHS is otherwise at least of integer type.
670 switch {
671 case allInteger(y.typ):
672 if !allUnsigned(y.typ) && !check.verifyVersionf(y, go1_13, invalidOp+"signed shift count %s", y) {
673 x.mode = invalid
674 return
675 }
676 case isUntyped(y.typ):
677 // This is incorrect, but preserves pre-existing behavior.
678 // See also go.dev/issue/47410.
679 check.convertUntyped(y, Typ[Uint])
680 if y.mode == invalid {
681 x.mode = invalid
682 return
683 }
684 default:
685 check.errorf(y, InvalidShiftCount, invalidOp+"shift count %s must be integer", y)
686 x.mode = invalid
687 return
688 }
689 }
690 691 if x.mode == constant_ {
692 if y.mode == constant_ {
693 // if either x or y has an unknown value, the result is unknown
694 if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
695 x.val = constant.MakeUnknown()
696 // ensure the correct type - see comment below
697 if !isInteger(x.typ) {
698 x.typ = Typ[UntypedInt]
699 }
700 return
701 }
702 // rhs must be within reasonable bounds in constant shifts
703 const shiftBound = 1023 - 1 + 52 // so we can express smallestFloat64 (see go.dev/issue/44057)
704 s, ok := constant.Uint64Val(yval)
705 if !ok || s > shiftBound {
706 check.errorf(y, InvalidShiftCount, invalidOp+"invalid shift count %s", y)
707 x.mode = invalid
708 return
709 }
710 // The lhs is representable as an integer but may not be an integer
711 // (e.g., 2.0, an untyped float) - this can only happen for untyped
712 // non-integer numeric constants. Correct the type so that the shift
713 // result is of integer type.
714 if !isInteger(x.typ) {
715 x.typ = Typ[UntypedInt]
716 }
717 // x is a constant so xval != nil and it must be of Int kind.
718 x.val = constant.Shift(xval, op, uint(s))
719 x.expr = e
720 check.overflow(x, opPos(x.expr))
721 return
722 }
723 724 // non-constant shift with constant lhs
725 if isUntyped(x.typ) {
726 // spec: "If the left operand of a non-constant shift
727 // expression is an untyped constant, the type of the
728 // constant is what it would be if the shift expression
729 // were replaced by its left operand alone.".
730 //
731 // Delay operand checking until we know the final type
732 // by marking the lhs expression as lhs shift operand.
733 //
734 // Usually (in correct programs), the lhs expression
735 // is in the untyped map. However, it is possible to
736 // create incorrect programs where the same expression
737 // is evaluated twice (via a declaration cycle) such
738 // that the lhs expression type is determined in the
739 // first round and thus deleted from the map, and then
740 // not found in the second round (double insertion of
741 // the same expr node still just leads to one entry for
742 // that node, and it can only be deleted once).
743 // Be cautious and check for presence of entry.
744 // Example: var e, f = int(1<<""[f]) // go.dev/issue/11347
745 if info, found := check.untyped[x.expr]; found {
746 info.isLhs = true
747 check.untyped[x.expr] = info
748 }
749 // keep x's type
750 x.mode = value
751 return
752 }
753 }
754 755 // non-constant shift - lhs must be an integer
756 if !allInteger(x.typ) {
757 check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", x)
758 x.mode = invalid
759 return
760 }
761 762 x.mode = value
763 }
764 765 var binaryOpPredicates opPredicates
766 767 func init() {
768 // Setting binaryOpPredicates in init avoids declaration cycles.
769 binaryOpPredicates = opPredicates{
770 token.ADD: allNumericOrString,
771 token.SUB: allNumeric,
772 token.MUL: allNumeric,
773 token.QUO: allNumeric,
774 token.REM: allInteger,
775 776 token.AND: allInteger,
777 token.OR: allInteger,
778 token.XOR: allInteger,
779 token.AND_NOT: allInteger,
780 781 token.LAND: allBoolean,
782 token.LOR: allBoolean,
783 }
784 }
785 786 // If e != nil, it must be the binary expression; it may be nil for non-constant expressions
787 // (when invoked for an assignment operation where the binary expression is implicit).
788 func (check *Checker) binary(x *operand, e ast.Expr, lhs, rhs ast.Expr, op token.Token, opPos token.Pos) {
789 var y operand
790 791 check.expr(nil, x, lhs)
792 check.expr(nil, &y, rhs)
793 794 if x.mode == invalid {
795 return
796 }
797 if y.mode == invalid {
798 x.mode = invalid
799 x.expr = y.expr
800 return
801 }
802 803 if isShift(op) {
804 check.shift(x, &y, e, op)
805 return
806 }
807 808 check.matchTypes(x, &y)
809 if x.mode == invalid {
810 return
811 }
812 813 if isComparison(op) {
814 check.comparison(x, &y, op, false)
815 return
816 }
817 818 if !Identical(x.typ, y.typ) {
819 // only report an error if we have valid types
820 // (otherwise we had an error reported elsewhere already)
821 if isValid(x.typ) && isValid(y.typ) {
822 var posn positioner = x
823 if e != nil {
824 posn = e
825 }
826 if e != nil {
827 check.errorf(posn, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", e, x.typ, y.typ)
828 } else {
829 check.errorf(posn, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ, y.typ)
830 }
831 }
832 x.mode = invalid
833 return
834 }
835 836 // Moxie: | on matching slice types is concatenation.
837 _, mxSliceX := under(x.typ).(*Slice)
838 _, mxSliceY := under(y.typ).(*Slice)
839 mxSliceConcat := mxSliceX || mxSliceY || isString(x.typ) || isString(y.typ)
840 if !(op == token.OR && mxSliceConcat) && !check.op(binaryOpPredicates, x, op) {
841 x.mode = invalid
842 return
843 }
844 845 if op == token.QUO || op == token.REM {
846 // check for zero divisor
847 if (x.mode == constant_ || allInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 {
848 check.error(&y, DivByZero, invalidOp+"division by zero")
849 x.mode = invalid
850 return
851 }
852 853 // check for divisor underflow in complex division (see go.dev/issue/20227)
854 if x.mode == constant_ && y.mode == constant_ && isComplex(x.typ) {
855 re, im := constant.Real(y.val), constant.Imag(y.val)
856 re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
857 if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
858 check.error(&y, DivByZero, invalidOp+"division by zero")
859 x.mode = invalid
860 return
861 }
862 }
863 }
864 865 if x.mode == constant_ && y.mode == constant_ {
866 // if either x or y has an unknown value, the result is unknown
867 if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
868 x.val = constant.MakeUnknown()
869 // x.typ is unchanged
870 return
871 }
872 // force integer division of integer operands
873 if op == token.QUO && isInteger(x.typ) {
874 op = token.QUO_ASSIGN
875 }
876 x.val = constant.BinaryOp(x.val, op, y.val)
877 x.expr = e
878 check.overflow(x, opPos)
879 return
880 }
881 882 x.mode = value
883 // x.typ is unchanged
884 }
885 886 // matchTypes attempts to convert any untyped types x and y such that they match.
887 // If an error occurs, x.mode is set to invalid.
888 func (check *Checker) matchTypes(x, y *operand) {
889 // mayConvert reports whether the operands x and y may
890 // possibly have matching types after converting one
891 // untyped operand to the type of the other.
892 // If mayConvert returns true, we try to convert the
893 // operands to each other's types, and if that fails
894 // we report a conversion failure.
895 // If mayConvert returns false, we continue without an
896 // attempt at conversion, and if the operand types are
897 // not compatible, we report a type mismatch error.
898 mayConvert := func(x, y *operand) bool {
899 // If both operands are typed, there's no need for an implicit conversion.
900 if isTyped(x.typ) && isTyped(y.typ) {
901 return false
902 }
903 // An untyped operand may convert to its default type when paired with an empty interface
904 // TODO(gri) This should only matter for comparisons (the only binary operation that is
905 // valid with interfaces), but in that case the assignability check should take
906 // care of the conversion. Verify and possibly eliminate this extra test.
907 if isNonTypeParamInterface(x.typ) || isNonTypeParamInterface(y.typ) {
908 return true
909 }
910 // A boolean type can only convert to another boolean type.
911 if allBoolean(x.typ) != allBoolean(y.typ) {
912 return false
913 }
914 // A string type can only convert to another string type.
915 if allString(x.typ) != allString(y.typ) {
916 // Moxie: string and []byte unify — allow conversion in either direction.
917 if allString(x.typ) && isByteSlice(y.typ) {
918 return true
919 }
920 if isByteSlice(x.typ) && allString(y.typ) {
921 return true
922 }
923 return false
924 }
925 // Untyped nil can only convert to a type that has a nil.
926 if x.isNil() {
927 return hasNil(y.typ)
928 }
929 if y.isNil() {
930 return hasNil(x.typ)
931 }
932 // An untyped operand cannot convert to a pointer.
933 // TODO(gri) generalize to type parameters
934 if isPointer(x.typ) || isPointer(y.typ) {
935 return false
936 }
937 return true
938 }
939 940 if mayConvert(x, y) {
941 check.convertUntyped(x, y.typ)
942 if x.mode == invalid {
943 return
944 }
945 check.convertUntyped(y, x.typ)
946 if y.mode == invalid {
947 x.mode = invalid
948 return
949 }
950 }
951 }
952 953 // exprKind describes the kind of an expression; the kind
954 // determines if an expression is valid in 'statement context'.
955 type exprKind int
956 957 const (
958 conversion exprKind = iota
959 expression
960 statement
961 )
962 963 // target represent the (signature) type and description of the LHS
964 // variable of an assignment, or of a function result variable.
965 type target struct {
966 sig *Signature
967 desc string
968 }
969 970 // newTarget creates a new target for the given type and description.
971 // The result is nil if typ is not a signature.
972 func newTarget(typ Type, desc string) *target {
973 if typ != nil {
974 if sig, _ := under(typ).(*Signature); sig != nil {
975 return &target{sig, desc}
976 }
977 }
978 return nil
979 }
980 981 // rawExpr typechecks expression e and initializes x with the expression
982 // value or type. If an error occurred, x.mode is set to invalid.
983 // If a non-nil target T is given and e is a generic function,
984 // T is used to infer the type arguments for e.
985 // If hint != nil, it is the type of a composite literal element.
986 // If allowGeneric is set, the operand type may be an uninstantiated
987 // parameterized type or function value.
988 func (check *Checker) rawExpr(T *target, x *operand, e ast.Expr, hint Type, allowGeneric bool) exprKind {
989 if check.conf._Trace {
990 check.trace(e.Pos(), "-- expr %s", e)
991 check.indent++
992 defer func() {
993 check.indent--
994 check.trace(e.Pos(), "=> %s", x)
995 }()
996 }
997 998 kind := check.exprInternal(T, x, e, hint)
999 1000 if !allowGeneric {
1001 check.nonGeneric(T, x)
1002 }
1003 1004 check.record(x)
1005 1006 return kind
1007 }
1008 1009 // If x is a generic type, or a generic function whose type arguments cannot be inferred
1010 // from a non-nil target T, nonGeneric reports an error and invalidates x.mode and x.typ.
1011 // Otherwise it leaves x alone.
1012 func (check *Checker) nonGeneric(T *target, x *operand) {
1013 if x.mode == invalid || x.mode == novalue {
1014 return
1015 }
1016 var what string
1017 switch t := x.typ.(type) {
1018 case *Alias, *Named:
1019 if isGeneric(t) {
1020 what = "type"
1021 }
1022 case *Signature:
1023 if t.tparams != nil {
1024 if enableReverseTypeInference && T != nil {
1025 check.funcInst(T, x.Pos(), x, nil, true)
1026 return
1027 }
1028 what = "function"
1029 }
1030 }
1031 if what != "" {
1032 check.errorf(x.expr, WrongTypeArgCount, "cannot use generic %s %s without instantiation", what, x.expr)
1033 x.mode = invalid
1034 x.typ = Typ[Invalid]
1035 }
1036 }
1037 1038 // exprInternal contains the core of type checking of expressions.
1039 // Must only be called by rawExpr.
1040 // (See rawExpr for an explanation of the parameters.)
1041 func (check *Checker) exprInternal(T *target, x *operand, e ast.Expr, hint Type) exprKind {
1042 // make sure x has a valid state in case of bailout
1043 // (was go.dev/issue/5770)
1044 x.mode = invalid
1045 x.typ = Typ[Invalid]
1046 1047 switch e := e.(type) {
1048 case *ast.BadExpr:
1049 goto Error // error was reported before
1050 1051 case *ast.Ident:
1052 check.ident(x, e, nil, false)
1053 1054 case *ast.Ellipsis:
1055 // ellipses are handled explicitly where they are valid
1056 check.error(e, InvalidSyntaxTree, "invalid use of ...")
1057 goto Error
1058 1059 case *ast.BasicLit:
1060 check.basicLit(x, e)
1061 if x.mode == invalid {
1062 goto Error
1063 }
1064 1065 case *ast.FuncLit:
1066 check.funcLit(x, e)
1067 if x.mode == invalid {
1068 goto Error
1069 }
1070 1071 case *ast.CompositeLit:
1072 check.compositeLit(x, e, hint)
1073 if x.mode == invalid {
1074 goto Error
1075 }
1076 1077 case *ast.ParenExpr:
1078 // type inference doesn't go past parentheses (target type T = nil)
1079 kind := check.rawExpr(nil, x, e.X, nil, false)
1080 x.expr = e
1081 return kind
1082 1083 case *ast.SelectorExpr:
1084 check.selector(x, e, nil, false)
1085 1086 case *ast.IndexExpr, *ast.IndexListExpr:
1087 ix := unpackIndexedExpr(e)
1088 if check.indexExpr(x, ix) {
1089 if !enableReverseTypeInference {
1090 T = nil
1091 }
1092 check.funcInst(T, e.Pos(), x, ix, true)
1093 }
1094 if x.mode == invalid {
1095 goto Error
1096 }
1097 1098 case *ast.SliceExpr:
1099 check.sliceExpr(x, e)
1100 if x.mode == invalid {
1101 goto Error
1102 }
1103 1104 case *ast.TypeAssertExpr:
1105 check.expr(nil, x, e.X)
1106 if x.mode == invalid {
1107 goto Error
1108 }
1109 // x.(type) expressions are handled explicitly in type switches
1110 if e.Type == nil {
1111 // Don't use InvalidSyntaxTree because this can occur in the AST produced by
1112 // go/parser.
1113 check.error(e, BadTypeKeyword, "use of .(type) outside type switch")
1114 goto Error
1115 }
1116 if isTypeParam(x.typ) {
1117 check.errorf(x, InvalidAssert, invalidOp+"cannot use type assertion on type parameter value %s", x)
1118 goto Error
1119 }
1120 if _, ok := under(x.typ).(*Interface); !ok {
1121 check.errorf(x, InvalidAssert, invalidOp+"%s is not an interface", x)
1122 goto Error
1123 }
1124 T := check.varType(e.Type)
1125 if !isValid(T) {
1126 goto Error
1127 }
1128 check.typeAssertion(e, x, T, false)
1129 x.mode = commaok
1130 x.typ = T
1131 1132 case *ast.CallExpr:
1133 return check.callExpr(x, e)
1134 1135 case *ast.StarExpr:
1136 check.exprOrType(x, e.X, false)
1137 switch x.mode {
1138 case invalid:
1139 goto Error
1140 case typexpr:
1141 check.validVarType(e.X, x.typ)
1142 x.typ = &Pointer{base: x.typ}
1143 default:
1144 var base Type
1145 if !underIs(x.typ, func(u Type) bool {
1146 p, _ := u.(*Pointer)
1147 if p == nil {
1148 check.errorf(x, InvalidIndirection, invalidOp+"cannot indirect %s", x)
1149 return false
1150 }
1151 if base != nil && !Identical(p.base, base) {
1152 check.errorf(x, InvalidIndirection, invalidOp+"pointers of %s must have identical base types", x)
1153 return false
1154 }
1155 base = p.base
1156 return true
1157 }) {
1158 goto Error
1159 }
1160 x.mode = variable
1161 x.typ = base
1162 }
1163 1164 case *ast.UnaryExpr:
1165 check.unary(x, e)
1166 if x.mode == invalid {
1167 goto Error
1168 }
1169 if e.Op == token.ARROW {
1170 x.expr = e
1171 return statement // receive operations may appear in statement context
1172 }
1173 1174 case *ast.BinaryExpr:
1175 check.binary(x, e, e.X, e.Y, e.Op, e.OpPos)
1176 if x.mode == invalid {
1177 goto Error
1178 }
1179 1180 case *ast.KeyValueExpr:
1181 // key:value expressions are handled in composite literals
1182 check.error(e, InvalidSyntaxTree, "no key:value expected")
1183 goto Error
1184 1185 case *ast.ArrayType, *ast.StructType, *ast.FuncType,
1186 *ast.InterfaceType, *ast.MapType, *ast.ChanType:
1187 x.mode = typexpr
1188 x.typ = check.typ(e)
1189 // Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue
1190 // even though check.typ has already called it. This is fine as both
1191 // times the same expression and type are recorded. It is also not a
1192 // performance issue because we only reach here for composite literal
1193 // types, which are comparatively rare.
1194 1195 default:
1196 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e))
1197 }
1198 1199 // everything went well
1200 x.expr = e
1201 return expression
1202 1203 Error:
1204 x.mode = invalid
1205 x.expr = e
1206 return statement // avoid follow-up errors
1207 }
1208 1209 // keyVal maps a complex, float, integer, string or boolean constant value
1210 // to the corresponding complex128, float64, int64, uint64, string, or bool
1211 // Go value if possible; otherwise it returns x.
1212 // A complex constant that can be represented as a float (such as 1.2 + 0i)
1213 // is returned as a floating point value; if a floating point value can be
1214 // represented as an integer (such as 1.0) it is returned as an integer value.
1215 // This ensures that constants of different kind but equal value (such as
1216 // 1.0 + 0i, 1.0, 1) result in the same value.
1217 func keyVal(x constant.Value) interface{} {
1218 switch x.Kind() {
1219 case constant.Complex:
1220 f := constant.ToFloat(x)
1221 if f.Kind() != constant.Float {
1222 r, _ := constant.Float64Val(constant.Real(x))
1223 i, _ := constant.Float64Val(constant.Imag(x))
1224 return complex(r, i)
1225 }
1226 x = f
1227 fallthrough
1228 case constant.Float:
1229 i := constant.ToInt(x)
1230 if i.Kind() != constant.Int {
1231 v, _ := constant.Float64Val(x)
1232 return v
1233 }
1234 x = i
1235 fallthrough
1236 case constant.Int:
1237 if v, ok := constant.Int64Val(x); ok {
1238 return v
1239 }
1240 if v, ok := constant.Uint64Val(x); ok {
1241 return v
1242 }
1243 case constant.String:
1244 return constant.StringVal(x)
1245 case constant.Bool:
1246 return constant.BoolVal(x)
1247 }
1248 return x
1249 }
1250 1251 // typeAssertion checks x.(T). The type of x must be an interface.
1252 func (check *Checker) typeAssertion(e ast.Expr, x *operand, T Type, typeSwitch bool) {
1253 var cause string
1254 if check.assertableTo(x.typ, T, &cause) {
1255 return // success
1256 }
1257 1258 if typeSwitch {
1259 check.errorf(e, ImpossibleAssert, "impossible type switch case: %s\n\t%s cannot have dynamic type %s %s", e, x, T, cause)
1260 return
1261 }
1262 1263 check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ, cause)
1264 }
1265 1266 // expr typechecks expression e and initializes x with the expression value.
1267 // If a non-nil target T is given and e is a generic function or
1268 // a function call, T is used to infer the type arguments for e.
1269 // The result must be a single value.
1270 // If an error occurred, x.mode is set to invalid.
1271 func (check *Checker) expr(T *target, x *operand, e ast.Expr) {
1272 check.rawExpr(T, x, e, nil, false)
1273 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1274 check.singleValue(x)
1275 }
1276 1277 // genericExpr is like expr but the result may also be generic.
1278 func (check *Checker) genericExpr(x *operand, e ast.Expr) {
1279 check.rawExpr(nil, x, e, nil, true)
1280 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1281 check.singleValue(x)
1282 }
1283 1284 // multiExpr typechecks e and returns its value (or values) in list.
1285 // If allowCommaOk is set and e is a map index, comma-ok, or comma-err
1286 // expression, the result is a two-element list containing the value
1287 // of e, and an untyped bool value or an error value, respectively.
1288 // If an error occurred, list[0] is not valid.
1289 func (check *Checker) multiExpr(e ast.Expr, allowCommaOk bool) (list []*operand, commaOk bool) {
1290 var x operand
1291 check.rawExpr(nil, &x, e, nil, false)
1292 check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
1293 1294 if t, ok := x.typ.(*Tuple); ok && x.mode != invalid {
1295 // multiple values
1296 list = make([]*operand, t.Len())
1297 for i, v := range t.vars {
1298 list[i] = &operand{mode: value, expr: e, typ: v.typ}
1299 }
1300 return
1301 }
1302 1303 // exactly one (possibly invalid or comma-ok) value
1304 list = []*operand{&x}
1305 if allowCommaOk && (x.mode == mapindex || x.mode == commaok || x.mode == commaerr) {
1306 x2 := &operand{mode: value, expr: e, typ: Typ[UntypedBool]}
1307 if x.mode == commaerr {
1308 x2.typ = universeError
1309 }
1310 list = append(list, x2)
1311 commaOk = true
1312 }
1313 1314 return
1315 }
1316 1317 // exprWithHint typechecks expression e and initializes x with the expression value;
1318 // hint is the type of a composite literal element.
1319 // If an error occurred, x.mode is set to invalid.
1320 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) {
1321 assert(hint != nil)
1322 check.rawExpr(nil, x, e, hint, false)
1323 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1324 check.singleValue(x)
1325 }
1326 1327 // exprOrType typechecks expression or type e and initializes x with the expression value or type.
1328 // If allowGeneric is set, the operand type may be an uninstantiated parameterized type or function
1329 // value.
1330 // If an error occurred, x.mode is set to invalid.
1331 func (check *Checker) exprOrType(x *operand, e ast.Expr, allowGeneric bool) {
1332 check.rawExpr(nil, x, e, nil, allowGeneric)
1333 check.exclude(x, 1<<novalue)
1334 check.singleValue(x)
1335 }
1336 1337 // exclude reports an error if x.mode is in modeset and sets x.mode to invalid.
1338 // The modeset may contain any of 1<<novalue, 1<<builtin, 1<<typexpr.
1339 func (check *Checker) exclude(x *operand, modeset uint) {
1340 if modeset&(1<<x.mode) != 0 {
1341 var msg string
1342 var code Code
1343 switch x.mode {
1344 case novalue:
1345 if modeset&(1<<typexpr) != 0 {
1346 msg = "%s used as value"
1347 } else {
1348 msg = "%s used as value or type"
1349 }
1350 code = TooManyValues
1351 case builtin:
1352 msg = "%s must be called"
1353 code = UncalledBuiltin
1354 case typexpr:
1355 msg = "%s is not an expression"
1356 code = NotAnExpr
1357 default:
1358 panic("unreachable")
1359 }
1360 check.errorf(x, code, msg, x)
1361 x.mode = invalid
1362 }
1363 }
1364 1365 // singleValue reports an error if x describes a tuple and sets x.mode to invalid.
1366 func (check *Checker) singleValue(x *operand) {
1367 if x.mode == value {
1368 // tuple types are never named - no need for underlying type below
1369 if t, ok := x.typ.(*Tuple); ok {
1370 assert(t.Len() != 1)
1371 check.errorf(x, TooManyValues, "multiple-value %s in single-value context", x)
1372 x.mode = invalid
1373 }
1374 }
1375 }
1376