Sign in Join
Wiki copytemporary

WebAssembly/JS: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: WebAssembly/JS

OldNewLine
1+The primary target for WebAssembly is the browser. With WebAssembly, you can create functions in Pascal and use these functions in web pages with short glue code in Javascript.
2+
3+WebAssembly is not Javascript, it is an addition to Javascript.
4+
5+WebAssembly is not asm.js.
6+
7+## API
8+
9+The primary API for dealing with WebAssembly (.wasm) files is the [WebAssembly JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly) standard
10+
11+## Using Wasm Functions
12+
13+In order to use a .wasm file in Javascript the following steps needs to be taken:
14+
15+- The .wasm file needs to be loaded
16+
17+:* as an external resource (a web server is required due to browser security)
18+
19+:* a binary file loaded through a javascript (i.e. inlined).
20+
21+- The loaded .wasm binary file needs to be compiled.
22+- The compiled file needs to be linked (aka instantiated). It is also common to do the compilation and instantiation in one step, rather than two separate steps. (Two separate steps are typically needed, when the "compiled" form is used, either for caching OR for the dependencies resolution stage)
23+
24+:* when creating an instance (linking) all dependencies must be resolved.
25+
26+- after creating an instance, the exported functions of the instance can be called through Javascript as normal JS functions.
27+
28+Here is a common JS example:
29+
30+``` javascript
31+
32+// step #1 - loading the file and converting it to array of bytes, using the fetch() function
33+fetch('../out/main.wasm').then(
34+ response => response.arrayBuffer()
35+).then(
36+ // step #2 and #3 - compiling and linking the array of bytes (in one call) to WebAssembly.instantiate()
37+ bytes => WebAssembly.instantiate(bytes)).then(
38+
39+ // step #4 using the linked instance object to call the exported function add()
40+ results => {
41+ instance = results.instance;
42+ document.getElementById("container").textContent = instance.exports.add(1,1);
43+ }
44+ ).catch(console.error);
45+```
46+
47+## Dependencies
48+
49+As of 2019 there is no "out-of-the-box" way to resolve WebAssembly file **import** dependencies.
50+
51+WebAssembly expects an import to be resolved by providing the import module name. The import module name does not have to be a WebAssembly module, it can be a plain JavaScript function as well. And the name of the object (i.e. function of memory) WebAssembly is trying to access.
52+
53+### Example
54+
55+Here is an example of dependencies loading.
56+
57+**WARNING:** you should NOT use this code in production. It is only used for educational purposes! Javascript and its APIs are designed to do all the tasks asynchronously.
58+
59+Most of the code is based on the callbacks (closures), that are triggered when the particular task is done. I.e. loading a resources from the web, would trigger an event once the loading is completed (or failed) - as shown in the example above.
60+
61+The example below is **intentionally** performs each step synchronously (by using "await" syntax is used to explicitly wait for a completion of synchronous actions). Such intentional synchronization would impose slowness in a real-life application and should not be used.
62+
63+The example consists of two WebAssembly files and a single Javascript file to load them.
64+
65+
66+**main.wasm**:
67+
68+The module imports function named "add" from an external module named "test2"
69+
70+``` lisp
71+(module
72+ (import "test2" "add" (func $add (param i32)(param i32)(result i32) ))
73+
74+ ;; the main() function calls the external add() with arguments 4 and 5
75+ ;; and forwards the result of add as its own result
76+ (func $main
77+ (result i32)
78+ i32.const 4
79+ i32.const 5
80+ call $add
81+ return
82+ )
83+ ;; module exports the main function so it can be called outside (in javascript)
84+ (export "main" (func $main))
85+)
86+```
87+
88+
89+**test2.wasm**:
90+
91+The module implements the function "add" and exports it.
92+
93+``` lisp
94+(module
95+ (func $add (param $lhs i32) (param $rhs i32) (result i32)
96+ get_local $lhs
97+ get_local $rhs
98+ i32.add)
99+ (export "add" (func $add))
100+)
101+```
102+
103+
104+**javascript**
105+
106+The code below loads the "main.wasm".
107+
108+Once loaded, it compiles the module. The compiled module is investigated, if it needs any dependencies.
109+
110+For each dependency found, the code tries to load the next module (assuming it is a .wasm unit).
111+
112+The dependency module is loaded, compiled and linked. After it is linked, its exported functions are populated into the Import object.
113+
114+The Import object is used to satisfy the "main.wasm" unit dependencies.
115+
116+Once all imported entities are processed, the main module is finally linked and the main function is executed.
117+
118+``` javascript
119+// only "async" functions are allowed to perform actions "synchronously" via "await" syntax.
120+// Just because "async" functions themselves are performed "on the thread"
121+//
122+// Typically, calling fetch() function returns right away, with the Promise object.
123+// The Promise object should be studied, in order to identify if the job has been finished or not
124+// or an event needs to be assigned that would be called once the job is completed.
125+//
126+// using "await fetch()" syntax is forcing the fetch() operation to perform synchronously
127+// and the next line of code will be executed only after the operation has completed.
128+async function runWasm()
129+{
130+ // Reading the main.wasm file
131+ var r = await fetch('../out/main.wasm');
132+ var bytes = await r.arrayBuffer(); // converting the file to array of bytes
133+
134+ // compilation is also a time-consuming process. Thus, "await" is needed.
135+ // the result of compile is WebAssembly.Module type
136+ var mainmod = await WebAssembly.compile(bytes);
137+
138+ // console.log(mainmod); // print the main module
139+
140+ var impobj = {}; // the Import object is supposed to resolve the main unit dependencies
141+ // originally we set it to an empty object
142+
143+ // asking the compiled module for the list of imported objects
144+ var imports = WebAssembly.Module.imports(mainmod);
145+ // console.log(imports); // print the list of dependencies
146+
147+ // keeping track of loaded dependencies instances
148+ // just to avoid loading the same module twice
149+ var loadedInst = [];
150+
151+ // loading dependencies should be recursive!
152+ // for simplicity, we assume that dependencies
153+ // do not have dependencies themselves.
154+ for (var i = 0; i < imports.length; i++)
155+ {
156+ var dep = imports[i]; // dep contains the fields "module","name" and "kind"
157+
158+ var subinst = loadedInst[dep.module];
159+ if (!subinst)
160+ {
161+ // the module has not been loaded yet, let's load it!
162+ var rr = await fetch('../out/'+dep.module+'.wasm');
163+ var buf = await rr.arrayBuffer();
164+ // try to link the module right away
165+ var submod = await WebAssembly.instantiate(buf);
166+ subinst = submod.instance;
167+ // saving the instance for later use, if it is used more than once
168+ loadedInst[dep.module] = subinst;
169+ }
170+ //console.log(subinst); // print the sub module instance
171+
172+ // adding the module to the list of Import objects (if not there yet)
173+ var impmod = impobj[dep.module];
174+ if (!impmod) {
175+ impmod = {};
176+ impobj[dep.module] = impmod;
177+ }
178+ // extracting the function exported function
179+ impmod[dep.name] = await subinst.exports[dep.name];
180+ impobj[dep.module] = impmod;
181+ }
182+ // console.log(impobj); // print the imported object
183+
184+ // impobj - should now contain all the necessary functions of the main module
185+ // in this example, it should only have
186+ // imbobj.test2.add
187+ var maininst = await WebAssembly.instantiate(mainmod, impobj);
188+ // console.log(maininst); // print the main instance object
189+
190+ // call the main() function of the main unit
191+ document.getElementById("container").textContent = maininst.exports.main();
192+}
193+runWasm();
194+```
195+
196+## See Also
197+
198+- [[WebAssembly]]
199+- [WebAssembly JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly) at MDN
200+
201+---
202+*From the Free Pascal wiki, page "WebAssembly/JS", as it stood on 2021-01-20 after a change by Mischi, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
203+Category: WebAssembly

Back to history