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