-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathintrinsics.rs
461 lines (420 loc) · 16.1 KB
/
intrinsics.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use crate::source::Source;
use crate::uwrite;
use std::collections::BTreeSet;
use std::fmt::Write;
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Intrinsic {
Base64Compile,
ClampGuest,
ComponentError,
DataView,
EmptyFunc,
F32ToI32,
F64ToI64,
FetchCompile,
GetErrorPayload,
HasOwnProperty,
I32ToF32,
I64ToF64,
InstantiateCore,
IsLE,
SymbolResourceHandle,
SymbolDispose,
ThrowInvalidBool,
ThrowUninitialized,
/// Implementation of https://tc39.es/ecma262/#sec-tobigint64.
ToBigInt64,
/// Implementation of https://tc39.es/ecma262/#sec-tobiguint64.
ToBigUint64,
/// Implementation of https://tc39.es/ecma262/#sec-toint16.
ToInt16,
/// Implementation of https://tc39.es/ecma262/#sec-toint32.
ToInt32,
/// Implementation of https://tc39.es/ecma262/#sec-toint8.
ToInt8,
ToResultString,
/// Implementation of https://tc39.es/ecma262/#sec-tostring.
ToString,
/// Implementation of https://tc39.es/ecma262/#sec-touint16.
ToUint16,
/// Implementation of https://tc39.es/ecma262/#sec-touint32.
ToUint32,
/// Implementation of https://tc39.es/ecma262/#sec-touint8.
ToUint8,
Utf16Decoder,
Utf16Encode,
Utf8Decoder,
Utf8Encode,
Utf8EncodedLen,
ValidateGuestChar,
ValidateHostChar,
}
/// Emits the intrinsic `i` to this file and then returns the name of the
/// intrinsic.
pub fn render_intrinsics(
intrinsics: &mut BTreeSet<Intrinsic>,
no_nodejs_compat: bool,
instantiation: bool,
) -> Source {
let mut output = Source::default();
// Handle intrinsic "dependence"
if intrinsics.contains(&Intrinsic::GetErrorPayload) {
intrinsics.insert(Intrinsic::HasOwnProperty);
}
if intrinsics.contains(&Intrinsic::Utf16Encode) {
intrinsics.insert(Intrinsic::IsLE);
}
if intrinsics.contains(&Intrinsic::F32ToI32) || intrinsics.contains(&Intrinsic::I32ToF32) {
output.push_str(
"
const i32ToF32I = new Int32Array(1);
const i32ToF32F = new Float32Array(i32ToF32I.buffer);
",
);
}
if intrinsics.contains(&Intrinsic::F64ToI64) || intrinsics.contains(&Intrinsic::I64ToF64) {
output.push_str(
"
const i64ToF64I = new BigInt64Array(1);
const i64ToF64F = new Float64Array(i64ToF64I.buffer);
",
);
}
for i in intrinsics.iter() {
match i {
Intrinsic::Base64Compile => if !no_nodejs_compat {
output.push_str("
const base64Compile = str => WebAssembly.compile(typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64') : Uint8Array.from(atob(str), b => b.charCodeAt(0)));
")
} else {
output.push_str("
const base64Compile = str => WebAssembly.compile(Uint8Array.from(atob(str), b => b.charCodeAt(0)));
")
},
Intrinsic::ClampGuest => output.push_str("
function clampGuest(i, min, max) {
if (i < min || i > max) \
throw new TypeError(`must be between ${min} and ${max}`);
return i;
}
"),
Intrinsic::ComponentError => output.push_str("
class ComponentError extends Error {
constructor (value) {
const enumerable = typeof value !== 'string';
super(enumerable ? `${String(value)} (see error.payload)` : value);
Object.defineProperty(this, 'payload', { value, enumerable });
}
}
"),
Intrinsic::DataView => output.push_str("
let dv = new DataView(new ArrayBuffer());
const dataView = mem => dv.buffer === mem.buffer ? dv : dv = new DataView(mem.buffer);
"),
Intrinsic::EmptyFunc => output.push_str("
const emptyFunc = () => {};
"),
Intrinsic::F64ToI64 => output.push_str("
const f64ToI64 = f => (i64ToF64F[0] = f, i64ToF64I[0]);
"),
Intrinsic::FetchCompile => if !no_nodejs_compat {
output.push_str("
const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
let _fs;
async function fetchCompile (url) {
if (isNode) {
_fs = _fs || await import('fs/promises');
return WebAssembly.compile(await _fs.readFile(url));
}
return fetch(url).then(WebAssembly.compileStreaming);
}
")
} else {
output.push_str("
const fetchCompile = url => fetch(url).then(WebAssembly.compileStreaming);
")
},
Intrinsic::GetErrorPayload => {
let hop = Intrinsic::HasOwnProperty.name();
uwrite!(output, "
function getErrorPayload(e) {{
if (e && {hop}.call(e, 'payload')) return e.payload;
return e;
}}
")
},
Intrinsic::HasOwnProperty => output.push_str("
const hasOwnProperty = Object.prototype.hasOwnProperty;
"),
Intrinsic::I32ToF32 => output.push_str("
const i32ToF32 = i => (i32ToF32I[0] = i, i32ToF32F[0]);
"),
Intrinsic::F32ToI32 => output.push_str("
const f32ToI32 = f => (i32ToF32F[0] = f, i32ToF32I[0]);
"),
Intrinsic::I64ToF64 => output.push_str("
const i64ToF64 = i => (i64ToF64I[0] = i, i64ToF64F[0]);
"),
Intrinsic::InstantiateCore => if !instantiation {
output.push_str("
const instantiateCore = WebAssembly.instantiate;
")
},
Intrinsic::IsLE => output.push_str("
const isLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
"),
Intrinsic::SymbolResourceHandle => output.push_str("
const resourceHandleSymbol = Symbol('resource');
"),
Intrinsic::SymbolDispose => output.push_str("
const symbolDispose = Symbol.dispose || Symbol.for('dispose');
"),
Intrinsic::ThrowInvalidBool => output.push_str("
function throwInvalidBool() {
throw new TypeError('invalid variant discriminant for bool');
}
"),
Intrinsic::ThrowUninitialized => output.push_str("
function throwUninitialized() {
throw new TypeError('Wasm uninitialized use `await $init` first');
}
"),
Intrinsic::ToBigInt64 => output.push_str("
const toInt64 = val => BigInt.asIntN(64, BigInt(val));
"),
Intrinsic::ToBigUint64 => output.push_str("
const toUint64 = val => BigInt.asUintN(64, BigInt(val));
"),
Intrinsic::ToInt16 => output.push_str("
function toInt16(val) {
val >>>= 0;
val %= 2 ** 16;
if (val >= 2 ** 15) {
val -= 2 ** 16;
}
return val;
}
"),
Intrinsic::ToInt32 => output.push_str("
function toInt32(val) {
return val >> 0;
}
"),
Intrinsic::ToInt8 => output.push_str("
function toInt8(val) {
val >>>= 0;
val %= 2 ** 8;
if (val >= 2 ** 7) {
val -= 2 ** 8;
}
return val;
}
"),
Intrinsic::ToResultString => output.push_str("
function toResultString(obj) {
return JSON.stringify(obj, (_, v) => {
if (v && Object.getPrototypeOf(v) === Uint8Array.prototype) {
return `[${v[Symbol.toStringTag]} (${v.byteLength})]`;
} else if (typeof v === 'bigint') {
return v.toString();
}
return v;
});
}
"),
// Calling `String` almost directly calls `ToString`, except that it also allows symbols,
// which is why we have the symbol-rejecting branch above.
//
// Definition of `String`: https://tc39.es/ecma262/#sec-string-constructor-string-value
Intrinsic::ToString => output.push_str("
function toString(val) {
if (typeof val === 'symbol') throw new TypeError('symbols cannot be converted to strings');
return String(val);
}
"),
Intrinsic::ToUint16 => output.push_str("
function toUint16(val) {
val >>>= 0;
val %= 2 ** 16;
return val;
}
"),
Intrinsic::ToUint32 => output.push_str("
function toUint32(val) {
return val >>> 0;
}
"),
Intrinsic::ToUint8 => output.push_str("
function toUint8(val) {
val >>>= 0;
val %= 2 ** 8;
return val;
}
"),
Intrinsic::Utf16Decoder => output.push_str("
const utf16Decoder = new TextDecoder('utf-16');
"),
Intrinsic::Utf16Encode => {
let is_le = Intrinsic::IsLE.name();
uwrite!(output, "
function utf16Encode (str, realloc, memory) {{
const len = str.length, ptr = realloc(0, 0, 2, len * 2), out = new Uint16Array(memory.buffer, ptr, len);
let i = 0;
if ({is_le}) {{
while (i < len) out[i] = str.charCodeAt(i++);
}} else {{
while (i < len) {{
const ch = str.charCodeAt(i);
out[i++] = (ch & 0xff) << 8 | ch >>> 8;
}}
}}
return ptr;
}}
");
},
Intrinsic::Utf8Decoder => output.push_str("
const utf8Decoder = new TextDecoder();
"),
Intrinsic::Utf8EncodedLen => {},
Intrinsic::Utf8Encode => output.push_str("
const utf8Encoder = new TextEncoder();
let utf8EncodedLen = 0;
function utf8Encode(s, realloc, memory) {
if (typeof s !== 'string') \
throw new TypeError('expected a string');
if (s.length === 0) {
utf8EncodedLen = 0;
return 1;
}
let allocLen = 0;
let ptr = 0;
let writtenTotal = 0;
while (s.length > 0) {
ptr = realloc(ptr, allocLen, 1, allocLen += s.length * 2);
const { read, written } = utf8Encoder.encodeInto(
s,
new Uint8Array(memory.buffer, ptr + writtenTotal, allocLen - writtenTotal),
);
writtenTotal += written;
s = s.slice(read);
}
utf8EncodedLen = writtenTotal;
return ptr;
}
"),
Intrinsic::ValidateGuestChar => output.push_str("
function validateGuestChar(i) {
if ((i > 0x10ffff) || (i >= 0xd800 && i <= 0xdfff)) \
throw new TypeError(`not a valid char`);
return String.fromCodePoint(i);
}
"),
// TODO: this is incorrect. It at least allows strings of length > 0
// but it probably doesn't do the right thing for unicode or invalid
// utf16 strings either.
Intrinsic::ValidateHostChar => output.push_str("
function validateHostChar(s) {
if (typeof s !== 'string') \
throw new TypeError(`must be a string`);
return s.codePointAt(0);
}
"),
}
}
output
}
impl Intrinsic {
pub fn get_global_names() -> &'static [&'static str] {
&[
"base64Compile",
"BigInt",
"BigInt64Array",
"clampGuest",
"ComponentError",
"dataView",
"DataView",
"dv",
"emptyFunc",
"Error",
"f32ToI32",
"f64ToI64",
"fetch",
"fetchCompile",
"Float32Array",
"Float64Array",
"getErrorPayload",
"hasOwnProperty",
"i32ToF32",
"i64ToF64",
"instantiateCore",
"Int32Array",
"isLE",
"Object",
"process",
"String",
"symbolDispose",
"throwInvalidBool",
"throwUninitialized",
"toInt16",
"toInt32",
"toInt64",
"toInt8",
"toString",
"toUint16",
"toUint32",
"toUint64",
"toUint8",
"TypeError",
"Uint16Array",
"Uint8Array",
"URL",
"utf16Decoder",
"utf16Encode",
"utf8Decoder",
"utf8Encode",
"utf8EncodedLen",
"validateGuestChar",
"validateHostChar",
"WebAssembly",
]
}
pub fn name(&self) -> &'static str {
match self {
Intrinsic::Base64Compile => "base64Compile",
Intrinsic::ClampGuest => "clampGuest",
Intrinsic::ComponentError => "ComponentError",
Intrinsic::DataView => "dataView",
Intrinsic::EmptyFunc => "emptyFunc",
Intrinsic::F32ToI32 => "f32ToI32",
Intrinsic::F64ToI64 => "f64ToI64",
Intrinsic::FetchCompile => "fetchCompile",
Intrinsic::GetErrorPayload => "getErrorPayload",
Intrinsic::HasOwnProperty => "hasOwnProperty",
Intrinsic::I32ToF32 => "i32ToF32",
Intrinsic::I64ToF64 => "i64ToF64",
Intrinsic::InstantiateCore => "instantiateCore",
Intrinsic::IsLE => "isLE",
Intrinsic::SymbolResourceHandle => "resourceHandleSymbol",
Intrinsic::SymbolDispose => "symbolDispose",
Intrinsic::ThrowInvalidBool => "throwInvalidBool",
Intrinsic::ThrowUninitialized => "throwUninitialized",
Intrinsic::ToBigInt64 => "toInt64",
Intrinsic::ToBigUint64 => "toUint64",
Intrinsic::ToInt16 => "toInt16",
Intrinsic::ToInt32 => "toInt32",
Intrinsic::ToInt8 => "toInt8",
Intrinsic::ToResultString => "toResultString",
Intrinsic::ToString => "toString",
Intrinsic::ToUint16 => "toUint16",
Intrinsic::ToUint32 => "toUint32",
Intrinsic::ToUint8 => "toUint8",
Intrinsic::Utf16Decoder => "utf16Decoder",
Intrinsic::Utf16Encode => "utf16Encode",
Intrinsic::Utf8Decoder => "utf8Decoder",
Intrinsic::Utf8Encode => "utf8Encode",
Intrinsic::Utf8EncodedLen => "utf8EncodedLen",
Intrinsic::ValidateGuestChar => "validateGuestChar",
Intrinsic::ValidateHostChar => "validateHostChar",
}
}
}