Source file src/go/types/stmt.go

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

View as plain text