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