forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules.go
455 lines (417 loc) · 12.9 KB
/
modules.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
package goja
import (
"errors"
)
type HostResolveImportedModuleFunc func(referencingScriptOrModule interface{}, specifier string) (ModuleRecord, error)
// TODO most things here probably should be unexported and names should be revised before merged in master
// Record should probably be dropped from everywhere
// ModuleRecord is the common interface for module record as defined in the EcmaScript specification
type ModuleRecord interface {
GetExportedNames(resolveset ...ModuleRecord) []string
ResolveExport(exportName string, resolveset ...ResolveSetElement) (*ResolvedBinding, bool)
Link() error
Evaluate(*Runtime) *Promise
}
type CyclicModuleRecordStatus uint8
const (
Unlinked CyclicModuleRecordStatus = iota
Linking
Linked
Evaluating
Evaluating_Async
Evaluated
)
type CyclicModuleRecord interface {
ModuleRecord
RequestedModules() []string
InitializeEnvironment() error
Instantiate(rt *Runtime) (CyclicModuleInstance, error)
}
type (
ModuleInstance interface {
GetBindingValue(string) Value
}
CyclicModuleInstance interface {
ModuleInstance
HasTLA() bool
ExecuteModule(rt *Runtime, res, rej func(interface{})) (CyclicModuleInstance, error)
}
)
type linkState struct {
status map[ModuleRecord]CyclicModuleRecordStatus
dfsIndex map[ModuleRecord]uint
dfsAncestorIndex map[ModuleRecord]uint
}
func newLinkState() *linkState {
return &linkState{
status: make(map[ModuleRecord]CyclicModuleRecordStatus),
dfsIndex: make(map[ModuleRecord]uint),
dfsAncestorIndex: make(map[ModuleRecord]uint),
}
}
func (c *compiler) CyclicModuleRecordConcreteLink(module ModuleRecord) error {
stack := []CyclicModuleRecord{}
if _, err := c.innerModuleLinking(newLinkState(), module, &stack, 0); err != nil {
return err
}
return nil
}
func (c *compiler) innerModuleLinking(state *linkState, m ModuleRecord, stack *[]CyclicModuleRecord, index uint) (uint, error) {
var module CyclicModuleRecord
var ok bool
if module, ok = m.(CyclicModuleRecord); !ok {
return index, m.Link()
}
if status := state.status[module]; status == Linking || status == Linked || status == Evaluated {
return index, nil
} else if status != Unlinked {
return 0, errors.New("bad status on link") // TODO fix
}
state.status[module] = Linking
state.dfsIndex[module] = index
state.dfsAncestorIndex[module] = index
index++
*stack = append(*stack, module)
var err error
var requiredModule ModuleRecord
for _, required := range module.RequestedModules() {
requiredModule, err = c.hostResolveImportedModule(module, required)
if err != nil {
return 0, err
}
index, err = c.innerModuleLinking(state, requiredModule, stack, index)
if err != nil {
return 0, err
}
if requiredC, ok := requiredModule.(CyclicModuleRecord); ok {
if state.status[requiredC] == Linking {
if ancestorIndex := state.dfsAncestorIndex[module]; state.dfsAncestorIndex[requiredC] > ancestorIndex {
state.dfsAncestorIndex[requiredC] = ancestorIndex
}
}
}
}
err = module.InitializeEnvironment()
if err != nil {
return 0, err
}
if state.dfsAncestorIndex[module] == state.dfsIndex[module] {
for i := len(*stack) - 1; i >= 0; i-- {
requiredModule := (*stack)[i]
*stack = (*stack)[:i]
state.status[requiredModule] = Linked
if requiredModule == module {
break
}
}
}
return index, nil
}
type evaluationState struct {
status map[ModuleInstance]CyclicModuleRecordStatus
dfsIndex map[ModuleInstance]uint
dfsAncestorIndex map[ModuleInstance]uint
pendingAsyncDependancies map[ModuleInstance]uint
cycleRoot map[ModuleInstance]CyclicModuleInstance
asyncEvaluation map[CyclicModuleInstance]bool
asyncParentModules map[CyclicModuleInstance][]CyclicModuleInstance
evaluationError map[CyclicModuleInstance]error
topLevelCapability map[CyclicModuleRecord]*promiseCapability
}
func newEvaluationState() *evaluationState {
return &evaluationState{
status: make(map[ModuleInstance]CyclicModuleRecordStatus),
dfsIndex: make(map[ModuleInstance]uint),
dfsAncestorIndex: make(map[ModuleInstance]uint),
pendingAsyncDependancies: make(map[ModuleInstance]uint),
cycleRoot: make(map[ModuleInstance]CyclicModuleInstance),
asyncEvaluation: make(map[CyclicModuleInstance]bool),
asyncParentModules: make(map[CyclicModuleInstance][]CyclicModuleInstance),
evaluationError: make(map[CyclicModuleInstance]error),
topLevelCapability: make(map[CyclicModuleRecord]*promiseCapability),
}
}
// TODO have resolve as part of runtime
func (r *Runtime) CyclicModuleRecordEvaluate(c CyclicModuleRecord, resolve HostResolveImportedModuleFunc,
) *Promise {
if r.modules == nil {
r.modules = make(map[ModuleRecord]ModuleInstance)
}
// TODO implement all the promise stuff
stackInstance := []CyclicModuleInstance{}
state := newEvaluationState()
capability := r.newPromiseCapability(r.global.Promise)
state.topLevelCapability[c] = capability
// TODO fix abrupt result
_, err := r.innerModuleEvaluation(state, c, &stackInstance, 0, resolve)
if err != nil {
for _, m := range stackInstance {
state.status[m] = Evaluated
state.evaluationError[m] = err
}
capability.reject(r.ToValue(err))
} else {
if !state.asyncEvaluation[r.modules[c].(CyclicModuleInstance)] {
state.topLevelCapability[c].resolve(_undefined)
}
}
// TODO handle completion
return state.topLevelCapability[c].promise.Export().(*Promise)
}
func (r *Runtime) innerModuleEvaluation(
state *evaluationState,
m ModuleRecord, stack *[]CyclicModuleInstance, index uint,
resolve HostResolveImportedModuleFunc,
) (idx uint, err error) {
if len(*stack) > 100000 {
panic("too deep dependancy stack of 100000")
}
var cr CyclicModuleRecord
var ok bool
var c CyclicModuleInstance
if cr, ok = m.(CyclicModuleRecord); !ok {
p := m.Evaluate(r)
if p.state == PromiseStateRejected {
return index, p.Result().Export().(error)
}
r.modules[m] = p.Result().Export().(ModuleInstance) // TODO fix this cast ... somehow
return index, nil
}
if _, ok = r.modules[m]; ok {
return index, nil
}
c, err = cr.Instantiate(r)
if err != nil {
// state.evaluationError[cr] = err
// TODO handle this somehow - maybe just panic
return index, err
}
r.modules[m] = c
if status := state.status[c]; status == Evaluated {
return index, nil
} else if status == Evaluating || status == Evaluating_Async {
// maybe check evaluation error
return index, nil
}
state.status[c] = Evaluating
state.dfsIndex[c] = index
state.dfsAncestorIndex[c] = index
state.pendingAsyncDependancies[c] = 0
index++
*stack = append(*stack, c)
var requiredModule ModuleRecord
for _, required := range cr.RequestedModules() {
requiredModule, err = resolve(m, required)
if err != nil {
state.evaluationError[c] = err
return index, err
}
var requiredInstance ModuleInstance
index, err = r.innerModuleEvaluation(state, requiredModule, stack, index, resolve)
if err != nil {
return index, err
}
if requiredC, ok := requiredInstance.(CyclicModuleInstance); ok {
if state.status[requiredC] == Evaluating {
if ancestorIndex := state.dfsAncestorIndex[c]; state.dfsAncestorIndex[requiredC] > ancestorIndex {
state.dfsAncestorIndex[requiredC] = ancestorIndex
}
} else {
requiredC = state.cycleRoot[requiredC]
// check stuff
}
if state.asyncEvaluation[requiredC] {
state.pendingAsyncDependancies[c]++
state.asyncParentModules[requiredC] = append(state.asyncParentModules[requiredC], c)
}
}
}
if state.pendingAsyncDependancies[c] > 0 || c.HasTLA() {
state.asyncEvaluation[c] = true
if state.pendingAsyncDependancies[c] == 0 {
r.executeAsyncModule(state, c)
}
} else {
c, err = c.ExecuteModule(r, nil, nil)
if err != nil {
// state.evaluationError[c] = err
return index, err
}
}
if state.dfsAncestorIndex[c] == state.dfsIndex[c] {
for i := len(*stack) - 1; i >= 0; i-- {
requiredModuleInstance := (*stack)[i]
*stack = (*stack)[:i]
if !state.asyncEvaluation[requiredModuleInstance] {
state.status[requiredModuleInstance] = Evaluated
} else {
state.status[requiredModuleInstance] = Evaluating_Async
}
state.cycleRoot[requiredModuleInstance] = c
if requiredModuleInstance == c {
break
}
}
}
return index, nil
}
func (r *Runtime) executeAsyncModule(state *evaluationState, c CyclicModuleInstance) {
// implement https://262.ecma-international.org/13.0/#sec-execute-async-module
// TODO likely wrong
p, res, rej := r.NewPromise()
r.performPromiseThen(p, r.ToValue(func() {
r.asyncModuleExecutionFulfilled(state, c)
}), r.ToValue(func(err error) {
r.asyncModuleExecutionRejected(state, c, err)
}), nil)
c.ExecuteModule(r, res, rej)
}
func (r *Runtime) asyncModuleExecutionFulfilled(state *evaluationState, c CyclicModuleInstance) {
if state.status[c] == Evaluated {
return
}
state.asyncEvaluation[c] = false
// TODO fix this
for m, i := range r.modules {
if i == c {
if cap := state.topLevelCapability[m.(CyclicModuleRecord)]; cap != nil {
cap.resolve(_undefined)
}
break
}
}
execList := make([]CyclicModuleInstance, 0)
r.gatherAvailableAncestors(state, c, &execList)
// TODO sort? per when the modules got their AsyncEvaluation set ... somehow
for _, m := range execList {
if state.status[m] == Evaluated {
continue
}
if m.HasTLA() {
r.executeAsyncModule(state, m)
} else {
result, err := m.ExecuteModule(r, nil, nil)
if err != nil {
r.asyncModuleExecutionRejected(state, m, err)
continue
}
state.status[m] = Evaluated
if cap := state.topLevelCapability[r.findModuleRecord(c).(CyclicModuleRecord)]; cap != nil {
// TODO having the module instances going through Values and back is likely not a *great* idea
cap.resolve(r.ToValue(result))
}
}
}
}
func (r *Runtime) gatherAvailableAncestors(state *evaluationState, c CyclicModuleInstance, execList *[]CyclicModuleInstance) {
contains := func(m CyclicModuleInstance) bool {
for _, l := range *execList {
if l == m {
return true
}
}
return false
}
for _, m := range state.asyncParentModules[c] {
if contains(m) || state.evaluationError[m] != nil {
continue
}
state.pendingAsyncDependancies[m]--
if state.pendingAsyncDependancies[m] == 0 {
*execList = append(*execList, m)
if !m.HasTLA() {
r.gatherAvailableAncestors(state, m, execList)
}
}
}
}
func (r *Runtime) asyncModuleExecutionRejected(state *evaluationState, c CyclicModuleInstance, err error) {
if state.status[c] == Evaluated {
return
}
state.evaluationError[c] = err
state.status[c] = Evaluated
for _, m := range state.asyncParentModules[c] {
r.asyncModuleExecutionRejected(state, m, err)
}
// TODO handle top level capabiltiy better
if cap := state.topLevelCapability[r.findModuleRecord(c).(CyclicModuleRecord)]; cap != nil {
cap.reject(r.ToValue(err))
}
}
// TODO fix this whole thing
func (r *Runtime) findModuleRecord(i ModuleInstance) ModuleRecord {
for m, mi := range r.modules {
if mi == i {
return m
}
}
panic("this should never happen")
}
func (r *Runtime) GetActiveScriptOrModule() interface{} { // have some better type
if r.vm.prg != nil && r.vm.prg.scriptOrModule != nil {
return r.vm.prg.scriptOrModule
}
for i := len(r.vm.callStack) - 1; i >= 0; i-- {
prg := r.vm.callStack[i].prg
if prg.scriptOrModule != nil {
return prg.scriptOrModule
}
}
return nil
}
func (r *Runtime) getImportMetaFor(m ModuleRecord) *Object {
if r.importMetas == nil {
r.importMetas = make(map[ModuleRecord]*Object)
}
if o, ok := r.importMetas[m]; ok {
return o
}
o := r.NewObject()
o.SetPrototype(nil)
var properties []MetaProperty
if r.getImportMetaProperties != nil {
properties = r.getImportMetaProperties(m)
}
for _, property := range properties {
o.Set(property.Key, property.Value)
}
if r.finalizeImportMeta != nil {
r.finalizeImportMeta(o, m)
}
r.importMetas[m] = o
return o
}
type MetaProperty struct {
Key string
Value Value
}
func (r *Runtime) SetGetImportMetaProperties(fn func(ModuleRecord) []MetaProperty) {
r.getImportMetaProperties = fn
}
func (r *Runtime) SetFinalImportMeta(fn func(*Object, ModuleRecord)) {
r.finalizeImportMeta = fn
}
// TODO fix signature
type ImportModuleDynamicallyCallback func(referencingScriptOrModule interface{}, specifier Value, promiseCapability interface{})
func (r *Runtime) SetImportModuleDynamically(callback ImportModuleDynamicallyCallback) {
r.importModuleDynamically = callback
}
// TODO figure out the arguments
func (r *Runtime) FinalizeDynamicImport(m ModuleRecord, pcap interface{}, err interface{}) {
p := pcap.(*promiseCapability)
if err != nil {
switch x1 := err.(type) {
case *Exception:
p.reject(x1.val)
case *CompilerSyntaxError:
p.reject(r.builtin_new(r.global.SyntaxError, []Value{newStringValue(x1.Error())}))
case *CompilerReferenceError:
p.reject(r.newError(r.global.ReferenceError, x1.Message))
default:
p.reject(r.ToValue(err))
}
return
}
p.resolve(r.NamespaceObjectFor(m))
}