github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/src/go/types/stmt.go (about)

     1  // Copyright 2012 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.
     4  
     5  // This file implements typechecking of statements.
     6  
     7  package types
     8  
     9  import (
    10  	"fmt"
    11  	"go/ast"
    12  	"go/constant"
    13  	"go/token"
    14  )
    15  
    16  func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt) {
    17  	if trace {
    18  		if name == "" {
    19  			name = "<function literal>"
    20  		}
    21  		fmt.Printf("--- %s: %s {\n", name, sig)
    22  		defer fmt.Println("--- <end>")
    23  	}
    24  
    25  	// set function scope extent
    26  	sig.scope.pos = body.Pos()
    27  	sig.scope.end = body.End()
    28  
    29  	// save/restore current context and setup function context
    30  	// (and use 0 indentation at function start)
    31  	defer func(ctxt context, indent int) {
    32  		check.context = ctxt
    33  		check.indent = indent
    34  	}(check.context, check.indent)
    35  	check.context = context{
    36  		decl:  decl,
    37  		scope: sig.scope,
    38  		sig:   sig,
    39  	}
    40  	check.indent = 0
    41  
    42  	check.stmtList(0, body.List)
    43  
    44  	if check.hasLabel {
    45  		check.labels(body)
    46  	}
    47  
    48  	if sig.results.Len() > 0 && !check.isTerminating(body, "") {
    49  		check.error(body.Rbrace, "missing return")
    50  	}
    51  
    52  	// spec: "Implementation restriction: A compiler may make it illegal to
    53  	// declare a variable inside a function body if the variable is never used."
    54  	// (One could check each scope after use, but that distributes this check
    55  	// over several places because CloseScope is not always called explicitly.)
    56  	check.usage(sig.scope)
    57  }
    58  
    59  func (check *Checker) usage(scope *Scope) {
    60  	for _, obj := range scope.elems {
    61  		if v, _ := obj.(*Var); v != nil && !v.used {
    62  			check.softErrorf(v.pos, "%s declared but not used", v.name)
    63  		}
    64  	}
    65  	for _, scope := range scope.children {
    66  		check.usage(scope)
    67  	}
    68  }
    69  
    70  // stmtContext is a bitset describing which
    71  // control-flow statements are permissible.
    72  type stmtContext uint
    73  
    74  const (
    75  	breakOk stmtContext = 1 << iota
    76  	continueOk
    77  	fallthroughOk
    78  )
    79  
    80  func (check *Checker) simpleStmt(s ast.Stmt) {
    81  	if s != nil {
    82  		check.stmt(0, s)
    83  	}
    84  }
    85  
    86  func trimTrailingEmptyStmts(list []ast.Stmt) []ast.Stmt {
    87  	for i := len(list); i > 0; i-- {
    88  		if _, ok := list[i-1].(*ast.EmptyStmt); !ok {
    89  			return list[:i]
    90  		}
    91  	}
    92  	return nil
    93  }
    94  
    95  func (check *Checker) stmtList(ctxt stmtContext, list []ast.Stmt) {
    96  	ok := ctxt&fallthroughOk != 0
    97  	inner := ctxt &^ fallthroughOk
    98  	list = trimTrailingEmptyStmts(list) // trailing empty statements are "invisible" to fallthrough analysis
    99  	for i, s := range list {
   100  		inner := inner
   101  		if ok && i+1 == len(list) {
   102  			inner |= fallthroughOk
   103  		}
   104  		check.stmt(inner, s)
   105  	}
   106  }
   107  
   108  func (check *Checker) multipleDefaults(list []ast.Stmt) {
   109  	var first ast.Stmt
   110  	for _, s := range list {
   111  		var d ast.Stmt
   112  		switch c := s.(type) {
   113  		case *ast.CaseClause:
   114  			if len(c.List) == 0 {
   115  				d = s
   116  			}
   117  		case *ast.CommClause:
   118  			if c.Comm == nil {
   119  				d = s
   120  			}
   121  		default:
   122  			check.invalidAST(s.Pos(), "case/communication clause expected")
   123  		}
   124  		if d != nil {
   125  			if first != nil {
   126  				check.errorf(d.Pos(), "multiple defaults (first at %s)", check.fset.Position(first.Pos()))
   127  			} else {
   128  				first = d
   129  			}
   130  		}
   131  	}
   132  }
   133  
   134  func (check *Checker) openScope(s ast.Stmt, comment string) {
   135  	scope := NewScope(check.scope, s.Pos(), s.End(), comment)
   136  	check.recordScope(s, scope)
   137  	check.scope = scope
   138  }
   139  
   140  func (check *Checker) closeScope() {
   141  	check.scope = check.scope.Parent()
   142  }
   143  
   144  func assignOp(op token.Token) token.Token {
   145  	// token_test.go verifies the token ordering this function relies on
   146  	if token.ADD_ASSIGN <= op && op <= token.AND_NOT_ASSIGN {
   147  		return op + (token.ADD - token.ADD_ASSIGN)
   148  	}
   149  	return token.ILLEGAL
   150  }
   151  
   152  func (check *Checker) suspendedCall(keyword string, call *ast.CallExpr) {
   153  	var x operand
   154  	var msg string
   155  	switch check.rawExpr(&x, call, nil) {
   156  	case conversion:
   157  		msg = "requires function call, not conversion"
   158  	case expression:
   159  		msg = "discards result of"
   160  	case statement:
   161  		return
   162  	default:
   163  		unreachable()
   164  	}
   165  	check.errorf(x.pos(), "%s %s %s", keyword, msg, &x)
   166  }
   167  
   168  // goVal returns the Go value for val, or nil.
   169  func goVal(val constant.Value) interface{} {
   170  	// val should exist, but be conservative and check
   171  	if val == nil {
   172  		return nil
   173  	}
   174  	// Match implementation restriction of other compilers.
   175  	// gc only checks duplicates for integer, floating-point
   176  	// and string values, so only create Go values for these
   177  	// types.
   178  	switch val.Kind() {
   179  	case constant.Int:
   180  		if x, ok := constant.Int64Val(val); ok {
   181  			return x
   182  		}
   183  		if x, ok := constant.Uint64Val(val); ok {
   184  			return x
   185  		}
   186  	case constant.Float:
   187  		if x, ok := constant.Float64Val(val); ok {
   188  			return x
   189  		}
   190  	case constant.String:
   191  		return constant.StringVal(val)
   192  	}
   193  	return nil
   194  }
   195  
   196  // A valueMap maps a case value (of a basic Go type) to a list of positions
   197  // where the same case value appeared, together with the corresponding case
   198  // types.
   199  // Since two case values may have the same "underlying" value but different
   200  // types we need to also check the value's types (e.g., byte(1) vs myByte(1))
   201  // when the switch expression is of interface type.
   202  type (
   203  	valueMap  map[interface{}][]valueType // underlying Go value -> valueType
   204  	valueType struct {
   205  		pos token.Pos
   206  		typ Type
   207  	}
   208  )
   209  
   210  func (check *Checker) caseValues(x *operand, values []ast.Expr, seen valueMap) {
   211  L:
   212  	for _, e := range values {
   213  		var v operand
   214  		check.expr(&v, e)
   215  		if x.mode == invalid || v.mode == invalid {
   216  			continue L
   217  		}
   218  		check.convertUntyped(&v, x.typ)
   219  		if v.mode == invalid {
   220  			continue L
   221  		}
   222  		// Order matters: By comparing v against x, error positions are at the case values.
   223  		res := v // keep original v unchanged
   224  		check.comparison(&res, x, token.EQL)
   225  		if res.mode == invalid {
   226  			continue L
   227  		}
   228  		if v.mode != constant_ {
   229  			continue L // we're done
   230  		}
   231  		// look for duplicate values
   232  		if val := goVal(v.val); val != nil {
   233  			if list := seen[val]; list != nil {
   234  				// look for duplicate types for a given value
   235  				// (quadratic algorithm, but these lists tend to be very short)
   236  				for _, vt := range list {
   237  					if Identical(v.typ, vt.typ) {
   238  						check.errorf(v.pos(), "duplicate case %s in expression switch", &v)
   239  						check.error(vt.pos, "\tprevious case") // secondary error, \t indented
   240  						continue L
   241  					}
   242  				}
   243  			}
   244  			seen[val] = append(seen[val], valueType{v.pos(), v.typ})
   245  		}
   246  	}
   247  }
   248  
   249  func (check *Checker) caseTypes(x *operand, xtyp *Interface, types []ast.Expr, seen map[Type]token.Pos) (T Type) {
   250  L:
   251  	for _, e := range types {
   252  		T = check.typOrNil(e)
   253  		if T == Typ[Invalid] {
   254  			continue L
   255  		}
   256  		// look for duplicate types
   257  		// (quadratic algorithm, but type switches tend to be reasonably small)
   258  		for t, pos := range seen {
   259  			if T == nil && t == nil || T != nil && t != nil && Identical(T, t) {
   260  				// talk about "case" rather than "type" because of nil case
   261  				Ts := "nil"
   262  				if T != nil {
   263  					Ts = T.String()
   264  				}
   265  				check.errorf(e.Pos(), "duplicate case %s in type switch", Ts)
   266  				check.error(pos, "\tprevious case") // secondary error, \t indented
   267  				continue L
   268  			}
   269  		}
   270  		seen[T] = e.Pos()
   271  		if T != nil {
   272  			check.typeAssertion(e.Pos(), x, xtyp, T)
   273  		}
   274  	}
   275  	return
   276  }
   277  
   278  // stmt typechecks statement s.
   279  func (check *Checker) stmt(ctxt stmtContext, s ast.Stmt) {
   280  	// statements cannot use iota in general
   281  	// (constant declarations set it explicitly)
   282  	assert(check.iota == nil)
   283  
   284  	// statements must end with the same top scope as they started with
   285  	if debug {
   286  		defer func(scope *Scope) {
   287  			// don't check if code is panicking
   288  			if p := recover(); p != nil {
   289  				panic(p)
   290  			}
   291  			assert(scope == check.scope)
   292  		}(check.scope)
   293  	}
   294  
   295  	inner := ctxt &^ fallthroughOk
   296  	switch s := s.(type) {
   297  	case *ast.BadStmt, *ast.EmptyStmt:
   298  		// ignore
   299  
   300  	case *ast.DeclStmt:
   301  		check.declStmt(s.Decl)
   302  
   303  	case *ast.LabeledStmt:
   304  		check.hasLabel = true
   305  		check.stmt(ctxt, s.Stmt)
   306  
   307  	case *ast.ExprStmt:
   308  		// spec: "With the exception of specific built-in functions,
   309  		// function and method calls and receive operations can appear
   310  		// in statement context. Such statements may be parenthesized."
   311  		var x operand
   312  		kind := check.rawExpr(&x, s.X, nil)
   313  		var msg string
   314  		switch x.mode {
   315  		default:
   316  			if kind == statement {
   317  				return
   318  			}
   319  			msg = "is not used"
   320  		case builtin:
   321  			msg = "must be called"
   322  		case typexpr:
   323  			msg = "is not an expression"
   324  		}
   325  		check.errorf(x.pos(), "%s %s", &x, msg)
   326  
   327  	case *ast.SendStmt:
   328  		var ch, x operand
   329  		check.expr(&ch, s.Chan)
   330  		check.expr(&x, s.Value)
   331  		if ch.mode == invalid || x.mode == invalid {
   332  			return
   333  		}
   334  
   335  		tch, ok := ch.typ.Underlying().(*Chan)
   336  		if !ok {
   337  			check.invalidOp(s.Arrow, "cannot send to non-chan type %s", ch.typ)
   338  			return
   339  		}
   340  
   341  		if tch.dir == RecvOnly {
   342  			check.invalidOp(s.Arrow, "cannot send to receive-only type %s", tch)
   343  			return
   344  		}
   345  
   346  		check.assignment(&x, tch.elem, "send")
   347  
   348  	case *ast.IncDecStmt:
   349  		var op token.Token
   350  		switch s.Tok {
   351  		case token.INC:
   352  			op = token.ADD
   353  		case token.DEC:
   354  			op = token.SUB
   355  		default:
   356  			check.invalidAST(s.TokPos, "unknown inc/dec operation %s", s.Tok)
   357  			return
   358  		}
   359  
   360  		var x operand
   361  		check.expr(&x, s.X)
   362  		if x.mode == invalid {
   363  			return
   364  		}
   365  		if !isNumeric(x.typ) {
   366  			check.invalidOp(s.X.Pos(), "%s%s (non-numeric type %s)", s.X, s.Tok, x.typ)
   367  			return
   368  		}
   369  
   370  		Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"} // use x's position
   371  		check.binary(&x, nil, s.X, Y, op)
   372  		if x.mode == invalid {
   373  			return
   374  		}
   375  		check.assignVar(s.X, &x)
   376  
   377  	case *ast.AssignStmt:
   378  		switch s.Tok {
   379  		case token.ASSIGN, token.DEFINE:
   380  			if len(s.Lhs) == 0 {
   381  				check.invalidAST(s.Pos(), "missing lhs in assignment")
   382  				return
   383  			}
   384  			if s.Tok == token.DEFINE {
   385  				check.shortVarDecl(s.TokPos, s.Lhs, s.Rhs)
   386  			} else {
   387  				// regular assignment
   388  				check.assignVars(s.Lhs, s.Rhs)
   389  			}
   390  
   391  		default:
   392  			// assignment operations
   393  			if len(s.Lhs) != 1 || len(s.Rhs) != 1 {
   394  				check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok)
   395  				return
   396  			}
   397  			op := assignOp(s.Tok)
   398  			if op == token.ILLEGAL {
   399  				check.invalidAST(s.TokPos, "unknown assignment operation %s", s.Tok)
   400  				return
   401  			}
   402  			var x operand
   403  			check.binary(&x, nil, s.Lhs[0], s.Rhs[0], op)
   404  			if x.mode == invalid {
   405  				return
   406  			}
   407  			check.assignVar(s.Lhs[0], &x)
   408  		}
   409  
   410  	case *ast.GoStmt:
   411  		check.suspendedCall("go", s.Call)
   412  
   413  	case *ast.DeferStmt:
   414  		check.suspendedCall("defer", s.Call)
   415  
   416  	case *ast.ReturnStmt:
   417  		res := check.sig.results
   418  		if res.Len() > 0 {
   419  			// function returns results
   420  			// (if one, say the first, result parameter is named, all of them are named)
   421  			if len(s.Results) == 0 && res.vars[0].name != "" {
   422  				// spec: "Implementation restriction: A compiler may disallow an empty expression
   423  				// list in a "return" statement if a different entity (constant, type, or variable)
   424  				// with the same name as a result parameter is in scope at the place of the return."
   425  				for _, obj := range res.vars {
   426  					if _, alt := check.scope.LookupParent(obj.name, check.pos); alt != nil && alt != obj {
   427  						check.errorf(s.Pos(), "result parameter %s not in scope at return", obj.name)
   428  						check.errorf(alt.Pos(), "\tinner declaration of %s", obj)
   429  						// ok to continue
   430  					}
   431  				}
   432  			} else {
   433  				// return has results or result parameters are unnamed
   434  				check.initVars(res.vars, s.Results, s.Return)
   435  			}
   436  		} else if len(s.Results) > 0 {
   437  			check.error(s.Results[0].Pos(), "no result values expected")
   438  			check.use(s.Results...)
   439  		}
   440  
   441  	case *ast.BranchStmt:
   442  		if s.Label != nil {
   443  			check.hasLabel = true
   444  			return // checked in 2nd pass (check.labels)
   445  		}
   446  		switch s.Tok {
   447  		case token.BREAK:
   448  			if ctxt&breakOk == 0 {
   449  				check.error(s.Pos(), "break not in for, switch, or select statement")
   450  			}
   451  		case token.CONTINUE:
   452  			if ctxt&continueOk == 0 {
   453  				check.error(s.Pos(), "continue not in for statement")
   454  			}
   455  		case token.FALLTHROUGH:
   456  			if ctxt&fallthroughOk == 0 {
   457  				check.error(s.Pos(), "fallthrough statement out of place")
   458  			}
   459  		default:
   460  			check.invalidAST(s.Pos(), "branch statement: %s", s.Tok)
   461  		}
   462  
   463  	case *ast.BlockStmt:
   464  		check.openScope(s, "block")
   465  		defer check.closeScope()
   466  
   467  		check.stmtList(inner, s.List)
   468  
   469  	case *ast.IfStmt:
   470  		check.openScope(s, "if")
   471  		defer check.closeScope()
   472  
   473  		check.simpleStmt(s.Init)
   474  		var x operand
   475  		check.expr(&x, s.Cond)
   476  		if x.mode != invalid && !isBoolean(x.typ) {
   477  			check.error(s.Cond.Pos(), "non-boolean condition in if statement")
   478  		}
   479  		check.stmt(inner, s.Body)
   480  		// The parser produces a correct AST but if it was modified
   481  		// elsewhere the else branch may be invalid. Check again.
   482  		switch s.Else.(type) {
   483  		case nil, *ast.BadStmt:
   484  			// valid or error already reported
   485  		case *ast.IfStmt, *ast.BlockStmt:
   486  			check.stmt(inner, s.Else)
   487  		default:
   488  			check.error(s.Else.Pos(), "invalid else branch in if statement")
   489  		}
   490  
   491  	case *ast.SwitchStmt:
   492  		inner |= breakOk
   493  		check.openScope(s, "switch")
   494  		defer check.closeScope()
   495  
   496  		check.simpleStmt(s.Init)
   497  		var x operand
   498  		if s.Tag != nil {
   499  			check.expr(&x, s.Tag)
   500  			// By checking assignment of x to an invisible temporary
   501  			// (as a compiler would), we get all the relevant checks.
   502  			check.assignment(&x, nil, "switch expression")
   503  		} else {
   504  			// spec: "A missing switch expression is
   505  			// equivalent to the boolean value true."
   506  			x.mode = constant_
   507  			x.typ = Typ[Bool]
   508  			x.val = constant.MakeBool(true)
   509  			x.expr = &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"}
   510  		}
   511  
   512  		check.multipleDefaults(s.Body.List)
   513  
   514  		seen := make(valueMap) // map of seen case values to positions and types
   515  		for i, c := range s.Body.List {
   516  			clause, _ := c.(*ast.CaseClause)
   517  			if clause == nil {
   518  				check.invalidAST(c.Pos(), "incorrect expression switch case")
   519  				continue
   520  			}
   521  			check.caseValues(&x, clause.List, seen)
   522  			check.openScope(clause, "case")
   523  			inner := inner
   524  			if i+1 < len(s.Body.List) {
   525  				inner |= fallthroughOk
   526  			}
   527  			check.stmtList(inner, clause.Body)
   528  			check.closeScope()
   529  		}
   530  
   531  	case *ast.TypeSwitchStmt:
   532  		inner |= breakOk
   533  		check.openScope(s, "type switch")
   534  		defer check.closeScope()
   535  
   536  		check.simpleStmt(s.Init)
   537  
   538  		// A type switch guard must be of the form:
   539  		//
   540  		//     TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
   541  		//
   542  		// The parser is checking syntactic correctness;
   543  		// remaining syntactic errors are considered AST errors here.
   544  		// TODO(gri) better factoring of error handling (invalid ASTs)
   545  		//
   546  		var lhs *ast.Ident // lhs identifier or nil
   547  		var rhs ast.Expr
   548  		switch guard := s.Assign.(type) {
   549  		case *ast.ExprStmt:
   550  			rhs = guard.X
   551  		case *ast.AssignStmt:
   552  			if len(guard.Lhs) != 1 || guard.Tok != token.DEFINE || len(guard.Rhs) != 1 {
   553  				check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   554  				return
   555  			}
   556  
   557  			lhs, _ = guard.Lhs[0].(*ast.Ident)
   558  			if lhs == nil {
   559  				check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   560  				return
   561  			}
   562  
   563  			if lhs.Name == "_" {
   564  				// _ := x.(type) is an invalid short variable declaration
   565  				check.softErrorf(lhs.Pos(), "no new variable on left side of :=")
   566  				lhs = nil // avoid declared but not used error below
   567  			} else {
   568  				check.recordDef(lhs, nil) // lhs variable is implicitly declared in each cause clause
   569  			}
   570  
   571  			rhs = guard.Rhs[0]
   572  
   573  		default:
   574  			check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   575  			return
   576  		}
   577  
   578  		// rhs must be of the form: expr.(type) and expr must be an interface
   579  		expr, _ := rhs.(*ast.TypeAssertExpr)
   580  		if expr == nil || expr.Type != nil {
   581  			check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   582  			return
   583  		}
   584  		var x operand
   585  		check.expr(&x, expr.X)
   586  		if x.mode == invalid {
   587  			return
   588  		}
   589  		xtyp, _ := x.typ.Underlying().(*Interface)
   590  		if xtyp == nil {
   591  			check.errorf(x.pos(), "%s is not an interface", &x)
   592  			return
   593  		}
   594  
   595  		check.multipleDefaults(s.Body.List)
   596  
   597  		var lhsVars []*Var               // list of implicitly declared lhs variables
   598  		seen := make(map[Type]token.Pos) // map of seen types to positions
   599  		for _, s := range s.Body.List {
   600  			clause, _ := s.(*ast.CaseClause)
   601  			if clause == nil {
   602  				check.invalidAST(s.Pos(), "incorrect type switch case")
   603  				continue
   604  			}
   605  			// Check each type in this type switch case.
   606  			T := check.caseTypes(&x, xtyp, clause.List, seen)
   607  			check.openScope(clause, "case")
   608  			// If lhs exists, declare a corresponding variable in the case-local scope.
   609  			if lhs != nil {
   610  				// spec: "The TypeSwitchGuard may include a short variable declaration.
   611  				// When that form is used, the variable is declared at the beginning of
   612  				// the implicit block in each clause. In clauses with a case listing
   613  				// exactly one type, the variable has that type; otherwise, the variable
   614  				// has the type of the expression in the TypeSwitchGuard."
   615  				if len(clause.List) != 1 || T == nil {
   616  					T = x.typ
   617  				}
   618  				obj := NewVar(lhs.Pos(), check.pkg, lhs.Name, T)
   619  				scopePos := clause.End()
   620  				if len(clause.Body) > 0 {
   621  					scopePos = clause.Body[0].Pos()
   622  				}
   623  				check.declare(check.scope, nil, obj, scopePos)
   624  				check.recordImplicit(clause, obj)
   625  				// For the "declared but not used" error, all lhs variables act as
   626  				// one; i.e., if any one of them is 'used', all of them are 'used'.
   627  				// Collect them for later analysis.
   628  				lhsVars = append(lhsVars, obj)
   629  			}
   630  			check.stmtList(inner, clause.Body)
   631  			check.closeScope()
   632  		}
   633  
   634  		// If lhs exists, we must have at least one lhs variable that was used.
   635  		if lhs != nil {
   636  			var used bool
   637  			for _, v := range lhsVars {
   638  				if v.used {
   639  					used = true
   640  				}
   641  				v.used = true // avoid usage error when checking entire function
   642  			}
   643  			if !used {
   644  				check.softErrorf(lhs.Pos(), "%s declared but not used", lhs.Name)
   645  			}
   646  		}
   647  
   648  	case *ast.SelectStmt:
   649  		inner |= breakOk
   650  
   651  		check.multipleDefaults(s.Body.List)
   652  
   653  		for _, s := range s.Body.List {
   654  			clause, _ := s.(*ast.CommClause)
   655  			if clause == nil {
   656  				continue // error reported before
   657  			}
   658  
   659  			// clause.Comm must be a SendStmt, RecvStmt, or default case
   660  			valid := false
   661  			var rhs ast.Expr // rhs of RecvStmt, or nil
   662  			switch s := clause.Comm.(type) {
   663  			case nil, *ast.SendStmt:
   664  				valid = true
   665  			case *ast.AssignStmt:
   666  				if len(s.Rhs) == 1 {
   667  					rhs = s.Rhs[0]
   668  				}
   669  			case *ast.ExprStmt:
   670  				rhs = s.X
   671  			}
   672  
   673  			// if present, rhs must be a receive operation
   674  			if rhs != nil {
   675  				if x, _ := unparen(rhs).(*ast.UnaryExpr); x != nil && x.Op == token.ARROW {
   676  					valid = true
   677  				}
   678  			}
   679  
   680  			if !valid {
   681  				check.error(clause.Comm.Pos(), "select case must be send or receive (possibly with assignment)")
   682  				continue
   683  			}
   684  
   685  			check.openScope(s, "case")
   686  			if clause.Comm != nil {
   687  				check.stmt(inner, clause.Comm)
   688  			}
   689  			check.stmtList(inner, clause.Body)
   690  			check.closeScope()
   691  		}
   692  
   693  	case *ast.ForStmt:
   694  		inner |= breakOk | continueOk
   695  		check.openScope(s, "for")
   696  		defer check.closeScope()
   697  
   698  		check.simpleStmt(s.Init)
   699  		if s.Cond != nil {
   700  			var x operand
   701  			check.expr(&x, s.Cond)
   702  			if x.mode != invalid && !isBoolean(x.typ) {
   703  				check.error(s.Cond.Pos(), "non-boolean condition in for statement")
   704  			}
   705  		}
   706  		check.simpleStmt(s.Post)
   707  		// spec: "The init statement may be a short variable
   708  		// declaration, but the post statement must not."
   709  		if s, _ := s.Post.(*ast.AssignStmt); s != nil && s.Tok == token.DEFINE {
   710  			check.softErrorf(s.Pos(), "cannot declare in post statement")
   711  			check.use(s.Lhs...) // avoid follow-up errors
   712  		}
   713  		check.stmt(inner, s.Body)
   714  
   715  	case *ast.RangeStmt:
   716  		inner |= breakOk | continueOk
   717  		check.openScope(s, "for")
   718  		defer check.closeScope()
   719  
   720  		// check expression to iterate over
   721  		var x operand
   722  		check.expr(&x, s.X)
   723  
   724  		// determine key/value types
   725  		var key, val Type
   726  		if x.mode != invalid {
   727  			switch typ := x.typ.Underlying().(type) {
   728  			case *Basic:
   729  				if isString(typ) {
   730  					key = Typ[Int]
   731  					val = universeRune // use 'rune' name
   732  				}
   733  			case *Array:
   734  				key = Typ[Int]
   735  				val = typ.elem
   736  			case *Slice:
   737  				key = Typ[Int]
   738  				val = typ.elem
   739  			case *Pointer:
   740  				if typ, _ := typ.base.Underlying().(*Array); typ != nil {
   741  					key = Typ[Int]
   742  					val = typ.elem
   743  				}
   744  			case *Map:
   745  				key = typ.key
   746  				val = typ.elem
   747  			case *Chan:
   748  				key = typ.elem
   749  				val = Typ[Invalid]
   750  				if typ.dir == SendOnly {
   751  					check.errorf(x.pos(), "cannot range over send-only channel %s", &x)
   752  					// ok to continue
   753  				}
   754  				if s.Value != nil {
   755  					check.errorf(s.Value.Pos(), "iteration over %s permits only one iteration variable", &x)
   756  					// ok to continue
   757  				}
   758  			}
   759  		}
   760  
   761  		if key == nil {
   762  			check.errorf(x.pos(), "cannot range over %s", &x)
   763  			// ok to continue
   764  		}
   765  
   766  		// check assignment to/declaration of iteration variables
   767  		// (irregular assignment, cannot easily map to existing assignment checks)
   768  
   769  		// lhs expressions and initialization value (rhs) types
   770  		lhs := [2]ast.Expr{s.Key, s.Value}
   771  		rhs := [2]Type{key, val} // key, val may be nil
   772  
   773  		if s.Tok == token.DEFINE {
   774  			// short variable declaration; variable scope starts after the range clause
   775  			// (the for loop opens a new scope, so variables on the lhs never redeclare
   776  			// previously declared variables)
   777  			var vars []*Var
   778  			for i, lhs := range lhs {
   779  				if lhs == nil {
   780  					continue
   781  				}
   782  
   783  				// determine lhs variable
   784  				var obj *Var
   785  				if ident, _ := lhs.(*ast.Ident); ident != nil {
   786  					// declare new variable
   787  					name := ident.Name
   788  					obj = NewVar(ident.Pos(), check.pkg, name, nil)
   789  					check.recordDef(ident, obj)
   790  					// _ variables don't count as new variables
   791  					if name != "_" {
   792  						vars = append(vars, obj)
   793  					}
   794  				} else {
   795  					check.errorf(lhs.Pos(), "cannot declare %s", lhs)
   796  					obj = NewVar(lhs.Pos(), check.pkg, "_", nil) // dummy variable
   797  				}
   798  
   799  				// initialize lhs variable
   800  				if typ := rhs[i]; typ != nil {
   801  					x.mode = value
   802  					x.expr = lhs // we don't have a better rhs expression to use here
   803  					x.typ = typ
   804  					check.initVar(obj, &x, "range clause")
   805  				} else {
   806  					obj.typ = Typ[Invalid]
   807  					obj.used = true // don't complain about unused variable
   808  				}
   809  			}
   810  
   811  			// declare variables
   812  			if len(vars) > 0 {
   813  				for _, obj := range vars {
   814  					// spec: "The scope of a constant or variable identifier declared inside
   815  					// a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl
   816  					// for short variable declarations) and ends at the end of the innermost
   817  					// containing block."
   818  					scopePos := s.End()
   819  					check.declare(check.scope, nil /* recordDef already called */, obj, scopePos)
   820  				}
   821  			} else {
   822  				check.error(s.TokPos, "no new variables on left side of :=")
   823  			}
   824  		} else {
   825  			// ordinary assignment
   826  			for i, lhs := range lhs {
   827  				if lhs == nil {
   828  					continue
   829  				}
   830  				if typ := rhs[i]; typ != nil {
   831  					x.mode = value
   832  					x.expr = lhs // we don't have a better rhs expression to use here
   833  					x.typ = typ
   834  					check.assignVar(lhs, &x)
   835  				}
   836  			}
   837  		}
   838  
   839  		check.stmt(inner, s.Body)
   840  
   841  	default:
   842  		check.error(s.Pos(), "invalid statement")
   843  	}
   844  }