diff --git a/design/mvp/Binary.md b/design/mvp/Binary.md index 194840c0e..0d5f9432d 100644 --- a/design/mvp/Binary.md +++ b/design/mvp/Binary.md @@ -264,7 +264,9 @@ Notes: * Validation of `stream` rejects `(stream char)` as a temporary [TODO](Concurrency.md#TODO). * Validation of `resourcetype` requires the destructor (if present) to have - type `[i32] -> []`. + type `[t] -> []`, where `t` is the representation type. +* Validation of `resourcetype` requires the representation type to be `i32`, + `i64` (🐘) or `(ref any)` (🛸). * In addition to the validation rules for `alias` *definitions* mentioned above, validation of `alias` *declarators* also requires: * `export` aliases only alias the `instance` and `type` sorts @@ -351,6 +353,35 @@ canon ::= 0x00 0x00 f: opts: ft: => (canon lift | 0x40 sh?: ft: => (canon thread.spawn-ref sh? ft (core func)) 🧵② | 0x41 sh?: ft: t: => (canon thread.spawn-indirect sh? ft t (core func)) 🧵② | 0x42 sh?: => (canon thread.available-parallelism sh? (core func)) 🧵② + | 0x43 dst: src: => (canon array.new-array dst src (core func)) 🛸 + | 0x44 dst: src: => (canon array.new-memory dst src (core func)) 🛸 + | 0x45 dst: src: => (canon array.new-table dst src (core func)) 🛸 + | 0x46 rt: => (canon gc.resource.new rt (core func)) 🛸 + | 0x47 rt: => (canon gc.resource.drop rt (core func)) 🛸 + | 0x48 rt: => (canon gc.resource.rep rt (core func)) 🛸 + | 0x49 t: => (canon gc.stream.new t (core func)) 🛸 + | 0x4a t: async?: => (canon gc.stream.cancel-read t async? (core func)) 🛸 + | 0x4b t: async?: => (canon gc.stream.cancel-write t async? (core func)) 🛸 + | 0x4c t: => (canon gc.stream.drop-readable t (core func)) 🛸 + | 0x4d t: => (canon gc.stream.drop-writable t (core func)) 🛸 + | 0x4e t: => (canon gc.stream.forward t (core func)) 🛸 + | 0x4f t: => (canon gc.future.new t (core func)) 🛸 + | 0x50 t: async?: => (canon gc.future.cancel-read t async? (core func)) 🛸 + | 0x51 t: async?: => (canon gc.future.cancel-write t async? (core func)) 🛸 + | 0x52 t: => (canon gc.future.drop-readable t (core func)) 🛸 + | 0x53 t: => (canon gc.future.drop-writable t (core func)) 🛸 + | 0x54 t: => (canon gc.future.forward t (core func)) 🛸 + | 0x55 => (canon gc.error-context.drop (core func)) 🛸 + | 0x56 => (canon gc.waitable-set.new (core func)) 🛸 + | 0x57 => (canon gc.waitable-set.wait (core func)) 🛸 + | 0x58 => (canon gc.waitable-set.poll (core func)) 🛸 + | 0x59 => (canon gc.waitable-set.drop (core func)) 🛸 + | 0x5a => (canon gc.waitable.join (core func)) 🛸 + | 0x5b async?: => (canon gc.subtask.cancel async? (core func)) 🛸 + | 0x5c => (canon gc.subtask.drop (core func)) 🛸 + | 0x5d => (canon gc.handle-ref.index (core func)) 🛸 + | 0x5e => (canon gc.handle-ref.new (core func)) 🛸 + | 0x5f => (canon gc.handle-ref.get (core func)) 🛸 async? ::= 0x00 => | 0x01 => async sh? ::= 0x00 => @@ -364,15 +395,21 @@ canonopt ::= 0x00 => string-encod | 0x05 f: => (post-return f) | 0x06 => async 🔀 | 0x07 f: => (callback f) 🔀 + | 0x08 => gc 🛸 ``` Notes: * The second `0x00` byte in `canon` stands for the `func` sort and thus the `0x00 ` pair standards for a `func` `sortidx` or `core:sortidx`. * Validation prevents duplicate or conflicting `canonopt`. + * 🛸 Validation rejects using both `gc` and `memory` (and thus `realloc`) in + the same `opts`, for example. * When there is no `string-encoding` present, the default value is `utf8`. For all other values, the default value is "none". * Validation of the individual canonical definitions is described in [`CanonicalABI.md`](CanonicalABI.md#canonical-definitions). +* 🛸 The `gc.*` canonical definitions only exist because the associated non-GC + definitions do not take ``; the definitions that do take `` use + the `gc` `canonopt` to switch to the GC mode instead. ## 🪙 Start Definitions diff --git a/design/mvp/CanonicalABI.md b/design/mvp/CanonicalABI.md index 7e9d7e779..d3571e39f 100644 --- a/design/mvp/CanonicalABI.md +++ b/design/mvp/CanonicalABI.md @@ -12,15 +12,15 @@ specified here. The Canonical ABI specifies, for each component function signature, a corresponding core function signature and the process for reading -component-level values into and out of linear memory. While a full formal -specification would specify the Canonical ABI in terms of macro-expansion into -Core WebAssembly instructions augmented with a new set of (spec-internal) -[administrative instructions], the informal presentation here instead specifies -the process in terms of Python code that would be logically executed at -validation- and run-time by a component model implementation. The Python code -is presented by interleaving definitions with descriptions and eliding some -boilerplate. For a complete listing of all Python definitions in a single -executable file with a small unit test suite, see the +component-level values into and out of linear memory (or, with 🛸 `gc`, the GC +heap). While a full formal specification would specify the Canonical ABI in +terms of macro-expansion into Core WebAssembly instructions augmented with a new +set of (spec-internal) [administrative instructions], the informal presentation +here instead specifies the process in terms of Python code that would be +logically executed at validation- and run-time by a component model +implementation. The Python code is presented by interleaving definitions with +descriptions and eliding some boilerplate. For a complete listing of all Python +definitions in a single executable file with a small unit test suite, see the [`canonical-abi`](canonical-abi/) directory. The convention followed by the Python code below is that all traps are raised by @@ -913,11 +913,16 @@ when lifting individual parameters and results: class LiftOptions: string_encoding: str = 'utf8' memory: Optional[MemInst] = None + gc: bool = False def equal(lhs, rhs): return lhs.string_encoding == rhs.string_encoding and \ - lhs.memory is rhs.memory + lhs.memory is rhs.memory and \ + lhs.gc == rhs.gc ``` +By default, values are lifted from linear memory. When the 🛸 `gc` field is +true, values are lifted from objects in the GC heap instead. + The `equal` static method is used by `task.return` below to dynamically compare equality of just this subset of `canonopt`. @@ -1039,8 +1044,13 @@ table containing everything else ([resource handles](#resource-state), [waitables and waitable sets](#waitable-state) and [error contexts](#-canon-error-contextnew)). ```python +@dataclass +class TableEntry: + item: any + handle_ref: Optional[HandleRef] = None + class Table: - array: list[any] + array: list[Optional[TableEntry]] free: list[int] MAX_LENGTH = 2**28 - 1 @@ -1050,24 +1060,24 @@ class Table: self.free = [] def __iter__(self): - for e in self.array: - if e is not None: - yield e + for entry in self.array: + if entry is not None: + yield entry.item def get(self, i): trap_if(i >= len(self.array)) trap_if(self.array[i] is None) - return self.array[i] + return self.array[i].item def add(self, e): if self.free: i = self.free.pop() assert(self.array[i] is None) - self.array[i] = e + self.array[i] = TableEntry(e) else: i = len(self.array) trap_if(i > Table.MAX_LENGTH) - self.array.append(e) + self.array.append(TableEntry(e)) return i def remove(self, i): @@ -1075,6 +1085,19 @@ class Table: self.array[i] = None self.free.append(i) return e + + def get_handle_ref(self, i): + trap_if(i >= len(self.array)) + if self.array[i] is None: + return None + else: + return self.array[i].handle_ref + + def set_handle_ref(self, i, r): + trap_if(i >= len(self.array)) + trap_if(self.array[i] is None) + trap_if(self.array[i].handle_ref is not None) + self.array[i].handle_ref = r ``` `Table` maintains a dense array of elements that can contain holes created by the `remove` method (defined above). When table elements are accessed (e.g., by @@ -1093,6 +1116,13 @@ The limit of `2**28` ensures that the high 4 bits of table indices are unset and available for other use in guest code (e.g., for tagging, packed words or sentinel values). +Each element is stored in a `TableEntry` along with its unique 🛸 `HandleRef` +(if it has one), so `remove` also removes the index's `HandleRef` (letting the +index be reused while the old `HandleRef` becomes stale). `get_handle_ref` +returns the `HandleRef` associated with the given index, if any; +`set_handle_ref` sets the `HandleRef` for the given index, trapping if it +already has one. + ### Resource State @@ -1136,9 +1166,11 @@ instances). `ResourceType` Python object identity is used by trapping guards on the `rt` field of `ResourceHandle` (above) and thus resource type equality is *not* defined structurally (on the contents of `ResourceType`). ```python +ANYREF = CoreRefType('any') + class ResourceType(Type): impl_inst: ComponentInstance - rep: Literal['i32', 'i64'] + rep: Literal['i32', 'i64'] | CoreRefType dtor: Optional[Callable] def __init__(self, impl_inst, rep, dtor = None): @@ -1146,9 +1178,10 @@ class ResourceType(Type): self.rep = rep self.dtor = dtor ``` -The `rep` field stores the core value type given by the `(rep ...)` immediate -of the `resource` type definition. The `impl_inst` field stores the component -instance that generated this resource type. +The `rep` field stores the core value type given by the `(rep ...)` immediate of +the `resource` type definition (with 🛸, `ANYREF` for `(rep (ref any))`). The +`impl_inst` field stores the component instance that generated this resource +type. ### Waitable State @@ -1520,6 +1553,7 @@ class WritableGuestBuffer(GuestBuffer, WritableBuffer): assert(all(v == () for v in vs)) self.progress += len(vs) ``` + As with `load_list_from_range` below, the alignment and range checks are performed even when `length` is `0`. When `t` is `None` (arising from `stream` and `future` with empty element types), the core-wasm-supplied `ptr` is @@ -1532,6 +1566,79 @@ The `load_list_from_valid_range` and `store_list_into_valid_range` functions that do all the heavy lifting are shared with function parameter/result lifting and lowering and defined below. +The 🛸 `gc` buffers are the GC equivalents of the linear memory buffers, holding +GC reference storage rather than pointing into a region of linear memory. For +`stream`s, the buffer wraps a GC `array`, whose elements are lifted with +`lift_gc_value` when the reader reads them and elements are lowered into the +array via `lower_gc_value`. `future`s use a buffer that wraps its single `(ref +$results)` cell (see `gc_async_results_type`). +```python +class GcBuffer(Buffer): + cx: LiftLowerContext + t: Optional[ValType] + elems: list[any] + offset: int + length: int + progress: int + + def __init__(self, t, cx, elems, offset, length): + trap_if(length > Buffer.MAX_LENGTH) + if t is not None: + trap_if(offset + length > len(elems)) + self.cx = cx + self.t = t + self.elems = elems + self.offset = offset + self.length = length + self.progress = 0 + + def remain(self): + return self.length - self.progress + +class ReadableGcBuffer(GcBuffer, ReadableBuffer): + def read(self, n): + assert(n <= self.remain()) + if self.t: + vs = [] + for i in range(n): + vs.append(self.lift(self.elems[self.offset + self.progress + i])) + else: + vs = n * [()] + self.progress += n + return vs + + def lift(self, v): + return lift_gc_value(self.cx, v, self.t) + +class WritableGcBuffer(GcBuffer, WritableBuffer): + def write(self, vs): + assert(len(vs) <= self.remain()) + if self.t: + for i,v in enumerate(vs): + self.elems[self.offset + self.progress + i] = self.lower(v) + else: + assert(all(v == () for v in vs)) + self.progress += len(vs) + + def lower(self, v): + return lower_gc_value(self.cx, v, self.t) + +class ReadableGcValueBuffer(ReadableGcBuffer): + def __init__(self, t, cx, v = None): + assert(t is not None or v is None) + ReadableGcBuffer.__init__(self, t, cx, [v], 0, 1) + + def lift(self, v): + return lift_unpacked_gc_value(self.cx, v, self.t) + +def lift_unpacked_gc_value(cx, v, t): + match gc_storage_type(cx, t): + case 'i8' | 'i16': + return lift_flat(cx, CoreValueIter([v]), t) + case 'i32' | 'i64' | 'f32' | 'f64' | CoreRefType(): + return lift_gc_value(cx, v, t) +``` + ### Stream and Future State @@ -2013,6 +2120,7 @@ thus alignment depends on the resource's `(rep $t)`. ```python def alignment_borrow(cx, borrowt): if pass_rep_not_handle(cx, borrowt): + assert(borrowt.rt.rep in ['i32', 'i64']) return ptr_size(borrowt.rt.rep) else: return 4 @@ -2091,11 +2199,198 @@ def elem_size_flags(labels): def elem_size_borrow(cx, borrowt): if pass_rep_not_handle(cx, borrowt): + assert(borrowt.rt.rep in ['i32', 'i64']) return ptr_size(borrowt.rt.rep) else: return 4 ``` +## 🛸 GC Types + +This section defines lowering component model types into core Wasm types on the +GC heap. This is fairly different from type lowering to linear memory, as we +have to define the various core Wasm GC types that the component-model types +lower to, rather than their size and alignment in linear memory. + +Lowering to flat value types in a function's parameters and results, rather than +into the GC heap or linear memory, follows different rules, documented in the +[Flattening](#flattening) section. + +To represent core Wasm's GC types, objects, and references in the Python spec +code, we use the following definitions: + +| Core Wasm | Python | +| -------------------------------------------------------- | ------------------------------------------------------ | +| `(ref heapty)` type | `CoreRefType(heapty)` | +| `(ref null heapty)` type | `CoreRefType(heapty, nullable = True)` | +| `extern`, `any`, `eq`, `struct` and `array` heap types | `'extern'`, `'any'`, `'eq'`, `'struct'` and `'array'` | +| Defined type (the `i`th type of rec group `rec`) | `CoreDefType(rec, i)` | +| `(rec subtype*)` rec group | `CoreRecType(subtypes)` | +| `(sub final? supertype* comptype)` type | `CoreSubType(final, supertypes, comptype)` | +| Reference to the `i`th type of the same rec group | `CoreRecIdx(i)` | +| `(struct field*)` type | `CoreStructType(fields)` | +| `(array field)` type | `CoreArrayType(elem)` | +| `(field mut? storagetype)` | `CoreFieldType(t, mutable)` | +| `i8`, `i16`, `i32`, `i64`, `f32` and `f64` storage types | `'i8'`, `'i16'`, `'i32'`, `'i64'`, `'f32'` and `'f64'` | +| Defined type matching (`t1 <: t2`) | `t1.matches(t2)` | +| Null reference | `None` | +| `struct` object | `GcStruct(t, fields)` | +| `array` object | `GcArray(t, elems)` | +| `struct.new` | `struct_new(t, vs)` | +| `struct.get` and `struct.get_u` | `struct_get(s, i)` | +| `array.new_fixed` | `array_new_fixed(t, vs)` | +| `array.len` | `array_len(a)` | +| `array.get` and `array.get_u` | `array_get(a, i)` | +| `ref.test` | `ref_test(v, rt)` | + +Where the linear memory ABI uses `i32` handles to `own`s, `borrow`s, `stream`s, +`future`s, and `error-context`s, the GC ABI uses `(ref extern)` handles instead. +```python +EXTERNREF = CoreRefType('extern') + +def handle_type(cx): + if cx.opts.gc: + return EXTERNREF + else: + return 'i32' +``` + +The `gc_storage_type` function defines a component model type's lowering into a +type in the GC heap (e.g. into a standalone GC object, a `struct` field, or an +`array` element). +```python +def gc_storage_type(cx, t): + match despecialize(t): + case BoolType() | S8Type() | U8Type() : return 'i8' + case S16Type() | U16Type() : return 'i16' + case S32Type() | U32Type() | CharType() : return 'i32' + case F32Type() : return 'f32' + case S64Type() | U64Type() : return 'i64' + case F64Type() : return 'f64' + case StringType() : return CoreRefType(gc_string_type(cx)) + case ListType(t, l) : return CoreRefType(gc_list_type(cx, t)) + case RecordType(fields) : return CoreRefType(gc_record_type(cx, fields)) + case VariantType(cases) : return gc_variant_type(cx, cases) + case FlagsType(labels) : return gc_packed_int_type(elem_size_flags(labels)) + case BorrowType() : return gc_borrow_type(cx, t) + case OwnType() | StreamType() | FutureType() | ErrorContextType(): + return EXTERNREF + +def gc_borrow_type(cx, borrowt): + if pass_rep_not_handle(cx, borrowt): + return borrowt.rt.rep + else: + return EXTERNREF + +def gc_packed_int_type(nbytes): + match nbytes: + case 1: return 'i8' + case 2: return 'i16' + case 4: return 'i32' + case 8: return 'i64' +``` + +Other than the types for `variant`s, every `struct` and `array` type in the GC +ABI is `final`, has no declared supertype, has non-`mut` (immutable) fields or +elements, and is defined in its own singleton `rec` group. +```python +def gc_final_type(comptype): + return CoreDefType(CoreRecType((CoreSubType(True, (), comptype),)), 0) +``` + +UTF-8 and UTF-16 strings are `array`s of `i8` and `i16` code points +respectively. Compact `latin1+utf16` strings are lowered to `(ref array)` where +Latin1 strings are `array`s of `i8` (the same core Wasm type as UTF-8 strings). +```python +GC_UTF8_ARRAY = gc_final_type(CoreArrayType(CoreFieldType('i8'))) +GC_LATIN1_ARRAY = gc_final_type(CoreArrayType(CoreFieldType('i8'))) +GC_UTF16_ARRAY = gc_final_type(CoreArrayType(CoreFieldType('i16'))) + +def gc_string_type(cx): + match cx.opts.string_encoding: + case 'utf8' : return GC_UTF8_ARRAY + case 'utf16' : return GC_UTF16_ARRAY + case 'latin1+utf16' : return 'array' +``` + +`list`s are lowered to `array`s whose elements are of the type of the `list`'s +element type lowered to a GC heap storage type. +```python +def gc_list_type(cx, elem_type): + return gc_final_type(CoreArrayType(CoreFieldType(gc_storage_type(cx, elem_type)))) +``` + +`record`s are lowered to `struct`s whose field types are the `record`'s fields +point-wise lowered into GC heap storage types. +```python +def gc_record_type(cx, fields): + return gc_final_type(CoreStructType(tuple(CoreFieldType(gc_storage_type(cx, f.t)) for f in fields))) +``` + +`variant`s where none of the `case`s have a payload are lowered to the smallest +integer that can assign a unique number to each `case`. + +`variant`s with at least one `case` with a payload are lowered into a `rec` +group containing a non-`final` base `struct` with one discriminant field, and +each `case` is a `struct` that is `final`, declares the base as its supertype, +and appends the lowered payload as a new, non-`mut` field (if any payload is +present). The discriminant field enables $O(1)$ exhaustive matching on the +`case`s -- without it, exhaustive matching would be an $O(n)$ chain of +`br_on_cast`s or `ref.test`s. +```python +def gc_variant_type(cx, cases): + if has_payload(cases): + return CoreRefType(gc_variant_base_type(cx, cases)) + else: + return gc_storage_type(cx, discriminant_type(cases)) + +def has_payload(cases): + return any(c.t is not None for c in cases) + +def gc_variant_rec_type(cx, cases): + discriminant = CoreFieldType(gc_storage_type(cx, discriminant_type(cases))) + base = CoreSubType(False, (), CoreStructType((discriminant,))) + case_types = [] + for c in cases: + fields = (discriminant,) + if c.t is not None: + fields += (CoreFieldType(gc_storage_type(cx, c.t)),) + case_types.append(CoreSubType(True, (CoreRecIdx(0),), CoreStructType(fields))) + return CoreRecType((base, *case_types)) + +def gc_variant_base_type(cx, cases): + return CoreDefType(gc_variant_rec_type(cx, cases), 0) + +def gc_variant_case_type(cx, cases, case_index): + return CoreDefType(gc_variant_rec_type(cx, cases), 1 + case_index) +``` + +The `nullable_type` operation converts non-nullable reference types into +nullable reference types, ensuring that its result type is defaultable. The +`unpacked_type` operation converts packed `i8` and `i16` heap storage types into +`i32` value types (like core Wasm's `unpack`). They're used by 🛸 `gc` paths. +```python +def nullable_type(t): + match t: + case CoreRefType(heap_type, _) : return CoreRefType(heap_type, nullable = True) + case 'i8' | 'i16' | 'i32' | 'i64' | 'f32' | 'f64' : return t + +def unpacked_type(t): + match t: + case 'i8' | 'i16' : return 'i32' + case 'i32' | 'i64' | 'f32' | 'f64' | CoreRefType() : return t +``` + +`gc_async_results_type` returns the type of the `(ref $results)` out-param +passed to 🛸 `gc` `async`-lowered functions and to `gc` `future.read`: a `final` +struct in its own `rec` group with a single mutable, nullable field of the +result's GC heap storage type, which is overwritten when the result is ready. +```python +def gc_async_results_type(cx, t): + field = CoreFieldType(nullable_type(gc_storage_type(cx, t)), mutable = True) + return gc_final_type(CoreStructType((field,))) +``` + ## Loading The `load` function defines how to read a value of a given value type `t` @@ -2146,10 +2441,10 @@ def convert_int_to_bool(i): return bool(i) ``` -Floats are loaded directly from memory, with the sign and payload information -of NaN values discarded. Consequently, there is only one unique NaN value per -floating-point type. This reflects the practical reality that some languages -and protocols do not preserve these bits. In the Python code below, this is +Floats are loaded directly from memory, with the sign and payload information of +NaN values discarded. Consequently, there is only one unique NaN value per +floating-point type. This reflects the practical reality that some languages and +protocols do not preserve these bits. In the Python code below, this is expressed as canonicalizing NaNs to a particular bit pattern. See the comments about lowering of float values for a discussion of possible @@ -2200,11 +2495,15 @@ memory) and a number of [code units]. There are three supported string encodings in [`canonopt`]: [UTF-8], [UTF-16] and `latin1+utf16`. This last option allows a *dynamic* choice between [Latin-1] and UTF-16, indicated by the high bit of the second pointer-sized value (32nd bit on 32-bit memories, 64th bit on 64-bit -memories). String values include their original encoding and length in tagged -code units as a "hint" that enables `store_string` (defined below) to make -better up-front allocation size choices in many cases. Thus, the value produced -by `load_string` isn't simply a Python `str`, but a *tuple* containing a `str`, -the original encoding and the number of source code units. +memories). String values include a "hint" that enables `store_string` (defined +below) to make better up-front allocation size choices in many cases. Thus, the +value produced by `load_string` isn't simply a Python `str`, but a *tuple* +containing a `str`, a `StringHint` and the number of source code units (with +the UTF-16 tag removed). `StringHint` records the source encoding, splitting +`latin1+utf16` into `DYNAMIC_LATIN1` and `DYNAMIC_UTF16` according to the +dynamic choice. Because the hint is independent of the source memory's pointer +size, it can be stored into a memory with a different pointer size (and thus a +different UTF-16 tag bit). The `MAX_STRING_BYTE_LENGTH` constant limits the byte length of a string when loading. This limit is low enough to ensure that when storing the string via @@ -2214,7 +2513,13 @@ short enough to be stored in 32-bit components. The worst case inflation in string byte length is by a factor of 2 (e.g. this could occur when converting from [UTF-8] to [UTF-16]). ```python -String = tuple[str, str, int] +class StringHint(Enum): + UTF8 = 0 + UTF16 = 1 + DYNAMIC_LATIN1 = 2 + DYNAMIC_UTF16 = 3 + +String = tuple[str, StringHint, int] def load_string(cx, ptr) -> String: ptr_size = cx.opts.memory.ptr_size() @@ -2234,20 +2539,28 @@ def load_string_from_range(cx, ptr, tagged_code_units) -> String: match cx.opts.string_encoding: case 'utf8': alignment = 1 - byte_length = tagged_code_units + code_units = tagged_code_units + byte_length = code_units encoding = 'utf-8' + hint = StringHint.UTF8 case 'utf16': alignment = 2 - byte_length = 2 * tagged_code_units + code_units = tagged_code_units + byte_length = 2 * code_units encoding = 'utf-16-le' + hint = StringHint.UTF16 case 'latin1+utf16': alignment = 2 if bool(tagged_code_units & tag): - byte_length = 2 * (tagged_code_units ^ tag) + code_units = tagged_code_units ^ tag + byte_length = 2 * code_units encoding = 'utf-16-le' + hint = StringHint.DYNAMIC_UTF16 else: - byte_length = tagged_code_units + code_units = tagged_code_units + byte_length = code_units encoding = 'latin-1' + hint = StringHint.DYNAMIC_LATIN1 trap_if(byte_length > MAX_STRING_BYTE_LENGTH) trap_if(ptr != align_to(ptr, alignment)) @@ -2257,7 +2570,7 @@ def load_string_from_range(cx, ptr, tagged_code_units) -> String: except UnicodeError: trap() - return (s, cx.opts.string_encoding, tagged_code_units) + return (s, hint, code_units) ``` Error context values are lifted directly from the current component instance's @@ -2533,12 +2846,11 @@ approach to update the allocation size during the single copy. A blind `realloc` approach would normally suffer from multiple reallocations per string (e.g., using the standard doubling-growth strategy). However, as already shown in `load_string` above, string values come with two useful hints: their -original encoding and number of source [code units]. From this hint data, +`StringHint` and number of source [code units]. From this hint data, `store_string` can do a much better job minimizing the number of reallocations. -We start with a case analysis to enumerate all the meaningful encoding -combinations, subdividing the `latin1+utf16` encoding into either `latin1` or -`utf16` based on the `utf16_tag` flag set by `load_string`: +We start with a case analysis to enumerate all the meaningful combinations of +destination encoding and source `StringHint`: ```python def store_string(cx, v: String, ptr): begin, tagged_code_units = store_string_into_range(cx, v) @@ -2547,42 +2859,29 @@ def store_string(cx, v: String, ptr): store_int(cx, tagged_code_units, ptr + ptr_size, ptr_size) def store_string_into_range(cx, v: String): - src, src_encoding, src_tagged_code_units = v - tag = utf16_tag(cx) - - if src_encoding == 'latin1+utf16': - if bool(src_tagged_code_units & tag): - src_simple_encoding = 'utf16' - src_code_units = src_tagged_code_units ^ tag - else: - src_simple_encoding = 'latin1' - src_code_units = src_tagged_code_units - else: - src_simple_encoding = src_encoding - src_code_units = src_tagged_code_units - + src, src_hint, src_code_units = v match cx.opts.string_encoding: case 'utf8': - match src_simple_encoding: - case 'utf8' : return store_string_copy(cx, src, src_code_units, 1, 1, 'utf-8') - case 'utf16' : return store_utf16_to_utf8(cx, src, src_code_units) - case 'latin1' : return store_latin1_to_utf8(cx, src, src_code_units) + match src_hint: + case StringHint.UTF8 : return store_string_copy(cx, src, src_code_units, 1, 1, 'utf-8') + case StringHint.UTF16 : return store_utf16_to_utf8(cx, src, src_code_units) + case StringHint.DYNAMIC_LATIN1 : return store_latin1_to_utf8(cx, src, src_code_units) + case StringHint.DYNAMIC_UTF16 : return store_utf16_to_utf8(cx, src, src_code_units) case 'utf16': - match src_simple_encoding: - case 'utf8' : return store_utf8_to_utf16(cx, src, src_code_units) - case 'utf16' : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') - case 'latin1' : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') + match src_hint: + case StringHint.UTF8 : return store_utf8_to_utf16(cx, src, src_code_units) + case StringHint.UTF16 : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') + case StringHint.DYNAMIC_LATIN1 : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') + case StringHint.DYNAMIC_UTF16 : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') case 'latin1+utf16': - match src_encoding: - case 'utf8' : return store_string_to_latin1_or_utf16(cx, src, src_code_units) - case 'utf16' : return store_string_to_latin1_or_utf16(cx, src, src_code_units) - case 'latin1+utf16' : - match src_simple_encoding: - case 'latin1' : return store_string_copy(cx, src, src_code_units, 1, 2, 'latin-1') - case 'utf16' : return store_probably_utf16_to_latin1_or_utf16(cx, src, src_code_units) + match src_hint: + case StringHint.UTF8 : return store_string_to_latin1_or_utf16(cx, src, src_code_units) + case StringHint.UTF16 : return store_string_to_latin1_or_utf16(cx, src, src_code_units) + case StringHint.DYNAMIC_LATIN1 : return store_string_copy(cx, src, src_code_units, 1, 2, 'latin-1') + case StringHint.DYNAMIC_UTF16 : return store_probably_utf16_to_latin1_or_utf16(cx, src, src_code_units) ``` -The simplest 4 cases above can compute the exact destination size and then copy +The simplest 5 cases above can compute the exact destination size and then copy with a simply loop (that possibly inflates Latin-1 to UTF-16 by injecting a 0 byte after every Latin-1 byte). ```python @@ -2880,37 +3179,63 @@ lowered (by `canon lower`): MAX_FLAT_PARAMS = 16 MAX_FLAT_ASYNC_PARAMS = 4 MAX_FLAT_RESULTS = 1 +MAX_FLAT_GC_RESULTS = 16 def flatten_functype(cx, ft): flat_params = flatten_types(cx.reverse_direction(), ft.param_types()) flat_results = flatten_types(cx, ft.result_type()) - if not cx.opts.async_: - if len(flat_params) > MAX_FLAT_PARAMS: - flat_params = [cx.opts.memory.ptr_type()] - if len(flat_results) > MAX_FLAT_RESULTS: + if cx.opts.gc: + if not cx.opts.async_: + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [gc_storage_type(cx.reverse_direction(), TupleType(ft.param_types()))] + if len(flat_results) > MAX_FLAT_GC_RESULTS: + [result_type] = ft.result_type() + flat_results = [gc_storage_type(cx, result_type)] + else: match cx.direction: case 'lift': - flat_results = [cx.opts.memory.ptr_type()] + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [gc_storage_type(cx.reverse_direction(), TupleType(ft.param_types()))] + if cx.opts.callback: + flat_results = ['i32', nullable_type(EXTERNREF)] + else: + flat_results = [] case 'lower': - flat_params += [cx.opts.memory.ptr_type()] - flat_results = [] + if len(flat_params) > MAX_FLAT_ASYNC_PARAMS: + flat_params = [gc_storage_type(cx.reverse_direction(), TupleType(ft.param_types()))] + if len(flat_results) > 0: + [result_type] = ft.result_type() + flat_params += [CoreRefType(gc_async_results_type(cx, result_type))] + flat_results = ['i32', nullable_type(EXTERNREF)] return CoreFuncType(flat_params, flat_results) else: - match cx.direction: - case 'lift': - if len(flat_params) > MAX_FLAT_PARAMS: - flat_params = [cx.opts.memory.ptr_type()] - if cx.opts.callback: + if not cx.opts.async_: + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [cx.opts.memory.ptr_type()] + if len(flat_results) > MAX_FLAT_RESULTS: + match cx.direction: + case 'lift': + flat_results = [cx.opts.memory.ptr_type()] + case 'lower': + flat_params += [cx.opts.memory.ptr_type()] + flat_results = [] + return CoreFuncType(flat_params, flat_results) + else: + match cx.direction: + case 'lift': + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [cx.opts.memory.ptr_type()] + if cx.opts.callback: + flat_results = ['i32'] + else: + flat_results = [] + case 'lower': + if len(flat_params) > MAX_FLAT_ASYNC_PARAMS: + flat_params = [cx.opts.memory.ptr_type()] + if len(flat_results) > 0: + flat_params += [cx.opts.memory.ptr_type()] flat_results = ['i32'] - else: - flat_results = [] - case 'lower': - if len(flat_params) > MAX_FLAT_ASYNC_PARAMS: - flat_params = [cx.opts.memory.ptr_type()] - if len(flat_results) > 0: - flat_params += [cx.opts.memory.ptr_type()] - flat_results = ['i32'] - return CoreFuncType(flat_params, flat_results) + return CoreFuncType(flat_params, flat_results) def flatten_types(cx, ts): return [ft for t in ts for ft in flatten_type(cx, t)] @@ -2919,6 +3244,24 @@ As shown here, the core signatures of `async`-lowered functions use a lower limit on the maximum number of parameters (4) and results (0) passed as scalars before falling back to passing through memory. +With 🛸 `gc` flattening, when the flat parameters overflows the +`MAX_FLAT_PARAMS`, a single `(ref $params)` parameter is passed instead, where +`$params` is a GC `struct` (`final` and in its own singleton `rec` group) with +each of the parameters lowered to GC heap storage types as non-`mut` field. When +the result flattening overflows `MAX_FLAG_GC_RESULTS`, then the result type is +lowered to a GC heap storage type and returned; otherwise, when flattening does +not overflow, results are returned directly (without an out-pointer parameter) +via multi-value returns. + +With 🛸 `gc` and 🔀 `async` flattening, when `MAX_FLAT_PARAMS` overflows, +lifting spills parameters into a `(ref $params)` and, with a `callback`, return +`[i32 (ref null extern)]` (the callback code and the waitable set to wait on) or +no results for stackful concurrency. `async` lowering spills parameters past +`MAX_FLAT_ASYNC_PARAMS` into a `(ref $params)` and additionally take a `(ref +$results)` out-parameter (see `gc_async_results_type`) if there is a result; it +returns `[i32 (ref null extern)]` (the packed subtask state and index, and the +associated subtask, if any). + Presenting the definition of `flatten_type` piecewise, we start with the top-level case analysis: ```python @@ -2931,24 +3274,38 @@ def flatten_type(cx, t): case F32Type() : return ['f32'] case F64Type() : return ['f64'] case CharType() : return ['i32'] - case StringType() : return 2 * [cx.opts.memory.ptr_type()] - case ErrorContextType() : return ['i32'] + case StringType() : return flatten_string(cx) + case ErrorContextType() : return [handle_type(cx)] case ListType(t, l) : return flatten_list(cx, t, l) case RecordType(fields) : return flatten_record(cx, fields) case VariantType(cases) : return flatten_variant(cx, cases) case FlagsType(labels) : return ['i32'] - case OwnType() : return ['i32'] + case OwnType() : return [handle_type(cx)] case BorrowType() : return flatten_borrow(cx, t) - case StreamType() | FutureType() : return ['i32'] + case StreamType() | FutureType() : return [handle_type(cx)] +``` + +Strings flatten to a pointer and length into linear memory or, with 🛸 `gc`, to +a single reference to a GC array. +```python +def flatten_string(cx): + if cx.opts.gc: + return [CoreRefType(gc_string_type(cx))] + else: + return 2 * [cx.opts.memory.ptr_type()] ``` List flattening of a fixed-length list uses the same flattening as a tuple -(via `flatten_record` below). +(via `flatten_record` below), except with 🛸 `gc`, where all lists are a single +reference to a GC array. ```python def flatten_list(cx, elem_type, maybe_length): - if maybe_length is not None: - return flatten_type(cx, elem_type) * maybe_length - return 2 * [cx.opts.memory.ptr_type()] + if cx.opts.gc: + return [CoreRefType(gc_list_type(cx, elem_type))] + else: + if maybe_length is not None: + return flatten_type(cx, elem_type) * maybe_length + return 2 * [cx.opts.memory.ptr_type()] ``` Record flattening simply flattens each field in sequence. @@ -2968,17 +3325,26 @@ tightest approximation. What this means is that, regardless of the dynamic case, all flattened variants are passed with the same static set of core types, which may involve, e.g., reinterpreting an `f32` as an `i32` or zero-extending an `i32` into an `i64`. + +With 🛸 `gc`, a `variant` where none of the `case`s have a payload is flattened +identically to the linear-memory ABI. However, when any `case` has a payload, +then the `variant` is lowered with the same approach as when it is lowered to a +GC heap storage type: a base `struct` type with a discriminant field that is +subtyped for each `case`, which adds a field for the payload, when present. ```python def flatten_variant(cx, cases): - flat = [] - for c in cases: - if c.t is not None: - for i,ft in enumerate(flatten_type(cx, c.t)): - if i < len(flat): - flat[i] = join(flat[i], ft) - else: - flat.append(ft) - return flatten_type(cx, discriminant_type(cases)) + flat + if cx.opts.gc and has_payload(cases): + return [CoreRefType(gc_variant_base_type(cx, cases))] + else: + flat = [] + for c in cases: + if c.t is not None: + for i,ft in enumerate(flatten_type(cx, c.t)): + if i < len(flat): + flat[i] = join(flat[i], ft) + else: + flat.append(ft) + return flatten_type(cx, discriminant_type(cases)) + flat def join(a, b): if a == b: return a @@ -2991,9 +3357,10 @@ that defined its resource type is passed as its representation value: ```python def flatten_borrow(cx, borrowt): if pass_rep_not_handle(cx, borrowt): + assert(cx.opts.gc or borrowt.rt.rep in ['i32', 'i64']) return [borrowt.rt.rep] else: - return ['i32'] + return [handle_type(cx)] ``` ## Flat Lifting @@ -3017,6 +3384,7 @@ class CoreValueIter: case 'i64': assert(isinstance(v, int) and 0 <= v < 2**64) case 'f32': assert(isinstance(v, (int,float))) case 'f64': assert(isinstance(v, (int,float))) + case CoreRefType(): assert(ref_test(v, t)) case _ : assert(False) return v ``` @@ -3042,15 +3410,15 @@ def lift_flat(cx, vi, t): case F64Type() : return canonicalize_nan64(vi.next('f64')) case CharType() : return convert_i32_to_char(cx, vi.next('i32')) case StringType() : return lift_flat_string(cx, vi) - case ErrorContextType() : return lift_error_context(cx, vi.next('i32')) + case ErrorContextType() : return lift_error_context(cx, lift_flat_handle(cx, vi)) case ListType(t, l) : return lift_flat_list(cx, vi, t, l) case RecordType(fields) : return lift_flat_record(cx, vi, fields) case VariantType(cases) : return lift_flat_variant(cx, vi, cases) case FlagsType(labels) : return lift_flat_flags(vi, labels) - case OwnType() : return lift_own(cx, vi.next('i32'), t) - case BorrowType() : return lift_borrow(cx, vi.next('i32'), t) - case StreamType(t) : return lift_stream(cx, vi.next('i32'), t) - case FutureType(t) : return lift_future(cx, vi.next('i32'), t) + case OwnType() : return lift_own(cx, lift_flat_handle(cx, vi), t) + case BorrowType() : return lift_borrow(cx, lift_flat_handle(cx, vi), t) + case StreamType(t) : return lift_stream(cx, lift_flat_handle(cx, vi), t) + case FutureType(t) : return lift_future(cx, lift_flat_handle(cx, vi), t) ``` Integers are lifted from core `i32` or `i64` values using the signedness of the @@ -3068,9 +3436,12 @@ def lift_flat_unsigned(vi, core_width, t_width): def lift_flat_signed(vi, core_width, t_width): i = vi.next('i' + str(core_width)) assert(0 <= i < (1 << core_width)) - i %= (1 << t_width) - if i >= (1 << (t_width - 1)): - return i - (1 << t_width) + return lift_signed(i % (1 << t_width), t_width) + +def lift_signed(i, width): + assert(0 <= i < (1 << width)) + if i >= (1 << (width - 1)): + return i - (1 << width) return i ``` @@ -3081,19 +3452,89 @@ instead of from linear memory. Fixed-length lists are lifted the same way as a tuple. ```python def lift_flat_string(cx, vi): - ptr = vi.next(cx.opts.memory.ptr_type()) - packed_length = vi.next(cx.opts.memory.ptr_type()) - return load_string_from_range(cx, ptr, packed_length) + if cx.opts.gc: + return lift_gc_string(cx, vi.next(CoreRefType(gc_string_type(cx)))) + else: + ptr = vi.next(cx.opts.memory.ptr_type()) + packed_length = vi.next(cx.opts.memory.ptr_type()) + return load_string_from_range(cx, ptr, packed_length) def lift_flat_list(cx, vi, elem_type, maybe_length): + if cx.opts.gc: + return lift_gc_list(cx, vi.next(CoreRefType(gc_list_type(cx, elem_type))), elem_type, maybe_length) + else: + if maybe_length is not None: + a = [] + for i in range(maybe_length): + a.append(lift_flat(cx, vi, elem_type)) + return a + ptr = vi.next(cx.opts.memory.ptr_type()) + length = vi.next(cx.opts.memory.ptr_type()) + return load_list_from_range(cx, ptr, length, elem_type) +``` + +With 🛸 `gc`, UTF-8 `string`s are lifted out of an `(array i8)` of UTF-8 code +point elements and UTF-16 `string`s are lifted out of an `(array i16)` of UTF-16 +code point elements. Compact `latin1+utf16`-encoded `string`s are passed as +`(ref array)`s and are `ref.test`ed to be either an `(array i8)` of Latin-1 code +points or an `(array i16)` of UTF-16 code points and then re-encoded +appropriately. If, however, the given `(ref array)` is not one of those two +types, then a trap is raised. +```python +def lift_gc_string(cx, arr) -> String: + match cx.opts.string_encoding: + case 'utf8': + code_unit_size = 1 + encoding = 'utf-8' + hint = StringHint.UTF8 + case 'utf16': + code_unit_size = 2 + encoding = 'utf-16-le' + hint = StringHint.UTF16 + case 'latin1+utf16': + if ref_test(arr, CoreRefType(GC_LATIN1_ARRAY)): + code_unit_size = 1 + encoding = 'latin-1' + hint = StringHint.DYNAMIC_LATIN1 + else: + trap_if(not ref_test(arr, CoreRefType(GC_UTF16_ARRAY))) + code_unit_size = 2 + encoding = 'utf-16-le' + hint = StringHint.DYNAMIC_UTF16 + + code_units = array_len(arr) + trap_if(code_units * code_unit_size > MAX_STRING_BYTE_LENGTH) + encoded = b''.join(int.to_bytes(array_get(arr, i), code_unit_size, 'little') for i in range(code_units)) + try: + s = encoded.decode(encoding) + except UnicodeError: + trap() + + return (s, hint, code_units) +``` + +When lifting 🛸 `gc` lists, elements are lifted out of GC `array`s. If a +fixed-length is specified and the `array`'s actual length does not match the +specified fixed-length, then a trap is raised. When the `array` elements have a +defined byte size, then the sum or element sizes is compared to +`MAX_LIST_BYTE_LENGTH`, and a trap is raised if the sum is greater than the +maximum. Finally, each `array` element is lifted into a `list` element via +`lift_gc_value`. +```python +def lift_gc_list(cx, arr, elem_type, maybe_length): + length = array_len(arr) if maybe_length is not None: - a = [] - for i in range(maybe_length): - a.append(lift_flat(cx, vi, elem_type)) - return a - ptr = vi.next(cx.opts.memory.ptr_type()) - length = vi.next(cx.opts.memory.ptr_type()) - return load_list_from_range(cx, ptr, length, elem_type) + trap_if(length != maybe_length) + elif not isinstance(gc_storage_type(cx, elem_type), CoreRefType): + trap_if(length * elem_size(cx, elem_type) > MAX_LIST_BYTE_LENGTH) + else: + # TODO FITZGEN: How do we want to impose `MAX_LIST_BYTE_LENGTH` on arrays of + # references? Do we want to even impose any limit in this case? + pass + a = [] + for i in range(length): + a.append(lift_gc_value(cx, array_get(arr, i), elem_type)) + return a ``` Records are lifted by recursively lifting their fields: @@ -3113,34 +3554,62 @@ reinterprets between the different types appropriately and also wraps `i64` values to 32-bit when needed: ```python def lift_flat_variant(cx, vi, cases): - flat_types = flatten_variant(cx, cases) - assert(flat_types.pop(0) == 'i32') - case_index = vi.next('i32') - trap_if(case_index >= len(cases)) - class CoerceValueIter: - def next(self, want): - have = flat_types.pop(0) - x = vi.next(have) - match (have, want): - case ('i32', 'f32') : return decode_i32_as_float(x) - case ('i64', 'i32') : return wrap_i64_to_i32(x) - case ('i64', 'f32') : return decode_i32_as_float(wrap_i64_to_i32(x)) - case ('i64', 'f64') : return decode_i64_as_float(x) - case _ : assert(have == want); return x - c = cases[case_index] - if c.t is None: - v = None + if cx.opts.gc and has_payload(cases): + return lift_gc_variant(cx, vi.next(CoreRefType(gc_variant_base_type(cx, cases))), cases) else: - v = lift_flat(cx, CoerceValueIter(), c.t) - for have in flat_types: - _ = vi.next(have) - return { c.label: v } + flat_types = flatten_variant(cx, cases) + assert(flat_types.pop(0) == 'i32') + case_index = vi.next('i32') + trap_if(case_index >= len(cases)) + class CoerceValueIter: + def next(self, want): + have = flat_types.pop(0) + x = vi.next(have) + match (have, want): + case ('i32', 'f32') : return decode_i32_as_float(x) + case ('i64', 'i32') : return wrap_i64_to_i32(x) + case ('i64', 'f32') : return decode_i32_as_float(wrap_i64_to_i32(x)) + case ('i64', 'f64') : return decode_i64_as_float(x) + case _ : assert(have == want); return x + c = cases[case_index] + if c.t is None: + v = None + else: + v = lift_flat(cx, CoerceValueIter(), c.t) + for have in flat_types: + _ = vi.next(have) + return { c.label: v } def wrap_i64_to_i32(i): assert(0 <= i < (1 << 64)) return i % (1 << 32) ``` +When lifting 🛸 `gc` variants, if the `variant`'s `case`s all do not have any +payload, then the value is a discriminant integer, which is checked for validity +(trapping if invalid) and the payload-free `case` is returned. When at least one +of the `case`s has a payload, then the value is a `(ref $base)`. The +`case_index` discriminant is read via `struct.get` and checked for validity +(trapping if invalid). Then it is checked that the given `(ref $base)` is an +instance of the `case_index`th `case`'s `struct` lowering (which is a subtype of +`$base`) with `ref.test`, and a trap is raised if it is not. Then the `case` is +lifted, along with its payload (if present), which is read via `struct.get` on +the downcasted reference. +```python +def lift_gc_variant(cx, v, cases): + if has_payload(cases): + case_index = struct_get(v, 0) + trap_if(case_index >= len(cases)) + trap_if(not ref_test(v, CoreRefType(gc_variant_case_type(cx, cases, case_index)))) + c = cases[case_index] + if c.t is None: + return { c.label: None } + return { c.label: lift_gc_value(cx, struct_get(v, 1), c.t) } + else: + trap_if(v >= len(cases)) + return { cases[v].label: None } +``` + Finally, flags are lifted by lifting to a record the same way as when loading flags from linear memory. ```python @@ -3150,6 +3619,91 @@ def lift_flat_flags(vi, labels): return unpack_flags_from_int(i, labels) ``` +With the default linear-memory ABI, `resource` handles (and `stream`, `future` +and `error-context` values) are lifted from `i32` table indices. With the 🛸 +`gc` ABI, they are instead lifted from `(ref extern)` `HandleRef` objects that +box the `i32` table index. A trap is raised if any other kind of `(ref extern)` +is given. + +Each `i32` handle has at most one associated `HandleRef` (tracked in its +`TableEntry`; attempting to create a second one traps. Unboxing a stale +`HandleRef` (whose handle has since been removed from the table) traps. + +> Non-normative note: the one-`HandleRef`-per-table-entry property sets the +> stage for automatically dropping owned resource handles and closing +> streams/futures when their `HandleRef` is garbage collected. + +```python +class HandleRef: + index: int + + def __init__(self, inst, index): + inst.handles.set_handle_ref(index, self) + self.index = index + +def lift_flat_handle(cx, vi): + v = vi.next(handle_type(cx)) + if cx.opts.gc: + return unbox_handle(cx.inst, v) + else: + return v + +def unbox_handle(inst, r): + trap_if(not isinstance(r, HandleRef)) + trap_if(inst.handles.get_handle_ref(r.index) is not r) + return r.index +``` + +🛸 `lift_gc_value` lifts a single instance of a GC heap storage type (a `struct` +field, `array` element, or `variant` payload) into a component model +value. Packed `i8` and `i16` storage values were already zero-extended to their +exact bit width when read out of their `struct` or `array` (via +e.g. `struct.get_u` when necessary) and into an instance of a value type; +therefore unsigned integers can be returned directly, while signed integers must +be sign-extended via `lift_signed`. + +> Non-normative note: it is expected that non-reference, production +> implementations can simply use e.g. `struct.get_s` when lifting signed +> integers out of packed fields and elements, but that optimization would +> complicate this specification and reference implementation slightly, and the +> reference implementation's goal is clarity not optimization. +```python +def lift_gc_value(cx, v, t): + match despecialize(t): + case BoolType() : return convert_int_to_bool(v) + case U8Type() : return v + case S8Type() : return lift_signed(v, 8) + case U16Type() : return v + case S16Type() : return lift_signed(v, 16) + case U32Type() : return v + case S32Type() : return lift_signed(v, 32) + case CharType() : return convert_i32_to_char(cx, v) + case F32Type() : return canonicalize_nan32(v) + case U64Type() : return v + case S64Type() : return lift_signed(v, 64) + case F64Type() : return canonicalize_nan64(v) + case StringType() : return lift_gc_string(cx, v) + case ListType(t, l) : return lift_gc_list(cx, v, t, l) + case RecordType(fields) : return lift_gc_record(cx, v, fields) + case VariantType(cases) : return lift_gc_variant(cx, v, cases) + case FlagsType(labels) : return unpack_flags_from_int(v, labels) + case BorrowType() : return lift_borrow(cx, unbox_handle(cx.inst, v), t) + case OwnType() : return lift_own(cx, unbox_handle(cx.inst, v), t) + case StreamType(t) : return lift_stream(cx, unbox_handle(cx.inst, v), t) + case FutureType(t) : return lift_future(cx, unbox_handle(cx.inst, v), t) + case ErrorContextType() : return lift_error_context(cx, unbox_handle(cx.inst, v)) +``` + +With 🛸 `gc`, `record`s are lifted from GC heap storage by recursively lifting +their fields: +```python +def lift_gc_record(cx, s, fields): + record = {} + for i,f in enumerate(fields): + record[f.label] = lift_gc_value(cx, struct_get(s, i), f.t) + return record +``` + ## Flat Lowering The `lower_flat` function defines how to convert a value `v` of a given type @@ -3171,15 +3725,15 @@ def lower_flat(cx, v, t): case F64Type() : return [maybe_scramble_nan64(v)] case CharType() : return [char_to_i32(v)] case StringType() : return lower_flat_string(cx, v) - case ErrorContextType() : return [lower_error_context(cx, v)] + case ErrorContextType() : return [lower_flat_handle(cx, lower_error_context(cx, v))] case ListType(t, l) : return lower_flat_list(cx, v, t, l) case RecordType(fields) : return lower_flat_record(cx, v, fields) case VariantType(cases) : return lower_flat_variant(cx, v, cases) case FlagsType(labels) : return lower_flat_flags(v, labels) case OwnType() : return lower_flat_own(cx, v, t) case BorrowType() : return lower_flat_borrow(cx, v, t) - case StreamType(t) : return [lower_stream(cx, v, t)] - case FutureType(t) : return [lower_future(cx, v, t)] + case StreamType(t) : return [lower_flat_handle(cx, lower_stream(cx, v, t))] + case FutureType(t) : return [lower_flat_handle(cx, lower_future(cx, v, t))] ``` Since component-level values are assumed in-range and, as previously stated, @@ -3189,9 +3743,12 @@ converted to unsigned core `i32` or `i64` values by 2s complement arithmetic (which again would be a no-op in hardware): ```python def lower_flat_signed(i, core_bits): + return [lower_signed(i, core_bits)] + +def lower_signed(i, width): if i < 0: - i += (1 << core_bits) - return [i] + i += (1 << width) + return i ``` Since strings and variable-length lists are stored in linear memory, lowering @@ -3200,18 +3757,59 @@ differently (as flat values instead of as a pair in linear memory). Fixed-length lists are lowered the same way as tuples. ```python def lower_flat_string(cx, v): - ptr, packed_length = store_string_into_range(cx, v) - return [ptr, packed_length] + if cx.opts.gc: + return [lower_gc_string(cx, v)] + else: + ptr, packed_length = store_string_into_range(cx, v) + return [ptr, packed_length] def lower_flat_list(cx, v, elem_type, maybe_length): - if maybe_length is not None: - assert(maybe_length == len(v)) - flat = [] - for e in v: - flat += lower_flat(cx, e, elem_type) - return flat - (ptr, length) = store_list_into_range(cx, v, elem_type) - return [ptr, length] + if cx.opts.gc: + return [lower_gc_list(cx, v, elem_type, maybe_length)] + else: + if maybe_length is not None: + assert(maybe_length == len(v)) + flat = [] + for e in v: + flat += lower_flat(cx, e, elem_type) + return flat + (ptr, length) = store_list_into_range(cx, v, elem_type) + return [ptr, length] +``` + +🛸 `gc` strings are lowered into new `array` objects. With the compact +`latin1+utf16` encoding, if every character can be encoded in Latin-1, then an +`(array i8)` of Latin-1 code points is returned; otherwise, an `(array i16)` of +UTF-16 code points is returned. With the `utf8` encoding, an `(array i8)` of +UTF-8 code points is returned. With the `utf16` encoding, an `(array i16)` of +UTF-16 code points is returned. +```python +def lower_gc_string(cx, v: String): + src, _, _ = v + match cx.opts.string_encoding: + case 'utf8': + return array_new_fixed(GC_UTF8_ARRAY, list(src.encode('utf-8'))) + case 'utf16': + return array_new_fixed(GC_UTF16_ARRAY, encode_utf16_code_units(src)) + case 'latin1+utf16': + if all(ord(c) < (1 << 8) for c in src): + return array_new_fixed(GC_LATIN1_ARRAY, list(src.encode('latin-1'))) + return array_new_fixed(GC_UTF16_ARRAY, encode_utf16_code_units(src)) + +def encode_utf16_code_units(src): + encoded = src.encode('utf-16-le') + return [int.from_bytes(encoded[i : i+2], 'little') for i in range(0, len(encoded), 2)] +``` + +🛸 `gc` lists are lowered (regardless whether they have a fixed-length or not) +to new `array` objects. +```python +def lower_gc_list(cx, v, elem_type, maybe_length): + assert(maybe_length is None or maybe_length == len(v)) + elems = [] + for e in v: + elems.append(lower_gc_value(cx, e, elem_type)) + return array_new_fixed(gc_list_type(cx, elem_type), elems) ``` Records are lowered by recursively lowering their fields: @@ -3228,25 +3826,45 @@ Variants are also lowered recursively. Symmetric to `lift_flat_variant` above, manually coercing the otherwise-incompatible type pairings allowed by `join`: ```python def lower_flat_variant(cx, v, cases): + if cx.opts.gc and has_payload(cases): + return [lower_gc_variant(cx, v, cases)] + else: + case_index, case_value = match_case(v, cases) + flat_types = flatten_variant(cx, cases) + assert(flat_types.pop(0) == 'i32') + c = cases[case_index] + if c.t is None: + payload = [] + else: + payload = lower_flat(cx, case_value, c.t) + for i,(fv,have) in enumerate(zip(payload, flatten_type(cx, c.t))): + want = flat_types.pop(0) + match (have, want): + case ('f32', 'i32') : payload[i] = encode_float_as_i32(fv) + case ('i32', 'i64') : payload[i] = fv + case ('f32', 'i64') : payload[i] = encode_float_as_i32(fv) + case ('f64', 'i64') : payload[i] = encode_float_as_i64(fv) + case _ : assert(have == want) + for _ in flat_types: + payload.append(0) + return [case_index] + payload +``` + +With 🛸 `gc`, `variant`s where at least one `case` has a payload are lowered +into a new `struct` of that `case`'s `struct` type lowering and with its first +field set to its `case`-index discriminant. `variant`s where no `case` has a +payload are lowered into their `case`-index discriminant integer directly. +```python +def lower_gc_variant(cx, v, cases): case_index, case_value = match_case(v, cases) - flat_types = flatten_variant(cx, cases) - assert(flat_types.pop(0) == 'i32') - c = cases[case_index] - if c.t is None: - payload = [] + if has_payload(cases): + fields = [case_index] + c = cases[case_index] + if c.t is not None: + fields.append(lower_gc_value(cx, case_value, c.t)) + return struct_new(gc_variant_case_type(cx, cases, case_index), fields) else: - payload = lower_flat(cx, case_value, c.t) - for i,(fv,have) in enumerate(zip(payload, flatten_type(cx, c.t))): - want = flat_types.pop(0) - match (have, want): - case ('f32', 'i32') : payload[i] = encode_float_as_i32(fv) - case ('i32', 'i64') : payload[i] = fv - case ('f32', 'i64') : payload[i] = encode_float_as_i32(fv) - case ('f64', 'i64') : payload[i] = encode_float_as_i64(fv) - case _ : assert(have == want) - for _ in flat_types: - payload.append(0) - return [case_index] + payload + return case_index ``` Flags are lowered by packing the flags into an `i32` bitvector. @@ -3260,7 +3878,7 @@ Owned handles are lowered the same way as in `store_own`, except the `i32` table index is returned directly. ```python def lower_flat_own(cx, rep_val, ownt): - return [add_own(cx, rep_val, ownt)] + return [lower_flat_handle(cx, add_own(cx, rep_val, ownt))] ``` Lastly, borrowed handles are lowered with the same optimization as @@ -3270,7 +3888,73 @@ def lower_flat_borrow(cx, rep_val, borrowt): if pass_rep_not_handle(cx, borrowt): return [rep_val] else: - return [add_borrow(cx, rep_val, borrowt)] + return [lower_flat_handle(cx, add_borrow(cx, rep_val, borrowt))] +``` + +In the default linear-memory ABI, handle indices are loweed into `i32` table +indices. With 🛸 `gc`, they are instead boxed into `HandleRef` objects and +returned as `(ref extern)` reference values. +```python +def lower_flat_handle(cx, i): + if cx.opts.gc: + return HandleRef(cx.inst, i) + else: + return i +``` + +🛸 The `lower_gc_value` is the inverse of `lift_gc_value`: it lowers a single +component model value into an instance of a GC heap storage type. It is used +when lowering a value into a GC `struct` field or `array` element (as opposed to +flat values for function parameters or results). Unsigned component model +integers are already in their already in range for their associated +two's-complement core value. Signed integers are converted to their +two's-complement core value representation at their type's width by +`lower_signed`. +```python +def lower_gc_value(cx, v, t): + match despecialize(t): + case BoolType() : return int(v) + case U8Type() : return v + case S8Type() : return lower_signed(v, 8) + case U16Type() : return v + case S16Type() : return lower_signed(v, 16) + case U32Type() : return v + case S32Type() : return lower_signed(v, 32) + case CharType() : return char_to_i32(v) + case F32Type() : return maybe_scramble_nan32(v) + case U64Type() : return v + case S64Type() : return lower_signed(v, 64) + case F64Type() : return maybe_scramble_nan64(v) + case StringType() : return lower_gc_string(cx, v) + case ListType(t, l) : return lower_gc_list(cx, v, t, l) + case RecordType(fields) : return lower_gc_record(cx, v, fields) + case VariantType(cases) : return lower_gc_variant(cx, v, cases) + case FlagsType(labels) : return pack_flags_into_int(v, labels) + case BorrowType() : return lower_gc_borrow(cx, v, t) + case OwnType() : return HandleRef(cx.inst, add_own(cx, v, t)) + case StreamType(t) : return HandleRef(cx.inst, lower_stream(cx, v, t)) + case FutureType(t) : return HandleRef(cx.inst, lower_future(cx, v, t)) + case ErrorContextType() : return HandleRef(cx.inst, lower_error_context(cx, v)) +``` + +With 🛸 `gc`, `borrow`s are passed as their `rep` to the `resource`'s defining +component, same as with `lower_flat_borrow`. +```python +def lower_gc_borrow(cx, rep_val, borrowt): + if pass_rep_not_handle(cx, borrowt): + return rep_val + else: + return HandleRef(cx.inst, add_borrow(cx, rep_val, borrowt)) +``` + +With 🛸 `gc`, `record`s are recursively lowered a field at a time, and then a +new GC `struct` object is allocated with the lowered fields. +```python +def lower_gc_record(cx, v, fields): + vs = [] + for f in fields: + vs.append(lower_gc_value(cx, v[f.label], f.t)) + return struct_new(gc_record_type(cx, fields), vs) ``` ## Lifting and Lowering Values @@ -3279,14 +3963,22 @@ The `lift_flat_values` function defines how to lift a list of core parameters or results (given by the `CoreValueIter` `vi`) into a tuple of component-level values with types `ts`. ```python -def lift_flat_values(cx, max_flat, vi, ts): +def lift_flat_values(cx, max_flat, vi, ts, is_result = False): flat_types = flatten_types(cx, ts) if len(flat_types) > max_flat: - ptr = vi.next(cx.opts.memory.ptr_type()) - tuple_type = TupleType(ts) - trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) - trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) - return list(load(cx, ptr, tuple_type).values()) + if cx.opts.gc: + if is_result: + [t] = ts + return [lift_gc_value(cx, vi.next(gc_storage_type(cx, t)), t)] + else: + tuple_type = TupleType(ts) + return list(lift_gc_value(cx, vi.next(gc_storage_type(cx, tuple_type)), tuple_type).values()) + else: + ptr = vi.next(cx.opts.memory.ptr_type()) + tuple_type = TupleType(ts) + trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) + trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) + return list(load(cx, ptr, tuple_type).values()) else: return [ lift_flat(cx, vi, t) for t in ts ] ``` @@ -3298,20 +3990,33 @@ lowering handles the greater-than-`max_flat` case by either allocating storage with `realloc` or accepting a caller-allocated buffer as an out-param: ```python -def lower_flat_values(cx, max_flat, vs, ts, out_param = None): +def lower_flat_values(cx, max_flat, vs, ts, out_param = None, is_result = False): flat_types = flatten_types(cx, ts) if len(flat_types) > max_flat: tuple_type = TupleType(ts) tuple_value = {str(i): v for i,v in enumerate(vs)} - if out_param is None: - ptr = cx.allocate(alignment(cx, tuple_type), elem_size(cx, tuple_type)) - flat_vals = [ptr] + if cx.opts.gc: + if is_result: + [v] = vs + [t] = ts + if cx.opts.async_: + results = out_param.next(CoreRefType(gc_async_results_type(cx, t))) + struct_set(results, 0, lower_gc_value(cx, v, t)) + return [] + else: + return [lower_gc_value(cx, v, t)] + else: + return [lower_gc_value(cx, tuple_value, tuple_type)] else: - ptr = out_param.next(cx.opts.memory.ptr_type()) - trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) - trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) - flat_vals = [] - store(cx, tuple_value, tuple_type, ptr) + if out_param is None: + ptr = cx.allocate(alignment(cx, tuple_type), elem_size(cx, tuple_type)) + flat_vals = [ptr] + else: + ptr = out_param.next(cx.opts.memory.ptr_type()) + trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) + trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) + flat_vals = [] + store(cx, tuple_value, tuple_type, ptr) else: flat_vals = [] for i in range(len(vs)): @@ -3319,6 +4024,16 @@ def lower_flat_values(cx, max_flat, vs, ts, out_param = None): return flat_vals ``` +With 🛸 `gc`, when the flat parameters overflow their maximum, the parameters +are lifted from and lowered into a single `(ref $params)` reference +instead. That `$params` object is a `struct` that is `final`, has no supertype, +is defined in its own singleton `rec` group, and has a non-`mut` field for every +parameter, which is an instance of the GC heap storage type lowering of the +field's component model type. When the flat results overflow their maximum, then +the component model result type is lowered to a GC heap storage type, and +results are lifted into and lowered from that type directly. The `is_result` +parameter to `{lift,lower}_flat_values` discriminates between these cases. + ## Canonical Definitions @@ -3334,31 +4049,59 @@ specifying `string-encoding=utf8` twice is an error. Each individual option, if present, is validated as such: * `string-encoding=N` - can be passed at most once, regardless of `N`. + * `memory` - this is a subtype of `(memory 0)` + * 🐘 `memory` may also be a subtype of `(memory i64 0)` + * `realloc` - the function has type `(func (param addr addr addr addr) (result addr))` where `addr` is the address type coming from the [`memtype`] of the `memory` canonopt (restricted to `i32`, but with 🐘 may also be `i64`). + * if `realloc` is present then `memory` must be present + * `post-return` - only allowed on [`canon lift`](#canon-lift), which has rules for validation + * 🔀 `async` - is only allowed when used with an `async` function type in [`canon lift`](#canon-lift) or [`canon lower`](#canon-lower) and cannot be present with `post-return` + * 🔀,not(🚟) `async` - `callback` must also be present. Note that with the 🚟 feature (the "stackful" ABI), this restriction is lifted. + * 🔀 `callback` - the function has type `(func (param i32 i32 i32) (result i32))` and cannot be present without `async` and is only allowed with [`canon lift`](#canon-lift) + * 🛸 with `gc`, the function instead has type `(func (param i32 i32 (ref null + extern)) (result i32 (ref null extern)))` + +* 🛸 `gc` - The `gc` option is allowed on every canonical definition that takes + `$opts`: ([`canon lift`](#canon-lift), [`canon lower`](#canon-lower), [`canon + task.return`](#-canon-taskreturn), [`canon + {stream,future}.{read,write}`](#-canon-streamfuturereadwrite) and [`canon + error-context.{new,debug-message}`](#-canon-error-contextnew)). The `gc` + option switches its associated definition from the default linear-memory ABI + to the GC ABI. The `gc` option must not be present alongside `memory` (and + thus not with `realloc`). + + > Non-normative note: for the canonical definitions that do not take `$opts`, + > and so the `gc` option cannot be used to switch them over to the GC ABI, + > there is a `gc.*` canonical definition that is equivalent to its associated + > non-`gc.`-prefixed canonical definition, but which uses the GC ABI instead + > of the default linear-memory ABI. + Additionally some options are required depending on lift/lower operations performed for a component. These are defined as: * `lower(T)` - * requires `memory` if `T` contains a `list` or `string` + * requires `memory` if `T` contains a `list` or `string` (unless 🛸 `gc` is + present) * `lift(T)` - * requires `realloc` if `T` contains a `list` or `string` + * requires `realloc` if `T` contains a `list` or `string` (unless 🛸 `gc` is + present) Value types used by `lift`/`lower` are already rejected at `defvaltype` definition if they exceed the [Element Size](#element-size) bound. @@ -3375,12 +4118,21 @@ validation is performed with `cx = LiftLowerContext('lift', $opts, inst)` where `inst` is the component instance containing this lifting definition: * `$callee` must have type `flatten_functype(cx, $ft)` + * 🛸 with `gc`, `$callee`'s type must instead [match] `flatten_functype(cx, $ft)` * `$f` is given type `$ft` * if a `post-return` is present, it has type `(func (param flatten_functype(cx, $ft).results))` + * 🛸 with `gc`, `post-return`'s type must instead [match] `(func (param + flatten_functype(cx, $ft).results))` * requires options based on [`lift(param)`](#canonopt-validation) for all parameters in `ft` * requires options based on [`lower(result)`](#canonopt-validation) if `ft` has a result -* if `len(flatten_types(ft.param_types())) > MAX_FLAT_PARAMS`, `realloc` is required -* if `len(flatten_types(ft.result_type())) > max` (where `max = MAX_FLAT_RESULTS` for sync lifts, and `max = MAX_FLAT_PARAMS` for async lifts), `memory` is required +* if `len(flatten_types(ft.param_types())) > MAX_FLAT_PARAMS`, `realloc` is + required (unless 🛸 `gc` is present) +* if `len(flatten_types(ft.result_type())) > max` (where `max = + MAX_FLAT_RESULTS` for sync lifts, and `max = MAX_FLAT_PARAMS` for async + lifts), `memory` is required (unless 🛸 `gc` is present) +* If 🛸 `gc` is not present, it is a validation error for a `borrow` of a + resource type with a `(ref any)` representation to be passed as its + representation Note that an `async`-lifted function whose result type requires a memory to lift (either because it contains lists or strings or because the number of flattened @@ -3431,7 +4183,8 @@ function can free any associated allocations. if not opts.async_: flat_results = call_and_trap_on_throw(callee, flat_args) assert(types_match_values(flat_ft.results, flat_results)) - result = lift_flat_values(cx, MAX_FLAT_RESULTS, CoreValueIter(flat_results), ft.result_type()) + max_flat_results = MAX_FLAT_GC_RESULTS if opts.gc else MAX_FLAT_RESULTS + result = lift_flat_values(cx, max_flat_results, CoreValueIter(flat_results), ft.result_type(), is_result = True) task.return_(result) if opts.post_return is not None: assert(cx.inst.may_leave) @@ -3474,8 +4227,12 @@ first calling the core wasm callee and then repeatedly calling the `callback` function (specified as a `funcidx` immediate in `canon lift`) until the `EXIT` code (`0`) is returned: ```python - [packed] = call_and_trap_on_throw(callee, flat_args) - code,si = unpack_callback_result(packed) + if opts.gc: + [code, sr] = call_and_trap_on_throw(callee, flat_args) + code,si = unpack_gc_callback_result(inst, code, sr) + else: + [packed] = call_and_trap_on_throw(callee, flat_args) + code,si = unpack_callback_result(packed) while code != CallbackCode.EXIT: if thread.task.deliver_pending_cancel(): event = (EventCode.TASK_CANCELLED, 0, 0) @@ -3499,9 +4256,13 @@ function (specified as a `funcidx` immediate in `canon lift`) until the assert(inst.exclusive_thread is None) thread.cancellable = False inst.exclusive_thread = task.implicit_thread - event_code, p1, p2 = event - [packed] = call_and_trap_on_throw(opts.callback, [event_code, p1, p2]) - code,si = unpack_callback_result(packed) + if opts.gc: + [code, sr] = call_and_trap_on_throw(opts.callback, unpack_gc_event(inst, event)) + code,si = unpack_gc_callback_result(inst, code, sr) + else: + event_code, p1, p2 = event + [packed] = call_and_trap_on_throw(opts.callback, [event_code, p1, p2]) + code,si = unpack_callback_result(packed) task.exit_implicit_thread() return ``` @@ -3581,7 +4342,21 @@ def unpack_callback_result(packed): assert(Table.MAX_LENGTH < 2**28) waitable_set_index = packed >> 4 return (CallbackCode(code), waitable_set_index) + +def unpack_gc_callback_result(inst, code, sr): + trap_if(code > CallbackCode.MAX) + if code == CallbackCode.WAIT and sr is not None: + waitable_set_index = unbox_handle(inst, sr) + else: + waitable_set_index = 0 + return (CallbackCode(code), waitable_set_index) ``` +With 🛸 `gc`, the callee and `callback` return the callback code and +additionally the waitable set (a `(ref null extern)`, which is only unboxed when +the code is `WAIT`, and which traps on null) as two results instead of one +packed `i32`, and the `callback` receives the event code, payload and waitable +(as returned by `gc.waitable-set.{wait,poll}`) instead of three `i32`s. + The ability to asynchronously wait, yield and exit is thus available to both the `callback` and non-`callback` cases, making `callback` just an optimization to avoid allocating stacks for async languages that have avoided @@ -3617,8 +4392,13 @@ instance containing this lowering definition: * `$f` is given type `flatten_functype(cx, ft)` * requires options [based on `lower(param)`](#canonopt-validation) for all parameters in `ft` * requires options [based on `lift(result)`](#canonopt-validation) if `ft` has a result -* if `len(flatten_types(ft.param_types())) > max_flat_params`, `memory` is required -* if `len(flatten_types(ft.result_type())) > max_flat_results`, `memory` is required +* if `len(flatten_types(ft.param_types())) > max_flat_params`, `memory` is + required (unless 🛸 `gc` is present) +* if `len(flatten_types(ft.result_type())) > max_flat_results`, `memory` is + required (unless 🛸 `gc` is present) +* If 🛸 `gc` is not present, it is a validation error for a `borrow` of a + resource type with a `(ref any)` representation to be passed as its + representation When instantiating a component instance, the runtime calls `Store.lower` (defined above) to capture the `$callee` and `$opts` immediates of `canon lower` along @@ -3649,7 +4429,7 @@ The values of `max_flat_{params,results}` mirror the flattening logic in if not opts.async_: max_flat_params = MAX_FLAT_PARAMS - max_flat_results = MAX_FLAT_RESULTS + max_flat_results = MAX_FLAT_GC_RESULTS if opts.gc else MAX_FLAT_RESULTS else: max_flat_params = MAX_FLAT_ASYNC_PARAMS max_flat_results = 0 @@ -3681,7 +4461,7 @@ caller. subtask.resolve(Subtask.State.CANCELLED_BEFORE_RETURNED, []) else: assert(subtask.state == Subtask.State.STARTED) - flat_results = lower_flat_values(cx, max_flat_results, result, ft.result_type(), flat_args) + flat_results = lower_flat_values(cx, max_flat_results, result, ft.result_type(), flat_args, is_result = True) subtask.resolve(Subtask.State.RETURNED, flat_results) subtask.on_cancel = callee(on_start, on_resolve) @@ -3730,7 +4510,10 @@ reserved. if subtask.resolved(): subtask.deliver_resolve() assert(subtask.flat_results == []) - return [Subtask.State.RETURNED] + if opts.gc: + return [Subtask.State.RETURNED, None] + else: + return [Subtask.State.RETURNED] else: subtaski = thread.task.inst.handles.add(subtask) def on_progress(): @@ -3742,8 +4525,16 @@ reserved. maybe_on_progress = on_progress assert(0 < subtaski <= Table.MAX_LENGTH < 2**28) assert(0 <= subtask.state < 2**4) - return [subtask.state | (subtaski << 4)] + if opts.gc: + return [subtask.state | (subtaski << 4), HandleRef(thread.task.inst, subtaski)] + else: + return [subtask.state | (subtaski << 4)] ``` +With 🛸 `gc`, `async`-lowered calls additionally return the subtask as a `(ref +null extern)` (a null reference if the call already returned), and that results +are written into the caller's `(ref $results)` struct (by `lower_flat_values`) +rather than into linear memory. + When `on_start` and `on_resolve` are called after this initial `async`-lowered call returns, the `on_progress` callback (called by `on_start` and `on_resolve` above) will set a pending event on the `Subtask` (which derives `Waitable`) so @@ -3767,6 +4558,7 @@ validation specifies: * `$f` is given type `(func (param $rt.rep) (result i32))`, where `$rt.rep` is fixed to be `i32` * 🐘 - `$rt.rep` may be `i32` or `i64` + * 🛸 - `$rt.rep` may also be `(ref any)` Calling `$f` invokes the following function, which adds an owning handle containing the given resource representation to the current component @@ -3836,6 +4628,7 @@ validation specifies: * `$f` is given type `(func (param i32) (result $rt.rep))`, where `$rt.rep` is fixed to be `i32` * 🐘 - `$rt.rep` may be `i32` or `i64` + * 🛸 - `$rt.rep` may also be `(ref any)` Calling `$f` invokes the following function, which extracts the resource representation from the handle in the current component instance's `handles` @@ -3852,6 +4645,38 @@ Note that the "locally-defined" requirement above ensures that only the component instance defining a resource can access its representation. +### 🛸 `canon gc.resource.{new,drop,rep}` + +For canonical definitions: +```wat +(canon gc.resource.new $rt (core func $new)) +(canon gc.resource.drop $rt (core func $drop)) +(canon gc.resource.rep $rt (core func $rep)) +``` +validation specifies all the same rules as [`canon +resource.new`](#canon-resourcenew), [`canon resource.drop`](#canon-resourcedrop) +and [`canon resource.rep`](#canon-resourcerep) respectively, except as follows: +* `$new` is given type `(func (param $rt.rep) (result (ref extern)))` +* `$drop` is given type `(func (param (ref extern)))` +* `$rep` is given type `(func (param (ref extern)) (result $rt.rep))` + +These are the 🛸 GC versions of the `resource.*` built-ins, which operate on +boxed `(ref extern)` handles instead of `i32` handles. +```python +def canon_gc_resource_new(rt, rep_val): + [i] = canon_resource_new(rt, rep_val) + return [HandleRef(current_instance(), i)] + +def canon_gc_resource_drop(rt, r): + i = unbox_handle(current_instance(), r) + return canon_resource_drop(rt, i) + +def canon_gc_resource_rep(rt, r): + i = unbox_handle(current_instance(), r) + return canon_resource_rep(rt, i) +``` + + ### 🔀 `canon context.get` For a canonical definition: @@ -3948,8 +4773,11 @@ specifies: * `$f` is given type `flatten_functype(('lower', $opts), (func (param $t)?))` * `$t` must not transitively contain `borrow` -* `$opts` may only contain `memory` and `string-encoding` +* `$opts` may only contain `memory`, `string-encoding`, and 🛸 `gc` * [`lift($f.result)` above](#canonopt-validation) defines required options +* 🛸 with `gc`, if the flattening of `$t` overflows `MAX_FLAT_PARAMS`, `$f` + takes `gc_storage_type($t)` directly instead of a `(ref $params)` struct (as + with `gc` results of synchronously-lifted functions) Calling `$f` invokes the following function which lifts the results from core wasm state and passes them to the [current task]'s caller via `Task.return_`: @@ -3961,7 +4789,7 @@ def canon_task_return(result_type, opts: LiftOptions, flat_args): trap_if(result_type != task.ft.result) trap_if(not LiftOptions.equal(opts, task.opts)) cx = LiftLowerContext('lift', opts, task.inst, task) - result = lift_flat_values(cx, MAX_FLAT_PARAMS, CoreValueIter(flat_args), task.ft.result_type()) + result = lift_flat_values(cx, MAX_FLAT_PARAMS, CoreValueIter(flat_args), task.ft.result_type(), is_result = True) task.return_(result) return [] ``` @@ -4259,6 +5087,141 @@ def canon_subtask_drop(i): ``` +### 🛸 `canon gc.{waitable-set,waitable,subtask}.*` + +For canonical definitions: +```wat +(canon gc.waitable-set.new (core func $f)) +(canon gc.waitable-set.wait (core func $f)) +(canon gc.waitable-set.poll (core func $f)) +(canon gc.waitable-set.drop (core func $f)) +(canon gc.waitable.join (core func $f)) +(canon gc.subtask.cancel $async? (core func $f)) +(canon gc.subtask.drop (core func $f)) +``` +validation specifies all the same rules as the non-`gc` versions of these built-ins, +except as follows: +* `gc.waitable-set.new`: `$f` is given type `(func (result (ref extern)))` +* `gc.waitable-set.{wait,poll}`: `$f` is given type + `(func (param (ref extern)) (result i32 i32 (ref null extern)))` +* `gc.waitable-set.drop`: `$f` is given type `(func (param (ref extern)))` +* `gc.waitable.join`: `$f` is given type + `(func (param $w (ref extern)) (param $maybe_set (ref null extern)))` +* `gc.subtask.cancel`: `$f` is given type + `(func (param (ref extern)) (result i32))` +* `gc.subtask.drop`: `$f` is given type `(func (param (ref extern)))` + +These are the 🛸 GC versions of the `waitable-set.*`, `waitable.join` and +`subtask.*` built-ins, which operate on boxed `(ref extern)` handles instead of +`i32` handles. + +Passing a null `$maybe_set` argument to `gc.waitable.join` removes the waitable +from its waitable set (like passing `0` to `waitable.join` does). + +Rather than storing the event's waitable index and payload to memory, +`gc.waitable-set.{wait,poll}` return three results: +1. The event code +2. The payload +3. A reference to the boxed waitable (or null if the event doesn't have an + associated waitable, such as `NONE` and `TASK_CANCELLED`) +```python +def canon_gc_waitable_set_new(): + [si] = canon_waitable_set_new() + return [HandleRef(current_instance(), si)] + +def canon_gc_waitable_set_wait(r): + inst = current_instance() + si = unbox_handle(inst, r) + trap_if(not inst.may_leave) + wset = inst.handles.get(si) + trap_if(not isinstance(wset, WaitableSet)) + event = wset.wait() + return unpack_gc_event(inst, event) + +def canon_gc_waitable_set_poll(r): + inst = current_instance() + si = unbox_handle(inst, r) + trap_if(not inst.may_leave) + wset = inst.handles.get(si) + trap_if(not isinstance(wset, WaitableSet)) + event = wset.poll() + return unpack_gc_event(inst, event) + +def unpack_gc_event(inst, e: EventTuple): + event, p1, p2 = e + if p1 == 0: + w = None + else: + w = inst.handles.get_handle_ref(p1) + if w is None: + w = HandleRef(inst, p1) + return [event, p2, w] + +def canon_gc_waitable_set_drop(r): + i = unbox_handle(current_instance(), r) + return canon_waitable_set_drop(i) + +def canon_gc_waitable_join(wr, sr): + wi = unbox_handle(current_instance(), wr) + if sr is None: + si = 0 + else: + si = unbox_handle(current_instance(), sr) + return canon_waitable_join(wi, si) + +def canon_gc_subtask_cancel(async_, r): + i = unbox_handle(current_instance(), r) + return canon_subtask_cancel(async_, i) + +def canon_gc_subtask_drop(r): + i = unbox_handle(current_instance(), r) + return canon_subtask_drop(i) +``` + + +### 🛸 `canon gc.handle-ref.{index,new,get}` + +For canonical definitions: +```wat +(canon gc.handle-ref.index (core func $f)) +(canon gc.handle-ref.new (core func $f)) +(canon gc.handle-ref.get (core func $f)) +``` +validation specifies: +* `gc.handle-ref.index`: `$f` is given type `(func (param (ref extern)) (result + i32))` +* `gc.handle-ref.new`: `$f` is given type `(func (param i32) (result (ref + extern)))` +* `gc.handle-ref.get`: `$f` is given type `(func (param i32) (result (ref null + extern)))` + +These builtins convert between `i32` handles and `(ref extern)` +`HandleRef`s. `gc.handle-ref.index` returns the `i32` index of a `(ref extern)` +`HandleRef` (allowing core wasm to identify, e.g., which waitable an event from +`gc.waitable-set.{wait,poll}` is for). `gc.handle-ref.new` creates the +`HandleRef` for a live `i32` handle, returning it as a `(ref extern)`, or raises +a trap if it already has one. `gc.handle-ref.get` returns the existing +`HandleRef` for an `i32` handle as a `(ref null extern)`, or the null reference +if there is none. +```python +def canon_gc_handle_ref_index(r): + inst = current_instance() + trap_if(not inst.may_leave) + i = unbox_handle(inst, r) + return [i] + +def canon_gc_handle_ref_new(i): + inst = current_instance() + trap_if(not inst.may_leave) + return [HandleRef(inst, i)] + +def canon_gc_handle_ref_get(i): + inst = current_instance() + trap_if(not inst.may_leave) + return [inst.handles.get_handle_ref(i)] +``` + + ### 🔀 `canon {stream,future}.new` For canonical definitions: @@ -4316,25 +5279,68 @@ specifies: * If `$t` is present: * [`lower($t)` above](#canonopt-validation) defines required options for `write` * [`lift($t)` above](#canonopt-validation) defines required options for `read` - * `memory` is required to be present + * `memory` is required to be present (unless 🛸 `gc` is present) * 🚝 - `async` is allowed to be omitted, otherwise it must be present +* 🛸 with `gc`, `$future_copy` is given type `(func (param (ref extern) (ref + $results)) (result i32))` for `future.read`, where `$results` is + `gc_async_results_type($t)`, and `(func (param (ref extern) U) (result i32))` + for `future.write`, where `U` is `unpacked_type(gc_storage_type($t))` (and the + `(ref $results)` and `U` parameters are omitted if `$t` is absent) +* 🛸 with `gc`, `$stream_copy` is given type `(func (param (ref extern) (ref $a) + i32 i32) (result i32))`, where `$a` is `(sub final (array (mut + nullable_type(gc_storage_type($t)))))` for `stream.read` and `(sub final + (array gc_storage_type($t)))` for `stream.write` (each in its own `rec` + group), or `(func (param (ref extern) i32) (result i32))` if `$t` is absent The implementations of these 4 built-ins all funnel down to a single parameterized `copy` function: ```python -def canon_stream_read(stream_t, opts, i, ptr, length): - return copy(ReadableStreamEnd, WritableGuestBuffer, 'lower', stream_t, opts, i, ptr, length) - -def canon_stream_write(stream_t, opts, i, ptr, length): - return copy(WritableStreamEnd, ReadableGuestBuffer, 'lift', stream_t, opts, i, ptr, length) +def canon_stream_read(stream_t, opts, i, *args): + if opts.gc: + ii = unbox_handle(current_instance(), i) + gc_args = gc_stream_buffer_args(stream_t, args) + return copy(ReadableStreamEnd, WritableGcBuffer, 'lower', stream_t, opts, ii, *gc_args) + else: + [ptr, length] = args + return copy(ReadableStreamEnd, WritableGuestBuffer, 'lower', stream_t, opts, i, ptr, length) + +def canon_stream_write(stream_t, opts, i, *args): + if opts.gc: + ii = unbox_handle(current_instance(), i) + gc_args = gc_stream_buffer_args(stream_t, args) + return copy(WritableStreamEnd, ReadableGcBuffer, 'lift', stream_t, opts, ii, *gc_args) + else: + [ptr, length] = args + return copy(WritableStreamEnd, ReadableGuestBuffer, 'lift', stream_t, opts, i, ptr, length) -def canon_future_read(future_t, opts, i, ptr): - return copy(ReadableFutureEnd, WritableGuestBuffer, 'lower', future_t, opts, i, ptr, 1) +def gc_stream_buffer_args(stream_t, args): + if stream_t.t is None: + [length] = args + return (None, 0, length) + else: + [arr, offset, length] = args + return (arr.elems, offset, length) + +def canon_future_read(future_t, opts, i, ptr_or_cell = None): + if opts.gc: + ii = unbox_handle(current_instance(), i) + if future_t.t is None: + assert(ptr_or_cell is None) + elems = None + else: + elems = ptr_or_cell.fields + return copy(ReadableFutureEnd, WritableGcBuffer, 'lower', future_t, opts, ii, elems, 0, 1) + else: + return copy(ReadableFutureEnd, WritableGuestBuffer, 'lower', future_t, opts, i, ptr_or_cell, 1) -def canon_future_write(future_t, opts, i, ptr): - return copy(WritableFutureEnd, ReadableGuestBuffer, 'lift', future_t, opts, i, ptr, 1) +def canon_future_write(future_t, opts, i, ptr_or_v = None): + if opts.gc: + ii = unbox_handle(current_instance(), i) + return copy(WritableFutureEnd, ReadableGcValueBuffer, 'lift', future_t, opts, ii, ptr_or_v) + else: + return copy(WritableFutureEnd, ReadableGuestBuffer, 'lift', future_t, opts, i, ptr_or_v, 1) -def copy(EndT, BufferT, direction, stream_or_future_t, opts, i, ptr, length): +def copy(EndT, BufferT, direction, stream_or_future_t, opts, i, *buffer_args): thread = current_thread() trap_if(not thread.task.inst.may_leave) end = thread.task.inst.handles.get(i) @@ -4343,7 +5349,7 @@ def copy(EndT, BufferT, direction, stream_or_future_t, opts, i, ptr, length): trap_if(end.state != End.State.IDLE) trap_if(end.in_waitable_set() and not opts.async_) cx = LiftLowerContext(direction, opts, thread.task.inst, borrow_scope = None) - buffer = BufferT(end.t, cx, ptr, length) + buffer = BufferT(end.t, cx, *buffer_args) end.copy(buffer) if not end.has_pending_event(): if not opts.async_: @@ -4360,7 +5366,8 @@ from a stream or future end that is already being asynchronously waited on via waitable set, as this might result in the waitable set "stealing" an event from the synchronous operation, leaving it hung. After these, a readable or writable buffer is created which (in `GuestBuffer`'s constructor) also eagerly guards the -alignment and bounds of (`ptr`, `length`). The `Buffer` object captures the +alignment and bounds of (`ptr`, `length`) (or, with 🛸 `gc`, a `GcBuffer` +holding a single value). The `Buffer` object captures the `$opts` immediate passed to `{stream,future}.{read,write}` so that subsequent lifting and lowering of elements is well-defined to use these same `$opts`. @@ -4392,6 +5399,16 @@ immediately returns the sentinel `BLOCKED` code (`-1`) and the caller must add `end` to a waitable set and call `waitable-set.{wait,poll}` or return to a `callback` event loop to be notified of progress. +With the 🛸 `gc` option, `stream.{read,write}` take a GC `array`, offset index, +and element length (or just a length if `T` is absent) instead of a pointer and +length. For `stream.read`, the `array` elements must be `mut` and +reference-typed elements must be nullable references. For `stream.write`, the +`array` elements must be non-`mut` and reference-typed elements must be +non-nullable. They both return the same bitpacked `i32` payload +result. `future.read` takes a `(ref $results)` cell (like `async`-lowered calls) +whose field is overwritten with the `future`'s value when it is read. The field +is never overwritten on cancel or drop. + ### 🔀 `canon {stream,future}.cancel-{read,write}` @@ -4552,6 +5569,96 @@ def forward(ReadableEndT, WritableEndT, stream_or_future_t, ri, wi): ``` +### 🛸 `canon gc.{stream,future}.*` + +For canonical definitions: +```wat +(canon gc.stream.new $stream_t (core func $f)) +(canon gc.stream.cancel-read $stream_t $async? (core func $f)) +(canon gc.stream.cancel-write $stream_t $async? (core func $f)) +(canon gc.stream.drop-readable $stream_t (core func $f)) +(canon gc.stream.drop-writable $stream_t (core func $f)) +(canon gc.stream.forward $stream_t (core func $f)) +(canon gc.future.new $future_t (core func $f)) +(canon gc.future.cancel-read $future_t $async? (core func $f)) +(canon gc.future.cancel-write $future_t $async? (core func $f)) +(canon gc.future.drop-readable $future_t (core func $f)) +(canon gc.future.drop-writable $future_t (core func $f)) +(canon gc.future.forward $future_t (core func $f)) +``` +validation specifies all the same rules as the non-`gc`-prefixed versions of +these built-ins, except as follows: +* `gc.{stream,future}.cancel-{read,write}`: `$f` is given type + `(func (param (ref extern)) (result i32))` +* `gc.{stream,future}.drop-{readable,writable}`: `$f` is given type + `(func (param (ref extern)))` +* `gc.{stream,future}.forward`: `$f` is given type + `(func (param $ri (ref extern)) (param $wi (ref extern)))` +* `gc.{stream,future}.new`: `$f` is given type + `(func (result (ref extern) (ref extern)))` (the readable end, then the + writable end) + +These are the 🛸 GC versions of the `stream.*` and `future.*` built-ins, which +operate on boxed `(ref extern)` ends instead of `i32` ends. `new` returns the +readable end followed by the writable end. +```python +def canon_gc_stream_new(stream_t): + [packed] = canon_stream_new(stream_t) + return box_new_ends(current_instance(), packed) + +def canon_gc_future_new(future_t): + [packed] = canon_future_new(future_t) + return box_new_ends(current_instance(), packed) + +def box_new_ends(inst, packed): + readable_index = packed & 0xffff_ffff + writable_index = packed >> 32 + return [HandleRef(inst, readable_index), HandleRef(inst, writable_index)] + +def canon_gc_stream_cancel_read(stream_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_stream_cancel_read(stream_t, async_, i) + +def canon_gc_stream_cancel_write(stream_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_stream_cancel_write(stream_t, async_, i) + +def canon_gc_future_cancel_read(future_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_future_cancel_read(future_t, async_, i) + +def canon_gc_future_cancel_write(future_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_future_cancel_write(future_t, async_, i) + +def canon_gc_stream_drop_readable(stream_t, r): + i = unbox_handle(current_instance(), r) + return canon_stream_drop_readable(stream_t, i) + +def canon_gc_stream_drop_writable(stream_t, r): + i = unbox_handle(current_instance(), r) + return canon_stream_drop_writable(stream_t, i) + +def canon_gc_future_drop_readable(future_t, r): + i = unbox_handle(current_instance(), r) + return canon_future_drop_readable(future_t, i) + +def canon_gc_future_drop_writable(future_t, r): + i = unbox_handle(current_instance(), r) + return canon_future_drop_writable(future_t, i) + +def canon_gc_stream_forward(stream_t, rr, wr): + ri = unbox_handle(current_instance(), rr) + wi = unbox_handle(current_instance(), wr) + return canon_stream_forward(stream_t, ri, wi) + +def canon_gc_future_forward(future_t, rr, wr): + ri = unbox_handle(current_instance(), rr) + wi = unbox_handle(current_instance(), wr) + return canon_future_forward(future_t, ri, wi) +``` + + ### 🧵 `canon thread.index` For a canonical definition: @@ -4800,8 +5907,11 @@ validation specifies: * `$f` is given type `(func (param $ptr T) (param $units T) (result i32))` where `T` is `i32` * 🐘 - `T` is `i32` or `i64` as determined by the `memory` field of `$opts` + * 🛸 with `gc`, `$f` is instead given type + `(func (param S) (result (ref extern)))` where `S` is the `gc` lowering of + `string` for the `string-encoding` in `$opts` (see `gc_string_type`) * `async` is not present -* `memory` must be present +* `memory` must be present (unless 🛸 `gc` is present) Calling `$f` calls the following function which uses the `$opts` immediate to (nondeterministically) lift the debug message, create a new `ErrorContext` @@ -4812,17 +5922,24 @@ its index. class ErrorContext: debug_message: String -def canon_error_context_new(opts, ptr, tagged_code_units): +def canon_error_context_new(opts, ptr_or_arr, tagged_code_units = None): inst = current_instance() trap_if(not inst.may_leave) if DETERMINISTIC_PROFILE or random.randint(0,1): - s = String(('', 'utf8', 0)) + s = String(('', StringHint.UTF8, 0)) else: cx = LiftLowerContext('lift', opts, inst) - s = load_string_from_range(cx, ptr, tagged_code_units) + if opts.gc: + assert(tagged_code_units is None) + s = lift_gc_string(cx, ptr_or_arr) + else: + s = load_string_from_range(cx, ptr_or_arr, tagged_code_units) s = host_defined_transformation(s) i = inst.handles.add(ErrorContext(s)) - return [i] + if opts.gc: + return [HandleRef(inst, i)] + else: + return [i] ``` Supporting the requirement (introduced in the [explainer](Text.md#-error-context-type)) that wasm code does not depend on @@ -4833,6 +5950,11 @@ discarded, it is not even lifted and thus the O(N) well-formedness conditions are not checked. (Note that `host_defined_transformation` is not defined by the Canonical ABI and stands for an arbitrary host-defined function.) +With 🛸 `gc`, the debug message is passed as a GC string `array` (per +`string-encoding`, as for any `gc`-lifted `string`), which is likewise only +lifted (and checked) when it isn't discarded, and the new error context is +returned as a `(ref extern)` instead of an `i32`. + ### 📝 `canon error-context.debug-message` @@ -4844,9 +5966,12 @@ validation specifies: * `$f` is given type `(func (param i32) (param $ptr T))` where `T` is `i32` * 🐘 - `T` is `i32` or `i64` as determined by the address type of `memory` from `$opts` + * 🛸 with `gc`, `$f` is instead given type `(func (param (ref extern)) (result + S))` where `S` is the `gc` lowering of `string` for the `string-encoding` in + `$opts` (see `gc_string_type`) * `async` is not present -* `memory` must be present -* `realloc` must be present +* `memory` must be present (unless 🛸 `gc` is present) +* `realloc` must be present (unless 🛸 `gc` is present) Calling `$f` calls the following function which uses the `$opts` immediate to lowers the `ErrorContext`'s debug message. While *producing* an `error-context` @@ -4854,16 +5979,22 @@ value may nondeterministically discard or transform the debug message, a single `error-context` value must return the same debug message from `error-context.debug-message` over time. ```python -def canon_error_context_debug_message(opts, i, ptr): +def canon_error_context_debug_message(opts, i, ptr = None): inst = current_instance() trap_if(not inst.may_leave) + if opts.gc: + i = unbox_handle(inst, i) errctx = inst.handles.get(i) trap_if(not isinstance(errctx, ErrorContext)) cx = LiftLowerContext('lower', opts, inst) - trap_if(ptr != align_to(ptr, alignment(cx, StringType()))) - trap_if(ptr + elem_size(cx, StringType()) > len(cx.opts.memory)) - store(cx, errctx.debug_message, StringType(), ptr) - return [] + if opts.gc: + assert(ptr is None) + return [lower_gc_string(cx, errctx.debug_message)] + else: + trap_if(ptr != align_to(ptr, alignment(cx, StringType()))) + trap_if(ptr + elem_size(cx, StringType()) > len(cx.opts.memory)) + store(cx, errctx.debug_message, StringType(), ptr) + return [] ``` Note that `ptr` points to a region of memory (8 bytes for memory32, 16 bytes for memory64) into which will be stored the pointer and length of the debug @@ -4872,6 +6003,10 @@ memory, `ptr` must be aligned to the pointer size (4 bytes for memory32, 8 bytes for memory64) and the whole region must be in bounds, which is checked (trapping otherwise) before `opts.realloc` is called. +With 🛸 `gc`, the debug message is returned as a new GC string `array` (per +`string-encoding`, as for any `gc`-lowered `string`) instead of being stored +through `ptr`. + ### 📝 `canon error-context.drop` @@ -4894,6 +6029,84 @@ def canon_error_context_drop(i): ``` +### 🛸 `canon gc.error-context.drop` + +For a canonical definition: +```wat +(canon gc.error-context.drop (core func $f)) +``` +validation specifies: +* `$f` is given type `(func (param (ref extern)))` + +This is the 🛸 GC version of `error-context.drop`, which operates on a boxed +`(ref extern)` error context instead of an `i32` index. +```python +def canon_gc_error_context_drop(r): + i = unbox_handle(current_instance(), r) + return canon_error_context_drop(i) +``` + + +### 🛸 `canon array.new-{array,memory,table}` + +For canonical definitions: +```wat +(canon array.new-array $dst $src (core func $f)) +(canon array.new-memory $dst $mem (core func $f)) +(canon array.new-table $dst $tbl (core func $f)) +``` +validation specifies: +* `array.new-array`: `$f` is given type `(func (param $src-arr (ref null $src)) + (param $offset i32) (param $len i32) (result (ref $dst)))` +* `array.new-memory`: `$f` is given type + `(func (param $offset $mem.addrtype) (param $len i32) (result (ref $dst)))` +* `array.new-table`: `$f` is given type + `(func (param $ofset $tbl.addrtype) (param $len i32) (result (ref $dst)))` +* `$dst` must be an `array` type +* The elements of `$src` must [match] the elements of `$dst` +* The elements of `$tbl` must [match] the elements of `$dst` +* For `array.new-memory`, the elements of `$dst` must have a defined byte size + +`array.new-array` defines a function that creates a new `array` from +`$src_param[$offset..($offset + $len)]`. + +`array.new-table` defines a function that creates a new `array` from +`$tbl[$offset..($offset + $len)]`. + +`array.new-memory` defines a function that creates a new `array` from +`$mem[byte_size($dst.elem) * $offset..(byte_size($dst.elem) * ($offset + +$len))]`. + +> Non-normative note: these are polyfills for the `array.new_array`, +> `array.new_memory` and `array.new_table` instructions of the +> [more-array-constructors] proposal, which are needed to create immutable +> arrays of dynamic length and contents (e.g. for lifting and lowering 🛸 `gc` +> strings and lists). +```python +def canon_array_new_array(dst: CoreDefType, src: CoreDefType, a, i, n): + trap_if(a is None) + trap_if(i + n > array_len(a)) + return [array_new_fixed(dst, [array_get(a, j) for j in range(i, i + n)])] + +def canon_array_new_memory(dst: CoreDefType, mem: MemInst, ptr, n): + t = dst.comptype().elem.t + nbytes = storage_byte_size(t) + trap_if(ptr + n * nbytes > len(mem)) + vs = [] + for j in range(n): + bits = int.from_bytes(mem[ptr + j*nbytes : ptr + (j+1)*nbytes], 'little') + match t: + case 'f32' : vs.append(core_f32_reinterpret_i32(bits)) + case 'f64' : vs.append(core_f64_reinterpret_i64(bits)) + case 'i8' | 'i16' | 'i32' | 'i64' : vs.append(bits) + return [array_new_fixed(dst, vs)] + +def canon_array_new_table(dst: CoreDefType, tbl: list[any], i, n): + trap_if(i + n > len(tbl)) + return [array_new_fixed(dst, tbl[i : i+n])] +``` + + ### 🧵② `canon thread.spawn-ref` For a canonical definition: @@ -5026,6 +6239,9 @@ def canon_thread_available_parallelism(): [Stream Readiness]: Concurrency.md#stream-readiness [Lazy Lowering]: https://github.com/WebAssembly/component-model/issues/383 +[more-array-constructors]: https://github.com/WebAssembly/more-array-constructors/blob/main/proposals/more-array-constructors/Overview.md +[Match]: https://webassembly.github.io/spec/core/valid/matching.html +[Matching]: https://webassembly.github.io/spec/core/valid/matching.html [GC ABI Option]: https://github.com/WebAssembly/component-model/issues/525 [Core WebAssembly Embedding]: https://webassembly.github.io/spec/core/appendix/embedding.html diff --git a/design/mvp/Concurrency.md b/design/mvp/Concurrency.md index 2d4542826..6d4b3f76b 100644 --- a/design/mvp/Concurrency.md +++ b/design/mvp/Concurrency.md @@ -102,7 +102,7 @@ Thus, overall, `async` in WIT and the Component Model does not behave like a essay. The following table summarizes how the behavior of a callee changes, depending -on whether `async` is set as a lifting or lowering ABI option and whether the +on whether `async` is set as a lifting or lowering ABI option and whether the component function type is `async`: | Component function type | Lift canonical option | Valid? | Effect of callee blocking | Holds instances's exclusive lock? | Can call while instance lock held? | @@ -1170,6 +1170,62 @@ and the runtime will repeatedly call the callback until a value of `0` is returned. The `i32` parameters describe what happened that caused the callback to be called again. +##### 🚟 🛸 Stackful Async Exports and `gc` + +When the 🚟 stackful ABI and 🛸 `gc` option are both provided, the `foo` +function from the `w` world has the following signatures: + +```wat +(rec (type $utf8 (sub final (array i8)))) + +;; async, no callback, gc +(func (param $s (ref $utf8))) + +;; task.return, gc +(func (param $ret (ref $utf8))) +``` + +Parameters work just like synchronous parameters. + +Results are passed the same way as they are for non-`gc` stackful async exports, +except that they use the `gc`-lowering of the flattened result types, except +that if they overflow `MAX_FLAG_PARAMS`, then the result's GC heap storage type +is passed directly (rather than a `(ref $params)` struct). + +##### 🛸 Stackless Async Exports and `gc` + +The async stackless export function signature for `foo` from world `w` is: +```wat +(rec (type $utf8 (sub final (array i8)))) + +;; async, callback, gc +(func (param $s (ref $utf8)) (result i32 (ref null extern))) +``` + +The parameters work just like synchronous parameters. + +The callee returns their value by calling `task.return` just like the stackful +case. + +The resulting `i32` tells the runtime what to do next, the same as for non-`gc` +stackless exports, however the waitable set (if any) is not an index bitpacked +into the `i32`, it is the second `(ref null extern)` result, and must be +non-null when waiting. + +The associated callback must have the following signature: +```wat +(func (param $event-code i32) + (param $payload i32) + (param $waitable (ref null extern)) + (result i32 (ref null extern))) +``` + +The `(result i32 (ref null extern))` has the same interpretation as the +stackless `gc` export function, and the runtime will repeatedly call the +callback until the first result is `0`. The `$event-code`, `$payload`, and +`waitable` parameters describe what happened that caused the callback to be +called again. + For a complete description of how async exports work, see [`canon_lift`] in the Canonical ABI Explainer. diff --git a/design/mvp/Explainer.md b/design/mvp/Explainer.md index 14d6029eb..d0fbe2183 100644 --- a/design/mvp/Explainer.md +++ b/design/mvp/Explainer.md @@ -119,11 +119,11 @@ example. Given the ABI options supplied to `canon`, the Component Model specifies how the given component-level type (`(func (result string))`) is **lowered** into a core-level type (`(func (result i32))`). The Component Model's validation rules -for `canon lift` require that this lowered type matches the given core -function (`$main-greeting`). With memory64 ([🐘]), when the `memory` ABI option -refers to a 64-bit memory, the pointers and lengths mentioned above are replaced -with `i64`. In the future, a new ABI option will likely be added for [wasm-gc] -to replace these integer offsets with typed GC references. +for `canon lift` require that this lowered type matches the given core function +(`$main-greeting`). With memory64 ([🐘]), when the `memory` ABI option refers to +a 64-bit memory, the pointers and lengths mentioned above are replaced with +`i64`. With the 🛸 `gc` option supplied, values are not lifted and lowered +through linear memory at all, but through GC heap objects instead. The Component Model text format also provides **inline aliases** as syntactic sugar that implicitly emits export aliases as needed. Using inline aliases, the @@ -762,11 +762,11 @@ Walking through the definitions in order, starting after `$alloc`: The `(type $file (resource ...))` defines a new resource type with an `i64` representation type that, when destroyed, calls the `free` function exported by -`$alloc` to free the memory allocation. Currently, `i32` and `i64` [🐘] are the -only allowed representation types but, in the future, as part of [wasm-gc] -support, reference types could be added. In any case, the general idea is that a -resource's representation value is pointer-like and pointer-sized. This example -uses a 64-bit `memory` and thus specifies an `i64` resource representation. +`$alloc` to free the memory allocation. Currently, `i32`, `i64` [🐘], and `(ref +any)` [🛸] are the only allowed representation types. In any case, the general idea +is that a resource's representation value is pointer-like and +pointer-sized. This example uses a 64-bit `memory` and thus specifies an `i64` +resource representation. Next, the `(core func $file-new (canon resource.new $file))` definition appends a new `core func` index for the `resource.new` ABI built-in. As this definition @@ -1601,6 +1601,7 @@ the basis of a portable inside-and-outside-the-browser WebAssembly ecosystem. [External Visibility]: Text.md#external-visibility-of-types [🪺]: Text.md#gated-features [🐘]: Text.md#gated-features +[🛸]: Text.md#gated-features [🔧]: Text.md#gated-features [📡]: Text.md#gated-features [Binary Format reference]: Binary.md diff --git a/design/mvp/Text.md b/design/mvp/Text.md index fdfa18be6..d6f5eb418 100644 --- a/design/mvp/Text.md +++ b/design/mvp/Text.md @@ -35,6 +35,7 @@ shipped as part of a future WASI Developer Preview release: * 🐘: [memory64] * 📡: getters and setters * ➡️: `stream.forward` and `future.forward` built-ins +* 🛸: [GC] mode for the Canonical ABI ## Grammar @@ -594,6 +595,7 @@ valtype ::= keytype ::= bool | s8 | u8 | s16 | u16 | s32 | u32 | s64 | u64 | char | string 🗺️ resourcetype ::= (resource (rep i32) (dtor core-prefix())?) | (resource (rep i64) (dtor core-prefix())?) 🐘 + | (resource (rep (ref any)) (dtor core-prefix())?) 🛸 functype ::= (func async? (param )* (result )?) componenttype ::= (component *) instancetype ::= (instance *) @@ -619,7 +621,7 @@ valuebound ::= (eq ) 🪙 where bind-id(X) parses '(' sort ? Y ')' when X parses '(' sort Y ')' ``` -Because there is nothing in this type grammar analogous to the [gc] proposal's +Because there is nothing in this type grammar analogous to the [GC] proposal's [`rectype`], none of these types are recursive. To prevent integer overflow in obscure corner cases, as an extra validation @@ -717,12 +719,11 @@ handles are analogous to file descriptors, which are stored in a table and may only be used indirectly by untrusted user-mode processes via their integer index in the table. -In the Component Model, handles are lifted-from and lowered-into `i32` values -that index an encapsulated per-component-instance table that is maintained by -the canonical function definitions described [below](#canonical-definitions). -In the future, handles could be backwards-compatibly lifted and lowered from -[reference types] (via the addition of a new `canonopt`, as introduced -[below](#canonical-abi)). +In the Component Model, by default handles are lifted-from and lowered-into +`i32` values that index an encapsulated per-component-instance table that is +maintained by the canonical function definitions described +[below](#canonical-definitions). Alternatively, when the the 🛸 `gc` `canonopt` +is provided, handles are lifted from and lowered into `(ref extern)` values. The uniqueness and dropping conditions mentioned above are enforced at runtime by the Component Model through these canonical definitions. The `typeidx` @@ -847,14 +848,14 @@ The `resource` type constructor creates a fresh type for each instance of the containing component (with "freshness" and its interaction with general type-checking described in more detail [below](#type-checking)). Resource types can be referred to by handle types (such as `own` and `borrow`) as well as the -canonical built-ins described [below](#canonical-built-ins). The `rep` -immediate of a `resource` type specifies its *core representation type*, which -is currently fixed to `i32` or `i64`, but will potentially be relaxed to include -other types. When the last handle to a resource is dropped, the resource's -destructor function specified by the `dtor` immediate will be called (if -present), allowing the implementing component to perform clean-up like freeing -linear memory allocations. A destructor for a `resource (rep $T)` must have type -`($T) -> ()`. +canonical built-ins described [below](#canonical-built-ins). The `rep` immediate +of a `resource` type specifies its *core representation type*, which is +currently fixed to `i32`, `i64` or (🛸) `(ref any)`, but will potentially be +relaxed to include other types. When the last handle to a resource is dropped, +the resource's destructor function specified by the `dtor` immediate will be +called (if present), allowing the implementing component to perform clean-up +like freeing linear memory allocations. A destructor for a `resource (rep $T)` +must have type `($T) -> ()`. The `instance` type constructor describes a list of named, typed definitions that can be imported or exported by a component. Informally, instance types @@ -1368,6 +1369,7 @@ canonopt ::= string-encoding=utf8 | (post-return core-prefix()) | async 🔀 | (callback core-prefix()) 🔀 + | gc 🛸 ``` While the production `externtype` accepts any `sort`, the validation rules for `canon lift` would only allow the `func` sort. In the future, other sorts @@ -1423,8 +1425,25 @@ validated to have the following core function type: (param $payload i32) (result $done i32)) ``` +With 🛸 `gc`, the `callback` instead has type +```wat +(func (param $event i32) + (param $payload i32) + (param $waitable (ref null extern)) + (result $done i32) + (result $waitable-set (ref null extern))) +``` +and it receives the event code, payload, and waitable (if any); it returns the +callback code and the waitable set (if waiting). + Again, see the [concurrency explainer] for more details. +🛸 The `gc` option may be used to opt into a [GC]-based ABI that uses references +to managed objects, rather than a linear memory-based ABI that uses pointers. It +cannot be combined with the `memory` option (and therefore, not with `realloc` +either). `list`s become `array`s, `record`s with too many flat values and +`variant`s with payloads become `struct`s, and handles become `(ref extern)`s. + Based on this description of the AST, the [Canonical ABI explainer] gives a detailed walkthrough of the static and dynamic semantics of `lift` and `lower`. @@ -1562,6 +1581,35 @@ canon ::= ... | (canon thread.spawn-ref shared? core-prefix() (core func ?)) 🧵② | (canon thread.spawn-indirect shared? core-prefix() core-prefix() (core func ?)) 🧵② | (canon thread.available-parallelism shared? (core func ?)) 🧵② + | (canon gc.resource.new (core func ?)) 🛸 + | (canon gc.resource.drop (core func ?)) 🛸 + | (canon gc.resource.rep (core func ?)) 🛸 + | (canon gc.waitable-set.new (core func ?)) 🛸 + | (canon gc.waitable-set.wait (core func ?)) 🛸 + | (canon gc.waitable-set.poll (core func ?)) 🛸 + | (canon gc.waitable-set.drop (core func ?)) 🛸 + | (canon gc.waitable.join (core func ?)) 🛸 + | (canon gc.subtask.cancel async? (core func ?)) 🛸 + | (canon gc.subtask.drop (core func ?)) 🛸 + | (canon gc.handle-ref.index (core func ?)) 🛸 + | (canon gc.handle-ref.new (core func ?)) 🛸 + | (canon gc.handle-ref.get (core func ?)) 🛸 + | (canon gc.stream.new (core func ?)) 🛸 + | (canon gc.stream.cancel-read async? (core func ?)) 🛸 + | (canon gc.stream.cancel-write async? (core func ?)) 🛸 + | (canon gc.stream.drop-readable (core func ?)) 🛸 + | (canon gc.stream.drop-writable (core func ?)) 🛸 + | (canon gc.stream.forward (core func ?)) 🛸 + | (canon gc.future.new (core func ?)) 🛸 + | (canon gc.future.cancel-read async? (core func ?)) 🛸 + | (canon gc.future.cancel-write async? (core func ?)) 🛸 + | (canon gc.future.drop-readable (core func ?)) 🛸 + | (canon gc.future.drop-writable (core func ?)) 🛸 + | (canon gc.future.forward (core func ?)) 🛸 + | (canon gc.error-context.drop (core func ?)) 🛸 + | (canon array.new-array core-prefix() core-prefix() (core func ?)) 🛸 + | (canon array.new-memory core-prefix() core-prefix() (core func ?)) 🛸 + | (canon array.new-table core-prefix() core-prefix() (core func ?)) 🛸 ``` ##### Resource built-ins @@ -1581,7 +1629,7 @@ component that defined `T`. In the Canonical ABI, `T.rep` is defined to be the `$rep` in the `(type $T (resource (rep $rep) ...))` type definition that defined `T`. While it's designed to allow different types in the future, it is currently -limited to `i32` or `i64`. +limited to `i32`, `i64` or (🛸) `(ref any)`. For details, see [`canon_resource_new`] in the Canonical ABI explainer. @@ -1611,7 +1659,7 @@ resource type `T`) pointed to by the handle `t`. Validation only allows In the Canonical ABI, `T.rep` is defined to be the `$rep` in the `(type $T (resource (rep $rep) ...))` type definition that defined `T`. While it's designed to allow different types in the future, it is currently -limited to `i32` or `i64`. +limited to `i32`, `i64` or (🛸) `(ref any)`. As an example, the following component imports the `resource.new` built-in, allowing it to create and return new resources to its client: @@ -1644,6 +1692,19 @@ transferring ownership of the newly-created resource to the export's caller. For details, see [`canon_resource_rep`] in the Canonical ABI explainer. +###### 🛸 `gc.resource.new`, `gc.resource.drop` and `gc.resource.rep` + +| Synopsis | | +| --------------------------------------------------- | -------------------------------- | +| Canonical ABI signature for `gc.resource.new` | `[rep: T.rep] -> [(ref extern)]` | +| Canonical ABI signature for `gc.resource.drop` | `[t:(ref extern)] -> []` | +| Canonical ABI signature for `gc.resource.rep` | `[t:(ref extern)] -> [T.rep]` | + +These are the same as `resource.{new,drop,rep}`, except that they operate on +`(ref extern)` handles instead of `i32` handles. + +For details, see [`canon_gc_resource_new`] in the Canonical ABI explainer. + ##### 🔀🧵 Concurrency built-ins See the [concurrency explainer] for background. @@ -1717,8 +1778,12 @@ from any of a task's threads; if neither is called, the task never resolves. The `canon task.return` definition takes component-level return type and the list of `canonopt` to be used to lift the return value. When called, the -declared return type and the `string-encoding` and `memory` `canonopt`s are -checked to exactly match those of the current task. +declared return type and the `string-encoding`, `memory` and 🛸 `gc` +`canonopt`s are checked to exactly match those of the current task. + +With 🛸 `gc`, the results are passed with the `gc` lowering. If they overflow +`MAX_FLAT_PARAMS`, the result's GC heap storage type is passed directly (rather +than a `(ref $params)` struct). For details, see [Returning] in the concurrency explainer and [`canon_task_return`] in the Canonical ABI explainer. @@ -1901,6 +1966,53 @@ resolution (via `waitable-set.{wait,poll}` or `callback` event). For details, see [`canon_subtask_drop`] in the Canonical ABI explainer. +###### 🛸 `gc.waitable-set.*`, `gc.waitable.join` and `gc.subtask.*` + +| Synopsis | | +| -------------------------------------------------- | ---------------------------------------------------------------------- | +| Canonical ABI signature for `gc.waitable-set.new` | `[] -> [(ref extern)]` | +| Canonical ABI signature for `gc.waitable-set.wait` | `[s:(ref extern)] -> [event-code:i32 payload:i32 w:(ref null extern)]` | +| Canonical ABI signature for `gc.waitable-set.poll` | `[s:(ref extern)] -> [event-code:i32 payload:i32 w:(ref null extern)]` | +| Canonical ABI signature for `gc.waitable-set.drop` | `[s:(ref extern)] -> []` | +| Canonical ABI signature for `gc.waitable.join` | `[w:(ref extern) maybe_set:(ref null extern)] -> []` | +| Canonical ABI signature for `gc.subtask.cancel` | `[subtask:(ref extern)] -> [i32]` | +| Canonical ABI signature for `gc.subtask.drop` | `[subtask:(ref extern)] -> []` | + +These are the GC versions of the `waitable-set.*`, `waitable.join`, and +`subtask.*` built-ins, which take and return `(ref extern)` handles instead of +`i32` handles. + +For `gc.waitable.join`, a null `maybe_set` removes the waitable from its set +(same as passing zero to `waitable.join` does). + +For `gc.waitable-set.{wait,poll}`, the `event-code:i32` and `payload:i32` +results are identical to the event code and payload of the non-`gc.`-prefixed +versions. They additionally return a `(ref null extern)`, which is the waitable +in the set that the event applies to, if any, otherwise the reference is +null. (The `gc.handle-ref.index` canonical definition (see below) can also be +used to identify which waitable an event is for.) + +For details, see [`canon_gc_waitable_set_new`] in the Canonical ABI explainer. + +###### 🛸 `gc.handle-ref.index`, `gc.handle-ref.new` and `gc.handle-ref.get` + +| Synopsis | | +| ------------------------------------------------- | -------------------------------- | +| Canonical ABI signature for `gc.handle-ref.index` | `[r:(ref extern)] -> [i32]` | +| Canonical ABI signature for `gc.handle-ref.new` | `[i:i32] -> [(ref extern)]` | +| Canonical ABI signature for `gc.handle-ref.get` | `[i:i32] -> [(ref null extern)]` | + +These builtins convert between `i32` handles and `(ref extern)` +`HandleRef`s. `gc.handle-ref.index` returns the `i32` index of a `(ref extern)` +`HandleRef` (allowing core wasm to identify, e.g., which waitable an event from +`gc.waitable-set.{wait,poll}` is for). `gc.handle-ref.new` creates the +`HandleRef` for a live `i32` handle, returning it as a `(ref extern)`, or raises +a trap if it already has one. `gc.handle-ref.get` returns the existing +`HandleRef` for an `i32` handle as a `(ref null extern)`, or the null reference +if there is none. + +For details, see [`canon_gc_handle_ref_index`] in the Canonical ABI explainer. + ###### 🔀 `stream.new` and `future.new` | Synopsis | | @@ -1927,11 +2039,16 @@ For details, see [Streams and Futures] in the concurrency explainer and ###### 🔀 `stream.read` and `stream.write` -| Synopsis | | -| -------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -| Approximate WIT signature for `stream.read` | `func,memory>(e: readable-stream-end, b: writable-buffer?) -> option` | -| Approximate WIT signature for `stream.write` | `func,memory>(e: writable-stream-end, b: readable-buffer?) -> option` | -| Canonical ABI signature | `[stream-end:i32 ptr:memory.addrtype num:memory.addrtype] -> [memory.addrtype]` | +| Synopsis | `gc`? | | +| -------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| Approximate WIT signature for `stream.read` | (n/a) | `func,memory>(e: readable-stream-end, b: writable-buffer?) -> option` | +| Approximate WIT signature for `stream.write` | (n/a) | `func,memory>(e: writable-stream-end, b: readable-buffer?) -> option` | +| Canonical ABI signature for `stream.read` | | `[readable-stream-end:i32 ptr:memory.addrtype num:memory.addrtype] -> [memory.addrtype]` | +| Canonical ABI signature for `stream.write` | | `[writable-stream-end:i32 ptr:memory.addrtype num:memory.addrtype] -> [memory.addrtype]` | +| Canonical ABI signature for `stream.read` | 🛸 `gc` | `[readable-stream-end:(ref extern) b:(ref (sub final (array (mut nullable_type(gc_storage_type(T)))))) offset:i32 length:i32] -> [i32]` | +| Canonical ABI signature for `stream.write` | 🛸 `gc` | `[writable-stream-end:(ref extern) b:(ref (sub final (array gc_storage_type(T)))) offset:i32 length:i32] -> [i32]` | +| Canonical ABI signature for `stream.read` | 🛸 `gc`, no `T` | `[readable-stream-end:(ref extern) length:i32] -> [i32]` | +| Canonical ABI signature for `stream.write` | 🛸 `gc`, no `T` | `[writable-stream-end:(ref extern) length:i32] -> [i32]` | where `stream-result` is defined in WIT as: ```wit @@ -1996,16 +2113,28 @@ bit-packed into a single `memory.addrtype` where: * Otherwise, the `result` is in the low 4 bits and the `progress` is in the remaining high bits. +🛸 When using `gc`, the `stream.read` function takes a mutable `array`, `i32` +offset, and `i32` length to write the just-read stream elements into, and +`stream.write` takes an immutable `array`, `i32` offset, and `i32` length to +read the to-be-written stream elements from. Instead of an `i32` handle, they +both take a `(ref extern)` handle. The `i32` result uses the same bit-packing +as above. + For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_read`] in the Canonical ABI explainer. ###### 🔀 `future.read` and `future.write` -| Synopsis | | -| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| Approximate WIT signature for `future.read` | `func,memory>(e: readable-future-end, b: writable-buffer?) -> option` | -| Approximate WIT signature for `future.write` | `func,memory>(e: writable-future-end, v: readable-buffer?) -> option` | -| Canonical ABI signature | `[readable-future-end:i32 ptr:memory.addrtype] -> [i32]` | +| Synopsis | `gc`? | | +| -------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------- | +| Approximate WIT signature for `future.read` | (n/a) | `func,memory>(e: readable-future-end, b: writable-buffer?) -> option` | +| Approximate WIT signature for `future.write` | (n/a) | `func,memory>(e: writable-future-end, v: readable-buffer?) -> option` | +| Canonical ABI signature for `future.read` | | `[readable-future-end:i32 ptr:memory.addrtype] -> [i32]` | +| Canonical ABI signature for `future.write` | | `[writable-future-end:i32 ptr:memory.addrtype] -> [i32]` | +| Canonical ABI signature for `future.read` | 🛸 `gc` | `[readable-future-end:(ref extern) results:(ref $results)] -> [i32]` | +| Canonical ABI signature for `future.write` | 🛸 `gc` | `[writable-future-end:(ref extern) v:unpacked_type(gc_storage_type(T))] -> [i32]` | +| Canonical ABI signature for `future.read` | 🛸 `gc`, no `T` | `[readable-future-end:(ref extern)] -> [i32]` | +| Canonical ABI signature for `future.write` | 🛸 `gc`, no `T` | `[writable-future-end:(ref extern)] -> [i32]` | where `future-{read,write}-result` are defined in WIT as: ```wit @@ -2064,6 +2193,15 @@ represents `none`. And, `future-read-result.cancelled` is encoded as the value of `future-write-result.cancelled`, rather than the value implied by the `enum` definition above. +🛸 When using `gc`, the `i32` handles are replaced by `(ref extern)` handles, +and, rather than passing in a pointer to a buffer for `T` to be read from or +written to, `future.read` takes a `(ref $results)` struct (`final`, no +supertype, singleton `rec` group, one field of type `(mut +nullable_type(gc_storage_type(T)))`) whose field is overwritten with the +future's resolved value, and `future.write` takes the value to resolve the +future with as an argument. The `future-{read,write}-result` bit-packing is +unchanged. + For details, see [Streams and Futures] in the concurrency explainer and [`canon_future_read`] in the Canonical ABI explainer. @@ -2134,6 +2272,23 @@ member of a waitable set, or has received its final `dropped` or, for futures, For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_forward`] in the Canonical ABI explainer. +###### 🛸 `gc.stream.*` and `gc.future.*` + +| Synopsis | | +| ------------------------------------------------------------------------- | ---------------------------------------------- | +| Canonical ABI signature for `gc.{stream,future}.new` | `[] -> [read:(ref extern) write:(ref extern)]` | +| Canonical ABI signature for `gc.{stream,future}.cancel-{read,write}` | `[e:(ref extern)] -> [i32]` | +| Canonical ABI signature for `gc.{stream,future}.drop-{readable,writable}` | `[end:(ref extern)] -> []` | +| Canonical ABI signature for `gc.{stream,future}.forward` | `[r:(ref extern) w:(ref extern)] -> []` | + +These are the same as `stream.*` and `future.*` except that they take and return +`(ref extern)` handles instead of `i32` handles. + +For details, see [`canon_gc_stream_new`] in the Canonical ABI explainer. + +> Note: `{stream,future}.{read,write}` are used for both linear-memory and GC +> ABIs, chosen by the presence of the `gc` `canonopt`. + ###### 🧵 `thread.index` | Synopsis | | @@ -2338,10 +2493,13 @@ explainer. ###### 📝 `error-context.new` -| Synopsis | | -| -------------------------------- | ---------------------------------------------------- | -| Approximate WIT signature | `func(message: string) -> error-context` | -| Canonical ABI signature | `[ptr:memory.addrtype len:memory.addrtype] -> [i32]` | +| Synopsis | `gc`? | | +| ------------------------- | --------------------------------------- | ---------------------------------------------------- | +| Approximate WIT signature | (n/a) | `func(message: string) -> error-context` | +| Canonical ABI signature | | `[ptr:memory.addrtype len:memory.addrtype] -> [i32]` | +| Canonical ABI signature | 🛸 `gc`, `string-encoding=utf8` | `[(ref (sub final (array i8)))] -> [(ref extern)]` | +| Canonical ABI signature | 🛸 `gc`, `string-encoding=utf16` | `[(ref (sub final (array i16)))] -> [(ref extern)]` | +| Canonical ABI signature | 🛸 `gc`, `string-encoding=latin1+utf16` | `[(ref array)] -> [(ref extern)]` | The `error-context.new` built-in returns a new `error-context` value. The given string is nondeterministically transformed to produce the `error-context`'s @@ -2350,14 +2508,21 @@ internal [debug message](#error-context-type). In the Canonical ABI, the returned value is an index into the current component instance's table of a new error context value. +🛸 When using `gc`, the resulting handle is returned as a `(ref extern)` rather +than an `i32`, and the debug message is passed via the `gc` lowering for +`string`s. + For details, see [`canon_error_context_new`] in the Canonical ABI explainer. ###### 📝 `error-context.debug-message` -| Synopsis | | -| -------------------------------- | ----------------------------------------------- | -| Approximate WIT signature | `func(errctx: error-context) -> string` | -| Canonical ABI signature | `[errctxi:i32 ptr:memory.addrtype] -> []` | +| Synopsis | `gc`? | | +| ------------------------- | --------------------------------------- | ---------------------------------------------------------- | +| Approximate WIT signature | (n/a) | `func(errctx: error-context) -> string` | +| Canonical ABI signature | | `[errctxi:i32 ptr:memory.addrtype] -> []` | +| Canonical ABI signature | 🛸 `gc`, `string-encoding=utf8` | `[errctx:(ref extern)] -> [(ref (sub final (array i8)))]` | +| Canonical ABI signature | 🛸 `gc`, `string-encoding=utf16` | `[errctx:(ref extern)] -> [(ref (sub final (array i16)))]` | +| Canonical ABI signature | 🛸 `gc`, `string-encoding=latin1+utf16` | `[errctx:(ref extern)] -> [(ref array)]` | The `error-context.debug-message` built-in returns the [debug message](#error-context-type) of the given `error-context`. @@ -2367,6 +2532,10 @@ In the Canonical ABI, it writes the debug message into `ptr` as an 8-byte or given the `*` immediates, trapping if `ptr` is misaligned or out of bounds. +🛸 When using `gc`, the handle is passed as a `(ref extern)` instead of an `i32` +and the message is returned via the `gc` lowering of a `string`, rather than +through an out pointer. + For details, see [`canon_error_context_debug_message`] in the Canonical ABI explainer. @@ -2385,6 +2554,35 @@ instance's table. For details, see [`canon_error_context_drop`] in the Canonical ABI explainer. +###### 🛸 `gc.error-context.drop` + +| Synopsis | | +| -------------------------------- | ----------------------------- | +| Approximate WIT signature | `func(errctx: error-context)` | +| Canonical ABI signature | `[errctx:(ref extern)] -> []` | + +This is the same as `error-context.drop`, but takes a `(ref extern)` handle +instead of an `i32` handle. + +For details, see [`canon_gc_error_context_drop`] in the Canonical ABI explainer. + +##### 🛸 Array built-ins + +###### 🛸 `array.new-array`, `array.new-memory` and `array.new-table` + +| Synopsis | | +| ---------------------------------------------- | --------------------------------------------- | +| Canonical ABI signature for `array.new-array` | `[(ref null src) i32 i32] -> [(ref dst)]` | +| Canonical ABI signature for `array.new-memory` | `[mem.addrtype i32] -> [(ref dst)]` | +| Canonical ABI signature for `array.new-table` | `[tbl.addrtype i32] -> [(ref dst)]` | + +These are the same as the `array.new_{array,memory,table}` instructions from the +[more-array-constructors] proposal. + +> Note: these are needed to create immutable arrays of dynamic length and +> contents. + +For details, see [`canon_array_new_array`] in the Canonical ABI explainer. ### 🪙 Value Definitions @@ -3170,7 +3368,8 @@ For some use-case-focused, worked examples, see: [exception-handling]: https://github.com/WebAssembly/exception-handling/blob/main/proposals/exception-handling/Exceptions.md [stack-switching]: https://github.com/WebAssembly/stack-switching/blob/main/proposals/stack-switching/Explainer.md [ESM-integration]: https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration -[gc]: https://github.com/WebAssembly/gc/blob/main/proposals/gc/MVP.md +[GC]: https://github.com/WebAssembly/gc/blob/main/proposals/gc/MVP.md +[more-array-constructors]: https://github.com/WebAssembly/more-array-constructors/blob/main/proposals/more-array-constructors/Overview.md [memory64]: https://github.com/webAssembly/memory64 [`rectype`]: https://webassembly.github.io/gc/core/text/types.html#text-rectype [shared-everything-threads]: https://github.com/WebAssembly/shared-everything-threads @@ -3199,14 +3398,20 @@ For some use-case-focused, worked examples, see: [`canon_stream_cancel_read`]: CanonicalABI.md#-canon-streamfuturecancel-readwrite [`canon_stream_drop_readable`]: CanonicalABI.md#-canon-streamfuturedrop-readablewritable [`canon_stream_forward`]: CanonicalABI.md#-canon-streamfutureforward +[`canon_gc_stream_new`]: CanonicalABI.md#-canon-gcstreamfuture [`canon_subtask_cancel`]: CanonicalABI.md#-canon-subtaskcancel [`canon_subtask_drop`]: CanonicalABI.md#-canon-subtaskdrop [`canon_resource_new`]: CanonicalABI.md#canon-resourcenew [`canon_resource_drop`]: CanonicalABI.md#canon-resourcedrop [`canon_resource_rep`]: CanonicalABI.md#canon-resourcerep +[`canon_gc_resource_new`]: CanonicalABI.md#-canon-gcresourcenewdroprep +[`canon_gc_waitable_set_new`]: CanonicalABI.md#-canon-gcwaitable-setwaitablesubtask +[`canon_gc_handle_ref_index`]: CanonicalABI.md#-canon-gchandle-refindexnewget [`canon_error_context_new`]: CanonicalABI.md#-canon-error-contextnew [`canon_error_context_debug_message`]: CanonicalABI.md#-canon-error-contextdebug-message [`canon_error_context_drop`]: CanonicalABI.md#-canon-error-contextdrop +[`canon_gc_error_context_drop`]: CanonicalABI.md#-canon-gcerror-contextdrop +[`canon_array_new_array`]: CanonicalABI.md#-canon-arraynew-arraymemorytable [`canon_thread_index`]: CanonicalABI.md#-canon-threadindex [`canon_thread_new_indirect`]: CanonicalABI.md#-canon-threadnew-indirect [`canon_thread_resume_later`]: CanonicalABI.md#-canon-threadresume-later diff --git a/design/mvp/canonical-abi/definitions.py b/design/mvp/canonical-abi/definitions.py index 2ebf9581e..b3d03ef11 100644 --- a/design/mvp/canonical-abi/definitions.py +++ b/design/mvp/canonical-abi/definitions.py @@ -54,6 +54,120 @@ def type_matches_value(t, v): match t: case 'i32' | 'i64': return type(v) == int case 'f32' | 'f64': return type(v) == float + case CoreRefType(): return ref_test(v, t) + assert(False) + +# Core Wasm GC types. Rec groups are compared structurally, which gives +# iso-recursive type canonicalization for free, since references to other types +# in the same rec group are rec-group-relative (`CoreRecIdx`). + +@dataclass(frozen = True) +class CoreRecIdx: + i: int + +@dataclass(frozen = True) +class CoreRefType: + heap_type: str | CoreDefType # 'extern', 'any', 'eq', 'struct', 'array' or a defined type + nullable: bool = False + +@dataclass(frozen = True) +class CoreFieldType: + t: str | CoreRefType # 'i8', 'i16', 'i32', 'i64', 'f32', 'f64' or a reference type + mutable: bool = False + +@dataclass(frozen = True) +class CoreStructType: + fields: tuple[CoreFieldType, ...] + +@dataclass(frozen = True) +class CoreArrayType: + elem: CoreFieldType + +@dataclass(frozen = True) +class CoreSubType: + final: bool + supertypes: tuple[CoreRecIdx | CoreDefType, ...] + comptype: CoreStructType | CoreArrayType + +@dataclass(frozen = True) +class CoreRecType: + subtypes: tuple[CoreSubType, ...] + +@dataclass(frozen = True) +class CoreDefType: + rec: CoreRecType + i: int + + def comptype(self): + return self.rec.subtypes[self.i].comptype + + def supertypes(self): + for st in self.rec.subtypes[self.i].supertypes: + if isinstance(st, CoreRecIdx): + yield CoreDefType(self.rec, st.i) + else: + yield st + + def matches(self, other): + return self == other or any(st.matches(other) for st in self.supertypes()) + +# Core Wasm GC objects and the subset of GC instructions used by the Canonical +# ABI. Packed (`i8` and `i16`) fields hold their zero-extended bits. + +@dataclass(eq = False) +class GcStruct: + t: CoreDefType + fields: list[any] + +@dataclass(eq = False) +class GcArray: + t: CoreDefType + elems: list[any] + +def wrap_packed(t, v): + match t: + case 'i8' : return v % (1 << 8) + case 'i16' : return v % (1 << 16) + case 'i32' | 'i64' | 'f32' | 'f64' | CoreRefType() : return v + +def struct_new(t: CoreDefType, vs): # struct.new + fields = t.comptype().fields + assert(len(fields) == len(vs)) + return GcStruct(t, [wrap_packed(f.t, v) for f,v in zip(fields, vs)]) + +def struct_get(s: GcStruct, i): # struct.get or struct.get_u + return s.fields[i] + +def struct_set(s: GcStruct, i, v): # struct.set + field = s.t.comptype().fields[i] + assert(field.mutable) + s.fields[i] = wrap_packed(field.t, v) + +def array_new_fixed(t: CoreDefType, vs): # array.new_fixed + return GcArray(t, [wrap_packed(t.comptype().elem.t, v) for v in vs]) + +def array_len(a: GcArray): # array.len + return len(a.elems) + +def array_get(a: GcArray, i): # array.get or array.get_u + return a.elems[i] + +def storage_byte_size(t): + match t: + case 'i8' : return 1 + case 'i16' : return 2 + case 'i32' | 'f32' : return 4 + case 'i64' | 'f64' : return 8 + +def ref_test(v, rt: CoreRefType): # ref.test + if v is None: + return rt.nullable + match rt.heap_type: + case 'extern' : return True + case 'any' | 'eq' : return isinstance(v, GcStruct | GcArray) + case 'struct' : return isinstance(v, GcStruct) + case 'array' : return isinstance(v, GcArray) + case CoreDefType() : return isinstance(v, GcStruct | GcArray) and v.t.matches(rt.heap_type) assert(False) @dataclass @@ -578,10 +692,12 @@ def ptr_size(self): class LiftOptions: string_encoding: str = 'utf8' memory: Optional[MemInst] = None + gc: bool = False def equal(lhs, rhs): return lhs.string_encoding == rhs.string_encoding and \ - lhs.memory is rhs.memory + lhs.memory is rhs.memory and \ + lhs.gc == rhs.gc @dataclass class LiftLowerOptions(LiftOptions): @@ -638,8 +754,13 @@ def allocate(self, alignment, byte_length): ### Table State +@dataclass +class TableEntry: + item: any + handle_ref: Optional[HandleRef] = None + class Table: - array: list[any] + array: list[Optional[TableEntry]] free: list[int] MAX_LENGTH = 2**28 - 1 @@ -649,24 +770,24 @@ def __init__(self): self.free = [] def __iter__(self): - for e in self.array: - if e is not None: - yield e + for entry in self.array: + if entry is not None: + yield entry.item def get(self, i): trap_if(i >= len(self.array)) trap_if(self.array[i] is None) - return self.array[i] + return self.array[i].item def add(self, e): if self.free: i = self.free.pop() assert(self.array[i] is None) - self.array[i] = e + self.array[i] = TableEntry(e) else: i = len(self.array) trap_if(i > Table.MAX_LENGTH) - self.array.append(e) + self.array.append(TableEntry(e)) return i def remove(self, i): @@ -675,6 +796,19 @@ def remove(self, i): self.free.append(i) return e + def get_handle_ref(self, i): + trap_if(i >= len(self.array)) + if self.array[i] is None: + return None + else: + return self.array[i].handle_ref + + def set_handle_ref(self, i, r): + trap_if(i >= len(self.array)) + trap_if(self.array[i] is None) + trap_if(self.array[i].handle_ref is not None) + self.array[i].handle_ref = r + ### Resource State class ResourceHandle: @@ -691,9 +825,11 @@ def __init__(self, rt, rep_val, own, borrow_scope = None): self.borrow_scope = borrow_scope self.num_lends = 0 +ANYREF = CoreRefType('any') + class ResourceType(Type): impl_inst: ComponentInstance - rep: Literal['i32', 'i64'] + rep: Literal['i32', 'i64'] | CoreRefType dtor: Optional[Callable] def __init__(self, impl_inst, rep, dtor = None): @@ -919,6 +1055,71 @@ def write(self, vs): assert(all(v == () for v in vs)) self.progress += len(vs) +class GcBuffer(Buffer): + cx: LiftLowerContext + t: Optional[ValType] + elems: list[any] + offset: int + length: int + progress: int + + def __init__(self, t, cx, elems, offset, length): + trap_if(length > Buffer.MAX_LENGTH) + if t is not None: + trap_if(offset + length > len(elems)) + self.cx = cx + self.t = t + self.elems = elems + self.offset = offset + self.length = length + self.progress = 0 + + def remain(self): + return self.length - self.progress + +class ReadableGcBuffer(GcBuffer, ReadableBuffer): + def read(self, n): + assert(n <= self.remain()) + if self.t: + vs = [] + for i in range(n): + vs.append(self.lift(self.elems[self.offset + self.progress + i])) + else: + vs = n * [()] + self.progress += n + return vs + + def lift(self, v): + return lift_gc_value(self.cx, v, self.t) + +class WritableGcBuffer(GcBuffer, WritableBuffer): + def write(self, vs): + assert(len(vs) <= self.remain()) + if self.t: + for i,v in enumerate(vs): + self.elems[self.offset + self.progress + i] = self.lower(v) + else: + assert(all(v == () for v in vs)) + self.progress += len(vs) + + def lower(self, v): + return lower_gc_value(self.cx, v, self.t) + +class ReadableGcValueBuffer(ReadableGcBuffer): + def __init__(self, t, cx, v = None): + assert(t is not None or v is None) + ReadableGcBuffer.__init__(self, t, cx, [v], 0, 1) + + def lift(self, v): + return lift_unpacked_gc_value(self.cx, v, self.t) + +def lift_unpacked_gc_value(cx, v, t): + match gc_storage_type(cx, t): + case 'i8' | 'i16': + return lift_flat(cx, CoreValueIter([v]), t) + case 'i32' | 'i64' | 'f32' | 'f64' | CoreRefType(): + return lift_gc_value(cx, v, t) + ### Stream and Future State class End(Waitable): @@ -1195,6 +1396,7 @@ def alignment_flags(labels): def alignment_borrow(cx, borrowt): if pass_rep_not_handle(cx, borrowt): + assert(borrowt.rt.rep in ['i32', 'i64']) return ptr_size(borrowt.rt.rep) else: return 4 @@ -1260,10 +1462,110 @@ def elem_size_flags(labels): def elem_size_borrow(cx, borrowt): if pass_rep_not_handle(cx, borrowt): + assert(borrowt.rt.rep in ['i32', 'i64']) return ptr_size(borrowt.rt.rep) else: return 4 +## 🛸 GC Types + +EXTERNREF = CoreRefType('extern') + +def handle_type(cx): + if cx.opts.gc: + return EXTERNREF + else: + return 'i32' + +def gc_storage_type(cx, t): + match despecialize(t): + case BoolType() | S8Type() | U8Type() : return 'i8' + case S16Type() | U16Type() : return 'i16' + case S32Type() | U32Type() | CharType() : return 'i32' + case F32Type() : return 'f32' + case S64Type() | U64Type() : return 'i64' + case F64Type() : return 'f64' + case StringType() : return CoreRefType(gc_string_type(cx)) + case ListType(t, l) : return CoreRefType(gc_list_type(cx, t)) + case RecordType(fields) : return CoreRefType(gc_record_type(cx, fields)) + case VariantType(cases) : return gc_variant_type(cx, cases) + case FlagsType(labels) : return gc_packed_int_type(elem_size_flags(labels)) + case BorrowType() : return gc_borrow_type(cx, t) + case OwnType() | StreamType() | FutureType() | ErrorContextType(): + return EXTERNREF + +def gc_borrow_type(cx, borrowt): + if pass_rep_not_handle(cx, borrowt): + return borrowt.rt.rep + else: + return EXTERNREF + +def gc_packed_int_type(nbytes): + match nbytes: + case 1: return 'i8' + case 2: return 'i16' + case 4: return 'i32' + case 8: return 'i64' + +def gc_final_type(comptype): + return CoreDefType(CoreRecType((CoreSubType(True, (), comptype),)), 0) + +GC_UTF8_ARRAY = gc_final_type(CoreArrayType(CoreFieldType('i8'))) +GC_LATIN1_ARRAY = gc_final_type(CoreArrayType(CoreFieldType('i8'))) +GC_UTF16_ARRAY = gc_final_type(CoreArrayType(CoreFieldType('i16'))) + +def gc_string_type(cx): + match cx.opts.string_encoding: + case 'utf8' : return GC_UTF8_ARRAY + case 'utf16' : return GC_UTF16_ARRAY + case 'latin1+utf16' : return 'array' + +def gc_list_type(cx, elem_type): + return gc_final_type(CoreArrayType(CoreFieldType(gc_storage_type(cx, elem_type)))) + +def gc_record_type(cx, fields): + return gc_final_type(CoreStructType(tuple(CoreFieldType(gc_storage_type(cx, f.t)) for f in fields))) + +def gc_variant_type(cx, cases): + if has_payload(cases): + return CoreRefType(gc_variant_base_type(cx, cases)) + else: + return gc_storage_type(cx, discriminant_type(cases)) + +def has_payload(cases): + return any(c.t is not None for c in cases) + +def gc_variant_rec_type(cx, cases): + discriminant = CoreFieldType(gc_storage_type(cx, discriminant_type(cases))) + base = CoreSubType(False, (), CoreStructType((discriminant,))) + case_types = [] + for c in cases: + fields = (discriminant,) + if c.t is not None: + fields += (CoreFieldType(gc_storage_type(cx, c.t)),) + case_types.append(CoreSubType(True, (CoreRecIdx(0),), CoreStructType(fields))) + return CoreRecType((base, *case_types)) + +def gc_variant_base_type(cx, cases): + return CoreDefType(gc_variant_rec_type(cx, cases), 0) + +def gc_variant_case_type(cx, cases, case_index): + return CoreDefType(gc_variant_rec_type(cx, cases), 1 + case_index) + +def nullable_type(t): + match t: + case CoreRefType(heap_type, _) : return CoreRefType(heap_type, nullable = True) + case 'i8' | 'i16' | 'i32' | 'i64' | 'f32' | 'f64' : return t + +def unpacked_type(t): + match t: + case 'i8' | 'i16' : return 'i32' + case 'i32' | 'i64' | 'f32' | 'f64' | CoreRefType() : return t + +def gc_async_results_type(cx, t): + field = CoreFieldType(nullable_type(gc_storage_type(cx, t)), mutable = True) + return gc_final_type(CoreStructType((field,))) + ## Loading def load(cx, ptr, t): @@ -1334,7 +1636,13 @@ def convert_i32_to_char(cx, i): trap_if(0xD800 <= i <= 0xDFFF) return chr(i) -String = tuple[str, str, int] +class StringHint(Enum): + UTF8 = 0 + UTF16 = 1 + DYNAMIC_LATIN1 = 2 + DYNAMIC_UTF16 = 3 + +String = tuple[str, StringHint, int] def load_string(cx, ptr) -> String: ptr_size = cx.opts.memory.ptr_size() @@ -1354,20 +1662,28 @@ def load_string_from_range(cx, ptr, tagged_code_units) -> String: match cx.opts.string_encoding: case 'utf8': alignment = 1 - byte_length = tagged_code_units + code_units = tagged_code_units + byte_length = code_units encoding = 'utf-8' + hint = StringHint.UTF8 case 'utf16': alignment = 2 - byte_length = 2 * tagged_code_units + code_units = tagged_code_units + byte_length = 2 * code_units encoding = 'utf-16-le' + hint = StringHint.UTF16 case 'latin1+utf16': alignment = 2 if bool(tagged_code_units & tag): - byte_length = 2 * (tagged_code_units ^ tag) + code_units = tagged_code_units ^ tag + byte_length = 2 * code_units encoding = 'utf-16-le' + hint = StringHint.DYNAMIC_UTF16 else: - byte_length = tagged_code_units + code_units = tagged_code_units + byte_length = code_units encoding = 'latin-1' + hint = StringHint.DYNAMIC_LATIN1 trap_if(byte_length > MAX_STRING_BYTE_LENGTH) trap_if(ptr != align_to(ptr, alignment)) @@ -1377,7 +1693,7 @@ def load_string_from_range(cx, ptr, tagged_code_units) -> String: except UnicodeError: trap() - return (s, cx.opts.string_encoding, tagged_code_units) + return (s, hint, code_units) def lift_error_context(cx, i): errctx = cx.inst.handles.get(i) @@ -1552,39 +1868,26 @@ def store_string(cx, v: String, ptr): store_int(cx, tagged_code_units, ptr + ptr_size, ptr_size) def store_string_into_range(cx, v: String): - src, src_encoding, src_tagged_code_units = v - tag = utf16_tag(cx) - - if src_encoding == 'latin1+utf16': - if bool(src_tagged_code_units & tag): - src_simple_encoding = 'utf16' - src_code_units = src_tagged_code_units ^ tag - else: - src_simple_encoding = 'latin1' - src_code_units = src_tagged_code_units - else: - src_simple_encoding = src_encoding - src_code_units = src_tagged_code_units - + src, src_hint, src_code_units = v match cx.opts.string_encoding: case 'utf8': - match src_simple_encoding: - case 'utf8' : return store_string_copy(cx, src, src_code_units, 1, 1, 'utf-8') - case 'utf16' : return store_utf16_to_utf8(cx, src, src_code_units) - case 'latin1' : return store_latin1_to_utf8(cx, src, src_code_units) + match src_hint: + case StringHint.UTF8 : return store_string_copy(cx, src, src_code_units, 1, 1, 'utf-8') + case StringHint.UTF16 : return store_utf16_to_utf8(cx, src, src_code_units) + case StringHint.DYNAMIC_LATIN1 : return store_latin1_to_utf8(cx, src, src_code_units) + case StringHint.DYNAMIC_UTF16 : return store_utf16_to_utf8(cx, src, src_code_units) case 'utf16': - match src_simple_encoding: - case 'utf8' : return store_utf8_to_utf16(cx, src, src_code_units) - case 'utf16' : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') - case 'latin1' : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') + match src_hint: + case StringHint.UTF8 : return store_utf8_to_utf16(cx, src, src_code_units) + case StringHint.UTF16 : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') + case StringHint.DYNAMIC_LATIN1 : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') + case StringHint.DYNAMIC_UTF16 : return store_string_copy(cx, src, src_code_units, 2, 2, 'utf-16-le') case 'latin1+utf16': - match src_encoding: - case 'utf8' : return store_string_to_latin1_or_utf16(cx, src, src_code_units) - case 'utf16' : return store_string_to_latin1_or_utf16(cx, src, src_code_units) - case 'latin1+utf16' : - match src_simple_encoding: - case 'latin1' : return store_string_copy(cx, src, src_code_units, 1, 2, 'latin-1') - case 'utf16' : return store_probably_utf16_to_latin1_or_utf16(cx, src, src_code_units) + match src_hint: + case StringHint.UTF8 : return store_string_to_latin1_or_utf16(cx, src, src_code_units) + case StringHint.UTF16 : return store_string_to_latin1_or_utf16(cx, src, src_code_units) + case StringHint.DYNAMIC_LATIN1 : return store_string_copy(cx, src, src_code_units, 1, 2, 'latin-1') + case StringHint.DYNAMIC_UTF16 : return store_probably_utf16_to_latin1_or_utf16(cx, src, src_code_units) def store_string_copy(cx, src, src_code_units, dst_code_unit_size, dst_alignment, dst_encoding): dst_byte_length = dst_code_unit_size * src_code_units @@ -1767,37 +2070,63 @@ def lower_async_value(ReadableEndT, cx, end, t): MAX_FLAT_PARAMS = 16 MAX_FLAT_ASYNC_PARAMS = 4 MAX_FLAT_RESULTS = 1 +MAX_FLAT_GC_RESULTS = 16 def flatten_functype(cx, ft): flat_params = flatten_types(cx.reverse_direction(), ft.param_types()) flat_results = flatten_types(cx, ft.result_type()) - if not cx.opts.async_: - if len(flat_params) > MAX_FLAT_PARAMS: - flat_params = [cx.opts.memory.ptr_type()] - if len(flat_results) > MAX_FLAT_RESULTS: + if cx.opts.gc: + if not cx.opts.async_: + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [gc_storage_type(cx.reverse_direction(), TupleType(ft.param_types()))] + if len(flat_results) > MAX_FLAT_GC_RESULTS: + [result_type] = ft.result_type() + flat_results = [gc_storage_type(cx, result_type)] + else: match cx.direction: case 'lift': - flat_results = [cx.opts.memory.ptr_type()] + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [gc_storage_type(cx.reverse_direction(), TupleType(ft.param_types()))] + if cx.opts.callback: + flat_results = ['i32', nullable_type(EXTERNREF)] + else: + flat_results = [] case 'lower': - flat_params += [cx.opts.memory.ptr_type()] - flat_results = [] + if len(flat_params) > MAX_FLAT_ASYNC_PARAMS: + flat_params = [gc_storage_type(cx.reverse_direction(), TupleType(ft.param_types()))] + if len(flat_results) > 0: + [result_type] = ft.result_type() + flat_params += [CoreRefType(gc_async_results_type(cx, result_type))] + flat_results = ['i32', nullable_type(EXTERNREF)] return CoreFuncType(flat_params, flat_results) else: - match cx.direction: - case 'lift': - if len(flat_params) > MAX_FLAT_PARAMS: - flat_params = [cx.opts.memory.ptr_type()] - if cx.opts.callback: + if not cx.opts.async_: + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [cx.opts.memory.ptr_type()] + if len(flat_results) > MAX_FLAT_RESULTS: + match cx.direction: + case 'lift': + flat_results = [cx.opts.memory.ptr_type()] + case 'lower': + flat_params += [cx.opts.memory.ptr_type()] + flat_results = [] + return CoreFuncType(flat_params, flat_results) + else: + match cx.direction: + case 'lift': + if len(flat_params) > MAX_FLAT_PARAMS: + flat_params = [cx.opts.memory.ptr_type()] + if cx.opts.callback: + flat_results = ['i32'] + else: + flat_results = [] + case 'lower': + if len(flat_params) > MAX_FLAT_ASYNC_PARAMS: + flat_params = [cx.opts.memory.ptr_type()] + if len(flat_results) > 0: + flat_params += [cx.opts.memory.ptr_type()] flat_results = ['i32'] - else: - flat_results = [] - case 'lower': - if len(flat_params) > MAX_FLAT_ASYNC_PARAMS: - flat_params = [cx.opts.memory.ptr_type()] - if len(flat_results) > 0: - flat_params += [cx.opts.memory.ptr_type()] - flat_results = ['i32'] - return CoreFuncType(flat_params, flat_results) + return CoreFuncType(flat_params, flat_results) def flatten_types(cx, ts): return [ft for t in ts for ft in flatten_type(cx, t)] @@ -1811,20 +2140,29 @@ def flatten_type(cx, t): case F32Type() : return ['f32'] case F64Type() : return ['f64'] case CharType() : return ['i32'] - case StringType() : return 2 * [cx.opts.memory.ptr_type()] - case ErrorContextType() : return ['i32'] + case StringType() : return flatten_string(cx) + case ErrorContextType() : return [handle_type(cx)] case ListType(t, l) : return flatten_list(cx, t, l) case RecordType(fields) : return flatten_record(cx, fields) case VariantType(cases) : return flatten_variant(cx, cases) case FlagsType(labels) : return ['i32'] - case OwnType() : return ['i32'] + case OwnType() : return [handle_type(cx)] case BorrowType() : return flatten_borrow(cx, t) - case StreamType() | FutureType() : return ['i32'] + case StreamType() | FutureType() : return [handle_type(cx)] + +def flatten_string(cx): + if cx.opts.gc: + return [CoreRefType(gc_string_type(cx))] + else: + return 2 * [cx.opts.memory.ptr_type()] def flatten_list(cx, elem_type, maybe_length): - if maybe_length is not None: - return flatten_type(cx, elem_type) * maybe_length - return 2 * [cx.opts.memory.ptr_type()] + if cx.opts.gc: + return [CoreRefType(gc_list_type(cx, elem_type))] + else: + if maybe_length is not None: + return flatten_type(cx, elem_type) * maybe_length + return 2 * [cx.opts.memory.ptr_type()] def flatten_record(cx, fields): flat = [] @@ -1833,15 +2171,18 @@ def flatten_record(cx, fields): return flat def flatten_variant(cx, cases): - flat = [] - for c in cases: - if c.t is not None: - for i,ft in enumerate(flatten_type(cx, c.t)): - if i < len(flat): - flat[i] = join(flat[i], ft) - else: - flat.append(ft) - return flatten_type(cx, discriminant_type(cases)) + flat + if cx.opts.gc and has_payload(cases): + return [CoreRefType(gc_variant_base_type(cx, cases))] + else: + flat = [] + for c in cases: + if c.t is not None: + for i,ft in enumerate(flatten_type(cx, c.t)): + if i < len(flat): + flat[i] = join(flat[i], ft) + else: + flat.append(ft) + return flatten_type(cx, discriminant_type(cases)) + flat def join(a, b): if a == b: return a @@ -1850,9 +2191,10 @@ def join(a, b): def flatten_borrow(cx, borrowt): if pass_rep_not_handle(cx, borrowt): + assert(cx.opts.gc or borrowt.rt.rep in ['i32', 'i64']) return [borrowt.rt.rep] else: - return ['i32'] + return [handle_type(cx)] ## Flat Lifting @@ -1872,6 +2214,7 @@ def next(self, t): case 'i64': assert(isinstance(v, int) and 0 <= v < 2**64) case 'f32': assert(isinstance(v, (int,float))) case 'f64': assert(isinstance(v, (int,float))) + case CoreRefType(): assert(ref_test(v, t)) case _ : assert(False) return v @@ -1890,15 +2233,15 @@ def lift_flat(cx, vi, t): case F64Type() : return canonicalize_nan64(vi.next('f64')) case CharType() : return convert_i32_to_char(cx, vi.next('i32')) case StringType() : return lift_flat_string(cx, vi) - case ErrorContextType() : return lift_error_context(cx, vi.next('i32')) + case ErrorContextType() : return lift_error_context(cx, lift_flat_handle(cx, vi)) case ListType(t, l) : return lift_flat_list(cx, vi, t, l) case RecordType(fields) : return lift_flat_record(cx, vi, fields) case VariantType(cases) : return lift_flat_variant(cx, vi, cases) case FlagsType(labels) : return lift_flat_flags(vi, labels) - case OwnType() : return lift_own(cx, vi.next('i32'), t) - case BorrowType() : return lift_borrow(cx, vi.next('i32'), t) - case StreamType(t) : return lift_stream(cx, vi.next('i32'), t) - case FutureType(t) : return lift_future(cx, vi.next('i32'), t) + case OwnType() : return lift_own(cx, lift_flat_handle(cx, vi), t) + case BorrowType() : return lift_borrow(cx, lift_flat_handle(cx, vi), t) + case StreamType(t) : return lift_stream(cx, lift_flat_handle(cx, vi), t) + case FutureType(t) : return lift_future(cx, lift_flat_handle(cx, vi), t) def lift_flat_unsigned(vi, core_width, t_width): i = vi.next('i' + str(core_width)) @@ -1908,25 +2251,80 @@ def lift_flat_unsigned(vi, core_width, t_width): def lift_flat_signed(vi, core_width, t_width): i = vi.next('i' + str(core_width)) assert(0 <= i < (1 << core_width)) - i %= (1 << t_width) - if i >= (1 << (t_width - 1)): - return i - (1 << t_width) + return lift_signed(i % (1 << t_width), t_width) + +def lift_signed(i, width): + assert(0 <= i < (1 << width)) + if i >= (1 << (width - 1)): + return i - (1 << width) return i def lift_flat_string(cx, vi): - ptr = vi.next(cx.opts.memory.ptr_type()) - packed_length = vi.next(cx.opts.memory.ptr_type()) - return load_string_from_range(cx, ptr, packed_length) + if cx.opts.gc: + return lift_gc_string(cx, vi.next(CoreRefType(gc_string_type(cx)))) + else: + ptr = vi.next(cx.opts.memory.ptr_type()) + packed_length = vi.next(cx.opts.memory.ptr_type()) + return load_string_from_range(cx, ptr, packed_length) def lift_flat_list(cx, vi, elem_type, maybe_length): + if cx.opts.gc: + return lift_gc_list(cx, vi.next(CoreRefType(gc_list_type(cx, elem_type))), elem_type, maybe_length) + else: + if maybe_length is not None: + a = [] + for i in range(maybe_length): + a.append(lift_flat(cx, vi, elem_type)) + return a + ptr = vi.next(cx.opts.memory.ptr_type()) + length = vi.next(cx.opts.memory.ptr_type()) + return load_list_from_range(cx, ptr, length, elem_type) + +def lift_gc_string(cx, arr) -> String: + match cx.opts.string_encoding: + case 'utf8': + code_unit_size = 1 + encoding = 'utf-8' + hint = StringHint.UTF8 + case 'utf16': + code_unit_size = 2 + encoding = 'utf-16-le' + hint = StringHint.UTF16 + case 'latin1+utf16': + if ref_test(arr, CoreRefType(GC_LATIN1_ARRAY)): + code_unit_size = 1 + encoding = 'latin-1' + hint = StringHint.DYNAMIC_LATIN1 + else: + trap_if(not ref_test(arr, CoreRefType(GC_UTF16_ARRAY))) + code_unit_size = 2 + encoding = 'utf-16-le' + hint = StringHint.DYNAMIC_UTF16 + + code_units = array_len(arr) + trap_if(code_units * code_unit_size > MAX_STRING_BYTE_LENGTH) + encoded = b''.join(int.to_bytes(array_get(arr, i), code_unit_size, 'little') for i in range(code_units)) + try: + s = encoded.decode(encoding) + except UnicodeError: + trap() + + return (s, hint, code_units) + +def lift_gc_list(cx, arr, elem_type, maybe_length): + length = array_len(arr) if maybe_length is not None: - a = [] - for i in range(maybe_length): - a.append(lift_flat(cx, vi, elem_type)) - return a - ptr = vi.next(cx.opts.memory.ptr_type()) - length = vi.next(cx.opts.memory.ptr_type()) - return load_list_from_range(cx, ptr, length, elem_type) + trap_if(length != maybe_length) + elif not isinstance(gc_storage_type(cx, elem_type), CoreRefType): + trap_if(length * elem_size(cx, elem_type) > MAX_LIST_BYTE_LENGTH) + else: + # TODO FITZGEN: How do we want to impose `MAX_LIST_BYTE_LENGTH` on arrays of + # references? Do we want to even impose any limit in this case? + pass + a = [] + for i in range(length): + a.append(lift_gc_value(cx, array_get(arr, i), elem_type)) + return a def lift_flat_record(cx, vi, fields): record = {} @@ -1935,38 +2333,104 @@ def lift_flat_record(cx, vi, fields): return record def lift_flat_variant(cx, vi, cases): - flat_types = flatten_variant(cx, cases) - assert(flat_types.pop(0) == 'i32') - case_index = vi.next('i32') - trap_if(case_index >= len(cases)) - class CoerceValueIter: - def next(self, want): - have = flat_types.pop(0) - x = vi.next(have) - match (have, want): - case ('i32', 'f32') : return decode_i32_as_float(x) - case ('i64', 'i32') : return wrap_i64_to_i32(x) - case ('i64', 'f32') : return decode_i32_as_float(wrap_i64_to_i32(x)) - case ('i64', 'f64') : return decode_i64_as_float(x) - case _ : assert(have == want); return x - c = cases[case_index] - if c.t is None: - v = None + if cx.opts.gc and has_payload(cases): + return lift_gc_variant(cx, vi.next(CoreRefType(gc_variant_base_type(cx, cases))), cases) else: - v = lift_flat(cx, CoerceValueIter(), c.t) - for have in flat_types: - _ = vi.next(have) - return { c.label: v } + flat_types = flatten_variant(cx, cases) + assert(flat_types.pop(0) == 'i32') + case_index = vi.next('i32') + trap_if(case_index >= len(cases)) + class CoerceValueIter: + def next(self, want): + have = flat_types.pop(0) + x = vi.next(have) + match (have, want): + case ('i32', 'f32') : return decode_i32_as_float(x) + case ('i64', 'i32') : return wrap_i64_to_i32(x) + case ('i64', 'f32') : return decode_i32_as_float(wrap_i64_to_i32(x)) + case ('i64', 'f64') : return decode_i64_as_float(x) + case _ : assert(have == want); return x + c = cases[case_index] + if c.t is None: + v = None + else: + v = lift_flat(cx, CoerceValueIter(), c.t) + for have in flat_types: + _ = vi.next(have) + return { c.label: v } def wrap_i64_to_i32(i): assert(0 <= i < (1 << 64)) return i % (1 << 32) +def lift_gc_variant(cx, v, cases): + if has_payload(cases): + case_index = struct_get(v, 0) + trap_if(case_index >= len(cases)) + trap_if(not ref_test(v, CoreRefType(gc_variant_case_type(cx, cases, case_index)))) + c = cases[case_index] + if c.t is None: + return { c.label: None } + return { c.label: lift_gc_value(cx, struct_get(v, 1), c.t) } + else: + trap_if(v >= len(cases)) + return { cases[v].label: None } + def lift_flat_flags(vi, labels): assert(0 < len(labels) <= 32) i = vi.next('i32') return unpack_flags_from_int(i, labels) +class HandleRef: + index: int + + def __init__(self, inst, index): + inst.handles.set_handle_ref(index, self) + self.index = index + +def lift_flat_handle(cx, vi): + v = vi.next(handle_type(cx)) + if cx.opts.gc: + return unbox_handle(cx.inst, v) + else: + return v + +def unbox_handle(inst, r): + trap_if(not isinstance(r, HandleRef)) + trap_if(inst.handles.get_handle_ref(r.index) is not r) + return r.index + +def lift_gc_value(cx, v, t): + match despecialize(t): + case BoolType() : return convert_int_to_bool(v) + case U8Type() : return v + case S8Type() : return lift_signed(v, 8) + case U16Type() : return v + case S16Type() : return lift_signed(v, 16) + case U32Type() : return v + case S32Type() : return lift_signed(v, 32) + case CharType() : return convert_i32_to_char(cx, v) + case F32Type() : return canonicalize_nan32(v) + case U64Type() : return v + case S64Type() : return lift_signed(v, 64) + case F64Type() : return canonicalize_nan64(v) + case StringType() : return lift_gc_string(cx, v) + case ListType(t, l) : return lift_gc_list(cx, v, t, l) + case RecordType(fields) : return lift_gc_record(cx, v, fields) + case VariantType(cases) : return lift_gc_variant(cx, v, cases) + case FlagsType(labels) : return unpack_flags_from_int(v, labels) + case BorrowType() : return lift_borrow(cx, unbox_handle(cx.inst, v), t) + case OwnType() : return lift_own(cx, unbox_handle(cx.inst, v), t) + case StreamType(t) : return lift_stream(cx, unbox_handle(cx.inst, v), t) + case FutureType(t) : return lift_future(cx, unbox_handle(cx.inst, v), t) + case ErrorContextType() : return lift_error_context(cx, unbox_handle(cx.inst, v)) + +def lift_gc_record(cx, s, fields): + record = {} + for i,f in enumerate(fields): + record[f.label] = lift_gc_value(cx, struct_get(s, i), f.t) + return record + ## Flat Lowering def lower_flat(cx, v, t): @@ -1984,34 +2448,66 @@ def lower_flat(cx, v, t): case F64Type() : return [maybe_scramble_nan64(v)] case CharType() : return [char_to_i32(v)] case StringType() : return lower_flat_string(cx, v) - case ErrorContextType() : return [lower_error_context(cx, v)] + case ErrorContextType() : return [lower_flat_handle(cx, lower_error_context(cx, v))] case ListType(t, l) : return lower_flat_list(cx, v, t, l) case RecordType(fields) : return lower_flat_record(cx, v, fields) case VariantType(cases) : return lower_flat_variant(cx, v, cases) case FlagsType(labels) : return lower_flat_flags(v, labels) case OwnType() : return lower_flat_own(cx, v, t) case BorrowType() : return lower_flat_borrow(cx, v, t) - case StreamType(t) : return [lower_stream(cx, v, t)] - case FutureType(t) : return [lower_future(cx, v, t)] + case StreamType(t) : return [lower_flat_handle(cx, lower_stream(cx, v, t))] + case FutureType(t) : return [lower_flat_handle(cx, lower_future(cx, v, t))] def lower_flat_signed(i, core_bits): + return [lower_signed(i, core_bits)] + +def lower_signed(i, width): if i < 0: - i += (1 << core_bits) - return [i] + i += (1 << width) + return i def lower_flat_string(cx, v): - ptr, packed_length = store_string_into_range(cx, v) - return [ptr, packed_length] + if cx.opts.gc: + return [lower_gc_string(cx, v)] + else: + ptr, packed_length = store_string_into_range(cx, v) + return [ptr, packed_length] def lower_flat_list(cx, v, elem_type, maybe_length): - if maybe_length is not None: - assert(maybe_length == len(v)) - flat = [] - for e in v: - flat += lower_flat(cx, e, elem_type) - return flat - (ptr, length) = store_list_into_range(cx, v, elem_type) - return [ptr, length] + if cx.opts.gc: + return [lower_gc_list(cx, v, elem_type, maybe_length)] + else: + if maybe_length is not None: + assert(maybe_length == len(v)) + flat = [] + for e in v: + flat += lower_flat(cx, e, elem_type) + return flat + (ptr, length) = store_list_into_range(cx, v, elem_type) + return [ptr, length] + +def lower_gc_string(cx, v: String): + src, _, _ = v + match cx.opts.string_encoding: + case 'utf8': + return array_new_fixed(GC_UTF8_ARRAY, list(src.encode('utf-8'))) + case 'utf16': + return array_new_fixed(GC_UTF16_ARRAY, encode_utf16_code_units(src)) + case 'latin1+utf16': + if all(ord(c) < (1 << 8) for c in src): + return array_new_fixed(GC_LATIN1_ARRAY, list(src.encode('latin-1'))) + return array_new_fixed(GC_UTF16_ARRAY, encode_utf16_code_units(src)) + +def encode_utf16_code_units(src): + encoded = src.encode('utf-16-le') + return [int.from_bytes(encoded[i : i+2], 'little') for i in range(0, len(encoded), 2)] + +def lower_gc_list(cx, v, elem_type, maybe_length): + assert(maybe_length is None or maybe_length == len(v)) + elems = [] + for e in v: + elems.append(lower_gc_value(cx, e, elem_type)) + return array_new_fixed(gc_list_type(cx, elem_type), elems) def lower_flat_record(cx, v, fields): flat = [] @@ -2020,66 +2516,144 @@ def lower_flat_record(cx, v, fields): return flat def lower_flat_variant(cx, v, cases): + if cx.opts.gc and has_payload(cases): + return [lower_gc_variant(cx, v, cases)] + else: + case_index, case_value = match_case(v, cases) + flat_types = flatten_variant(cx, cases) + assert(flat_types.pop(0) == 'i32') + c = cases[case_index] + if c.t is None: + payload = [] + else: + payload = lower_flat(cx, case_value, c.t) + for i,(fv,have) in enumerate(zip(payload, flatten_type(cx, c.t))): + want = flat_types.pop(0) + match (have, want): + case ('f32', 'i32') : payload[i] = encode_float_as_i32(fv) + case ('i32', 'i64') : payload[i] = fv + case ('f32', 'i64') : payload[i] = encode_float_as_i32(fv) + case ('f64', 'i64') : payload[i] = encode_float_as_i64(fv) + case _ : assert(have == want) + for _ in flat_types: + payload.append(0) + return [case_index] + payload + +def lower_gc_variant(cx, v, cases): case_index, case_value = match_case(v, cases) - flat_types = flatten_variant(cx, cases) - assert(flat_types.pop(0) == 'i32') - c = cases[case_index] - if c.t is None: - payload = [] + if has_payload(cases): + fields = [case_index] + c = cases[case_index] + if c.t is not None: + fields.append(lower_gc_value(cx, case_value, c.t)) + return struct_new(gc_variant_case_type(cx, cases, case_index), fields) else: - payload = lower_flat(cx, case_value, c.t) - for i,(fv,have) in enumerate(zip(payload, flatten_type(cx, c.t))): - want = flat_types.pop(0) - match (have, want): - case ('f32', 'i32') : payload[i] = encode_float_as_i32(fv) - case ('i32', 'i64') : payload[i] = fv - case ('f32', 'i64') : payload[i] = encode_float_as_i32(fv) - case ('f64', 'i64') : payload[i] = encode_float_as_i64(fv) - case _ : assert(have == want) - for _ in flat_types: - payload.append(0) - return [case_index] + payload + return case_index def lower_flat_flags(v, labels): assert(0 < len(labels) <= 32) return [pack_flags_into_int(v, labels)] def lower_flat_own(cx, rep_val, ownt): - return [add_own(cx, rep_val, ownt)] + return [lower_flat_handle(cx, add_own(cx, rep_val, ownt))] def lower_flat_borrow(cx, rep_val, borrowt): if pass_rep_not_handle(cx, borrowt): return [rep_val] else: - return [add_borrow(cx, rep_val, borrowt)] + return [lower_flat_handle(cx, add_borrow(cx, rep_val, borrowt))] + +def lower_flat_handle(cx, i): + if cx.opts.gc: + return HandleRef(cx.inst, i) + else: + return i + +def lower_gc_value(cx, v, t): + match despecialize(t): + case BoolType() : return int(v) + case U8Type() : return v + case S8Type() : return lower_signed(v, 8) + case U16Type() : return v + case S16Type() : return lower_signed(v, 16) + case U32Type() : return v + case S32Type() : return lower_signed(v, 32) + case CharType() : return char_to_i32(v) + case F32Type() : return maybe_scramble_nan32(v) + case U64Type() : return v + case S64Type() : return lower_signed(v, 64) + case F64Type() : return maybe_scramble_nan64(v) + case StringType() : return lower_gc_string(cx, v) + case ListType(t, l) : return lower_gc_list(cx, v, t, l) + case RecordType(fields) : return lower_gc_record(cx, v, fields) + case VariantType(cases) : return lower_gc_variant(cx, v, cases) + case FlagsType(labels) : return pack_flags_into_int(v, labels) + case BorrowType() : return lower_gc_borrow(cx, v, t) + case OwnType() : return HandleRef(cx.inst, add_own(cx, v, t)) + case StreamType(t) : return HandleRef(cx.inst, lower_stream(cx, v, t)) + case FutureType(t) : return HandleRef(cx.inst, lower_future(cx, v, t)) + case ErrorContextType() : return HandleRef(cx.inst, lower_error_context(cx, v)) + +def lower_gc_borrow(cx, rep_val, borrowt): + if pass_rep_not_handle(cx, borrowt): + return rep_val + else: + return HandleRef(cx.inst, add_borrow(cx, rep_val, borrowt)) + +def lower_gc_record(cx, v, fields): + vs = [] + for f in fields: + vs.append(lower_gc_value(cx, v[f.label], f.t)) + return struct_new(gc_record_type(cx, fields), vs) ## Lifting and Lowering Values -def lift_flat_values(cx, max_flat, vi, ts): +def lift_flat_values(cx, max_flat, vi, ts, is_result = False): flat_types = flatten_types(cx, ts) if len(flat_types) > max_flat: - ptr = vi.next(cx.opts.memory.ptr_type()) - tuple_type = TupleType(ts) - trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) - trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) - return list(load(cx, ptr, tuple_type).values()) + if cx.opts.gc: + if is_result: + [t] = ts + return [lift_gc_value(cx, vi.next(gc_storage_type(cx, t)), t)] + else: + tuple_type = TupleType(ts) + return list(lift_gc_value(cx, vi.next(gc_storage_type(cx, tuple_type)), tuple_type).values()) + else: + ptr = vi.next(cx.opts.memory.ptr_type()) + tuple_type = TupleType(ts) + trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) + trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) + return list(load(cx, ptr, tuple_type).values()) else: return [ lift_flat(cx, vi, t) for t in ts ] -def lower_flat_values(cx, max_flat, vs, ts, out_param = None): +def lower_flat_values(cx, max_flat, vs, ts, out_param = None, is_result = False): flat_types = flatten_types(cx, ts) if len(flat_types) > max_flat: tuple_type = TupleType(ts) tuple_value = {str(i): v for i,v in enumerate(vs)} - if out_param is None: - ptr = cx.allocate(alignment(cx, tuple_type), elem_size(cx, tuple_type)) - flat_vals = [ptr] + if cx.opts.gc: + if is_result: + [v] = vs + [t] = ts + if cx.opts.async_: + results = out_param.next(CoreRefType(gc_async_results_type(cx, t))) + struct_set(results, 0, lower_gc_value(cx, v, t)) + return [] + else: + return [lower_gc_value(cx, v, t)] + else: + return [lower_gc_value(cx, tuple_value, tuple_type)] else: - ptr = out_param.next(cx.opts.memory.ptr_type()) - trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) - trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) - flat_vals = [] - store(cx, tuple_value, tuple_type, ptr) + if out_param is None: + ptr = cx.allocate(alignment(cx, tuple_type), elem_size(cx, tuple_type)) + flat_vals = [ptr] + else: + ptr = out_param.next(cx.opts.memory.ptr_type()) + trap_if(ptr != align_to(ptr, alignment(cx, tuple_type))) + trap_if(ptr + elem_size(cx, tuple_type) > len(cx.opts.memory)) + flat_vals = [] + store(cx, tuple_value, tuple_type, ptr) else: flat_vals = [] for i in range(len(vs)): @@ -2104,7 +2678,8 @@ def thread_func(): if not opts.async_: flat_results = call_and_trap_on_throw(callee, flat_args) assert(types_match_values(flat_ft.results, flat_results)) - result = lift_flat_values(cx, MAX_FLAT_RESULTS, CoreValueIter(flat_results), ft.result_type()) + max_flat_results = MAX_FLAT_GC_RESULTS if opts.gc else MAX_FLAT_RESULTS + result = lift_flat_values(cx, max_flat_results, CoreValueIter(flat_results), ft.result_type(), is_result = True) task.return_(result) if opts.post_return is not None: assert(cx.inst.may_leave) @@ -2120,8 +2695,12 @@ def thread_func(): task.exit_implicit_thread() return - [packed] = call_and_trap_on_throw(callee, flat_args) - code,si = unpack_callback_result(packed) + if opts.gc: + [code, sr] = call_and_trap_on_throw(callee, flat_args) + code,si = unpack_gc_callback_result(inst, code, sr) + else: + [packed] = call_and_trap_on_throw(callee, flat_args) + code,si = unpack_callback_result(packed) while code != CallbackCode.EXIT: if thread.task.deliver_pending_cancel(): event = (EventCode.TASK_CANCELLED, 0, 0) @@ -2145,9 +2724,13 @@ def thread_func(): assert(inst.exclusive_thread is None) thread.cancellable = False inst.exclusive_thread = task.implicit_thread - event_code, p1, p2 = event - [packed] = call_and_trap_on_throw(opts.callback, [event_code, p1, p2]) - code,si = unpack_callback_result(packed) + if opts.gc: + [code, sr] = call_and_trap_on_throw(opts.callback, unpack_gc_event(inst, event)) + code,si = unpack_gc_callback_result(inst, code, sr) + else: + event_code, p1, p2 = event + [packed] = call_and_trap_on_throw(opts.callback, [event_code, p1, p2]) + code,si = unpack_callback_result(packed) task.exit_implicit_thread() return @@ -2175,6 +2758,14 @@ def unpack_callback_result(packed): waitable_set_index = packed >> 4 return (CallbackCode(code), waitable_set_index) +def unpack_gc_callback_result(inst, code, sr): + trap_if(code > CallbackCode.MAX) + if code == CallbackCode.WAIT and sr is not None: + waitable_set_index = unbox_handle(inst, sr) + else: + waitable_set_index = 0 + return (CallbackCode(code), waitable_set_index) + def call_and_trap_on_throw(callee, args): try: return callee(args) @@ -2195,7 +2786,7 @@ def canon_lower(callee, ft, opts, flat_args: list[CoreValType]) -> list[CoreValT if not opts.async_: max_flat_params = MAX_FLAT_PARAMS - max_flat_results = MAX_FLAT_RESULTS + max_flat_results = MAX_FLAT_GC_RESULTS if opts.gc else MAX_FLAT_RESULTS else: max_flat_params = MAX_FLAT_ASYNC_PARAMS max_flat_results = 0 @@ -2219,7 +2810,7 @@ def on_resolve(result): subtask.resolve(Subtask.State.CANCELLED_BEFORE_RETURNED, []) else: assert(subtask.state == Subtask.State.STARTED) - flat_results = lower_flat_values(cx, max_flat_results, result, ft.result_type(), flat_args) + flat_results = lower_flat_values(cx, max_flat_results, result, ft.result_type(), flat_args, is_result = True) subtask.resolve(Subtask.State.RETURNED, flat_results) subtask.on_cancel = callee(on_start, on_resolve) @@ -2235,7 +2826,10 @@ def on_resolve(result): if subtask.resolved(): subtask.deliver_resolve() assert(subtask.flat_results == []) - return [Subtask.State.RETURNED] + if opts.gc: + return [Subtask.State.RETURNED, None] + else: + return [Subtask.State.RETURNED] else: subtaski = thread.task.inst.handles.add(subtask) def on_progress(): @@ -2247,7 +2841,10 @@ def subtask_event(): maybe_on_progress = on_progress assert(0 < subtaski <= Table.MAX_LENGTH < 2**28) assert(0 <= subtask.state < 2**4) - return [subtask.state | (subtaski << 4)] + if opts.gc: + return [subtask.state | (subtaski << 4), HandleRef(thread.task.inst, subtaski)] + else: + return [subtask.state | (subtaski << 4)] ### `canon resource.new` @@ -2291,6 +2888,20 @@ def canon_resource_rep(rt, i): trap_if(h.rt is not rt) return [h.rep_val] +### 🛸 `canon gc.resource.{new,drop,rep}` + +def canon_gc_resource_new(rt, rep_val): + [i] = canon_resource_new(rt, rep_val) + return [HandleRef(current_instance(), i)] + +def canon_gc_resource_drop(rt, r): + i = unbox_handle(current_instance(), r) + return canon_resource_drop(rt, i) + +def canon_gc_resource_rep(rt, r): + i = unbox_handle(current_instance(), r) + return canon_resource_rep(rt, i) + ### 🔀 `canon context.get` def canon_context_get(t, i): @@ -2336,7 +2947,7 @@ def canon_task_return(result_type, opts: LiftOptions, flat_args): trap_if(result_type != task.ft.result) trap_if(not LiftOptions.equal(opts, task.opts)) cx = LiftLowerContext('lift', opts, task.inst, task) - result = lift_flat_values(cx, MAX_FLAT_PARAMS, CoreValueIter(flat_args), task.ft.result_type()) + result = lift_flat_values(cx, MAX_FLAT_PARAMS, CoreValueIter(flat_args), task.ft.result_type(), is_result = True) task.return_(result) return [] @@ -2448,6 +3059,78 @@ def canon_subtask_drop(i): s.drop() return [] +### 🛸 `canon gc.{waitable-set,waitable,subtask}.*` + +def canon_gc_waitable_set_new(): + [si] = canon_waitable_set_new() + return [HandleRef(current_instance(), si)] + +def canon_gc_waitable_set_wait(r): + inst = current_instance() + si = unbox_handle(inst, r) + trap_if(not inst.may_leave) + wset = inst.handles.get(si) + trap_if(not isinstance(wset, WaitableSet)) + event = wset.wait() + return unpack_gc_event(inst, event) + +def canon_gc_waitable_set_poll(r): + inst = current_instance() + si = unbox_handle(inst, r) + trap_if(not inst.may_leave) + wset = inst.handles.get(si) + trap_if(not isinstance(wset, WaitableSet)) + event = wset.poll() + return unpack_gc_event(inst, event) + +def unpack_gc_event(inst, e: EventTuple): + event, p1, p2 = e + if p1 == 0: + w = None + else: + w = inst.handles.get_handle_ref(p1) + if w is None: + w = HandleRef(inst, p1) + return [event, p2, w] + +def canon_gc_waitable_set_drop(r): + i = unbox_handle(current_instance(), r) + return canon_waitable_set_drop(i) + +def canon_gc_waitable_join(wr, sr): + wi = unbox_handle(current_instance(), wr) + if sr is None: + si = 0 + else: + si = unbox_handle(current_instance(), sr) + return canon_waitable_join(wi, si) + +def canon_gc_subtask_cancel(async_, r): + i = unbox_handle(current_instance(), r) + return canon_subtask_cancel(async_, i) + +def canon_gc_subtask_drop(r): + i = unbox_handle(current_instance(), r) + return canon_subtask_drop(i) + +### 🛸 `canon gc.handle-ref.{index,new,get}` + +def canon_gc_handle_ref_index(r): + inst = current_instance() + trap_if(not inst.may_leave) + i = unbox_handle(inst, r) + return [i] + +def canon_gc_handle_ref_new(i): + inst = current_instance() + trap_if(not inst.may_leave) + return [HandleRef(inst, i)] + +def canon_gc_handle_ref_get(i): + inst = current_instance() + trap_if(not inst.may_leave) + return [inst.handles.get_handle_ref(i)] + ### 🔀 `canon {stream,future}.new` def canon_stream_new(stream_t): @@ -2468,19 +3151,52 @@ def canon_future_new(future_t): ### 🔀 `canon stream.{read,write}` -def canon_stream_read(stream_t, opts, i, ptr, length): - return copy(ReadableStreamEnd, WritableGuestBuffer, 'lower', stream_t, opts, i, ptr, length) - -def canon_stream_write(stream_t, opts, i, ptr, length): - return copy(WritableStreamEnd, ReadableGuestBuffer, 'lift', stream_t, opts, i, ptr, length) +def canon_stream_read(stream_t, opts, i, *args): + if opts.gc: + ii = unbox_handle(current_instance(), i) + gc_args = gc_stream_buffer_args(stream_t, args) + return copy(ReadableStreamEnd, WritableGcBuffer, 'lower', stream_t, opts, ii, *gc_args) + else: + [ptr, length] = args + return copy(ReadableStreamEnd, WritableGuestBuffer, 'lower', stream_t, opts, i, ptr, length) + +def canon_stream_write(stream_t, opts, i, *args): + if opts.gc: + ii = unbox_handle(current_instance(), i) + gc_args = gc_stream_buffer_args(stream_t, args) + return copy(WritableStreamEnd, ReadableGcBuffer, 'lift', stream_t, opts, ii, *gc_args) + else: + [ptr, length] = args + return copy(WritableStreamEnd, ReadableGuestBuffer, 'lift', stream_t, opts, i, ptr, length) -def canon_future_read(future_t, opts, i, ptr): - return copy(ReadableFutureEnd, WritableGuestBuffer, 'lower', future_t, opts, i, ptr, 1) +def gc_stream_buffer_args(stream_t, args): + if stream_t.t is None: + [length] = args + return (None, 0, length) + else: + [arr, offset, length] = args + return (arr.elems, offset, length) + +def canon_future_read(future_t, opts, i, ptr_or_cell = None): + if opts.gc: + ii = unbox_handle(current_instance(), i) + if future_t.t is None: + assert(ptr_or_cell is None) + elems = None + else: + elems = ptr_or_cell.fields + return copy(ReadableFutureEnd, WritableGcBuffer, 'lower', future_t, opts, ii, elems, 0, 1) + else: + return copy(ReadableFutureEnd, WritableGuestBuffer, 'lower', future_t, opts, i, ptr_or_cell, 1) -def canon_future_write(future_t, opts, i, ptr): - return copy(WritableFutureEnd, ReadableGuestBuffer, 'lift', future_t, opts, i, ptr, 1) +def canon_future_write(future_t, opts, i, ptr_or_v = None): + if opts.gc: + ii = unbox_handle(current_instance(), i) + return copy(WritableFutureEnd, ReadableGcValueBuffer, 'lift', future_t, opts, ii, ptr_or_v) + else: + return copy(WritableFutureEnd, ReadableGuestBuffer, 'lift', future_t, opts, i, ptr_or_v, 1) -def copy(EndT, BufferT, direction, stream_or_future_t, opts, i, ptr, length): +def copy(EndT, BufferT, direction, stream_or_future_t, opts, i, *buffer_args): thread = current_thread() trap_if(not thread.task.inst.may_leave) end = thread.task.inst.handles.get(i) @@ -2489,7 +3205,7 @@ def copy(EndT, BufferT, direction, stream_or_future_t, opts, i, ptr, length): trap_if(end.state != End.State.IDLE) trap_if(end.in_waitable_set() and not opts.async_) cx = LiftLowerContext(direction, opts, thread.task.inst, borrow_scope = None) - buffer = BufferT(end.t, cx, ptr, length) + buffer = BufferT(end.t, cx, *buffer_args) end.copy(buffer) if not end.has_pending_event(): if not opts.async_: @@ -2583,6 +3299,63 @@ def forward(ReadableEndT, WritableEndT, stream_or_future_t, ri, wi): End.forward(readable_end, writable_end) return [] +### 🛸 `canon gc.{stream,future}.*` + +def canon_gc_stream_new(stream_t): + [packed] = canon_stream_new(stream_t) + return box_new_ends(current_instance(), packed) + +def canon_gc_future_new(future_t): + [packed] = canon_future_new(future_t) + return box_new_ends(current_instance(), packed) + +def box_new_ends(inst, packed): + readable_index = packed & 0xffff_ffff + writable_index = packed >> 32 + return [HandleRef(inst, readable_index), HandleRef(inst, writable_index)] + +def canon_gc_stream_cancel_read(stream_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_stream_cancel_read(stream_t, async_, i) + +def canon_gc_stream_cancel_write(stream_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_stream_cancel_write(stream_t, async_, i) + +def canon_gc_future_cancel_read(future_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_future_cancel_read(future_t, async_, i) + +def canon_gc_future_cancel_write(future_t, async_, r): + i = unbox_handle(current_instance(), r) + return canon_future_cancel_write(future_t, async_, i) + +def canon_gc_stream_drop_readable(stream_t, r): + i = unbox_handle(current_instance(), r) + return canon_stream_drop_readable(stream_t, i) + +def canon_gc_stream_drop_writable(stream_t, r): + i = unbox_handle(current_instance(), r) + return canon_stream_drop_writable(stream_t, i) + +def canon_gc_future_drop_readable(future_t, r): + i = unbox_handle(current_instance(), r) + return canon_future_drop_readable(future_t, i) + +def canon_gc_future_drop_writable(future_t, r): + i = unbox_handle(current_instance(), r) + return canon_future_drop_writable(future_t, i) + +def canon_gc_stream_forward(stream_t, rr, wr): + ri = unbox_handle(current_instance(), rr) + wi = unbox_handle(current_instance(), wr) + return canon_stream_forward(stream_t, ri, wi) + +def canon_gc_future_forward(future_t, rr, wr): + ri = unbox_handle(current_instance(), rr) + wi = unbox_handle(current_instance(), wr) + return canon_future_forward(future_t, ri, wi) + ### 🧵 `canon thread.index` def canon_thread_index(): @@ -2689,30 +3462,43 @@ def canon_thread_yield_then_promote(i): class ErrorContext: debug_message: String -def canon_error_context_new(opts, ptr, tagged_code_units): +def canon_error_context_new(opts, ptr_or_arr, tagged_code_units = None): inst = current_instance() trap_if(not inst.may_leave) if DETERMINISTIC_PROFILE or random.randint(0,1): - s = String(('', 'utf8', 0)) + s = String(('', StringHint.UTF8, 0)) else: cx = LiftLowerContext('lift', opts, inst) - s = load_string_from_range(cx, ptr, tagged_code_units) + if opts.gc: + assert(tagged_code_units is None) + s = lift_gc_string(cx, ptr_or_arr) + else: + s = load_string_from_range(cx, ptr_or_arr, tagged_code_units) s = host_defined_transformation(s) i = inst.handles.add(ErrorContext(s)) - return [i] + if opts.gc: + return [HandleRef(inst, i)] + else: + return [i] ### 📝 `canon error-context.debug-message` -def canon_error_context_debug_message(opts, i, ptr): +def canon_error_context_debug_message(opts, i, ptr = None): inst = current_instance() trap_if(not inst.may_leave) + if opts.gc: + i = unbox_handle(inst, i) errctx = inst.handles.get(i) trap_if(not isinstance(errctx, ErrorContext)) cx = LiftLowerContext('lower', opts, inst) - trap_if(ptr != align_to(ptr, alignment(cx, StringType()))) - trap_if(ptr + elem_size(cx, StringType()) > len(cx.opts.memory)) - store(cx, errctx.debug_message, StringType(), ptr) - return [] + if opts.gc: + assert(ptr is None) + return [lower_gc_string(cx, errctx.debug_message)] + else: + trap_if(ptr != align_to(ptr, alignment(cx, StringType()))) + trap_if(ptr + elem_size(cx, StringType()) > len(cx.opts.memory)) + store(cx, errctx.debug_message, StringType(), ptr) + return [] ### 📝 `canon error-context.drop` @@ -2722,3 +3508,33 @@ def canon_error_context_drop(i): errctx = inst.handles.remove(i) trap_if(not isinstance(errctx, ErrorContext)) return [] + +### 🛸 `canon gc.error-context.*` + +def canon_gc_error_context_drop(r): + i = unbox_handle(current_instance(), r) + return canon_error_context_drop(i) + +### 🛸 `canon array.new-{array,memory,table}` + +def canon_array_new_array(dst: CoreDefType, src: CoreDefType, a, i, n): + trap_if(a is None) + trap_if(i + n > array_len(a)) + return [array_new_fixed(dst, [array_get(a, j) for j in range(i, i + n)])] + +def canon_array_new_memory(dst: CoreDefType, mem: MemInst, ptr, n): + t = dst.comptype().elem.t + nbytes = storage_byte_size(t) + trap_if(ptr + n * nbytes > len(mem)) + vs = [] + for j in range(n): + bits = int.from_bytes(mem[ptr + j*nbytes : ptr + (j+1)*nbytes], 'little') + match t: + case 'f32' : vs.append(core_f32_reinterpret_i32(bits)) + case 'f64' : vs.append(core_f64_reinterpret_i64(bits)) + case 'i8' | 'i16' | 'i32' | 'i64' : vs.append(bits) + return [array_new_fixed(dst, vs)] + +def canon_array_new_table(dst: CoreDefType, tbl: list[any], i, n): + trap_if(i + n > len(tbl)) + return [array_new_fixed(dst, tbl[i : i+n])] diff --git a/design/mvp/canonical-abi/run_tests.py b/design/mvp/canonical-abi/run_tests.py index 73561b290..ddea1552a 100644 --- a/design/mvp/canonical-abi/run_tests.py +++ b/design/mvp/canonical-abi/run_tests.py @@ -72,7 +72,7 @@ def on_cancel(): return func_inst def mk_str(s): - return (s, 'utf8', len(s.encode('utf-8'))) + return (s, StringHint.UTF8, len(s.encode('utf-8'))) def mk_tup(*a): def mk_tup_rec(x): @@ -118,13 +118,15 @@ def test(t, vals_to_lift, v, cx = mk_cx(), dst_encoding = None, lower_t = None, - lower_v = None): + lower_v = None, + dst_addr_type = None, + lowered_vals = None): def test_name(): return "test({},{},{}):".format(t, vals_to_lift, v) error = None def thread_func(): - nonlocal error, cx, dst_encoding, lower_t, lower_v + nonlocal error, cx, dst_encoding, lower_t, lower_v, dst_addr_type try: vi = CoreValueIter(vals_to_lift) @@ -148,10 +150,14 @@ def lift_expecting_trap(): heap = Heap(5*len(cx.opts.memory)) if dst_encoding is None: dst_encoding = cx.opts.string_encoding - cx = mk_cx(MemInst(heap.memory, cx.opts.memory.ptr_type()), dst_encoding, heap.realloc) - lowered_vals = lower_flat(cx, v, lower_t) - - vi = CoreValueIter(lowered_vals) + if dst_addr_type is None: + dst_addr_type = cx.opts.memory.ptr_type() + cx = mk_cx(MemInst(heap.memory, dst_addr_type), dst_encoding, heap.realloc) + got_lowered_vals = lower_flat(cx, v, lower_t) + if lowered_vals is not None and got_lowered_vals != lowered_vals: + fail("{} lower_flat() expected {} but got {}".format(test_name(), lowered_vals, got_lowered_vals)) + + vi = CoreValueIter(got_lowered_vals) got = lift_flat(cx, vi, lower_t) if not equal_modulo_string_encoding(got, lower_v): fail("{} re-lift expected {} but got {}".format(test_name(), lower_v, got)) @@ -266,44 +272,62 @@ def test_nan64(inbits, outbits): test_nan64(0x7ff0000000000000, 0x7ff0000000000000) test_nan64(0x3ff0000000000000, 0x3ff0000000000000) -def test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, addr_type='i32'): +def test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, hint, + src_addr_type='i32', dst_addr_type='i32', lowered_vals=None): heap = Heap(len(encoded)) heap.memory[:] = encoded[:] - cx = mk_cx(MemInst(heap.memory, addr_type), src_encoding) - v = (s, src_encoding, tagged_code_units) - test(StringType(), [0, tagged_code_units], v, cx, dst_encoding) - -def test_string(src_encoding, dst_encoding, s, addr_type='i32'): + cx = mk_cx(MemInst(heap.memory, src_addr_type), src_encoding) + tag = 1 << (ptr_size(src_addr_type) * 8 - 1) + code_units = tagged_code_units & ~tag + v = (s, hint, code_units) + test(StringType(), [0, tagged_code_units], v, cx, dst_encoding, + dst_addr_type = dst_addr_type, lowered_vals = lowered_vals) + +def test_string(src_encoding, dst_encoding, s, src_addr_type='i32', dst_addr_type='i32'): + def run(encoded, tagged_code_units, hint): + test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, hint, + src_addr_type, dst_addr_type) if src_encoding == 'utf8': encoded = s.encode('utf-8') - tagged_code_units = len(encoded) - test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, addr_type) + run(encoded, len(encoded), StringHint.UTF8) elif src_encoding == 'utf16': encoded = s.encode('utf-16-le') - tagged_code_units = int(len(encoded) / 2) - test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, addr_type) + run(encoded, int(len(encoded) / 2), StringHint.UTF16) elif src_encoding == 'latin1+utf16': try: encoded = s.encode('latin-1') - tagged_code_units = len(encoded) - test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, addr_type) + run(encoded, len(encoded), StringHint.DYNAMIC_LATIN1) except UnicodeEncodeError: pass encoded = s.encode('utf-16-le') - tagged_code_units = int(len(encoded) / 2) | (1 << (ptr_size(addr_type) * 8 - 1)) - test_string_internal(src_encoding, dst_encoding, s, encoded, tagged_code_units, addr_type) + tag = 1 << (ptr_size(src_addr_type) * 8 - 1) + run(encoded, int(len(encoded) / 2) | tag, StringHint.DYNAMIC_UTF16) encodings = ['utf8', 'utf16', 'latin1+utf16'] fun_strings = ['', 'a', 'hi', '\x00', 'a\x00b', '\x80', '\x80b', 'ab\xefc', - '\u01ffy', 'xy\u01ff', 'a\ud7ffb', 'a\u02ff\u03ff\u04ffbc', - '\uf123', '\uf123\uf123abc', 'abcdef\uf123'] - -for addr_type in ['i32', 'i64']: - for src_encoding in encodings: - for dst_encoding in encodings: - for s in fun_strings: - test_string(src_encoding, dst_encoding, s, addr_type) + 'ǿy', 'xyǿ', 'a퟿b', 'a˿Ͽӿbc', + '', 'abc', 'abcdef'] + +for src_addr_type in ['i32', 'i64']: + for dst_addr_type in ['i32', 'i64']: + for src_encoding in encodings: + for dst_encoding in encodings: + for s in fun_strings: + test_string(src_encoding, dst_encoding, s, src_addr_type, dst_addr_type) + +# A `latin1+utf16` string's UTF-16 tag is read from the source memory's high +# pointer bit and written to the destination memory's. +for src_addr_type, dst_addr_type in [('i32', 'i64'), ('i64', 'i32')]: + src_tag = 1 << (ptr_size(src_addr_type) * 8 - 1) + dst_tag = 1 << (ptr_size(dst_addr_type) * 8 - 1) + def t(s, dst_encoding, lowered_vals): + test_string_internal('latin1+utf16', dst_encoding, s, s.encode('utf-16-le'), len(s) | src_tag, + StringHint.DYNAMIC_UTF16, src_addr_type, dst_addr_type, lowered_vals) + t('a', 'latin1+utf16', [0, 2 | dst_tag]) + t('ab', 'latin1+utf16', [4, 2]) + t('a', 'utf16', [0, 2]) + t('a', 'utf8', [2, 4]) def test_heap(t, expect, args, byte_array, addr_type='i32'): heap = Heap(byte_array) @@ -3175,6 +3199,931 @@ def on_resolve(v): assert(result == 42) assert(other_result == 43) +def mk_gc_opts(encoding = 'utf8', post_return = None): + opts = mk_opts(memory = None, encoding = encoding, post_return = post_return) + opts.gc = True + return opts + +def mk_gc_cx(encoding = 'utf8', direction = 'lift', inst = None): + if inst is None: + inst = ComponentInstance(Store()) + return LiftLowerContext(direction, mk_gc_opts(encoding), inst) + +def run_in_task(inst, f): + error = None + def thread_func(): + nonlocal error + try: + f() + except BaseException as e: + error = e + task = Task(FuncType([],[]), CanonicalOptions(), inst, lambda: [], lambda _: ()) + Thread(task, thread_func).resume() + if error is not None: + raise error + +def gc_struct_t(*field_types): + return gc_final_type(CoreStructType(tuple(CoreFieldType(t) for t in field_types))) + +def gc_array_t(elem_type): + return gc_final_type(CoreArrayType(CoreFieldType(elem_type))) + +def test_gc_flatten(): + def flat(ft, direction = 'lift', encoding = 'utf8', inst = None): + return flatten_functype(mk_gc_cx(encoding, direction, inst), ft) + + # Small scalars are i32 when flat but packed when in GC heap storage. + got = flat(FuncType([U8Type(), S16Type(), BoolType()], [])) + assert(got == CoreFuncType(['i32','i32','i32'], [])) + got = flat(FuncType([ListType(TupleType([BoolType(), S8Type(), U16Type()]))], [])) + tup = gc_struct_t('i8', 'i8', 'i16') + assert(got == CoreFuncType([CoreRefType(gc_array_t(CoreRefType(tup)))], [])) + got = flat(FuncType([U32Type(), S64Type(), F32Type()], [F64Type()])) + assert(got == CoreFuncType(['i32','i64','f32'], ['f64'])) + + # Strings. + utf8 = gc_array_t('i8') + utf16 = gc_array_t('i16') + assert(GC_UTF8_ARRAY == utf8 and GC_LATIN1_ARRAY == utf8 and GC_UTF16_ARRAY == utf16) + ft = FuncType([StringType()], [StringType()]) + assert(flat(ft, encoding = 'utf8') == CoreFuncType([CoreRefType(utf8)], [CoreRefType(utf8)])) + assert(flat(ft, encoding = 'utf16') == CoreFuncType([CoreRefType(utf16)], [CoreRefType(utf16)])) + assert(flat(ft, encoding = 'latin1+utf16') == CoreFuncType([CoreRefType('array')], [CoreRefType('array')])) + + # Records and tuples are flattened when flat, but are structs in storage. + point = TupleType([S32Type(), S32Type()]) + line = RecordType([FieldType('a', point), FieldType('b', point)]) + assert(flat(FuncType([line], [])) == CoreFuncType(['i32','i32','i32','i32'], [])) + point_t = gc_struct_t('i32', 'i32') + line_t = gc_struct_t(CoreRefType(point_t), CoreRefType(point_t)) + lines_t = gc_array_t(CoreRefType(line_t)) + assert(flat(FuncType([ListType(line)], [])) == CoreFuncType([CoreRefType(lines_t)], [])) + + # Variants without payloads are integers. + color = EnumType(['red', 'green', 'blue']) + got = flat(FuncType([color, ListType(color)], [])) + assert(got == CoreFuncType(['i32', CoreRefType(gc_array_t('i8'))], [])) + + # Variants with payloads are a rec group of a base struct and a final + # subtype for each case. + animal = VariantType([CaseType('cat', U32Type()), CaseType('dog', U16Type()), CaseType('rabbit', None)]) + disc = CoreFieldType('i8') + rec = CoreRecType(( + CoreSubType(False, (), CoreStructType((disc,))), + CoreSubType(True, (CoreRecIdx(0),), CoreStructType((disc, CoreFieldType('i32')))), + CoreSubType(True, (CoreRecIdx(0),), CoreStructType((disc, CoreFieldType('i16')))), + CoreSubType(True, (CoreRecIdx(0),), CoreStructType((disc,))))) + assert(flat(FuncType([animal], [])) == CoreFuncType([CoreRefType(CoreDefType(rec, 0))], [])) + for i in range(1, 4): + assert(CoreDefType(rec, i).matches(CoreDefType(rec, 0))) + assert(not CoreDefType(rec, 0).matches(CoreDefType(rec, i))) + + # Options and results desugar to variants. + tri_bool = OptionType(BoolType()) + rec = CoreRecType(( + CoreSubType(False, (), CoreStructType((disc,))), + CoreSubType(True, (CoreRecIdx(0),), CoreStructType((disc,))), + CoreSubType(True, (CoreRecIdx(0),), CoreStructType((disc, CoreFieldType('i8')))))) + assert(flat(FuncType([tri_bool], [])) == CoreFuncType([CoreRefType(CoreDefType(rec, 0))], [])) + + # Flags are i32 when flat but the smallest packed integer in storage. + flags = FlagsType([f'f{i}' for i in range(9)]) + got = flat(FuncType([flags, ListType(flags)], [])) + assert(got == CoreFuncType(['i32', CoreRefType(gc_array_t('i16'))], [])) + + # Maps desugar to lists of tuples. + got = flat(FuncType([MapType(U32Type(), U8Type())], [])) + assert(got == CoreFuncType([CoreRefType(gc_array_t(CoreRefType(gc_struct_t('i32', 'i8'))))], [])) + + # Fixed-length lists are lowered the same as variable-length lists. + got = flat(FuncType([ListType(U8Type(), 3)], [])) + assert(got == CoreFuncType([CoreRefType(gc_array_t('i8'))], [])) + + # Handles, streams and futures are externrefs. + store = Store() + impl_inst = ComponentInstance(store) + other_inst = ComponentInstance(store) + rt = ResourceType(impl_inst, 'i64') + ft = FuncType([OwnType(rt), BorrowType(rt), FutureType(BoolType()), StreamType(U32Type()), ErrorContextType()], []) + assert(flat(ft, 'lift', inst = other_inst) == CoreFuncType(5 * [EXTERNREF], [])) + assert(flat(ft, 'lower', inst = other_inst) == CoreFuncType(5 * [EXTERNREF], [])) + assert(flat(ft, 'lower', inst = impl_inst) == CoreFuncType(5 * [EXTERNREF], [])) + # ... except borrows lowered into the resource's defining component. + assert(flat(ft, 'lift', inst = impl_inst) == CoreFuncType([EXTERNREF, 'i64'] + 3 * [EXTERNREF], [])) + + # Too many flat params are passed as a single struct of all the params. + ft = FuncType([U8Type() for _ in range(17)], []) + assert(flat(ft) == CoreFuncType([CoreRefType(gc_struct_t(*(17 * ['i8'])))], [])) + ft = FuncType([U8Type() for _ in range(16)], []) + assert(flat(ft) == CoreFuncType(16 * ['i32'], [])) + + # Too many flat results return the result's storage type (in both directions). + big = TupleType([U8Type() for _ in range(17)]) + ft = FuncType([], [big]) + for direction in ['lift', 'lower']: + assert(flat(ft, direction) == CoreFuncType([], [CoreRefType(gc_struct_t(*(17 * ['i8'])))])) + ft = FuncType([], [TupleType([U8Type() for _ in range(16)])]) + assert(flat(ft) == CoreFuncType([], 16 * ['i32'])) + + # Async lifts and lowers. + def async_flat(ft, direction, callback = None): + cx = mk_gc_cx(direction = direction) + cx.opts.async_ = True + cx.opts.callback = callback + return flatten_functype(cx, ft) + nullable_externref = CoreRefType('extern', nullable = True) + ft = FuncType([U8Type() for _ in range(17)], [StringType()], async_ = True) + params_t = CoreRefType(gc_struct_t(*(17 * ['i8']))) + assert(async_flat(ft, 'lift', callback = lambda _: None) == CoreFuncType([params_t], ['i32', nullable_externref])) + assert(async_flat(ft, 'lift') == CoreFuncType([params_t], [])) + results_t = CoreRefType(gc_final_type(CoreStructType((CoreFieldType(CoreRefType(GC_UTF8_ARRAY, nullable = True), mutable = True),)))) + assert(async_flat(ft, 'lower') == CoreFuncType([params_t, results_t], ['i32', nullable_externref])) + ft = FuncType([U8Type() for _ in range(4)], [], async_ = True) + assert(async_flat(ft, 'lower') == CoreFuncType(4 * ['i32'], ['i32', nullable_externref])) + ft = FuncType([U8Type() for _ in range(5)], [], async_ = True) + assert(async_flat(ft, 'lower') == CoreFuncType([CoreRefType(gc_struct_t(*(5 * ['i8'])))], ['i32', nullable_externref])) + +def test_gc_values(): + big_tuple_t = TupleType([U32Type() for _ in range(16)] + [StringType()]) + big_tuple_v = mk_tup(*range(16), mk_str("big")) + animal = VariantType([CaseType('cat', U32Type()), CaseType('dog', S16Type()), CaseType('rabbit', None)]) + cases = [ + (BoolType(), True), + (S8Type(), -1), + (U8Type(), 255), + (S16Type(), -2), + (U16Type(), 65535), + (S32Type(), -3), + (U32Type(), 2**32-1), + (S64Type(), -4), + (U64Type(), 2**64-1), + (F32Type(), 1.5), + (F64Type(), -2.5), + (CharType(), '\U0001F6F8'), + (StringType(), mk_str("hello")), + (StringType(), mk_str("héllo")), + (StringType(), mk_str("hēllo \U0001F6F8")), + (ListType(S8Type()), [-1, 0, 1, -128, 127]), + (ListType(S16Type()), [-1, 0, 1, -32768, 32767]), + (ListType(BoolType()), [True, False, True]), + (ListType(CharType()), ['a', 'é', '\U0001F6F8']), + (ListType(F32Type()), [1.5, -0.5]), + (ListType(U8Type(), 3), [1, 2, 3]), + (ListType(StringType()), [mk_str("a"), mk_str("ē"), mk_str("c")]), + (ListType(ListType(StringType())), [[mk_str("one"), mk_str("two")], [mk_str("three")]]), + (TupleType([U16Type(), S8Type()]), mk_tup(3, -4)), + (ListType(TupleType([U16Type(), S8Type()])), [mk_tup(3, -4), mk_tup(5, 6)]), + (ListType(TupleType([S32Type(), S64Type(), U64Type(), F64Type(), CharType()])), + [mk_tup(-2**31, -2**63, 2**64-1, -0.5, '\u00e9'), mk_tup(7, 8, 9, 1.0, 'a')]), + (EnumType(['a', 'b', 'c']), {'c': None}), + (ListType(EnumType(['a', 'b', 'c'])), [{'c': None}, {'a': None}]), + (FlagsType(['a', 'b']), {'a': False, 'b': True}), + (ListType(FlagsType([str(i) for i in range(9)])), [{str(i): i % 2 == 0 for i in range(9)}]), + (animal, {'cat': 42}), + (animal, {'dog': -42}), + (animal, {'rabbit': None}), + (ListType(animal), [{'cat': 1}, {'dog': -1}, {'rabbit': None}]), + (OptionType(StringType()), {'some': mk_str("x")}), + (OptionType(StringType()), {'none': None}), + (ResultType(U32Type(), BoolType()), {'error': True}), + (ListType(OptionType(TupleType([StringType(), U16Type()]))), [{'some': mk_tup(mk_str("answer"), 42)}, {'none': None}]), + (MapType(U32Type(), StringType()), [mk_tup(1, mk_str("one")), mk_tup(2, mk_str("two"))]), + (big_tuple_t, big_tuple_v), + (VariantType([CaseType('x', big_tuple_t)]), {'x': big_tuple_v}), + ] + + # Lift each value as both a parameter and a result of an identity function + # lifted with the GC ABI in each string encoding. + for encoding in ['utf8', 'utf16', 'latin1+utf16']: + for t, v in cases: + store = Store() + ft = FuncType([t], [t]) + def callee(args): + if len(flatten_type(mk_gc_cx(encoding), t)) > MAX_FLAT_PARAMS: + [params] = args + return [struct_get(params, 0)] + return args + callee_inst = ComponentInstance(store) + got = None + def on_start(): + return [v] + def on_resolve(result): + nonlocal got + [got] = result + lift_and_run(mk_gc_opts(encoding), callee_inst, ft, callee, on_start, on_resolve) + if not equal_modulo_string_encoding(got, v): + fail("test_gc_values({},{},{}) got {}".format(encoding, t, v, got)) + + # Then call the same GC-lifted function from a component that lowers it + # with the GC ABI using a (possibly) different string encoding. + for caller_encoding in ['utf8', 'utf16', 'latin1+utf16']: + store = Store() + callee_inst = ComponentInstance(store) + func = store.lift(callee, ft, mk_gc_opts(encoding), callee_inst) + caller_inst = ComponentInstance(store) + caller_opts = mk_gc_opts(caller_encoding) + def core_caller(args): + cx = LiftLowerContext('lower', caller_opts, caller_inst) + flat_args = lower_flat_values(cx, MAX_FLAT_PARAMS, [v], [t]) + flat_results = store.lower(func, ft, caller_opts, caller_inst)(flat_args) + assert(types_match_values(flatten_functype(cx, ft).results, flat_results)) + [got] = lift_flat_values(cx, MAX_FLAT_GC_RESULTS, CoreValueIter(flat_results), [t], is_result = True) + if not equal_modulo_string_encoding(got, v): + fail("test_gc_values({},{},{},{}) got {}".format(encoding, caller_encoding, t, v, got)) + return [] + lift_and_run(mk_opts(), caller_inst, FuncType([], []), core_caller, lambda: [], lambda _: ()) + +def test_gc_strings(): + def lift(encoding, a): + cx = mk_gc_cx(encoding) + got = None + def f(): + nonlocal got + got = lift_flat(cx, CoreValueIter([a]), StringType()) + run_in_task(cx.inst, f) + return got + + def lower(encoding, s): + cx = mk_gc_cx(encoding, 'lower') + return lower_flat(cx, mk_str(s), StringType())[0] + + a = lower('utf8', 'hé') + assert(a.t == GC_UTF8_ARRAY and a.elems == [0x68, 0xc3, 0xa9]) + a = lower('utf16', '\U0001F6F8') + assert(a.t == GC_UTF16_ARRAY and a.elems == [0xd83d, 0xdef8]) + a = lower('latin1+utf16', 'hé') + assert(a.t == GC_LATIN1_ARRAY and a.elems == [0x68, 0xe9]) + a = lower('latin1+utf16', 'hē') + assert(a.t == GC_UTF16_ARRAY and a.elems == [0x68, 0x113]) + + assert(lift('utf8', array_new_fixed(GC_UTF8_ARRAY, [0x68, 0xc3, 0xa9])) == ('hé', StringHint.UTF8, 3)) + assert(lift('utf16', array_new_fixed(GC_UTF16_ARRAY, [0xd83d, 0xdef8])) == ('\U0001F6F8', StringHint.UTF16, 2)) + assert(lift('latin1+utf16', array_new_fixed(GC_LATIN1_ARRAY, [0x68, 0xe9])) == ('hé', StringHint.DYNAMIC_LATIN1, 2)) + assert(lift('latin1+utf16', array_new_fixed(GC_UTF16_ARRAY, [0x68, 0x113])) == ('hē', StringHint.DYNAMIC_UTF16, 2)) + + # Invalid encodings trap. + try: + lift('utf8', array_new_fixed(GC_UTF8_ARRAY, [0xff])) + fail("expected trap") + except Trap: + pass + try: + lift('utf16', array_new_fixed(GC_UTF16_ARRAY, [0xd83d])) + fail("expected trap") + except Trap: + pass + # latin1+utf16 strings must be one of the two array types. + try: + lift('latin1+utf16', array_new_fixed(gc_array_t('i32'), [0x68])) + fail("expected trap") + except Trap: + pass + + # GC-lifted latin1+utf16 strings can be stored into linear memory using either + # address type. + for addr_type in ['i32', 'i64']: + for s in ['hé', 'hē']: + v = lift('latin1+utf16', lower('latin1+utf16', s)) + heap = Heap(100) + cx = mk_cx(MemInst(heap.memory, addr_type), 'latin1+utf16', heap.realloc) + def f(): + flat = lower_flat(cx, v, StringType()) + got = lift_flat(cx, CoreValueIter(flat), StringType()) + assert(got[0] == s) + run_in_task(cx.inst, f) + +def test_gc_lift_traps(): + def expect_trap(t, v, encoding = 'utf8'): + cx = mk_gc_cx(encoding) + def f(): + try: + lift_flat(cx, CoreValueIter([v]), t) + except Trap: + cx.inst.store.lockdown = False + return + fail("expected trap lifting {} from {}".format(t, v)) + run_in_task(cx.inst, f) + + # Out-of-range discriminants. + expect_trap(EnumType(['a', 'b']), 2) + cx = mk_gc_cx() + t = ListType(EnumType(['a', 'b'])) + expect_trap(t, array_new_fixed(gc_list_type(cx, EnumType(['a', 'b'])), [0, 2])) + + # Variant structs must have a valid discriminant and the matching case type. + animal = VariantType([CaseType('cat', U32Type()), CaseType('dog', U16Type()), CaseType('rabbit', None)]) + rec = gc_variant_rec_type(cx, animal.cases) + expect_trap(animal, struct_new(CoreDefType(rec, 0), [0])) + expect_trap(animal, struct_new(CoreDefType(rec, 1), [1, 7])) + expect_trap(animal, struct_new(CoreDefType(rec, 3), [3])) + expect_trap(animal, struct_new(CoreDefType(rec, 3), [0])) + + # Fixed-length lists must have the right length. + t = ListType(U8Type(), 3) + expect_trap(t, array_new_fixed(gc_list_type(cx, U8Type()), [1, 2])) + expect_trap(t, array_new_fixed(gc_list_type(cx, U8Type()), [1, 2, 3, 4])) + + # Lists and strings respect the same byte length limits as linear memory. + before = (definitions.MAX_LIST_BYTE_LENGTH, definitions.MAX_STRING_BYTE_LENGTH) + definitions.MAX_LIST_BYTE_LENGTH = 7 + definitions.MAX_STRING_BYTE_LENGTH = 7 + expect_trap(ListType(U16Type()), array_new_fixed(gc_list_type(cx, U16Type()), [1, 2, 3, 4])) + expect_trap(StringType(), array_new_fixed(GC_UTF16_ARRAY, [0x61, 0x62, 0x63, 0x64]), 'utf16') + definitions.MAX_LIST_BYTE_LENGTH, definitions.MAX_STRING_BYTE_LENGTH = before + + # Handles must be boxed handle indices. + store = Store() + inst = ComponentInstance(store) + rt = ResourceType(inst, 'i32') + expect_trap(OwnType(rt), "not a handle") + other_inst = ComponentInstance(store) + expect_trap(OwnType(rt), HandleRef(other_inst, other_inst.handles.add(ResourceHandle(rt, 0, own = True)))) + +def test_gc_handles(): + dtor_value = None + def dtor(args): + nonlocal dtor_value + [dtor_value] = args + return [] + + store = Store() + producer_inst = ComponentInstance(store) + rt = ResourceType(producer_inst, 'i32', dtor) + inst = ComponentInstance(store) + opts = mk_gc_opts() + + host_ft = FuncType([BorrowType(rt), ListType(OwnType(rt))], [OwnType(rt)]) + def host_func(on_start, on_return, wait_until): + args = on_start() + assert(args == [42, [43]]) + on_return([45]) + host_func_inst = mk_host_func(store, host_func, host_ft) + + def core_wasm(args): + nonlocal dtor_value + [h1, h2] = args + assert(isinstance(h1, HandleRef) and isinstance(h2, HandleRef)) + assert(canon_gc_resource_rep(rt, h1) == [42]) + assert(canon_gc_resource_rep(rt, h2) == [43]) + hs = array_new_fixed(gc_list_type(LiftLowerContext('lower', opts, inst), OwnType(rt)), [h2]) + [h3] = store.lower(host_func_inst, host_ft, opts, inst)([h1, hs]) + assert(isinstance(h3, HandleRef)) + assert(canon_gc_resource_rep(rt, h3) == [45]) + # h2 was moved to the callee, so its index was reused for h3 and h2 is stale. + assert(h2.index == h3.index) + expect_fail(lambda: canon_gc_resource_rep(rt, h2)) + expect_fail(lambda: canon_gc_resource_rep(rt, h2.index)) + [h4] = canon_gc_resource_new(rt, 46) + assert(isinstance(h4, HandleRef)) + dtor_value = None + assert(canon_gc_resource_drop(rt, h1) == []) + assert(dtor_value == 42) + return [h3, h4] + + ft = FuncType([OwnType(rt), OwnType(rt)], [TupleType([OwnType(rt), OwnType(rt)])]) + got = None + def on_resolve(results): + nonlocal got + got = results + lift_and_run(opts, inst, ft, core_wasm, lambda: [42, 43], on_resolve) + assert(got == [mk_tup(45, 46)]) + assert(all(h is None for h in inst.handles.array)) + + # Borrows lowered into the defining component pass the rep, both as flat + # values and in GC heap storage. + rt2 = ResourceType(inst, 'i64') + def core_wasm2(args): + [rep, rs] = args + assert(rep == 7) + assert(rs.elems == [8, 9]) + return [] + ft = FuncType([BorrowType(rt2), ListType(BorrowType(rt2))], []) + lift_and_run(opts, inst, ft, core_wasm2, lambda: [7, [8, 9]], lambda _: ()) + +def test_gc_streams(): + store = Store() + inst = ComponentInstance(store) + stream_t = StreamType(U8Type()) + future_t = FutureType(U8Type()) + def core_wasm(args): + packed = canon_stream_new(stream_t)[0] + ri, wi = unpack_new_ends(packed) + r = HandleRef(inst, ri) + assert(canon_gc_stream_drop_readable(stream_t, r) == []) + assert(canon_gc_stream_drop_writable(stream_t, HandleRef(inst, wi)) == []) + expect_fail(lambda: canon_gc_stream_drop_readable(stream_t, r)) + packed = canon_future_new(future_t)[0] + ri, wi = unpack_new_ends(packed) + r = HandleRef(inst, ri) + assert(canon_gc_future_drop_readable(future_t, r) == []) + expect_fail(lambda: canon_gc_future_drop_readable(future_t, r)) + expect_fail(lambda: canon_gc_future_drop_writable(future_t, wi)) + [gc_r, gc_w] = canon_gc_stream_new(stream_t) + assert(isinstance(inst.handles.get(gc_w.index), WritableStreamEnd)) + assert(isinstance(inst.handles.get(gc_r.index), ReadableStreamEnd)) + assert(inst.handles.get(gc_w.index).other is inst.handles.get(gc_r.index)) + assert(canon_gc_stream_drop_writable(stream_t, gc_w) == []) + assert(canon_gc_stream_drop_readable(stream_t, gc_r) == []) + [gc_r, gc_w] = canon_gc_future_new(future_t) + assert(isinstance(inst.handles.get(gc_w.index), WritableFutureEnd)) + assert(isinstance(inst.handles.get(gc_r.index), ReadableFutureEnd)) + assert(inst.handles.get(gc_w.index).other is inst.handles.get(gc_r.index)) + assert(canon_gc_future_drop_readable(future_t, gc_r) == []) + return [] + lift_and_run(mk_opts(), inst, FuncType([], []), core_wasm, lambda: [], lambda _: ()) + +def test_gc_futures(): + store = Store() + inst = ComponentInstance(store) + gc_opts = mk_gc_opts() + async_gc_opts = mk_gc_opts() + async_gc_opts.async_ = True + + def host_end(end): + end.owner = None + end.index = None + return end + + def guest_end(end): + end.owner = inst + end.index = inst.handles.add(end) + return HandleRef(inst, end.index) + + cx = LiftLowerContext('lower', gc_opts, inst) + def mk_cell(t, junk): + return struct_new(gc_async_results_type(cx, t), [junk]) + + def core_wasm(args): + # Futures within the same component: an async write blocks until a sync + # read completes it, which overwrites the cell's field with the value's GC + # heap storage representation. + for t, written, stored, junk in [(S8Type(), 0x1ff, 0xff, 7), + (U16Type(), 0xbeef, 0xbeef, 7), + (F64Type(), -1.5, -1.5, 7.0)]: + future_t = FutureType(t) + [r, w] = canon_gc_future_new(future_t) + assert(canon_future_write(future_t, async_gc_opts, w, written) == [BLOCKED]) + cell = mk_cell(t, junk) + assert(canon_future_read(future_t, gc_opts, r, cell) == [CopyResult.COMPLETED]) + assert(cell.fields == [stored]) + future_t = FutureType(None) + [r, w] = canon_gc_future_new(future_t) + assert(canon_future_write(future_t, async_gc_opts, w) == [BLOCKED]) + assert(canon_future_read(future_t, gc_opts, r) == [CopyResult.COMPLETED]) + + # A host writer and a GC reader of a `future`. + future_t = FutureType(StringType()) + reader, writer = new_future(StringType(), None) + host_end(writer) + r = guest_end(reader) + writer.copy(HostReadableBuffer(StringType(), [mk_str("hi")])) + cell = mk_cell(StringType(), None) + assert(canon_future_read(future_t, gc_opts, r, cell) == [CopyResult.COMPLETED]) + assert(cell.fields[0].t == GC_UTF8_ARRAY and cell.fields[0].elems == list(b'hi')) + + # If no value is read, the cell is left untouched. + reader, writer = new_future(StringType(), None) + host_end(writer) + r = guest_end(reader) + writer.drop() + junk = array_new_fixed(GC_UTF8_ARRAY, []) + cell = mk_cell(StringType(), junk) + assert(canon_future_read(future_t, gc_opts, r, cell) == [CopyResult.DROPPED]) + assert(cell.fields[0] is junk) + + # A GC writer and a host reader: the written value is lifted when read. + reader, writer = new_future(StringType(), None) + host_end(reader) + w = guest_end(writer) + a = array_new_fixed(GC_UTF8_ARRAY, list(b'yo')) + assert(canon_future_write(future_t, async_gc_opts, w, a) == [BLOCKED]) + buffer = HostWritableBuffer(StringType(), 1) + reader.copy(buffer) + assert(buffer.received == [('yo', StringHint.UTF8, 2)]) + + # An async read that blocks writes the cell when the value arrives. + reader, writer = new_future(StringType(), None) + host_end(writer) + r = guest_end(reader) + cell = mk_cell(StringType(), None) + assert(canon_future_read(future_t, async_gc_opts, r, cell) == [BLOCKED]) + assert(cell.fields[0] is None) + writer.copy(HostReadableBuffer(StringType(), [mk_str("later")])) + assert(cell.fields[0].elems == list(b'later')) + + # Cancelling a blocked read leaves the cell untouched. + reader, writer = new_future(StringType(), None) + host_end(writer) + r = guest_end(reader) + cell = mk_cell(StringType(), junk) + assert(canon_future_read(future_t, async_gc_opts, r, cell) == [BLOCKED]) + assert(canon_gc_future_cancel_read(future_t, False, r) == [CopyResult.CANCELLED]) + assert(cell.fields[0] is junk) + return [] + + lift_and_run(mk_opts(), inst, FuncType([], []), core_wasm, lambda: [], lambda _: ()) + +def test_gc_stream_copy(): + store = Store() + inst = ComponentInstance(store) + gc_opts = mk_gc_opts() + async_gc_opts = mk_gc_opts() + async_gc_opts.async_ = True + cx = LiftLowerContext('lower', gc_opts, inst) + + def read_array_t(t): + elem = CoreFieldType(nullable_type(gc_storage_type(cx, t)), mutable = True) + return gc_final_type(CoreArrayType(elem)) + + def packed(result, progress): + return result | (progress << 4) + + def host_end(end): + end.owner = None + end.index = None + return end + + def guest_end(end): + end.owner = inst + end.index = inst.handles.add(end) + return HandleRef(inst, end.index) + + def core_wasm(args): + # A stream within the same component: an async write blocks until a sync + # read copies into the given range of the reader's array. + stream_t = StreamType(U8Type()) + [r, w] = canon_gc_stream_new(stream_t) + src = array_new_fixed(gc_list_type(cx, U8Type()), [7, 1, 2, 3]) + assert(canon_stream_write(stream_t, async_gc_opts, w, src, 1, 3) == [BLOCKED]) + dst = array_new_fixed(read_array_t(U8Type()), [0, 0, 0, 0, 0]) + assert(canon_stream_read(stream_t, gc_opts, r, dst, 1, 4) == [packed(CopyResult.COMPLETED, 3)]) + assert(dst.elems == [0, 1, 2, 3, 0]) + + # Out-of-bounds buffers trap eagerly, even when the length is 0. + expect_fail(lambda: canon_stream_read(stream_t, gc_opts, r, dst, 6, 0)) + [r, w] = canon_gc_stream_new(stream_t) + expect_fail(lambda: canon_stream_write(stream_t, gc_opts, w, src, 2, 3)) + + # An async read that blocks returns BLOCKED and is filled in later. + [r, w] = canon_gc_stream_new(stream_t) + dst = array_new_fixed(read_array_t(U8Type()), [0, 0]) + assert(canon_stream_read(stream_t, async_gc_opts, r, dst, 0, 2) == [BLOCKED]) + assert(canon_stream_write(stream_t, gc_opts, w, src, 0, 2) == [packed(CopyResult.COMPLETED, 2)]) + assert(dst.elems == [7, 1]) + + # A stream without an element type just takes a length. + stream_t = StreamType(None) + [r, w] = canon_gc_stream_new(stream_t) + assert(canon_stream_write(stream_t, async_gc_opts, w, 2) == [BLOCKED]) + assert(canon_stream_read(stream_t, gc_opts, r, 5) == [packed(CopyResult.COMPLETED, 2)]) + + # A host writer and a GC reader of a `stream`. + stream_t = StreamType(StringType()) + reader, writer = new_stream(StringType(), None) + host_end(writer) + r = guest_end(reader) + writer.copy(HostReadableBuffer(StringType(), [mk_str("a"), mk_str("bc")])) + dst = array_new_fixed(read_array_t(StringType()), [None, None, None]) + assert(canon_stream_read(stream_t, gc_opts, r, dst, 0, 3) == [packed(CopyResult.COMPLETED, 2)]) + assert([a.elems for a in dst.elems[:2]] == [list(b'a'), list(b'bc')] and dst.elems[2] is None) + + # A GC writer and a host reader: elements are lifted when read. + reader, writer = new_stream(StringType(), None) + host_end(reader) + w = guest_end(writer) + src = array_new_fixed(gc_list_type(cx, StringType()), + [array_new_fixed(GC_UTF8_ARRAY, list(b'x')), + array_new_fixed(GC_UTF8_ARRAY, list(b'yz'))]) + assert(canon_stream_write(stream_t, async_gc_opts, w, src, 0, 2) == [BLOCKED]) + buffer = HostWritableBuffer(StringType(), 2) + reader.copy(buffer) + assert(buffer.received == [('x', StringHint.UTF8, 1), ('yz', StringHint.UTF8, 2)]) + return [] + + lift_and_run(mk_opts(), inst, FuncType([], []), core_wasm, lambda: [], lambda _: ()) + +def test_gc_error_context(): + store = Store() + inst = ComponentInstance(store) + def core_wasm(args): + for s, encoding, array_t, elems in [ + ('h\u00e9', 'utf8', GC_UTF8_ARRAY, [0x68, 0xc3, 0xa9]), + ('h\u00e9', 'utf16', GC_UTF16_ARRAY, [0x68, 0xe9]), + ('h\u00e9', 'latin1+utf16', GC_LATIN1_ARRAY, [0x68, 0xe9]), + ('h\u0113', 'latin1+utf16', GC_UTF16_ARRAY, [0x68, 0x113])]: + r = HandleRef(inst, inst.handles.add(ErrorContext(mk_str(s)))) + [a] = canon_error_context_debug_message(mk_gc_opts(encoding), r) + assert(a.t == array_t and a.elems == elems) + assert(canon_gc_error_context_drop(r) == []) + expect_fail(lambda: canon_error_context_debug_message(mk_gc_opts(), 1)) + + # In the deterministic profile, the debug message is always discarded. + [r] = canon_error_context_new(mk_gc_opts(), array_new_fixed(GC_UTF8_ARRAY, list(b'hi'))) + assert(isinstance(r, HandleRef)) + [a] = canon_error_context_debug_message(mk_gc_opts(), r) + assert(a.t == GC_UTF8_ARRAY and a.elems == []) + + # Otherwise, the debug message is lifted from the GC string array. + saved = (definitions.DETERMINISTIC_PROFILE, definitions.random.randint) + definitions.DETERMINISTIC_PROFILE = False + definitions.random.randint = lambda a, b: 0 + definitions.host_defined_transformation = lambda s: s + try: + for encoding, arr in [('utf8', array_new_fixed(GC_UTF8_ARRAY, [0x68, 0xc3, 0xa9])), + ('utf16', array_new_fixed(GC_UTF16_ARRAY, [0x68, 0xe9])), + ('latin1+utf16', array_new_fixed(GC_UTF16_ARRAY, [0x68, 0x113]))]: + [r] = canon_error_context_new(mk_gc_opts(encoding), arr) + [a] = canon_error_context_debug_message(mk_gc_opts('utf16'), r) + assert(a.elems == encode_utf16_code_units(inst.handles.get(r.index).debug_message[0])) + assert(inst.handles.get(r.index).debug_message[0] in ('h\u00e9', 'h\u0113')) + finally: + definitions.DETERMINISTIC_PROFILE, definitions.random.randint = saved + del definitions.host_defined_transformation + return [] + lift_and_run(mk_opts(), inst, FuncType([], []), core_wasm, lambda: [], lambda _: ()) + +def test_gc_waitables(): + store = Store() + inst = ComponentInstance(store) + def core_wasm(args): + [s] = canon_gc_waitable_set_new() + assert(isinstance(s, HandleRef) and isinstance(inst.handles.get(s.index), WaitableSet)) + + # Joining a waitable to a set, and a null set removes it again. + stream_t = StreamType(U8Type()) + [r, w] = canon_gc_stream_new(stream_t) + assert(canon_gc_waitable_join(r, s) == []) + assert(inst.handles.get(r.index).wset is inst.handles.get(s.index)) + assert(canon_gc_waitable_join(r, None) == []) + assert(inst.handles.get(r.index).wset is None) + expect_fail(lambda: canon_gc_waitable_join(r, 1)) + assert(canon_gc_waitable_set_drop(s) == []) + expect_fail(lambda: canon_gc_waitable_set_drop(s)) + + # Subtasks (created directly, since gc + async lowering is not yet specified). + subtask = Subtask() + subtask.resolve(Subtask.State.RETURNED, []) + subtask.deliver_resolve() + st = HandleRef(inst, inst.handles.add(subtask)) + expect_fail(lambda: canon_gc_subtask_cancel(False, st)) + assert(canon_gc_subtask_drop(st) == []) + expect_fail(lambda: canon_gc_subtask_drop(st)) + + # gc.waitable-set.{wait,poll} return the event code, payload and waitable. + [s] = canon_gc_waitable_set_new() + assert(canon_gc_waitable_set_poll(s) == [EventCode.NONE, 0, None]) + async_gc_opts = mk_gc_opts() + async_gc_opts.async_ = True + src = array_new_fixed(gc_list_type(LiftLowerContext('lift', async_gc_opts, inst), U8Type()), [1, 2]) + dst = array_new_fixed(gc_final_type(CoreArrayType(CoreFieldType('i8', mutable = True))), [0, 0]) + for wait_or_poll in [canon_gc_waitable_set_poll, canon_gc_waitable_set_wait]: + [r, w] = canon_gc_stream_new(stream_t) + assert(canon_gc_waitable_join(r, s) == []) + assert(canon_stream_read(stream_t, async_gc_opts, r, dst, 0, 2) == [BLOCKED]) + assert(canon_stream_write(stream_t, mk_gc_opts(), w, src, 0, 2) == [CopyResult.COMPLETED | (2 << 4)]) + [code, payload, e] = wait_or_poll(s) + assert(code == EventCode.STREAM_READ and payload == CopyResult.COMPLETED | (2 << 4)) + assert(isinstance(e, HandleRef) and e.index == r.index) + assert(canon_gc_waitable_join(r, None) == []) + expect_fail(lambda: canon_gc_waitable_set_poll(r)) + return [] + lift_and_run(mk_opts(), inst, FuncType([], []), core_wasm, lambda: [], lambda _: ()) + +def test_gc_anyref_reps(): + store = Store() + inst = ComponentInstance(store) + dtor_args = None + def dtor(args): + nonlocal dtor_args + dtor_args = args + return [] + rt = ResourceType(inst, ANYREF, dtor) + rep1 = struct_new(gc_struct_t('i32'), [1]) + rep2 = struct_new(gc_struct_t('i32'), [2]) + + # gc.resource.{new,rep,drop} with a `(ref any)` rep. + def core_new_rep_drop(args): + [h] = canon_gc_resource_new(rt, rep1) + assert(canon_gc_resource_rep(rt, h) == [rep1]) + assert(canon_gc_resource_drop(rt, h) == []) + assert(dtor_args == [rep1]) + return [] + lift_and_run(mk_opts(), inst, FuncType([], []), core_new_rep_drop, lambda: [], lambda _: ()) + + # Borrows lowered into the defining component pass the `(ref any)` rep, both + # as a flat value and in GC heap storage. + def core_gc(args): + [r, rs] = args + assert(r is rep1) + assert(rs.elems[0] is rep1 and rs.elems[1] is rep2) + return [] + ft = FuncType([BorrowType(rt), ListType(BorrowType(rt))], []) + cx = LiftLowerContext('lower', mk_gc_opts(), inst) + assert(flatten_functype(LiftLowerContext('lift', mk_gc_opts(), inst), ft).params == + [ANYREF, CoreRefType(gc_list_type(cx, BorrowType(rt)))]) + lift_and_run(mk_gc_opts(), inst, ft, core_gc, lambda: [rep1, [rep1, rep2]], lambda _: ()) + +def test_gc_handle_refs(): + store = Store() + inst = ComponentInstance(store) + stream_t = StreamType(U8Type()) + def core_wasm(args): + # gc.handle-ref.index returns the `i32` handle of a `HandleRef`, and + # gc.handle-ref.get returns the unique `HandleRef` of an `i32` handle. + [r, w] = canon_gc_stream_new(stream_t) + [ri] = canon_gc_handle_ref_index(r) + assert(ri == r.index and canon_gc_handle_ref_get(ri) == [r]) + expect_fail(lambda: canon_gc_handle_ref_new(ri)) + + # An `i32` handle without a `HandleRef` can be given one exactly once. + packed = canon_stream_new(stream_t)[0] + ri2, wi2 = unpack_new_ends(packed) + assert(canon_gc_handle_ref_get(ri2) == [None]) + [r2] = canon_gc_handle_ref_new(ri2) + assert(canon_gc_handle_ref_get(ri2) == [r2]) + expect_fail(lambda: canon_gc_handle_ref_new(ri2)) + + # Both trap for out-of-bounds indices, but only gc.handle-ref.new traps for + # in-bounds indices without a live handle. + expect_fail(lambda: canon_gc_handle_ref_new(1000)) + expect_fail(lambda: canon_gc_handle_ref_get(1000)) + assert(canon_gc_handle_ref_get(0) == [None]) + expect_fail(lambda: canon_gc_handle_ref_new(0)) + + # Removing a handle from the table removes its `HandleRef`, which is then + # stale (even if its index is reused). + assert(canon_gc_stream_drop_readable(stream_t, r2) == []) + assert(canon_gc_handle_ref_get(ri2) == [None]) + expect_fail(lambda: canon_gc_handle_ref_index(r2)) + [r3, w3] = canon_gc_stream_new(stream_t) + assert(r3.index == ri2) + expect_fail(lambda: canon_gc_stream_drop_readable(stream_t, r2)) + expect_fail(lambda: canon_gc_handle_ref_index("not a handle ref")) + + # All three check `may_leave` (and succeed once it is restored). + ri4, _ = unpack_new_ends(canon_stream_new(stream_t)[0]) + inst.may_leave = False + expect_fail(lambda: canon_gc_handle_ref_index(r3)) + expect_fail(lambda: canon_gc_handle_ref_get(ri4)) + expect_fail(lambda: canon_gc_handle_ref_new(ri4)) + inst.may_leave = True + assert(canon_gc_handle_ref_index(r3) == [r3.index]) + assert(canon_gc_handle_ref_get(ri4) == [None]) + [r4] = canon_gc_handle_ref_new(ri4) + assert(canon_gc_handle_ref_get(ri4) == [r4]) + + # Events from gc.waitable-set.{wait,poll} return the existing `HandleRef`. + [s] = canon_gc_waitable_set_new() + assert(canon_gc_waitable_join(r3, s) == []) + async_gc_opts = mk_gc_opts() + async_gc_opts.async_ = True + cx = LiftLowerContext('lift', async_gc_opts, inst) + dst = array_new_fixed(gc_final_type(CoreArrayType(CoreFieldType('i8', mutable = True))), [0]) + assert(canon_stream_read(stream_t, async_gc_opts, r3, dst, 0, 1) == [BLOCKED]) + src = array_new_fixed(gc_list_type(cx, U8Type()), [9]) + assert(canon_stream_write(stream_t, mk_gc_opts(), w3, src, 0, 1) == [CopyResult.COMPLETED | (1 << 4)]) + [code, payload, e] = canon_gc_waitable_set_poll(s) + assert(code == EventCode.STREAM_READ and e is r3) + return [] + lift_and_run(mk_opts(), inst, FuncType([], []), core_wasm, lambda: [], lambda _: ()) + +def test_gc_async(): + store = Store() + producer_inst = ComponentInstance(store) + producer_opts = mk_gc_opts() + producer_opts.async_ = True + producer_ft = FuncType([StringType()], [StringType()], async_ = True) + big_t = TupleType([U8Type() for _ in range(17)]) + big_ft = FuncType([], [big_t], async_ = True) + + # A stackful async producer that blocks before returning. + fut = RacyBool(False) + def core_blocking_producer(args): + [a] = args + assert(a.t == GC_UTF8_ARRAY and a.elems == list(b'in')) + current_thread().wait_until(fut.is_set) + canon_task_return([StringType()], producer_opts, [array_new_fixed(GC_UTF8_ARRAY, list(b'out'))]) + return [] + blocking_producer = store.lift(core_blocking_producer, producer_ft, producer_opts, producer_inst) + + # A producer that returns immediately. + def core_eager_producer(args): + canon_task_return([StringType()], producer_opts, [array_new_fixed(GC_UTF8_ARRAY, list(b'now'))]) + return [] + eager_producer = store.lift(core_eager_producer, producer_ft, producer_opts, producer_inst) + + # A producer whose result has too many flat values, so task.return takes the + # result's storage type directly. + def core_big_producer(args): + pcx = LiftLowerContext('lift', producer_opts, producer_inst) + v = struct_new(gc_record_type(pcx, despecialize(big_t).fields), list(range(17))) + canon_task_return([big_t], producer_opts, [v]) + return [] + big_producer = store.lift(core_big_producer, big_ft, producer_opts, producer_inst) + + consumer_inst = ComponentInstance(store) + consumer_ft = FuncType([], [StringType()], async_ = True) + lower_opts = mk_gc_opts() + lower_opts.async_ = True + cx = LiftLowerContext('lower', lower_opts, consumer_inst) + results = struct_new(gc_async_results_type(cx, StringType()), [None]) + arg = array_new_fixed(GC_UTF8_ARRAY, list(b'in')) + st = None + step = 0 + + def consumer(args): + nonlocal st, step + [packed, st] = store.lower(blocking_producer, producer_ft, lower_opts, consumer_inst)([arg, results]) + assert(packed & 0xf == Subtask.State.STARTED) + assert(isinstance(st, HandleRef) and packed >> 4 == st.index) + assert(results.fields[0] is None) + [s] = canon_gc_waitable_set_new() + assert(canon_gc_waitable_join(st, s) == []) + fut.set() + return [CallbackCode.WAIT, s] + + def callback(args): + nonlocal step + [code, payload, w] = args + step += 1 + match step: + case 1: + assert(code == EventCode.SUBTASK and payload == Subtask.State.RETURNED and w is st) + assert(results.fields[0].t == GC_UTF8_ARRAY and results.fields[0].elems == list(b'out')) + assert(canon_gc_subtask_drop(st) == []) + return [CallbackCode.YIELD, None] + case 2: + assert([code, payload, w] == [EventCode.NONE, 0, None]) + assert(store.lower(eager_producer, producer_ft, lower_opts, consumer_inst)([arg, results]) == + [Subtask.State.RETURNED, None]) + assert(results.fields[0].elems == list(b'now')) + big_results = struct_new(gc_async_results_type(cx, big_t), [None]) + assert(store.lower(big_producer, big_ft, lower_opts, consumer_inst)([big_results]) == + [Subtask.State.RETURNED, None]) + assert(big_results.fields[0].fields == list(range(17))) + canon_task_return([StringType()], consumer_opts, [array_new_fixed(GC_UTF8_ARRAY, list(b'done'))]) + return [CallbackCode.EXIT, None] + + consumer_opts = mk_gc_opts() + consumer_opts.async_ = True + consumer_opts.callback = callback + got = None + def on_resolve(result): + nonlocal got + [got] = result + lift_and_run(consumer_opts, consumer_inst, consumer_ft, consumer, lambda: [], on_resolve) + assert(step == 2) + assert(got == ('done', StringHint.UTF8, 4)) + +def test_gc_post_return(): + store = Store() + inst = ComponentInstance(store) + post_return_args = None + def post_return(args): + nonlocal post_return_args + post_return_args = args + return [] + def core_wasm(args): + return [array_new_fixed(GC_UTF8_ARRAY, list(b'hi'))] + got = None + def on_resolve(results): + nonlocal got + [got] = results + ft = FuncType([], [StringType()]) + lift_and_run(mk_gc_opts(post_return = post_return), inst, ft, core_wasm, lambda: [], on_resolve) + assert(got == ('hi', StringHint.UTF8, 2)) + [a] = post_return_args + assert(a.t == GC_UTF8_ARRAY and a.elems == list(b'hi')) + +def test_gc_array_new(): + store = Store() + inst = ComponentInstance(store) + i8s = gc_array_t('i8') + i16s = gc_array_t('i16') + f32s = gc_array_t('f32') + refs = gc_array_t(EXTERNREF) + def f(): + src = array_new_fixed(i8s, [1, 2, 3, 4]) + [a] = canon_array_new_array(i8s, i8s, src, 1, 2) + assert(a.t == i8s and a.elems == [2, 3]) + [a] = canon_array_new_array(i8s, i8s, src, 4, 0) + assert(a.elems == []) + expect_fail(lambda: canon_array_new_array(i8s, i8s, src, 3, 2)) + expect_fail(lambda: canon_array_new_array(i8s, i8s, None, 0, 0)) + + mem = MemInst(bytearray(b'\x01\x02\x03\x04\x00\x00\xc0\x3f'), 'i32') + [a] = canon_array_new_memory(i16s, mem, 1, 2) + assert(a.t == i16s and a.elems == [0x0302, 0x0004]) + [a] = canon_array_new_memory(f32s, mem, 4, 1) + assert(a.elems == [1.5]) + expect_fail(lambda: canon_array_new_memory(i16s, mem, 6, 2)) + + tbl = [object(), object(), object()] + [a] = canon_array_new_table(refs, tbl, 1, 2) + assert(a.t == refs and a.elems == tbl[1:]) + expect_fail(lambda: canon_array_new_table(refs, tbl, 2, 2)) + run_in_task(inst, f) + test_roundtrips() test_trap_propagation() test_cross_component_realloc() @@ -3206,5 +4155,20 @@ def on_resolve(v): test_async_flat_params() test_threads() test_sync_threads() +test_gc_flatten() +test_gc_values() +test_gc_strings() +test_gc_lift_traps() +test_gc_handles() +test_gc_streams() +test_gc_futures() +test_gc_stream_copy() +test_gc_error_context() +test_gc_waitables() +test_gc_anyref_reps() +test_gc_handle_refs() +test_gc_async() +test_gc_post_return() +test_gc_array_new() print("All tests passed") diff --git a/test/nyi.txt b/test/nyi.txt index ec1ec1d78..4dcc5c205 100644 --- a/test/nyi.txt +++ b/test/nyi.txt @@ -4,3 +4,4 @@ ./async/big-interleaving-test.wast ./async/forward.wast ./async/exit-without-resolving.wast +./values/transcode-memory64.wast diff --git a/test/values/transcode-memory64.wast b/test/values/transcode-memory64.wast new file mode 100644 index 000000000..086337e64 --- /dev/null +++ b/test/values/transcode-memory64.wast @@ -0,0 +1,230 @@ +;; Test latin1+utf16 strings passed between components whose memories have +;; different address types. + +;; i64 caller -> i32 callee: utf16-tagged input whose code points all fit in +;; latin1 must arrive deflated to latin1; wide content stays utf16. +(component + (component $C + (core module $M + (memory (export "mem") 1) + (global $next (mut i32) (i32.const 1024)) + (func (export "realloc") (param $old i32) (param $osize i32) (param $align i32) (param $nsize i32) (result i32) + (local $r i32) + ;; shrinking realloc: keep the (8-aligned) allocation in place + (if (i32.and (i32.ne (local.get $old) (i32.const 0)) + (i32.le_u (local.get $nsize) (local.get $osize))) + (then (return (local.get $old)))) + ;; fresh 8-aligned bump allocation + (global.set $next (i32.and (i32.add (global.get $next) (i32.const 7)) (i32.const -8))) + (local.set $r (global.get $next)) + (global.set $next (i32.add (global.get $next) (local.get $nsize))) + ;; growing realloc must preserve the old contents + (if (i32.ne (local.get $old) (i32.const 0)) + (then (memory.copy (local.get $r) (local.get $old) (local.get $osize)))) + (local.get $r)) + + ;; response "øk" latin1 = F8 6B (2 code units, untagged) + (data (i32.const 64) "\f8\6b") + ;; response "n☃" utf16 = 006E 2603 (2 code units, tagged) + (data (i32.const 68) "\6e\00\03\26") + + ;; expect "AB" deflated to latin1 = 41 42 (2 code units, untagged) + (func (export "deflate") (param $ptr i32) (param $tagged i32) (result i32) + (if (i32.ne (local.get $tagged) (i32.const 2)) (then unreachable)) + (if (i32.ne (i32.load16_u (local.get $ptr)) (i32.const 0x4241)) (then unreachable)) + (i32.store (i32.const 0) (i32.const 64)) + (i32.store (i32.const 4) (i32.const 2)) + (i32.const 0)) + + ;; expect "☃" kept as utf16 = 2603 (1 code unit, i32-tagged) + (func (export "keep-wide") (param $ptr i32) (param $tagged i32) (result i32) + (if (i32.ne (local.get $tagged) (i32.const 0x80000001)) (then unreachable)) + (if (i32.ne (i32.load16_u (local.get $ptr)) (i32.const 0x2603)) (then unreachable)) + (i32.store (i32.const 0) (i32.const 68)) + (i32.store (i32.const 4) (i32.const 0x80000002)) + (i32.const 0)) + ) + (core instance $m (instantiate $M)) + (func (export "deflate") (param "s" string) (result string) + (canon lift (core func $m "deflate") string-encoding=latin1+utf16 + (memory (core memory $m "mem")) (realloc (core func $m "realloc")))) + (func (export "keep-wide") (param "s" string) (result string) + (canon lift (core func $m "keep-wide") string-encoding=latin1+utf16 + (memory (core memory $m "mem")) (realloc (core func $m "realloc")))) + ) + + (component $D + (import "deflate" (func $deflate (param "s" string) (result string))) + (import "keep-wide" (func $keep-wide (param "s" string) (result string))) + (core module $Libc + (memory (export "mem") i64 1) + (global $next (mut i64) (i64.const 1024)) + (func (export "realloc") (param $old i64) (param $osize i64) (param $align i64) (param $nsize i64) (result i64) + (local $r i64) + (if (i32.and (i64.ne (local.get $old) (i64.const 0)) + (i64.le_u (local.get $nsize) (local.get $osize))) + (then (return (local.get $old)))) + (global.set $next (i64.and (i64.add (global.get $next) (i64.const 7)) (i64.const -8))) + (local.set $r (global.get $next)) + (global.set $next (i64.add (global.get $next) (local.get $nsize))) + (if (i64.ne (local.get $old) (i64.const 0)) + (then (memory.copy (local.get $r) (local.get $old) (local.get $osize)))) + (local.get $r)) + ) + (core instance $libc (instantiate $Libc)) + (core func $deflate' (canon lower (func $deflate) string-encoding=latin1+utf16 + (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")))) + (core func $keep-wide' (canon lower (func $keep-wide) string-encoding=latin1+utf16 + (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")))) + (core module $Main + (import "" "mem" (memory i64 1)) + (import "" "deflate" (func $deflate (param i64 i64 i64))) + (import "" "keep-wide" (func $keep-wide (param i64 i64 i64))) + + ;; argument "AB" over-encoded as utf16 = 0041 0042 (2 code units, tagged) + (data (i64.const 16) "\41\00\42\00") + ;; argument "☃" utf16 = 2603 (1 code unit, tagged) + (data (i64.const 24) "\03\26") + + (func (export "run") (result i32) + (local $p i64) + (call $deflate (i64.const 16) (i64.const 0x8000000000000002) (i64.const 32)) + ;; expect "øk" latin1 = F8 6B (2 code units, untagged) + (local.set $p (i64.load (i64.const 32))) + (if (i64.ne (i64.load (i64.const 40)) (i64.const 2)) (then unreachable)) + (if (i32.ne (i32.load16_u (local.get $p)) (i32.const 0x6BF8)) (then unreachable)) + (call $keep-wide (i64.const 24) (i64.const 0x8000000000000001) (i64.const 32)) + ;; expect "n☃" utf16 = 006E 2603 (2 code units, i64-tagged) + (local.set $p (i64.load (i64.const 32))) + (if (i64.ne (i64.load (i64.const 40)) (i64.const 0x8000000000000002)) (then unreachable)) + (if (i32.ne (i32.load (local.get $p)) (i32.const 0x2603006E)) (then unreachable)) + (i32.const 42)) + ) + (core instance $main (instantiate $Main (with "" (instance + (export "mem" (memory $libc "mem")) + (export "deflate" (func $deflate')) + (export "keep-wide" (func $keep-wide')) + )))) + (func (export "run") (result u32) (canon lift (core func $main "run"))) + ) + + (instance $c (instantiate $C)) + (instance $d (instantiate $D + (with "deflate" (func $c "deflate")) + (with "keep-wide" (func $c "keep-wide")) + )) + (func (export "run") (alias export $d "run")) +) +(assert_return (invoke "run") (u32.const 42)) + +;; i32 caller -> i64 callee: the same strings in the other direction. +(component + (component $C + (core module $M + (memory (export "mem") i64 1) + (global $next (mut i64) (i64.const 1024)) + (func (export "realloc") (param $old i64) (param $osize i64) (param $align i64) (param $nsize i64) (result i64) + (local $r i64) + (if (i32.and (i64.ne (local.get $old) (i64.const 0)) + (i64.le_u (local.get $nsize) (local.get $osize))) + (then (return (local.get $old)))) + (global.set $next (i64.and (i64.add (global.get $next) (i64.const 7)) (i64.const -8))) + (local.set $r (global.get $next)) + (global.set $next (i64.add (global.get $next) (local.get $nsize))) + (if (i64.ne (local.get $old) (i64.const 0)) + (then (memory.copy (local.get $r) (local.get $old) (local.get $osize)))) + (local.get $r)) + + ;; response "øk" latin1 = F8 6B (2 code units, untagged) + (data (i64.const 64) "\f8\6b") + ;; response "n☃" utf16 = 006E 2603 (2 code units, tagged) + (data (i64.const 68) "\6e\00\03\26") + + ;; expect "AB" deflated to latin1 = 41 42 (2 code units, untagged) + (func (export "deflate") (param $ptr i64) (param $tagged i64) (result i64) + (if (i64.ne (local.get $tagged) (i64.const 2)) (then unreachable)) + (if (i32.ne (i32.load16_u (local.get $ptr)) (i32.const 0x4241)) (then unreachable)) + (i64.store (i64.const 0) (i64.const 64)) + (i64.store (i64.const 8) (i64.const 2)) + (i64.const 0)) + + ;; expect "☃" kept as utf16 = 2603 (1 code unit, i64-tagged) + (func (export "keep-wide") (param $ptr i64) (param $tagged i64) (result i64) + (if (i64.ne (local.get $tagged) (i64.const 0x8000000000000001)) (then unreachable)) + (if (i32.ne (i32.load16_u (local.get $ptr)) (i32.const 0x2603)) (then unreachable)) + (i64.store (i64.const 0) (i64.const 68)) + (i64.store (i64.const 8) (i64.const 0x8000000000000002)) + (i64.const 0)) + ) + (core instance $m (instantiate $M)) + (func (export "deflate") (param "s" string) (result string) + (canon lift (core func $m "deflate") string-encoding=latin1+utf16 + (memory (core memory $m "mem")) (realloc (core func $m "realloc")))) + (func (export "keep-wide") (param "s" string) (result string) + (canon lift (core func $m "keep-wide") string-encoding=latin1+utf16 + (memory (core memory $m "mem")) (realloc (core func $m "realloc")))) + ) + + (component $D + (import "deflate" (func $deflate (param "s" string) (result string))) + (import "keep-wide" (func $keep-wide (param "s" string) (result string))) + (core module $Libc + (memory (export "mem") 1) + (global $next (mut i32) (i32.const 1024)) + (func (export "realloc") (param $old i32) (param $osize i32) (param $align i32) (param $nsize i32) (result i32) + (local $r i32) + (if (i32.and (i32.ne (local.get $old) (i32.const 0)) + (i32.le_u (local.get $nsize) (local.get $osize))) + (then (return (local.get $old)))) + (global.set $next (i32.and (i32.add (global.get $next) (i32.const 7)) (i32.const -8))) + (local.set $r (global.get $next)) + (global.set $next (i32.add (global.get $next) (local.get $nsize))) + (if (i32.ne (local.get $old) (i32.const 0)) + (then (memory.copy (local.get $r) (local.get $old) (local.get $osize)))) + (local.get $r)) + ) + (core instance $libc (instantiate $Libc)) + (core func $deflate' (canon lower (func $deflate) string-encoding=latin1+utf16 + (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")))) + (core func $keep-wide' (canon lower (func $keep-wide) string-encoding=latin1+utf16 + (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")))) + (core module $Main + (import "" "mem" (memory 1)) + (import "" "deflate" (func $deflate (param i32 i32 i32))) + (import "" "keep-wide" (func $keep-wide (param i32 i32 i32))) + + ;; argument "AB" over-encoded as utf16 = 0041 0042 (2 code units, tagged) + (data (i32.const 16) "\41\00\42\00") + ;; argument "☃" utf16 = 2603 (1 code unit, tagged) + (data (i32.const 24) "\03\26") + + (func (export "run") (result i32) + (local $p i32) + (call $deflate (i32.const 16) (i32.const 0x80000002) (i32.const 8)) + ;; expect "øk" latin1 = F8 6B (2 code units, untagged) + (local.set $p (i32.load (i32.const 8))) + (if (i32.ne (i32.load (i32.const 12)) (i32.const 2)) (then unreachable)) + (if (i32.ne (i32.load16_u (local.get $p)) (i32.const 0x6BF8)) (then unreachable)) + (call $keep-wide (i32.const 24) (i32.const 0x80000001) (i32.const 8)) + ;; expect "n☃" utf16 = 006E 2603 (2 code units, i32-tagged) + (local.set $p (i32.load (i32.const 8))) + (if (i32.ne (i32.load (i32.const 12)) (i32.const 0x80000002)) (then unreachable)) + (if (i32.ne (i32.load (local.get $p)) (i32.const 0x2603006E)) (then unreachable)) + (i32.const 43)) + ) + (core instance $main (instantiate $Main (with "" (instance + (export "mem" (memory $libc "mem")) + (export "deflate" (func $deflate')) + (export "keep-wide" (func $keep-wide')) + )))) + (func (export "run") (result u32) (canon lift (core func $main "run"))) + ) + + (instance $c (instantiate $C)) + (instance $d (instantiate $D + (with "deflate" (func $c "deflate")) + (with "keep-wide" (func $c "keep-wide")) + )) + (func (export "run") (alias export $d "run")) +) +(assert_return (invoke "run") (u32.const 43))