import-callables.js (1754B)
1 // Test importing callable object types other than plain functions. 2 3 // Wasm function equivalent to: function run(x) { return timesSeven(x) + 3; } 4 let bytes = wasmTextToBinary(` 5 (module 6 (func $timesSeven (import "imports" "timesSeven") 7 (param i32) (result i32)) 8 (func $run (export "run") (param i32) (result i32) 9 local.get 0 10 call $timesSeven 11 i32.const 3 12 i32.add))`); 13 let mod = new WebAssembly.Module(bytes); 14 15 function test(timesSeven) { 16 let inst = new WebAssembly.Instance(mod, {imports: {timesSeven}}); 17 return inst.exports.run(1) + inst.exports.run(3); 18 } 19 20 // Various supported callables. 21 let timesSeven = x => x * 7; 22 assertEq(test(timesSeven), 34); 23 assertEq(test(timesSeven.bind(null)), 34); 24 assertEq(test(timesSeven.bind(null, 4)), 62); 25 assertEq(test(new Proxy(timesSeven, {})), 34); 26 assertEq(test(wrapWithProto(timesSeven, null)), 34); 27 28 // Test proxy `apply` trap. 29 let traps = []; 30 assertEq(test(new Proxy(timesSeven, {apply(target, thisArg, args) { 31 traps.push(arguments); 32 return 5; 33 }})), 16); 34 assertEq(traps.length, 2); 35 for (let trap of traps) { 36 assertEq(trap[0], timesSeven); // target 37 assertEq(trap[1], undefined); // thisArg 38 assertEq(trap[2].length, 1); // args 39 } 40 41 function testThrowsLinkError(f) { 42 assertErrorMessage(() => test(f), WebAssembly.LinkError, /is not a Function/); 43 } 44 45 // Non-callables. 46 testThrowsLinkError({}); 47 testThrowsLinkError(null); 48 testThrowsLinkError(this); 49 testThrowsLinkError(new Proxy({}, {})); 50 testThrowsLinkError(wrapWithProto({}, null)); 51 52 // Cross-compartment wrappers are currently not supported. 53 let g = newGlobal({newCompartment: true}); 54 g.evaluate(`function timesSeven(x) { return x * 7; }`); 55 testThrowsLinkError(g.timesSeven);