-
Notifications
You must be signed in to change notification settings - Fork 82
/
definitions.py
2091 lines (1795 loc) · 64.9 KB
/
definitions.py
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 __future__ import annotations
from dataclasses import dataclass
from functools import partial
from typing import Any, Optional, Callable, Awaitable, Literal, MutableMapping, TypeVar, Generic
from enum import IntEnum
from copy import copy
import math
import struct
import random
import asyncio
class Trap(BaseException): pass
class CoreWebAssemblyException(BaseException): pass
def trap():
raise Trap()
def trap_if(cond):
if cond:
raise Trap()
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
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]]
results: list[ValType|tuple[str,ValType]]
def param_types(self):
return self.extract_types(self.params)
def result_types(self):
return self.extract_types(self.results)
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 FlagsType(ValType):
labels: list[str]
@dataclass
class OwnType(ValType):
rt: ResourceType
@dataclass
class BorrowType(ValType):
rt: ResourceType
@dataclass
class StreamType(ValType):
t: ValType
@dataclass
class FutureType(ValType):
t: ValType
### Lifting and Lowering Context
class LiftLowerContext:
opts: CanonicalOptions
inst: ComponentInstance
borrow_scope: Optional[Task|Subtask]
def __init__(self, opts, inst, borrow_scope = None):
self.opts = opts
self.inst = inst
self.borrow_scope = borrow_scope
### Canonical ABI Options
@dataclass
class CanonicalOptions:
memory: Optional[bytearray] = None
string_encoding: Optional[str] = None
realloc: Optional[Callable] = None
post_return: Optional[Callable] = None
sync: bool = True # = !canonopt.async
callback: Optional[Callable] = None
always_task_return: bool = False
### Runtime State
class ComponentInstance:
resources: ResourceTables
waitables: Table[Subtask|StreamHandle|FutureHandle]
error_contexts: Table[ErrorContext]
num_tasks: int
may_leave: bool
backpressure: bool
interruptible: asyncio.Event
pending_tasks: list[tuple[Task, asyncio.Future]]
starting_pending_task: bool
def __init__(self):
self.resources = ResourceTables()
self.waitables = Table[Subtask|StreamHandle|FutureHandle]()
self.error_contexts = Table[ErrorContext]()
self.num_tasks = 0
self.may_leave = True
self.backpressure = False
self.interruptible = asyncio.Event()
self.interruptible.set()
self.pending_tasks = []
self.starting_pending_task = False
#### Resource State
class ResourceTables:
rt_to_table: MutableMapping[ResourceType, Table[ResourceHandle]]
def __init__(self):
self.rt_to_table = dict()
def table(self, rt):
if rt not in self.rt_to_table:
self.rt_to_table[rt] = Table[ResourceHandle]()
return self.rt_to_table[rt]
def get(self, rt, i):
return self.table(rt).get(i)
def add(self, rt, h):
return self.table(rt).add(h)
def remove(self, rt, i):
return self.table(rt).remove(i)
class ResourceType(Type):
impl: ComponentInstance
dtor: Optional[Callable]
dtor_sync: bool
dtor_callback: Optional[Callable]
def __init__(self, impl, dtor = None, dtor_sync = True, dtor_callback = None):
self.impl = impl
self.dtor = dtor
self.dtor_sync = dtor_sync
self.dtor_callback = dtor_callback
ElemT = TypeVar('ElemT')
class Table(Generic[ElemT]):
array: list[Optional[ElemT]]
free: list[int]
MAX_LENGTH = 2**30 - 1
def __init__(self):
self.array = [None]
self.free = []
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
class ResourceHandle:
rep: int
own: bool
borrow_scope: Optional[Task]
lend_count: int
def __init__(self, rep, own, borrow_scope = None):
self.rep = rep
self.own = own
self.borrow_scope = borrow_scope
self.lend_count = 0
#### Task State
class CallState(IntEnum):
STARTING = 0
STARTED = 1
RETURNED = 2
DONE = 3
class EventCode(IntEnum):
CALL_STARTING = CallState.STARTING
CALL_STARTED = CallState.STARTED
CALL_RETURNED = CallState.RETURNED
CALL_DONE = CallState.DONE
YIELDED = 4
STREAM_READ = 5
STREAM_WRITE = 6
FUTURE_READ = 7
FUTURE_WRITE = 8
EventTuple = tuple[EventCode, int, int]
EventCallback = Callable[[], Optional[EventTuple]]
OnBlockCallback = Callable[[Awaitable], Awaitable]
current_task = asyncio.Lock()
asyncio.run(current_task.acquire())
async def default_on_block(f):
current_task.release()
v = await f
await current_task.acquire()
return v
class Blocked: pass
class Returned: pass
async def call_and_handle_blocking(callee, *args) -> Blocked|Returned:
ret = asyncio.Future[Blocked|Returned]()
async def on_block(f):
if not ret.done():
ret.set_result(Blocked())
else:
current_task.release()
v = await f
await current_task.acquire()
return v
async def do_call():
await callee(*args, on_block)
if not ret.done():
ret.set_result(Returned())
else:
current_task.release()
asyncio.create_task(do_call())
return await ret
class Task:
opts: CanonicalOptions
inst: ComponentInstance
ft: FuncType
caller: Optional[Task]
on_return: Optional[Callable]
on_block: OnBlockCallback
events: list[EventCallback]
has_events: asyncio.Event
todo: int
def __init__(self, opts, inst, ft, caller, on_return, on_block):
self.opts = opts
self.inst = inst
self.ft = ft
self.caller = caller
self.on_return = on_return
self.on_block = on_block
self.events = []
self.has_events = asyncio.Event()
self.todo = 0
def task(self):
return self
def trap_if_on_the_stack(self, inst):
c = self.caller
while c is not None:
trap_if(c.inst is inst)
c = c.caller
async def enter(self, on_start):
assert(current_task.locked())
self.trap_if_on_the_stack(self.inst)
if not self.may_enter(self) or self.inst.pending_tasks:
f = asyncio.Future()
self.inst.pending_tasks.append((self, f))
await self.on_block(f)
assert(self.inst.starting_pending_task)
self.inst.starting_pending_task = False
if self.opts.sync:
assert(self.inst.interruptible.is_set())
self.inst.interruptible.clear()
self.inst.num_tasks += 1
cx = LiftLowerContext(self.opts, self.inst, self)
return lower_flat_values(cx, MAX_FLAT_PARAMS, on_start(), self.ft.param_types())
def may_enter(self, pending_task):
return self.inst.interruptible.is_set() and \
not (pending_task.opts.sync and self.inst.num_tasks > 0) and \
not self.inst.backpressure
def maybe_start_pending_task(self):
if self.inst.pending_tasks and not self.inst.starting_pending_task:
pending_task, pending_future = self.inst.pending_tasks[0]
if self.may_enter(pending_task):
self.inst.pending_tasks.pop(0)
self.inst.starting_pending_task = True
pending_future.set_result(None)
async def wait_on(self, sync, f):
self.maybe_start_pending_task()
if self.inst.interruptible.is_set():
if sync:
self.inst.interruptible.clear()
v = await self.on_block(f)
if sync:
self.inst.interruptible.set()
else:
while not self.inst.interruptible.is_set():
await self.on_block(self.inst.interruptible.wait())
else:
v = await self.on_block(f)
return v
async def call_sync(self, callee, *args):
if self.inst.interruptible.is_set():
self.inst.interruptible.clear()
await callee(*args, self.on_block)
self.inst.interruptible.set()
else:
await callee(*args, self.on_block)
async def wait(self, sync) -> EventTuple:
while True:
await self.wait_on(sync, self.has_events.wait())
if (e := self.maybe_next_event()):
return e
def maybe_next_event(self) -> Optional[EventTuple]:
while self.events:
event = self.events.pop(0)
if (e := event()):
return e
self.has_events.clear()
return None
def notify(self, event: EventCallback):
self.events.append(event)
self.has_events.set()
async def yield_(self, sync):
await self.wait_on(sync, asyncio.sleep(0))
async def poll(self, sync) -> Optional[EventTuple]:
await self.yield_(sync)
return self.maybe_next_event()
def return_(self, flat_results):
trap_if(not self.on_return)
if self.opts.sync and not self.opts.always_task_return:
maxflat = MAX_FLAT_RESULTS
else:
maxflat = MAX_FLAT_PARAMS
ts = self.ft.result_types()
cx = LiftLowerContext(self.opts, self.inst, self)
vs = lift_flat_values(cx, maxflat, CoreValueIter(flat_results), ts)
self.on_return(vs)
self.on_return = None
def exit(self):
assert(current_task.locked())
assert(not self.maybe_next_event())
assert(self.inst.num_tasks >= 1)
trap_if(self.todo)
trap_if(self.on_return)
trap_if(self.inst.num_tasks == 1 and self.inst.backpressure)
self.inst.num_tasks -= 1
if self.opts.sync:
assert(not self.inst.interruptible.is_set())
self.inst.interruptible.set()
self.maybe_start_pending_task()
class Subtask:
opts: CanonicalOptions
inst: ComponentInstance
supertask: Task
ft: FuncType
flat_args: CoreValueIter
flat_results: Optional[list[Any]]
state: CallState
lenders: list[ResourceHandle]
notify_supertask: bool
enqueued: bool
def __init__(self, opts, ft, task, flat_args):
self.opts = opts
self.inst = task.inst
self.supertask = task
self.ft = ft
self.flat_args = CoreValueIter(flat_args)
self.flat_results = None
self.state = CallState.STARTING
self.lenders = []
self.notify_supertask = False
self.enqueued = False
def task(self):
return self.supertask
def add_lender(self, lending_handle):
assert(lending_handle.own)
lending_handle.lend_count += 1
self.lenders.append(lending_handle)
def release_lenders(self):
for h in self.lenders:
h.lend_count -= 1
def maybe_notify_supertask(self):
if self.notify_supertask and not self.enqueued:
self.enqueued = True
def subtask_event():
self.enqueued = False
i = self.inst.waitables.array.index(self)
if self.state == CallState.DONE:
self.release_lenders()
return (EventCode(self.state), i, 0)
self.supertask.notify(subtask_event)
def on_start(self):
assert(self.state == CallState.STARTING)
self.state = CallState.STARTED
self.maybe_notify_supertask()
max_flat = MAX_FLAT_PARAMS if self.opts.sync else 1
ts = self.ft.param_types()
cx = LiftLowerContext(self.opts, self.inst, self)
return lift_flat_values(cx, max_flat, self.flat_args, ts)
def on_return(self, vs):
assert(self.state == CallState.STARTED)
self.state = CallState.RETURNED
self.maybe_notify_supertask()
max_flat = MAX_FLAT_RESULTS if self.opts.sync else 0
ts = self.ft.result_types()
cx = LiftLowerContext(self.opts, self.inst, self)
self.flat_results = lower_flat_values(cx, max_flat, vs, ts, self.flat_args)
def finish(self):
assert(self.state == CallState.RETURNED)
self.state = CallState.DONE
if self.notify_supertask:
self.maybe_notify_supertask()
else:
self.release_lenders()
return self.flat_results
def drop(self):
trap_if(self.state != CallState.DONE)
assert(not self.enqueued)
self.supertask.todo -= 1
#### Buffer, Stream and Future State
class Buffer:
MAX_LENGTH = 2**30 - 1
class WritableBuffer(Buffer):
remain: Callable[[], int]
lower: Callable[[list[any]]]
class ReadableStream:
closed: Callable[[], bool]
closed_with_error: Callable[[], Optional[ErrorContext]]
read: Callable[[WritableBuffer, OnBlockCallback], Awaitable]
cancel_read: Callable[[WritableBuffer, OnBlockCallback], Awaitable]
close: Callable[[]]
class BufferGuestImpl(Buffer):
cx: LiftLowerContext
t: ValType
ptr: int
progress: int
length: int
def __init__(self, cx, t, ptr, length):
trap_if(length == 0 or length > Buffer.MAX_LENGTH)
trap_if(ptr != align_to(ptr, alignment(t)))
trap_if(ptr + length * elem_size(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 ReadableBufferGuestImpl(BufferGuestImpl):
def lift(self, n):
assert(n <= self.remain())
vs = load_list_from_valid_range(self.cx, self.ptr, n, self.t)
self.ptr += n * elem_size(self.t)
self.progress += n
return vs
class WritableBufferGuestImpl(BufferGuestImpl, WritableBuffer):
def lower(self, vs):
assert(len(vs) <= self.remain())
store_list_into_valid_range(self.cx, vs, self.ptr, self.t)
self.ptr += len(vs) * elem_size(self.t)
self.progress += len(vs)
class ReadableStreamGuestImpl(ReadableStream):
impl: ComponentInstance
is_closed: bool
errctx: Optional[ErrorContext]
other_buffer: Optional[Buffer]
other_future: Optional[asyncio.Future]
def __init__(self, inst):
self.impl = inst
self.is_closed = False
self.errctx = None
self.other_buffer = None
self.other_future = None
def closed(self):
return self.is_closed
def closed_with_error(self):
assert(self.is_closed)
return self.errctx
async def read(self, dst, on_block):
await self.rendezvous(dst, self.other_buffer, dst, on_block)
async def write(self, src, on_block):
await self.rendezvous(src, src, self.other_buffer, on_block)
async def rendezvous(self, this_buffer, src, dst, on_block):
assert(not self.is_closed)
if self.other_buffer:
ncopy = min(src.remain(), dst.remain())
assert(ncopy > 0)
dst.lower(src.lift(ncopy))
if not self.other_buffer.remain():
self.other_buffer = None
if self.other_future:
self.other_future.set_result(None)
self.other_future = None
else:
assert(not self.other_future)
self.other_buffer = this_buffer
self.other_future = asyncio.Future()
await on_block(self.other_future)
if self.other_buffer is this_buffer:
self.other_buffer = None
async def cancel_read(self, dst, on_block):
await self.cancel_rendezvous(dst, on_block)
async def cancel_write(self, src, on_block):
await self.cancel_rendezvous(src, on_block)
async def cancel_rendezvous(self, this_buffer, on_block):
assert(not self.is_closed)
if not DETERMINISTIC_PROFILE and random.randint(0,1):
await on_block(asyncio.sleep(0))
if self.other_buffer is this_buffer:
self.other_buffer = None
if self.other_future:
self.other_future.set_result(None)
self.other_future = None
def close(self, errctx = None):
if not self.is_closed:
assert(not self.errctx)
self.is_closed = True
self.errctx = errctx
self.other_buffer = None
if self.other_future:
self.other_future.set_result(None)
self.other_future = None
else:
assert(not self.other_buffer and not self.other_future)
class StreamHandle:
stream: ReadableStream
t: ValType
paired: bool
borrow_scope: Optional[Task|Subtask]
copying_task: Optional[Task]
copying_buffer: Optional[Buffer]
def __init__(self, stream, t):
self.stream = stream
self.t = t
self.paired = False
self.borrow_scope = None
self.copying_task = None
self.copying_buffer = None
def start_copying(self, task, buffer):
assert(not self.copying_task and not self.copying_buffer)
task.todo += 1
self.copying_task = task
self.copying_buffer = buffer
def stop_copying(self):
assert(self.copying_task and self.copying_buffer)
self.copying_task.todo -= 1
self.copying_task = None
self.copying_buffer = None
def drop(self, errctx):
trap_if(self.copying_buffer)
self.stream.close(errctx)
if isinstance(self.borrow_scope, Task):
self.borrow_scope.todo -= 1
class ReadableStreamHandle(StreamHandle):
async def copy(self, dst, on_block):
await self.stream.read(dst, on_block)
async def cancel_copy(self, dst, on_block):
await self.stream.cancel_read(dst, on_block)
class WritableStreamHandle(StreamHandle):
def __init__(self, t, inst):
stream = ReadableStreamGuestImpl(inst)
StreamHandle.__init__(self, stream, t)
async def copy(self, src, on_block):
await self.stream.write(src, on_block)
async def cancel_copy(self, src, on_block):
await self.stream.cancel_write(src, on_block)
class FutureHandle(StreamHandle): pass
class ReadableFutureHandle(FutureHandle):
async def copy(self, dst, on_block):
assert(dst.remain() == 1)
await self.stream.read(dst, on_block)
if dst.remain() == 0:
self.stream.close()
async def cancel_copy(self, dst, on_block):
await self.stream.cancel_read(dst, on_block)
if dst.remain() == 0:
self.stream.close()
class WritableFutureHandle(FutureHandle):
def __init__(self, t, inst):
stream = ReadableStreamGuestImpl(inst)
FutureHandle.__init__(self, stream, t)
async def copy(self, src, on_block):
assert(src.remain() == 1)
await self.stream.write(src, on_block)
if src.remain() == 0:
self.stream.close()
async def cancel_copy(self, src, on_block):
await self.cancel_write(src, on_block)
if src.remain() == 0:
self.stream.close()
def drop(self, errctx):
trap_if(not self.stream.closed() and not errctx)
FutureHandle.drop(self, errctx)
### Despecialization
def despecialize(t):
match t:
case TupleType(ts) : return RecordType([ FieldType(str(i), t) for i,t in enumerate(ts) ])
case EnumType(labels) : return VariantType([ CaseType(l, None) for l in labels ])
case OptionType(t) : return VariantType([ CaseType("none", None), CaseType("some", t) ])
case ResultType(ok, err) : return VariantType([ CaseType("ok", ok), CaseType("error", err) ])
case _ : return t
### Type Predicates
def contains_borrow(t):
return contains(t, lambda u: isinstance(u, BorrowType))
def contains_async_value(t):
return contains(t, lambda u: isinstance(u, StreamType | FutureType))
def contains(t, p):
t = despecialize(t)
match t:
case None:
return False
case PrimValType() | OwnType() | BorrowType():
return p(t)
case ListType(u) | StreamType(u) | FutureType(u):
return p(t) or contains(u, p)
case RecordType(fields):
return p(t) or any(contains(f.t, p) for f in fields)
case VariantType(cases):
return p(t) or any(contains(c.t, p) for c in cases)
case FuncType():
return any(p(u) for u in t.param_types() + t.result_types())
case _:
assert(False)
### Alignment
def alignment(t):
match despecialize(t):
case BoolType() : return 1
case S8Type() | U8Type() : return 1
case S16Type() | U16Type() : return 2
case S32Type() | U32Type() : return 4
case S64Type() | U64Type() : return 8
case F32Type() : return 4
case F64Type() : return 8
case CharType() : return 4
case StringType() : return 4
case ErrorContextType() : return 4
case ListType(t, l) : return alignment_list(t, l)
case RecordType(fields) : return alignment_record(fields)
case VariantType(cases) : return alignment_variant(cases)
case FlagsType(labels) : return alignment_flags(labels)
case OwnType() | BorrowType() : return 4
case StreamType() | FutureType() : return 4
def alignment_list(elem_type, maybe_length):
if maybe_length is not None:
return alignment(elem_type)
return 4
def alignment_record(fields):
a = 1
for f in fields:
a = max(a, alignment(f.t))
return a
def alignment_variant(cases):
return max(alignment(discriminant_type(cases)), max_case_alignment(cases))
def discriminant_type(cases):
n = len(cases)
assert(0 < n < (1 << 32))
match math.ceil(math.log2(n)/8):
case 0: return U8Type()
case 1: return U8Type()
case 2: return U16Type()
case 3: return U32Type()
def max_case_alignment(cases):
a = 1
for c in cases:
if c.t is not None:
a = max(a, alignment(c.t))
return a
def alignment_flags(labels):
n = len(labels)
assert(0 < n <= 32)
if n <= 8: return 1
if n <= 16: return 2
return 4
### Element Size
def elem_size(t):
match despecialize(t):
case BoolType() : return 1
case S8Type() | U8Type() : return 1
case S16Type() | U16Type() : return 2
case S32Type() | U32Type() : return 4
case S64Type() | U64Type() : return 8
case F32Type() : return 4
case F64Type() : return 8
case CharType() : return 4
case StringType() : return 8
case ErrorContextType() : return 4
case ListType(t, l) : return elem_size_list(t, l)
case RecordType(fields) : return elem_size_record(fields)
case VariantType(cases) : return elem_size_variant(cases)
case FlagsType(labels) : return elem_size_flags(labels)
case OwnType() | BorrowType() : return 4
case StreamType() | FutureType() : return 4
def elem_size_list(elem_type, maybe_length):
if maybe_length is not None:
return maybe_length * elem_size(elem_type)
return 8
def elem_size_record(fields):
s = 0
for f in fields:
s = align_to(s, alignment(f.t))
s += elem_size(f.t)
assert(s > 0)
return align_to(s, alignment_record(fields))
def align_to(ptr, alignment):
return math.ceil(ptr / alignment) * alignment
def elem_size_variant(cases):
s = elem_size(discriminant_type(cases))
s = align_to(s, max_case_alignment(cases))
cs = 0
for c in cases:
if c.t is not None:
cs = max(cs, elem_size(c.t))
s += cs
return align_to(s, alignment_variant(cases))
def elem_size_flags(labels):
n = len(labels)
assert(0 < n <= 32)
if n <= 8: return 1
if n <= 16: return 2
return 4
### Loading
def load(cx, ptr, t):
assert(ptr == align_to(ptr, alignment(t)))
assert(ptr + elem_size(t) <= len(cx.opts.memory))
match despecialize(t):
case BoolType() : return convert_int_to_bool(load_int(cx, ptr, 1))
case U8Type() : return load_int(cx, ptr, 1)
case U16Type() : return load_int(cx, ptr, 2)
case U32Type() : return load_int(cx, ptr, 4)
case U64Type() : return load_int(cx, ptr, 8)
case S8Type() : return load_int(cx, ptr, 1, signed=True)
case S16Type() : return load_int(cx, ptr, 2, signed=True)
case S32Type() : return load_int(cx, ptr, 4, signed=True)
case S64Type() : return load_int(cx, ptr, 8, signed=True)
case F32Type() : return decode_i32_as_float(load_int(cx, ptr, 4))
case F64Type() : return decode_i64_as_float(load_int(cx, ptr, 8))
case CharType() : return convert_i32_to_char(cx, load_int(cx, ptr, 4))
case StringType() : return load_string(cx, ptr)
case ErrorContextType() : return lift_error_context(cx, load_int(cx, ptr, 4))
case ListType(t, l) : return load_list(cx, ptr, t, l)
case RecordType(fields) : return load_record(cx, ptr, fields)
case VariantType(cases) : return load_variant(cx, ptr, cases)
case FlagsType(labels) : return load_flags(cx, ptr, labels)
case OwnType() : return lift_own(cx, load_int(cx, ptr, 4), t)
case BorrowType() : return lift_borrow(cx, load_int(cx, ptr, 4), t)
case StreamType(t) : return lift_stream(cx, load_int(cx, ptr, 4), t)
case FutureType(t) : return lift_future(cx, load_int(cx, ptr, 4), t)
def load_int(cx, ptr, nbytes, signed = False):
return int.from_bytes(cx.opts.memory[ptr : ptr+nbytes], 'little', signed=signed)
def convert_int_to_bool(i):
assert(i >= 0)
return bool(i)
DETERMINISTIC_PROFILE = False # or True
CANONICAL_FLOAT32_NAN = 0x7fc00000
CANONICAL_FLOAT64_NAN = 0x7ff8000000000000
def canonicalize_nan32(f):
if math.isnan(f):
f = core_f32_reinterpret_i32(CANONICAL_FLOAT32_NAN)
assert(math.isnan(f))
return f
def canonicalize_nan64(f):
if math.isnan(f):
f = core_f64_reinterpret_i64(CANONICAL_FLOAT64_NAN)
assert(math.isnan(f))
return f
def decode_i32_as_float(i):
return canonicalize_nan32(core_f32_reinterpret_i32(i))
def decode_i64_as_float(i):
return canonicalize_nan64(core_f64_reinterpret_i64(i))
def core_f32_reinterpret_i32(i):
return struct.unpack('<f', struct.pack('<I', i))[0] # f32.reinterpret_i32
def core_f64_reinterpret_i64(i):
return struct.unpack('<d', struct.pack('<Q', i))[0] # f64.reinterpret_i64
def convert_i32_to_char(cx, i):
assert(i >= 0)
trap_if(i >= 0x110000)
trap_if(0xD800 <= i <= 0xDFFF)
return chr(i)
String = tuple[str, str, int]
def load_string(cx, ptr) -> String:
begin = load_int(cx, ptr, 4)
tagged_code_units = load_int(cx, ptr + 4, 4)
return load_string_from_range(cx, begin, tagged_code_units)