-
Notifications
You must be signed in to change notification settings - Fork 93
/
compile.go
499 lines (462 loc) · 11.6 KB
/
compile.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/*
* 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/.
*
*
* compile.go
*
* Created on Apr 01, 2017
* Author Massimiliano Ghilardi
*/
package fast
import (
"go/ast"
"go/token"
r "reflect"
. "github.com/cosmos72/gomacro/ast2"
"github.com/cosmos72/gomacro/base"
"github.com/cosmos72/gomacro/base/dep"
"github.com/cosmos72/gomacro/gls"
xr "github.com/cosmos72/gomacro/xreflect"
)
func NewComp(outer *Comp, code *Code) *Comp {
if outer == nil {
return &Comp{UpCost: 1}
}
c := Comp{
UpCost: 1,
Depth: outer.Depth + 1,
Outer: outer,
CompGlobals: outer.CompGlobals,
}
// Debugf("NewComp(%p->%p) %s", outer, &c, debug.Stack())
if code != nil {
c.Code = *code
}
return &c
}
func (c *Comp) TopComp() *Comp {
for ; c != nil; c = c.Outer {
if c.Outer == nil {
break
}
}
return c
}
func (c *Comp) FileComp() *Comp {
for ; c != nil; c = c.Outer {
outer := c.Outer
if outer == nil || outer.Outer == nil {
break
}
}
return c
}
func NewIrGlobals() *IrGlobals {
return &IrGlobals{
gls: make(map[uintptr]*Run),
Globals: *base.NewGlobals(),
}
}
func (g *IrGlobals) glsGet(goid uintptr) *Run {
g.lock.Lock()
ret := g.gls[goid]
g.lock.Unlock()
return ret
}
func (run *Run) getRun4Goid(goid uintptr) *Run {
g := run.IrGlobals
ret := g.glsGet(goid)
if ret == nil {
ret = run.new(goid)
ret.glsStore()
}
return ret
}
func (tg *Run) glsStore() {
g := tg.IrGlobals
goid := tg.goid
g.lock.Lock()
g.gls[goid] = tg
g.lock.Unlock()
}
func (tg *Run) glsDel() {
g := tg.IrGlobals
goid := tg.goid
g.lock.Lock()
delete(g.gls, goid)
g.lock.Unlock()
}
func (run *Run) new(goid uintptr) *Run {
return &Run{
IrGlobals: run.IrGlobals,
goid: goid,
// Interrupt, Signal, PoolSize and Pool are zero-initialized, fine with that
}
}
// common part between NewEnv() and newEnv4Func()
func newEnv(run *Run, outer *Env, nbind int, nintbind int) *Env {
pool := &run.Pool // pool is an array, do NOT copy it!
index := run.PoolSize - 1
var env *Env
if index >= 0 {
run.PoolSize = index
env = pool[index]
pool[index] = nil
} else {
env = &Env{}
}
if cap(env.Vals) >= nbind {
env.Vals = env.Vals[0:nbind]
} else {
env.Vals = make([]xr.Value, nbind)
}
if cap(env.Ints) >= nintbind {
env.Ints = env.Ints[0:nintbind]
} else {
env.Ints = make([]uint64, nintbind)
}
env.Outer = outer
env.Run = run
env.FileEnv = outer.FileEnv
return env
}
// return a new, nested Env with given number of binds and intbinds
func NewEnv(outer *Env, nbind int, nintbind int) *Env {
run := outer.Run
// manually inline
// env := newEnv(run, outer, nbind, nintbind)
var env *Env
{
pool := &run.Pool // pool is an array, do NOT copy it!
index := run.PoolSize - 1
if index >= 0 {
run.PoolSize = index
env = pool[index]
pool[index] = nil
} else {
env = &Env{}
}
if cap(env.Vals) >= nbind {
env.Vals = env.Vals[0:nbind]
} else {
env.Vals = make([]xr.Value, nbind)
}
if cap(env.Ints) >= nintbind {
env.Ints = env.Ints[0:nintbind]
} else {
env.Ints = make([]uint64, nintbind)
}
env.Outer = outer
env.Run = run
env.FileEnv = outer.FileEnv
}
env.IP = outer.IP
env.Code = outer.Code
env.DebugPos = outer.DebugPos
env.CallDepth = outer.CallDepth
// this is a nested *Env, not a function body: to obtain the caller function,
// follow env.Outer.Outer... chain until you find an *Env with non-nil Caller
// env.Caller = nil
// DebugCallStack Debugf("NewEnv(%p->%p) nbind=%d nintbind=%d calldepth: %d->%d", outer, env, nbind, nintbind, outer.CallDepth, env.CallDepth)
run.CurrEnv = env
return env
}
func newEnv4Func(outer *Env, nbind int, nintbind int, debugComp *Comp) *Env {
goid := gls.GoID()
run := outer.Run
if run.goid != goid {
// no luck... get the correct ThreadGlobals for goid
run = run.getRun4Goid(goid)
}
// manually inline
// env := newEnv(run, outer, nbind, nintbind)
var env *Env
{
pool := &run.Pool // pool is an array, do NOT copy it!
index := run.PoolSize - 1
if index >= 0 {
run.PoolSize = index
env = pool[index]
pool[index] = nil
} else {
env = &Env{}
}
if cap(env.Vals) >= nbind {
env.Vals = env.Vals[0:nbind]
} else {
env.Vals = make([]xr.Value, nbind)
}
if cap(env.Ints) >= nintbind {
env.Ints = env.Ints[0:nintbind]
} else {
env.Ints = make([]uint64, nintbind)
}
env.Outer = outer
env.Run = run
env.FileEnv = outer.FileEnv
}
env.DebugComp = debugComp
caller := run.CurrEnv
env.Caller = caller
if caller == nil {
env.CallDepth = 1
} else {
env.CallDepth = caller.CallDepth + 1
}
// DebugCallStack Debugf("newEnv4Func(%p->%p) nbind=%d nintbind=%d calldepth: %d->%d", caller, env, nbind, nintbind, env.CallDepth-1, env.CallDepth)
run.CurrEnv = env
return env
}
func (env *Env) MarkUsedByClosure() {
for ; env != nil && !env.UsedByClosure; env = env.Outer {
env.UsedByClosure = true
}
}
// FreeEnv tells the interpreter that given nested *Env is no longer needed.
func (env *Env) FreeEnv() {
run := env.Run
run.CurrEnv = env.Outer
env.freeEnv(run)
}
// freeEnv4Func tells the interpreter that given function body *Env is no longer needed.
func (env *Env) freeEnv4Func() {
run := env.Run
run.CurrEnv = env.Caller
env.freeEnv(run)
}
func (env *Env) freeEnv(run *Run) {
// DebugCallStack Debugf("FreeEnv(%p->%p), calldepth: %d->%d", env, caller, env.CallDepth, caller.CallDepth)
if env.UsedByClosure {
// output.Debugf("freeEnv: used by closure, cannot reuse: %p %+v", env, env)
return
}
n := run.PoolSize
if n >= poolCapacity {
return
}
if env.IntAddressTaken {
env.Ints = nil
env.IntAddressTaken = false
}
env.Outer = nil
env.Code = nil
env.DebugPos = nil
env.DebugComp = nil
env.Caller = nil
env.Run = nil
env.FileEnv = nil
run.Pool[n] = env // pool is an array, be careful NOT to copy it!
run.PoolSize = n + 1
}
func (env *Env) Top() *Env {
if env == nil {
return nil
}
if file := env.FileEnv; file != nil {
if top := file.Outer; top != nil && top.Outer == nil {
return top
}
}
for o := env.Outer; o != nil; o = o.Outer {
env = o
}
return env
}
func (env *Env) Up(n int) *Env {
for ; n >= 3; n -= 3 {
env = env.Outer.Outer.Outer
}
switch n {
case 2:
env = env.Outer
fallthrough
case 1:
env = env.Outer
}
return env
}
// combined Parse + MacroExpandCodeWalk
func (c *Comp) Parse(src string) Ast {
// do NOT set c.Globals.Line = 0
// caller can do it manually if needed
nodes := c.ParseBytes([]byte(src))
forms := anyToAst(nodes, "Parse")
forms, _ = c.MacroExpandCodewalk(forms)
if c.Options&base.OptShowMacroExpand != 0 {
c.Debugf("after macroexpansion: %v", forms.Interface())
}
return forms
}
// find all import statements in decls, remove them and return them separately
func extractImports(decls dep.DeclList) (*ast.GenDecl, dep.DeclList) {
var imports []ast.Spec
var nonimports dep.DeclList
for _, decl := range decls {
if decl.Kind == dep.Import {
if node, _ := decl.Node.(*ast.ImportSpec); node != nil {
imports = append(imports, node)
}
} else {
nonimports = append(nonimports, decl)
}
}
return &ast.GenDecl{
Tok: token.IMPORT,
Specs: imports,
}, nonimports
}
// compile code. support out-of-order declarations
func (c *Comp) Compile(in Ast) *Expr {
if in == nil {
return nil
}
switch node := in.Interface().(type) {
case *ast.File, ast.Decl, *ast.ValueSpec:
// complicated, use general technique below
case ast.Node:
// shortcut
return c.compileNode(node, dep.Unknown)
}
// order declarations by topological sort on their dependencies
sorter := dep.NewSorter()
sorter.LoadAst(in)
decls := sorter.All()
switch n := len(decls); n {
case 0:
return nil
case 1:
return c.compileDecl(decls[0])
default:
// sorter.All() returns a list that may contain naked *ast.ImportSpec,
// instead of wrapping []*ast.ImportSpec in a single *ast.GenDecl as parser does.
//
// So we collect and execute all import statements first:
// different imports may depend on different versions of the same package,
// and we need 'go mod tidy' to resolve any version conflict
imports, decls := extractImports(decls)
c.MultiImport(imports)
exprs := make([]*Expr, 0, len(decls))
for _, decl := range decls {
e := c.compileDecl(decl)
if e != nil {
exprs = append(exprs, e)
}
}
return exprList(exprs, c.CompileOptions())
}
return nil
}
// compile code. support out-of-order declarations too
func (c *Comp) CompileNode(node ast.Node) *Expr {
return c.Compile(ToAst(node))
}
func (c *Comp) compileDecl(decl *dep.Decl) *Expr {
if decl == nil {
return nil
}
if extra := decl.Extra; extra != nil {
// decl.Node may declare multiple constants or variables:
// do not use it!
// instead get the single const or var declaration from Extra
switch decl.Kind {
case dep.Const:
// see Comp.GenDecl() in declaration.go for a discussion
// on the scope where to declare iota, and what to do
// with any previous declaration of iota in the same scope
top := c.TopComp()
defer top.endIota(top.beginIota())
top.setIota(extra.Iota)
c.DeclConsts(extra.Spec(), nil, nil)
return c.Code.AsExpr()
case dep.Var:
c.DeclVars(extra.Spec())
return c.Code.AsExpr()
}
}
if node := decl.Node; node != nil {
return c.compileNode(node, decl.Kind)
}
// may happen for second and later variables in VarMulti,
// which CANNOT be declared individually
return nil
}
// compileExpr is a wrapper for Compile
// that guarantees Code does not get clobbered/cleared.
// Used by Comp.Quasiquote
func (c *Comp) compileExpr(in Ast) *Expr {
cf := NewComp(c, nil)
cf.UpCost = 0
cf.Depth--
return cf.Compile(in)
}
// common backend for Compile, CompileNode, File, compileDecl.
// does NOT support out-of-order declarations
func (c *Comp) compileNode(node ast.Node, kind dep.Kind) *Expr {
if n := c.Code.Len(); n != 0 {
c.Warnf("Compile: discarding %d previously compiled statements from code buffer", n)
}
if node == nil {
return nil
}
c.Code.Clear()
c.Loop = nil
c.Func = nil
c.Labels = nil
c.FuncMaker = nil
c.Pos = node.Pos()
switch node := node.(type) {
case ast.Decl:
c.Decl(node)
case ast.Expr:
return c.Expr(node, nil)
case *ast.ImportSpec:
// may happen if we are compiling a single import declaration
c.Import(node)
case *ast.TypeSpec:
// dep.Sorter.Some() returns naked *ast.TypeSpec,
// instead of *ast.GenDecl containing one or more *ast.TypeSpec as parser does
if kind == dep.TypeFwd {
// forward type declaration
c.DeclNamedType(node.Name.Name)
} else {
c.DeclType(node)
}
case *ast.ExprStmt:
// special case of statement
return c.Expr(node.X, nil)
case ast.Stmt:
c.Stmt(node)
case *ast.File:
// not c.File(node): unnecessary and risks an infinite recursion
for _, decl := range node.Decls {
c.Decl(decl)
}
case *ast.ValueSpec:
// dep.Sorter.Some() returns naked *ast.ValueSpec for `package foo`
// instead of *ast.GenDecl containing one or more *ast.ValueSpec as parser does
c.packageStub(node)
default:
c.Errorf("unsupported node type, expecting <ast.Decl>, <ast.Expr>, <ast.Stmt> or <*ast.File>, found %v <%v>", node, r.TypeOf(node))
return nil
}
return c.Code.AsExpr()
}
// compile file. support out-of-order declarations too
func (c *Comp) File(node *ast.File) {
if node != nil {
c.Name = node.Name.Name
c.Compile(File{node})
}
}
func (c *Comp) Append(stmt Stmt, pos token.Pos) {
c.Code.Append(stmt, pos)
}
func (c *Comp) append(stmt Stmt) {
c.Code.Append(stmt, c.Pos)
}