-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathdefinitions.py
2179 lines (1852 loc) · 66.5 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, TypeVar, Generic, Literal
from enum import IntEnum
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: Optional[ValType]
@dataclass
class FutureType(ValType):
t: Optional[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: Table[ResourceHandle]
waitables: Table[Waitable]
waitable_sets: Table[WaitableSet]
error_contexts: Table[ErrorContext]
may_leave: bool
backpressure: bool
calling_sync_export: bool
calling_sync_import: bool
pending_tasks: list[tuple[Task, asyncio.Future]]
starting_pending_task: bool
def __init__(self):
self.resources = Table[ResourceHandle]()
self.waitables = Table[Waitable]()
self.waitable_sets = Table[WaitableSet]()
self.error_contexts = Table[ErrorContext]()
self.may_leave = True
self.backpressure = False
self.calling_sync_export = False
self.calling_sync_import = False
self.pending_tasks = []
self.starting_pending_task = False
#### Table State
ElemT = TypeVar('ElemT')
class Table(Generic[ElemT]):
array: list[Optional[ElemT]]
free: list[int]
MAX_LENGTH = 2**28 - 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
#### Resource State
class ResourceHandle:
rt: ResourceType
rep: int
own: bool
borrow_scope: Optional[Task]
num_lends: int
def __init__(self, rt, rep, own, borrow_scope = None):
self.rt = rt
self.rep = rep
self.own = own
self.borrow_scope = borrow_scope
self.num_lends = 0
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
#### Buffer State
class Buffer:
MAX_LENGTH = 2**30 - 1
t: ValType
remain: Callable[[], int]
class ReadableBuffer(Buffer):
read: Callable[[int], list[any]]
class WritableBuffer(Buffer):
write: Callable[[list[any]]]
class BufferGuestImpl(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 and length > 0:
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 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.t)
else:
vs = n * [()]
self.progress += n
return vs
class WritableBufferGuestImpl(BufferGuestImpl, 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.t)
else:
assert(all(v == () for v in vs))
self.progress += len(vs)
#### Context-Local Storage
class ContextLocalStorage:
LENGTH = 2
array: list[int]
def __init__(self):
self.array = [0] * ContextLocalStorage.LENGTH
def set(self, i, v):
assert(types_match_values(['i32'], [v]))
self.array[i] = v
def get(self, i):
return self.array[i]
#### Task State
class Task:
opts: CanonicalOptions
inst: ComponentInstance
ft: FuncType
caller: Optional[Task]
on_return: Optional[Callable]
on_block: Callable[[Awaitable], Awaitable]
num_subtasks: int
num_borrows: int
context: ContextLocalStorage
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.num_subtasks = 0
self.num_borrows = 0
self.context = ContextLocalStorage()
current = asyncio.Lock()
async def sync_on_block(a: Awaitable):
Task.current.release()
v = await a
await Task.current.acquire()
return v
async def enter(self, on_start):
assert(Task.current.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.may_enter(self) and self.inst.starting_pending_task)
self.inst.starting_pending_task = False
if self.opts.sync:
self.inst.calling_sync_export = True
cx = LiftLowerContext(self.opts, self.inst, self)
return lower_flat_values(cx, MAX_FLAT_PARAMS, on_start(), self.ft.param_types())
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
def may_enter(self, pending_task):
return not self.inst.backpressure and \
not self.inst.calling_sync_import and \
not (self.inst.calling_sync_export and pending_task.opts.sync)
def maybe_start_pending_task(self):
if self.inst.starting_pending_task:
return
for i,(pending_task,pending_future) in enumerate(self.inst.pending_tasks):
if self.may_enter(pending_task):
self.inst.pending_tasks.pop(i)
self.inst.starting_pending_task = True
pending_future.set_result(None)
return
async def yield_(self, sync):
await self.wait_on(asyncio.sleep(0), sync)
async_waiting_tasks = asyncio.Condition(current)
async def wait_on(self, awaitable, sync):
assert(not self.inst.calling_sync_import)
if sync:
self.inst.calling_sync_import = True
v = await self.on_block(awaitable)
self.inst.calling_sync_import = False
self.async_waiting_tasks.notify_all()
else:
self.maybe_start_pending_task()
v = await self.on_block(awaitable)
while self.inst.calling_sync_import:
Task.current.release()
await self.async_waiting_tasks.wait()
return v
async def call_sync(self, callee, *args):
assert(not self.inst.calling_sync_import)
self.inst.calling_sync_import = True
v = await callee(*args, self.on_block)
self.inst.calling_sync_import = False
self.async_waiting_tasks.notify_all()
return v
async def call_async(self, callee, *args):
ret = asyncio.Future()
async def async_on_block(a: Awaitable):
if not ret.done():
ret.set_result(None)
else:
Task.current.release()
v = await a
await Task.current.acquire()
return v
async def do_call():
await callee(*args, async_on_block)
if not ret.done():
ret.set_result(None)
else:
Task.current.release()
asyncio.create_task(do_call())
await ret
def return_(self, flat_results):
trap_if(not self.on_return)
trap_if(self.num_borrows > 0)
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(Task.current.locked())
trap_if(self.num_subtasks > 0)
trap_if(self.on_return)
assert(self.num_borrows == 0)
if self.opts.sync:
assert(self.inst.calling_sync_export)
self.inst.calling_sync_export = False
self.maybe_start_pending_task()
#### Waitable State
class CallState(IntEnum):
STARTING = 1
STARTED = 2
RETURNED = 3
class EventCode(IntEnum):
NONE = 0
CALL_STARTING = CallState.STARTING
CALL_STARTED = CallState.STARTED
CALL_RETURNED = CallState.RETURNED
STREAM_READ = 5
STREAM_WRITE = 6
FUTURE_READ = 7
FUTURE_WRITE = 8
EventTuple = tuple[EventCode, int, int]
class Waitable:
pending_event: Optional[Callable[[], EventTuple]]
has_pending_event_: asyncio.Event
maybe_waitable_set: Optional[WaitableSet]
def __init__(self):
self.pending_event = None
self.has_pending_event_ = asyncio.Event()
self.maybe_waitable_set = None
def set_event(self, pending_event):
self.pending_event = pending_event
self.has_pending_event_.set()
if self.maybe_waitable_set:
self.maybe_waitable_set.maybe_has_pending_event.set()
def has_pending_event(self):
assert(self.has_pending_event_.is_set() == bool(self.pending_event))
return self.has_pending_event_.is_set()
async def wait_for_pending_event(self):
return await self.has_pending_event_.wait()
def get_event(self) -> EventTuple:
assert(self.has_pending_event())
pending_event = self.pending_event
self.pending_event = None
self.has_pending_event_.clear()
return pending_event()
def join(self, maybe_waitable_set):
if self.maybe_waitable_set:
self.maybe_waitable_set.elems.remove(self)
self.maybe_waitable_set = maybe_waitable_set
if maybe_waitable_set:
maybe_waitable_set.elems.append(self)
if self.has_pending_event():
maybe_waitable_set.maybe_has_pending_event.set()
def drop(self):
assert(not self.has_pending_event())
self.join(None)
class WaitableSet:
elems: list[Waitable]
maybe_has_pending_event: asyncio.Event
num_waiting: int
def __init__(self):
self.elems = []
self.maybe_has_pending_event = asyncio.Event()
self.num_waiting = 0
async def wait(self) -> EventTuple:
self.num_waiting += 1
while True:
await self.maybe_has_pending_event.wait()
if (e := self.poll()):
self.num_waiting -= 1
return e
def poll(self) -> Optional[EventTuple]:
random.shuffle(self.elems)
for w in self.elems:
assert(self is w.maybe_waitable_set)
if w.has_pending_event():
assert(self.maybe_has_pending_event.is_set())
return w.get_event()
self.maybe_has_pending_event.clear()
return None
def drop(self):
trap_if(len(self.elems) > 0)
trap_if(self.num_waiting > 0)
#### Subtask State
class Subtask(Waitable):
state: CallState
lenders: list[ResourceHandle]
finished: bool
supertask: Optional[Task]
def __init__(self):
self.state = CallState.STARTING
self.lenders = []
self.finished = False
self.supertask = None
def add_to_waitables(self, task):
assert(not self.supertask)
self.supertask = task
self.supertask.num_subtasks += 1
Waitable.__init__(self)
return task.inst.waitables.add(self)
def add_lender(self, lending_handle):
assert(not self.finished and self.state != CallState.RETURNED)
lending_handle.num_lends += 1
self.lenders.append(lending_handle)
def finish(self):
assert(not self.finished and self.state == CallState.RETURNED)
for h in self.lenders:
h.num_lends -= 1
self.finished = True
def drop(self):
trap_if(not self.finished)
assert(self.state == CallState.RETURNED)
self.supertask.num_subtasks -= 1
Waitable.drop(self)
#### Stream State
RevokeBuffer = Callable[[], None]
OnPartialCopy = Callable[RevokeBuffer, None]
OnCopyDone = Callable[[], None]
class ReadableStream:
t: ValType
read: Callable[[WritableBuffer, OnPartialCopy, OnCopyDone], Literal['done','blocked']]
cancel: Callable[[], None]
close: Callable[[Optional[ErrorContext]]]
closed: Callable[[], bool]
closed_with: Callable[[], Optional[ErrorContext]]
class ReadableStreamGuestImpl(ReadableStream):
impl: ComponentInstance
closed_: bool
maybe_errctx: Optional[ErrorContext]
pending_buffer: Optional[Buffer]
pending_on_partial_copy: Optional[OnPartialCopy]
pending_on_copy_done: Optional[OnCopyDone]
def __init__(self, t, inst):
self.t = t
self.impl = inst
self.closed_ = False
self.maybe_errctx = None
self.reset_pending()
def reset_pending(self):
self.set_pending(None, None, None)
def set_pending(self, buffer, on_partial_copy, on_copy_done):
self.pending_buffer = buffer
self.pending_on_partial_copy = on_partial_copy
self.pending_on_copy_done = on_copy_done
def reset_and_notify_pending(self):
pending_on_copy_done = self.pending_on_copy_done
self.reset_pending()
pending_on_copy_done()
def cancel(self):
self.reset_and_notify_pending()
def close(self, maybe_errctx):
if not self.closed_:
self.closed_ = True
self.maybe_errctx = maybe_errctx
if self.pending_buffer:
self.reset_and_notify_pending()
def closed(self):
return self.closed_
def closed_with(self):
assert(self.closed_)
return self.maybe_errctx
def read(self, dst, on_partial_copy, on_copy_done):
return self.copy(dst, on_partial_copy, on_copy_done, self.pending_buffer, dst)
def write(self, src, on_partial_copy, on_copy_done):
return self.copy(src, on_partial_copy, on_copy_done, src, self.pending_buffer)
def copy(self, buffer, on_partial_copy, on_copy_done, src, dst):
if self.closed_:
return 'done'
elif not self.pending_buffer:
self.set_pending(buffer, on_partial_copy, on_copy_done)
return 'blocked'
else:
if self.pending_buffer.remain() > 0:
if buffer.remain() > 0:
dst.write(src.read(min(src.remain(), dst.remain())))
if self.pending_buffer.remain() > 0:
self.pending_on_partial_copy(self.reset_pending)
else:
self.reset_and_notify_pending()
return 'done'
else:
if buffer.remain() > 0 or buffer is dst:
self.reset_and_notify_pending()
self.set_pending(buffer, on_partial_copy, on_copy_done)
return 'blocked'
else:
return 'done'
class StreamEnd(Waitable):
stream: ReadableStream
copying: bool
def __init__(self, stream):
Waitable.__init__(self)
self.stream = stream
self.copying = False
def drop(self, maybe_errctx):
trap_if(self.copying)
self.stream.close(maybe_errctx)
Waitable.drop(self)
class ReadableStreamEnd(StreamEnd):
def copy(self, dst, on_partial_copy, on_copy_done):
return self.stream.read(dst, on_partial_copy, on_copy_done)
class WritableStreamEnd(StreamEnd):
paired: bool = False
def copy(self, src, on_partial_copy, on_copy_done):
return self.stream.write(src, on_partial_copy, on_copy_done)
#### Future State
class FutureEnd(StreamEnd):
def close_after_copy(self, copy_op, buffer, on_copy_done):
assert(buffer.remain() == 1)
def on_copy_done_wrapper():
if buffer.remain() == 0:
self.stream.close(maybe_errctx = None)
on_copy_done()
ret = copy_op(buffer, on_partial_copy = None, on_copy_done = on_copy_done_wrapper)
if ret == 'done' and buffer.remain() == 0:
self.stream.close(maybe_errctx = None)
return ret
class ReadableFutureEnd(FutureEnd):
def copy(self, dst, on_partial_copy, on_copy_done):
return self.close_after_copy(self.stream.read, dst, on_copy_done)
class WritableFutureEnd(FutureEnd):
paired: bool = False
def copy(self, src, on_partial_copy, on_copy_done):
return self.close_after_copy(self.stream.write, src, on_copy_done)
def drop(self, maybe_errctx):
trap_if(not self.stream.closed() and not maybe_errctx)
FutureEnd.drop(self, maybe_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)
UTF16_TAG = 1 << 31
def load_string_from_range(cx, ptr, tagged_code_units) -> String:
match cx.opts.string_encoding:
case 'utf8':