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