Repository navigation
Expand file tree
/
Copy pathbase_coroutine.go
More file actions
471 lines (441 loc) · 15.1 KB
/
Copy pathbase_coroutine.go
File metadata and controls
471 lines (441 loc) · 15.1 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
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
package ember
import (
"context"
"fmt"
)
type vmCoroutineStatus string
const (
vmCoroutineSuspended vmCoroutineStatus = "suspended"
vmCoroutineRunning vmCoroutineStatus = "running"
vmCoroutineNormal vmCoroutineStatus = "normal"
vmCoroutineDead vmCoroutineStatus = "dead"
)
type vmCoroutine struct {
status vmCoroutineStatus
owner *runtimeOwner
thread vmThread
root *closure
userdata *UserData
suspended vmSuspendedFrames
yieldedValues []Value
yieldedInline [2]Value
resumeArgs []Value
resumeResults []Value
err error
}
func baseCoroutine() *Table {
table := newTableWithCapacity(0, 8)
_ = table.Set(StringValue("create"), nativeFuncValueWithID(baseCoroutineCreate, nativeFuncCoroutineCreate))
_ = table.Set(StringValue("resume"), nativeFuncValueWithID(baseCoroutineResume, nativeFuncCoroutineResume))
_ = table.Set(StringValue("yield"), nativeFuncValueWithID(baseCoroutineYield, nativeFuncCoroutineYield))
_ = table.Set(StringValue("status"), nativeFuncValueWithID(baseCoroutineStatusNative, nativeFuncCoroutineStatus))
_ = table.Set(StringValue("close"), HostFuncValue(baseCoroutineClose))
_ = table.Set(StringValue("running"), nativeFuncValue(baseCoroutineRunning))
_ = table.Set(StringValue("isyieldable"), nativeFuncValue(baseCoroutineIsYieldable))
_ = table.Set(StringValue("wrap"), nativeFuncValue(baseCoroutineWrap))
return table
}
func baseCoroutineCreate(globals *globalEnv, args []Value) ([]Value, error) {
if len(args) == 0 {
return nil, fmt.Errorf("coroutine.create: missing function")
}
closure, ok := args[0].scriptFunction()
if !ok {
return nil, fmt.Errorf("coroutine.create: argument is %s, want function", args[0].Kind())
}
coroutine, err := newVMCoroutineChecked(globals, closure)
if err != nil {
return nil, err
}
return []Value{UserDataValue(coroutine.userdata)}, nil
}
func newVMCoroutine(globals *globalEnv, root *closure) *vmCoroutine {
coroutine, _ := newVMCoroutineChecked(globals, root)
return coroutine
}
func newVMCoroutineChecked(globals *globalEnv, root *closure) (*vmCoroutine, error) {
controller := executionControllerForGlobals(globals)
if controller != nil {
if err := controller.chargeRuntimeObjects(2); err != nil {
return nil, err
}
}
owner := runtimeOwnerFromGlobals(globals)
coroutineGlobals := globals
if globals != nil && globals.pooled {
coroutineGlobals = promotePooledGlobals(globals)
}
coroutine := &vmCoroutine{
status: vmCoroutineSuspended,
owner: owner,
thread: newVMThread(coroutineGlobals),
root: root,
}
if globals != nil {
if globals.thread != nil {
coroutine.thread.owner = globals.thread.owner
coroutine.thread.inheritDebugConfig(globals.thread)
}
}
coroutine.userdata = NewUserData(coroutine)
if owner != nil {
if err := owner.retainCoroutine(coroutine); err != nil {
if controller != nil {
controller.releaseRuntimeObjects(2)
}
coroutine.disposeFrames()
return nil, err
}
}
return coroutine, nil
}
// promotePooledGlobals transfers an active pooled environment to a stable
// heap object before a coroutine can retain it. The parent thread switches to
// that same object, preserving shared global values, slot versions, and host
// snapshots across parent/sibling coroutine execution. A pooled environment
// with no active thread is cloned as a defensive slow-path fallback.
func promotePooledGlobals(globals *globalEnv) *globalEnv {
if globals == nil || !globals.pooled {
return globals
}
if globals.thread == nil {
promoted := *globals
promoted.values = cloneGlobalValues(globals.values)
promoted.host = cloneGlobalValues(globals.host)
promoted.slots = cloneGlobalSlots(globals.slots)
promoted.thread = nil
promoted.pooled = false
promoted.scope = invocationScope{}
promoted.hasScope = false
promoted.controller = nil
return &promoted
}
parent := globals.thread
promoted := *globals
// Do not let pool reset clear backing maps that the retained coroutine will
// keep using. The parent switches to this same promoted environment, so the
// copies still preserve all parent/sibling sharing and slot versions.
promoted.values = cloneGlobalValues(globals.values)
promoted.host = cloneGlobalValues(globals.host)
promoted.slots = cloneGlobalSlots(globals.slots)
promoted.pooled = false
promoted.thread = parent
parent.globals = &promoted
return &promoted
}
func cloneGlobalValues(values map[string]Value) map[string]Value {
if len(values) == 0 {
return nil
}
clone := make(map[string]Value, len(values))
for name, value := range values {
clone[name] = value
}
return clone
}
func cloneGlobalSlots(slots []globalSlot) []globalSlot {
if len(slots) == 0 {
return nil
}
clone := make([]globalSlot, len(slots))
copy(clone, slots)
return clone
}
func baseCoroutineResume(globals *globalEnv, args []Value) ([]Value, error) {
coroutine, err := coroutineArg("coroutine.resume", args, 0)
if err != nil {
return nil, err
}
if coroutine.status == vmCoroutineDead {
return []Value{BoolValue(false), StringValue("cannot resume dead coroutine")}, nil
}
if coroutine.status == vmCoroutineRunning {
return []Value{BoolValue(false), StringValue("cannot resume running coroutine")}, nil
}
if coroutine.status == vmCoroutineNormal {
return []Value{BoolValue(false), StringValue("cannot resume non-suspended coroutine")}, nil
}
callerOwner := runtimeOwnerFromGlobals(globals)
if coroutine.owner != callerOwner {
return []Value{BoolValue(false), StringValue("coroutine.resume: runtime owner mismatch")}, nil
}
if coroutine.owner != nil {
if err := coroutine.owner.registerCoroutine(coroutine); err != nil {
return []Value{BoolValue(false), StringValue("coroutine.resume: " + err.Error())}, nil
}
defer coroutine.owner.unregisterCoroutine(coroutine)
}
coroutine.status = vmCoroutineRunning
coroutine.resumeArgs = append(coroutine.resumeArgs[:0], args[1:]...)
parent, restoreParent := activeParentCoroutine(globals, coroutine)
if parent != nil {
parent.status = vmCoroutineNormal
defer restoreParent()
}
parentThread := activeThread(globals)
if parentThread != nil {
coroutine.thread.ctx = parentThread.ctx
coroutine.thread.controller = parentThread.controller
coroutine.thread.scope = parentThread.scope
coroutine.thread.hasScope = parentThread.hasScope
coroutine.thread.inheritedScriptFrames = parentThread.inheritedScriptFrames
}
results, err := resumeCoroutine(coroutine, globals, args[1:])
if yield, ok := err.(vmYieldRequest); ok {
coroutine.status = vmCoroutineSuspended
coroutine.yieldedValues = append(coroutine.yieldedValues[:0], yield.values...)
coroutine.thread.coroutine = coroutine
coroutine.suspended = coroutine.thread.suspendFrames()
// A yielded coroutine must not retain the invocation's spent budget or
// cancellation context. Public resume attaches the new invocation
// controller before restoring these frames.
coroutine.suspended.ctx = context.Background()
coroutine.suspended.controller = nil
coroutine.suspended.scope = invocationScope{}
coroutine.suspended.hasScope = false
coroutine.suspended.inheritedScriptFrames = nil
coroutine.thread.ctx = context.Background()
coroutine.thread.controller = nil
coroutine.thread.scope = invocationScope{}
coroutine.thread.hasScope = false
coroutine.thread.inheritedScriptFrames = nil
return coroutine.resumeResult(true, yield.values), nil
}
if err != nil {
coroutine.status = vmCoroutineDead
coroutine.err = err
coroutine.disposeFrames()
coroutine.releaseOwner()
return []Value{BoolValue(false), StringValue(err.Error())}, nil
}
coroutine.status = vmCoroutineDead
returned := coroutine.resumeResult(true, results)
coroutine.disposeFrames()
coroutine.releaseOwner()
return returned, nil
}
func runtimeOwnerFromGlobals(globals *globalEnv) *runtimeOwner {
if globals == nil {
return nil
}
if globals.owner != nil {
return globals.owner
}
if globals.thread != nil {
return globals.thread.owner
}
return nil
}
func (coroutine *vmCoroutine) releaseOwner() {
if coroutine != nil && coroutine.owner != nil {
coroutine.owner.releaseCoroutine(coroutine)
}
}
func (coroutine *vmCoroutine) disposeFrames() {
if coroutine == nil {
return
}
if len(coroutine.suspended.frames) != 0 || len(coroutine.suspended.frameRecords) != 0 || coroutine.suspended.owner != nil {
coroutine.thread.resumeFrames(coroutine.suspended)
coroutine.suspended = vmSuspendedFrames{}
}
coroutine.thread.dropFrames(0)
coroutine.thread.closeAllOpenUpvalues()
coroutine.thread.clearFrameRecords()
coroutine.thread.clearRootClosureSlots()
for _, frame := range coroutine.thread.frameSlots {
if frame != nil {
frame.resetForPool()
}
}
coroutine.thread.frames = nil
coroutine.thread.frameSlots = nil
coroutine.thread.rootClosureSlots = nil
coroutine.thread.stack = nil
coroutine.thread.stackOwner = nil
coroutine.thread.globals = nil
coroutine.thread.scope = invocationScope{}
coroutine.thread.hasScope = false
coroutine.thread.inheritedScriptFrames = nil
coroutine.thread.baseGlobals = globalEnv{}
coroutine.thread.ctx = context.Background()
coroutine.thread.controller = nil
coroutine.thread.resumeCallDepthErr = nil
coroutine.thread.coroutine = nil
coroutine.thread.stringIntern = nil
coroutine.thread.stringConcatIntern = nil
coroutine.thread.functionInstances = nil
coroutine.thread.functionInstanceSites = 0
coroutine.thread.intrinsicGuards = nil
coroutine.thread.debugHook = nil
coroutine.root = nil
coroutine.yieldedValues = nil
clear(coroutine.yieldedInline[:])
coroutine.resumeArgs = nil
coroutine.resumeResults = nil
}
func (coroutine *vmCoroutine) resumeResult(ok bool, values []Value) []Value {
needed := 1 + len(values)
if cap(coroutine.resumeResults) < needed {
coroutine.resumeResults = make([]Value, needed)
} else {
coroutine.resumeResults = coroutine.resumeResults[:needed]
}
coroutine.resumeResults[0] = BoolValue(ok)
copy(coroutine.resumeResults[1:], values)
return coroutine.resumeResults
}
func activeParentCoroutine(globals *globalEnv, child *vmCoroutine) (*vmCoroutine, func()) {
if globals == nil || globals.thread == nil {
return nil, func() {}
}
parent := globals.thread.coroutine
if parent == nil || parent == child || parent.status != vmCoroutineRunning {
return nil, func() {}
}
previousStatus := parent.status
return parent, func() {
parent.status = previousStatus
}
}
func resumeCoroutine(coroutine *vmCoroutine, globals *globalEnv, args []Value) ([]Value, error) {
if coroutine.thread.globals == nil {
coroutine.thread.globals = globals
}
previousCoroutine := coroutine.thread.coroutine
coroutine.thread.coroutine = coroutine
defer func() {
coroutine.thread.coroutine = previousCoroutine
}()
if len(coroutine.suspended.frames) > 0 || len(coroutine.suspended.frameRecords) > 0 {
coroutine.thread.resumeFrames(coroutine.suspended)
coroutine.thread.coroutine = coroutine
coroutine.suspended = vmSuspendedFrames{}
return coroutine.thread.continueSuspended(args)
}
return coroutine.thread.runWithUpvalues(coroutine.root.proto, args, coroutine.root.upvalues, coroutine.root.upvalueValues, coroutine.root.upvalueValueOK)
}
func baseCoroutineYield(globals *globalEnv, args []Value) ([]Value, error) {
if globals == nil || globals.thread == nil || globals.thread.coroutine == nil {
return nil, fmt.Errorf("coroutine.yield: outside coroutine")
}
if !globals.thread.isYieldable() {
return nil, fmt.Errorf("coroutine.yield: not yieldable")
}
coroutine := globals.thread.coroutine
if coroutine.status != vmCoroutineRunning {
return nil, fmt.Errorf("coroutine.yield: coroutine is not running")
}
if len(args) <= len(coroutine.yieldedInline) {
copy(coroutine.yieldedInline[:], args)
coroutine.yieldedValues = coroutine.yieldedInline[:len(args)]
} else {
coroutine.yieldedValues = append(coroutine.yieldedValues[:0], args...)
}
return nil, vmYieldRequest{values: coroutine.yieldedValues}
}
func baseCoroutineStatusNative(_ *globalEnv, args []Value) ([]Value, error) {
return baseCoroutineStatus(args)
}
func baseCoroutineStatus(args []Value) ([]Value, error) {
status, err := baseCoroutineStatusValue(args)
if err != nil {
return nil, err
}
return []Value{status}, nil
}
func baseCoroutineStatusValue(args []Value) (Value, error) {
coroutine, err := coroutineArg("coroutine.status", args, 0)
if err != nil {
return NilValue(), err
}
return StringValue(string(coroutine.status)), nil
}
func baseCoroutineClose(args []Value) ([]Value, error) {
coroutine, err := coroutineArg("coroutine.close", args, 0)
if err != nil {
return nil, err
}
if coroutine.status == vmCoroutineRunning {
return nil, fmt.Errorf("coroutine.close: cannot close running coroutine")
}
if coroutine.err != nil {
err := coroutine.err
coroutine.err = nil
coroutine.status = vmCoroutineDead
coroutine.disposeFrames()
coroutine.releaseOwner()
return []Value{BoolValue(false), StringValue(err.Error())}, nil
}
coroutine.status = vmCoroutineDead
coroutine.disposeFrames()
coroutine.releaseOwner()
return []Value{BoolValue(true)}, nil
}
func baseCoroutineRunning(globals *globalEnv, args []Value) ([]Value, error) {
if globals == nil || globals.thread == nil || globals.thread.coroutine == nil {
return []Value{NilValue()}, nil
}
coroutine := globals.thread.coroutine
if coroutine.userdata == nil {
return []Value{NilValue()}, nil
}
return []Value{UserDataValue(coroutine.userdata)}, nil
}
func baseCoroutineIsYieldable(globals *globalEnv, args []Value) ([]Value, error) {
yieldable := globals != nil &&
globals.thread != nil &&
globals.thread.isYieldable() &&
globals.thread.coroutine != nil &&
globals.thread.coroutine.status == vmCoroutineRunning
return []Value{BoolValue(yieldable)}, nil
}
func baseCoroutineWrap(globals *globalEnv, args []Value) ([]Value, error) {
if len(args) == 0 {
return nil, fmt.Errorf("coroutine.wrap: missing function")
}
closure, ok := args[0].scriptFunction()
if !ok {
return nil, fmt.Errorf("coroutine.wrap: argument is %s, want function", args[0].Kind())
}
coroutine, err := newVMCoroutineChecked(globals, closure)
if err != nil {
return nil, err
}
definingGlobals := coroutine.thread.globals
wrapped := func(callerGlobals *globalEnv, args []Value) ([]Value, error) {
if callerGlobals == nil {
callerGlobals = definingGlobals
}
results, err := baseCoroutineResume(callerGlobals, append([]Value{UserDataValue(coroutine.userdata)}, args...))
if err != nil {
return nil, err
}
ok, _ := adjustedResultAt(results, 0).Bool()
if !ok {
return nil, fmt.Errorf("%s", valueToString(adjustedResultAt(results, 1)))
}
return results[1:], nil
}
return []Value{nativeFuncValue(wrapped)}, nil
}
func activeThread(globals *globalEnv) *vmThread {
if globals == nil {
return nil
}
return globals.thread
}
func coroutineArg(name string, args []Value, index int) (*vmCoroutine, error) {
if index >= len(args) {
return nil, fmt.Errorf("%s: missing coroutine", name)
}
userdata, ok := args[index].UserData()
if !ok {
return nil, fmt.Errorf("%s: argument is %s, want thread", name, args[index].Kind())
}
coroutine, ok := userdata.Payload().(*vmCoroutine)
if !ok || coroutine == nil {
return nil, fmt.Errorf("%s: argument is userdata, want thread", name)
}
return coroutine, nil
}