-
Notifications
You must be signed in to change notification settings - Fork 47
/
index.ts
478 lines (460 loc) · 16.3 KB
/
index.ts
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
import State from '../state'
import { OP, SIGNAL } from '../share/const'
import { getDptor, define, inherits, getGetter, getSetter } from '../share/utils'
function step(state: State) {
const stack = state.stack
const code = state.opCodes[state.pc]
let signal = SIGNAL.NONE
switch (code.op) {
case OP.LOADK: stack[state.esp++] = code.val; break
case OP.LOADV: {
const value = state.context[code.val] && state.context[code.val].store
if (code.this && value['#sval_super_called#'] === false) {
throw new ReferenceError("Must call super constructor in derived class before accessing 'this'")
}
stack[state.esp++] = value
break
}
case OP.ALLOC: {
const ebp = state.ebpList[state.ebpList.length - 1]
const storeVal = state.esp > ebp ? stack[--state.esp] : undefined
state.context[code.val] = { store: storeVal }
if (!ebp) {
const globalPointer = state.symbols.get('window').pointer
const globalVariable = state.context[globalPointer].store
const globalVarName = state.symbols.globalVarName[code.val]
define(globalVariable, globalVarName, { value: storeVal, writable: true, enumerable: true })
}
break
}
case OP.STORE: state.context[code.val].store = stack[--state.esp]; break
case OP.BIOP: {
const right = stack[--state.esp]
const left = stack[--state.esp]
switch (code.val) {
// very often used
case '+': stack[state.esp++] = left + right; break
case '-': stack[state.esp++] = left - right; break
case '*': stack[state.esp++] = left * right; break
case '/': stack[state.esp++] = left / right; break
case '==': stack[state.esp++] = left == right; break
case '!=': stack[state.esp++] = left != right; break
case '===': stack[state.esp++] = left === right; break
case '!==': stack[state.esp++] = left !== right; break
case '<': stack[state.esp++] = left < right; break
case '<=': stack[state.esp++] = left <= right; break
case '>': stack[state.esp++] = left > right; break
case '>=': stack[state.esp++] = left >= right; break
case '||': stack[state.esp++] = left || right; break
case '&&': stack[state.esp++] = left && right; break
case 'in': stack[state.esp++] = left in right; break
case 'instanceof': stack[state.esp++] = left instanceof right; break
// not quite often used
case '**': stack[state.esp++] = left ** right; break
case '%': stack[state.esp++] = left % right; break
case '|': stack[state.esp++] = left | right; break
case '^': stack[state.esp++] = left ^ right; break
case '&': stack[state.esp++] = left & right; break
case '<<': stack[state.esp++] = left << right; break
case '>>': stack[state.esp++] = left >> right; break
case '>>>': stack[state.esp++] = left >>> right; break
default: throw new SyntaxError(`Unexpected token ${code.val}`)
}
break
}
case OP.UNOP: {
const arg = stack[--state.esp]
switch (code.val) {
case '+': stack[state.esp++] = +arg; break
case '-': stack[state.esp++] = -arg; break
case '!': stack[state.esp++] = !arg; break
case '~': stack[state.esp++] = ~arg; break
case 'void': stack[state.esp++] = void arg; break
case 'typeof': stack[state.esp++] = typeof arg; break
case 'delete': throw new SyntaxError('delete is not implemented')
default: throw new SyntaxError(`Unexpected token ${code.val}`)
}
break
}
case OP.JMP: state.pc = code.val - 1; break
case OP.IF: stack[--state.esp] && (state.pc = code.val - 1); break
case OP.IFNOT: !stack[--state.esp] && (state.pc = code.val - 1); break
case OP.CSNE: stack[--state.esp] !== stack[state.esp - 1] && (state.pc = code.val - 1); break
case OP.ARR: {
const spread = code.val.concat()
const newEsp = state.esp - spread.pop()
const arrItems = stack.slice(newEsp, state.esp)
state.esp = newEsp
let arr: any[] = []
for (let i = 0; i < arrItems.length; i++) {
if (spread.indexOf(i) === -1) {
arr.push(arrItems[i])
} else {
arr = [...arr, ...arrItems[i]]
}
}
stack[state.esp++] = arr
break
}
case OP.OBJ: {
const object: any = {}
const propKinds = code.val
const newEsp = state.esp - propKinds.length * 2
const keyValue = stack.slice(newEsp, state.esp)
state.esp = newEsp
for (let i = 0; i < propKinds.length * 2; i += 2) {
const key = keyValue[i]
const value = keyValue[i + 1]
const kind = propKinds[i / 2]
if (kind === 'init') {
object[key] = value
} else if (kind === 'get') {
const oriDptor = getDptor(object, key)
define(object, key, {
get: value,
set: oriDptor && oriDptor.set,
enumerable: true,
configurable: true
})
} else if (kind === 'set') {
const oriDptor = getDptor(object, key)
define(object, key, {
get: oriDptor && oriDptor.get,
set: value,
enumerable: true,
configurable: true
})
} else { // kind === 'sprd'
Object.assign(object, value)
}
}
stack[state.esp++] = object
break
}
case OP.MGET: {
const key = stack[--state.esp]
const object = stack[--state.esp]
if (object == undefined) {
throw new TypeError(`Cannot read property '${key}' of ${object}`)
}
const superProto = code.val && stack[--state.esp]
const getter = getGetter(superProto || object, key)
stack[state.esp++] = getter ? getter.call(object) : object[key]
break
}
case OP.MSET: {
const key = stack[--state.esp]
const object = stack[--state.esp]
if (object == undefined) {
throw new TypeError(`Cannot set property '${key}' of ${object}`)
}
const superProto = code.val && stack[--state.esp]
const value = stack[--state.esp]
const setter = getSetter(superProto || object, key)
setter ? setter.call(object, value) : object[key] = value
break
}
case OP.REST: {
if (code.val === 'obj') {
const newEsp = state.esp - code.remove
const rmKeys = stack.slice(newEsp, state.esp)
state.esp = newEsp
const object = Object.assign({}, stack[--state.esp])
for (let i = 0; i < rmKeys.length; i++) {
delete object[rmKeys[i]]
}
stack[state.esp++] = object
} else if (code.val === 'arr') {
const arr = stack[--state.esp].slice(code.remove)
stack[state.esp++] = arr
} else { // code.val === 'func'
const newEsp = state.ebpList[state.ebpList.length - 1]
stack[state.esp++] = stack.slice(newEsp, state.esp).reverse()
state.esp = newEsp
}
break
}
case OP.KOVS: {
const kovs = []
if (code.val) {
for (const key in stack[--state.esp]) {
kovs.push(key)
}
} else {
const iterator = stack[--state.esp]
if (!iterator[Symbol.iterator]) {
throw new TypeError(`${JSON.stringify(iterator)} is not iterable`)
}
for (const value of iterator) {
kovs.push(value)
}
}
stack[state.esp++] = kovs
stack[state.esp++] = kovs.length
break
}
case OP.FUNC: {
const beginPc = state.pc + 1 // the begin pc
const endPc = code.end // the end pc
const lexicalCtx = state.context.concat() // reserve the lexical context for function
if (!code.generator && !code.async) {
const func = function () {
for (let i = arguments.length - 1; i > -1; i--) {
stack[state.esp++] = arguments[i] // load arguments
}
if (!code.arrow) {
stack[state.esp++] = arguments // load argument array itself
stack[state.esp++] = this // load this
}
const resetPc = state.pc // reserve the current pc
const resetCtx = state.context // reserve the current context
state.pc = beginPc // offset pc to the function op codes
state.context = lexicalCtx // set the context as the lexical context of function
let signal = SIGNAL.NONE
let ret: any
while (state.pc < endPc) {
signal = step(state)
if (signal === SIGNAL.RET) {
ret = stack[--state.esp]
break
}
}
state.pc = resetPc // reset to the current pc
state.context = resetCtx // reset to the current context
return ret
}
define(func, 'name', {
value: code.val,
configurable: true
})
define(func, 'length', {
value: code.length,
configurable: true
})
stack[state.esp++] = func
} else {
// const tmpFunc = function* () {
// for (let i = arguments.length - 1; i > -1; i--) {
// stack[state.esp++] = arguments[i] // load arguments
// }
// if (!code.arrow) {
// stack[state.esp++] = arguments // load argument array itself
// stack[state.esp++] = this // load this
// }
// const resetPc = state.pc // reserve the current pc
// const resetCtx = state.context // reserve the current context
// state.pc = beginPc // offset pc to the function op codes
// state.context = lexicalCtx // set the context as the lexical context of function
// while (state.pc < endPc) {
// const s = step(state)
// if (s === SIGNAL.RET) break
// else if (s === SIGNAL.YIELD) yield
// }
// state.pc = resetPc // reset to the current pc
// state.context = resetCtx // reset to the current context
// }
// if (code.async && code.generator) {
// stack[state.esp++] = function (: AsyncIterator<any> {
// const iterator = tmpFunc.apply(void 0, arguments)
// let last: Promise<any> = Promise.resolve()
// let hasCatch = false
// const run = (opts: runAsyncOptions) =>
// last = last
// .then(() => runAsync(iterator, assign({ fullRet: true }, opts)))
// .catch(err => {
// if (!hasCatch) {
// hasCatch = true
// return Promise.reject(err)
// }
// })
// const asyncIterator: AsyncIterator<any> = {
// next: (res?: any) => run({ res }),
// throw: (err?: any) => run({ err }),
// return: (ret?: any) => run({ ret })
// }
// if (typeof Symbol === 'function') {
// (asyncIterator as any)[Symbol.iterator] = function () { return this }
// }
// return asyncIterator
// })
// } else if (code.async) {
// stack[state.esp++] = function ( {
// return runAsync(tmpFunc.apply(void 0, arguments))
// })
// } else {
// stack[state.esp++] = tmpFunc
// }
}
state.pc = endPc - 1
break
}
case OP.CLS: {
let superClass: any = null
if (code.inherit) {
superClass = stack[--state.esp]
}
let classCtor: any = null
if (code.constructor) {
classCtor = stack[--state.esp]
}
let ctor = function () {
if (classCtor) {
if (superClass) {
define(this, '#sval_super_called#', { value: false, configurable: true })
}
const result = classCtor.apply(this, arguments)
if (superClass) {
if (!this['#sval_super_called#']) {
throw new ReferenceError('Must call super constructor in derived class before returning from derived constructor')
}
delete this['#sval_super_called#']
}
return result
} else if (superClass) {
return superClass.apply(this, arguments)
}
}
if (superClass) {
inherits(ctor, superClass)
}
define(ctor, 'name', {
value: code.val,
configurable: true
})
define(ctor, '#sval_es6_class#', { value: true })
stack[state.esp++] = ctor
break
}
case OP.CMET: {
const key = stack[--state.esp]
const met = stack[--state.esp]
const obj = code.static ? stack[state.esp - 1] : stack[state.esp - 1].prototype
switch (code.val) {
case 'get': {
const oriDptor = getDptor(obj, key)
define(obj, key, {
get: met,
set: oriDptor && oriDptor.set,
configurable: true,
})
break
}
case 'set': {
const oriDptor = getDptor(obj, key)
define(obj, key, {
get: oriDptor && oriDptor.get,
set: met,
configurable: true,
})
break
}
default: // kind is 'method'
define(obj, key, {
value: met,
writable: true,
configurable: true,
})
}
break
}
case OP.CALL: {
const func = stack[--state.esp]
if (!code.super && func['#sval_es6_class#']) {
throw new TypeError(`Class constructor ${func.name} cannot be invoked without 'new'`)
}
const obj = stack[--state.esp]
if (code.super) {
if (obj['#sval_super_called#']) {
throw new ReferenceError('Super constructor may only be called once')
}
define(obj, '#sval_super_called#', { value: true, configurable: true })
}
const spread = code.val.concat()
const newEsp = state.esp - spread.pop()
const argsItems = stack.slice(newEsp, state.esp)
state.esp = newEsp
let args: any[] = []
for (let i = 0; i < argsItems.length; i++) {
if (spread.indexOf(i) === -1) {
args.push(argsItems[i])
} else {
args = [...args, ...argsItems[i]]
}
}
// push ebp here instead of inside functions
// to avoid a wrong ebp list caused by throwing error in functions
state.ebpList.push(state.esp)
let result: any
if (code.catch) {
try {
result = func.apply(obj, args)
} catch (err) {
result = err
state.pc = code.catch.pc - 1
}
} else {
result = func.apply(obj, args)
}
state.esp = state.ebpList.pop()
stack[state.esp++] = result
break
}
case OP.NEW: {
const ctor = stack[--state.esp]
const spread = code.val.concat()
const newEsp = state.esp - spread.pop()
const argsItems = stack.slice(newEsp, state.esp)
state.esp = newEsp
let args: any[] = []
for (let i = 0; i < argsItems.length; i++) {
if (spread.indexOf(i) === -1) {
args.push(argsItems[i])
} else {
args = [...args, ...argsItems[i]]
}
}
// push ebp here instead of inside functions
// to avoid a wrong ebp list caused by throwing error in functions
state.ebpList.push(state.esp)
let result: any
if (code.catch) {
try {
result = new ctor(...args)
} catch (err) {
result = err
state.pc = code.catch.pc - 1
}
} else {
result = new ctor(...args)
}
state.esp = state.ebpList.pop()
stack[state.esp++] = result
break
}
case OP.RET: signal = SIGNAL.RET; break
case OP.YIELD: signal = SIGNAL.YIELD; break
case OP.AWAIT: signal = SIGNAL.AWAIT; break
case OP.COPY: {
const top = stack[state.esp - 1]
stack[state.esp++] = top
break
}
case OP.POP: --state.esp; break
case OP.DBG: debugger; break
case OP.THROW: {
if (code.val) {
state.pc = code.val.pc - 1
break
} else {
throw stack[--state.esp]
}
}
case OP.GC: state.esp = state.ebpList[state.ebpList.length - 1]; break
default: throw new Error('Unknown instruct code')
}
state.pc++
return signal
}
export default function execute(state: State) {
while (state.pc < state.opCodes.length) step(state)
}