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.
8 "cmd/compile/internal/base"
9 "cmd/compile/internal/ir"
10 "cmd/compile/internal/types"
12 "internal/types/errors"
15 func RangeExprType(t *types.Type) *types.Type {
16 if t.IsPtr() && t.Elem().IsArray() {
22 func typecheckrangeExpr(n *ir.RangeStmt) {
25 // type check assignment.
26 // if this assignment is the definition of a var on the left side,
27 // fill in the var's type.
28 func tcAssign(n *ir.AssignStmt) {
29 if base.EnableTrace && base.Flag.LowerT {
30 defer tracePrint("tcAssign", n)(nil)
38 lhs, rhs := []ir.Node{n.X}, []ir.Node{n.Y}
40 n.X, n.Y = lhs[0], rhs[0]
42 // TODO(mdempsky): This seems out of place.
44 types.CheckSize(n.X.Type()) // ensure width is calculated for backend
48 func tcAssignList(n *ir.AssignListStmt) {
49 if base.EnableTrace && base.Flag.LowerT {
50 defer tracePrint("tcAssignList", n)(nil)
53 assign(n, n.Lhs, n.Rhs)
56 func assign(stmt ir.Node, lhs, rhs []ir.Node) {
57 // delicate little dance.
58 // the definition of lhs may refer to this assignment
59 // as its definition, in which case it will call tcAssign.
60 // in that case, do not call typecheck back, or it will cycle.
61 // if the variable has a type (ntype) then typechecking
62 // will not look at defn, so it is okay (and desirable,
63 // so that the conversion below happens).
65 checkLHS := func(i int, typ *types.Type) {
66 if n := lhs[i]; typ != nil && ir.DeclaredBy(n, stmt) && n.Type() == nil {
67 base.Assertf(typ.Kind() == types.TNIL, "unexpected untyped nil")
68 n.SetType(defaultType(typ))
70 if lhs[i].Typecheck() == 0 {
71 lhs[i] = AssignExpr(lhs[i])
76 assignType := func(i int, typ *types.Type) {
79 checkassignto(typ, lhs[i])
85 rhs[0] = typecheck(rhs[0], ctxExpr|ctxMultiOK)
86 if rtyp := rhs[0].Type(); rtyp != nil && rtyp.IsFuncArgStruct() {
95 for len(lhs) == 2 && cr == 1 {
96 stmt := stmt.(*ir.AssignListStmt)
101 stmt.SetOp(ir.OAS2MAPR)
103 stmt.SetOp(ir.OAS2RECV)
105 r := r.(*ir.TypeAssertExpr)
106 stmt.SetOp(ir.OAS2DOTTYPE)
107 r.SetOp(ir.ODOTTYPE2)
108 case ir.ODYNAMICDOTTYPE:
109 r := r.(*ir.DynamicTypeAssertExpr)
110 stmt.SetOp(ir.OAS2DOTTYPE)
111 r.SetOp(ir.ODYNAMICDOTTYPE2)
116 assignType(0, r.Type())
117 assignType(1, types.UntypedBool)
122 if r, ok := rhs[0].(*ir.CallExpr); ok && len(rhs) == 1 {
124 base.ErrorfAt(stmt.Pos(), errors.WrongAssignCount, "assignment mismatch: %d variable%s but %v returns %d value%s", len(lhs), plural(len(lhs)), r.X, cr, plural(cr))
127 base.ErrorfAt(stmt.Pos(), errors.WrongAssignCount, "assignment mismatch: %d variable%s but %v value%s", len(lhs), plural(len(lhs)), len(rhs), plural(len(rhs)))
138 stmt := stmt.(*ir.AssignListStmt)
139 stmt.SetOp(ir.OAS2FUNC)
140 r := rhs[0].(*ir.CallExpr)
146 result := rtyp.Field(i).Type
147 assignType(i, result)
149 if lhs[i].Type() == nil || result == nil {
151 } else if lhs[i] != ir.BlankNode && !types.Identical(lhs[i].Type(), result) {
155 if mismatched && !failed {
156 RewriteMultiValueCall(stmt, r)
161 for i, r := range rhs {
162 checkLHS(i, r.Type())
163 if lhs[i].Type() != nil {
164 rhs[i] = AssignConv(r, lhs[i].Type(), "assignment")
169 func plural(n int) string {
176 // tcCheckNil typechecks an OCHECKNIL node.
177 func tcCheckNil(n *ir.UnaryExpr) ir.Node {
179 if !n.X.Type().IsPtrShaped() {
180 base.FatalfAt(n.Pos(), "%L is not pointer shaped", n.X)
185 // tcFor typechecks an OFOR node.
186 func tcFor(n *ir.ForStmt) ir.Node {
188 n.Cond = Expr(n.Cond)
189 n.Cond = DefaultLit(n.Cond, nil)
192 if t != nil && !t.IsBoolean() {
193 base.Errorf("non-bool %L used as for condition", n.Cond)
196 n.Post = Stmt(n.Post)
201 func tcGoDefer(n *ir.GoDeferStmt) {
203 if n.Op() == ir.OGO {
236 ir.OLITERAL: // conversion or unsafe.Alignof, Offsetof, Sizeof
237 if orig := ir.Orig(n.Call); orig.Op() == ir.OCONV {
240 base.ErrorfAt(n.Pos(), errors.UnusedResults, "%s discards result of %v", what, n.Call)
244 // type is broken or missing, most likely a method call on a broken type
245 // we will warn about the broken type elsewhere. no need to emit a potentially confusing error
246 if n.Call.Type() == nil {
250 // The syntax made sure it was a call, so this must be
252 base.FatalfAt(n.Pos(), "%s requires function call, not conversion", what)
255 // tcIf typechecks an OIF node.
256 func tcIf(n *ir.IfStmt) ir.Node {
258 n.Cond = Expr(n.Cond)
259 n.Cond = DefaultLit(n.Cond, nil)
262 if t != nil && !t.IsBoolean() {
263 base.Errorf("non-bool %L used as if condition", n.Cond)
272 func tcRange(n *ir.RangeStmt) {
275 // delicate little dance. see tcAssignList
277 if !ir.DeclaredBy(n.Key, n) {
278 n.Key = AssignExpr(n.Key)
283 if !ir.DeclaredBy(n.Value, n) {
284 n.Value = AssignExpr(n.Value)
289 // second half of dance
291 if n.Key != nil && n.Key.Typecheck() == 0 {
292 n.Key = AssignExpr(n.Key)
294 if n.Value != nil && n.Value.Typecheck() == 0 {
295 n.Value = AssignExpr(n.Value)
301 // tcReturn typechecks an ORETURN node.
302 func tcReturn(n *ir.ReturnStmt) ir.Node {
304 if ir.CurFunc == nil {
305 base.Errorf("return outside function")
310 if ir.HasNamedResults(ir.CurFunc) && len(n.Results) == 0 {
313 typecheckaste(ir.ORETURN, nil, false, ir.CurFunc.Type().Results(), n.Results, func() string { return "return argument" })
318 func tcSelect(sel *ir.SelectStmt) {
319 var def *ir.CommClause
320 lno := ir.SetPos(sel)
322 for _, ncase := range sel.Cases {
323 if ncase.Comm == nil {
326 base.ErrorfAt(ncase.Pos(), errors.DuplicateDefault, "multiple defaults in select (first at %v)", ir.Line(def))
331 n := Stmt(ncase.Comm)
333 oselrecv2 := func(dst, recv ir.Node, def bool) {
334 selrecv := ir.NewAssignListStmt(n.Pos(), ir.OSELRECV2, []ir.Node{dst, ir.BlankNode}, []ir.Node{recv})
336 selrecv.SetTypecheck(1)
337 selrecv.SetInit(n.Init())
343 if n.Op() == ir.ONAME {
344 // We don't have the right position for ONAME nodes (see #15459 and
345 // others). Using ncase.Pos for now as it will provide the correct
346 // line number (assuming the expression follows the "case" keyword
347 // on the same line). This matches the approach before 1.10.
350 base.ErrorfAt(pos, errors.InvalidSelectCase, "select case must be receive, send or assign recv")
353 // convert x = <-c into x, _ = <-c
354 // remove implicit conversions; the eventual assignment
355 // will reintroduce them.
356 n := n.(*ir.AssignStmt)
357 if r := n.Y; r.Op() == ir.OCONVNOP || r.Op() == ir.OCONVIFACE {
358 r := r.(*ir.ConvExpr)
363 if n.Y.Op() != ir.ORECV {
364 base.ErrorfAt(n.Pos(), errors.InvalidSelectCase, "select assignment must have receive on right hand side")
367 oselrecv2(n.X, n.Y, n.Def)
370 n := n.(*ir.AssignListStmt)
371 if n.Rhs[0].Op() != ir.ORECV {
372 base.ErrorfAt(n.Pos(), errors.InvalidSelectCase, "select assignment must have receive on right hand side")
375 n.SetOp(ir.OSELRECV2)
378 // convert <-c into _, _ = <-c
379 n := n.(*ir.UnaryExpr)
380 oselrecv2(ir.BlankNode, n, false)
393 // tcSend typechecks an OSEND node.
394 func tcSend(n *ir.SendStmt) ir.Node {
395 n.Chan = Expr(n.Chan)
396 n.Value = Expr(n.Value)
397 n.Chan = DefaultLit(n.Chan, nil)
403 base.Errorf("invalid operation: %v (send to non-chan type %v)", n, t)
407 if !t.ChanDir().CanSend() {
408 base.Errorf("invalid operation: %v (send to receive-only type %v)", n, t)
412 n.Value = AssignConv(n.Value, t.Elem(), "send")
413 if n.Value.Type() == nil {
419 // tcSwitch typechecks a switch statement.
420 func tcSwitch(n *ir.SwitchStmt) {
422 if n.Tag != nil && n.Tag.Op() == ir.OTYPESW {
429 func tcSwitchExpr(n *ir.SwitchStmt) {
430 t := types.Types[types.TBOOL]
433 n.Tag = DefaultLit(n.Tag, nil)
442 case t.Kind() == types.TFUNC:
447 case !types.IsComparable(t):
449 base.ErrorfAt(n.Pos(), errors.InvalidExprSwitch, "cannot switch on %L (struct containing %v cannot be compared)", n.Tag, types.IncomparableField(t).Type)
451 base.ErrorfAt(n.Pos(), errors.InvalidExprSwitch, "cannot switch on %L", n.Tag)
458 for _, ncase := range n.Cases {
460 if len(ls) == 0 { // default:
462 base.ErrorfAt(ncase.Pos(), errors.DuplicateDefault, "multiple defaults in switch (first at %v)", ir.Line(defCase))
471 ls[i] = DefaultLit(ls[i], t)
473 if t == nil || n1.Type() == nil {
477 if nilonly != "" && !ir.IsNil(n1) {
478 base.ErrorfAt(ncase.Pos(), errors.MismatchedTypes, "invalid case %v in switch (can only compare %s %v to nil)", n1, nilonly, n.Tag)
479 } else if t.IsInterface() && !n1.Type().IsInterface() && !types.IsComparable(n1.Type()) {
480 base.ErrorfAt(ncase.Pos(), errors.UndefinedOp, "invalid case %L in switch (incomparable type)", n1)
482 op1, _ := Assignop(n1.Type(), t)
483 op2, _ := Assignop(t, n1.Type())
484 if op1 == ir.OXXX && op2 == ir.OXXX {
486 base.ErrorfAt(ncase.Pos(), errors.MismatchedTypes, "invalid case %v in switch on %v (mismatched types %v and %v)", n1, n.Tag, n1.Type(), t)
488 base.ErrorfAt(ncase.Pos(), errors.MismatchedTypes, "invalid case %v in switch (mismatched types %v and bool)", n1, n1.Type())
498 func tcSwitchType(n *ir.SwitchStmt) {
499 guard := n.Tag.(*ir.TypeSwitchGuard)
500 guard.X = Expr(guard.X)
502 if t != nil && !t.IsInterface() {
503 base.ErrorfAt(n.Pos(), errors.InvalidTypeSwitch, "cannot type switch on non-interface value %L", guard.X)
507 // We don't actually declare the type switch's guarded
508 // declaration itself. So if there are no cases, we won't
509 // notice that it went unused.
510 if v := guard.Tag; v != nil && !ir.IsBlank(v) && len(n.Cases) == 0 {
511 base.ErrorfAt(v.Pos(), errors.UnusedVar, "%v declared but not used", v.Sym())
514 var defCase, nilCase ir.Node
516 for _, ncase := range n.Cases {
518 if len(ls) == 0 { // default:
520 base.ErrorfAt(ncase.Pos(), errors.DuplicateDefault, "multiple defaults in switch (first at %v)", ir.Line(defCase))
527 ls[i] = typecheck(ls[i], ctxExpr|ctxType)
529 if t == nil || n1.Type() == nil {
533 if ir.IsNil(n1) { // case nil:
535 base.ErrorfAt(ncase.Pos(), errors.DuplicateCase, "multiple nil cases in type switch (first at %v)", ir.Line(nilCase))
541 if n1.Op() == ir.ODYNAMICTYPE {
544 if n1.Op() != ir.OTYPE {
545 base.ErrorfAt(ncase.Pos(), errors.NotAType, "%L is not a type", n1)
548 if !n1.Type().IsInterface() {
549 why := ImplementsExplain(n1.Type(), t)
551 base.ErrorfAt(ncase.Pos(), errors.ImpossibleAssert, "impossible type switch case: %L cannot have dynamic type %v (%s)", guard.X, n1.Type(), why)
556 ts.add(ncase.Pos(), n1.Type())
559 if ncase.Var != nil {
560 // Assign the clause variable's type.
563 if ls[0].Op() == ir.OTYPE || ls[0].Op() == ir.ODYNAMICTYPE {
565 } else if !ir.IsNil(ls[0]) {
566 // Invalid single-type case;
567 // mark variable as broken.
575 nvar = AssignExpr(nvar).(*ir.Name)
577 // Clause variable is broken; prevent typechecking.
587 type typeSet struct {
588 m map[string]src.XPos
591 func (s *typeSet) add(pos src.XPos, typ *types.Type) {
593 s.m = make(map[string]src.XPos)
596 ls := typ.LinkString()
597 if prev, ok := s.m[ls]; ok {
598 base.ErrorfAt(pos, errors.DuplicateCase, "duplicate case %v in type switch\n\tprevious case at %s", typ, base.FmtPos(prev))