github.com/aloncn/graphics-go@v0.0.1/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  		// The parser produces a correct AST but if it was modified
   461  		// elsewhere the else branch may be invalid. Check again.
   462  		switch s.Else.(type) {
   463  		case nil, *ast.BadStmt:
   464  			// valid or error already reported
   465  		case *ast.IfStmt, *ast.BlockStmt:
   466  			check.stmt(inner, s.Else)
   467  		default:
   468  			check.error(s.Else.Pos(), "invalid else branch in if statement")
   469  		}
   470  
   471  	case *ast.SwitchStmt:
   472  		inner |= breakOk
   473  		check.openScope(s, "switch")
   474  		defer check.closeScope()
   475  
   476  		check.simpleStmt(s.Init)
   477  		var x operand
   478  		if s.Tag != nil {
   479  			check.expr(&x, s.Tag)
   480  			// By checking assignment of x to an invisible temporary
   481  			// (as a compiler would), we get all the relevant checks.
   482  			check.assignment(&x, nil, "switch expression")
   483  		} else {
   484  			// spec: "A missing switch expression is
   485  			// equivalent to the boolean value true."
   486  			x.mode = constant_
   487  			x.typ = Typ[Bool]
   488  			x.val = constant.MakeBool(true)
   489  			x.expr = &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"}
   490  		}
   491  
   492  		check.multipleDefaults(s.Body.List)
   493  
   494  		seen := make(valueMap) // map of seen case values to positions and types
   495  		for i, c := range s.Body.List {
   496  			clause, _ := c.(*ast.CaseClause)
   497  			if clause == nil {
   498  				check.invalidAST(c.Pos(), "incorrect expression switch case")
   499  				continue
   500  			}
   501  			check.caseValues(&x, clause.List, seen)
   502  			check.openScope(clause, "case")
   503  			inner := inner
   504  			if i+1 < len(s.Body.List) {
   505  				inner |= fallthroughOk
   506  			}
   507  			check.stmtList(inner, clause.Body)
   508  			check.closeScope()
   509  		}
   510  
   511  	case *ast.TypeSwitchStmt:
   512  		inner |= breakOk
   513  		check.openScope(s, "type switch")
   514  		defer check.closeScope()
   515  
   516  		check.simpleStmt(s.Init)
   517  
   518  		// A type switch guard must be of the form:
   519  		//
   520  		//     TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
   521  		//
   522  		// The parser is checking syntactic correctness;
   523  		// remaining syntactic errors are considered AST errors here.
   524  		// TODO(gri) better factoring of error handling (invalid ASTs)
   525  		//
   526  		var lhs *ast.Ident // lhs identifier or nil
   527  		var rhs ast.Expr
   528  		switch guard := s.Assign.(type) {
   529  		case *ast.ExprStmt:
   530  			rhs = guard.X
   531  		case *ast.AssignStmt:
   532  			if len(guard.Lhs) != 1 || guard.Tok != token.DEFINE || len(guard.Rhs) != 1 {
   533  				check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   534  				return
   535  			}
   536  
   537  			lhs, _ = guard.Lhs[0].(*ast.Ident)
   538  			if lhs == nil {
   539  				check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   540  				return
   541  			}
   542  
   543  			if lhs.Name == "_" {
   544  				// _ := x.(type) is an invalid short variable declaration
   545  				check.softErrorf(lhs.Pos(), "no new variable on left side of :=")
   546  				lhs = nil // avoid declared but not used error below
   547  			} else {
   548  				check.recordDef(lhs, nil) // lhs variable is implicitly declared in each cause clause
   549  			}
   550  
   551  			rhs = guard.Rhs[0]
   552  
   553  		default:
   554  			check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   555  			return
   556  		}
   557  
   558  		// rhs must be of the form: expr.(type) and expr must be an interface
   559  		expr, _ := rhs.(*ast.TypeAssertExpr)
   560  		if expr == nil || expr.Type != nil {
   561  			check.invalidAST(s.Pos(), "incorrect form of type switch guard")
   562  			return
   563  		}
   564  		var x operand
   565  		check.expr(&x, expr.X)
   566  		if x.mode == invalid {
   567  			return
   568  		}
   569  		xtyp, _ := x.typ.Underlying().(*Interface)
   570  		if xtyp == nil {
   571  			check.errorf(x.pos(), "%s is not an interface", &x)
   572  			return
   573  		}
   574  
   575  		check.multipleDefaults(s.Body.List)
   576  
   577  		var lhsVars []*Var               // list of implicitly declared lhs variables
   578  		seen := make(map[Type]token.Pos) // map of seen types to positions
   579  		for _, s := range s.Body.List {
   580  			clause, _ := s.(*ast.CaseClause)
   581  			if clause == nil {
   582  				check.invalidAST(s.Pos(), "incorrect type switch case")
   583  				continue
   584  			}
   585  			// Check each type in this type switch case.
   586  			T := check.caseTypes(&x, xtyp, clause.List, seen)
   587  			check.openScope(clause, "case")
   588  			// If lhs exists, declare a corresponding variable in the case-local scope.
   589  			if lhs != nil {
   590  				// spec: "The TypeSwitchGuard may include a short variable declaration.
   591  				// When that form is used, the variable is declared at the beginning of
   592  				// the implicit block in each clause. In clauses with a case listing
   593  				// exactly one type, the variable has that type; otherwise, the variable
   594  				// has the type of the expression in the TypeSwitchGuard."
   595  				if len(clause.List) != 1 || T == nil {
   596  					T = x.typ
   597  				}
   598  				obj := NewVar(lhs.Pos(), check.pkg, lhs.Name, T)
   599  				scopePos := clause.End()
   600  				if len(clause.Body) > 0 {
   601  					scopePos = clause.Body[0].Pos()
   602  				}
   603  				check.declare(check.scope, nil, obj, scopePos)
   604  				check.recordImplicit(clause, obj)
   605  				// For the "declared but not used" error, all lhs variables act as
   606  				// one; i.e., if any one of them is 'used', all of them are 'used'.
   607  				// Collect them for later analysis.
   608  				lhsVars = append(lhsVars, obj)
   609  			}
   610  			check.stmtList(inner, clause.Body)
   611  			check.closeScope()
   612  		}
   613  
   614  		// If lhs exists, we must have at least one lhs variable that was used.
   615  		if lhs != nil {
   616  			var used bool
   617  			for _, v := range lhsVars {
   618  				if v.used {
   619  					used = true
   620  				}
   621  				v.used = true // avoid usage error when checking entire function
   622  			}
   623  			if !used {
   624  				check.softErrorf(lhs.Pos(), "%s declared but not used", lhs.Name)
   625  			}
   626  		}
   627  
   628  	case *ast.SelectStmt:
   629  		inner |= breakOk
   630  
   631  		check.multipleDefaults(s.Body.List)
   632  
   633  		for _, s := range s.Body.List {
   634  			clause, _ := s.(*ast.CommClause)
   635  			if clause == nil {
   636  				continue // error reported before
   637  			}
   638  
   639  			// clause.Comm must be a SendStmt, RecvStmt, or default case
   640  			valid := false
   641  			var rhs ast.Expr // rhs of RecvStmt, or nil
   642  			switch s := clause.Comm.(type) {
   643  			case nil, *ast.SendStmt:
   644  				valid = true
   645  			case *ast.AssignStmt:
   646  				if len(s.Rhs) == 1 {
   647  					rhs = s.Rhs[0]
   648  				}
   649  			case *ast.ExprStmt:
   650  				rhs = s.X
   651  			}
   652  
   653  			// if present, rhs must be a receive operation
   654  			if rhs != nil {
   655  				if x, _ := unparen(rhs).(*ast.UnaryExpr); x != nil && x.Op == token.ARROW {
   656  					valid = true
   657  				}
   658  			}
   659  
   660  			if !valid {
   661  				check.error(clause.Comm.Pos(), "select case must be send or receive (possibly with assignment)")
   662  				continue
   663  			}
   664  
   665  			check.openScope(s, "case")
   666  			if clause.Comm != nil {
   667  				check.stmt(inner, clause.Comm)
   668  			}
   669  			check.stmtList(inner, clause.Body)
   670  			check.closeScope()
   671  		}
   672  
   673  	case *ast.ForStmt:
   674  		inner |= breakOk | continueOk
   675  		check.openScope(s, "for")
   676  		defer check.closeScope()
   677  
   678  		check.simpleStmt(s.Init)
   679  		if s.Cond != nil {
   680  			var x operand
   681  			check.expr(&x, s.Cond)
   682  			if x.mode != invalid && !isBoolean(x.typ) {
   683  				check.error(s.Cond.Pos(), "non-boolean condition in for statement")
   684  			}
   685  		}
   686  		check.simpleStmt(s.Post)
   687  		// spec: "The init statement may be a short variable
   688  		// declaration, but the post statement must not."
   689  		if s, _ := s.Post.(*ast.AssignStmt); s != nil && s.Tok == token.DEFINE {
   690  			check.softErrorf(s.Pos(), "cannot declare in post statement")
   691  			check.use(s.Lhs...) // avoid follow-up errors
   692  		}
   693  		check.stmt(inner, s.Body)
   694  
   695  	case *ast.RangeStmt:
   696  		inner |= breakOk | continueOk
   697  		check.openScope(s, "for")
   698  		defer check.closeScope()
   699  
   700  		// check expression to iterate over
   701  		var x operand
   702  		check.expr(&x, s.X)
   703  
   704  		// determine key/value types
   705  		var key, val Type
   706  		if x.mode != invalid {
   707  			switch typ := x.typ.Underlying().(type) {
   708  			case *Basic:
   709  				if isString(typ) {
   710  					key = Typ[Int]
   711  					val = universeRune // use 'rune' name
   712  				}
   713  			case *Array:
   714  				key = Typ[Int]
   715  				val = typ.elem
   716  			case *Slice:
   717  				key = Typ[Int]
   718  				val = typ.elem
   719  			case *Pointer:
   720  				if typ, _ := typ.base.Underlying().(*Array); typ != nil {
   721  					key = Typ[Int]
   722  					val = typ.elem
   723  				}
   724  			case *Map:
   725  				key = typ.key
   726  				val = typ.elem
   727  			case *Chan:
   728  				key = typ.elem
   729  				val = Typ[Invalid]
   730  				if typ.dir == SendOnly {
   731  					check.errorf(x.pos(), "cannot range over send-only channel %s", &x)
   732  					// ok to continue
   733  				}
   734  				if s.Value != nil {
   735  					check.errorf(s.Value.Pos(), "iteration over %s permits only one iteration variable", &x)
   736  					// ok to continue
   737  				}
   738  			}
   739  		}
   740  
   741  		if key == nil {
   742  			check.errorf(x.pos(), "cannot range over %s", &x)
   743  			// ok to continue
   744  		}
   745  
   746  		// check assignment to/declaration of iteration variables
   747  		// (irregular assignment, cannot easily map to existing assignment checks)
   748  
   749  		// lhs expressions and initialization value (rhs) types
   750  		lhs := [2]ast.Expr{s.Key, s.Value}
   751  		rhs := [2]Type{key, val} // key, val may be nil
   752  
   753  		if s.Tok == token.DEFINE {
   754  			// short variable declaration; variable scope starts after the range clause
   755  			// (the for loop opens a new scope, so variables on the lhs never redeclare
   756  			// previously declared variables)
   757  			var vars []*Var
   758  			for i, lhs := range lhs {
   759  				if lhs == nil {
   760  					continue
   761  				}
   762  
   763  				// determine lhs variable
   764  				var obj *Var
   765  				if ident, _ := lhs.(*ast.Ident); ident != nil {
   766  					// declare new variable
   767  					name := ident.Name
   768  					obj = NewVar(ident.Pos(), check.pkg, name, nil)
   769  					check.recordDef(ident, obj)
   770  					// _ variables don't count as new variables
   771  					if name != "_" {
   772  						vars = append(vars, obj)
   773  					}
   774  				} else {
   775  					check.errorf(lhs.Pos(), "cannot declare %s", lhs)
   776  					obj = NewVar(lhs.Pos(), check.pkg, "_", nil) // dummy variable
   777  				}
   778  
   779  				// initialize lhs variable
   780  				if typ := rhs[i]; typ != nil {
   781  					x.mode = value
   782  					x.expr = lhs // we don't have a better rhs expression to use here
   783  					x.typ = typ
   784  					check.initVar(obj, &x, "range clause")
   785  				} else {
   786  					obj.typ = Typ[Invalid]
   787  					obj.used = true // don't complain about unused variable
   788  				}
   789  			}
   790  
   791  			// declare variables
   792  			if len(vars) > 0 {
   793  				for _, obj := range vars {
   794  					// spec: "The scope of a constant or variable identifier declared inside
   795  					// a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl
   796  					// for short variable declarations) and ends at the end of the innermost
   797  					// containing block."
   798  					scopePos := s.End()
   799  					check.declare(check.scope, nil /* recordDef already called */, obj, scopePos)
   800  				}
   801  			} else {
   802  				check.error(s.TokPos, "no new variables on left side of :=")
   803  			}
   804  		} else {
   805  			// ordinary assignment
   806  			for i, lhs := range lhs {
   807  				if lhs == nil {
   808  					continue
   809  				}
   810  				if typ := rhs[i]; typ != nil {
   811  					x.mode = value
   812  					x.expr = lhs // we don't have a better rhs expression to use here
   813  					x.typ = typ
   814  					check.assignVar(lhs, &x)
   815  				}
   816  			}
   817  		}
   818  
   819  		check.stmt(inner, s.Body)
   820  
   821  	default:
   822  		check.error(s.Pos(), "invalid statement")
   823  	}
   824  }