Repository navigation
Expand file tree
/
Copy pathscope_stack.go
More file actions
355 lines (318 loc) · 9.25 KB
/
Copy pathscope_stack.go
File metadata and controls
355 lines (318 loc) · 9.25 KB
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
package glisp
import (
"errors"
"fmt"
"sync"
"sync/atomic"
)
// Scope defines a single layer of lexical bindings, mapping symbol numbers to their Sexp values.
type Scope map[int]Sexp
// ScopeStack owns the layers above shared. The shared layer and its ancestors
// may be held by closures or other environments and are managed by Go's GC.
// Only the exclusive prefix is eligible for pooling.
type ScopeStack struct {
top, bottom *ScopeLayer
shared atomic.Pointer[ScopeLayer]
callBase *ScopeLayer
}
// ScopeLayer stores one set of lexical bindings. Its parent link is immutable
// while shared; set! may update bindings under mu.
type ScopeLayer struct {
Scope Scope
layout *scopeLayout
locals []localValue
mu sync.RWMutex
// overlay layers belong to the same lexical frame as their parent.
overlay bool
next *ScopeLayer
}
// NewScopeStack creates and returns an empty ScopeStack.
func NewScopeStack() *ScopeStack {
return &ScopeStack{}
}
// newScope retrieves a Scope map from the object pool.
func newScope() Scope { return scopePool.Get().(Scope) }
// newScopeLayer retrieves a ScopeLayer from the object pool and initializes it
// with a new, empty Scope.
func newScopeLayer() *ScopeLayer {
return newScopeLayerWith(newScope())
}
// newScopeLayerWith retrieves a ScopeLayer from the object pool and initializes it
// with the provided Scope.
func newScopeLayerWith(s Scope) *ScopeLayer {
if s == nil {
s = newScope()
}
layer := scopeLayerPool.Get().(*ScopeLayer)
layer.Scope = s
return layer
}
// IsStackElem is a marker method for the StackElem interface.
func (s *ScopeLayer) IsStackElem() {}
// Clone creates a deep copy of the ScopeLayer and its underlying Scope map.
func (s *ScopeLayer) Clone() *ScopeLayer {
newScope := newScopeLayer()
s.mu.RLock()
defer s.mu.RUnlock()
for k, v := range s.Scope {
newScope.Scope[k] = v
}
newScope.layout = s.layout
newScope.locals = append(newScope.locals[:0], s.locals...)
return newScope
}
// Find searches for a symbol's value within this specific scope layer.
func (s *ScopeLayer) Find(n int) (Sexp, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.layout != nil {
if i, ok := s.layout.index[n]; ok {
local := s.locals[i]
return local.value, local.bound
}
}
if expr, ok := s.Scope[n]; ok {
return expr, true
}
return SexpNull, false
}
// Bind sets the value for a symbol in this specific scope layer.
func (s *ScopeLayer) Bind(n int, e Sexp) {
s.mu.Lock()
if s.layout != nil {
if i, ok := s.layout.index[n]; ok {
s.locals[i] = localValue{value: e, bound: true}
s.mu.Unlock()
return
}
}
s.Scope[n] = e
s.mu.Unlock()
}
// Fork captures the current lexical environment without traversing its parents.
func (stack *ScopeStack) Fork() *ScopeStack {
stack.shared.Store(stack.top)
st := &ScopeStack{top: stack.top, bottom: stack.bottom}
st.shared.Store(st.top)
return st
}
// ForkBottom shares the global environment. Global layers are always GC-owned.
func (stack *ScopeStack) ForkBottom() *ScopeStack {
st := &ScopeStack{top: stack.bottom, bottom: stack.bottom}
st.shared.Store(st.top)
return st
}
// Only transient call-stack wrappers are pooled, never captured wrappers.
var callScopePool = sync.Pool{New: func() any { return &ScopeStack{} }}
func (stack *ScopeStack) forkCall(capture bool) *ScopeStack {
frame := callScopePool.Get().(*ScopeStack)
frame.bottom = stack.bottom
frame.top = stack.bottom
if capture {
stack.shared.Store(stack.top)
frame.top = stack.top
}
frame.shared.Store(frame.top)
frame.callBase = frame.top
return frame
}
// IsStackElem is a marker method for the StackElem interface.
func (stack *ScopeStack) IsStackElem() {}
// Clone creates a full, deep copy of the ScopeStack, including all its layers.
// This is a more expensive operation than Fork and is used when a completely
// independent environment is required.
func (stack *ScopeStack) Clone() *ScopeStack {
return newCloneContext().scope(stack)
}
// push adds a new layer to the top of the stack.
func (stack *ScopeStack) push(layer *ScopeLayer) {
if layer == nil {
return
}
if stack.top != nil {
layer.next = stack.top
} else {
stack.bottom = layer
stack.shared.Store(layer)
}
stack.top = layer
}
// Pop releases an exclusive layer or drops a reference to a captured layer.
func (stack *ScopeStack) Pop() error {
if stack.top == nil {
return errors.New("pop from empty scope stack")
}
cur := stack.top
stack.top = cur.next
if stack.top == nil {
stack.bottom = nil
}
if cur == stack.shared.Load() {
stack.shared.Store(stack.top)
} else {
recycleScopeLayer(cur)
}
return nil
}
// PushScope creates a new, empty scope and pushes it onto the stack.
// This is used for constructs like `let`.
func (stack *ScopeStack) PushScope() {
stack.Push()
}
// PopScope removes the top scope from the stack.
func (stack *ScopeStack) PopScope() error {
for stack.top != nil {
overlay := stack.top.overlay
if err := stack.Pop(); err != nil {
return err
}
if !overlay {
return nil
}
}
return errors.New("pop from empty scope stack")
}
// Push adds one or more pre-existing scopes to the top of the stack.
func (stack *ScopeStack) Push(scopes ...Scope) {
if len(scopes) == 0 {
layer := newScopeLayer()
stack.push(layer)
} else {
for i := range scopes {
stack.push(newScopeLayerWith(scopes[i]))
}
}
}
// LookupSymbol searches for a symbol starting from the top of the stack and
// moving down through parent scopes until the symbol is found.
func (stack *ScopeStack) LookupSymbol(sym SexpSymbol) (Sexp, error) {
for ptr := stack.top; ptr != nil; {
if expr, ok := ptr.Find(sym.number); ok {
return expr, nil
}
ptr = ptr.next
}
return SexpNull, fmt.Errorf("symbol `%v` not found", sym.Name())
}
// GlobalFuntions returns a list of function names found in the global scope (bottom layer).
func (stack *ScopeStack) GlobalFuntions() (ret []string) {
if stack.IsEmpty() {
return nil
}
stack.bottom.mu.RLock()
defer stack.bottom.mu.RUnlock()
for _, v := range stack.bottom.Scope {
if fn, ok := v.(*SexpFunction); ok {
ret = append(ret, fn.name)
}
}
return
}
// IsEmpty returns true if the stack has no layers.
func (stack *ScopeStack) IsEmpty() bool {
return stack.top == nil
}
type BindSymbolOption int
const (
BIND_DEFAULT BindSymbolOption = iota
BIND_GLOBAL
)
// BindSymbol adds a binding. A captured lexical layer receives a new overlay
// so that def does not replace the bindings seen by existing closures.
func (stack *ScopeStack) BindSymbol(sym SexpSymbol, expr Sexp, options ...BindSymbolOption) error {
if stack.IsEmpty() {
return errors.New("no scope available")
}
if len(options) > 0 && options[0] == BIND_GLOBAL {
stack.bottom.Bind(sym.number, expr)
} else {
if stack.top != stack.bottom && stack.top == stack.shared.Load() {
layer := newScopeLayer()
layer.overlay = true
stack.push(layer)
}
stack.top.Bind(sym.number, expr)
}
return nil
}
// SetSymbol updates an existing binding for a symbol. This is the implementation for `set!`.
// It searches up the scope stack for the first occurrence of the symbol and
// modifies its value in-place.
//
// NOTE: By design, this can mutate a shared parent scope. This behavior is
// intentional to mimic `set!` in many Lisp dialects.
func (stack *ScopeStack) SetSymbol(sym SexpSymbol, expr Sexp) error {
if stack.IsEmpty() {
return errors.New("no scope available")
}
for ptr := stack.top; ptr != nil; {
if _, ok := ptr.Find(sym.number); ok {
ptr.Bind(sym.number, expr)
return nil
}
ptr = ptr.next
}
return stack.BindSymbol(sym, expr)
}
// releaseOwned recycles only the exclusive prefix. Captured layers retain
// their bindings and parent links for any surviving closures.
func (stack *ScopeStack) releaseOwned() {
boundary := stack.shared.Load()
for stack.top != nil && stack.top != boundary {
cur := stack.top
stack.top = cur.next
recycleScopeLayer(cur)
}
}
// Clear releases this stack's ownership without traversing captured ancestors.
func (stack *ScopeStack) Clear() {
stack.releaseOwned()
stack.top = nil
stack.bottom = nil
stack.shared.Store(nil)
stack.callBase = nil
}
// resetCall starts the next tail-call iteration with a fresh parameter frame.
func (stack *ScopeStack) resetCall(layout *scopeLayout) {
// An uncaptured parameter frame can be cleared in place for the next call.
if top := stack.top; top != nil && top != stack.shared.Load() && top.next == stack.callBase && !top.overlay && top.layout == layout {
clear(top.Scope)
clear(top.locals)
return
}
stack.releaseOwned()
stack.top = stack.callBase
stack.shared.Store(stack.callBase)
stack.pushLayout(layout)
}
// scopePool holds maps for reuse.
var scopePool = sync.Pool{
New: func() any { return make(Scope) },
}
// scopeLayerPool holds ScopeLayer structs for reuse.
var scopeLayerPool = sync.Pool{
New: func() any {
return &ScopeLayer{}
},
}
// recycleScope clears a scope map and returns it to the pool.
func recycleScope(s Scope) {
if s != nil {
clear(s)
scopePool.Put(s)
}
}
// recycleScopeLayer is used only for layers exclusively owned by a stack.
func recycleScopeLayer(layer *ScopeLayer) {
if layer == nil {
return
}
recycleScope(layer.Scope)
layer.Scope = nil
layer.next = nil
layer.overlay = false
layer.layout = nil
clear(layer.locals)
layer.locals = layer.locals[:0]
scopeLayerPool.Put(layer)
}