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