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