1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 "cmd/compile/internal/base"
14 "cmd/compile/internal/ir"
15 "cmd/compile/internal/types"
19 func tcShift(n, l, r ir.Node) (ir.Node, ir.Node, *types.Type) {
20 if l.Type() == nil || r.Type() == nil {
24 r = DefaultLit(r, types.Types[types.TUINT])
27 base.Errorf("invalid operation: %v (shift count type %v, must be integer)", n, r.Type())
31 if t != nil && t.Kind() != types.TIDEAL && !t.IsInteger() {
32 base.Errorf("invalid operation: %v (shift of type %v)", n, t)
36 // no DefaultLit for left
37 // the outer context gives the type
39 if (l.Type() == types.UntypedFloat || l.Type() == types.UntypedComplex) && r.Op() == ir.OLITERAL {
45 // tcArith typechecks operands of a binary arithmetic expression.
46 // The result of tcArith MUST be assigned back to original operands,
47 // t is the type of the expression, and should be set by the caller. e.g:
49 // n.X, n.Y, t = tcArith(n, op, n.X, n.Y)
51 func tcArith(n ir.Node, op ir.Op, l, r ir.Node) (ir.Node, ir.Node, *types.Type) {
52 l, r = defaultlit2(l, r, false)
53 if l.Type() == nil || r.Type() == nil {
57 if t.Kind() == types.TIDEAL {
61 if n.Op().IsCmp() && t.Kind() != types.TIDEAL && !types.Identical(l.Type(), r.Type()) {
62 // comparison is okay as long as one side is
63 // assignable to the other. convert so they have
66 // the only conversion that isn't a no-op is concrete == interface.
67 // in that case, check comparability of the concrete type.
68 // The conversion allocates, so only do it if the concrete type is huge.
70 if r.Type().Kind() != types.TBLANK {
71 aop, _ = Assignop(l.Type(), r.Type())
73 if r.Type().IsInterface() && !l.Type().IsInterface() && !types.IsComparable(l.Type()) {
74 base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, op, typekind(l.Type()))
78 types.CalcSize(l.Type())
79 if r.Type().IsInterface() == l.Type().IsInterface() || l.Type().Size() >= 1<<16 {
80 l = ir.NewConvExpr(base.Pos, aop, r.Type(), l)
89 if !converted && l.Type().Kind() != types.TBLANK {
90 aop, _ = Assignop(r.Type(), l.Type())
92 if l.Type().IsInterface() && !r.Type().IsInterface() && !types.IsComparable(r.Type()) {
93 base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, op, typekind(r.Type()))
97 types.CalcSize(r.Type())
98 if r.Type().IsInterface() == l.Type().IsInterface() || r.Type().Size() >= 1<<16 {
99 r = ir.NewConvExpr(base.Pos, aop, l.Type(), r)
108 if t.Kind() != types.TIDEAL && !types.Identical(l.Type(), r.Type()) {
109 l, r = defaultlit2(l, r, true)
110 if l.Type() == nil || r.Type() == nil {
113 if l.Type().IsInterface() == r.Type().IsInterface() || aop == 0 {
114 base.Errorf("invalid operation: %v (mismatched types %v and %v)", n, l.Type(), r.Type())
119 if t.Kind() == types.TIDEAL {
120 t = mixUntyped(l.Type(), r.Type())
122 if dt := defaultType(t); !okfor[op][dt.Kind()] {
123 base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, op, typekind(t))
127 // okfor allows any array == array, map == map, func == func.
128 // restrict to slice/map/func == nil and nil == slice/map/func.
129 if l.Type().IsArray() && !types.IsComparable(l.Type()) {
130 base.Errorf("invalid operation: %v (%v cannot be compared)", n, l.Type())
134 if l.Type().IsSlice() && !ir.IsNil(l) && !ir.IsNil(r) {
135 base.Errorf("invalid operation: %v (slice can only be compared to nil)", n)
139 if l.Type().IsMap() && !ir.IsNil(l) && !ir.IsNil(r) {
140 base.Errorf("invalid operation: %v (map can only be compared to nil)", n)
144 if l.Type().Kind() == types.TFUNC && !ir.IsNil(l) && !ir.IsNil(r) {
145 base.Errorf("invalid operation: %v (func can only be compared to nil)", n)
149 if l.Type().IsStruct() {
150 if f := types.IncomparableField(l.Type()); f != nil {
151 base.Errorf("invalid operation: %v (struct containing %v cannot be compared)", n, f.Type)
159 // The result of tcCompLit MUST be assigned back to n, e.g.
161 // n.Left = tcCompLit(n.Left)
162 func tcCompLit(n *ir.CompLitExpr) (res ir.Node) {
163 if base.EnableTrace && base.Flag.LowerT {
164 defer tracePrint("tcCompLit", n)(&res)
175 base.AssertfAt(t != nil, n.Pos(), "missing type in composite literal")
179 base.Errorf("invalid composite literal type %v", t)
183 typecheckarraylit(t.Elem(), t.NumElem(), n.List, "array literal")
184 n.SetOp(ir.OARRAYLIT)
187 length := typecheckarraylit(t.Elem(), -1, n.List, "slice literal")
188 n.SetOp(ir.OSLICELIT)
192 for i3, l := range n.List {
194 if l.Op() != ir.OKEY {
196 base.Errorf("missing key in map literal")
203 l.Key = AssignConv(r, t.Key(), "map key")
207 l.Value = AssignConv(r, t.Elem(), "map value")
213 // Need valid field offsets for Xoffset below.
217 if len(n.List) != 0 && nokeys(n.List) {
218 // simple list of variables
220 for i, n1 := range ls {
224 if i >= t.NumFields() {
226 base.Errorf("too many values in %v", n)
235 // Do the test for assigning to unexported fields.
236 // But if this is an instantiated function, then
237 // the function has already been typechecked. In
238 // that case, don't do the test, since it can fail
239 // for the closure structs created in
240 // walkClosure(), because the instantiated
241 // function is compiled as if in the source
242 // package of the generic function.
243 if !(ir.CurFunc != nil && strings.Index(ir.CurFunc.Nname.Sym().Name, "[") >= 0) {
244 if s != nil && !types.IsExported(s.Name) && s.Pkg != types.LocalPkg {
245 base.Errorf("implicit assignment of unexported field '%s' in %v literal", s.Name, t)
248 // No pushtype allowed here. Must name fields for that.
249 n1 = AssignConv(n1, f.Type, "field value")
250 ls[i] = ir.NewStructKeyExpr(base.Pos, f, n1)
252 if len(ls) < t.NumFields() {
253 base.Errorf("too few values in %v", n)
256 hash := make(map[string]bool)
260 for i, n := range ls {
263 sk, ok := n.(*ir.StructKeyExpr)
265 kv, ok := n.(*ir.KeyExpr)
268 base.Errorf("mixture of field:value and value initializers")
275 sk = tcStructLitKey(t, kv)
280 fielddup(sk.Sym().Name, hash)
283 // No pushtype allowed here. Tried and rejected.
284 sk.Value = Expr(sk.Value)
285 sk.Value = AssignConv(sk.Value, sk.Field.Type, "field value")
290 n.SetOp(ir.OSTRUCTLIT)
296 // tcStructLitKey typechecks an OKEY node that appeared within a
298 func tcStructLitKey(typ *types.Type, kv *ir.KeyExpr) *ir.StructKeyExpr {
303 // An OXDOT uses the Sym field to hold
304 // the field to the right of the dot,
305 // so s will be non-nil, but an OXDOT
306 // is never a valid struct literal key.
307 if sym == nil || sym.Pkg != types.LocalPkg || key.Op() == ir.OXDOT || sym.IsBlank() {
308 base.Errorf("invalid field name %v in struct initializer", key)
312 if f := Lookdot1(nil, sym, typ, typ.Fields(), 0); f != nil {
313 return ir.NewStructKeyExpr(kv.Pos(), f, kv.Value)
316 if ci := Lookdot1(nil, sym, typ, typ.Fields(), 2); ci != nil { // Case-insensitive lookup.
318 base.Errorf("unknown field '%v' in struct literal of type %v (but does have %v)", sym, typ, ci.Sym)
319 } else if nonexported(sym) && sym.Name == ci.Sym.Name { // Ensure exactness before the suggestion.
320 base.Errorf("cannot refer to unexported field '%v' in struct literal of type %v", sym, typ)
322 base.Errorf("unknown field '%v' in struct literal of type %v", sym, typ)
328 p, _ := dotpath(sym, typ, &f, true)
329 if p == nil || f.IsMethod() {
330 base.Errorf("unknown field '%v' in struct literal of type %v", sym, typ)
334 // dotpath returns the parent embedded types in reverse order.
336 for ei := len(p) - 1; ei >= 0; ei-- {
337 ep = append(ep, p[ei].field.Sym.Name)
339 ep = append(ep, sym.Name)
340 base.Errorf("cannot use promoted field %v in struct literal of type %v", strings.Join(ep, "."), typ)
344 // tcConv typechecks an OCONV node.
345 func tcConv(n *ir.ConvExpr) ir.Node {
346 types.CheckSize(n.Type()) // ensure width is calculated for backend
348 n.X = convlit1(n.X, n.Type(), true, nil)
350 if t == nil || n.Type() == nil {
354 op, why := Convertop(n.X.Op() == ir.OLITERAL, t, n.Type())
356 base.Fatalf("cannot convert %L to type %v%s", n.X, n.Type(), why)
362 if t.Kind() == n.Type().Kind() {
364 case types.TFLOAT32, types.TFLOAT64, types.TCOMPLEX64, types.TCOMPLEX128:
365 // Floating point casts imply rounding and
366 // so the conversion must be kept.
371 // do not convert to []byte literal. See CL 125796.
372 // generated code and compiler memory footprint is better without it.
377 if n.X.Op() == ir.OLITERAL {
378 return stringtoruneslit(n)
382 if t.Elem() != types.ByteType && t.Elem() != types.Types[types.TUINT8] {
383 // If t is a slice of a user-defined byte type B (not uint8
384 // or byte), then add an extra CONVNOP from []B to []byte, so
385 // that the call to slicebytetostring() added in walk will
386 // typecheck correctly.
387 n.X = ir.NewConvExpr(n.X.Pos(), ir.OCONVNOP, types.NewSlice(types.ByteType), n.X)
392 if t.Elem() != types.RuneType && t.Elem() != types.Types[types.TINT32] {
393 // If t is a slice of a user-defined rune type B (not uint32
394 // or rune), then add an extra CONVNOP from []B to []rune, so
395 // that the call to slicerunetostring() added in walk will
396 // typecheck correctly.
397 n.X = ir.NewConvExpr(n.X.Pos(), ir.OCONVNOP, types.NewSlice(types.RuneType), n.X)
405 // DotField returns a field selector expression that selects the
406 // index'th field of the given expression, which must be of struct or
407 // pointer-to-struct type.
408 func DotField(pos src.XPos, x ir.Node, index int) *ir.SelectorExpr {
409 op, typ := ir.ODOT, x.Type()
411 op, typ = ir.ODOTPTR, typ.Elem()
414 base.FatalfAt(pos, "DotField of non-struct: %L", x)
417 // TODO(mdempsky): This is the backend's responsibility.
420 field := typ.Field(index)
421 return dot(pos, field.Type, op, x, field)
424 func dot(pos src.XPos, typ *types.Type, op ir.Op, x ir.Node, selection *types.Field) *ir.SelectorExpr {
425 n := ir.NewSelectorExpr(pos, op, x, selection.Sym)
426 n.Selection = selection
432 // XDotMethod returns an expression representing the field selection
433 // x.sym. If any implicit field selection are necessary, those are
435 func XDotField(pos src.XPos, x ir.Node, sym *types.Sym) *ir.SelectorExpr {
436 n := Expr(ir.NewSelectorExpr(pos, ir.OXDOT, x, sym)).(*ir.SelectorExpr)
437 if n.Op() != ir.ODOT && n.Op() != ir.ODOTPTR {
438 base.FatalfAt(pos, "unexpected result op: %v (%v)", n.Op(), n)
443 // XDotMethod returns an expression representing the method value
444 // x.sym (i.e., x is a value, not a type). If any implicit field
445 // selection are necessary, those are inserted too.
447 // If callee is true, the result is an ODOTMETH/ODOTINTER, otherwise
449 func XDotMethod(pos src.XPos, x ir.Node, sym *types.Sym, callee bool) *ir.SelectorExpr {
450 n := ir.NewSelectorExpr(pos, ir.OXDOT, x, sym)
452 n = Callee(n).(*ir.SelectorExpr)
453 if n.Op() != ir.ODOTMETH && n.Op() != ir.ODOTINTER {
454 base.FatalfAt(pos, "unexpected result op: %v (%v)", n.Op(), n)
457 n = Expr(n).(*ir.SelectorExpr)
458 if n.Op() != ir.OMETHVALUE {
459 base.FatalfAt(pos, "unexpected result op: %v (%v)", n.Op(), n)
465 // tcDot typechecks an OXDOT or ODOT node.
466 func tcDot(n *ir.SelectorExpr, top int) ir.Node {
467 if n.Op() == ir.OXDOT {
468 n = AddImplicitDots(n)
477 n.X = DefaultLit(n.X, nil)
481 base.UpdateErrorDot(ir.Line(n), fmt.Sprint(n.X), fmt.Sprint(n))
486 if n.X.Op() == ir.OTYPE {
487 base.FatalfAt(n.Pos(), "use NewMethodExpr to construct OMETHEXPR")
490 if t.IsPtr() && !t.Elem().IsInterface() {
501 base.Errorf("cannot refer to blank field or method")
506 if Lookdot(n, t, 0) == nil {
507 // Legitimate field or method lookup failed, try to explain the error
509 case t.IsEmptyInterface():
510 base.Errorf("%v undefined (type %v is interface with no methods)", n, n.X.Type())
512 case t.IsPtr() && t.Elem().IsInterface():
513 // Pointer to interface is almost always a mistake.
514 base.Errorf("%v undefined (type %v is pointer to interface, not interface)", n, n.X.Type())
516 case Lookdot(n, t, 1) != nil:
517 // Field or method matches by name, but it is not exported.
518 base.Errorf("%v undefined (cannot refer to unexported field or method %v)", n, n.Sel)
521 if mt := Lookdot(n, t, 2); mt != nil && visible(mt.Sym) { // Case-insensitive lookup.
522 base.Errorf("%v undefined (type %v has no field or method %v, but does have %v)", n, n.X.Type(), n.Sel, mt.Sym)
524 base.Errorf("%v undefined (type %v has no field or method %v)", n, n.X.Type(), n.Sel)
531 if (n.Op() == ir.ODOTINTER || n.Op() == ir.ODOTMETH) && top&ctxCallee == 0 {
532 n.SetOp(ir.OMETHVALUE)
533 n.SetType(NewMethodType(n.Type(), nil))
538 // tcDotType typechecks an ODOTTYPE node.
539 func tcDotType(n *ir.TypeAssertExpr) ir.Node {
541 n.X = DefaultLit(n.X, nil)
548 if !t.IsInterface() {
549 base.Errorf("invalid type assertion: %v (non-interface type %v on left)", n, t)
554 base.AssertfAt(n.Type() != nil, n.Pos(), "missing type: %v", n)
556 if n.Type() != nil && !n.Type().IsInterface() {
557 why := ImplementsExplain(n.Type(), t)
559 base.Fatalf("impossible type assertion:\n\t%s", why)
567 // tcITab typechecks an OITAB node.
568 func tcITab(n *ir.UnaryExpr) ir.Node {
575 if !t.IsInterface() {
576 base.Fatalf("OITAB of %v", t)
578 n.SetType(types.NewPtr(types.Types[types.TUINTPTR]))
582 // tcIndex typechecks an OINDEX node.
583 func tcIndex(n *ir.IndexExpr) ir.Node {
585 n.X = DefaultLit(n.X, nil)
586 n.X = implicitstar(n.X)
588 n.Index = Expr(n.Index)
591 if t == nil || r.Type() == nil {
597 base.Errorf("invalid operation: %v (type %v does not support indexing)", n, t)
601 case types.TSTRING, types.TARRAY, types.TSLICE:
602 n.Index = indexlit(n.Index)
604 n.SetType(types.ByteType)
611 } else if t.IsSlice() {
615 if n.Index.Type() != nil && !n.Index.Type().IsInteger() {
616 base.Errorf("non-integer %s index %v", why, n.Index)
620 if !n.Bounded() && ir.IsConst(n.Index, constant.Int) {
622 if constant.Sign(x) < 0 {
623 base.Errorf("invalid %s index %v (index must be non-negative)", why, n.Index)
624 } else if t.IsArray() && constant.Compare(x, token.GEQ, constant.MakeInt64(t.NumElem())) {
625 base.Errorf("invalid array index %v (out of bounds for %d-element array)", n.Index, t.NumElem())
626 } else if ir.IsConst(n.X, constant.String) && constant.Compare(x, token.GEQ, constant.MakeInt64(int64(len(ir.StringVal(n.X))))) {
627 base.Errorf("invalid string index %v (out of bounds for %d-byte string)", n.Index, len(ir.StringVal(n.X)))
628 } else if ir.ConstOverflow(x, types.Types[types.TINT]) {
629 base.Errorf("invalid %s index %v (index too large)", why, n.Index)
634 n.Index = AssignConv(n.Index, t.Key(), "map index")
636 n.SetOp(ir.OINDEXMAP)
642 // tcLenCap typechecks an OLEN or OCAP node.
643 func tcLenCap(n *ir.UnaryExpr) ir.Node {
645 n.X = DefaultLit(n.X, nil)
646 n.X = implicitstar(n.X)
655 if n.Op() == ir.OLEN {
656 ok = okforlen[t.Kind()]
658 ok = okforcap[t.Kind()]
661 base.Errorf("invalid argument %L for %v", l, n.Op())
666 n.SetType(types.Types[types.TINT])
670 // tcUnsafeData typechecks an OUNSAFESLICEDATA or OUNSAFESTRINGDATA node.
671 func tcUnsafeData(n *ir.UnaryExpr) ir.Node {
673 n.X = DefaultLit(n.X, nil)
682 if n.Op() == ir.OUNSAFESLICEDATA {
689 if t.Kind() != kind {
690 base.Errorf("invalid argument %L for %v", l, n.Op())
695 if kind == types.TSTRING {
700 n.SetType(types.NewPtr(t))
704 // tcRecv typechecks an ORECV node.
705 func tcRecv(n *ir.UnaryExpr) ir.Node {
707 n.X = DefaultLit(n.X, nil)
715 base.Errorf("invalid operation: %v (receive from non-chan type %v)", n, t)
720 if !t.ChanDir().CanRecv() {
721 base.Errorf("invalid operation: %v (receive from send-only type %v)", n, t)
730 // tcSPtr typechecks an OSPTR node.
731 func tcSPtr(n *ir.UnaryExpr) ir.Node {
738 if !t.IsSlice() && !t.IsString() {
739 base.Fatalf("OSPTR of %v", t)
742 n.SetType(types.NewPtr(types.Types[types.TUINT8]))
744 n.SetType(types.NewPtr(t.Elem()))
749 // tcSlice typechecks an OSLICE or OSLICE3 node.
750 func tcSlice(n *ir.SliceExpr) ir.Node {
751 n.X = DefaultLit(Expr(n.X), nil)
752 n.Low = indexlit(Expr(n.Low))
753 n.High = indexlit(Expr(n.High))
754 n.Max = indexlit(Expr(n.Max))
755 hasmax := n.Op().IsSlice3()
761 if l.Type().IsArray() {
762 if !ir.IsAddressable(n.X) {
763 base.Errorf("invalid operation %v (slice of unaddressable value)", n)
769 addr.SetImplicit(true)
777 base.Errorf("invalid operation %v (3-index slice of string)", n)
782 n.SetOp(ir.OSLICESTR)
783 } else if t.IsPtr() && t.Elem().IsArray() {
785 n.SetType(types.NewSlice(tp.Elem()))
786 types.CalcSize(n.Type())
788 n.SetOp(ir.OSLICE3ARR)
790 n.SetOp(ir.OSLICEARR)
792 } else if t.IsSlice() {
795 base.Errorf("cannot slice %v (type %v)", l, t)
800 if n.Low != nil && !checksliceindex(l, n.Low, tp) {
804 if n.High != nil && !checksliceindex(l, n.High, tp) {
808 if n.Max != nil && !checksliceindex(l, n.Max, tp) {
812 if !checksliceconst(n.Low, n.High) || !checksliceconst(n.Low, n.Max) || !checksliceconst(n.High, n.Max) {
819 // tcSliceHeader typechecks an OSLICEHEADER node.
820 func tcSliceHeader(n *ir.SliceHeaderExpr) ir.Node {
821 // Errors here are Fatalf instead of Errorf because only the compiler
822 // can construct an OSLICEHEADER node.
823 // Components used in OSLICEHEADER that are supplied by parsed source code
824 // have already been typechecked in e.g. OMAKESLICE earlier.
827 base.Fatalf("no type specified for OSLICEHEADER")
831 base.Fatalf("invalid type %v for OSLICEHEADER", n.Type())
834 if n.Ptr == nil || n.Ptr.Type() == nil || !n.Ptr.Type().IsUnsafePtr() {
835 base.Fatalf("need unsafe.Pointer for OSLICEHEADER")
839 n.Len = DefaultLit(Expr(n.Len), types.Types[types.TINT])
840 n.Cap = DefaultLit(Expr(n.Cap), types.Types[types.TINT])
842 if ir.IsConst(n.Len, constant.Int) && ir.Int64Val(n.Len) < 0 {
843 base.Fatalf("len for OSLICEHEADER must be non-negative")
846 if ir.IsConst(n.Cap, constant.Int) && ir.Int64Val(n.Cap) < 0 {
847 base.Fatalf("cap for OSLICEHEADER must be non-negative")
850 if ir.IsConst(n.Len, constant.Int) && ir.IsConst(n.Cap, constant.Int) && constant.Compare(n.Len.Val(), token.GTR, n.Cap.Val()) {
851 base.Fatalf("len larger than cap for OSLICEHEADER")
857 // tcStringHeader typechecks an OSTRINGHEADER node.
858 func tcStringHeader(n *ir.StringHeaderExpr) ir.Node {
861 base.Fatalf("no type specified for OSTRINGHEADER")
865 base.Fatalf("invalid type %v for OSTRINGHEADER", n.Type())
868 if n.Ptr == nil || n.Ptr.Type() == nil || !n.Ptr.Type().IsUnsafePtr() {
869 base.Fatalf("need unsafe.Pointer for OSTRINGHEADER")
873 n.Len = DefaultLit(Expr(n.Len), types.Types[types.TINT])
875 if ir.IsConst(n.Len, constant.Int) && ir.Int64Val(n.Len) < 0 {
876 base.Fatalf("len for OSTRINGHEADER must be non-negative")
882 // tcStar typechecks an ODEREF node, which may be an expression or a type.
883 func tcStar(n *ir.StarExpr, top int) ir.Node {
884 n.X = typecheck(n.X, ctxExpr|ctxType)
892 // TODO(mdempsky): Remove (along with ctxType above) once I'm
893 // confident this code path isn't needed any more.
894 if l.Op() == ir.OTYPE {
895 base.Fatalf("unexpected type in deref expression: %v", l)
899 if top&(ctxExpr|ctxStmt) != 0 {
900 base.Errorf("invalid indirect of %L", n.X)
904 base.Errorf("%v is not a type", l)
912 // tcUnaryArith typechecks a unary arithmetic expression.
913 func tcUnaryArith(n *ir.UnaryExpr) ir.Node {
921 if !okfor[n.Op()][defaultType(t).Kind()] {
922 base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, n.Op(), typekind(t))