bytecodealliance / jco

JavaScript tooling for working with WebAssembly Components
https://bytecodealliance.github.io/jco/
Apache License 2.0
571 stars 53 forks source link

`definedResourceTables` codegen generates invalid JS with `--instantiation async` #436

Closed kateinoigakukun closed 1 month ago

kateinoigakukun commented 1 month ago

Using dir.virt.wasm attached in https://github.com/bytecodealliance/jco/issues/431, the following command generates syntactically and semantically invalid JavaScript code.

$ jco transpile test/fixtures/commands/dir.virt.wasm -o tmp --instantiation async
  1. The line of definedResourceTables definition needs to be new-lined.
  2. resourceTransferBorrow cannot see the definedResourceTables definition because it's defined under instantiate scope.
// (snip)

function resourceTransferBorrow(handle, fromTid, toTid) {
  const fromTable = handleTables[fromTid];
  const isOwn = (fromTable[(handle << 1) + 1] & T_FLAG) !== 0;
  const rep = isOwn ? fromTable[(handle << 1) + 1] & ~T_FLAG : rscTableRemove(fromTable, handle).rep;
  if (definedResourceTables[toTid]) return rep;
  const toTable = handleTables[toTid] || (handleTables[toTid] = [T_FLAG, 0]);
  const newHandle = rscTableCreateBorrow(toTable, rep);
  resourceCallBorrows.push({ rid: toTid, handle: newHandle });
  return newHandle;
}

// (snip)

export async function instantiate(getCoreModule, imports, instantiateCore = WebAssembly.instantiate) {
  // ... (snip)
  const definedResourceTables = [,,,,,,,,,,,,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,]const run020 = {
    run: run,

  };

  return { run: run020, 'wasi:cli/run@0.2.0': run020,  };
}
kateinoigakukun commented 1 month ago

Thanks for your quick fix!