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