assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Array cannot store ref_extern elements

Open ijsf opened this issue 1 year ago • 2 comments

Bug description

If an Array<ref_extern> is declared and used, the compiler generates an error due to ref_extern not being compatible with the alignof function. This will trigger three compiler errors and a warning related to size, my guess would be because the size of a ref_extern is not fully defined somewhere?

I'm not sure if this is intended, but it seems like a viable option to have an Array with external references (e.g. host maintained objects). This might also affect other types and classes.

Steps to reproduce

Use the following code:

declare function external_function(): ref_extern;
let external_ref = external_function();

let broken_array:Array<ref_extern> = [];
broken_array.push(external_ref);

The last line of code will trigger a number of errors and warnings:

ERROR AS203: Operation 'alignof' cannot be applied to type 'ref_extern'.
     :
 209 │ ensureCapacity(changetype<usize>(this), len, alignof<T>());
     │                                                      ~
     └─ in ~lib/array.ts(209,58)

WARNING AS201: Conversion from type 'usize' to 'u32' will require an explicit cast when switching between 32/64-bit.
     :
 209 │ ensureCapacity(changetype<usize>(this), len, alignof<T>());
     │                                              ~~~~~~~~~~~~
     └─ in ~lib/array.ts(209,50)

ERROR AS203: Operation 'alignof' cannot be applied to type 'ref_extern'.
     :
 214 │ store<T>(this.dataStart + (<usize>oldLen << alignof<T>()), value);
     │                                                     ~
     └─ in ~lib/array.ts(214,59)

ERROR AS203: Operation 'store' cannot be applied to type 'ref_extern'.
     :
 214 │ store<T>(this.dataStart + (<usize>oldLen << alignof<T>()), value);
     │       ~
     └─ in ~lib/array.ts(214,13)

FAILURE 3 compile error(s)

AssemblyScript version

0.27.6

ijsf avatar Jul 24 '23 17:07 ijsf

externrefs can't be stored in linear memory so having an array of them doesn't make much sense. You could have a table of externrefs which would function like an array, but I'm not sure if assemblyscript provides direct access to tables.

pufferfish101007 avatar Jul 25 '23 07:07 pufferfish101007

Got it, checked the documentation and that's correct indeed. The table approach makes more sense here, although it seems the tables haven't been implemented yet https://github.com/AssemblyScript/assemblyscript/blob/main/std/assembly/table.ts (perhaps table_set and table_get can be used instead).

ijsf avatar Jul 25 '23 14:07 ijsf