forked from cosmos72/gomacro
/
range.go
368 lines (324 loc) · 8.61 KB
/
range.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
* gomacro - A Go interpreter with Lisp-like macros
*
* Copyright (C) 2017-2019 Massimiliano Ghilardi
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*
* range.go
*
* Created on Jun 04, 2017
* Author Massimiliano Ghilardi
*/
package fast
import (
"go/ast"
"go/token"
r "reflect"
"sort"
"unicode/utf8"
"unsafe"
xr "github.com/lifepod-solutions/gomacro/xreflect"
)
type rangeJump struct {
Start, Continue, Break int
}
// Range compiles a "for-range" statement
func (c *Comp) Range(node *ast.RangeStmt, labels []string) {
var nbinds [2]int
flag := true // node.Tok == token.DEFINE || (node.Body != nil && containLocalBinds(node.Body.List...))
c, _ = c.pushEnvIfFlag(&nbinds, flag)
erange := c.Expr1(node.X, nil)
t := erange.Type
if erange.Untyped() {
t = erange.DefaultType()
erange.ConstTo(t)
}
var jump rangeJump
sort.Strings(labels)
// we need a fresh Comp here... created above by c.pushEnvIfFlag()
c.Loop = &LoopInfo{
Continue: &jump.Continue,
Break: &jump.Break,
ThisLabels: labels,
}
switch t.Kind() {
case xr.Ptr:
if t.Elem().Kind() != r.Array {
c.Errorf("cannot range over %v <%v>", node.X, t)
}
// range on pointer to array: dereference it
t = t.Elem()
efun := erange.AsX1()
erange = exprX1(t, func(env *Env) xr.Value {
return efun(env).Elem()
})
fallthrough
case xr.Array, r.Slice:
c.rangeSlice(node, erange, &jump)
case xr.Chan:
c.rangeChan(node, erange, &jump)
case xr.Map:
c.rangeMap(node, erange, &jump)
case xr.String:
c.rangeString(node, erange, &jump)
default:
c.Errorf("cannot range over %v <%v>", node.X, t)
}
jump.Break = c.Code.Len()
c = c.popEnvIfFlag(&nbinds, flag)
}
func (c *Comp) rangeChan(node *ast.RangeStmt, erange *Expr, jump *rangeJump) {
t := erange.Type
telem := t.Elem()
// unnamed bind, contains channel
bindchan := c.DeclVar0("", nil, erange)
idxchan := bindchan.Desc.Index()
placekey, _ := c.rangeVars(node, telem, nil)
jump.Start = c.Code.Len()
if placekey == nil {
c.append(func(env *Env) (Stmt, *Env) {
_, ok := env.Vals[idxchan].Recv()
var ip int
if ok {
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
} else {
// unnamed bind, contains last received value
bindrecv := c.NewBind("", VarBind, c.TypeOfInterface())
idxrecv := bindrecv.Desc.Index()
c.append(func(env *Env) (Stmt, *Env) {
v, ok := env.Vals[idxchan].Recv()
var ip int
if ok {
env.Vals[idxrecv] = v
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
c.SetPlace(placekey, token.ASSIGN, unwrapBind(bindrecv, telem))
}
// compile the body
c.Block(node.Body)
// "continue" is a jump to loop beginning
jump.Continue = jump.Start
// jump back to start
c.append(func(env *Env) (Stmt, *Env) {
ip := jump.Start
env.IP = ip
return env.Code[ip], env
})
}
func (c *Comp) rangeSlice(node *ast.RangeStmt, erange *Expr, jump *rangeJump) {
t := erange.Type
var constlen int
var elen *Expr
if node.Value != nil || t.Kind() != r.Array {
// Go spec: one-variable range on array ONLY evaluates the array length, not the array itself
// save range variable in an unnamed bind
bind := c.DeclVar0("", nil, erange)
erange = c.Bind(bind)
}
if t.Kind() == r.Array {
constlen = t.Len()
} else {
// save range length in an unnamed bind
rangefun := erange.AsX1()
elen0 := exprFun(c.TypeOfInt(), func(env *Env) int {
return rangefun(env).Len()
})
bindlen := c.DeclVar0("", nil, elen0)
elen = c.Bind(bindlen)
}
placekey, placeval := c.rangeVars(node, c.TypeOfInt(), t.Elem())
if placekey == nil {
// we need an interation variable, even if user code ignores it
placekey = c.DeclVar0("", c.TypeOfInt(), nil).AsVar(0, PlaceSettable).AsPlace()
}
if placekey.Desc.Class() != IntBind {
c.Errorf("internal error: for-range counter variable allocated with class = %v, expecting class = %v",
placekey.Desc.Class(), IntBind)
}
jump.Start = c.Code.Len()
// compile comparison against range length
ekey := c.GetPlace(placekey)
funkey := ekey.WithFun().(func(*Env) int)
if t.Kind() == r.Array {
c.append(func(env *Env) (Stmt, *Env) {
var ip int
if funkey(env) < constlen {
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
} else {
funlen := elen.WithFun().(func(*Env) int)
c.append(func(env *Env) (Stmt, *Env) {
var ip int
if funkey(env) < funlen(env) {
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
}
if placeval != nil {
// for error messages
indexnode := &ast.IndexExpr{X: node.X, Lbrack: node.X.Pos(), Index: node.Key, Rbrack: node.X.Pos()}
eindex := c.vectorIndex(indexnode, erange, ekey)
c.SetPlace(placeval, token.ASSIGN, eindex)
}
// compile the body
c.Block(node.Body)
// "continue" is a jump to the increment below
jump.Continue = c.Code.Len()
// increment key
c.Pos = node.End() - 1
one := c.exprValue(c.TypeOfInt(), 1)
c.SetPlace(placekey, token.ADD_ASSIGN, one)
// jump back to comparison
c.append(func(env *Env) (Stmt, *Env) {
ip := jump.Start
env.IP = ip
return env.Code[ip], env
})
}
func (c *Comp) rangeString(node *ast.RangeStmt, erange *Expr, jump *rangeJump) {
// save string in an unnamed bind
bindrange := c.DeclVar0("", nil, erange)
idxrange := bindrange.Desc.Index()
placekey, placeval := c.rangeVars(node, c.TypeOfInt(), c.TypeOfInt32())
bindnext := c.DeclVar0("", c.TypeOfInt(), nil)
idxnext := bindnext.Desc.Index()
var bindrune *Bind
if placeval != nil && !placeval.IsVar() {
bindrune = c.DeclVar0("", c.TypeOfInt32(), nil)
}
jump.Start = c.Code.Len()
if placekey != nil {
c.SetPlace(placekey, token.ASSIGN, c.Bind(bindnext))
}
if placeval == nil {
c.append(func(env *Env) (Stmt, *Env) {
s := env.Vals[idxrange].String()
pnext := (*int)(unsafe.Pointer(&env.Ints[idxnext]))
next := *pnext
_, size := utf8.DecodeRuneInString(s[next:])
var ip int
if size != 0 {
next += size
*pnext = next
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
} else if placeval.IsVar() {
idxval := placeval.Var.Desc.Index()
upval := placeval.Var.Upn
c.append(func(env *Env) (Stmt, *Env) {
s := env.Vals[idxrange].String()
pnext := (*int)(unsafe.Pointer(&env.Ints[idxnext]))
next := *pnext
r, size := utf8.DecodeRuneInString(s[next:])
var ip int
if size != 0 {
next += size
*pnext = next
o := env
for i := 0; i < upval; i++ {
o = o.Outer
}
*(*int32)(unsafe.Pointer(&env.Ints[idxval])) = r
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
} else {
idxrune := bindrune.Desc.Index()
c.append(func(env *Env) (Stmt, *Env) {
s := env.Vals[idxrange].String()
pnext := (*int)(unsafe.Pointer(&env.Ints[idxnext]))
next := *pnext
r, size := utf8.DecodeRuneInString(s[next:])
var ip int
if size != 0 {
next += size
*pnext = next
*(*int32)(unsafe.Pointer(&env.Ints[idxrune])) = r
ip = env.IP + 1
} else {
ip = jump.Break
}
env.IP = ip
return env.Code[ip], env
})
c.SetPlace(placeval, token.ASSIGN, c.Bind(bindrune))
}
// compile the body
c.Block(node.Body)
// "continue" is a jump to the iteration above
jump.Continue = jump.Start
// jump back to iteration
c.append(func(env *Env) (Stmt, *Env) {
ip := jump.Start
env.IP = ip
return env.Code[ip], env
})
}
// rangeVars compiles the key and value iteration variables in a for-range
func (c *Comp) rangeVars(node *ast.RangeStmt, tkey xr.Type, tval xr.Type) (*Place, *Place) {
place := [2]*Place{nil, nil}
t := [2]xr.Type{tkey, tval}
for i, expr := range [2]ast.Expr{node.Key, node.Value} {
if expr == nil {
continue
} else if t[i] == nil {
c.Pos = expr.Pos()
c.Errorf("too many variables in range")
}
c.Pos = expr.Pos()
if node.Tok == token.DEFINE {
switch expr := expr.(type) {
case *ast.Ident:
name := expr.Name
if name != "_" {
place[i] = c.DeclVar0(name, t[i], nil).AsVar(0, PlaceSettable).AsPlace()
}
default:
c.Errorf("non-name %v on left side of :=", expr)
}
} else {
if ident, ok := expr.(*ast.Ident); ok && ident.Name == "_" {
// ignore range variable "_"
continue
}
place[i] = c.Place(expr)
if !t[i].AssignableTo(place[i].Type) {
c.Errorf("cannot assign type <%v> to %v <%v> in range", t[i], expr, place[i].Type)
}
}
}
return place[0], place[1]
}