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