Source file
src/go/types/range.go
1
2
3
4
5
6
7
8
9
10 package types
11
12 import (
13 "go/ast"
14 "go/constant"
15 . "internal/types/errors"
16 )
17
18
19
20
21
22
23
24
25
26 func (check *Checker) rangeStmt(inner stmtContext, rangeStmt *ast.RangeStmt, noNewVarPos positioner, sKey, sValue, sExtra, rangeVar ast.Expr, isDef bool) {
27
28 var x operand
29
30
31
32
33
34
35
36
37
38
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
50
51
52 p, ok := rangeVar.(*ast.ParenExpr)
53 if !ok {
54 break
55 }
56 rangeVar = p.X
57 }
58
59
60
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
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
93
94 check.openScope(rangeStmt, "range")
95 defer check.closeScope()
96
97
98
99
100
101 lhs := [2]ast.Expr{sKey, sValue}
102 rhs := [2]Type{key, val}
103
104 rangeOverInt := isInteger(x.typ())
105
106 if isDef {
107
108 var vars []*Var
109 for i, lhs := range lhs {
110 if lhs == nil {
111 continue
112 }
113
114
115 var obj *Var
116 if ident, _ := lhs.(*ast.Ident); ident != nil {
117
118 name := ident.Name
119 obj = newVar(LocalVar, ident.Pos(), check.pkg, name, nil)
120 check.recordDef(ident, obj)
121
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)
129 }
130 assert(obj.typ == nil)
131
132
133 typ := rhs[i]
134 if typ == nil || typ == Typ[Invalid] {
135
136 obj.typ = Typ[Invalid]
137 check.usedVars[obj] = true
138 continue
139 }
140
141 if rangeOverInt {
142 assert(i == 0)
143 check.initVar(obj, &x, "range clause")
144 } else {
145 var y operand
146 y.mode_ = value
147 y.expr = lhs
148 y.typ_ = typ
149 check.initVar(obj, &y, "assignment")
150 }
151 assert(obj.typ != nil)
152 }
153
154
155 if len(vars) > 0 {
156 scopePos := rangeStmt.Body.Pos()
157 for _, obj := range vars {
158 check.declare(check.scope, nil , obj, scopePos)
159 }
160 } else {
161 check.error(noNewVarPos, NoNewVar, "no new variables on left side of :=")
162 }
163 } else if sKey != nil {
164
165 for i, lhs := range lhs {
166 if lhs == nil {
167 continue
168 }
169
170
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)
179 check.assignVar(lhs, nil, &x, "range clause")
180
181
182
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
190 y.typ_ = typ
191 check.assignVar(lhs, nil, &y, "assignment")
192 }
193 }
194 } else if rangeOverInt {
195
196
197
198
199
200
201 check.assignment(&x, nil, "range clause")
202 }
203
204 check.stmt(inner, rangeStmt.Body)
205 }
206
207
208
209
210
211
212
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
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
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
254
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
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
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
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