Skip to content

Commit 41b66fd

Browse files
nschonniHimanshu Garg
authored and
Himanshu Garg
committed
style: run prettier on webassembly (mdn#20405)
1 parent 47c602d commit 41b66fd

File tree

77 files changed

+351
-309
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+351
-309
lines changed

files/en-us/webassembly/c_to_wasm/index.md

Lines changed: 59 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ tags:
99
- WebAssembly
1010
- wasm
1111
---
12+
1213
{{WebAssemblySidebar}}
1314

1415
When you've written a new code module in a language like C/C++, you can compile it into WebAssembly using a tool like [Emscripten](https://emscripten.org/). Let's look at how it works.
@@ -36,20 +37,20 @@ This is the simplest case we'll look at, whereby you get emscripten to generate
3637

3738
1. First we need an example to compile. Take a copy of the following simple C example, and save it in a file called `hello.c` in a new directory on your local drive:
3839

39-
```cpp
40-
#include <stdio.h>
40+
```cpp
41+
#include <stdio.h>
4142

42-
int main() {
43-
printf("Hello World\n");
44-
return 0;
45-
}
46-
```
43+
int main() {
44+
printf("Hello World\n");
45+
return 0;
46+
}
47+
```
4748
4849
2. Now, using the terminal window you used to enter the Emscripten compiler environment, navigate to the same directory as your `hello.c` file, and run the following command:
4950
50-
```bash
51-
emcc hello.c -o hello.html
52-
```
51+
```bash
52+
emcc hello.c -o hello.html
53+
```
5354

5455
The options we've passed in with the command are as follows:
5556

@@ -76,26 +77,26 @@ Sometimes you will want to use a custom HTML template. Let's look at how we can
7677

7778
1. First of all, save the following C code in a file called `hello2.c`, in a new directory:
7879

79-
```cpp
80-
#include <stdio.h>
80+
```cpp
81+
#include <stdio.h>
8182

82-
int main() {
83-
printf("Hello World\n");
84-
return 0;
85-
}
86-
```
83+
int main() {
84+
printf("Hello World\n");
85+
return 0;
86+
}
87+
```
8788
8889
2. Search for the file `shell_minimal.html` in your emsdk repo. Copy it into a subdirectory called `html_template` inside your previous new directory.
8990
3. Now navigate into your new directory (again, in your Emscripten compiler environment terminal window), and run the following command:
9091
91-
```bash
92-
emcc -o hello2.html hello2.c -O3 --shell-file html_template/shell_minimal.html
93-
```
92+
```bash
93+
emcc -o hello2.html hello2.c -O3 --shell-file html_template/shell_minimal.html
94+
```
9495

95-
The options we've passed are slightly different this time:
96+
The options we've passed are slightly different this time:
9697

97-
- We've specified `-o hello2.html`, meaning that the compiler will still output the JavaScript glue code and `.html`.
98-
- We've also specified `--shell-file html_template/shell_minimal.html` — this provides the path to the HTML template you want to use to create the HTML you will run your example through.
98+
- We've specified `-o hello2.html`, meaning that the compiler will still output the JavaScript glue code and `.html`.
99+
- We've also specified `--shell-file html_template/shell_minimal.html` — this provides the path to the HTML template you want to use to create the HTML you will run your example through.
99100

100101
4. Now let's run this example. The above command will have generated `hello2.html`, which will have much the same content as the template with some glue code added into load the generated wasm, run it, etc. Open it in your browser and you'll see much the same output as the last example.
101102

@@ -109,60 +110,58 @@ If you have a function defined in your C code that you want to call as needed fr
109110

110111
1. To start with, save the following code as `hello3.c` in a new directory:
111112

112-
```cpp
113-
#include <stdio.h>
114-
#include <emscripten/emscripten.h>
113+
```cpp
114+
#include <stdio.h>
115+
#include <emscripten/emscripten.h>
115116

116-
int main() {
117-
printf("Hello World\n");
118-
return 0;
119-
}
117+
int main() {
118+
printf("Hello World\n");
119+
return 0;
120+
}
120121

121-
#ifdef __cplusplus
122-
#define EXTERN extern "C"
123-
#else
124-
#define EXTERN
125-
#endif
122+
#ifdef __cplusplus
123+
#define EXTERN extern "C"
124+
#else
125+
#define EXTERN
126+
#endif
126127

127-
EXTERN EMSCRIPTEN_KEEPALIVE void myFunction(int argc, char ** argv) {
128-
printf("MyFunction Called\n");
129-
}
130-
```
128+
EXTERN EMSCRIPTEN_KEEPALIVE void myFunction(int argc, char ** argv) {
129+
printf("MyFunction Called\n");
130+
}
131+
```
131132
132-
By default, Emscripten-generated code always just calls the `main()` function, and other functions are eliminated as dead code. Putting `EMSCRIPTEN_KEEPALIVE` before a function name stops this from happening. You also need to import the `emscripten.h` library to use `EMSCRIPTEN_KEEPALIVE`.
133+
By default, Emscripten-generated code always just calls the `main()` function, and other functions are eliminated as dead code. Putting `EMSCRIPTEN_KEEPALIVE` before a function name stops this from happening. You also need to import the `emscripten.h` library to use `EMSCRIPTEN_KEEPALIVE`.
133134
134-
> **Note:** We are including the `#ifdef` blocks so that if you are trying to include this in C++ code, the example will still work. Due to C versus C++ name mangling rules, this would otherwise break, but here we are setting it so that it treats it as an external C function if you are using C++.
135+
> **Note:** We are including the `#ifdef` blocks so that if you are trying to include this in C++ code, the example will still work. Due to C versus C++ name mangling rules, this would otherwise break, but here we are setting it so that it treats it as an external C function if you are using C++.
135136
136137
2. Now add `html_template/shell_minimal.html` with `\{\{{ SCRIPT }}}` as content into this new directory too, just for convenience (you'd obviously put this in a central place in your real dev environment).
137138
3. Now let's run the compilation step again. From inside your latest directory (and while inside your Emscripten compiler environment terminal window), compile your C code with the following command. (Note that we need to compile with `NO_EXIT_RUNTIME`, which is necessary as otherwise when `main()` exits the runtime would be shut down — necessary for proper C emulation, e.g., atexits are called — and it wouldn't be valid to call compiled code.)
138139
139-
```bash
140-
emcc -o hello3.html hello3.c -O3 --shell-file html_template/shell_minimal.html -s NO_EXIT_RUNTIME=1 -s "EXPORTED_RUNTIME_METHODS=['ccall']"
141-
```
140+
```bash
141+
emcc -o hello3.html hello3.c -O3 --shell-file html_template/shell_minimal.html -s NO_EXIT_RUNTIME=1 -s "EXPORTED_RUNTIME_METHODS=['ccall']"
142+
```
142143

143144
4. If you load the example in your browser again, you'll see the same thing as before!
144145
5. Now we need to run our new `myFunction()` function from JavaScript. First of all, open up your hello3.html file in a text editor.
145146
6. Add a {{HTMLElement("button")}} element as shown below, just above the first opening `<script type='text/javascript'>` tag.
146147

147-
```html
148-
<button id="mybutton">Run myFunction</button>
149-
```
148+
```html
149+
<button id="mybutton">Run myFunction</button>
150+
```
150151

151152
7. Now add the following code at the end of the first {{HTMLElement("script")}} element:
152153

153-
```js
154-
document
155-
.getElementById("mybutton")
156-
.addEventListener("click", () => {
157-
alert("check console");
158-
const result = Module.ccall(
159-
"myFunction", // name of C function
160-
null, // return type
161-
null, // argument types
162-
null, // arguments
163-
);
164-
});
165-
```
154+
```js
155+
document.getElementById("mybutton").addEventListener("click", () => {
156+
alert("check console");
157+
const result = Module.ccall(
158+
"myFunction", // name of C function
159+
null, // return type
160+
null, // argument types
161+
null // arguments
162+
);
163+
});
164+
```
166165

167166
This illustrates how `ccall()` is used to call the exported function.
168167

files/en-us/webassembly/caching_modules/index.md

Lines changed: 47 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ tags:
1010
- compile
1111
- wasm
1212
---
13+
1314
{{WebAssemblySidebar}}
1415

1516
> **Warning:** Experimental {{jsxref("WebAssembly.Module")}} IndexedDB serialization support is being removed from browsers; see {{bug("1469395")}} and [this spec issue](https://github.com/WebAssembly/spec/issues/821).
@@ -43,56 +44,62 @@ function instantiateCachedURL(dbVersion, url, importObject) {
4344
The first helper function contained inside `instantiateCachedURL()``openDatabase()` — creates an object store for storing wasm modules, and also handles clearing out the database if the `dbVersion` is updated; it returns a promise resolving to the new database.
4445
4546
```js
46-
function openDatabase() {
47-
return new Promise((resolve, reject) => {
48-
const request = indexedDB.open(dbName, dbVersion);
49-
request.onerror = reject.bind(null, 'Error opening wasm cache database');
50-
request.onsuccess = () => { resolve(request.result) };
51-
request.onupgradeneeded = (event) => {
52-
const db = request.result;
53-
if (db.objectStoreNames.contains(storeName)) {
54-
console.log(`Clearing out version ${event.oldVersion} wasm cache`);
55-
db.deleteObjectStore(storeName);
56-
}
57-
console.log(`Creating version ${event.newVersion} wasm cache`);
58-
db.createObjectStore(storeName)
59-
};
60-
});
61-
}
47+
function openDatabase() {
48+
return new Promise((resolve, reject) => {
49+
const request = indexedDB.open(dbName, dbVersion);
50+
request.onerror = reject.bind(null, "Error opening wasm cache database");
51+
request.onsuccess = () => {
52+
resolve(request.result);
53+
};
54+
request.onupgradeneeded = (event) => {
55+
const db = request.result;
56+
if (db.objectStoreNames.contains(storeName)) {
57+
console.log(`Clearing out version ${event.oldVersion} wasm cache`);
58+
db.deleteObjectStore(storeName);
59+
}
60+
console.log(`Creating version ${event.newVersion} wasm cache`);
61+
db.createObjectStore(storeName);
62+
};
63+
});
64+
}
6265
```
6366
6467
### Looking up modules in the database
6568
6669
Our next function — `lookupInDatabase()` — provides a simple promise-based operation for looking up the given `url` in the object store we created above. It resolves with the stored compiled module, or rejects with an error.
6770
6871
```js
69-
function lookupInDatabase(db) {
70-
return new Promise((resolve, reject) => {
71-
const store = db.transaction([storeName]).objectStore(storeName);
72-
const request = store.get(url);
73-
request.onerror = reject.bind(null, `Error getting wasm module ${url}`);
74-
request.onsuccess = (event) => {
75-
if (request.result) {
76-
resolve(request.result);
77-
} else {
78-
reject(`Module ${url} was not found in wasm cache`);
79-
}
72+
function lookupInDatabase(db) {
73+
return new Promise((resolve, reject) => {
74+
const store = db.transaction([storeName]).objectStore(storeName);
75+
const request = store.get(url);
76+
request.onerror = reject.bind(null, `Error getting wasm module ${url}`);
77+
request.onsuccess = (event) => {
78+
if (request.result) {
79+
resolve(request.result);
80+
} else {
81+
reject(`Module ${url} was not found in wasm cache`);
8082
}
81-
});
82-
}
83+
};
84+
});
85+
}
8386
```
8487
8588
### Storing and instantiating modules
8689
8790
Next, we define a function `storeInDatabase()` that fires off an async operation to store a given wasm module in a given database.
8891
8992
```js
90-
function storeInDatabase(db, module) {
91-
const store = db.transaction([storeName], 'readwrite').objectStore(storeName);
92-
const request = store.put(module, url);
93-
request.onerror = (err) => { console.log(`Failed to store in wasm cache: ${err}`) };
94-
request.onsuccess = (err) => { console.log(`Successfully stored ${url} in wasm cache`) };
95-
}
93+
function storeInDatabase(db, module) {
94+
const store = db.transaction([storeName], "readwrite").objectStore(storeName);
95+
const request = store.put(module, url);
96+
request.onerror = (err) => {
97+
console.log(`Failed to store in wasm cache: ${err}`);
98+
};
99+
request.onsuccess = (err) => {
100+
console.log(`Successfully stored ${url} in wasm cache`);
101+
};
102+
}
96103
```
97104
98105
### Using our helper functions
@@ -150,11 +157,11 @@ With the above library function defined, getting a wasm module instance and usin
150157
```js
151158
const wasmCacheVersion = 1;
152159

153-
instantiateCachedURL(wasmCacheVersion, 'test.wasm').then((instance) =>
154-
console.log(`Instance says the answer is: ${instance.exports.answer()}`)
155-
).catch((err) =>
156-
console.error(`Failure to instantiate: ${err}`)
157-
);
160+
instantiateCachedURL(wasmCacheVersion, "test.wasm")
161+
.then((instance) =>
162+
console.log(`Instance says the answer is: ${instance.exports.answer()}`)
163+
)
164+
.catch((err) => console.error(`Failure to instantiate: ${err}`));
158165
```
159166

160167
## Browser support

files/en-us/webassembly/concepts/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ tags:
1313
- text format
1414
- web platform
1515
---
16+
1617
{{WebAssemblySidebar}}
1718

1819
This article explains the concepts behind how WebAssembly works including its goals, the problems it solves, and how it runs inside the web browser's rendering engine.

files/en-us/webassembly/existing_c_to_wasm/index.md

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ tags:
88
- WebAssembly
99
- wasm
1010
---
11+
1112
{{WebAssemblySidebar}}
1213

1314
A core use-case for WebAssembly is to take the existing ecosystem of C libraries and allow developers to use them on the web.
@@ -52,7 +53,7 @@ Now you only need some HTML and JavaScript to load your new module:
5253
<script>
5354
Module.onRuntimeInitialized = async () => {
5455
const api = {
55-
version: Module.cwrap('version', 'number', []),
56+
version: Module.cwrap("version", "number", []),
5657
};
5758
console.log(api.version());
5859
};
@@ -72,16 +73,16 @@ Getting the encoder's version number is great, but encoding an actual image woul
7273
The first question you need to answer is: how do I get the image into wasm? Looking at the [encoding API of libwebp](https://developers.google.com/speed/webp/docs/api#simple_encoding_api), you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. Luckily, the Canvas API has {{domxref("CanvasRenderingContext2D.getImageData")}} — that gives you an {{jsxref("Uint8ClampedArray")}} containing the image data in RGBA:
7374

7475
```js
75-
async function loadImage(src) {
76+
async function loadImage(src) {
7677
// Load image
7778
const imgBlob = await fetch(src).then((resp) => resp.blob());
7879
const img = await createImageBitmap(imgBlob);
7980
// Make canvas same size as image
80-
const canvas = document.createElement('canvas');
81+
const canvas = document.createElement("canvas");
8182
canvas.width = img.width;
8283
canvas.height = img.height;
8384
// Draw image onto canvas
84-
const ctx = canvas.getContext('2d');
85+
const ctx = canvas.getContext("2d");
8586
ctx.drawImage(img, 0, 0);
8687
return ctx.getImageData(0, 0, img.width, img.height);
8788
}
@@ -107,16 +108,16 @@ The `create_buffer()` function allocates a buffer for the RGBA image — hence 4
107108
108109
```js
109110
const api = {
110-
version: Module.cwrap('version', 'number', []),
111-
create_buffer: Module.cwrap('create_buffer', 'number', ['number', 'number']),
112-
destroy_buffer: Module.cwrap('destroy_buffer', '', ['number']),
113-
encode: Module.cwrap("encode", "", ["number","number","number","number",]),
111+
version: Module.cwrap("version", "number", []),
112+
create_buffer: Module.cwrap("create_buffer", "number", ["number", "number"]),
113+
destroy_buffer: Module.cwrap("destroy_buffer", "", ["number"]),
114+
encode: Module.cwrap("encode", "", ["number", "number", "number", "number"]),
114115
free_result: Module.cwrap("free_result", "", ["number"]),
115116
get_result_pointer: Module.cwrap("get_result_pointer", "number", []),
116117
get_result_size: Module.cwrap("get_result_size", "number", []),
117118
};
118119
119-
const image = await loadImage('./image.jpg');
120+
const image = await loadImage("./image.jpg");
120121
const p = api.create_buffer(image.width, image.height);
121122
Module.HEAP8.set(image.data, p);
122123
// ... call encoder ...
@@ -164,7 +165,11 @@ Now with all of that in place, you can call the encoding function, grab the poin
164165
api.encode(p, image.width, image.height, 100);
165166
const resultPointer = api.get_result_pointer();
166167
const resultSize = api.get_result_size();
167-
const resultView = new Uint8Array(Module.HEAP8.buffer, resultPointer, resultSize);
168+
const resultView = new Uint8Array(
169+
Module.HEAP8.buffer,
170+
resultPointer,
171+
resultSize
172+
);
168173
const result = new Uint8Array(resultView);
169174
api.free_result(resultPointer);
170175
```
@@ -180,11 +185,11 @@ Luckily, the solution to this problem is in the error message. You just need to
180185
And there you have it. You have compiled a WebP encoder and transcoded a JPEG image to WebP. To prove that it worked, turn your result buffer into a blob and use it on an `<img>` element:
181186

182187
```js
183-
const blob = new Blob([result], {type: 'image/webp'});
188+
const blob = new Blob([result], { type: "image/webp" });
184189
const blobURL = URL.createObjectURL(blob);
185-
const img = document.createElement('img');
190+
const img = document.createElement("img");
186191
img.src = blobURL;
187-
document.body.appendChild(img)
192+
document.body.appendChild(img);
188193
```
189194

190195
Behold, the glory of a new WebP image.

0 commit comments

Comments
 (0)