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