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"
18 // Function collecting autotmps generated during typechecking,
19 // to be included in the package-level init function.
20 var InitTodoFunc = ir.NewFunc(base.Pos)
22 var inimport bool // set during import
24 var TypecheckAllowed bool
27 NeedRuntimeType = func(*types.Type) {}
30 func AssignExpr(n ir.Node) ir.Node { return typecheck(n, ctxExpr|ctxAssign) }
31 func Expr(n ir.Node) ir.Node { return typecheck(n, ctxExpr) }
32 func Stmt(n ir.Node) ir.Node { return typecheck(n, ctxStmt) }
34 func Exprs(exprs []ir.Node) { typecheckslice(exprs, ctxExpr) }
35 func Stmts(stmts []ir.Node) { typecheckslice(stmts, ctxStmt) }
37 func Call(call *ir.CallExpr) {
40 panic("misuse of Call")
43 if t.NumResults() > 0 {
44 ctx = ctxExpr | ctxMultiOK
46 if typecheck(call, ctx) != call {
47 panic("bad typecheck")
51 func Callee(n ir.Node) ir.Node {
52 return typecheck(n, ctxExpr|ctxCallee)
55 func FuncBody(n *ir.Func) {
57 errorsBefore := base.Errors()
61 if base.Errors() > errorsBefore {
62 n.Body = nil // type errors; do not compile
66 var importlist []*ir.Func
68 // AllImportedBodies reads in the bodies of all imported functions and typechecks
70 func AllImportedBodies() {
71 for _, n := range importlist {
78 var traceIndent []byte
80 func tracePrint(title string, n ir.Node) func(np *ir.Node) {
87 pos = base.FmtPos(n.Pos())
92 types.SkipSizeForTracing = true
93 defer func() { types.SkipSizeForTracing = false }()
94 fmt.Printf("%s: %s%s %p %s %v tc=%d\n", pos, indent, title, n, op, n, tc)
95 traceIndent = append(traceIndent, ". "...)
97 return func(np *ir.Node) {
98 traceIndent = traceIndent[:len(traceIndent)-2]
100 // if we have a result, use that
106 // use outer pos, op so we don't get empty pos/op if n == nil (nicer output)
110 pos = base.FmtPos(n.Pos())
116 types.SkipSizeForTracing = true
117 defer func() { types.SkipSizeForTracing = false }()
118 fmt.Printf("%s: %s=> %p %s %v tc=%d type=%L\n", pos, indent, n, op, n, tc, typ)
123 ctxStmt = 1 << iota // evaluated at statement level
124 ctxExpr // evaluated in value context
125 ctxType // evaluated in type context
126 ctxCallee // call-only expressions are ok
127 ctxMultiOK // multivalue function returns are ok
128 ctxAssign // assigning to expression
131 // type checks the whole tree of an expression.
132 // calculates expression types.
133 // evaluates compile time constants.
134 // marks variables that escape the local frame.
135 // rewrites n.Op to be more specific in some cases.
137 var typecheckdefstack []*ir.Name
139 // Resolve ONONAME to definition, if any.
140 func Resolve(n ir.Node) (res ir.Node) {
141 if n == nil || n.Op() != ir.ONONAME {
145 // only trace if there's work to do
146 if base.EnableTrace && base.Flag.LowerT {
147 defer tracePrint("resolve", n)(&res)
150 if sym := n.Sym(); sym.Pkg != types.LocalPkg {
151 // We might have an ir.Ident from oldname or importDot.
152 if id, ok := n.(*ir.Ident); ok {
153 if pkgName := DotImportRefs[id]; pkgName != nil {
161 r := ir.AsNode(n.Sym().Def)
166 if r.Op() == ir.OIOTA {
167 if x := getIotaValue(); x >= 0 {
176 func typecheckslice(l []ir.Node, top int) {
178 l[i] = typecheck(l[i], top)
182 var _typekind = []string{
186 types.TUINT8: "uint8",
187 types.TINT16: "int16",
188 types.TUINT16: "uint16",
189 types.TINT32: "int32",
190 types.TUINT32: "uint32",
191 types.TINT64: "int64",
192 types.TUINT64: "uint64",
193 types.TUINTPTR: "uintptr",
194 types.TCOMPLEX64: "complex64",
195 types.TCOMPLEX128: "complex128",
196 types.TFLOAT32: "float32",
197 types.TFLOAT64: "float64",
199 types.TSTRING: "string",
200 types.TPTR: "pointer",
201 types.TUNSAFEPTR: "unsafe.Pointer",
202 types.TSTRUCT: "struct",
203 types.TINTER: "interface",
206 types.TARRAY: "array",
207 types.TSLICE: "slice",
210 types.TIDEAL: "untyped number",
213 func typekind(t *types.Type) string {
215 return fmt.Sprintf("%v", t)
218 if int(et) < len(_typekind) {
224 return fmt.Sprintf("etype=%d", et)
227 func cycleFor(start ir.Node) []ir.Node {
228 // Find the start node in typecheck_tcstack.
229 // We know that it must exist because each time we mark
230 // a node with n.SetTypecheck(2) we push it on the stack,
231 // and each time we mark a node with n.SetTypecheck(2) we
232 // pop it from the stack. We hit a cycle when we encounter
233 // a node marked 2 in which case is must be on the stack.
234 i := len(typecheck_tcstack) - 1
235 for i > 0 && typecheck_tcstack[i] != start {
239 // collect all nodes with same Op
241 for _, n := range typecheck_tcstack[i:] {
242 if n.Op() == start.Op() {
243 cycle = append(cycle, n)
250 func cycleTrace(cycle []ir.Node) string {
252 for i, n := range cycle {
253 s += fmt.Sprintf("\n\t%v: %v uses %v", ir.Line(n), n, cycle[(i+1)%len(cycle)])
258 var typecheck_tcstack []ir.Node
260 func Func(fn *ir.Func) {
263 base.Fatalf("typecheck changed func")
267 func typecheckNtype(n ir.Ntype) ir.Ntype {
268 return typecheck(n, ctxType).(ir.Ntype)
271 // typecheck type checks node n.
272 // The result of typecheck MUST be assigned back to n, e.g.
273 // n.Left = typecheck(n.Left, top)
274 func typecheck(n ir.Node, top int) (res ir.Node) {
275 // cannot type check until all the source has been parsed
276 if !TypecheckAllowed {
277 base.Fatalf("early typecheck")
284 // only trace if there's work to do
285 if base.EnableTrace && base.Flag.LowerT {
286 defer tracePrint("typecheck", n)(&res)
292 for n.Op() == ir.OPAREN {
293 n = n.(*ir.ParenExpr).X
296 // Resolve definition of name and value of iota lazily.
299 // Skip typecheck if already done.
300 // But re-typecheck ONAME/OTYPE/OLITERAL/OPACK node in case context has changed.
301 if n.Typecheck() == 1 || n.Typecheck() == 3 {
303 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.OPACK:
312 if n.Typecheck() == 2 {
313 // Typechecking loop. Trying printing a meaningful message,
314 // otherwise a stack trace of typechecking.
316 // We can already diagnose variables used as types.
319 if top&(ctxExpr|ctxType) == ctxType {
320 base.Errorf("%v is not a type", n)
324 // Only report a type cycle if we are expecting a type.
325 // Otherwise let other code report an error.
326 if top&ctxType == ctxType {
327 // A cycle containing only alias types is an error
328 // since it would expand indefinitely when aliases
331 for _, n1 := range cycle {
332 if n1.Name() != nil && !n1.Name().Alias() {
333 // Cycle is ok. But if n is an alias type and doesn't
334 // have a type yet, we have a recursive type declaration
335 // with aliases that we can't handle properly yet.
336 // Report an error rather than crashing later.
337 if n.Name() != nil && n.Name().Alias() && n.Type() == nil {
339 base.Fatalf("cannot handle alias type declaration (issue #25838): %v", n)
345 base.ErrorfAt(n.Pos(), "invalid recursive type alias %v%s", n, cycleTrace(cycle))
349 if top&(ctxExpr|ctxType) == ctxType {
350 base.Errorf("%v is not a type", n)
353 base.ErrorfAt(n.Pos(), "constant definition loop%s", cycleTrace(cycleFor(n)))
356 if base.Errors() == 0 {
358 for i := len(typecheck_tcstack) - 1; i >= 0; i-- {
359 x := typecheck_tcstack[i]
360 trace += fmt.Sprintf("\n\t%v %v", ir.Line(x), x)
362 base.Errorf("typechecking loop involving %v%s", n, trace)
369 typecheck_tcstack = append(typecheck_tcstack, n)
372 n = typecheck1(n, top)
375 last := len(typecheck_tcstack) - 1
376 typecheck_tcstack[last] = nil
377 typecheck_tcstack = typecheck_tcstack[:last]
379 _, isExpr := n.(ir.Expr)
380 _, isStmt := n.(ir.Stmt)
383 case ir.OCALLFUNC, ir.OCALLINTER, ir.OCALLMETH:
384 n := n.(*ir.CallExpr)
385 if t := n.X.Type(); t != nil && t.Kind() == types.TFUNC {
393 // Must be used (and not BinaryExpr/UnaryExpr).
395 case ir.OCLOSE, ir.ODELETE, ir.OPANIC, ir.OPRINT, ir.OPRINTN, ir.OVARKILL, ir.OVARLIVE:
399 case ir.OCOPY, ir.ORECOVER, ir.ORECV:
400 // Can be used or not.
405 if t != nil && !t.IsFuncArgStruct() && n.Op() != ir.OTYPE {
407 case types.TFUNC, // might have TANY; wait until it's called
408 types.TANY, types.TFORW, types.TIDEAL, types.TNIL, types.TBLANK:
420 // TODO(rsc): Lots of the complexity here is because typecheck can
421 // see OTYPE, ONAME, and OLITERAL nodes multiple times.
422 // Once we make the IR a proper tree, we should be able to simplify
423 // this code a bit, especially the final case.
425 case top&(ctxStmt|ctxExpr) == ctxExpr && !isExpr && n.Op() != ir.OTYPE && !isMulti:
427 base.Errorf("%v used as value", n)
434 case top&ctxType == 0 && n.Op() == ir.OTYPE && t != nil:
435 if !n.Type().Broke() {
436 base.Errorf("type %v is not an expression", n.Type())
440 case top&(ctxStmt|ctxExpr) == ctxStmt && !isStmt && t != nil:
442 base.Errorf("%v evaluated but not used", n)
447 case top&(ctxType|ctxExpr) == ctxType && n.Op() != ir.OTYPE && n.Op() != ir.ONONAME && (t != nil || n.Op() == ir.ONAME):
448 base.Errorf("%v is not a type", n)
450 if n.Op() == ir.ONAME {
463 // indexlit implements typechecking of untyped values as
464 // array/slice indexes. It is almost equivalent to DefaultLit
465 // but also accepts untyped numeric values representable as
466 // value of type int (see also checkmake for comparison).
467 // The result of indexlit MUST be assigned back to n, e.g.
468 // n.Left = indexlit(n.Left)
469 func indexlit(n ir.Node) ir.Node {
470 if n != nil && n.Type() != nil && n.Type().Kind() == types.TIDEAL {
471 return DefaultLit(n, types.Types[types.TINT])
476 // typecheck1 should ONLY be called from typecheck.
477 func typecheck1(n ir.Node, top int) ir.Node {
478 if n, ok := n.(*ir.Name); ok {
484 ir.Dump("typecheck", n)
485 base.Fatalf("typecheck %v", n.Op())
489 if n.Sym() == nil && n.Type() == nil {
491 base.Fatalf("literal missing type: %v", n)
502 // Note: adderrorname looks for this string and
503 // adds context about the outer expression
504 base.ErrorfAt(n.Pos(), "undefined: %v", n.Sym())
512 if n.BuiltinOp != 0 {
513 if top&ctxCallee == 0 {
514 base.Errorf("use of builtin %v not in function call", n.Sym())
520 if top&ctxAssign == 0 {
521 // not a write to the variable
523 base.Errorf("cannot use _ as value")
531 case ir.OLINKSYMOFFSET:
537 base.Errorf("use of package %v without selector", n.Sym())
541 // types (ODEREF is with exprs)
546 n := n.(*ir.SliceType)
547 return tcSliceType(n)
550 n := n.(*ir.ArrayType)
551 return tcArrayType(n)
558 n := n.(*ir.ChanType)
562 n := n.(*ir.StructType)
563 return tcStructType(n)
566 n := n.(*ir.InterfaceType)
567 return tcInterfaceType(n)
570 n := n.(*ir.FuncType)
574 n := n.(*ir.StarExpr)
575 return tcStar(n, top)
579 n := n.(*ir.AssignOpStmt)
580 n.X, n.Y = Expr(n.X), Expr(n.Y)
582 if n.IncDec && !okforarith[n.X.Type().Kind()] {
583 base.Errorf("invalid operation: %v (non-numeric type %v)", n, n.X.Type())
587 case ir.OLSH, ir.ORSH:
588 n.X, n.Y, _ = tcShift(n, n.X, n.Y)
589 case ir.OADD, ir.OAND, ir.OANDNOT, ir.ODIV, ir.OMOD, ir.OMUL, ir.OOR, ir.OSUB, ir.OXOR:
590 n.X, n.Y, _ = tcArith(n, n.AsOp, n.X, n.Y)
592 base.Fatalf("invalid assign op: %v", n.AsOp)
597 case ir.OANDAND, ir.OOROR:
598 n := n.(*ir.LogicalExpr)
599 n.X, n.Y = Expr(n.X), Expr(n.Y)
600 if n.X.Type() == nil || n.Y.Type() == nil {
604 // For "x == x && len(s)", it's better to report that "len(s)" (type int)
605 // can't be used with "&&" than to report that "x == x" (type untyped bool)
606 // can't be converted to int (see issue #41500).
607 if !n.X.Type().IsBoolean() {
608 base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, n.Op(), typekind(n.X.Type()))
612 if !n.Y.Type().IsBoolean() {
613 base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, n.Op(), typekind(n.Y.Type()))
617 l, r, t := tcArith(n, n.Op(), n.X, n.Y)
623 case ir.OLSH, ir.ORSH:
624 n := n.(*ir.BinaryExpr)
625 n.X, n.Y = Expr(n.X), Expr(n.Y)
626 l, r, t := tcShift(n, n.X, n.Y)
631 // comparison operators
632 case ir.OEQ, ir.OGE, ir.OGT, ir.OLE, ir.OLT, ir.ONE:
633 n := n.(*ir.BinaryExpr)
634 n.X, n.Y = Expr(n.X), Expr(n.Y)
635 l, r, t := tcArith(n, n.Op(), n.X, n.Y)
638 n.SetType(types.UntypedBool)
639 if con := EvalConst(n); con.Op() == ir.OLITERAL {
642 n.X, n.Y = defaultlit2(l, r, true)
647 case ir.OADD, ir.OAND, ir.OANDNOT, ir.ODIV, ir.OMOD, ir.OMUL, ir.OOR, ir.OSUB, ir.OXOR:
648 n := n.(*ir.BinaryExpr)
649 n.X, n.Y = Expr(n.X), Expr(n.Y)
650 l, r, t := tcArith(n, n.Op(), n.X, n.Y)
651 if t != nil && t.Kind() == types.TSTRING && n.Op() == ir.OADD {
652 // create or update OADDSTR node with list of strings in x + y + z + (w + v) + ...
653 var add *ir.AddStringExpr
654 if l.Op() == ir.OADDSTR {
655 add = l.(*ir.AddStringExpr)
658 add = ir.NewAddStringExpr(n.Pos(), []ir.Node{l})
660 if r.Op() == ir.OADDSTR {
661 r := r.(*ir.AddStringExpr)
662 add.List.Append(r.List.Take()...)
673 case ir.OBITNOT, ir.ONEG, ir.ONOT, ir.OPLUS:
674 n := n.(*ir.UnaryExpr)
675 return tcUnaryArith(n)
679 n := n.(*ir.AddrExpr)
683 return tcCompLit(n.(*ir.CompLitExpr))
685 case ir.OXDOT, ir.ODOT:
686 n := n.(*ir.SelectorExpr)
690 n := n.(*ir.TypeAssertExpr)
694 n := n.(*ir.IndexExpr)
698 n := n.(*ir.UnaryExpr)
702 n := n.(*ir.SendStmt)
705 case ir.OSLICEHEADER:
706 n := n.(*ir.SliceHeaderExpr)
707 return tcSliceHeader(n)
709 case ir.OMAKESLICECOPY:
710 n := n.(*ir.MakeExpr)
711 return tcMakeSliceCopy(n)
713 case ir.OSLICE, ir.OSLICE3:
714 n := n.(*ir.SliceExpr)
717 // call and call like
719 n := n.(*ir.CallExpr)
720 return tcCall(n, top)
722 case ir.OALIGNOF, ir.OOFFSETOF, ir.OSIZEOF:
723 n := n.(*ir.UnaryExpr)
724 n.SetType(types.Types[types.TUINTPTR])
727 case ir.OCAP, ir.OLEN:
728 n := n.(*ir.UnaryExpr)
731 case ir.OREAL, ir.OIMAG:
732 n := n.(*ir.UnaryExpr)
736 n := n.(*ir.BinaryExpr)
740 n := n.(*ir.UnaryExpr)
744 n := n.(*ir.CallExpr)
748 n := n.(*ir.CallExpr)
752 n := n.(*ir.BinaryExpr)
756 n := n.(*ir.ConvExpr)
760 n := n.(*ir.CallExpr)
764 n := n.(*ir.UnaryExpr)
767 case ir.OPRINT, ir.OPRINTN:
768 n := n.(*ir.CallExpr)
772 n := n.(*ir.UnaryExpr)
776 n := n.(*ir.CallExpr)
780 n := n.(*ir.CallExpr)
781 return tcRecoverFP(n)
784 n := n.(*ir.BinaryExpr)
785 return tcUnsafeAdd(n)
787 case ir.OUNSAFESLICE:
788 n := n.(*ir.BinaryExpr)
789 return tcUnsafeSlice(n)
792 n := n.(*ir.ClosureExpr)
793 return tcClosure(n, top)
796 n := n.(*ir.UnaryExpr)
800 // Whoever creates the OIDATA node must know a priori the concrete type at that moment,
801 // usually by just having checked the OITAB.
802 n := n.(*ir.UnaryExpr)
803 base.Fatalf("cannot typecheck interface data %v", n)
807 n := n.(*ir.UnaryExpr)
811 n := n.(*ir.UnaryExpr)
813 n.SetType(types.Types[types.TUINTPTR])
816 case ir.OGETCALLERPC, ir.OGETCALLERSP:
817 n := n.(*ir.CallExpr)
818 if len(n.Args) != 0 {
819 base.FatalfAt(n.Pos(), "unexpected arguments: %v", n)
821 n.SetType(types.Types[types.TUINTPTR])
825 n := n.(*ir.ConvExpr)
831 n := n.(*ir.AssignStmt)
834 // Code that creates temps does not bother to set defn, so do it here.
835 if n.X.Op() == ir.ONAME && ir.IsAutoTmp(n.X) {
841 tcAssignList(n.(*ir.AssignListStmt))
854 n := n.(*ir.BlockStmt)
859 if n.Sym().IsBlank() {
860 // Empty identifier is valid but useless.
861 // Eliminate now to simplify life later.
862 // See issues 7538, 11589, 11593.
863 n = ir.NewBlockStmt(n.Pos(), nil)
867 case ir.ODEFER, ir.OGO:
868 n := n.(*ir.GoDeferStmt)
869 n.Call = typecheck(n.Call, ctxStmt|ctxExpr)
875 case ir.OFOR, ir.OFORUNTIL:
884 n := n.(*ir.ReturnStmt)
888 n := n.(*ir.TailCallStmt)
892 n := n.(*ir.UnaryExpr)
896 tcSelect(n.(*ir.SelectStmt))
900 tcSwitch(n.(*ir.SwitchStmt))
904 tcRange(n.(*ir.RangeStmt))
908 n := n.(*ir.TypeSwitchGuard)
909 base.Errorf("use of .(type) outside type switch")
919 n.X = Expr(n.X).(*ir.Name)
924 n.X = typecheck(n.X, ctxType).(*ir.Name)
925 types.CheckSize(n.X.Type())
930 // Individual cases can type-assert n, introducing a new one.
931 // Each must execute its own return n.
934 func typecheckargs(n ir.InitNode) {
936 switch n := n.(type) {
938 base.Fatalf("typecheckargs %+v", n.Op())
953 typecheckslice(list, ctxExpr|ctxMultiOK)
955 if t == nil || !t.IsFuncArgStruct() {
959 // Save n as n.Orig for fmt.go.
961 n.(ir.OrigNode).SetOrig(ir.SepCopy(n))
964 // Rewrite f(g()) into t1, t2, ... = g(); f(t1, t2, ...).
965 RewriteMultiValueCall(n, list[0])
968 // RewriteMultiValueCall rewrites multi-valued f() to use temporaries,
969 // so the backend wouldn't need to worry about tuple-valued expressions.
970 func RewriteMultiValueCall(n ir.InitNode, call ir.Node) {
971 // If we're outside of function context, then this call will
972 // be executed during the generated init function. However,
973 // init.go hasn't yet created it. Instead, associate the
974 // temporary variables with InitTodoFunc for now, and init.go
975 // will reassociate them later when it's appropriate.
976 static := ir.CurFunc == nil
978 ir.CurFunc = InitTodoFunc
981 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, []ir.Node{call})
982 results := call.Type().FieldSlice()
983 list := make([]ir.Node, len(results))
984 for i, result := range results {
985 tmp := Temp(result.Type)
986 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, tmp))
994 n.PtrInit().Append(Stmt(as))
996 switch n := n.(type) {
998 base.Fatalf("rewriteMultiValueCall %+v", n.Op())
1001 case *ir.ReturnStmt:
1003 case *ir.AssignListStmt:
1004 if n.Op() != ir.OAS2FUNC {
1005 base.Fatalf("rewriteMultiValueCall: invalid op %v", n.Op())
1007 as.SetOp(ir.OAS2FUNC)
1009 n.Rhs = make([]ir.Node, len(list))
1010 for i, tmp := range list {
1011 n.Rhs[i] = AssignConv(tmp, n.Lhs[i].Type(), "assignment")
1016 func checksliceindex(l ir.Node, r ir.Node, tp *types.Type) bool {
1022 base.Errorf("invalid slice index %v (type %v)", r, t)
1026 if r.Op() == ir.OLITERAL {
1028 if constant.Sign(x) < 0 {
1029 base.Errorf("invalid slice index %v (index must be non-negative)", r)
1031 } else if tp != nil && tp.NumElem() >= 0 && constant.Compare(x, token.GTR, constant.MakeInt64(tp.NumElem())) {
1032 base.Errorf("invalid slice index %v (out of bounds for %d-element array)", r, tp.NumElem())
1034 } else if ir.IsConst(l, constant.String) && constant.Compare(x, token.GTR, constant.MakeInt64(int64(len(ir.StringVal(l))))) {
1035 base.Errorf("invalid slice index %v (out of bounds for %d-byte string)", r, len(ir.StringVal(l)))
1037 } else if ir.ConstOverflow(x, types.Types[types.TINT]) {
1038 base.Errorf("invalid slice index %v (index too large)", r)
1046 func checksliceconst(lo ir.Node, hi ir.Node) bool {
1047 if lo != nil && hi != nil && lo.Op() == ir.OLITERAL && hi.Op() == ir.OLITERAL && constant.Compare(lo.Val(), token.GTR, hi.Val()) {
1048 base.Errorf("invalid slice index: %v > %v", lo, hi)
1055 // The result of implicitstar MUST be assigned back to n, e.g.
1056 // n.Left = implicitstar(n.Left)
1057 func implicitstar(n ir.Node) ir.Node {
1058 // insert implicit * if needed for fixed array
1060 if t == nil || !t.IsPtr() {
1070 star := ir.NewStarExpr(base.Pos, n)
1071 star.SetImplicit(true)
1075 func needOneArg(n *ir.CallExpr, f string, args ...interface{}) (ir.Node, bool) {
1076 if len(n.Args) == 0 {
1077 p := fmt.Sprintf(f, args...)
1078 base.Errorf("missing argument to %s: %v", p, n)
1082 if len(n.Args) > 1 {
1083 p := fmt.Sprintf(f, args...)
1084 base.Errorf("too many arguments to %s: %v", p, n)
1085 return n.Args[0], false
1088 return n.Args[0], true
1091 func needTwoArgs(n *ir.CallExpr) (ir.Node, ir.Node, bool) {
1092 if len(n.Args) != 2 {
1093 if len(n.Args) < 2 {
1094 base.Errorf("not enough arguments in call to %v", n)
1096 base.Errorf("too many arguments in call to %v", n)
1098 return nil, nil, false
1100 return n.Args[0], n.Args[1], true
1103 // Lookdot1 looks up the specified method s in the list fs of methods, returning
1104 // the matching field or nil. If dostrcmp is 0, it matches the symbols. If
1105 // dostrcmp is 1, it matches by name exactly. If dostrcmp is 2, it matches names
1106 // with case folding.
1107 func Lookdot1(errnode ir.Node, s *types.Sym, t *types.Type, fs *types.Fields, dostrcmp int) *types.Field {
1109 for _, f := range fs.Slice() {
1110 if dostrcmp != 0 && f.Sym.Name == s.Name {
1113 if dostrcmp == 2 && strings.EqualFold(f.Sym.Name, s.Name) {
1121 base.Errorf("ambiguous selector %v", errnode)
1122 } else if t.IsPtr() {
1123 base.Errorf("ambiguous selector (%v).%v", t, s)
1125 base.Errorf("ambiguous selector %v.%v", t, s)
1136 // typecheckMethodExpr checks selector expressions (ODOT) where the
1137 // base expression is a type expression (OTYPE).
1138 func typecheckMethodExpr(n *ir.SelectorExpr) (res ir.Node) {
1139 if base.EnableTrace && base.Flag.LowerT {
1140 defer tracePrint("typecheckMethodExpr", n)(&res)
1145 // Compute the method set for t.
1146 var ms *types.Fields
1147 if t.IsInterface() {
1150 mt := types.ReceiverBaseType(t)
1152 base.Errorf("%v undefined (type %v has no method %v)", n, t, n.Sel)
1157 ms = mt.AllMethods()
1159 // The method expression T.m requires a wrapper when T
1160 // is different from m's declared receiver type. We
1161 // normally generate these wrappers while writing out
1162 // runtime type descriptors, which is always done for
1163 // types declared at package scope. However, we need
1164 // to make sure to generate wrappers for anonymous
1165 // receiver types too.
1166 if mt.Sym() == nil {
1172 m := Lookdot1(n, s, t, ms, 0)
1174 if Lookdot1(n, s, t, ms, 1) != nil {
1175 base.Errorf("%v undefined (cannot refer to unexported method %v)", n, s)
1176 } else if _, ambig := dotpath(s, t, nil, false); ambig {
1177 base.Errorf("%v undefined (ambiguous selector)", n) // method or field
1179 base.Errorf("%v undefined (type %v has no method %v)", n, t, s)
1185 if !types.IsMethodApplicable(t, m) {
1186 base.Errorf("invalid method expression %v (needs pointer receiver: (*%v).%S)", n, t, s)
1191 n.SetOp(ir.OMETHEXPR)
1193 n.SetType(NewMethodType(m.Type, n.X.Type()))
1197 func derefall(t *types.Type) *types.Type {
1198 for t != nil && t.IsPtr() {
1204 // Lookdot looks up field or method n.Sel in the type t and returns the matching
1205 // field. It transforms the op of node n to ODOTINTER or ODOTMETH, if appropriate.
1206 // It also may add a StarExpr node to n.X as needed for access to non-pointer
1207 // methods. If dostrcmp is 0, it matches the field/method with the exact symbol
1208 // as n.Sel (appropriate for exported fields). If dostrcmp is 1, it matches by name
1209 // exactly. If dostrcmp is 2, it matches names with case folding.
1210 func Lookdot(n *ir.SelectorExpr, t *types.Type, dostrcmp int) *types.Field {
1216 f1 = Lookdot1(n, s, t, t.Fields(), dostrcmp)
1217 } else if t.IsInterface() {
1218 f1 = Lookdot1(n, s, t, t.AllMethods(), dostrcmp)
1222 if n.X.Type() == t || n.X.Type().Sym() == nil {
1223 mt := types.ReceiverBaseType(t)
1225 f2 = Lookdot1(n, s, mt, mt.Methods(), dostrcmp)
1230 if dostrcmp > 1 || f1.Broke() {
1231 // Already in the process of diagnosing an error.
1235 base.Errorf("%v is both field and method", n.Sel)
1237 if f1.Offset == types.BADWIDTH {
1238 base.Fatalf("Lookdot badwidth t=%v, f1=%v@%p", t, f1, f1)
1242 if t.IsInterface() {
1243 if n.X.Type().IsPtr() {
1244 star := ir.NewStarExpr(base.Pos, n.X)
1245 star.SetImplicit(true)
1249 n.SetOp(ir.ODOTINTER)
1256 // Already in the process of diagnosing an error.
1262 rcvr := f2.Type.Recv().Type
1263 if !types.Identical(rcvr, tt) {
1264 if rcvr.IsPtr() && types.Identical(rcvr.Elem(), tt) {
1265 checklvalue(n.X, "call pointer method on")
1266 addr := NodAddr(n.X)
1267 addr.SetImplicit(true)
1268 n.X = typecheck(addr, ctxType|ctxExpr)
1269 } else if tt.IsPtr() && (!rcvr.IsPtr() || rcvr.IsPtr() && rcvr.Elem().NotInHeap()) && types.Identical(tt.Elem(), rcvr) {
1270 star := ir.NewStarExpr(base.Pos, n.X)
1271 star.SetImplicit(true)
1272 n.X = typecheck(star, ctxType|ctxExpr)
1273 } else if tt.IsPtr() && tt.Elem().IsPtr() && types.Identical(derefall(tt), derefall(rcvr)) {
1274 base.Errorf("calling method %v with receiver %L requires explicit dereference", n.Sel, n.X)
1276 // Stop one level early for method with pointer receiver.
1277 if rcvr.IsPtr() && !tt.Elem().IsPtr() {
1280 star := ir.NewStarExpr(base.Pos, n.X)
1281 star.SetImplicit(true)
1282 n.X = typecheck(star, ctxType|ctxExpr)
1286 base.Fatalf("method mismatch: %v for %v", rcvr, tt)
1290 // Check that we haven't implicitly dereferenced any defined pointer types.
1294 switch x := x.(type) {
1296 inner, implicit = x.X, x.Implicit()
1297 case *ir.SelectorExpr:
1298 inner, implicit = x.X, x.Implicit()
1300 inner, implicit = x.X, x.Implicit()
1305 if inner.Type().Sym() != nil && (x.Op() == ir.ODEREF || x.Op() == ir.ODOTPTR) {
1306 // Found an implicit dereference of a defined pointer type.
1307 // Restore n.X for better error message.
1316 n.SetOp(ir.ODOTMETH)
1324 func nokeys(l ir.Nodes) bool {
1325 for _, n := range l {
1326 if n.Op() == ir.OKEY || n.Op() == ir.OSTRUCTKEY {
1333 func hasddd(t *types.Type) bool {
1334 for _, tl := range t.Fields().Slice() {
1343 // typecheck assignment: type list = expression list
1344 func typecheckaste(op ir.Op, call ir.Node, isddd bool, tstruct *types.Type, nl ir.Nodes, desc func() string) {
1349 defer func() { base.Pos = lno }()
1351 if tstruct.Broke() {
1360 n1 := tstruct.NumFields()
1362 if !hasddd(tstruct) {
1388 for _, tl := range tstruct.Fields().Slice() {
1400 if n.Type() != nil {
1401 nl[i] = assignconvfn(n, t, desc)
1406 // TODO(mdempsky): Make into ... call with implicit slice.
1407 for ; i < len(nl); i++ {
1410 if n.Type() != nil {
1411 nl[i] = assignconvfn(n, t.Elem(), desc)
1422 if n.Type() != nil {
1423 nl[i] = assignconvfn(n, t, desc)
1435 base.Errorf("invalid use of ... in call to %v", call)
1437 base.Errorf("invalid use of ... in %v", op)
1443 if n == nil || (!n.Diag() && n.Type() != nil) {
1444 details := errorDetails(nl, tstruct, isddd)
1446 // call is the expression being called, not the overall call.
1447 // Method expressions have the form T.M, and the compiler has
1448 // rewritten those to ONAME nodes but left T in Left.
1449 if call.Op() == ir.OMETHEXPR {
1450 call := call.(*ir.SelectorExpr)
1451 base.Errorf("not enough arguments in call to method expression %v%s", call, details)
1453 base.Errorf("not enough arguments in call to %v%s", call, details)
1456 base.Errorf("not enough arguments to %v%s", op, details)
1465 details := errorDetails(nl, tstruct, isddd)
1467 base.Errorf("too many arguments in call to %v%s", call, details)
1469 base.Errorf("too many arguments to %v%s", op, details)
1473 func errorDetails(nl ir.Nodes, tstruct *types.Type, isddd bool) string {
1474 // Suppress any return message signatures if:
1476 // (1) We don't know any type at a call site (see #19012).
1477 // (2) Any node has an unknown type.
1478 // (3) Invalid type for variadic parameter (see #46957).
1483 if isddd && !nl[len(nl)-1].Type().IsSlice() {
1487 for _, n := range nl {
1488 if n.Type() == nil {
1492 return fmt.Sprintf("\n\thave %s\n\twant %v", fmtSignature(nl, isddd), tstruct)
1495 // sigrepr is a type's representation to the outside world,
1496 // in string representations of return signatures
1497 // e.g in error messages about wrong arguments to return.
1498 func sigrepr(t *types.Type, isddd bool) string {
1500 case types.UntypedString:
1502 case types.UntypedBool:
1506 if t.Kind() == types.TIDEAL {
1507 // "untyped number" is not commonly used
1508 // outside of the compiler, so let's use "number".
1509 // TODO(mdempsky): Revisit this.
1513 // Turn []T... argument to ...T for clearer error message.
1516 base.Fatalf("bad type for ... argument: %v", t)
1518 return "..." + t.Elem().String()
1523 // sigerr returns the signature of the types at the call or return.
1524 func fmtSignature(nl ir.Nodes, isddd bool) string {
1529 var typeStrings []string
1530 for i, n := range nl {
1531 isdddArg := isddd && i == len(nl)-1
1532 typeStrings = append(typeStrings, sigrepr(n.Type(), isdddArg))
1535 return fmt.Sprintf("(%s)", strings.Join(typeStrings, ", "))
1538 // type check composite
1539 func fielddup(name string, hash map[string]bool) {
1541 base.Errorf("duplicate field name in struct literal: %s", name)
1547 // iscomptype reports whether type t is a composite literal type.
1548 func iscomptype(t *types.Type) bool {
1550 case types.TARRAY, types.TSLICE, types.TSTRUCT, types.TMAP:
1557 // pushtype adds elided type information for composite literals if
1558 // appropriate, and returns the resulting expression.
1559 func pushtype(nn ir.Node, t *types.Type) ir.Node {
1560 if nn == nil || nn.Op() != ir.OCOMPLIT {
1563 n := nn.(*ir.CompLitExpr)
1570 // For T, return T{...}.
1571 n.Ntype = ir.TypeNode(t)
1573 case t.IsPtr() && iscomptype(t.Elem()):
1574 // For *T, return &T{...}.
1575 n.Ntype = ir.TypeNode(t.Elem())
1577 addr := NodAddrAt(n.Pos(), n)
1578 addr.SetImplicit(true)
1584 // typecheckarraylit type-checks a sequence of slice/array literal elements.
1585 func typecheckarraylit(elemType *types.Type, bound int64, elts []ir.Node, ctx string) int64 {
1586 // If there are key/value pairs, create a map to keep seen
1587 // keys so we can check for duplicate indices.
1588 var indices map[int64]bool
1589 for _, elt := range elts {
1590 if elt.Op() == ir.OKEY {
1591 indices = make(map[int64]bool)
1596 var key, length int64
1597 for i, elt := range elts {
1601 if elt.Op() == ir.OKEY {
1602 elt := elt.(*ir.KeyExpr)
1603 elt.Key = Expr(elt.Key)
1604 key = IndexConst(elt.Key)
1606 if !elt.Key.Diag() {
1608 base.Errorf("index too large")
1610 base.Errorf("index must be non-negative integer constant")
1612 elt.Key.SetDiag(true)
1614 key = -(1 << 30) // stay negative for a while
1620 r = pushtype(r, elemType)
1622 r = AssignConv(r, elemType, ctx)
1632 base.Errorf("duplicate index in %s: %d", ctx, key)
1638 if bound >= 0 && key >= bound {
1639 base.Errorf("array index %d out of bounds [0:%d]", key, bound)
1653 // visible reports whether sym is exported or locally defined.
1654 func visible(sym *types.Sym) bool {
1655 return sym != nil && (types.IsExported(sym.Name) || sym.Pkg == types.LocalPkg)
1658 // nonexported reports whether sym is an unexported field.
1659 func nonexported(sym *types.Sym) bool {
1660 return sym != nil && !types.IsExported(sym.Name)
1663 func checklvalue(n ir.Node, verb string) {
1664 if !ir.IsAddressable(n) {
1665 base.Errorf("cannot %s %v", verb, n)
1669 func checkassign(stmt ir.Node, n ir.Node) {
1670 // have already complained about n being invalid
1671 if n.Type() == nil {
1672 if base.Errors() == 0 {
1673 base.Fatalf("expected an error about %v", n)
1678 if ir.IsAddressable(n) {
1681 if n.Op() == ir.OINDEXMAP {
1682 n := n.(*ir.IndexExpr)
1687 defer n.SetType(nil)
1692 case n.Op() == ir.ODOT && n.(*ir.SelectorExpr).X.Op() == ir.OINDEXMAP:
1693 base.Errorf("cannot assign to struct field %v in map", n)
1694 case (n.Op() == ir.OINDEX && n.(*ir.IndexExpr).X.Type().IsString()) || n.Op() == ir.OSLICESTR:
1695 base.Errorf("cannot assign to %v (strings are immutable)", n)
1696 case n.Op() == ir.OLITERAL && n.Sym() != nil && ir.IsConstNode(n):
1697 base.Errorf("cannot assign to %v (declared const)", n)
1699 base.Errorf("cannot assign to %v", n)
1703 func checkassignto(src *types.Type, dst ir.Node) {
1704 // TODO(mdempsky): Handle all untyped types correctly.
1705 if src == types.UntypedBool && dst.Type().IsBoolean() {
1709 if op, why := Assignop(src, dst.Type()); op == ir.OXXX {
1710 base.Errorf("cannot assign %v to %L in multiple assignment%s", src, dst, why)
1715 // The result of stringtoruneslit MUST be assigned back to n, e.g.
1716 // n.Left = stringtoruneslit(n.Left)
1717 func stringtoruneslit(n *ir.ConvExpr) ir.Node {
1718 if n.X.Op() != ir.OLITERAL || n.X.Val().Kind() != constant.String {
1719 base.Fatalf("stringtoarraylit %v", n)
1724 for _, r := range ir.StringVal(n.X) {
1725 l = append(l, ir.NewKeyExpr(base.Pos, ir.NewInt(int64(i)), ir.NewInt(int64(r))))
1729 nn := ir.NewCompLitExpr(base.Pos, ir.OCOMPLIT, ir.TypeNode(n.Type()), nil)
1734 var mapqueue []*ir.MapType
1736 func CheckMapKeys() {
1737 for _, n := range mapqueue {
1738 k := n.Type().MapType().Key
1739 if !k.Broke() && !types.IsComparable(k) {
1740 base.ErrorfAt(n.Pos(), "invalid map key type %v", k)
1746 // TypeGen tracks the number of function-scoped defined types that
1747 // have been declared. It's used to generate unique linker symbols for
1748 // their runtime type descriptors.
1751 func typecheckdeftype(n *ir.Name) {
1752 if base.EnableTrace && base.Flag.LowerT {
1753 defer tracePrint("typecheckdeftype", n)(nil)
1756 t := types.NewNamed(n)
1762 if n.Pragma()&ir.NotInHeap != 0 {
1763 t.SetNotInHeap(true)
1770 types.DeferCheckSize()
1771 errorsBefore := base.Errors()
1772 n.Ntype = typecheckNtype(n.Ntype)
1773 if underlying := n.Ntype.Type(); underlying != nil {
1774 t.SetUnderlying(underlying)
1779 if t.Kind() == types.TFORW && base.Errors() > errorsBefore {
1780 // Something went wrong during type-checking,
1781 // but it was reported. Silence future errors.
1784 types.ResumeCheckSize()
1787 func typecheckdef(n *ir.Name) {
1788 if base.EnableTrace && base.Flag.LowerT {
1789 defer tracePrint("typecheckdef", n)(nil)
1792 if n.Walkdef() == 1 {
1796 if n.Type() != nil { // builtin
1797 // Mark as Walkdef so that if n.SetType(nil) is called later, we
1798 // won't try walking again.
1799 if got := n.Walkdef(); got != 0 {
1800 base.Fatalf("unexpected walkdef: %v", got)
1807 typecheckdefstack = append(typecheckdefstack, n)
1808 if n.Walkdef() == 2 {
1810 fmt.Printf("typecheckdef loop:")
1811 for i := len(typecheckdefstack) - 1; i >= 0; i-- {
1812 n := typecheckdefstack[i]
1813 fmt.Printf(" %v", n.Sym())
1816 base.Fatalf("typecheckdef loop")
1823 base.Fatalf("typecheckdef %v", n.Op())
1827 n.Ntype = typecheckNtype(n.Ntype)
1828 n.SetType(n.Ntype.Type())
1830 if n.Type() == nil {
1839 ir.Dump("typecheckdef nil defn", n)
1840 base.ErrorfAt(n.Pos(), "xxx")
1844 if e.Type() == nil {
1847 if !ir.IsConstNode(e) {
1849 if e.Op() == ir.ONIL {
1850 base.ErrorfAt(n.Pos(), "const initializer cannot be nil")
1852 base.ErrorfAt(n.Pos(), "const initializer %v is not a constant", e)
1861 if !ir.OKForConst[t.Kind()] {
1862 base.ErrorfAt(n.Pos(), "invalid constant type %v", t)
1866 if !e.Type().IsUntyped() && !types.Identical(t, e.Type()) {
1867 base.ErrorfAt(n.Pos(), "cannot use %L as type %v in const initializer", e, t)
1875 if n.Type() != nil {
1881 n.Ntype = typecheckNtype(n.Ntype)
1882 n.SetType(n.Ntype.Type())
1883 if n.Type() == nil {
1889 if n.Type() != nil {
1893 if n.BuiltinOp != 0 { // like OPRINTN
1896 if base.Errors() > 0 {
1897 // Can have undefined variables in x := foo
1898 // that make x have an n.name.Defn == nil.
1899 // If there are other errors anyway, don't
1900 // bother adding to the noise.
1904 base.Fatalf("var without type, init: %v", n.Sym())
1907 if n.Defn.Op() == ir.ONAME {
1908 n.Defn = Expr(n.Defn)
1909 n.SetType(n.Defn.Type())
1913 n.Defn = Stmt(n.Defn) // fills in n.Type
1917 // Type alias declaration: Simply use the rhs type - no need
1918 // to create a new type.
1919 // If we have a syntax error, name.Ntype may be nil.
1921 n.Ntype = typecheckNtype(n.Ntype)
1922 n.SetType(n.Ntype.Type())
1923 if n.Type() == nil {
1931 // regular type declaration
1936 if n.Op() != ir.OLITERAL && n.Type() != nil && n.Type().IsUntyped() {
1937 base.Fatalf("got %v for %v", n.Type(), n)
1939 last := len(typecheckdefstack) - 1
1940 if typecheckdefstack[last] != n {
1941 base.Fatalf("typecheckdefstack mismatch")
1943 typecheckdefstack[last] = nil
1944 typecheckdefstack = typecheckdefstack[:last]
1950 func checkmake(t *types.Type, arg string, np *ir.Node) bool {
1952 if !n.Type().IsInteger() && n.Type().Kind() != types.TIDEAL {
1953 base.Errorf("non-integer %s argument in make(%v) - %v", arg, t, n.Type())
1957 // Do range checks for constants before DefaultLit
1958 // to avoid redundant "constant NNN overflows int" errors.
1959 if n.Op() == ir.OLITERAL {
1961 if constant.Sign(v) < 0 {
1962 base.Errorf("negative %s argument in make(%v)", arg, t)
1965 if ir.ConstOverflow(v, types.Types[types.TINT]) {
1966 base.Errorf("%s argument too large in make(%v)", arg, t)
1971 // DefaultLit is necessary for non-constants too: n might be 1.1<<k.
1972 // TODO(gri) The length argument requirements for (array/slice) make
1973 // are the same as for index expressions. Factor the code better;
1974 // for instance, indexlit might be called here and incorporate some
1975 // of the bounds checks done for make.
1976 n = DefaultLit(n, types.Types[types.TINT])
1982 // checkunsafeslice is like checkmake but for unsafe.Slice.
1983 func checkunsafeslice(np *ir.Node) bool {
1985 if !n.Type().IsInteger() && n.Type().Kind() != types.TIDEAL {
1986 base.Errorf("non-integer len argument in unsafe.Slice - %v", n.Type())
1990 // Do range checks for constants before DefaultLit
1991 // to avoid redundant "constant NNN overflows int" errors.
1992 if n.Op() == ir.OLITERAL {
1994 if constant.Sign(v) < 0 {
1995 base.Errorf("negative len argument in unsafe.Slice")
1998 if ir.ConstOverflow(v, types.Types[types.TINT]) {
1999 base.Errorf("len argument too large in unsafe.Slice")
2004 // DefaultLit is necessary for non-constants too: n might be 1.1<<k.
2005 n = DefaultLit(n, types.Types[types.TINT])
2011 // markBreak marks control statements containing break statements with SetHasBreak(true).
2012 func markBreak(fn *ir.Func) {
2013 var labels map[*types.Sym]ir.Node
2014 var implicit ir.Node
2016 var mark func(ir.Node) bool
2017 mark = func(n ir.Node) bool {
2020 ir.DoChildren(n, mark)
2023 n := n.(*ir.BranchStmt)
2025 setHasBreak(implicit)
2027 setHasBreak(labels[n.Label])
2030 case ir.OFOR, ir.OFORUNTIL, ir.OSWITCH, ir.OSELECT, ir.ORANGE:
2034 switch n := n.(type) {
2039 case *ir.SelectStmt:
2041 case *ir.SwitchStmt:
2046 // Map creation delayed until we need it - most functions don't.
2047 labels = make(map[*types.Sym]ir.Node)
2051 ir.DoChildren(n, mark)
2063 func controlLabel(n ir.Node) *types.Sym {
2064 switch n := n.(type) {
2066 base.Fatalf("controlLabel %+v", n.Op())
2072 case *ir.SelectStmt:
2074 case *ir.SwitchStmt:
2079 func setHasBreak(n ir.Node) {
2080 switch n := n.(type) {
2082 base.Fatalf("setHasBreak %+v", n.Op())
2089 case *ir.SelectStmt:
2091 case *ir.SwitchStmt:
2096 // isTermNodes reports whether the Nodes list ends with a terminating statement.
2097 func isTermNodes(l ir.Nodes) bool {
2103 return isTermNode(s[c-1])
2106 // isTermNode reports whether the node n, the last one in a
2107 // statement list, is a terminating statement.
2108 func isTermNode(n ir.Node) bool {
2110 // NOTE: OLABEL is treated as a separate statement,
2111 // not a separate prefix, so skipping to the last statement
2112 // in the block handles the labeled statement case by
2113 // skipping over the label. No case OLABEL here.
2116 n := n.(*ir.BlockStmt)
2117 return isTermNodes(n.List)
2119 case ir.OGOTO, ir.ORETURN, ir.OTAILCALL, ir.OPANIC, ir.OFALL:
2122 case ir.OFOR, ir.OFORUNTIL:
2123 n := n.(*ir.ForStmt)
2134 return isTermNodes(n.Body) && isTermNodes(n.Else)
2137 n := n.(*ir.SwitchStmt)
2142 for _, cas := range n.Cases {
2143 if !isTermNodes(cas.Body) {
2146 if len(cas.List) == 0 { // default
2153 n := n.(*ir.SelectStmt)
2157 for _, cas := range n.Cases {
2158 if !isTermNodes(cas.Body) {
2168 // CheckUnused checks for any declared variables that weren't used.
2169 func CheckUnused(fn *ir.Func) {
2170 // Only report unused variables if we haven't seen any type-checking
2172 if base.Errors() != 0 {
2176 // Propagate the used flag for typeswitch variables up to the NONAME in its definition.
2177 for _, ln := range fn.Dcl {
2178 if ln.Op() == ir.ONAME && ln.Class == ir.PAUTO && ln.Used() {
2179 if guard, ok := ln.Defn.(*ir.TypeSwitchGuard); ok {
2185 for _, ln := range fn.Dcl {
2186 if ln.Op() != ir.ONAME || ln.Class != ir.PAUTO || ln.Used() {
2189 if defn, ok := ln.Defn.(*ir.TypeSwitchGuard); ok {
2193 base.ErrorfAt(defn.Tag.Pos(), "%v declared but not used", ln.Sym())
2194 defn.Used = true // suppress repeats
2196 base.ErrorfAt(ln.Pos(), "%v declared but not used", ln.Sym())
2201 // CheckReturn makes sure that fn terminates appropriately.
2202 func CheckReturn(fn *ir.Func) {
2203 if fn.Type() != nil && fn.Type().NumResults() != 0 && len(fn.Body) != 0 {
2205 if !isTermNodes(fn.Body) {
2206 base.ErrorfAt(fn.Endlineno, "missing return at end of function")
2211 // getIotaValue returns the current value for "iota",
2212 // or -1 if not within a ConstSpec.
2213 func getIotaValue() int64 {
2214 if i := len(typecheckdefstack); i > 0 {
2215 if x := typecheckdefstack[i-1]; x.Op() == ir.OLITERAL {
2220 if ir.CurFunc != nil && ir.CurFunc.Iota >= 0 {
2221 return ir.CurFunc.Iota
2227 // curpkg returns the current package, based on Curfn.
2228 func curpkg() *types.Pkg {
2231 // Initialization expressions for package-scope variables.
2232 return types.LocalPkg
2234 return fnpkg(fn.Nname)
2237 func Conv(n ir.Node, t *types.Type) ir.Node {
2238 if types.Identical(n.Type(), t) {
2241 n = ir.NewConvExpr(base.Pos, ir.OCONV, nil, n)
2247 // ConvNop converts node n to type t using the OCONVNOP op
2248 // and typechecks the result with ctxExpr.
2249 func ConvNop(n ir.Node, t *types.Type) ir.Node {
2250 if types.Identical(n.Type(), t) {
2253 n = ir.NewConvExpr(base.Pos, ir.OCONVNOP, nil, n)