Source file
src/go/types/expr.go
1
2
3
4
5
6
7 package types
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/token"
14 . "internal/types/errors"
15 )
16
17
58
59 type opPredicates map[token.Token]func(Type) bool
60
61 var unaryOpPredicates opPredicates
62
63 func init() {
64
65 unaryOpPredicates = opPredicates{
66 token.ADD: allNumeric,
67 token.SUB: allNumeric,
68 token.XOR: allInteger,
69 token.NOT: allBoolean,
70 }
71 }
72
73 func (check *Checker) op(m opPredicates, x *operand, op token.Token) 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 ast.Expr) token.Pos {
89 switch op := x.(type) {
90 case nil:
91 return nopos
92 case *ast.BinaryExpr:
93 return op.OpPos
94 default:
95 return x.Pos()
96 }
97 }
98
99
100
101 func opName(e ast.Expr) string {
102 switch e := e.(type) {
103 case *ast.BinaryExpr:
104 if int(e.Op) < len(op2str2) {
105 return op2str2[e.Op]
106 }
107 case *ast.UnaryExpr:
108 if int(e.Op) < len(op2str1) {
109 return op2str1[e.Op]
110 }
111 }
112 return ""
113 }
114
115 var op2str1 = [...]string{
116 token.XOR: "bitwise complement",
117 }
118
119
120 var op2str2 = [...]string{
121 token.ADD: "addition",
122 token.SUB: "subtraction",
123 token.XOR: "bitwise XOR",
124 token.MUL: "multiplication",
125 token.SHL: "shift",
126 }
127
128
129 func (check *Checker) unary(x *operand, e *ast.UnaryExpr) {
130 check.expr(nil, x, e.X)
131 if !x.isValid() {
132 return
133 }
134
135 op := e.Op
136 switch op {
137 case token.AND:
138
139
140 if _, ok := ast.Unparen(e.X).(*ast.CompositeLit); !ok && x.mode() != variable {
141 check.errorf(x, UnaddressableOperand, invalidOp+"cannot take address of %s", x)
142 x.invalidate()
143 return
144 }
145 x.mode_ = value
146 x.typ_ = &Pointer{base: x.typ()}
147 return
148
149 case token.ARROW:
150
151 if elem := check.chanElem(x, x, true); elem != nil && check.isComplete(elem) {
152 x.mode_ = commaok
153 x.typ_ = elem
154 check.hasCallOrRecv = true
155 return
156 }
157 x.invalidate()
158 return
159
160 case token.TILDE:
161
162 if !allInteger(x.typ()) {
163 check.error(e, UndefinedOp, "cannot use ~ outside of interface or type constraint")
164 x.invalidate()
165 return
166 }
167 check.error(e, UndefinedOp, "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)")
168 op = token.XOR
169 }
170
171 if !check.op(unaryOpPredicates, x, op) {
172 x.invalidate()
173 return
174 }
175
176 if x.mode() == constant_ {
177 if x.val.Kind() == constant.Unknown {
178
179 return
180 }
181 var prec uint
182 if isUnsigned(x.typ()) {
183 prec = uint(check.conf.sizeof(x.typ()) * 8)
184 }
185 x.val = constant.UnaryOp(op, x.val, prec)
186 x.expr = e
187 check.overflow(x, opPos(x.expr))
188 return
189 }
190
191 x.mode_ = value
192
193 }
194
195
196
197
198 func (check *Checker) chanElem(pos positioner, x *operand, recv bool) Type {
199 u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
200 if u == nil {
201 return typeErrorf("no specific channel type")
202 }
203 ch, _ := u.(*Chan)
204 if ch == nil {
205 return typeErrorf("non-channel %s", t)
206 }
207 if recv && ch.dir == SendOnly {
208 return typeErrorf("send-only channel %s", t)
209 }
210 if !recv && ch.dir == RecvOnly {
211 return typeErrorf("receive-only channel %s", t)
212 }
213 return nil
214 })
215
216 if u != nil {
217 return u.(*Chan).elem
218 }
219
220 cause := err.format(check)
221 if recv {
222 if isTypeParam(x.typ()) {
223 check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s: %s", x, cause)
224 } else {
225
226 check.errorf(pos, InvalidReceive, invalidOp+"cannot receive from %s %s", cause, x)
227 }
228 } else {
229 if isTypeParam(x.typ()) {
230 check.errorf(pos, InvalidSend, invalidOp+"cannot send to %s: %s", x, cause)
231 } else {
232
233 check.errorf(pos, InvalidSend, invalidOp+"cannot send to %s %s", cause, x)
234 }
235 }
236 return nil
237 }
238
239 func isShift(op token.Token) bool {
240 return op == token.SHL || op == token.SHR
241 }
242
243 func isComparison(op token.Token) bool {
244
245 switch op {
246 case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
247 return true
248 }
249 return false
250 }
251
252
253
254
255
256
257
258
259
260
261 func (check *Checker) updateExprType(x ast.Expr, typ Type, final bool) {
262 old, found := check.untyped[x]
263 if !found {
264 return
265 }
266
267
268 switch x := x.(type) {
269 case *ast.BadExpr,
270 *ast.FuncLit,
271 *ast.CompositeLit,
272 *ast.IndexExpr,
273 *ast.SliceExpr,
274 *ast.TypeAssertExpr,
275 *ast.StarExpr,
276 *ast.KeyValueExpr,
277 *ast.ArrayType,
278 *ast.StructType,
279 *ast.FuncType,
280 *ast.InterfaceType,
281 *ast.MapType,
282 *ast.ChanType:
283
284
285
286 if debug {
287 check.dump("%v: found old type(%s): %s (new: %s)", x.Pos(), x, old.typ, typ)
288 panic("unreachable")
289 }
290 return
291
292 case *ast.CallExpr:
293
294
295
296
297 case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr:
298
299
300
301
302 case *ast.ParenExpr:
303 check.updateExprType(x.X, typ, final)
304
305 case *ast.UnaryExpr:
306
307
308
309
310
311 if old.val != nil {
312 break
313 }
314 check.updateExprType(x.X, typ, final)
315
316 case *ast.BinaryExpr:
317 if old.val != nil {
318 break
319 }
320 if isComparison(x.Op) {
321
322
323 } else if isShift(x.Op) {
324
325
326 check.updateExprType(x.X, typ, final)
327 } else {
328
329 check.updateExprType(x.X, typ, final)
330 check.updateExprType(x.Y, typ, final)
331 }
332
333 default:
334 panic("unreachable")
335 }
336
337
338
339 if !final && isUntyped(typ) {
340 old.typ = typ.Underlying().(*Basic)
341 check.untyped[x] = old
342 return
343 }
344
345
346
347 delete(check.untyped, x)
348
349 if old.isLhs {
350
351
352
353 if !allInteger(typ) {
354 check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s (type %s) must be integer", x, typ)
355 return
356 }
357
358
359
360 }
361 if old.val != nil {
362
363 c := operand{old.mode, x, old.typ, old.val, 0}
364 check.convertUntyped(&c, typ)
365 if !c.isValid() {
366 return
367 }
368 }
369
370
371 check.recordTypeAndValue(x, old.mode, typ, old.val)
372 }
373
374
375 func (check *Checker) updateExprVal(x ast.Expr, val constant.Value) {
376 if info, ok := check.untyped[x]; ok {
377 info.val = val
378 check.untyped[x] = info
379 }
380 }
381
382
383
384
385
386
387
388 func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, Code) {
389 if !x.isValid() || isTyped(x.typ()) || !isValid(target) {
390 return x.typ(), nil, 0
391 }
392
393
394 if isUntyped(target) {
395
396 if m := maxType(x.typ(), target); m != nil {
397 return m, nil, 0
398 }
399 return nil, nil, InvalidUntypedConversion
400 }
401
402 switch u := target.Underlying().(type) {
403 case *Basic:
404 if x.mode() == constant_ {
405 v, code := check.representation(x, u)
406 if code != 0 {
407 return nil, nil, code
408 }
409 return target, v, code
410 }
411
412
413
414
415 switch x.typ().(*Basic).kind {
416 case UntypedBool:
417 if !isBoolean(target) {
418 return nil, nil, InvalidUntypedConversion
419 }
420 case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex:
421 if !isNumeric(target) {
422 return nil, nil, InvalidUntypedConversion
423 }
424 case UntypedString:
425
426
427
428 if !isString(target) {
429 return nil, nil, InvalidUntypedConversion
430 }
431 case UntypedNil:
432
433 if !hasNil(target) {
434 return nil, nil, InvalidUntypedConversion
435 }
436
437 return Typ[UntypedNil], nil, 0
438 default:
439 return nil, nil, InvalidUntypedConversion
440 }
441 case *Interface:
442 if isTypeParam(target) {
443 if !underIs(target, func(u Type) bool {
444 if u == nil {
445 return false
446 }
447 t, _, _ := check.implicitTypeAndValue(x, u)
448 return t != nil
449 }) {
450 return nil, nil, InvalidUntypedConversion
451 }
452
453 if x.isNil() {
454 return Typ[UntypedNil], nil, 0
455 }
456 break
457 }
458
459
460
461
462 if x.isNil() {
463 return Typ[UntypedNil], nil, 0
464 }
465
466 if !u.Empty() {
467 return nil, nil, InvalidUntypedConversion
468 }
469 return Default(x.typ()), nil, 0
470 case *Pointer, *Signature, *Slice, *Map, *Chan:
471 if !x.isNil() {
472 return nil, nil, InvalidUntypedConversion
473 }
474
475 return Typ[UntypedNil], nil, 0
476 default:
477 return nil, nil, InvalidUntypedConversion
478 }
479 return target, nil, 0
480 }
481
482
483 func (check *Checker) comparison(x, y *operand, op token.Token, switchCase bool) {
484
485 if !isValid(x.typ()) || !isValid(y.typ()) {
486 x.invalidate()
487 return
488 }
489
490 if switchCase {
491 op = token.EQL
492 }
493
494 errOp := x
495 cause := ""
496
497
498
499 code := MismatchedTypes
500 ok, _ := x.assignableTo(check, y.typ(), nil)
501 if !ok {
502 ok, _ = y.assignableTo(check, x.typ(), nil)
503 }
504 if !ok {
505
506
507
508 errOp = y
509 cause = check.sprintf("mismatched types %s and %s", x.typ(), y.typ())
510 goto Error
511 }
512
513
514 code = UndefinedOp
515 switch op {
516 case token.EQL, token.NEQ:
517
518 switch {
519 case x.isNil() || y.isNil():
520
521 typ := x.typ()
522 if x.isNil() {
523 typ = y.typ()
524 }
525 if !hasNil(typ) {
526
527
528
529
530 errOp = y
531 goto Error
532 }
533
534 case !Comparable(x.typ()):
535 errOp = x
536 cause = check.incomparableCause(x.typ())
537 goto Error
538
539 case !Comparable(y.typ()):
540 errOp = y
541 cause = check.incomparableCause(y.typ())
542 goto Error
543 }
544
545 case token.LSS, token.LEQ, token.GTR, token.GEQ:
546
547 switch {
548 case !allOrdered(x.typ()):
549 errOp = x
550 goto Error
551 case !allOrdered(y.typ()):
552 errOp = y
553 goto Error
554 }
555
556 default:
557 panic("unreachable")
558 }
559
560
561 if x.mode() == constant_ && y.mode() == constant_ {
562 x.val = constant.MakeBool(constant.Compare(x.val, op, y.val))
563
564
565 } else {
566 x.mode_ = value
567
568
569
570
571 check.updateExprType(x.expr, Default(x.typ()), true)
572 check.updateExprType(y.expr, Default(y.typ()), true)
573 }
574
575
576
577 x.typ_ = Typ[UntypedBool]
578 return
579
580 Error:
581
582 if cause == "" {
583 if isTypeParam(x.typ()) || isTypeParam(y.typ()) {
584
585 if !isTypeParam(x.typ()) {
586 errOp = y
587 }
588 cause = check.sprintf("type parameter %s cannot use operator %s", errOp.typ(), op)
589 } else {
590
591 what := compositeKind(errOp.typ())
592 if what == "" {
593 what = check.sprintf("%s", errOp.typ())
594 }
595 cause = check.sprintf("operator %s not defined on %s", op, what)
596 }
597 }
598 if switchCase {
599 check.errorf(x, code, "invalid case %s in switch on %s (%s)", x.expr, y.expr, cause)
600 } else {
601 check.errorf(errOp, code, invalidOp+"%s %s %s (%s)", x.expr, op, y.expr, cause)
602 }
603 x.invalidate()
604 }
605
606
607
608 func (check *Checker) incomparableCause(typ Type) string {
609 switch typ.Underlying().(type) {
610 case *Slice, *Signature, *Map:
611 return compositeKind(typ) + " can only be compared to nil"
612 }
613
614 return comparableType(typ, true, nil).format(check)
615 }
616
617
618 func (check *Checker) shift(x, y *operand, e ast.Expr, op token.Token) {
619
620
621 var xval constant.Value
622 if x.mode() == constant_ {
623 xval = constant.ToInt(x.val)
624 }
625
626 if allInteger(x.typ()) || isUntyped(x.typ()) && xval != nil && xval.Kind() == constant.Int {
627
628
629 } else {
630
631 check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", x)
632 x.invalidate()
633 return
634 }
635
636
637
638
639
640
641 var yval constant.Value
642 if y.mode() == constant_ {
643
644 yval = constant.ToInt(y.val)
645 if yval.Kind() == constant.Int && constant.Sign(yval) < 0 {
646 check.errorf(y, InvalidShiftCount, invalidOp+"negative shift count %s", y)
647 x.invalidate()
648 return
649 }
650
651 if isUntyped(y.typ()) {
652
653
654 check.representable(y, Typ[Uint])
655 if !y.isValid() {
656 x.invalidate()
657 return
658 }
659 }
660 } else {
661
662 switch {
663 case allInteger(y.typ()):
664 if !allUnsigned(y.typ()) && !check.verifyVersionf(y, go1_13, invalidOp+"signed shift count %s", y) {
665 x.invalidate()
666 return
667 }
668 case isUntyped(y.typ()):
669
670
671 check.convertUntyped(y, Typ[Uint])
672 if !y.isValid() {
673 x.invalidate()
674 return
675 }
676 default:
677 check.errorf(y, InvalidShiftCount, invalidOp+"shift count %s must be integer", y)
678 x.invalidate()
679 return
680 }
681 }
682
683 if x.mode() == constant_ {
684 if y.mode() == constant_ {
685
686 if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
687 x.val = constant.MakeUnknown()
688
689 if !isInteger(x.typ()) {
690 x.typ_ = Typ[UntypedInt]
691 }
692 return
693 }
694
695 const shiftBound = 1023 - 1 + 52
696 s, ok := constant.Uint64Val(yval)
697 if !ok || s > shiftBound {
698 check.errorf(y, InvalidShiftCount, invalidOp+"invalid shift count %s", y)
699 x.invalidate()
700 return
701 }
702
703
704
705
706 if !isInteger(x.typ()) {
707 x.typ_ = Typ[UntypedInt]
708 }
709
710 x.val = constant.Shift(xval, op, uint(s))
711 x.expr = e
712 check.overflow(x, opPos(x.expr))
713 return
714 }
715
716
717 if isUntyped(x.typ()) {
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737 if info, found := check.untyped[x.expr]; found {
738 info.isLhs = true
739 check.untyped[x.expr] = info
740 }
741
742 x.mode_ = value
743 return
744 }
745 }
746
747
748 if !allInteger(x.typ()) {
749 check.errorf(x, InvalidShiftOperand, invalidOp+"shifted operand %s must be integer", x)
750 x.invalidate()
751 return
752 }
753
754 x.mode_ = value
755 }
756
757 var binaryOpPredicates opPredicates
758
759 func init() {
760
761 binaryOpPredicates = opPredicates{
762 token.ADD: allNumericOrString,
763 token.SUB: allNumeric,
764 token.MUL: allNumeric,
765 token.QUO: allNumeric,
766 token.REM: allInteger,
767
768 token.AND: allInteger,
769 token.OR: allInteger,
770 token.XOR: allInteger,
771 token.AND_NOT: allInteger,
772
773 token.LAND: allBoolean,
774 token.LOR: allBoolean,
775 }
776 }
777
778
779
780 func (check *Checker) binary(x *operand, e ast.Expr, lhs, rhs ast.Expr, op token.Token, opPos token.Pos) {
781 var y operand
782
783 check.expr(nil, x, lhs)
784 check.expr(nil, &y, rhs)
785
786 if !x.isValid() {
787 return
788 }
789 if !y.isValid() {
790 x.invalidate()
791 x.expr = y.expr
792 return
793 }
794
795 if isShift(op) {
796 check.shift(x, &y, e, op)
797 return
798 }
799
800 check.matchTypes(x, &y)
801 if !x.isValid() {
802 return
803 }
804
805 if isComparison(op) {
806 check.comparison(x, &y, op, false)
807 return
808 }
809
810 if !Identical(x.typ(), y.typ()) {
811
812
813 if isValid(x.typ()) && isValid(y.typ()) {
814 var posn positioner = x
815 if e != nil {
816 posn = e
817 }
818 if e != nil {
819 check.errorf(posn, MismatchedTypes, invalidOp+"%s (mismatched types %s and %s)", e, x.typ(), y.typ())
820 } else {
821 check.errorf(posn, MismatchedTypes, invalidOp+"%s %s= %s (mismatched types %s and %s)", lhs, op, rhs, x.typ(), y.typ())
822 }
823 }
824 x.invalidate()
825 return
826 }
827
828 if !check.op(binaryOpPredicates, x, op) {
829 x.invalidate()
830 return
831 }
832
833 if op == token.QUO || op == token.REM {
834
835 if (x.mode() == constant_ || allInteger(x.typ())) && y.mode() == constant_ && constant.Sign(y.val) == 0 {
836 check.error(&y, DivByZero, invalidOp+"division by zero")
837 x.invalidate()
838 return
839 }
840
841
842 if x.mode() == constant_ && y.mode() == constant_ && isComplex(x.typ()) {
843 re, im := constant.Real(y.val), constant.Imag(y.val)
844 re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
845 if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
846 check.error(&y, DivByZero, invalidOp+"division by zero")
847 x.invalidate()
848 return
849 }
850 }
851 }
852
853 if x.mode() == constant_ && y.mode() == constant_ {
854
855 if x.val.Kind() == constant.Unknown || y.val.Kind() == constant.Unknown {
856 x.val = constant.MakeUnknown()
857
858 return
859 }
860
861 if op == token.QUO && isInteger(x.typ()) {
862 op = token.QUO_ASSIGN
863 }
864 x.val = constant.BinaryOp(x.val, op, y.val)
865 x.expr = e
866 check.overflow(x, opPos)
867 return
868 }
869
870 x.mode_ = value
871
872 }
873
874
875
876 func (check *Checker) matchTypes(x, y *operand) {
877
878
879
880
881
882
883
884
885
886 mayConvert := func(x, y *operand) bool {
887
888 if isTyped(x.typ()) && isTyped(y.typ()) {
889 return false
890 }
891
892 if allNumeric(x.typ()) != allNumeric(y.typ()) {
893 return false
894 }
895
896
897
898
899 if isNonTypeParamInterface(x.typ()) || isNonTypeParamInterface(y.typ()) {
900 return true
901 }
902
903 if allBoolean(x.typ()) != allBoolean(y.typ()) {
904 return false
905 }
906
907 if allString(x.typ()) != allString(y.typ()) {
908 return false
909 }
910
911 if x.isNil() {
912 return hasNil(y.typ())
913 }
914 if y.isNil() {
915 return hasNil(x.typ())
916 }
917
918
919 if isPointer(x.typ()) || isPointer(y.typ()) {
920 return false
921 }
922 return true
923 }
924
925 if mayConvert(x, y) {
926 check.convertUntyped(x, y.typ())
927 if !x.isValid() {
928 return
929 }
930 check.convertUntyped(y, x.typ())
931 if !y.isValid() {
932 x.invalidate()
933 return
934 }
935 }
936 }
937
938
939
940 type exprKind int
941
942 const (
943 conversion exprKind = iota
944 expression
945 statement
946 )
947
948
949
950 type target struct {
951 sig *Signature
952 desc string
953 }
954
955
956
957 func newTarget(typ Type, desc string) *target {
958 if typ != nil {
959 if u, _ := commonUnder(typ, nil); u != nil {
960 if sig, _ := u.(*Signature); sig != nil {
961 return &target{sig, desc}
962 }
963 }
964 }
965 return nil
966 }
967
968
969
970
971
972
973
974
975 func (check *Checker) rawExpr(T *target, x *operand, e ast.Expr, hint Type, allowGeneric bool) exprKind {
976 if check.conf._Trace {
977 check.trace(e.Pos(), "-- expr %s", e)
978 check.indent++
979 defer func() {
980 check.indent--
981 check.trace(e.Pos(), "=> %s", x)
982 }()
983 }
984
985 kind := check.exprInternal(T, x, e, hint)
986
987 if !allowGeneric {
988 check.nonGeneric(T, x)
989 }
990
991 check.record(x)
992
993 return kind
994 }
995
996
997
998
999 func (check *Checker) nonGeneric(T *target, x *operand) {
1000 if !x.isValid() || x.mode() == novalue {
1001 return
1002 }
1003 var what string
1004 switch t := x.typ().(type) {
1005 case *Alias, *Named:
1006 if isGeneric(t) {
1007 what = "type"
1008 }
1009 case *Signature:
1010 if t.tparams != nil {
1011 if enableReverseTypeInference && T != nil {
1012 check.funcInst(T, x.Pos(), x, nil, true)
1013 return
1014 }
1015 what = "function"
1016 }
1017 }
1018 if what != "" {
1019 check.errorf(x.expr, WrongTypeArgCount, "cannot use generic %s %s without instantiation", what, x.expr)
1020 x.invalidate()
1021 x.typ_ = Typ[Invalid]
1022 }
1023 }
1024
1025
1026
1027
1028 func (check *Checker) exprInternal(T *target, x *operand, e ast.Expr, hint Type) exprKind {
1029
1030
1031 x.invalidate()
1032 x.typ_ = Typ[Invalid]
1033
1034 switch e := e.(type) {
1035 case *ast.BadExpr:
1036 goto Error
1037
1038 case *ast.Ident:
1039 check.ident(x, e, false)
1040
1041 case *ast.Ellipsis:
1042
1043 check.error(e, InvalidSyntaxTree, "invalid use of ...")
1044 goto Error
1045
1046 case *ast.BasicLit:
1047 check.basicLit(x, e)
1048 if !x.isValid() {
1049 goto Error
1050 }
1051
1052 case *ast.FuncLit:
1053 check.funcLit(x, e)
1054 if !x.isValid() {
1055 goto Error
1056 }
1057
1058 case *ast.CompositeLit:
1059 check.compositeLit(x, e, hint)
1060 if !x.isValid() {
1061 goto Error
1062 }
1063
1064 case *ast.ParenExpr:
1065
1066 kind := check.rawExpr(nil, x, e.X, nil, false)
1067 x.expr = e
1068 return kind
1069
1070 case *ast.SelectorExpr:
1071 check.selector(x, e, false)
1072
1073 case *ast.IndexExpr, *ast.IndexListExpr:
1074 ix := unpackIndexedExpr(e)
1075 if check.indexExpr(x, ix) {
1076 if !enableReverseTypeInference {
1077 T = nil
1078 }
1079 check.funcInst(T, e.Pos(), x, ix, true)
1080 }
1081 if !x.isValid() {
1082 goto Error
1083 }
1084
1085 case *ast.SliceExpr:
1086 check.sliceExpr(x, e)
1087 if !x.isValid() {
1088 goto Error
1089 }
1090
1091 case *ast.TypeAssertExpr:
1092 check.expr(nil, x, e.X)
1093 if !x.isValid() {
1094 goto Error
1095 }
1096
1097 if e.Type == nil {
1098
1099
1100 check.error(e, BadTypeKeyword, "use of .(type) outside type switch")
1101 goto Error
1102 }
1103 if isTypeParam(x.typ()) {
1104 check.errorf(x, InvalidAssert, invalidOp+"cannot use type assertion on type parameter value %s", x)
1105 goto Error
1106 }
1107 if _, ok := x.typ().Underlying().(*Interface); !ok {
1108 check.errorf(x, InvalidAssert, invalidOp+"%s is not an interface", x)
1109 goto Error
1110 }
1111 T := check.varType(e.Type)
1112 if !isValid(T) {
1113 goto Error
1114 }
1115
1116 if !check.isComplete(T) {
1117 goto Error
1118 }
1119 check.typeAssertion(e, x, T, false)
1120 x.mode_ = commaok
1121 x.typ_ = T
1122
1123 case *ast.CallExpr:
1124 return check.callExpr(x, e)
1125
1126 case *ast.StarExpr:
1127 check.exprOrType(x, e.X, false)
1128 switch x.mode() {
1129 case invalid:
1130 goto Error
1131 case typexpr:
1132 check.validVarType(e.X, x.typ())
1133 x.typ_ = &Pointer{base: x.typ()}
1134 default:
1135 var base Type
1136 if !underIs(x.typ(), func(u Type) bool {
1137 p, _ := u.(*Pointer)
1138 if p == nil {
1139 check.errorf(x, InvalidIndirection, invalidOp+"cannot indirect %s", x)
1140 return false
1141 }
1142 if base != nil && !Identical(p.base, base) {
1143 check.errorf(x, InvalidIndirection, invalidOp+"pointers of %s must have identical base types", x)
1144 return false
1145 }
1146 base = p.base
1147 return true
1148 }) {
1149 goto Error
1150 }
1151
1152 if !check.isComplete(base) {
1153 goto Error
1154 }
1155 x.mode_ = variable
1156 x.typ_ = base
1157 }
1158
1159 case *ast.UnaryExpr:
1160 check.unary(x, e)
1161 if !x.isValid() {
1162 goto Error
1163 }
1164 if e.Op == token.ARROW {
1165 x.expr = e
1166 return statement
1167 }
1168
1169 case *ast.BinaryExpr:
1170 check.binary(x, e, e.X, e.Y, e.Op, e.OpPos)
1171 if !x.isValid() {
1172 goto Error
1173 }
1174
1175 case *ast.KeyValueExpr:
1176
1177 check.error(e, InvalidSyntaxTree, "no key:value expected")
1178 goto Error
1179
1180 case *ast.ArrayType, *ast.StructType, *ast.FuncType,
1181 *ast.InterfaceType, *ast.MapType, *ast.ChanType:
1182 x.mode_ = typexpr
1183 x.typ_ = check.typ(e)
1184
1185
1186
1187
1188
1189
1190 default:
1191 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e))
1192 }
1193
1194
1195 x.expr = e
1196 return expression
1197
1198 Error:
1199 x.invalidate()
1200 x.expr = e
1201 return statement
1202 }
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212 func keyVal(x constant.Value) any {
1213 switch x.Kind() {
1214 case constant.Complex:
1215 f := constant.ToFloat(x)
1216 if f.Kind() != constant.Float {
1217 r, _ := constant.Float64Val(constant.Real(x))
1218 i, _ := constant.Float64Val(constant.Imag(x))
1219 return complex(r, i)
1220 }
1221 x = f
1222 fallthrough
1223 case constant.Float:
1224 i := constant.ToInt(x)
1225 if i.Kind() != constant.Int {
1226 v, _ := constant.Float64Val(x)
1227 return v
1228 }
1229 x = i
1230 fallthrough
1231 case constant.Int:
1232 if v, ok := constant.Int64Val(x); ok {
1233 return v
1234 }
1235 if v, ok := constant.Uint64Val(x); ok {
1236 return v
1237 }
1238 case constant.String:
1239 return constant.StringVal(x)
1240 case constant.Bool:
1241 return constant.BoolVal(x)
1242 }
1243 return x
1244 }
1245
1246
1247 func (check *Checker) typeAssertion(e ast.Expr, x *operand, T Type, typeSwitch bool) {
1248 var cause string
1249 if check.assertableTo(x.typ(), T, &cause) {
1250 return
1251 }
1252
1253 if typeSwitch {
1254 check.errorf(e, ImpossibleAssert, "impossible type switch case: %s\n\t%s cannot have dynamic type %s %s", e, x, T, cause)
1255 return
1256 }
1257
1258 check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ(), cause)
1259 }
1260
1261
1262
1263
1264
1265
1266 func (check *Checker) expr(T *target, x *operand, e ast.Expr) {
1267 check.rawExpr(T, x, e, nil, false)
1268 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1269 check.singleValue(x)
1270 }
1271
1272
1273 func (check *Checker) genericExpr(x *operand, e ast.Expr, hint Type) {
1274 check.rawExpr(nil, x, e, hint, true)
1275 check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
1276 check.singleValue(x)
1277 }
1278
1279
1280
1281
1282
1283
1284 func (check *Checker) multiExpr(e ast.Expr, allowCommaOk bool) (list []*operand, commaOk bool) {
1285 var x operand
1286 check.rawExpr(nil, &x, e, nil, false)
1287 check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
1288
1289 if t, ok := x.typ().(*Tuple); ok && x.isValid() {
1290
1291 list = make([]*operand, t.Len())
1292 for i, v := range t.vars {
1293
1294 dummy := ast.NewIdent(nth(i+1, "function result"))
1295 dummy.NamePos = e.Pos()
1296 list[i] = &operand{mode_: value, expr: dummy, typ_: v.typ}
1297 }
1298 return
1299 }
1300
1301
1302 list = []*operand{&x}
1303 if allowCommaOk && (x.mode() == mapindex || x.mode() == commaok || x.mode() == commaerr) {
1304 var what string = "ok value of (comma, ok) expression"
1305 var typ Type = Typ[UntypedBool]
1306 if x.mode() == commaerr {
1307 what = "err value of (comma, err) expression"
1308 typ = universeError
1309 }
1310
1311 dummy := ast.NewIdent(what)
1312 dummy.NamePos = e.Pos()
1313 x2 := &operand{mode_: value, expr: dummy, typ_: typ}
1314 list = append(list, x2)
1315 commaOk = true
1316 }
1317
1318 return
1319 }
1320
1321
1322
1323 func nth(n int, what string) string {
1324 var ext string
1325 switch n {
1326 case 1:
1327 ext = "st"
1328 case 2:
1329 ext = "nd"
1330 case 3:
1331 ext = "rd"
1332 default:
1333 ext = "th"
1334 }
1335 return fmt.Sprintf("%d%s %s", n, ext, what)
1336 }
1337
1338
1339
1340
1341
1342
1343 func (check *Checker) exprOrType(x *operand, e ast.Expr, allowGeneric bool) {
1344 check.rawExpr(nil, x, e, nil, allowGeneric)
1345 check.exclude(x, 1<<novalue)
1346 check.singleValue(x)
1347 }
1348
1349
1350
1351 func (check *Checker) exclude(x *operand, modeset uint) {
1352 if modeset&(1<<x.mode()) != 0 {
1353 var msg string
1354 var code Code
1355 switch x.mode() {
1356 case novalue:
1357 if modeset&(1<<typexpr) != 0 {
1358 msg = "%s used as value"
1359 } else {
1360 msg = "%s used as value or type"
1361 }
1362 code = TooManyValues
1363 case builtin:
1364 msg = "%s must be called"
1365 code = UncalledBuiltin
1366 case typexpr:
1367 msg = "%s is not an expression"
1368 code = NotAnExpr
1369 default:
1370 panic("unreachable")
1371 }
1372 check.errorf(x, code, msg, x)
1373 x.invalidate()
1374 }
1375 }
1376
1377
1378 func (check *Checker) singleValue(x *operand) {
1379 if x.mode() == value {
1380
1381 if t, ok := x.typ().(*Tuple); ok {
1382 assert(t.Len() != 1)
1383 check.errorf(x, TooManyValues, "multiple-value %s in single-value context", x)
1384 x.invalidate()
1385 }
1386 }
1387 }
1388
View as plain text