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