-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcontrol-flow.ts
557 lines (466 loc) · 12.8 KB
/
control-flow.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import type { Func, LocalsById, Param, ProgramState } from "../types"
import type { State } from '../state'
import type { Instruction } from "./instructions"
import type { Wasm, WasmValue, Satisfies, evaluate } from 'ts-type-math'
export type IBlock = {
kind: "Block"
/** a block identifier */
id: string
instructions: Instruction[]
}
export type IBranch = {
kind: "Branch"
/** a block identifier */
id: string
}
export type IBranchIf = {
kind: "BranchIf"
/** a block identifier */
id: string
}
export type IBranchTable = {
kind: "BranchTable"
/** a block identifier */
branches: Record<WasmValue, WasmValue>
default: string
}
export type ICall = {
kind: "Call"
/** a function identifier */
id: string
}
export type ICallIndirect = {
kind: "CallIndirect"
/** a function identifier */
id: string
}
export type IDrop = {
kind: "Drop"
}
export type IIf = {
kind: "If"
then: Instruction[]
else?: Instruction[]
}
export type ILoop = {
kind: "Loop"
id: string
instructions: Instruction[]
}
export type INop = {
kind: "Nop"
ziltoid: "theOmniscient"
}
export type IReturn = {
kind: "Return"
/** the number of items to return */
count: number
}
export type ISelect = {
kind: "Select"
}
export type IUnreachable = {
kind: "Unreachable"
}
export type ControlFlowInstruction =
| IBlock
| IBranch
| IBranchIf
| IBranchTable
| ICall
| ICallIndirect
| IDrop
| IIf
| ILoop
| INop
| IReturn
| ISelect
| IUnreachable
export type HandleControlFlowInstructions<
instruction extends ControlFlowInstruction,
state extends ProgramState
> = Satisfies<ProgramState,
instruction extends IBlock
? Block<instruction, state>
: instruction extends IBranch
? Branch<instruction, state>
: instruction extends IBranchIf
? BranchIf<instruction, state>
: instruction extends IBranchTable
? BranchTable<instruction, state>
: instruction extends ICall
? Call<instruction, state>
: instruction extends ICallIndirect
? CallIndirect<instruction, state>
: instruction extends IDrop
? Drop<instruction, state>
: instruction extends IIf
? If<instruction, state>
: instruction extends ILoop
? Loop<instruction, state>
: instruction extends INop
? Nop<instruction, state>
: instruction extends IReturn
? Return<instruction, state>
: instruction extends ISelect
? Select<instruction, state>
: instruction extends IUnreachable
? Unreachable<instruction, state>
: State.error<"unknown control-flow instruction", instruction, state>
>
export type Block<
instruction extends IBlock,
state extends ProgramState
> = Satisfies<ProgramState,
// then push the block's instructions onto the stack
State.Instructions.concat<
instruction['instructions'],
// first cache existing instructions (as they are at this moment) in the execution context for when we break to this block later
State.ExecutionContexts.Active.Branches.insert<
instruction['id'],
[
// this will trigger clearing this block from the activeBranches when we hit the EndBlock instruction
{ kind: 'EndBlock', id: instruction['id'] },
...state['instructions']
],
state
>
>
>
export type Branch<
instruction extends IBranch,
state extends ProgramState,
> = Satisfies<ProgramState,
State.Instructions.set<
state['activeBranches'][instruction['id']],
state
>
>
export type BranchIf<
instruction extends IBranchIf,
state extends ProgramState
> = Satisfies<ProgramState,
state['stack'] extends [
...infer remaining extends WasmValue[],
infer condition extends WasmValue,
]
? Wasm.I32Eqz<condition> extends Wasm.I32True
// false branch
// nothing happens. we just pop the stack and endLoop on to the next instruction
? State.Stack.set<
remaining,
state
>
// true branch
// true indicates we _want_ to branch back. so we do!
: State.Instructions.set<
state['activeBranches'][instruction['id']],
State.Stack.set<
remaining,
state
>
>
: State.error<"stack exhausted", instruction, state>
>
export type BranchTable<
instruction extends IBranchTable,
state extends ProgramState
> = Satisfies<ProgramState,
state['stack'] extends [
...infer remaining extends WasmValue[],
infer index extends WasmValue,
]
// the whole reason `BranchTable.branches` is an object instead of an array is to make it easy to check membership like we are here. if there's a more efficient way to do this: that'd be great
? index extends keyof instruction['branches']
// match found
?
State.Instructions.set<
state['activeBranches'][instruction['branches'][index]],
State.Stack.set<
remaining,
state
>
>
// no match found fallback to the default
: State.Instructions.set<
state['activeBranches'][instruction['default']],
State.Stack.set<
remaining,
state
>
>
: State.error<"stack exhausted", instruction, state>
>
type Refreshment = {
params: Param[],
stack: WasmValue[],
locals: LocalsById,
}
type Refresh<T extends Refreshment> =
T['params'] extends [
...infer remainingParams extends Param[],
infer param extends Param,
]
? T['stack'] extends [
...infer remainingStack extends WasmValue[],
infer pop extends WasmValue,
]
? Refresh<{
params: remainingParams,
stack: remainingStack,
locals: T['locals'] & {
[k in param]: pop
}
}>
: never // should never happen because the stack should always have at least as many items as there are params
: evaluate<T>
export type Call<
instruction extends ICall,
state extends ProgramState,
_func extends Func = state['funcs'][instruction['id']],
_funcId extends string = instruction['id'],
// pop things off the stack to populate params
_refreshment extends Refreshment = Refresh<{
params: _func['params'],
stack: state['stack'],
locals: {}
}>
> = Satisfies<ProgramState,
// push a new execution context for the old function we're just leaving
State.ExecutionContexts.push<
{
locals: _refreshment['locals'], // even though there may be known locals for the function (in addition to params), they are added when they're set with LocalSet
funcId: _funcId,
branches: {},
stackDepth: _refreshment['stack']['length'],
instructions: [], // we will capture current instructions in the State.ExecutionContexts.push helper
},
[
// set instructions from this func onto the instructions stack
// it's VERY important that this happens AFTER the execution context has a chance to capture the current instructions
..._func['instructions'],
// add this synthetic for when we hit the end
{ kind: 'EndFunction', id: _funcId }
],
State.Stack.set<
_refreshment['stack'],
State.CallHistory.record<
_funcId,
state
>
>
>
>
export type CallIndirect<
instruction extends ICallIndirect,
state extends ProgramState
> = Satisfies<ProgramState,
state['stack'] extends [
...infer remainder extends WasmValue[],
infer address extends WasmValue,
]
? state['indirect'][address] extends infer nextFunc extends WasmValue
? State.Instructions.unshift<
{ kind: 'Call', id: nextFunc },
State.Stack.set<
remainder,
state
>
>
: State.error<"CallIndirect instruction expects an address on the stack that points to a function", instruction, state>
: State.error<"CallIndirect instruction expects an address on the stack", instruction, state>
>
export type Drop<
instruction extends IDrop, // unused
state extends ProgramState
> = Satisfies<ProgramState,
state['stack'] extends [
...infer remaining extends WasmValue[],
infer drop extends WasmValue, // dropped instruction
]
? State.Stack.set<
remaining,
state
>
: State.error<"stack exhausted", instruction, state>
>
export type If<
instruction extends IIf,
state extends ProgramState
> = Satisfies<ProgramState,
state['stack'] extends [
...infer remaining extends WasmValue[],
infer condition extends WasmValue,
]
? // according to the WASM spec, a condition must be an i32
Wasm.I32Eqz<condition> extends Wasm.I32True
? // false branch
// pop the false branch instructions
instruction['else'] extends Instruction[]
? State.Instructions.concat<
instruction['else'],
// pop the condition (we're done with it now)
State.Stack.set<
remaining,
state
>
>
:
// pop the condition (we're done with it now)
State.Stack.set<
remaining,
state
>
: // true branch
// pop the false branch instructions
State.Instructions.concat<
instruction['then'],
// pop the condition (we're done with it now)
State.Stack.set<
remaining,
state
>
>
: State.error<"stack exhausted", instruction, state>
>
export type Loop<
instruction extends ILoop,
state extends ProgramState,
_withEndLoop extends Instruction[] = [
...instruction['instructions'],
{
kind: 'EndLoop',
id: instruction['id'],
// store the instructions _for this loop_ in the endLoop instruction in case we wanna revisit again later
instructions: state['instructions'],
}
]
> = Satisfies<ProgramState,
// State.debug<
// [
// 'anything I want',
// state['activeBranches'],
// ],
// cache this loop's following instructions for when we (more than likely) Branch to it later
State.ExecutionContexts.Active.Branches.insert<
instruction['id'],
_withEndLoop,
State.Instructions.concat<
_withEndLoop,
state
>
>
>
// >
export type Nop<
instruction extends INop, // unused
state extends ProgramState
> = Satisfies<ProgramState,
state
>
/**
* 1. remove the number of elements from the stack that the function returns
* 2. remove values from the stack until you get it to activeStackDepth
* - make sure you accumulate them with prepend logic
* 3. append the temporary return (_Acc) to the stack
* 4. pop instructions until you reach a `EndFunction` instruction
*/
export type Return<
instruction extends IReturn,
state extends ProgramState,
_Acc extends WasmValue[] = [],
> = Satisfies<ProgramState,
// step 1's check
_Acc['length'] extends instruction['count']
? // we can proceed to step 2
// step 2's check
state['stack']['length'] extends state['activeStackDepth']
? // we can proceed to step 3
// step 3
State.Stack.set<
[
...state['stack'],
..._Acc, // we already prepended, so we can put it here normally
],
// step 4: unshift an `EndFunction` instruction
State.Instructions.unshift<
{
kind: 'EndFunction',
id: state['activeFuncId']
},
state
>
>
: // we need to recurse more to grab more values off the stack
state['stack'] extends [
...infer remaining extends WasmValue[],
infer pop extends WasmValue,
]
? // add this value to the accumulator
Return<
instruction,
State.Stack.set<
remaining,
state
>,
_Acc // don't need to touch step 1's stuff
>
: State.error<"stack exhausted", instruction, state>
: // step 1's logic: grab more values off the stack
state['stack'] extends [
...infer remaining extends WasmValue[],
infer pop extends WasmValue,
]
? // add this value to the accumulator
Return<
instruction,
State.Stack.set<
remaining,
state
>,
[
pop, // MUCHO IMPORTANTE!! - PREPEND LOGIC!!
..._Acc,
]
>
: State.error<"stack exhausted", instruction, state>
>
export type Select<
instruction extends ISelect, // unused
state extends ProgramState
> = Satisfies<ProgramState,
state['stack'] extends [
...infer remaining extends WasmValue[],
infer b extends WasmValue,
infer a extends WasmValue,
infer condition extends WasmValue,
]
? Wasm.I32Eqz<condition> extends Wasm.I32True
? State.Stack.set<
[
...remaining,
a,
],
state
>
: State.Stack.set<
[
...remaining,
b,
],
state
>
: State.error<"stack exhausted", instruction, state>
>
export type Unreachable<
instruction extends IUnreachable,
state extends ProgramState
> = Satisfies<ProgramState,
State.Instructions.unshift<
{
kind: 'Halt',
reason: "reached an Unreachable instruction. you prolly deserve the debugging session that's coming next"
},
state
>
>