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