Repository navigation
Expand file tree
/
Copy pathdefinitions.py
More file actions
2741 lines (2318 loc) · 82.6 KB
/
Copy pathdefinitions.py
File metadata and controls
2741 lines (2318 loc) · 82.6 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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# After the Boilerplate section, this file is ordered to line up with the code
# blocks in ../CanonicalABI.md (split by # comment lines). If you update this
# file, don't forget to update ../CanonicalABI.md.
### Boilerplate
from dataclasses import dataclass
from typing import Optional, Callable, Literal
from enum import Enum, IntEnum
import math
import struct
import random
import threading
class Trap(BaseException): pass
class CoreWebAssemblyException(BaseException): pass
class Type: pass
class ValType(Type): pass
class ExternType(Type): pass
class CoreExternType(Type): pass
@dataclass
class CoreImportDecl:
module: str
field: str
t: CoreExternType
@dataclass
class CoreExportDecl:
name: str
t: CoreExternType
@dataclass
class ModuleType(ExternType):
imports: list[CoreImportDecl]
exports: list[CoreExportDecl]
@dataclass
class CoreFuncType(CoreExternType):
params: list[str]
results: list[str]
def __eq__(self, other):
return self.params == other.params and self.results == other.results
CoreValType = int | float
def types_match_values(ts, vs):
if len(ts) != len(vs):
return False
return all(type_matches_value(t, v) for t,v in zip(ts, vs))
def type_matches_value(t, v):
match t:
case 'i32' | 'i64': return type(v) == int
case 'f32' | 'f64': return type(v) == float
assert(False)
@dataclass
class CoreMemoryType(CoreExternType):
initial: list[int]
maximum: Optional[int]
@dataclass
class ExternDecl:
name: str
t: ExternType
@dataclass
class ComponentType(ExternType):
imports: list[ExternDecl]
exports: list[ExternDecl]
@dataclass
class InstanceType(ExternType):
exports: list[ExternDecl]
@dataclass
class FuncType(ExternType):
params: list[tuple[str,ValType]]
result: list[ValType|tuple[str,ValType]]
async_: bool = False
def param_types(self):
return self.extract_types(self.params)
def result_type(self):
return self.extract_types(self.result)
def extract_types(self, vec):
if len(vec) == 0:
return []
if isinstance(vec[0], ValType):
return vec
return [t for name,t in vec]
@dataclass
class PrimValType(ValType):
pass
class BoolType(PrimValType): pass
class S8Type(PrimValType): pass
class U8Type(PrimValType): pass
class S16Type(PrimValType): pass
class U16Type(PrimValType): pass
class S32Type(PrimValType): pass
class U32Type(PrimValType): pass
class S64Type(PrimValType): pass
class U64Type(PrimValType): pass
class F32Type(PrimValType): pass
class F64Type(PrimValType): pass
class CharType(PrimValType): pass
class StringType(PrimValType): pass
class ErrorContextType(ValType): pass
@dataclass
class ListType(ValType):
t: ValType
l: Optional[int] = None
@dataclass
class FieldType:
label: str
t: ValType
@dataclass
class RecordType(ValType):
fields: list[FieldType]
@dataclass
class TupleType(ValType):
ts: list[ValType]
@dataclass
class CaseType:
label: str
t: Optional[ValType]
@dataclass
class VariantType(ValType):
cases: list[CaseType]
@dataclass
class EnumType(ValType):
labels: list[str]
@dataclass
class OptionType(ValType):
t: ValType
@dataclass
class ResultType(ValType):
ok: Optional[ValType]
error: Optional[ValType]
@dataclass
class MapType(ValType):
k: ValType # <keytype>
v: ValType
@dataclass
class FlagsType(ValType):
labels: list[str]
@dataclass
class OwnType(ValType):
rt: ResourceType
@dataclass
class BorrowType(ValType):
rt: ResourceType
@dataclass
class StreamType(ValType):
t: Optional[ValType]
@dataclass
class FutureType(ValType):
t: Optional[ValType]
# START
def trap():
current_instance().store.lock_down()
raise Trap()
def trap_if(cond):
if cond:
trap()
## Component Instances
class ComponentInstance:
store: Store
handles: Table[ResourceHandle | Waitable | WaitableSet | ErrorContext]
threads: Table[Thread]
may_leave: bool
backpressure: int
num_waiting_to_enter: int
exclusive_thread: Optional[Thread]
def __init__(self, store):
self.store = store
self.handles = Table()
self.threads = Table()
self.may_leave = True
self.backpressure = 0
self.num_waiting_to_enter = 0
self.exclusive_thread = None
## Concurrency
### Stack Switching
class Continuation:
lock: threading.Lock
handler: Handler
class Handler:
lock: threading.Lock
current_thread: Thread
cont: Optional[Continuation]
result: Optional[Thread] | Trap
thread_local_handler = threading.local()
def new_already_acquired_lock() -> threading.Lock:
lock = threading.Lock()
lock.acquire()
return lock
def cont_new(f: Callable[[], Optional[Thread]]) -> Continuation:
cont = Continuation()
cont.lock = new_already_acquired_lock()
def thread_base():
cont.lock.acquire()
thread_local_handler.value = cont.handler
try:
result = f()
except Trap as t:
result = t
handler = thread_local_handler.value
handler.cont = None
handler.result = result
handler.lock.release()
threading.Thread(target = thread_base).start()
return cont
def resume(cont: Continuation, current_thread: Thread) -> \
tuple[Optional[Continuation], Optional[Thread]]:
handler = Handler()
handler.lock = new_already_acquired_lock()
handler.current_thread = current_thread
cont.handler = handler
cont.lock.release()
handler.lock.acquire()
if isinstance(handler.result, Trap):
raise handler.result
return (handler.cont, handler.result)
def block(switch_to: Optional[Thread] = None):
cont = Continuation()
cont.lock = new_already_acquired_lock()
handler = thread_local_handler.value
handler.cont = cont
handler.result = switch_to
handler.lock.release()
cont.lock.acquire()
thread_local_handler.value = cont.handler
def current_thread() -> Thread:
return thread_local_handler.value.current_thread
def current_task() -> Task:
return current_thread().task
def current_instance() -> ComponentInstance:
return current_task().inst
### Threads
class Thread:
cont: Optional[Continuation] | Literal['running']
ready_func: Optional[Callable[[], bool]]
task: Task
index: Optional[int]
storage: tuple[int,int]
cancellable: bool
def __init__(self, task, thread_func):
self.cont = cont_new(thread_func)
self.ready_func = None
self.task = task
self.index = None
self.storage = [0,0]
self.cancellable = False
assert(self.suspended())
def running(self):
return self.cont == 'running'
def exited(self):
return self.cont is None
def blocked(self):
return not (self.running() or self.exited())
def suspended(self):
return self.blocked() and self.ready_func is None
def waiting(self):
return self.blocked() and self.ready_func is not None
def ready(self):
return self.waiting() and self.ready_func()
def start_waiting(self, ready_func):
assert(self.ready_func is None)
self.ready_func = ready_func
self.task.inst.store.waiting.append(self)
def stop_waiting(self):
assert(self.waiting())
self.ready_func = None
self.task.inst.store.waiting.remove(self)
def resume_later(self):
assert(self.suspended())
self.start_waiting(ready_func = lambda: True)
assert(self.ready())
def resume(self):
assert(self.blocked())
if self.waiting():
self.stop_waiting()
thread = self
while thread is not None:
cont = thread.cont
thread.cont = 'running'
(thread.cont, thread) = resume(cont, thread)
assert(self.blocked() or self.exited())
def suspend(self):
assert(self.running())
block()
assert(self.running())
def wait_until(self, ready_func):
assert(self.running())
if ready_func() and not DETERMINISTIC_PROFILE and random.randint(0,1):
return
self.start_waiting(ready_func)
block()
assert(self.running())
def yield_(self):
return self.wait_until(ready_func = lambda: True)
def suspend_then_resume(self, other: Thread):
assert(self.running() and other.suspended())
block(switch_to = other)
assert(self.running())
def yield_then_resume(self, other: Thread):
assert(self.running() and other.suspended())
self.start_waiting(ready_func = lambda: True)
block(switch_to = other)
assert(self.running())
def suspend_then_promote(self, other: Thread):
assert(self.running())
if other.ready():
other.stop_waiting()
self.suspend_then_resume(other)
else:
self.suspend()
assert(self.running())
def yield_then_promote(self, other: Thread):
assert(self.running())
if other.ready():
other.stop_waiting()
self.yield_then_resume(other)
else:
self.yield_()
assert(self.running())
### Tasks
OnStart = Callable[[], list[any]]
OnResolve = Callable[[Optional[list[any]]], None]
OnCancel = Callable[[], None]
FuncInst = Callable[[OnStart, OnResolve], OnCancel]
class Task:
class State(Enum):
INITIAL = 1
STARTED = 2
PENDING_CANCEL = 3
CANCEL_DELIVERED = 4
RESOLVED = 5
ft: FuncType
opts: CanonicalOptions
inst: ComponentInstance
on_start: OnStart
on_resolve: OnResolve
state: State
num_borrows: int
implicit_thread: Optional[Thread]
threads: list[Thread]
def __init__(self, ft, opts, inst, on_start, on_resolve):
self.ft = ft
self.opts = opts
self.inst = inst
self.on_start = on_start
self.on_resolve = on_resolve
self.state = Task.State.INITIAL
self.num_borrows = 0
self.implicit_thread = None
self.threads = []
def needs_exclusive(self):
assert(self.ft.async_)
return not self.opts.async_ or self.opts.callback
def enter_implicit_thread(self):
assert(self.state == Task.State.INITIAL)
self.implicit_thread = current_thread()
if self.ft.async_:
def has_backpressure():
return (self.inst.backpressure > 0 or
(self.needs_exclusive() and self.inst.exclusive_thread is not None))
if has_backpressure() or self.inst.num_waiting_to_enter > 0:
self.inst.num_waiting_to_enter += 1
self.implicit_thread.wait_until(lambda: not has_backpressure())
self.inst.num_waiting_to_enter -= 1
if self.deliver_pending_cancel():
self.cancel()
return False
if self.needs_exclusive():
assert(self.inst.exclusive_thread is None)
self.inst.exclusive_thread = self.implicit_thread
self.register_thread(self.implicit_thread)
return True
def register_thread(self, thread):
assert(thread not in self.threads and thread.task is self)
self.threads.append(thread)
assert(thread.index is None)
thread.index = self.inst.threads.add(thread)
def exit_implicit_thread(self):
assert(current_thread() is self.implicit_thread)
self.unregister_thread(self.implicit_thread)
if self.ft.async_ and self.needs_exclusive():
assert(self.inst.exclusive_thread is self.implicit_thread)
self.inst.exclusive_thread = None
def unregister_thread(self, thread):
assert(thread in self.threads and thread.task is self)
self.threads.remove(thread)
if len(self.threads) == 0:
trap_if(self.state != Task.State.RESOLVED)
assert(self.num_borrows == 0)
assert(thread.index is not None)
self.inst.threads.remove(thread.index)
def request_cancellation(self):
if self.state == Task.State.INITIAL:
self.state = Task.State.PENDING_CANCEL
self.implicit_thread.resume()
assert(self.state == Task.State.RESOLVED)
else:
assert(self.state == Task.State.STARTED)
self.state = Task.State.PENDING_CANCEL
if self.implicit_thread.cancellable and self.implicit_thread.ready():
self.implicit_thread.resume()
def has_pending_cancel(self):
return self.state == Task.State.PENDING_CANCEL
def deliver_pending_cancel(self) -> bool:
if self.has_pending_cancel():
self.state = Task.State.CANCEL_DELIVERED
return True
else:
return False
def start(self) -> list[any]:
assert(self.state == Task.State.INITIAL)
self.state = Task.State.STARTED
return self.on_start()
def return_(self, result):
trap_if(self.state == Task.State.RESOLVED)
trap_if(self.num_borrows > 0)
assert(result is not None)
self.on_resolve(result)
self.state = Task.State.RESOLVED
def cancel(self):
trap_if(self.state != Task.State.CANCEL_DELIVERED)
trap_if(self.num_borrows > 0)
self.on_resolve(None)
self.state = Task.State.RESOLVED
## Embedding API
class Store:
waiting: list[Thread]
nesting_depth: int
lockdown: bool
def __init__(self):
self.waiting = []
self.nesting_depth = 0
self.lockdown = False
def is_locked_down(self):
return self.lockdown
def lock_down(self):
self.lockdown = True
def invoke(self, f: FuncInst, on_start: OnStart, on_resolve: OnResolve) -> OnCancel:
assert(not self.lockdown)
self.nesting_depth += 1
request_cancellation = f(on_start, on_resolve)
self.nesting_depth -= 1
def on_cancel():
assert(not self.lockdown)
self.nesting_depth += 1
request_cancellation()
self.nesting_depth -= 1
return on_cancel
CoreFuncInst = Callable[[list[CoreValType]], list[CoreValType]]
def lift(self, f: CoreFuncInst, ft: FuncType, opts: CanonicalOptions, inst: ComponentInstance) -> FuncInst:
def func_inst(on_start: OnStart, on_resolve: OnResolve) -> OnCancel:
assert(self.nesting_depth > 0)
on_cancel = canon_lift(f, ft, opts, inst, on_start, on_resolve)
assert(self.nesting_depth > 0)
return on_cancel
return func_inst
def lower(self, f: FuncInst, ft: FuncType, opts: CanonicalOptions, inst: ComponentInstance) -> CoreFuncInst:
def core_func_inst(args: list[CoreValType]) -> list[CoreValType]:
assert(inst is current_instance())
assert(self.nesting_depth > 0)
flat_results = canon_lower(f, ft, opts, args)
assert(self.nesting_depth > 0)
return flat_results
return core_func_inst
def tick(self):
assert(not self.lockdown)
assert(self.nesting_depth == 0)
self.nesting_depth += 1
candidates = { thread for thread in self.waiting if thread.ready() }
if candidates:
thread = random.choice(list(candidates))
thread.resume()
self.nesting_depth -= 1
## Canonical ABI Options
def ptr_size(ptr_type):
match ptr_type:
case 'i32':
return 4
case 'i64':
return 8
@dataclass
class MemInst:
bytes: bytearray
addrtype: Literal['i32', 'i64']
def __getitem__(self, i):
return self.bytes[i]
def __setitem__(self, i, v):
self.bytes[i] = v
def __len__(self):
return len(self.bytes)
def ptr_type(self):
return self.addrtype
def ptr_size(self):
return ptr_size(self.ptr_type())
@dataclass
class LiftOptions:
string_encoding: str = 'utf8'
memory: Optional[MemInst] = None
def equal(lhs, rhs):
return lhs.string_encoding == rhs.string_encoding and \
lhs.memory is rhs.memory
@dataclass
class LiftLowerOptions(LiftOptions):
realloc: Optional[Callable] = None
@dataclass
class CanonicalOptions(LiftLowerOptions):
post_return: Optional[Callable] = None
async_: bool = False
callback: Optional[Callable] = None
## Lifting and Lowering Context
class LiftLowerContext:
direction: Literal['lift', 'lower']
opts: LiftLowerOptions
inst: ComponentInstance
borrow_scope: Optional[Task|Subtask]
def __init__(self, direction, opts, inst, borrow_scope = None):
self.direction = direction
self.opts = opts
self.inst = inst
self.borrow_scope = borrow_scope
def reverse_direction(self):
new_direction = 'lift' if self.direction == 'lower' else 'lower'
return LiftLowerContext(new_direction, self.opts, self.inst, self.borrow_scope)
def reallocate(self, old, old_byte_length, alignment, new_byte_length):
ptrt = U32Type() if self.opts.memory.ptr_type() == 'i32' else U64Type()
ft = FuncType([ptrt, ptrt, ptrt, ptrt], [ptrt], async_ = False)
opts = CanonicalOptions(async_ = False)
realloc = self.inst.store.lift(self.opts.realloc, ft, opts, self.inst)
def on_start():
return [old, old_byte_length, alignment, new_byte_length]
ptr = None
def on_resolve(result):
nonlocal ptr
[ptr] = result
assert(self.inst.may_leave)
self.inst.may_leave = False
self.inst.store.invoke(realloc, on_start, on_resolve)
self.inst.may_leave = True
assert(ptr is not None)
trap_if(ptr != align_to(ptr, alignment))
trap_if(ptr + new_byte_length > len(self.opts.memory))
return ptr
def allocate(self, alignment, byte_length):
return self.reallocate(0, 0, alignment, byte_length)
## Runtime State
### Table State
class Table:
array: list[any]
free: list[int]
MAX_LENGTH = 2**28 - 1
def __init__(self):
self.array = [None]
self.free = []
def __iter__(self):
for e in self.array:
if e is not None:
yield e
def get(self, i):
trap_if(i >= len(self.array))
trap_if(self.array[i] is None)
return self.array[i]
def add(self, e):
if self.free:
i = self.free.pop()
assert(self.array[i] is None)
self.array[i] = e
else:
i = len(self.array)
trap_if(i > Table.MAX_LENGTH)
self.array.append(e)
return i
def remove(self, i):
e = self.get(i)
self.array[i] = None
self.free.append(i)
return e
### Resource State
class ResourceHandle:
rt: ResourceType
rep_val: int
own: bool
borrow_scope: Optional[Task]
num_lends: int
def __init__(self, rt, rep_val, own, borrow_scope = None):
self.rt = rt
self.rep_val = rep_val
self.own = own
self.borrow_scope = borrow_scope
self.num_lends = 0
class ResourceType(Type):
impl_inst: ComponentInstance
rep: Literal['i32', 'i64']
dtor: Optional[Callable]
def __init__(self, impl_inst, rep, dtor = None):
self.impl_inst = impl_inst
self.rep = rep
self.dtor = dtor
### Waitable State
class EventCode(IntEnum):
NONE = 0
SUBTASK = 1
STREAM_READ = 2
STREAM_WRITE = 3
FUTURE_READ = 4
FUTURE_WRITE = 5
TASK_CANCELLED = 6
EventTuple = tuple[EventCode, int, int]
class Waitable:
pending_event: Optional[Callable[[], EventTuple]]
wset: Optional[WaitableSet]
has_sync_waiter: bool
def __init__(self):
self.pending_event = None
self.wset = None
self.has_sync_waiter = False
def set_pending_event(self, pending_event):
self.pending_event = pending_event
def has_pending_event(self):
return bool(self.pending_event)
def in_waitable_set(self):
return self.wset is not None
def wait_for_pending_event(self):
assert(not self.in_waitable_set() and not self.has_sync_waiter)
self.has_sync_waiter = True
current_thread().wait_until(self.has_pending_event)
self.has_sync_waiter = False
def get_pending_event(self) -> EventTuple:
pending_event = self.pending_event
self.pending_event = None
return pending_event()
def join(self, wset):
assert(not self.has_sync_waiter)
if self.wset:
self.wset.elems.remove(self)
self.wset = wset
if wset:
wset.elems.append(self)
def drop(self):
assert(not self.has_sync_waiter)
self.join(None)
class WaitableSet:
elems: list[Waitable]
num_waiting: int
def __init__(self):
self.elems = []
self.num_waiting = 0
def has_pending_event(self):
return any(w.has_pending_event() for w in self.elems)
def get_pending_event(self) -> EventTuple:
assert(self.has_pending_event())
random.shuffle(self.elems)
for w in self.elems:
assert(self is w.wset)
if w.has_pending_event():
return w.get_pending_event()
def wait(self) -> EventTuple:
self.num_waiting += 1
current_thread().wait_until(self.has_pending_event)
self.num_waiting -= 1
return self.get_pending_event()
def poll(self) -> EventTuple:
if not self.has_pending_event():
return (EventCode.NONE, 0, 0)
else:
return self.get_pending_event()
def wait_from_callback(self) -> EventTuple:
thread = current_thread()
def ready():
return (thread.task.inst.exclusive_thread is None
and (self.has_pending_event() or thread.task.has_pending_cancel()))
self.num_waiting += 1
thread.wait_until(ready)
self.num_waiting -= 1
if thread.task.deliver_pending_cancel():
return (EventCode.TASK_CANCELLED, 0, 0)
else:
return self.get_pending_event()
def drop(self):
trap_if(len(self.elems) > 0)
trap_if(self.num_waiting > 0)
### Subtask State
class Subtask(Waitable):
class State(IntEnum):
STARTING = 0
STARTED = 1
RETURNED = 2
CANCELLED_BEFORE_STARTED = 3
CANCELLED_BEFORE_RETURNED = 4
state: State
on_cancel: Optional[OnCancel]
lenders: Optional[list[ResourceHandle]]
cancellation_requested: bool
flat_results: list[CoreValType]
def __init__(self):
Waitable.__init__(self)
self.state = Subtask.State.STARTING
self.on_cancel = None
self.lenders = []
self.cancellation_requested = False
self.flat_results = []
def resolved(self):
match self.state:
case (Subtask.State.STARTING |
Subtask.State.STARTED):
return False
case (Subtask.State.RETURNED |
Subtask.State.CANCELLED_BEFORE_STARTED |
Subtask.State.CANCELLED_BEFORE_RETURNED):
return True
def add_lender(self, lending_handle):
assert(not self.resolve_delivered() and not self.resolved())
lending_handle.num_lends += 1
self.lenders.append(lending_handle)
def resolve(self, state, flat_results):
assert(state == Subtask.State.RETURNED or flat_results == [])
assert(not self.resolved())
self.state = state
self.flat_results = flat_results
assert(self.resolved())
def deliver_resolve(self):
assert(not self.resolve_delivered() and self.resolved())
for h in self.lenders:
h.num_lends -= 1
self.lenders = None
def resolve_delivered(self):
assert(self.lenders is not None or self.resolved())
return self.lenders is None
def drop(self):
trap_if(not self.resolve_delivered())
Waitable.drop(self)
### Buffer State
class Buffer:
MAX_LENGTH = 2**28 - 1
t: ValType
remain: Callable[[], int]
class ReadableBuffer(Buffer):
read: Callable[[int], list[any]]
class WritableBuffer(Buffer):
write: Callable[[list[any]]]
class GuestBuffer(Buffer):
cx: LiftLowerContext
t: ValType
ptr: int
progress: int
length: int
def __init__(self, t, cx, ptr, length):
trap_if(length > Buffer.MAX_LENGTH)
if t is not None:
trap_if(ptr != align_to(ptr, alignment(cx, t)))
trap_if(ptr + length * elem_size(cx, t) > len(cx.opts.memory))
self.cx = cx
self.t = t
self.ptr = ptr
self.progress = 0
self.length = length
def remain(self):
return self.length - self.progress
class ReadableGuestBuffer(GuestBuffer, ReadableBuffer):
def read(self, n):
assert(n <= self.remain())
if self.t:
vs = load_list_from_valid_range(self.cx, self.ptr, n, self.t)
self.ptr += n * elem_size(self.cx, self.t)
else:
vs = n * [()]
self.progress += n
return vs
class WritableGuestBuffer(GuestBuffer, WritableBuffer):
def write(self, vs):
assert(len(vs) <= self.remain())
if self.t:
store_list_into_valid_range(self.cx, vs, self.ptr, self.t)
self.ptr += len(vs) * elem_size(self.cx, self.t)
else:
assert(all(v == () for v in vs))
self.progress += len(vs)
### Stream and Future State
class End(Waitable):
class State(Enum):
IDLE = 1
COPYING = 2
CANCELLING_COPY = 3
DONE = 4
t: ValType
state: State
other: Optional[End]
buffer: Optional[Buffer]
owner: Optional[ComponentInstance]
index: Optional[int]
event_code: EventCode
def __init__(self, t, owner, event_code):
Waitable.__init__(self)
self.t = t
self.state = End.State.IDLE
self.other = None
self.buffer = None
self.owner = owner
self.index = None
self.event_code = event_code
def copy(self, buffer: Buffer, is_read: bool):
assert(self.buffer is None)
self.state = End.State.COPYING
if self.other is None:
assert(self.has_pending_event())
elif self.other.buffer is None:
self.buffer = buffer
else:
trap_if(self.owner and self.owner is self.other.owner and not none_or_number_type(self.t))
if buffer.remain() > 0 and self.other.buffer.remain() > 0:
n = min(buffer.remain(), self.other.buffer.remain())
if is_read:
buffer.write(self.other.buffer.read(n))
else:
self.other.buffer.write(buffer.read(n))
self.notify(buffer.progress)
self.other.notify(self.other.buffer.progress)
if self.other.buffer.remain() == 0:
self.other.buffer = None
elif buffer.remain() > 0 or (is_read and self.other.buffer.remain() == 0):
self.other.notify(progress = 0)
self.other.buffer = None
self.buffer = buffer
else:
self.notify(progress = 0)
def cancel(self):
assert(self.state == End.State.COPYING)
self.state = End.State.CANCELLING_COPY
if (not self.has_pending_event()
and (self.other.owner is not None
or DETERMINISTIC_PROFILE
or random.randint(0,1))):
self.notify(progress = 0)