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