Source file
src/go/types/expr.go
1
2
3
4
5
6
7 package types
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/internal/typeparams"
14 "go/token"
15 "math"
16 )
17
18
59
60 type opPredicates map[token.Token]func(Type) bool
61
62 var unaryOpPredicates opPredicates
63
64 func init() {
65
66 unaryOpPredicates = opPredicates{
67 token.ADD: allNumeric,
68 token.SUB: allNumeric,
69 token.XOR: allInteger,
70 token.NOT: allBoolean,
71 }
72 }
73
74 func (check *Checker) op(m opPredicates, x *operand, op token.Token) bool {
75 if pred := m[op]; pred != nil {
76 if !pred(x.typ) {
77 check.invalidOp(x, _UndefinedOp, "operator %s not defined on %s", op, x)
78 return false
79 }
80 } else {
81 check.invalidAST(x, "unknown operator %s", op)
82 return false
83 }
84 return true
85 }
86
87
88
89
90 func (check *Checker) overflow(x *operand, opPos token.Pos) {
91 assert(x.mode == constant_)
92
93 if x.val.Kind() == constant.Unknown {
94
95
96
97 check.errorf(atPos(opPos), _InvalidConstVal, "constant result is not representable")
98 return
99 }
100
101
102
103
104
105 if isTyped(x.typ) {
106 check.representable(x, under(x.typ).(*Basic))
107 return
108 }
109
110
111 const prec = 512
112 if x.val.Kind() == constant.Int && constant.BitLen(x.val) > prec {
113 check.errorf(atPos(opPos), _InvalidConstVal, "constant %s overflow", opName(x.expr))
114 x.val = constant.MakeUnknown()
115 }
116 }
117
118
119
120 func opName(e ast.Expr) string {
121 switch e := e.(type) {
122 case *ast.BinaryExpr:
123 if int(e.Op) < len(op2str2) {
124 return op2str2[e.Op]
125 }
126 case *ast.UnaryExpr:
127 if int(e.Op) < len(op2str1) {
128 return op2str1[e.Op]
129 }
130 }
131 return ""
132 }
133
134 var op2str1 = [...]string{
135 token.XOR: "bitwise complement",
136 }
137
138
139 var op2str2 = [...]string{
140 token.ADD: "addition",
141 token.SUB: "subtraction",
142 token.XOR: "bitwise XOR",
143 token.MUL: "multiplication",
144 token.SHL: "shift",
145 }
146
147
148
149 func underIs(typ Type, f func(Type) bool) bool {
150 if tpar, _ := typ.(*TypeParam); tpar != nil {
151 return tpar.underIs(f)
152 }
153 return f(under(typ))
154 }
155
156
157 func (check *Checker) unary(x *operand, e *ast.UnaryExpr) {
158 check.expr(x, e.X)
159 if x.mode == invalid {
160 return
161 }
162 switch e.Op {
163 case token.AND:
164
165
166 if _, ok := unparen(e.X).(*ast.CompositeLit); !ok && x.mode != variable {
167 check.invalidOp(x, _UnaddressableOperand, "cannot take address of %s", x)
168 x.mode = invalid
169 return
170 }
171 x.mode = value
172 x.typ = &Pointer{base: x.typ}
173 return
174
175 case token.ARROW:
176 u := coreType(x.typ)
177 if u == nil {
178 check.invalidOp(x, _InvalidReceive, "cannot receive from %s: no core type", x)
179 x.mode = invalid
180 return
181 }
182 ch, _ := u.(*Chan)
183 if ch == nil {
184 check.invalidOp(x, _InvalidReceive, "cannot receive from non-channel %s", x)
185 x.mode = invalid
186 return
187 }
188 if ch.dir == SendOnly {
189 check.invalidOp(x, _InvalidReceive, "cannot receive from send-only channel %s", x)
190 x.mode = invalid
191 return
192 }
193
194 x.mode = commaok
195 x.typ = ch.elem
196 check.hasCallOrRecv = true
197 return
198
199 case token.TILDE:
200
201 check.error(e, _UndefinedOp, "cannot use ~ outside of interface or type constraint")
202 x.mode = invalid
203 return
204 }
205
206 if !check.op(unaryOpPredicates, x, e.Op) {
207 x.mode = invalid
208 return
209 }
210
211 if x.mode == constant_ {
212 if x.val.Kind() == constant.Unknown {
213
214 return
215 }
216 var prec uint
217 if isUnsigned(x.typ) {
218 prec = uint(check.conf.sizeof(x.typ) * 8)
219 }
220 x.val = constant.UnaryOp(e.Op, x.val, prec)
221 x.expr = e
222 check.overflow(x, x.Pos())
223 return
224 }
225
226 x.mode = value
227
228 }
229
230 func isShift(op token.Token) bool {
231 return op == token.SHL || op == token.SHR
232 }
233
234 func isComparison(op token.Token) bool {
235
236 switch op {
237 case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
238 return true
239 }
240 return false
241 }
242
243 func fitsFloat32(x constant.Value) bool {
244 f32, _ := constant.Float32Val(x)
245 f := float64(f32)
246 return !math.IsInf(f, 0)
247 }
248
249 func roundFloat32(x constant.Value) constant.Value {
250 f32, _ := constant.Float32Val(x)
251 f := float64(f32)
252 if !math.IsInf(f, 0) {
253 return constant.MakeFloat64(f)
254 }
255 return nil
256 }
257
258 func fitsFloat64(x constant.Value) bool {
259 f, _ := constant.Float64Val(x)
260 return !math.IsInf(f, 0)
261 }
262
263 func roundFloat64(x constant.Value) constant.Value {
264 f, _ := constant.Float64Val(x)
265 if !math.IsInf(f, 0) {
266 return constant.MakeFloat64(f)
267 }
268 return nil
269 }
270
271
272
273
274
275
276
277
278
279
280
281
282
283 func representableConst(x constant.Value, check *Checker, typ *Basic, rounded *constant.Value) bool {
284 if x.Kind() == constant.Unknown {
285 return true
286 }
287
288 var conf *Config
289 if check != nil {
290 conf = check.conf
291 }
292
293 switch {
294 case isInteger(typ):
295 x := constant.ToInt(x)
296 if x.Kind() != constant.Int {
297 return false
298 }
299 if rounded != nil {
300 *rounded = x
301 }
302 if x, ok := constant.Int64Val(x); ok {
303 switch typ.kind {
304 case Int:
305 var s = uint(conf.sizeof(typ)) * 8
306 return int64(-1)<<(s-1) <= x && x <= int64(1)<<(s-1)-1
307 case Int8:
308 const s = 8
309 return -1<<(s-1) <= x && x <= 1<<(s-1)-1
310 case Int16:
311 const s = 16
312 return -1<<(s-1) <= x && x <= 1<<(s-1)-1
313 case Int32:
314 const s = 32
315 return -1<<(s-1) <= x && x <= 1<<(s-1)-1
316 case Int64, UntypedInt:
317 return true
318 case Uint, Uintptr:
319 if s := uint(conf.sizeof(typ)) * 8; s < 64 {
320 return 0 <= x && x <= int64(1)<<s-1
321 }
322 return 0 <= x
323 case Uint8:
324 const s = 8
325 return 0 <= x && x <= 1<<s-1
326 case Uint16:
327 const s = 16
328 return 0 <= x && x <= 1<<s-1
329 case Uint32:
330 const s = 32
331 return 0 <= x && x <= 1<<s-1
332 case Uint64:
333 return 0 <= x
334 default:
335 unreachable()
336 }
337 }
338
339 switch n := constant.BitLen(x); typ.kind {
340 case Uint, Uintptr:
341 var s = uint(conf.sizeof(typ)) * 8
342 return constant.Sign(x) >= 0 && n <= int(s)
343 case Uint64:
344 return constant.Sign(x) >= 0 && n <= 64
345 case UntypedInt:
346 return true
347 }
348
349 case isFloat(typ):
350 x := constant.ToFloat(x)
351 if x.Kind() != constant.Float {
352 return false
353 }
354 switch typ.kind {
355 case Float32:
356 if rounded == nil {
357 return fitsFloat32(x)
358 }
359 r := roundFloat32(x)
360 if r != nil {
361 *rounded = r
362 return true
363 }
364 case Float64:
365 if rounded == nil {
366 return fitsFloat64(x)
367 }
368 r := roundFloat64(x)
369 if r != nil {
370 *rounded = r
371 return true
372 }
373 case UntypedFloat:
374 return true
375 default:
376 unreachable()
377 }
378
379 case isComplex(typ):
380 x := constant.ToComplex(x)
381 if x.Kind() != constant.Complex {
382 return false
383 }
384 switch typ.kind {
385 case Complex64:
386 if rounded == nil {
387 return fitsFloat32(constant.Real(x)) && fitsFloat32(constant.Imag(x))
388 }
389 re := roundFloat32(constant.Real(x))
390 im := roundFloat32(constant.Imag(x))
391 if re != nil && im != nil {
392 *rounded = constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
393 return true
394 }
395 case Complex128:
396 if rounded == nil {
397 return fitsFloat64(constant.Real(x)) && fitsFloat64(constant.Imag(x))
398 }
399 re := roundFloat64(constant.Real(x))
400 im := roundFloat64(constant.Imag(x))
401 if re != nil && im != nil {
402 *rounded = constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
403 return true
404 }
405 case UntypedComplex:
406 return true
407 default:
408 unreachable()
409 }
410
411 case isString(typ):
412 return x.Kind() == constant.String
413
414 case isBoolean(typ):
415 return x.Kind() == constant.Bool
416 }
417
418 return false
419 }
420
421
422
423 func (check *Checker) representable(x *operand, typ *Basic) {
424 v, code := check.representation(x, typ)
425 if code != 0 {
426 check.invalidConversion(code, x, typ)
427 x.mode = invalid
428 return
429 }
430 assert(v != nil)
431 x.val = v
432 }
433
434
435
436
437
438 func (check *Checker) representation(x *operand, typ *Basic) (constant.Value, errorCode) {
439 assert(x.mode == constant_)
440 v := x.val
441 if !representableConst(x.val, check, typ, &v) {
442 if isNumeric(x.typ) && isNumeric(typ) {
443
444
445
446
447
448
449
450 if !isInteger(x.typ) && isInteger(typ) {
451 return nil, _TruncatedFloat
452 } else {
453 return nil, _NumericOverflow
454 }
455 }
456 return nil, _InvalidConstVal
457 }
458 return v, 0
459 }
460
461 func (check *Checker) invalidConversion(code errorCode, x *operand, target Type) {
462 msg := "cannot convert %s to %s"
463 switch code {
464 case _TruncatedFloat:
465 msg = "%s truncated to %s"
466 case _NumericOverflow:
467 msg = "%s overflows %s"
468 }
469 check.errorf(x, code, msg, x, target)
470 }
471
472
473
474
475
476
477
478
479
480
481 func (check *Checker) updateExprType(x ast.Expr, typ Type, final bool) {
482 check.updateExprType0(nil, x, typ, final)
483 }
484
485 func (check *Checker) updateExprType0(parent, x ast.Expr, typ Type, final bool) {
486 old, found := check.untyped[x]
487 if !found {
488 return
489 }
490
491
492 switch x := x.(type) {
493 case *ast.BadExpr,
494 *ast.FuncLit,
495 *ast.CompositeLit,
496 *ast.IndexExpr,
497 *ast.SliceExpr,
498 *ast.TypeAssertExpr,
499 *ast.StarExpr,
500 *ast.KeyValueExpr,
501 *ast.ArrayType,
502 *ast.StructType,
503 *ast.FuncType,
504 *ast.InterfaceType,
505 *ast.MapType,
506 *ast.ChanType:
507
508
509
510 if debug {
511 check.dump("%v: found old type(%s): %s (new: %s)", x.Pos(), x, old.typ, typ)
512 unreachable()
513 }
514 return
515
516 case *ast.CallExpr:
517
518
519
520
521 case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr:
522
523
524
525
526 case *ast.ParenExpr:
527 check.updateExprType0(x, x.X, typ, final)
528
529 case *ast.UnaryExpr:
530
531
532
533
534
535 if old.val != nil {
536 break
537 }
538 check.updateExprType0(x, x.X, typ, final)
539
540 case *ast.BinaryExpr:
541 if old.val != nil {
542 break
543 }
544 if isComparison(x.Op) {
545
546
547 } else if isShift(x.Op) {
548
549
550 check.updateExprType0(x, x.X, typ, final)
551 } else {
552
553 check.updateExprType0(x, x.X, typ, final)
554 check.updateExprType0(x, x.Y, typ, final)
555 }
556
557 default:
558 unreachable()
559 }
560
561
562
563 if !final && isUntyped(typ) {
564 old.typ = under(typ).(*Basic)
565 check.untyped[x] = old
566 return
567 }
568
569
570
571 delete(check.untyped, x)
572
573 if old.isLhs {
574
575
576
577 if !allInteger(typ) {
578 if compilerErrorMessages {
579 check.invalidOp(x, _InvalidShiftOperand, "%s (shift of type %s)", parent, typ)
580 } else {
581 check.invalidOp(x, _InvalidShiftOperand, "shifted operand %s (type %s) must be integer", x, typ)
582 }
583 return
584 }
585
586
587
588 }
589 if old.val != nil {
590
591 c := operand{old.mode, x, old.typ, old.val, 0}
592 check.convertUntyped(&c, typ)
593 if c.mode == invalid {
594 return
595 }
596 }
597
598
599 check.recordTypeAndValue(x, old.mode, typ, old.val)
600 }
601
602
603 func (check *Checker) updateExprVal(x ast.Expr, val constant.Value) {
604 if info, ok := check.untyped[x]; ok {
605 info.val = val
606 check.untyped[x] = info
607 }
608 }
609
610
611 func (check *Checker) convertUntyped(x *operand, target Type) {
612 newType, val, code := check.implicitTypeAndValue(x, target)
613 if code != 0 {
614 t := target
615 if !isTypeParam(target) {
616 t = safeUnderlying(target)
617 }
618 check.invalidConversion(code, x, t)
619 x.mode = invalid
620 return
621 }
622 if val != nil {
623 x.val = val
624 check.updateExprVal(x.expr, val)
625 }
626 if newType != x.typ {
627 x.typ = newType
628 check.updateExprType(x.expr, newType, false)
629 }
630 }
631
632
633
634
635
636
637
638 func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, errorCode) {
639 if x.mode == invalid || isTyped(x.typ) || target == Typ[Invalid] {
640 return x.typ, nil, 0
641 }
642
643 if isUntyped(target) {
644
645 xkind := x.typ.(*Basic).kind
646 tkind := target.(*Basic).kind
647 if isNumeric(x.typ) && isNumeric(target) {
648 if xkind < tkind {
649 return target, nil, 0
650 }
651 } else if xkind != tkind {
652 return nil, nil, _InvalidUntypedConversion
653 }
654 return x.typ, nil, 0
655 }
656
657 switch u := under(target).(type) {
658 case *Basic:
659 if x.mode == constant_ {
660 v, code := check.representation(x, u)
661 if code != 0 {
662 return nil, nil, code
663 }
664 return target, v, code
665 }
666
667
668
669
670 switch x.typ.(*Basic).kind {
671 case UntypedBool:
672 if !isBoolean(target) {
673 return nil, nil, _InvalidUntypedConversion
674 }
675 case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex:
676 if !isNumeric(target) {
677 return nil, nil, _InvalidUntypedConversion
678 }
679 case UntypedString:
680
681
682
683 if !isString(target) {
684 return nil, nil, _InvalidUntypedConversion
685 }
686 case UntypedNil:
687
688 if !hasNil(target) {
689 return nil, nil, _InvalidUntypedConversion
690 }
691
692 return Typ[UntypedNil], nil, 0
693 default:
694 return nil, nil, _InvalidUntypedConversion
695 }
696 case *Interface:
697 if isTypeParam(target) {
698 if !u.typeSet().underIs(func(u Type) bool {
699 if u == nil {
700 return false
701 }
702 t, _, _ := check.implicitTypeAndValue(x, u)
703 return t != nil
704 }) {
705 return nil, nil, _InvalidUntypedConversion
706 }
707
708 if x.isNil() {
709 return Typ[UntypedNil], nil, 0
710 }
711 break
712 }
713
714
715
716
717 if x.isNil() {
718 return Typ[UntypedNil], nil, 0
719 }
720
721 if !u.Empty() {
722 return nil, nil, _InvalidUntypedConversion
723 }
724 return Default(x.typ), nil, 0
725 case *Pointer, *Signature, *Slice, *Map, *Chan:
726 if !x.isNil() {
727 return nil, nil, _InvalidUntypedConversion
728 }
729
730 return Typ[UntypedNil], nil, 0
731 default:
732 return nil, nil, _InvalidUntypedConversion
733 }
734 return target, nil, 0
735 }
736
737
738 func (check *Checker) comparison(x, y *operand, op token.Token, switchCase bool) {
739 if switchCase {
740 op = token.EQL
741 }
742
743 errOp := x
744 cause := ""
745
746
747
748 code := _MismatchedTypes
749 ok, _ := x.assignableTo(check, y.typ, nil)
750 if !ok {
751 ok, _ = y.assignableTo(check, x.typ, nil)
752 }
753 if !ok {
754
755
756
757 errOp = y
758
759
760 if !compilerErrorMessages {
761 errOp = x
762 }
763 cause = check.sprintf("mismatched types %s and %s", x.typ, y.typ)
764 goto Error
765 }
766
767
768 code = _UndefinedOp
769 switch op {
770 case token.EQL, token.NEQ:
771
772 switch {
773 case x.isNil() || y.isNil():
774
775 typ := x.typ
776 if x.isNil() {
777 typ = y.typ
778 }
779 if !hasNil(typ) {
780
781
782
783
784 errOp = y
785 goto Error
786 }
787
788 case !Comparable(x.typ):
789 errOp = x
790 cause = check.incomparableCause(x.typ)
791 goto Error
792
793 case !Comparable(y.typ):
794 errOp = y
795 cause = check.incomparableCause(y.typ)
796 goto Error
797 }
798
799 case token.LSS, token.LEQ, token.GTR, token.GEQ:
800
801 switch {
802 case !allOrdered(x.typ):
803 errOp = x
804 goto Error
805 case !allOrdered(y.typ):
806 errOp = y
807 goto Error
808 }
809
810 default:
811 unreachable()
812 }
813
814
815 if x.mode == constant_ && y.mode == constant_ {
816 x.val = constant.MakeBool(constant.Compare(x.val, op, y.val))
817
818
819 } else {
820 x.mode = value
821
822
823
824
825 check.updateExprType(x.expr, Default(x.typ), true)
826 check.updateExprType(y.expr, Default(y.typ), true)
827 }
828
829
830
831 x.typ = Typ[UntypedBool]
832 return
833
834 Error:
835
836 if cause == "" {
837 if isTypeParam(x.typ) || isTypeParam(y.typ) {
838
839 if !isTypeParam(x.typ) {
840 errOp = y
841 }
842 cause = check.sprintf("type parameter %s is not comparable with %s", errOp.typ, op)
843 } else {
844 cause = check.sprintf("operator %s not defined on %s", op, check.kindString(errOp.typ))
845 }
846 }
847 if switchCase {
848 check.errorf(x, code, "invalid case %s in switch on %s (%s)", x.expr, y.expr, cause)
849 } else {
850 if compilerErrorMessages {
851 check.invalidOp(errOp, code, "%s %s %s (%s)", x.expr, op, y.expr, cause)
852 } else {
853 check.invalidOp(errOp, code, "cannot compare %s %s %s (%s)", x.expr, op, y.expr, cause)
854 }
855 }
856 x.mode = invalid
857 }
858
859
860
861 func (check *Checker) incomparableCause(typ Type) string {
862 switch under(typ).(type) {
863 case *Slice, *Signature, *Map:
864 return check.kindString(typ) + " can only be compared to nil"
865 }
866
867 var cause string
868 comparable(typ, true, nil, func(format string, args ...interface{}) {
869 cause = check.sprintf(format, args...)
870 })
871 return cause
872 }
873
874
875 func (check *Checker) kindString(typ Type) string {
876 switch under(typ).(type) {
877 case *Array:
878 return "array"
879 case *Slice:
880 return "slice"
881 case *Struct:
882 return "struct"
883 case *Pointer:
884 return "pointer"
885 case *Signature:
886 return "func"
887 case *Interface:
888 if isTypeParam(typ) {
889 return check.sprintf("type parameter %s", typ)
890 }
891 return "interface"
892 case *Map:
893 return "map"
894 case *Chan:
895 return "chan"
896 default:
897 return check.sprintf("%s", typ)
898 }
899 }
900
901
902 func (check *Checker) shift(x, y *operand, e ast.Expr, op token.Token) {
903
904
905 var xval constant.Value
906 if x.mode == constant_ {
907 xval = constant.ToInt(x.val)
908 }
909
910 if allInteger(x.typ) || isUntyped(x.typ) && xval != nil && xval.Kind() == constant.Int {
911
912
913 } else {
914
915 check.invalidOp(x, _InvalidShiftOperand, "shifted operand %s must be integer", x)
916 x.mode = invalid
917 return
918 }
919
920
921
922
923
924
925 if y.mode == constant_ {
926
927 yval := constant.ToInt(y.val)
928 if yval.Kind() == constant.Int && constant.Sign(yval) < 0 {
929 check.invalidOp(y, _InvalidShiftCount, "negative shift count %s", y)
930 x.mode = invalid
931 return
932 }
933
934 if isUntyped(y.typ) {
935
936
937 check.representable(y, Typ[Uint])
938 if y.mode == invalid {
939 x.mode = invalid
940 return
941 }
942 }
943 } else {
944
945 switch {
946 case allInteger(y.typ):
947 if !allUnsigned(y.typ) && !check.allowVersion(check.pkg, 1, 13) {
948 check.invalidOp(y, _InvalidShiftCount, "signed shift count %s requires go1.13 or later", y)
949 x.mode = invalid
950 return
951 }
952 case isUntyped(y.typ):
953
954
955 check.convertUntyped(y, Typ[Uint])
956 if y.mode == invalid {
957 x.mode = invalid
958 return
959 }
960 default:
961 check.invalidOp(y, _InvalidShiftCount, "shift count %s must be integer", y)
962 x.mode = invalid
963 return
964 }
965 }
966
967 if x.mode == constant_ {
968 if y.mode == constant_ {
969
970 if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
971 x.val = constant.MakeUnknown()
972
973 if !isInteger(x.typ) {
974 x.typ = Typ[UntypedInt]
975 }
976 return
977 }
978
979 const shiftBound = 1023 - 1 + 52
980 s, ok := constant.Uint64Val(y.val)
981 if !ok || s > shiftBound {
982 check.invalidOp(y, _InvalidShiftCount, "invalid shift count %s", y)
983 x.mode = invalid
984 return
985 }
986
987
988
989
990 if !isInteger(x.typ) {
991 x.typ = Typ[UntypedInt]
992 }
993
994 x.val = constant.Shift(xval, op, uint(s))
995 x.expr = e
996 opPos := x.Pos()
997 if b, _ := e.(*ast.BinaryExpr); b != nil {
998 opPos = b.OpPos
999 }
1000 check.overflow(x, opPos)
1001 return
1002 }
1003
1004
1005 if isUntyped(x.typ) {
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025 if info, found := check.untyped[x.expr]; found {
1026 info.isLhs = true
1027 check.untyped[x.expr] = info
1028 }
1029
1030 x.mode = value
1031 return
1032 }
1033 }
1034
1035
1036 if !allInteger(x.typ) {
1037 check.invalidOp(x, _InvalidShiftOperand, "shifted operand %s must be integer", x)
1038 x.mode = invalid
1039 return
1040 }
1041
1042 x.mode = value
1043 }
1044
1045 var binaryOpPredicates opPredicates
1046
1047 func init() {
1048
1049 binaryOpPredicates = opPredicates{
1050 token.ADD: allNumericOrString,
1051 token.SUB: allNumeric,
1052 token.MUL: allNumeric,
1053 token.QUO: allNumeric,
1054 token.REM: allInteger,
1055
1056 token.AND: allInteger,
1057 token.OR: allInteger,
1058 token.XOR: allInteger,
1059 token.AND_NOT: allInteger,
1060
1061 token.LAND: allBoolean,
1062 token.LOR: allBoolean,
1063 }
1064 }
1065
1066
1067
1068 func (check *Checker) binary(x *operand, e ast.Expr, lhs, rhs ast.Expr, op token.Token, opPos token.Pos) {
1069 var y operand
1070
1071 check.expr(x, lhs)
1072 check.expr(&y, rhs)
1073
1074 if x.mode == invalid {
1075 return
1076 }
1077 if y.mode == invalid {
1078 x.mode = invalid
1079 x.expr = y.expr
1080 return
1081 }
1082
1083 if isShift(op) {
1084 check.shift(x, &y, e, op)
1085 return
1086 }
1087
1088
1089 canMix := func(x, y *operand) bool {
1090 if isNonTypeParamInterface(x.typ) || isNonTypeParamInterface(y.typ) {
1091 return true
1092 }
1093 if allBoolean(x.typ) != allBoolean(y.typ) {
1094 return false
1095 }
1096 if allString(x.typ) != allString(y.typ) {
1097 return false
1098 }
1099 if x.isNil() && !hasNil(y.typ) {
1100 return false
1101 }
1102 if y.isNil() && !hasNil(x.typ) {
1103 return false
1104 }
1105 return true
1106 }
1107 if canMix(x, &y) {
1108 check.convertUntyped(x, y.typ)
1109 if x.mode == invalid {
1110 return
1111 }
1112 check.convertUntyped(&y, x.typ)
1113 if y.mode == invalid {
1114 x.mode = invalid
1115 return
1116 }
1117 }
1118
1119 if isComparison(op) {
1120 check.comparison(x, &y, op, false)
1121 return
1122 }
1123
1124 if !Identical(x.typ, y.typ) {
1125
1126
1127 if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] {
1128 var posn positioner = x
1129 if e != nil {
1130 posn = e
1131 }
1132 if e != nil {
1133 check.invalidOp(posn, _MismatchedTypes, "%s (mismatched types %s and %s)", e, x.typ, y.typ)
1134 } else {
1135 check.invalidOp(posn, _MismatchedTypes, "%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ, y.typ)
1136 }
1137 }
1138 x.mode = invalid
1139 return
1140 }
1141
1142 if !check.op(binaryOpPredicates, x, op) {
1143 x.mode = invalid
1144 return
1145 }
1146
1147 if op == token.QUO || op == token.REM {
1148
1149 if (x.mode == constant_ || allInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 {
1150 check.invalidOp(&y, _DivByZero, "division by zero")
1151 x.mode = invalid
1152 return
1153 }
1154
1155
1156 if x.mode == constant_ && y.mode == constant_ && isComplex(x.typ) {
1157 re, im := constant.Real(y.val), constant.Imag(y.val)
1158 re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
1159 if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
1160 check.invalidOp(&y, _DivByZero, "division by zero")
1161 x.mode = invalid
1162 return
1163 }
1164 }
1165 }
1166
1167 if x.mode == constant_ && y.mode == constant_ {
1168
1169 if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
1170 x.val = constant.MakeUnknown()
1171
1172 return
1173 }
1174
1175 if op == token.QUO && isInteger(x.typ) {
1176 op = token.QUO_ASSIGN
1177 }
1178 x.val = constant.BinaryOp(x.val, op, y.val)
1179 x.expr = e
1180 check.overflow(x, opPos)
1181 return
1182 }
1183
1184 x.mode = value
1185
1186 }
1187
1188
1189
1190 type exprKind int
1191
1192 const (
1193 conversion exprKind = iota
1194 expression
1195 statement
1196 )
1197
1198
1199
1200
1201
1202
1203 func (check *Checker) rawExpr(x *operand, e ast.Expr, hint Type, allowGeneric bool) exprKind {
1204 if trace {
1205 check.trace(e.Pos(), "-- expr %s", e)
1206 check.indent++
1207 defer func() {
1208 check.indent--
1209 check.trace(e.Pos(), "=> %s", x)
1210 }()
1211 }
1212
1213 kind := check.exprInternal(x, e, hint)
1214
1215 if !allowGeneric {
1216 check.nonGeneric(x)
1217 }
1218
1219 check.record(x)
1220
1221 return kind
1222 }
1223
1224
1225
1226 func (check *Checker) nonGeneric(x *operand) {
1227 if x.mode == invalid || x.mode == novalue {
1228 return
1229 }
1230 var what string
1231 switch t := x.typ.(type) {
1232 case *Named:
1233 if isGeneric(t) {
1234 what = "type"
1235 }
1236 case *Signature:
1237 if t.tparams != nil {
1238 what = "function"
1239 }
1240 }
1241 if what != "" {
1242 check.errorf(x.expr, _WrongTypeArgCount, "cannot use generic %s %s without instantiation", what, x.expr)
1243 x.mode = invalid
1244 x.typ = Typ[Invalid]
1245 }
1246 }
1247
1248
1249
1250 func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
1251
1252
1253 x.mode = invalid
1254 x.typ = Typ[Invalid]
1255
1256 switch e := e.(type) {
1257 case *ast.BadExpr:
1258 goto Error
1259
1260 case *ast.Ident:
1261 check.ident(x, e, nil, false)
1262
1263 case *ast.Ellipsis:
1264
1265
1266 check.error(e, _BadDotDotDotSyntax, "invalid use of '...'")
1267 goto Error
1268
1269 case *ast.BasicLit:
1270 switch e.Kind {
1271 case token.INT, token.FLOAT, token.IMAG:
1272 check.langCompat(e)
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282 const limit = 10000
1283 if len(e.Value) > limit {
1284 check.errorf(e, _InvalidConstVal, "excessively long constant: %s... (%d chars)", e.Value[:10], len(e.Value))
1285 goto Error
1286 }
1287 }
1288 x.setConst(e.Kind, e.Value)
1289 if x.mode == invalid {
1290
1291
1292
1293
1294 check.errorf(e, _InvalidConstVal, "malformed constant: %s", e.Value)
1295 goto Error
1296 }
1297
1298 case *ast.FuncLit:
1299 if sig, ok := check.typ(e.Type).(*Signature); ok {
1300 if !check.conf.IgnoreFuncBodies && e.Body != nil {
1301
1302
1303
1304 decl := check.decl
1305 iota := check.iota
1306
1307
1308
1309
1310 check.later(func() {
1311 check.funcBody(decl, "<function literal>", sig, e.Body, iota)
1312 }).describef(e, "func literal")
1313 }
1314 x.mode = value
1315 x.typ = sig
1316 } else {
1317 check.invalidAST(e, "invalid function literal %s", e)
1318 goto Error
1319 }
1320
1321 case *ast.CompositeLit:
1322 var typ, base Type
1323
1324 switch {
1325 case e.Type != nil:
1326
1327
1328
1329 if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil {
1330 if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil {
1331
1332
1333
1334 typ = &Array{len: -1, elem: check.varType(atyp.Elt)}
1335 base = typ
1336 break
1337 }
1338 }
1339 typ = check.typ(e.Type)
1340 base = typ
1341
1342 case hint != nil:
1343
1344 typ = hint
1345 base, _ = deref(coreType(typ))
1346 if base == nil {
1347 check.errorf(e, _InvalidLit, "invalid composite literal element type %s: no core type", typ)
1348 goto Error
1349 }
1350
1351 default:
1352
1353 check.error(e, _UntypedLit, "missing type in composite literal")
1354 goto Error
1355 }
1356
1357 switch utyp := coreType(base).(type) {
1358 case *Struct:
1359
1360
1361 if utyp.fields == nil {
1362 check.error(e, _InvalidDeclCycle, "illegal cycle in type declaration")
1363 goto Error
1364 }
1365 if len(e.Elts) == 0 {
1366 break
1367 }
1368 fields := utyp.fields
1369 if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok {
1370
1371 visited := make([]bool, len(fields))
1372 for _, e := range e.Elts {
1373 kv, _ := e.(*ast.KeyValueExpr)
1374 if kv == nil {
1375 check.error(e, _MixedStructLit, "mixture of field:value and value elements in struct literal")
1376 continue
1377 }
1378 key, _ := kv.Key.(*ast.Ident)
1379
1380
1381 check.expr(x, kv.Value)
1382 if key == nil {
1383 check.errorf(kv, _InvalidLitField, "invalid field name %s in struct literal", kv.Key)
1384 continue
1385 }
1386 i := fieldIndex(utyp.fields, check.pkg, key.Name)
1387 if i < 0 {
1388 check.errorf(kv, _MissingLitField, "unknown field %s in struct literal", key.Name)
1389 continue
1390 }
1391 fld := fields[i]
1392 check.recordUse(key, fld)
1393 etyp := fld.typ
1394 check.assignment(x, etyp, "struct literal")
1395
1396 if visited[i] {
1397 check.errorf(kv, _DuplicateLitField, "duplicate field name %s in struct literal", key.Name)
1398 continue
1399 }
1400 visited[i] = true
1401 }
1402 } else {
1403
1404 for i, e := range e.Elts {
1405 if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
1406 check.error(kv, _MixedStructLit, "mixture of field:value and value elements in struct literal")
1407 continue
1408 }
1409 check.expr(x, e)
1410 if i >= len(fields) {
1411 check.errorf(x, _InvalidStructLit, "too many values in %s{…}", base)
1412 break
1413 }
1414
1415 fld := fields[i]
1416 if !fld.Exported() && fld.pkg != check.pkg {
1417 check.errorf(x,
1418 _UnexportedLitField,
1419 "implicit assignment to unexported field %s in %s literal", fld.name, typ)
1420 continue
1421 }
1422 etyp := fld.typ
1423 check.assignment(x, etyp, "struct literal")
1424 }
1425 if len(e.Elts) < len(fields) {
1426 check.errorf(inNode(e, e.Rbrace), _InvalidStructLit, "too few values in %s{…}", base)
1427
1428 }
1429 }
1430
1431 case *Array:
1432
1433
1434
1435 if utyp.elem == nil {
1436 check.error(e, _InvalidTypeCycle, "illegal cycle in type declaration")
1437 goto Error
1438 }
1439 n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
1440
1441
1442
1443
1444
1445
1446
1447
1448 if utyp.len < 0 {
1449 utyp.len = n
1450
1451
1452
1453
1454 if e.Type != nil {
1455 check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
1456 }
1457 }
1458
1459 case *Slice:
1460
1461
1462 if utyp.elem == nil {
1463 check.error(e, _InvalidTypeCycle, "illegal cycle in type declaration")
1464 goto Error
1465 }
1466 check.indexedElts(e.Elts, utyp.elem, -1)
1467
1468 case *Map:
1469
1470
1471 if utyp.key == nil || utyp.elem == nil {
1472 check.error(e, _InvalidTypeCycle, "illegal cycle in type declaration")
1473 goto Error
1474 }
1475
1476
1477
1478 keyIsInterface := isNonTypeParamInterface(utyp.key)
1479 visited := make(map[any][]Type, len(e.Elts))
1480 for _, e := range e.Elts {
1481 kv, _ := e.(*ast.KeyValueExpr)
1482 if kv == nil {
1483 check.error(e, _MissingLitKey, "missing key in map literal")
1484 continue
1485 }
1486 check.exprWithHint(x, kv.Key, utyp.key)
1487 check.assignment(x, utyp.key, "map literal")
1488 if x.mode == invalid {
1489 continue
1490 }
1491 if x.mode == constant_ {
1492 duplicate := false
1493 xkey := keyVal(x.val)
1494 if keyIsInterface {
1495 for _, vtyp := range visited[xkey] {
1496 if Identical(vtyp, x.typ) {
1497 duplicate = true
1498 break
1499 }
1500 }
1501 visited[xkey] = append(visited[xkey], x.typ)
1502 } else {
1503 _, duplicate = visited[xkey]
1504 visited[xkey] = nil
1505 }
1506 if duplicate {
1507 check.errorf(x, _DuplicateLitKey, "duplicate key %s in map literal", x.val)
1508 continue
1509 }
1510 }
1511 check.exprWithHint(x, kv.Value, utyp.elem)
1512 check.assignment(x, utyp.elem, "map literal")
1513 }
1514
1515 default:
1516
1517
1518 for _, e := range e.Elts {
1519 if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
1520
1521
1522
1523 e = kv.Value
1524 }
1525 check.use(e)
1526 }
1527
1528 if utyp != Typ[Invalid] {
1529 check.errorf(e, _InvalidLit, "invalid composite literal type %s", typ)
1530 goto Error
1531 }
1532 }
1533
1534 x.mode = value
1535 x.typ = typ
1536
1537 case *ast.ParenExpr:
1538 kind := check.rawExpr(x, e.X, nil, false)
1539 x.expr = e
1540 return kind
1541
1542 case *ast.SelectorExpr:
1543 check.selector(x, e, nil)
1544
1545 case *ast.IndexExpr, *ast.IndexListExpr:
1546 ix := typeparams.UnpackIndexExpr(e)
1547 if check.indexExpr(x, ix) {
1548 check.funcInst(x, ix)
1549 }
1550 if x.mode == invalid {
1551 goto Error
1552 }
1553
1554 case *ast.SliceExpr:
1555 check.sliceExpr(x, e)
1556 if x.mode == invalid {
1557 goto Error
1558 }
1559
1560 case *ast.TypeAssertExpr:
1561 check.expr(x, e.X)
1562 if x.mode == invalid {
1563 goto Error
1564 }
1565
1566 if isTypeParam(x.typ) {
1567 check.invalidOp(x, _InvalidAssert, "cannot use type assertion on type parameter value %s", x)
1568 goto Error
1569 }
1570 if _, ok := under(x.typ).(*Interface); !ok {
1571 check.invalidOp(x, _InvalidAssert, "%s is not an interface", x)
1572 goto Error
1573 }
1574
1575 if e.Type == nil {
1576
1577
1578 check.error(e, _BadTypeKeyword, "use of .(type) outside type switch")
1579 goto Error
1580 }
1581 T := check.varType(e.Type)
1582 if T == Typ[Invalid] {
1583 goto Error
1584 }
1585 check.typeAssertion(e, x, T, false)
1586 x.mode = commaok
1587 x.typ = T
1588
1589 case *ast.CallExpr:
1590 return check.callExpr(x, e)
1591
1592 case *ast.StarExpr:
1593 check.exprOrType(x, e.X, false)
1594 switch x.mode {
1595 case invalid:
1596 goto Error
1597 case typexpr:
1598 check.validVarType(e.X, x.typ)
1599 x.typ = &Pointer{base: x.typ}
1600 default:
1601 var base Type
1602 if !underIs(x.typ, func(u Type) bool {
1603 p, _ := u.(*Pointer)
1604 if p == nil {
1605 check.invalidOp(x, _InvalidIndirection, "cannot indirect %s", x)
1606 return false
1607 }
1608 if base != nil && !Identical(p.base, base) {
1609 check.invalidOp(x, _InvalidIndirection, "pointers of %s must have identical base types", x)
1610 return false
1611 }
1612 base = p.base
1613 return true
1614 }) {
1615 goto Error
1616 }
1617 x.mode = variable
1618 x.typ = base
1619 }
1620
1621 case *ast.UnaryExpr:
1622 check.unary(x, e)
1623 if x.mode == invalid {
1624 goto Error
1625 }
1626 if e.Op == token.ARROW {
1627 x.expr = e
1628 return statement
1629 }
1630
1631 case *ast.BinaryExpr:
1632 check.binary(x, e, e.X, e.Y, e.Op, e.OpPos)
1633 if x.mode == invalid {
1634 goto Error
1635 }
1636
1637 case *ast.KeyValueExpr:
1638
1639 check.invalidAST(e, "no key:value expected")
1640 goto Error
1641
1642 case *ast.ArrayType, *ast.StructType, *ast.FuncType,
1643 *ast.InterfaceType, *ast.MapType, *ast.ChanType:
1644 x.mode = typexpr
1645 x.typ = check.typ(e)
1646
1647
1648
1649
1650
1651
1652 default:
1653 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e))
1654 }
1655
1656
1657 x.expr = e
1658 return expression
1659
1660 Error:
1661 x.mode = invalid
1662 x.expr = e
1663 return statement
1664 }
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674 func keyVal(x constant.Value) interface{} {
1675 switch x.Kind() {
1676 case constant.Complex:
1677 f := constant.ToFloat(x)
1678 if f.Kind() != constant.Float {
1679 r, _ := constant.Float64Val(constant.Real(x))
1680 i, _ := constant.Float64Val(constant.Imag(x))
1681 return complex(r, i)
1682 }
1683 x = f
1684 fallthrough
1685 case constant.Float:
1686 i := constant.ToInt(x)
1687 if i.Kind() != constant.Int {
1688 v, _ := constant.Float64Val(x)
1689 return v
1690 }
1691 x = i
1692 fallthrough
1693 case constant.Int:
1694 if v, ok := constant.Int64Val(x); ok {
1695 return v
1696 }
1697 if v, ok := constant.Uint64Val(x); ok {
1698 return v
1699 }
1700 case constant.String:
1701 return constant.StringVal(x)
1702 case constant.Bool:
1703 return constant.BoolVal(x)
1704 }
1705 return x
1706 }
1707
1708
1709 func (check *Checker) typeAssertion(e ast.Expr, x *operand, T Type, typeSwitch bool) {
1710 method, alt := check.assertableTo(under(x.typ).(*Interface), T)
1711 if method == nil {
1712 return
1713 }
1714
1715 cause := check.missingMethodReason(T, x.typ, method, alt)
1716
1717 if typeSwitch {
1718 check.errorf(e, _ImpossibleAssert, "impossible type switch case: %s\n\t%s cannot have dynamic type %s %s", e, x, T, cause)
1719 return
1720 }
1721
1722 check.errorf(e, _ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ, cause)
1723 }
1724
1725
1726
1727
1728 func (check *Checker) expr(x *operand, e ast.Expr) {
1729 check.rawExpr(x, e, nil, false)
1730 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1731 check.singleValue(x)
1732 }
1733
1734
1735 func (check *Checker) multiExpr(x *operand, e ast.Expr) {
1736 check.rawExpr(x, e, nil, false)
1737 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1738 }
1739
1740
1741
1742
1743 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) {
1744 assert(hint != nil)
1745 check.rawExpr(x, e, hint, false)
1746 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1747 check.singleValue(x)
1748 }
1749
1750
1751
1752
1753
1754 func (check *Checker) exprOrType(x *operand, e ast.Expr, allowGeneric bool) {
1755 check.rawExpr(x, e, nil, allowGeneric)
1756 check.exclude(x, 1<<novalue)
1757 check.singleValue(x)
1758 }
1759
1760
1761
1762 func (check *Checker) exclude(x *operand, modeset uint) {
1763 if modeset&(1<<x.mode) != 0 {
1764 var msg string
1765 var code errorCode
1766 switch x.mode {
1767 case novalue:
1768 if modeset&(1<<typexpr) != 0 {
1769 msg = "%s used as value"
1770 } else {
1771 msg = "%s used as value or type"
1772 }
1773 code = _TooManyValues
1774 case builtin:
1775 msg = "%s must be called"
1776 code = _UncalledBuiltin
1777 case typexpr:
1778 msg = "%s is not an expression"
1779 code = _NotAnExpr
1780 default:
1781 unreachable()
1782 }
1783 check.errorf(x, code, msg, x)
1784 x.mode = invalid
1785 }
1786 }
1787
1788
1789 func (check *Checker) singleValue(x *operand) {
1790 if x.mode == value {
1791
1792 if t, ok := x.typ.(*Tuple); ok {
1793 assert(t.Len() != 1)
1794 if compilerErrorMessages {
1795 check.errorf(x, _TooManyValues, "multiple-value %s in single-value context", x)
1796 } else {
1797 check.errorf(x, _TooManyValues, "%d-valued %s where single value is expected", t.Len(), x)
1798 }
1799 x.mode = invalid
1800 }
1801 }
1802 }
1803
View as plain text