Source file src/go/types/range.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/range.go
     3  
     4  // Copyright 2025 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // This file implements typechecking of range statements.
     9  
    10  package types
    11  
    12  import (
    13  	"go/ast"
    14  	"go/constant"
    15  	. "internal/types/errors"
    16  )
    17  
    18  // rangeStmt type-checks a range statement of form
    19  //
    20  //	for sKey, sValue = range rangeVar { ... }
    21  //
    22  // where sKey, sValue, sExtra may be nil. isDef indicates whether these
    23  // variables are assigned to only (=) or whether there is a short variable
    24  // declaration (:=). If the latter and there are no variables, an error is
    25  // reported at noNewVarPos.
    26  func (check *Checker) rangeStmt(inner stmtContext, rangeStmt *ast.RangeStmt, noNewVarPos positioner, sKey, sValue, sExtra, rangeVar ast.Expr, isDef bool) {
    27  	// check expression to iterate over
    28  	var x operand
    29  
    30  	// From the spec:
    31  	//   If the last iteration variable is the blank identifier, the range
    32  	//   clause is equivalent to the same clause without that identifier.
    33  	//
    34  	//   The range expression x is evaluated before beginning the loop,
    35  	//   with one exception: if at most one iteration variable is present
    36  	//   and x or len(x) is constant, the range expression is not evaluated.
    37  	// So we have to be careful not to evaluate the arg in the
    38  	// described situation, and a blank sValue must not count as present.
    39  
    40  	check.hasCallOrRecv = false
    41  	check.expr(nil, &x, rangeVar)
    42  
    43  	ident, _ := ast.Unparen(sValue).(*ast.Ident)
    44  	noValue := sValue == nil || ident != nil && ident.Name == "_"
    45  
    46  	if isTypes2 && x.isValid() && noValue && !check.hasCallOrRecv {
    47  		if t, ok := arrayPtrDeref(x.typ().Underlying()).(*Array); ok {
    48  			for {
    49  				// Put constant info on the thing inside parentheses.
    50  				// That's where (*../noder/writer).expr expects it.
    51  				// See issue 73476.
    52  				p, ok := rangeVar.(*ast.ParenExpr)
    53  				if !ok {
    54  					break
    55  				}
    56  				rangeVar = p.X
    57  			}
    58  			// Override type of rangeVar to be a constant
    59  			// (and thus side-effects will not be computed
    60  			// by the backend).
    61  			check.record(&operand{
    62  				mode_: constant_,
    63  				expr:  rangeVar,
    64  				typ_:  Typ[Int],
    65  				val:   constant.MakeInt64(t.len),
    66  				id:    x.id,
    67  			})
    68  		}
    69  	}
    70  
    71  	// determine key/value types
    72  	var key, val Type
    73  	if x.isValid() {
    74  		k, v, cause, ok := rangeKeyVal(check, x.typ(), func(v goVersion) bool {
    75  			return check.allowVersion(v)
    76  		})
    77  		switch {
    78  		case !ok && cause != "":
    79  			check.softErrorf(&x, InvalidRangeExpr, "cannot range over %s: %s", &x, cause)
    80  		case !ok:
    81  			check.softErrorf(&x, InvalidRangeExpr, "cannot range over %s", &x)
    82  		case k == nil && sKey != nil:
    83  			check.softErrorf(sKey, InvalidIterVar, "range over %s permits no iteration variables", &x)
    84  		case v == nil && sValue != nil:
    85  			check.softErrorf(sValue, InvalidIterVar, "range over %s permits only one iteration variable", &x)
    86  		case sExtra != nil:
    87  			check.softErrorf(sExtra, InvalidIterVar, "range clause permits at most two iteration variables")
    88  		}
    89  		key, val = k, v
    90  	}
    91  
    92  	// Open the for-statement block scope now, after the range clause.
    93  	// Iteration variables declared with := need to go in this scope (was go.dev/issue/51437).
    94  	check.openScope(rangeStmt, "range")
    95  	defer check.closeScope()
    96  
    97  	// check assignment to/declaration of iteration variables
    98  	// (irregular assignment, cannot easily map to existing assignment checks)
    99  
   100  	// lhs expressions and initialization value (rhs) types
   101  	lhs := [2]ast.Expr{sKey, sValue} // sKey, sValue may be nil
   102  	rhs := [2]Type{key, val}         // key, val may be nil
   103  
   104  	rangeOverInt := isInteger(x.typ())
   105  
   106  	if isDef {
   107  		// short variable declaration
   108  		var vars []*Var
   109  		for i, lhs := range lhs {
   110  			if lhs == nil {
   111  				continue
   112  			}
   113  
   114  			// determine lhs variable
   115  			var obj *Var
   116  			if ident, _ := lhs.(*ast.Ident); ident != nil {
   117  				// declare new variable
   118  				name := ident.Name
   119  				obj = newVar(LocalVar, ident.Pos(), check.pkg, name, nil)
   120  				check.recordDef(ident, obj)
   121  				// _ variables don't count as new variables
   122  				if name != "_" {
   123  					vars = append(vars, obj)
   124  				}
   125  			} else {
   126  				check.errorf(lhs, InvalidSyntaxTree, "cannot declare %s", lhs)
   127  				check.useLHS(lhs)
   128  				obj = newVar(LocalVar, lhs.Pos(), check.pkg, "_", nil) // dummy variable
   129  			}
   130  			assert(obj.typ == nil)
   131  
   132  			// initialize lhs iteration variable, if any
   133  			typ := rhs[i]
   134  			if typ == nil || typ == Typ[Invalid] {
   135  				// typ == Typ[Invalid] can happen if allowVersion fails.
   136  				obj.typ = Typ[Invalid]
   137  				check.usedVars[obj] = true // don't complain about unused variable
   138  				continue
   139  			}
   140  
   141  			if rangeOverInt {
   142  				assert(i == 0) // at most one iteration variable (rhs[1] == nil or Typ[Invalid] for rangeOverInt)
   143  				check.initVar(obj, &x, "range clause")
   144  			} else {
   145  				var y operand
   146  				y.mode_ = value
   147  				y.expr = lhs // we don't have a better rhs expression to use here
   148  				y.typ_ = typ
   149  				check.initVar(obj, &y, "assignment") // error is on variable, use "assignment" not "range clause"
   150  			}
   151  			assert(obj.typ != nil)
   152  		}
   153  
   154  		// declare variables
   155  		if len(vars) > 0 {
   156  			scopePos := rangeStmt.Body.Pos()
   157  			for _, obj := range vars {
   158  				check.declare(check.scope, nil /* recordDef already called */, obj, scopePos)
   159  			}
   160  		} else {
   161  			check.error(noNewVarPos, NoNewVar, "no new variables on left side of :=")
   162  		}
   163  	} else if sKey != nil /* lhs[0] != nil */ {
   164  		// ordinary assignment
   165  		for i, lhs := range lhs {
   166  			if lhs == nil {
   167  				continue
   168  			}
   169  
   170  			// assign to lhs iteration variable, if any
   171  			typ := rhs[i]
   172  			if typ == nil || typ == Typ[Invalid] {
   173  				check.useLHS(lhs)
   174  				continue
   175  			}
   176  
   177  			if rangeOverInt {
   178  				assert(i == 0) // at most one iteration variable (rhs[1] == nil or Typ[Invalid] for rangeOverInt)
   179  				check.assignVar(lhs, nil, &x, "range clause")
   180  				// If the assignment succeeded, if x was untyped before, it now
   181  				// has a type inferred via the assignment. It must be an integer.
   182  				// (go.dev/issues/67027)
   183  				if x.isValid() && !isInteger(x.typ()) {
   184  					check.softErrorf(lhs, InvalidRangeExpr, "cannot use iteration variable of type %s", x.typ())
   185  				}
   186  			} else {
   187  				var y operand
   188  				y.mode_ = value
   189  				y.expr = lhs // we don't have a better rhs expression to use here
   190  				y.typ_ = typ
   191  				check.assignVar(lhs, nil, &y, "assignment") // error is on variable, use "assignment" not "range clause"
   192  			}
   193  		}
   194  	} else if rangeOverInt {
   195  		// If we don't have any iteration variables, we still need to
   196  		// check that a (possibly untyped) integer range expression x
   197  		// is valid.
   198  		// We do this by checking the assignment _ = x. This ensures
   199  		// that an untyped x can be converted to a value of its default
   200  		// type (rune or int).
   201  		check.assignment(&x, nil, "range clause")
   202  	}
   203  
   204  	check.stmt(inner, rangeStmt.Body)
   205  }
   206  
   207  // rangeKeyVal returns the key and value type produced by a range clause
   208  // over an expression of type orig.
   209  // If allowVersion != nil, it is used to check the required language version.
   210  // If the range clause is not permitted, rangeKeyVal returns ok = false.
   211  // When ok = false, rangeKeyVal may also return a reason in cause.
   212  // The check parameter is only used in case of an error; it may be nil.
   213  func rangeKeyVal(check *Checker, orig Type, allowVersion func(goVersion) bool) (key, val Type, cause string, ok bool) {
   214  	bad := func(cause string) (Type, Type, string, bool) {
   215  		return Typ[Invalid], Typ[Invalid], cause, false
   216  	}
   217  
   218  	rtyp, err := commonUnder(orig, func(t, u Type) *typeError {
   219  		// A channel must permit receive operations.
   220  		if ch, _ := u.(*Chan); ch != nil && ch.dir == SendOnly {
   221  			return typeErrorf("receive from send-only channel %s", t)
   222  		}
   223  		return nil
   224  	})
   225  	if rtyp == nil {
   226  		return bad(err.format(check))
   227  	}
   228  
   229  	switch typ := arrayPtrDeref(rtyp).(type) {
   230  	case *Basic:
   231  		if isString(typ) {
   232  			return Typ[Int], universeRune, "", true // use 'rune' name
   233  		}
   234  		if isInteger(typ) {
   235  			if allowVersion != nil && !allowVersion(go1_22) {
   236  				return bad("requires go1.22 or later")
   237  			}
   238  			return orig, nil, "", true
   239  		}
   240  	case *Array:
   241  		return Typ[Int], typ.elem, "", true
   242  	case *Slice:
   243  		return Typ[Int], typ.elem, "", true
   244  	case *Map:
   245  		return typ.key, typ.elem, "", true
   246  	case *Chan:
   247  		assert(typ.dir != SendOnly)
   248  		return typ.elem, nil, "", true
   249  	case *Signature:
   250  		if allowVersion != nil && !allowVersion(go1_23) {
   251  			return bad("requires go1.23 or later")
   252  		}
   253  		// check iterator arity
   254  		// TODO(gri) error messages could be less verbose (consider rangeStmt error and cause returned here)
   255  		switch {
   256  		case typ.Params().Len() != 1:
   257  			return bad("func must be func(yield func(...) bool): wrong argument count")
   258  		case typ.Results().Len() != 0:
   259  			return bad("func must be func(yield func(...) bool): unexpected results")
   260  		}
   261  		assert(typ.Recv() == nil)
   262  		// check iterator argument type
   263  		u, err := commonUnder(typ.Params().At(0).Type(), nil)
   264  		cb, _ := u.(*Signature)
   265  		switch {
   266  		case cb == nil:
   267  			if err != nil {
   268  				return bad(check.sprintf("func must be func(yield func(...) bool): in yield type, %s", err.format(check)))
   269  			} else {
   270  				return bad("func must be func(yield func(...) bool): argument is not func")
   271  			}
   272  		case cb.Params().Len() > 2:
   273  			return bad("func must be func(yield func(...) bool): yield func has too many parameters")
   274  		case cb.Results().Len() != 1 || !Identical(cb.Results().At(0).Type(), universeBool):
   275  			// see go.dev/issues/71131, go.dev/issues/71164
   276  			if cb.Results().Len() == 1 && isBoolean(cb.Results().At(0).Type()) {
   277  				return bad("func must be func(yield func(...) bool): yield func returns user-defined boolean, not bool")
   278  			} else {
   279  				return bad("func must be func(yield func(...) bool): yield func does not return bool")
   280  			}
   281  		case cb.Variadic():
   282  			return bad(check.sprintf("yield func of type %s cannot be variadic", cb))
   283  		}
   284  		assert(cb.Recv() == nil)
   285  		// determine key and value types, if any
   286  		if cb.Params().Len() >= 1 {
   287  			key = cb.Params().At(0).Type()
   288  		}
   289  		if cb.Params().Len() >= 2 {
   290  			val = cb.Params().At(1).Type()
   291  		}
   292  		return key, val, "", true
   293  	}
   294  	return
   295  }
   296  

View as plain text