porffor 0.2.0-50b82f8 → 0.2.0-532d8d0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +128 -78
  3. package/asur/README.md +2 -0
  4. package/asur/index.js +1262 -0
  5. package/byg/index.js +237 -0
  6. package/compiler/2c.js +317 -72
  7. package/compiler/{sections.js → assemble.js} +64 -16
  8. package/compiler/builtins/annexb_string.js +72 -0
  9. package/compiler/builtins/annexb_string.ts +19 -0
  10. package/compiler/builtins/array.ts +145 -0
  11. package/compiler/builtins/base64.ts +151 -0
  12. package/compiler/builtins/crypto.ts +120 -0
  13. package/compiler/builtins/date.ts +498 -0
  14. package/compiler/builtins/escape.ts +141 -0
  15. package/compiler/builtins/int.ts +147 -0
  16. package/compiler/builtins/number.ts +527 -0
  17. package/compiler/builtins/porffor.d.ts +42 -0
  18. package/compiler/builtins/string.ts +1055 -0
  19. package/compiler/builtins/tostring.ts +45 -0
  20. package/compiler/builtins.js +601 -269
  21. package/compiler/{codeGen.js → codegen.js} +1153 -374
  22. package/compiler/decompile.js +3 -3
  23. package/compiler/embedding.js +22 -22
  24. package/compiler/encoding.js +108 -10
  25. package/compiler/generated_builtins.js +939 -0
  26. package/compiler/index.js +36 -34
  27. package/compiler/log.js +6 -3
  28. package/compiler/opt.js +56 -30
  29. package/compiler/parse.js +35 -27
  30. package/compiler/precompile.js +123 -0
  31. package/compiler/prefs.js +26 -0
  32. package/compiler/prototype.js +177 -37
  33. package/compiler/types.js +37 -0
  34. package/compiler/wasmSpec.js +30 -7
  35. package/compiler/wrap.js +137 -42
  36. package/package.json +9 -5
  37. package/porf +4 -0
  38. package/rhemyn/compile.js +5 -3
  39. package/rhemyn/parse.js +323 -320
  40. package/rhemyn/test/parse.js +58 -58
  41. package/runner/compare.js +34 -34
  42. package/runner/debug.js +122 -0
  43. package/runner/index.js +49 -10
  44. package/runner/profiler.js +102 -0
  45. package/runner/repl.js +40 -7
  46. package/runner/sizes.js +37 -37
  47. package/compiler/builtins/base64.js +0 -92
  48. package/runner/info.js +0 -89
  49. package/runner/profile.js +0 -46
  50. package/runner/results.json +0 -1
  51. package/runner/transform.js +0 -15
  52. package/util/enum.js +0 -20
@@ -1,5 +1,5 @@
1
1
  import { Blocktype, Opcodes, Valtype, PageSize, ValtypeSize } from "./wasmSpec.js";
2
- import { ieee754_binary64, signedLEB128, unsignedLEB128 } from "./encoding.js";
2
+ import { ieee754_binary64, signedLEB128, unsignedLEB128, encodeVector } from "./encoding.js";
3
3
  import { operatorOpcode } from "./expression.js";
4
4
  import { BuiltinFuncs, BuiltinVars, importedFuncs, NULL, UNDEFINED } from "./builtins.js";
5
5
  import { PrototypeFuncs } from "./prototype.js";
@@ -7,6 +7,8 @@ import { number, i32x4, enforceOneByte, enforceTwoBytes, enforceFourBytes, enfor
7
7
  import { log } from "./log.js";
8
8
  import parse from "./parse.js";
9
9
  import * as Rhemyn from "../rhemyn/compile.js";
10
+ import Prefs from './prefs.js';
11
+ import { TYPES, TYPE_NAMES } from './types.js';
10
12
 
11
13
  let globals = {};
12
14
  let globalInd = 0;
@@ -23,39 +25,41 @@ const debug = str => {
23
25
  const logChar = n => {
24
26
  code.push(...number(n));
25
27
 
26
- code.push(Opcodes.call);
27
- code.push(...unsignedLEB128(0));
28
+ code.push([ Opcodes.call, 0 ]);
28
29
  };
29
30
 
30
31
  for (let i = 0; i < str.length; i++) {
31
32
  logChar(str.charCodeAt(i));
32
33
  }
33
34
 
34
- logChar('\n'.charCodeAt(0));
35
+ logChar(10); // new line
35
36
 
36
37
  return code;
37
38
  };
38
39
 
39
- const todo = msg => {
40
- class TodoError extends Error {
41
- constructor(message) {
42
- super(message);
43
- this.name = 'TodoError';
44
- }
40
+ class TodoError extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = 'TodoError';
45
44
  }
45
+ }
46
+ const todo = (scope, msg, expectsValue = undefined) => {
47
+ switch (Prefs.todoTime ?? 'runtime') {
48
+ case 'compile':
49
+ throw new TodoError(msg);
46
50
 
47
- throw new TodoError(`todo: ${msg}`);
48
-
49
- const code = [];
50
-
51
- code.push(...debug(`todo! ` + msg));
52
- code.push(Opcodes.unreachable);
51
+ case 'runtime':
52
+ return internalThrow(scope, 'TodoError', msg, expectsValue);
53
53
 
54
- return code;
54
+ // return [
55
+ // ...debug(`todo! ${msg}`),
56
+ // [ Opcodes.unreachable ]
57
+ // ];
58
+ }
55
59
  };
56
60
 
57
61
  const isFuncType = type => type === 'FunctionDeclaration' || type === 'FunctionExpression' || type === 'ArrowFunctionExpression';
58
- const generate = (scope, decl, global = false, name = undefined) => {
62
+ const generate = (scope, decl, global = false, name = undefined, valueUnused = false) => {
59
63
  switch (decl.type) {
60
64
  case 'BinaryExpression':
61
65
  return generateBinaryExp(scope, decl, global, name);
@@ -68,7 +72,12 @@ const generate = (scope, decl, global = false, name = undefined) => {
68
72
 
69
73
  case 'ArrowFunctionExpression':
70
74
  case 'FunctionDeclaration':
71
- generateFunc(scope, decl);
75
+ const func = generateFunc(scope, decl);
76
+
77
+ if (decl.type.endsWith('Expression')) {
78
+ return number(func.index);
79
+ }
80
+
72
81
  return [];
73
82
 
74
83
  case 'BlockStatement':
@@ -81,7 +90,7 @@ const generate = (scope, decl, global = false, name = undefined) => {
81
90
  return generateExp(scope, decl);
82
91
 
83
92
  case 'CallExpression':
84
- return generateCall(scope, decl, global, name);
93
+ return generateCall(scope, decl, global, name, valueUnused);
85
94
 
86
95
  case 'NewExpression':
87
96
  return generateNew(scope, decl, global, name);
@@ -99,7 +108,7 @@ const generate = (scope, decl, global = false, name = undefined) => {
99
108
  return generateUnary(scope, decl);
100
109
 
101
110
  case 'UpdateExpression':
102
- return generateUpdate(scope, decl);
111
+ return generateUpdate(scope, decl, global, name, valueUnused);
103
112
 
104
113
  case 'IfStatement':
105
114
  return generateIf(scope, decl);
@@ -110,6 +119,9 @@ const generate = (scope, decl, global = false, name = undefined) => {
110
119
  case 'WhileStatement':
111
120
  return generateWhile(scope, decl);
112
121
 
122
+ case 'DoWhileStatement':
123
+ return generateDoWhile(scope, decl);
124
+
113
125
  case 'ForOfStatement':
114
126
  return generateForOf(scope, decl);
115
127
 
@@ -119,6 +131,9 @@ const generate = (scope, decl, global = false, name = undefined) => {
119
131
  case 'ContinueStatement':
120
132
  return generateContinue(scope, decl);
121
133
 
134
+ case 'LabeledStatement':
135
+ return generateLabel(scope, decl);
136
+
122
137
  case 'EmptyStatement':
123
138
  return generateEmpty(scope, decl);
124
139
 
@@ -132,7 +147,7 @@ const generate = (scope, decl, global = false, name = undefined) => {
132
147
  return generateTry(scope, decl);
133
148
 
134
149
  case 'DebuggerStatement':
135
- // todo: add fancy terminal debugger?
150
+ // todo: hook into terminal debugger
136
151
  return [];
137
152
 
138
153
  case 'ArrayExpression':
@@ -146,16 +161,22 @@ const generate = (scope, decl, global = false, name = undefined) => {
146
161
  const funcsBefore = funcs.length;
147
162
  generate(scope, decl.declaration);
148
163
 
149
- if (funcsBefore === funcs.length) throw new Error('no new func added in export');
164
+ if (funcsBefore !== funcs.length) {
165
+ // new func added
166
+ const newFunc = funcs[funcs.length - 1];
167
+ newFunc.export = true;
168
+ }
169
+
170
+ // if (funcsBefore === funcs.length) throw new Error('no new func added in export');
150
171
 
151
- const newFunc = funcs[funcs.length - 1];
152
- newFunc.export = true;
172
+ // const newFunc = funcs[funcs.length - 1];
173
+ // newFunc.export = true;
153
174
 
154
175
  return [];
155
176
 
156
177
  case 'TaggedTemplateExpression': {
157
178
  const funcs = {
158
- asm: str => {
179
+ __Porffor_wasm: str => {
159
180
  let out = [];
160
181
 
161
182
  for (const line of str.split('\n')) {
@@ -163,8 +184,8 @@ const generate = (scope, decl, global = false, name = undefined) => {
163
184
  if (asm[0] === '') continue; // blank
164
185
 
165
186
  if (asm[0] === 'local') {
166
- const [ name, idx, type ] = asm.slice(1);
167
- scope.locals[name] = { idx: parseInt(idx), type: Valtype[type] };
187
+ const [ name, type ] = asm.slice(1);
188
+ scope.locals[name] = { idx: scope.localInd++, type: Valtype[type] };
168
189
  continue;
169
190
  }
170
191
 
@@ -174,7 +195,7 @@ const generate = (scope, decl, global = false, name = undefined) => {
174
195
  }
175
196
 
176
197
  if (asm[0] === 'memory') {
177
- allocPage('asm instrinsic');
198
+ allocPage(scope, 'asm instrinsic');
178
199
  // todo: add to store/load offset insts
179
200
  continue;
180
201
  }
@@ -183,7 +204,11 @@ const generate = (scope, decl, global = false, name = undefined) => {
183
204
  if (!inst) throw new Error(`inline asm: inst ${asm[0]} not found`);
184
205
 
185
206
  if (!Array.isArray(inst)) inst = [ inst ];
186
- const immediates = asm.slice(1).map(x => parseInt(x));
207
+ const immediates = asm.slice(1).map(x => {
208
+ const int = parseInt(x);
209
+ if (Number.isNaN(int)) return scope.locals[x]?.idx;
210
+ return int;
211
+ });
187
212
 
188
213
  out.push([ ...inst, ...immediates ]);
189
214
  }
@@ -191,35 +216,53 @@ const generate = (scope, decl, global = false, name = undefined) => {
191
216
  return out;
192
217
  },
193
218
 
194
- __internal_print_type: str => {
195
- const type = getType(scope, str) - TYPES.number;
219
+ __Porffor_bs: str => [
220
+ ...makeString(scope, str, global, name, true),
196
221
 
197
- return [
198
- ...number(type),
199
- [ Opcodes.call, importedFuncs.print ],
222
+ ...(name ? setType(scope, name, TYPES._bytestring) : [
223
+ ...number(TYPES._bytestring, Valtype.i32),
224
+ ...setLastType(scope)
225
+ ])
226
+ ],
227
+ __Porffor_s: str => [
228
+ ...makeString(scope, str, global, name, false),
200
229
 
201
- // newline
202
- ...number(10),
203
- [ Opcodes.call, importedFuncs.printChar ]
204
- ];
205
- }
206
- }
230
+ ...(name ? setType(scope, name, TYPES.string) : [
231
+ ...number(TYPES.string, Valtype.i32),
232
+ ...setLastType(scope)
233
+ ])
234
+ ],
235
+ };
207
236
 
208
- const name = decl.tag.name;
237
+ const func = decl.tag.name;
209
238
  // hack for inline asm
210
- if (!funcs[name]) return todo('tagged template expressions not implemented');
239
+ if (!funcs[func]) return todo(scope, 'tagged template expressions not implemented', true);
240
+
241
+ const { quasis, expressions } = decl.quasi;
242
+ let str = quasis[0].value.raw;
243
+
244
+ for (let i = 0; i < expressions.length; i++) {
245
+ const e = expressions[i];
246
+ if (!e.name) {
247
+ if (e.type === 'BinaryExpression' && e.operator === '+' && e.left.type === 'Identifier' && e.right.type === 'Literal') {
248
+ str += lookupName(scope, e.left.name)[0].idx + e.right.value;
249
+ } else todo(scope, 'unsupported expression in intrinsic');
250
+ } else str += lookupName(scope, e.name)[0].idx;
251
+
252
+ str += quasis[i + 1].value.raw;
253
+ }
211
254
 
212
- const str = decl.quasi.quasis[0].value.raw;
213
- return funcs[name](str);
255
+ return funcs[func](str);
214
256
  }
215
257
 
216
258
  default:
217
- if (decl.type.startsWith('TS')) {
218
- // ignore typescript nodes
259
+ // ignore typescript nodes
260
+ if (decl.type.startsWith('TS') ||
261
+ decl.type === 'ImportDeclaration' && decl.importKind === 'type') {
219
262
  return [];
220
263
  }
221
264
 
222
- return todo(`no generation for ${decl.type}!`);
265
+ return todo(scope, `no generation for ${decl.type}!`);
223
266
  }
224
267
  };
225
268
 
@@ -247,7 +290,7 @@ const lookupName = (scope, _name) => {
247
290
  return [ undefined, undefined ];
248
291
  };
249
292
 
250
- const internalThrow = (scope, constructor, message, expectsValue = false) => [
293
+ const internalThrow = (scope, constructor, message, expectsValue = Prefs.alwaysValueInternalThrows) => [
251
294
  ...generateThrow(scope, {
252
295
  argument: {
253
296
  type: 'NewExpression',
@@ -269,25 +312,33 @@ const generateIdent = (scope, decl) => {
269
312
  const name = mapName(rawName);
270
313
  let local = scope.locals[rawName];
271
314
 
272
- if (builtinVars[name]) {
315
+ if (Object.hasOwn(builtinVars, name)) {
273
316
  if (builtinVars[name].floatOnly && valtype[0] === 'i') throw new Error(`Cannot use ${unhackName(name)} with integer valtype`);
274
- return builtinVars[name];
317
+
318
+ let wasm = builtinVars[name];
319
+ if (typeof wasm === 'function') wasm = asmFuncToAsm(wasm, { name });
320
+ return wasm.slice();
321
+ }
322
+
323
+ if (Object.hasOwn(builtinFuncs, name) || Object.hasOwn(internalConstrs, name)) {
324
+ // todo: return an actual something
325
+ return number(1);
275
326
  }
276
327
 
277
- if (builtinFuncs[name] || internalConstrs[name]) {
328
+ if (isExistingProtoFunc(name)) {
278
329
  // todo: return an actual something
279
330
  return number(1);
280
331
  }
281
332
 
282
- if (local === undefined) {
333
+ if (local?.idx === undefined) {
283
334
  // no local var with name
284
- if (importedFuncs.hasOwnProperty(name)) return number(importedFuncs[name]);
285
- if (funcIndex[name] !== undefined) return number(funcIndex[name]);
335
+ if (Object.hasOwn(importedFuncs, name)) return number(importedFuncs[name]);
336
+ if (Object.hasOwn(funcIndex, name)) return number(funcIndex[name]);
286
337
 
287
- if (globals[name] !== undefined) return [ [ Opcodes.global_get, globals[name].idx ] ];
338
+ if (Object.hasOwn(globals, name)) return [ [ Opcodes.global_get, globals[name].idx ] ];
288
339
  }
289
340
 
290
- if (local === undefined && rawName.startsWith('__')) {
341
+ if (local?.idx === undefined && rawName.startsWith('__')) {
291
342
  // return undefined if unknown key in already known var
292
343
  let parent = rawName.slice(2).split('_').slice(0, -1).join('_');
293
344
  if (parent.includes('_')) parent = '__' + parent;
@@ -296,7 +347,7 @@ const generateIdent = (scope, decl) => {
296
347
  if (!parentLookup[1]) return number(UNDEFINED);
297
348
  }
298
349
 
299
- if (local === undefined) return internalThrow(scope, 'ReferenceError', `${unhackName(name)} is not defined`, true);
350
+ if (local?.idx === undefined) return internalThrow(scope, 'ReferenceError', `${unhackName(name)} is not defined`, true);
300
351
 
301
352
  return [ [ Opcodes.local_get, local.idx ] ];
302
353
  };
@@ -309,14 +360,18 @@ const generateReturn = (scope, decl) => {
309
360
  // just bare "return"
310
361
  return [
311
362
  ...number(UNDEFINED), // "undefined" if func returns
312
- ...number(TYPES.undefined, Valtype.i32), // type undefined
363
+ ...(scope.returnType != null ? [] : [
364
+ ...number(TYPES.undefined, Valtype.i32) // type undefined
365
+ ]),
313
366
  [ Opcodes.return ]
314
367
  ];
315
368
  }
316
369
 
317
370
  return [
318
371
  ...generate(scope, decl.argument),
319
- ...getNodeType(scope, decl.argument),
372
+ ...(scope.returnType != null ? [] : [
373
+ ...getNodeType(scope, decl.argument)
374
+ ]),
320
375
  [ Opcodes.return ]
321
376
  ];
322
377
  };
@@ -330,7 +385,8 @@ const localTmp = (scope, name, type = valtypeBinary) => {
330
385
  return idx;
331
386
  };
332
387
 
333
- const isIntOp = op => op && (op[0] >= 0xb7 && op[0] <= 0xba);
388
+ const isIntOp = op => op && ((op[0] >= 0x45 && op[0] <= 0x4f) || (op[0] >= 0x67 && op[0] <= 0x78) || op[0] === 0x41);
389
+ const isFloatToIntOp = op => op && (op[0] >= 0xb7 && op[0] <= 0xba);
334
390
 
335
391
  const performLogicOp = (scope, op, left, right, leftType, rightType) => {
336
392
  const checks = {
@@ -339,7 +395,7 @@ const performLogicOp = (scope, op, left, right, leftType, rightType) => {
339
395
  '??': nullish
340
396
  };
341
397
 
342
- if (!checks[op]) return todo(`logic operator ${op} not implemented yet`);
398
+ if (!checks[op]) return todo(scope, `logic operator ${op} not implemented yet`, true);
343
399
 
344
400
  // generic structure for {a} OP {b}
345
401
  // -->
@@ -347,8 +403,8 @@ const performLogicOp = (scope, op, left, right, leftType, rightType) => {
347
403
 
348
404
  // if we can, use int tmp and convert at the end to help prevent unneeded conversions
349
405
  // (like if we are in an if condition - very common)
350
- const leftIsInt = isIntOp(left[left.length - 1]);
351
- const rightIsInt = isIntOp(right[right.length - 1]);
406
+ const leftIsInt = isFloatToIntOp(left[left.length - 1]);
407
+ const rightIsInt = isFloatToIntOp(right[right.length - 1]);
352
408
 
353
409
  const canInt = leftIsInt && rightIsInt;
354
410
 
@@ -365,12 +421,12 @@ const performLogicOp = (scope, op, left, right, leftType, rightType) => {
365
421
  ...right,
366
422
  // note type
367
423
  ...rightType,
368
- setLastType(scope),
424
+ ...setLastType(scope),
369
425
  [ Opcodes.else ],
370
426
  [ Opcodes.local_get, localTmp(scope, 'logictmpi', Valtype.i32) ],
371
427
  // note type
372
428
  ...leftType,
373
- setLastType(scope),
429
+ ...setLastType(scope),
374
430
  [ Opcodes.end ],
375
431
  Opcodes.i32_from
376
432
  ];
@@ -384,17 +440,17 @@ const performLogicOp = (scope, op, left, right, leftType, rightType) => {
384
440
  ...right,
385
441
  // note type
386
442
  ...rightType,
387
- setLastType(scope),
443
+ ...setLastType(scope),
388
444
  [ Opcodes.else ],
389
445
  [ Opcodes.local_get, localTmp(scope, 'logictmp') ],
390
446
  // note type
391
447
  ...leftType,
392
- setLastType(scope),
448
+ ...setLastType(scope),
393
449
  [ Opcodes.end ]
394
450
  ];
395
451
  };
396
452
 
397
- const concatStrings = (scope, left, right, global, name, assign) => {
453
+ const concatStrings = (scope, left, right, global, name, assign = false, bytestrings = false) => {
398
454
  // todo: this should be rewritten into a built-in/func: String.prototype.concat
399
455
  // todo: convert left and right to strings if not
400
456
  // todo: optimize by looking up names in arrays and using that if exists?
@@ -404,11 +460,8 @@ const concatStrings = (scope, left, right, global, name, assign) => {
404
460
  const rightLength = localTmp(scope, 'concat_right_length', Valtype.i32);
405
461
  const leftLength = localTmp(scope, 'concat_left_length', Valtype.i32);
406
462
 
407
- const aotWFA = process.argv.includes('-aot-well-formed-string-approximation');
408
- if (aotWFA) addVarMeta(name, { wellFormed: undefined });
409
-
410
463
  if (assign) {
411
- const pointer = arrays.get(name ?? '$undeclared');
464
+ const pointer = scope.arrays?.get(name ?? '$undeclared');
412
465
 
413
466
  return [
414
467
  // setup right
@@ -433,11 +486,11 @@ const concatStrings = (scope, left, right, global, name, assign) => {
433
486
  [ Opcodes.i32_store, Math.log2(ValtypeSize.i32) - 1, ...unsignedLEB128(pointer) ],
434
487
 
435
488
  // copy right
436
- // dst = out pointer + length size + current length * i16 size
489
+ // dst = out pointer + length size + current length * sizeof valtype
437
490
  ...number(pointer + ValtypeSize.i32, Valtype.i32),
438
491
 
439
492
  [ Opcodes.local_get, leftLength ],
440
- ...number(ValtypeSize.i16, Valtype.i32),
493
+ ...number(bytestrings ? ValtypeSize.i8 : ValtypeSize.i16, Valtype.i32),
441
494
  [ Opcodes.i32_mul ],
442
495
  [ Opcodes.i32_add ],
443
496
 
@@ -446,9 +499,9 @@ const concatStrings = (scope, left, right, global, name, assign) => {
446
499
  ...number(ValtypeSize.i32, Valtype.i32),
447
500
  [ Opcodes.i32_add ],
448
501
 
449
- // size = right length * i16 size
502
+ // size = right length * sizeof valtype
450
503
  [ Opcodes.local_get, rightLength ],
451
- ...number(ValtypeSize.i16, Valtype.i32),
504
+ ...number(bytestrings ? ValtypeSize.i8 : ValtypeSize.i16, Valtype.i32),
452
505
  [ Opcodes.i32_mul ],
453
506
 
454
507
  [ ...Opcodes.memory_copy, 0x00, 0x00 ],
@@ -506,11 +559,11 @@ const concatStrings = (scope, left, right, global, name, assign) => {
506
559
  [ ...Opcodes.memory_copy, 0x00, 0x00 ],
507
560
 
508
561
  // copy right
509
- // dst = out pointer + length size + left length * i16 size
562
+ // dst = out pointer + length size + left length * sizeof valtype
510
563
  ...number(pointer + ValtypeSize.i32, Valtype.i32),
511
564
 
512
565
  [ Opcodes.local_get, leftLength ],
513
- ...number(ValtypeSize.i16, Valtype.i32),
566
+ ...number(bytestrings ? ValtypeSize.i8 : ValtypeSize.i16, Valtype.i32),
514
567
  [ Opcodes.i32_mul ],
515
568
  [ Opcodes.i32_add ],
516
569
 
@@ -519,9 +572,9 @@ const concatStrings = (scope, left, right, global, name, assign) => {
519
572
  ...number(ValtypeSize.i32, Valtype.i32),
520
573
  [ Opcodes.i32_add ],
521
574
 
522
- // size = right length * i16 size
575
+ // size = right length * sizeof valtype
523
576
  [ Opcodes.local_get, rightLength ],
524
- ...number(ValtypeSize.i16, Valtype.i32),
577
+ ...number(bytestrings ? ValtypeSize.i8 : ValtypeSize.i16, Valtype.i32),
525
578
  [ Opcodes.i32_mul ],
526
579
 
527
580
  [ ...Opcodes.memory_copy, 0x00, 0x00 ],
@@ -531,7 +584,7 @@ const concatStrings = (scope, left, right, global, name, assign) => {
531
584
  ];
532
585
  };
533
586
 
534
- const compareStrings = (scope, left, right) => {
587
+ const compareStrings = (scope, left, right, bytestrings = false) => {
535
588
  // todo: this should be rewritten into a func
536
589
  // todo: convert left and right to strings if not
537
590
  // todo: optimize by looking up names in arrays and using that if exists?
@@ -540,7 +593,6 @@ const compareStrings = (scope, left, right) => {
540
593
  const leftPointer = localTmp(scope, 'compare_left_pointer', Valtype.i32);
541
594
  const leftLength = localTmp(scope, 'compare_left_length', Valtype.i32);
542
595
  const rightPointer = localTmp(scope, 'compare_right_pointer', Valtype.i32);
543
- const rightLength = localTmp(scope, 'compare_right_length', Valtype.i32);
544
596
 
545
597
  const index = localTmp(scope, 'compare_index', Valtype.i32);
546
598
  const indexEnd = localTmp(scope, 'compare_index_end', Valtype.i32);
@@ -568,7 +620,6 @@ const compareStrings = (scope, left, right) => {
568
620
 
569
621
  [ Opcodes.local_get, rightPointer ],
570
622
  [ Opcodes.i32_load, Math.log2(ValtypeSize[valtype]) - 1, ...unsignedLEB128(0) ],
571
- [ Opcodes.local_tee, rightLength ],
572
623
 
573
624
  // fast path: check leftLength != rightLength
574
625
  [ Opcodes.i32_ne ],
@@ -583,11 +634,13 @@ const compareStrings = (scope, left, right) => {
583
634
  ...number(0, Valtype.i32),
584
635
  [ Opcodes.local_set, index ],
585
636
 
586
- // setup index end as length * sizeof i16 (2)
637
+ // setup index end as length * sizeof valtype (1 for bytestring, 2 for string)
587
638
  // we do this instead of having to do mul/div each iter for perf™
588
639
  [ Opcodes.local_get, leftLength ],
589
- ...number(ValtypeSize.i16, Valtype.i32),
590
- [ Opcodes.i32_mul ],
640
+ ...(bytestrings ? [] : [
641
+ ...number(ValtypeSize.i16, Valtype.i32),
642
+ [ Opcodes.i32_mul ],
643
+ ]),
591
644
  [ Opcodes.local_set, indexEnd ],
592
645
 
593
646
  // iterate over each char and check if eq
@@ -597,13 +650,17 @@ const compareStrings = (scope, left, right) => {
597
650
  [ Opcodes.local_get, index ],
598
651
  [ Opcodes.local_get, leftPointer ],
599
652
  [ Opcodes.i32_add ],
600
- [ Opcodes.i32_load16_u, Math.log2(ValtypeSize.i16) - 1, ...unsignedLEB128(ValtypeSize.i32) ],
653
+ bytestrings ?
654
+ [ Opcodes.i32_load8_u, 0, ValtypeSize.i32 ] :
655
+ [ Opcodes.i32_load16_u, Math.log2(ValtypeSize.i16) - 1, ValtypeSize.i32 ],
601
656
 
602
657
  // fetch right
603
658
  [ Opcodes.local_get, index ],
604
659
  [ Opcodes.local_get, rightPointer ],
605
660
  [ Opcodes.i32_add ],
606
- [ Opcodes.i32_load16_u, Math.log2(ValtypeSize.i16) - 1, ...unsignedLEB128(ValtypeSize.i32) ],
661
+ bytestrings ?
662
+ [ Opcodes.i32_load8_u, 0, ValtypeSize.i32 ] :
663
+ [ Opcodes.i32_load16_u, Math.log2(ValtypeSize.i16) - 1, ValtypeSize.i32 ],
607
664
 
608
665
  // not equal, "return" false
609
666
  [ Opcodes.i32_ne ],
@@ -612,13 +669,13 @@ const compareStrings = (scope, left, right) => {
612
669
  [ Opcodes.br, 2 ],
613
670
  [ Opcodes.end ],
614
671
 
615
- // index += sizeof i16 (2)
672
+ // index += sizeof valtype (1 for bytestring, 2 for string)
616
673
  [ Opcodes.local_get, index ],
617
- ...number(ValtypeSize.i16, Valtype.i32),
674
+ ...number(bytestrings ? ValtypeSize.i8 : ValtypeSize.i16, Valtype.i32),
618
675
  [ Opcodes.i32_add ],
619
676
  [ Opcodes.local_tee, index ],
620
677
 
621
- // if index != index end (length * sizeof 16), loop
678
+ // if index != index end (length * sizeof valtype), loop
622
679
  [ Opcodes.local_get, indexEnd ],
623
680
  [ Opcodes.i32_ne ],
624
681
  [ Opcodes.br_if, 0 ],
@@ -639,16 +696,18 @@ const compareStrings = (scope, left, right) => {
639
696
  };
640
697
 
641
698
  const truthy = (scope, wasm, type, intIn = false, intOut = false) => {
642
- if (isIntOp(wasm[wasm.length - 1])) return [
699
+ if (isFloatToIntOp(wasm[wasm.length - 1])) return [
643
700
  ...wasm,
644
701
  ...(!intIn && intOut ? [ Opcodes.i32_to_u ] : [])
645
702
  ];
703
+ // if (isIntOp(wasm[wasm.length - 1])) return [ ...wasm ];
646
704
 
647
- const tmp = localTmp(scope, `$logicinner_tmp${intIn ? '_int' : ''}`, intIn ? Valtype.i32 : valtypeBinary);
705
+ const useTmp = knownType(scope, type) == null;
706
+ const tmp = useTmp && localTmp(scope, `#logicinner_tmp${intIn ? '_int' : ''}`, intIn ? Valtype.i32 : valtypeBinary);
648
707
 
649
708
  const def = [
650
709
  // if value != 0
651
- [ Opcodes.local_get, tmp ],
710
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
652
711
 
653
712
  // ...(intIn ? [ [ Opcodes.i32_eqz ] ] : [ ...Opcodes.eqz ]),
654
713
  ...(!intOut || (intIn && intOut) ? [] : [ Opcodes.i32_to_u ]),
@@ -660,7 +719,7 @@ const truthy = (scope, wasm, type, intIn = false, intOut = false) => {
660
719
 
661
720
  return [
662
721
  ...wasm,
663
- [ Opcodes.local_set, tmp ],
722
+ ...(!useTmp ? [] : [ [ Opcodes.local_set, tmp ] ]),
664
723
 
665
724
  ...typeSwitch(scope, type, {
666
725
  // [TYPES.number]: def,
@@ -669,7 +728,7 @@ const truthy = (scope, wasm, type, intIn = false, intOut = false) => {
669
728
  ...number(1, intOut ? Valtype.i32 : valtypeBinary)
670
729
  ],
671
730
  [TYPES.string]: [
672
- [ Opcodes.local_get, tmp ],
731
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
673
732
  ...(intIn ? [] : [ Opcodes.i32_to_u ]),
674
733
 
675
734
  // get length
@@ -680,16 +739,27 @@ const truthy = (scope, wasm, type, intIn = false, intOut = false) => {
680
739
  [ Opcodes.i32_eqz ], */
681
740
  ...(intOut ? [] : [ Opcodes.i32_from_u ])
682
741
  ],
742
+ [TYPES._bytestring]: [ // duplicate of string
743
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
744
+ ...(intIn ? [] : [ Opcodes.i32_to_u ]),
745
+
746
+ // get length
747
+ [ Opcodes.i32_load, Math.log2(ValtypeSize.i32) - 1, 0 ],
748
+
749
+ ...(intOut ? [] : [ Opcodes.i32_from_u ])
750
+ ],
683
751
  default: def
684
752
  }, intOut ? Valtype.i32 : valtypeBinary)
685
753
  ];
686
754
  };
687
755
 
688
756
  const falsy = (scope, wasm, type, intIn = false, intOut = false) => {
689
- const tmp = localTmp(scope, `$logicinner_tmp${intIn ? '_int' : ''}`, intIn ? Valtype.i32 : valtypeBinary);
757
+ const useTmp = knownType(scope, type) == null;
758
+ const tmp = useTmp && localTmp(scope, `#logicinner_tmp${intIn ? '_int' : ''}`, intIn ? Valtype.i32 : valtypeBinary);
759
+
690
760
  return [
691
761
  ...wasm,
692
- [ Opcodes.local_set, tmp ],
762
+ ...(!useTmp ? [] : [ [ Opcodes.local_set, tmp ] ]),
693
763
 
694
764
  ...typeSwitch(scope, type, {
695
765
  [TYPES._array]: [
@@ -697,7 +767,18 @@ const falsy = (scope, wasm, type, intIn = false, intOut = false) => {
697
767
  ...number(0, intOut ? Valtype.i32 : valtypeBinary)
698
768
  ],
699
769
  [TYPES.string]: [
700
- [ Opcodes.local_get, tmp ],
770
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
771
+ ...(intIn ? [] : [ Opcodes.i32_to_u ]),
772
+
773
+ // get length
774
+ [ Opcodes.i32_load, Math.log2(ValtypeSize.i32) - 1, 0 ],
775
+
776
+ // if length == 0
777
+ [ Opcodes.i32_eqz ],
778
+ ...(intOut ? [] : [ Opcodes.i32_from_u ])
779
+ ],
780
+ [TYPES._bytestring]: [ // duplicate of string
781
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
701
782
  ...(intIn ? [] : [ Opcodes.i32_to_u ]),
702
783
 
703
784
  // get length
@@ -709,7 +790,7 @@ const falsy = (scope, wasm, type, intIn = false, intOut = false) => {
709
790
  ],
710
791
  default: [
711
792
  // if value == 0
712
- [ Opcodes.local_get, tmp ],
793
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
713
794
 
714
795
  ...(intIn ? [ [ Opcodes.i32_eqz ] ] : [ ...Opcodes.eqz ]),
715
796
  ...(intOut ? [] : [ Opcodes.i32_from_u ])
@@ -719,10 +800,12 @@ const falsy = (scope, wasm, type, intIn = false, intOut = false) => {
719
800
  };
720
801
 
721
802
  const nullish = (scope, wasm, type, intIn = false, intOut = false) => {
722
- const tmp = localTmp(scope, `$logicinner_tmp${intIn ? '_int' : ''}`, intIn ? Valtype.i32 : valtypeBinary);
803
+ const useTmp = knownType(scope, type) == null;
804
+ const tmp = useTmp && localTmp(scope, `#logicinner_tmp${intIn ? '_int' : ''}`, intIn ? Valtype.i32 : valtypeBinary);
805
+
723
806
  return [
724
807
  ...wasm,
725
- [ Opcodes.local_set, tmp ],
808
+ ...(!useTmp ? [] : [ [ Opcodes.local_set, tmp ] ]),
726
809
 
727
810
  ...typeSwitch(scope, type, {
728
811
  [TYPES.undefined]: [
@@ -731,7 +814,7 @@ const nullish = (scope, wasm, type, intIn = false, intOut = false) => {
731
814
  ],
732
815
  [TYPES.object]: [
733
816
  // object, null if == 0
734
- [ Opcodes.local_get, tmp ],
817
+ ...(!useTmp ? [] : [ [ Opcodes.local_get, tmp ] ]),
735
818
 
736
819
  ...(intIn ? [ [ Opcodes.i32_eqz ] ] : [ ...Opcodes.eqz ]),
737
820
  ...(intOut ? [] : [ Opcodes.i32_from_u ])
@@ -760,11 +843,14 @@ const performOp = (scope, op, left, right, leftType, rightType, _global = false,
760
843
  return performLogicOp(scope, op, left, right, leftType, rightType);
761
844
  }
762
845
 
846
+ const knownLeft = knownType(scope, leftType);
847
+ const knownRight = knownType(scope, rightType);
848
+
763
849
  const eqOp = ['==', '===', '!=', '!==', '>', '>=', '<', '<='].includes(op);
764
850
  const strictOp = op === '===' || op === '!==';
765
851
 
766
852
  const startOut = [], endOut = [];
767
- const finalise = out => startOut.concat(out, endOut);
853
+ const finalize = out => startOut.concat(out, endOut);
768
854
 
769
855
  // if strict (in)equal check types match
770
856
  if (strictOp) {
@@ -809,31 +895,59 @@ const performOp = (scope, op, left, right, leftType, rightType, _global = false,
809
895
  // todo: if equality op and an operand is undefined, return false
810
896
  // todo: niche null hell with 0
811
897
 
812
- // if (leftType === TYPES.string || rightType === TYPES.string) {
813
- // if (op === '+') {
814
- // // string concat (a + b)
815
- // return finalise(concatStrings(scope, left, right, _global, _name, assign));
816
- // }
817
-
818
- // // not an equality op, NaN
819
- // if (!eqOp) return finalise(number(NaN));
820
-
821
- // // else leave bool ops
822
- // // todo: convert string to number if string and number/bool
823
- // // todo: string (>|>=|<|<=) string
824
-
825
- // // string comparison
826
- // if (op === '===' || op === '==') {
827
- // return finalise(compareStrings(scope, left, right));
828
- // }
829
-
830
- // if (op === '!==' || op === '!=') {
831
- // return finalise([
832
- // ...compareStrings(scope, left, right),
833
- // [ Opcodes.i32_eqz ]
834
- // ]);
835
- // }
836
- // }
898
+ if (knownLeft === TYPES.string || knownRight === TYPES.string) {
899
+ if (op === '+') {
900
+ // todo: this should be dynamic too but for now only static
901
+ // string concat (a + b)
902
+ return concatStrings(scope, left, right, _global, _name, assign, false);
903
+ }
904
+
905
+ // not an equality op, NaN
906
+ if (!eqOp) return number(NaN);
907
+
908
+ // else leave bool ops
909
+ // todo: convert string to number if string and number/bool
910
+ // todo: string (>|>=|<|<=) string
911
+
912
+ // string comparison
913
+ if (op === '===' || op === '==') {
914
+ return compareStrings(scope, left, right);
915
+ }
916
+
917
+ if (op === '!==' || op === '!=') {
918
+ return [
919
+ ...compareStrings(scope, left, right),
920
+ [ Opcodes.i32_eqz ]
921
+ ];
922
+ }
923
+ }
924
+
925
+ if (knownLeft === TYPES._bytestring || knownRight === TYPES._bytestring) {
926
+ if (op === '+') {
927
+ // todo: this should be dynamic too but for now only static
928
+ // string concat (a + b)
929
+ return concatStrings(scope, left, right, _global, _name, assign, true);
930
+ }
931
+
932
+ // not an equality op, NaN
933
+ if (!eqOp) return number(NaN);
934
+
935
+ // else leave bool ops
936
+ // todo: convert string to number if string and number/bool
937
+ // todo: string (>|>=|<|<=) string
938
+
939
+ // string comparison
940
+ if (op === '===' || op === '==') {
941
+ return compareStrings(scope, left, right, true);
942
+ }
943
+
944
+ if (op === '!==' || op === '!=') {
945
+ return [
946
+ ...compareStrings(scope, left, right, true),
947
+ [ Opcodes.i32_eqz ]
948
+ ];
949
+ }
950
+ }
837
951
 
838
952
  let ops = operatorOpcode[valtype][op];
839
953
 
@@ -843,33 +957,69 @@ const performOp = (scope, op, left, right, leftType, rightType, _global = false,
843
957
  includeBuiltin(scope, builtinName);
844
958
  const idx = funcIndex[builtinName];
845
959
 
846
- return finalise([
960
+ return finalize([
847
961
  ...left,
848
962
  ...right,
849
963
  [ Opcodes.call, idx ]
850
964
  ]);
851
965
  }
852
966
 
853
- if (!ops) return todo(`operator ${op} not implemented yet`); // throw new Error(`unknown operator ${op}`);
967
+ if (!ops) return todo(scope, `operator ${op} not implemented yet`, true);
854
968
 
855
969
  if (!Array.isArray(ops)) ops = [ ops ];
856
970
  ops = [ ops ];
857
971
 
858
972
  let tmpLeft, tmpRight;
859
973
  // if equal op, check if strings for compareStrings
860
- if (op === '===' || op === '==' || op === '!==' || op === '!=') (() => {
861
- const knownLeft = knownType(scope, leftType);
862
- const knownRight = knownType(scope, rightType);
863
-
864
- // todo: intelligent partial skip later
865
- // if neither known are string, stop this madness
866
- if ((knownLeft != null && knownLeft !== TYPES.string) && (knownRight != null && knownRight !== TYPES.string)) {
867
- return;
868
- }
974
+ // todo: intelligent partial skip later
975
+ // if neither known are string, stop this madness
976
+ // we already do known checks earlier, so don't need to recheck
869
977
 
978
+ if ((op === '===' || op === '==' || op === '!==' || op === '!=') && (knownLeft == null && knownRight == null)) {
870
979
  tmpLeft = localTmp(scope, '__tmpop_left');
871
980
  tmpRight = localTmp(scope, '__tmpop_right');
872
981
 
982
+ // returns false for one string, one not - but more ops/slower
983
+ // ops.unshift(...stringOnly([
984
+ // // if left is string
985
+ // ...leftType,
986
+ // ...number(TYPES.string, Valtype.i32),
987
+ // [ Opcodes.i32_eq ],
988
+
989
+ // // if right is string
990
+ // ...rightType,
991
+ // ...number(TYPES.string, Valtype.i32),
992
+ // [ Opcodes.i32_eq ],
993
+
994
+ // // if either are true
995
+ // [ Opcodes.i32_or ],
996
+ // [ Opcodes.if, Blocktype.void ],
997
+
998
+ // // todo: convert non-strings to strings, for now fail immediately if one is not
999
+ // // if left is not string
1000
+ // ...leftType,
1001
+ // ...number(TYPES.string, Valtype.i32),
1002
+ // [ Opcodes.i32_ne ],
1003
+
1004
+ // // if right is not string
1005
+ // ...rightType,
1006
+ // ...number(TYPES.string, Valtype.i32),
1007
+ // [ Opcodes.i32_ne ],
1008
+
1009
+ // // if either are true
1010
+ // [ Opcodes.i32_or ],
1011
+ // [ Opcodes.if, Blocktype.void ],
1012
+ // ...number(0, Valtype.i32),
1013
+ // [ Opcodes.br, 2 ],
1014
+ // [ Opcodes.end ],
1015
+
1016
+ // ...compareStrings(scope, [ [ Opcodes.local_get, tmpLeft ] ], [ [ Opcodes.local_get, tmpRight ] ]),
1017
+ // ...(op === '!==' || op === '!=' ? [ [ Opcodes.i32_eqz ] ] : []),
1018
+ // [ Opcodes.br, 1 ],
1019
+ // [ Opcodes.end ],
1020
+ // ]));
1021
+
1022
+ // does not handle one string, one not (such cases go past)
873
1023
  ops.unshift(...stringOnly([
874
1024
  // if left is string
875
1025
  ...leftType,
@@ -881,30 +1031,28 @@ const performOp = (scope, op, left, right, leftType, rightType, _global = false,
881
1031
  ...number(TYPES.string, Valtype.i32),
882
1032
  [ Opcodes.i32_eq ],
883
1033
 
884
- // if either are true
885
- [ Opcodes.i32_or ],
1034
+ // if both are true
1035
+ [ Opcodes.i32_and ],
886
1036
  [ Opcodes.if, Blocktype.void ],
1037
+ ...compareStrings(scope, [ [ Opcodes.local_get, tmpLeft ] ], [ [ Opcodes.local_get, tmpRight ] ]),
1038
+ ...(op === '!==' || op === '!=' ? [ [ Opcodes.i32_eqz ] ] : []),
1039
+ [ Opcodes.br, 1 ],
1040
+ [ Opcodes.end ],
887
1041
 
888
- // todo: convert non-strings to strings, for now fail immediately if one is not
889
- // if left is not string
1042
+ // if left is bytestring
890
1043
  ...leftType,
891
- ...number(TYPES.string, Valtype.i32),
892
- [ Opcodes.i32_ne ],
1044
+ ...number(TYPES._bytestring, Valtype.i32),
1045
+ [ Opcodes.i32_eq ],
893
1046
 
894
- // if right is not string
1047
+ // if right is bytestring
895
1048
  ...rightType,
896
- ...number(TYPES.string, Valtype.i32),
897
- [ Opcodes.i32_ne ],
1049
+ ...number(TYPES._bytestring, Valtype.i32),
1050
+ [ Opcodes.i32_eq ],
898
1051
 
899
- // if either are true
900
- [ Opcodes.i32_or ],
1052
+ // if both are true
1053
+ [ Opcodes.i32_and ],
901
1054
  [ Opcodes.if, Blocktype.void ],
902
- ...number(0, Valtype.i32),
903
- [ Opcodes.br, 1 ],
904
- [ Opcodes.end ],
905
-
906
- ...compareStrings(scope, [ [ Opcodes.local_get, tmpLeft ] ], [ [ Opcodes.local_get, tmpRight ] ]),
907
- // ...compareStrings(scope, [ [ Opcodes.local_get, tmpLeft ] ], [ [ Opcodes.local_get, tmpRight ] ]),
1055
+ ...compareStrings(scope, [ [ Opcodes.local_get, tmpLeft ] ], [ [ Opcodes.local_get, tmpRight ] ], true),
908
1056
  ...(op === '!==' || op === '!=' ? [ [ Opcodes.i32_eqz ] ] : []),
909
1057
  [ Opcodes.br, 1 ],
910
1058
  [ Opcodes.end ],
@@ -916,9 +1064,9 @@ const performOp = (scope, op, left, right, leftType, rightType, _global = false,
916
1064
  // endOut.push(stringOnly([ Opcodes.end ]));
917
1065
  endOut.unshift(stringOnly([ Opcodes.end ]));
918
1066
  // }
919
- })();
1067
+ }
920
1068
 
921
- return finalise([
1069
+ return finalize([
922
1070
  ...left,
923
1071
  ...(tmpLeft != null ? stringOnly([ [ Opcodes.local_tee, tmpLeft ] ]) : []),
924
1072
  ...right,
@@ -935,7 +1083,22 @@ const generateBinaryExp = (scope, decl, _global, _name) => {
935
1083
  return out;
936
1084
  };
937
1085
 
938
- const asmFunc = (name, { wasm, params, locals: localTypes, globals: globalTypes = [], globalInits, returns, returnType, localNames = [], globalNames = [] }) => {
1086
+ const asmFuncToAsm = (func, { name = '#unknown_asm_func', params = [], locals = [], returns = [], localInd = 0 }) => {
1087
+ return func({ name, params, locals, returns, localInd }, {
1088
+ TYPES, TYPE_NAMES, typeSwitch, makeArray, makeString, allocPage,
1089
+ builtin: name => {
1090
+ let idx = funcIndex[name] ?? importedFuncs[name];
1091
+ if (idx === undefined && builtinFuncs[name]) {
1092
+ includeBuiltin(null, name);
1093
+ idx = funcIndex[name];
1094
+ }
1095
+
1096
+ return idx;
1097
+ }
1098
+ });
1099
+ };
1100
+
1101
+ const asmFunc = (name, { wasm, params, locals: localTypes, globals: globalTypes = [], globalInits, returns, returnType, localNames = [], globalNames = [], data: _data = [] }) => {
939
1102
  const existing = funcs.find(x => x.name === name);
940
1103
  if (existing) return existing;
941
1104
 
@@ -947,6 +1110,14 @@ const asmFunc = (name, { wasm, params, locals: localTypes, globals: globalTypes
947
1110
  locals[nameParam(i)] = { idx: i, type: allLocals[i] };
948
1111
  }
949
1112
 
1113
+ for (const x of _data) {
1114
+ const copy = { ...x };
1115
+ copy.offset += pages.size * pageSize;
1116
+ data.push(copy);
1117
+ }
1118
+
1119
+ if (typeof wasm === 'function') wasm = asmFuncToAsm(wasm, { name, params, locals, returns, localInd: allLocals.length });
1120
+
950
1121
  let baseGlobalIdx, i = 0;
951
1122
  for (const type of globalTypes) {
952
1123
  if (baseGlobalIdx === undefined) baseGlobalIdx = globalInd;
@@ -969,7 +1140,7 @@ const asmFunc = (name, { wasm, params, locals: localTypes, globals: globalTypes
969
1140
  params,
970
1141
  locals,
971
1142
  returns,
972
- returnType: TYPES[returnType ?? 'number'],
1143
+ returnType: returnType ?? TYPES.number,
973
1144
  wasm,
974
1145
  internal: true,
975
1146
  index: currentFuncIndex++
@@ -992,6 +1163,7 @@ const generateLogicExp = (scope, decl) => {
992
1163
  return performLogicOp(scope, decl.operator, generate(scope, decl.left), generate(scope, decl.right), getNodeType(scope, decl.left), getNodeType(scope, decl.right));
993
1164
  };
994
1165
 
1166
+ // potential future ideas for nan boxing (unused):
995
1167
  // T = JS type, V = value/pointer
996
1168
  // 0bTTT
997
1169
  // qNAN: 0 11111111111 1000000000000000000000000000000000000000000000000001
@@ -1015,47 +1187,29 @@ const generateLogicExp = (scope, decl) => {
1015
1187
  // 4: internal type
1016
1188
  // 5: pointer
1017
1189
 
1018
- const TYPES = {
1019
- number: 0x00,
1020
- boolean: 0x01,
1021
- string: 0x02,
1022
- undefined: 0x03,
1023
- object: 0x04,
1024
- function: 0x05,
1025
- symbol: 0x06,
1026
- bigint: 0x07,
1190
+ const isExistingProtoFunc = name => {
1191
+ if (name.startsWith('__Array_prototype')) return !!prototypeFuncs[TYPES._array][name.slice(18)];
1192
+ if (name.startsWith('__String_prototype_')) return !!prototypeFuncs[TYPES.string][name.slice(19)];
1027
1193
 
1028
- // these are not "typeof" types but tracked internally
1029
- _array: 0x10,
1030
- _regexp: 0x11
1031
- };
1032
-
1033
- const TYPE_NAMES = {
1034
- [TYPES.number]: 'Number',
1035
- [TYPES.boolean]: 'Boolean',
1036
- [TYPES.string]: 'String',
1037
- [TYPES.undefined]: 'undefined',
1038
- [TYPES.object]: 'Object',
1039
- [TYPES.function]: 'Function',
1040
- [TYPES.symbol]: 'Symbol',
1041
- [TYPES.bigint]: 'BigInt',
1042
-
1043
- [TYPES._array]: 'Array',
1044
- [TYPES._regexp]: 'RegExp'
1194
+ return false;
1045
1195
  };
1046
1196
 
1047
1197
  const getType = (scope, _name) => {
1048
1198
  const name = mapName(_name);
1049
1199
 
1200
+ // if (scope.locals[name] && !scope.locals[name + '#type']) console.log(name);
1201
+
1202
+ if (typedInput && scope.locals[name]?.metadata?.type != null) return number(scope.locals[name].metadata.type, Valtype.i32);
1050
1203
  if (scope.locals[name]) return [ [ Opcodes.local_get, scope.locals[name + '#type'].idx ] ];
1204
+
1205
+ if (typedInput && globals[name]?.metadata?.type != null) return number(globals[name].metadata.type, Valtype.i32);
1051
1206
  if (globals[name]) return [ [ Opcodes.global_get, globals[name + '#type'].idx ] ];
1052
1207
 
1053
1208
  let type = TYPES.undefined;
1054
- if (builtinVars[name]) type = TYPES[builtinVars[name].type ?? 'number'];
1209
+ if (builtinVars[name]) type = builtinVars[name].type ?? TYPES.number;
1055
1210
  if (builtinFuncs[name] !== undefined || importedFuncs[name] !== undefined || funcIndex[name] !== undefined || internalConstrs[name] !== undefined) type = TYPES.function;
1056
1211
 
1057
- if (name.startsWith('__Array_prototype_') && prototypeFuncs[TYPES._array][name.slice(18)] ||
1058
- name.startsWith('__String_prototype_') && prototypeFuncs[TYPES.string][name.slice(19)]) type = TYPES.function;
1212
+ if (isExistingProtoFunc(name)) type = TYPES.function;
1059
1213
 
1060
1214
  return number(type, Valtype.i32);
1061
1215
  };
@@ -1078,15 +1232,16 @@ const setType = (scope, _name, type) => {
1078
1232
  ];
1079
1233
 
1080
1234
  // throw new Error('could not find var');
1235
+ return [];
1081
1236
  };
1082
1237
 
1083
1238
  const getLastType = scope => {
1084
1239
  scope.gotLastType = true;
1085
- return [ Opcodes.local_get, localTmp(scope, '#last_type', Valtype.i32) ];
1240
+ return [ [ Opcodes.local_get, localTmp(scope, '#last_type', Valtype.i32) ] ];
1086
1241
  };
1087
1242
 
1088
1243
  const setLastType = scope => {
1089
- return [ Opcodes.local_set, localTmp(scope, '#last_type', Valtype.i32) ];
1244
+ return [ [ Opcodes.local_set, localTmp(scope, '#last_type', Valtype.i32) ] ];
1090
1245
  };
1091
1246
 
1092
1247
  const getNodeType = (scope, node) => {
@@ -1094,6 +1249,8 @@ const getNodeType = (scope, node) => {
1094
1249
  if (node.type === 'Literal') {
1095
1250
  if (node.regex) return TYPES._regexp;
1096
1251
 
1252
+ if (typeof node.value === 'string' && byteStringable(node.value)) return TYPES._bytestring;
1253
+
1097
1254
  return TYPES[typeof node.value];
1098
1255
  }
1099
1256
 
@@ -1107,6 +1264,27 @@ const getNodeType = (scope, node) => {
1107
1264
 
1108
1265
  if (node.type === 'CallExpression' || node.type === 'NewExpression') {
1109
1266
  const name = node.callee.name;
1267
+ if (!name) {
1268
+ // iife
1269
+ if (scope.locals['#last_type']) return getLastType(scope);
1270
+
1271
+ // presume
1272
+ // todo: warn here?
1273
+ return TYPES.number;
1274
+ }
1275
+
1276
+ if (node.type === 'NewExpression' && builtinFuncs[name + '$constructor']) {
1277
+ if (builtinFuncs[name + '$constructor'].typedReturns) {
1278
+ if (scope.locals['#last_type']) return getLastType(scope);
1279
+
1280
+ // presume
1281
+ // todo: warn here?
1282
+ return TYPES.number;
1283
+ }
1284
+
1285
+ return builtinFuncs[name + '$constructor'].returnType ?? TYPES.number;
1286
+ }
1287
+
1110
1288
  const func = funcs.find(x => x.name === name);
1111
1289
 
1112
1290
  if (func) {
@@ -1114,7 +1292,7 @@ const getNodeType = (scope, node) => {
1114
1292
  if (func.returnType) return func.returnType;
1115
1293
  }
1116
1294
 
1117
- if (builtinFuncs[name]) return TYPES[builtinFuncs[name].returnType ?? 'number'];
1295
+ if (builtinFuncs[name] && !builtinFuncs[name].typedReturns) return builtinFuncs[name].returnType ?? TYPES.number;
1118
1296
  if (internalConstrs[name]) return internalConstrs[name].type;
1119
1297
 
1120
1298
  // check if this is a prototype function
@@ -1125,11 +1303,16 @@ const getNodeType = (scope, node) => {
1125
1303
  const spl = name.slice(2).split('_');
1126
1304
 
1127
1305
  const func = spl[spl.length - 1];
1128
- const protoFuncs = Object.values(prototypeFuncs).filter(x => x[func] != null);
1306
+ const protoFuncs = Object.keys(prototypeFuncs).filter(x => x != TYPES._bytestring && prototypeFuncs[x][func] != null);
1129
1307
  if (protoFuncs.length === 1) return protoFuncs[0].returnType ?? TYPES.number;
1130
1308
  }
1131
1309
 
1132
- if (scope.locals['#last_type']) return [ getLastType(scope) ];
1310
+ if (name.startsWith('__Porffor_wasm_')) {
1311
+ // todo: return undefined for non-returning ops
1312
+ return TYPES.number;
1313
+ }
1314
+
1315
+ if (scope.locals['#last_type']) return getLastType(scope);
1133
1316
 
1134
1317
  // presume
1135
1318
  // todo: warn here?
@@ -1177,6 +1360,15 @@ const getNodeType = (scope, node) => {
1177
1360
 
1178
1361
  if (node.type === 'BinaryExpression') {
1179
1362
  if (['==', '===', '!=', '!==', '>', '>=', '<', '<='].includes(node.operator)) return TYPES.boolean;
1363
+ if (node.operator !== '+') return TYPES.number;
1364
+
1365
+ const knownLeft = knownType(scope, getNodeType(scope, node.left));
1366
+ const knownRight = knownType(scope, getNodeType(scope, node.right));
1367
+
1368
+ // todo: this should be dynamic but for now only static
1369
+ if (knownLeft === TYPES.string || knownRight === TYPES.string) return TYPES.string;
1370
+ if (knownLeft === TYPES._bytestring || knownRight === TYPES._bytestring) return TYPES._bytestring;
1371
+
1180
1372
  return TYPES.number;
1181
1373
 
1182
1374
  // todo: string concat types
@@ -1201,7 +1393,7 @@ const getNodeType = (scope, node) => {
1201
1393
  if (node.operator === '!') return TYPES.boolean;
1202
1394
  if (node.operator === 'void') return TYPES.undefined;
1203
1395
  if (node.operator === 'delete') return TYPES.boolean;
1204
- if (node.operator === 'typeof') return TYPES.string;
1396
+ if (node.operator === 'typeof') return Prefs.bytestring ? TYPES._bytestring : TYPES.string;
1205
1397
 
1206
1398
  return TYPES.number;
1207
1399
  }
@@ -1210,11 +1402,23 @@ const getNodeType = (scope, node) => {
1210
1402
  // hack: if something.length, number type
1211
1403
  if (node.property.name === 'length') return TYPES.number;
1212
1404
 
1213
- // we cannot guess
1405
+ // ts hack
1406
+ if (scope.locals[node.object.name]?.metadata?.type === TYPES.string) return TYPES.string;
1407
+ if (scope.locals[node.object.name]?.metadata?.type === TYPES._bytestring) return TYPES._bytestring;
1408
+ if (scope.locals[node.object.name]?.metadata?.type === TYPES._array) return TYPES.number;
1409
+
1410
+ if (scope.locals['#last_type']) return getLastType(scope);
1411
+
1412
+ // presume
1214
1413
  return TYPES.number;
1215
1414
  }
1216
1415
 
1217
- if (scope.locals['#last_type']) return [ getLastType(scope) ];
1416
+ if (node.type === 'TaggedTemplateExpression') {
1417
+ // hack
1418
+ if (node.tag.name.startsWith('__Porffor_')) return TYPES.number;
1419
+ }
1420
+
1421
+ if (scope.locals['#last_type']) return getLastType(scope);
1218
1422
 
1219
1423
  // presume
1220
1424
  // todo: warn here?
@@ -1230,8 +1434,8 @@ const getNodeType = (scope, node) => {
1230
1434
  const generateLiteral = (scope, decl, global, name) => {
1231
1435
  if (decl.value === null) return number(NULL);
1232
1436
 
1437
+ // hack: just return 1 for regex literals
1233
1438
  if (decl.regex) {
1234
- scope.regex[name] = decl.regex;
1235
1439
  return number(1);
1236
1440
  }
1237
1441
 
@@ -1244,19 +1448,10 @@ const generateLiteral = (scope, decl, global, name) => {
1244
1448
  return number(decl.value ? 1 : 0);
1245
1449
 
1246
1450
  case 'string':
1247
- const str = decl.value;
1248
- const rawElements = new Array(str.length);
1249
- let j = 0;
1250
- for (let i = 0; i < str.length; i++) {
1251
- rawElements[i] = str.charCodeAt(i);
1252
- }
1253
-
1254
- return makeArray(scope, {
1255
- rawElements
1256
- }, global, name, false, 'i16')[0];
1451
+ return makeString(scope, decl.value, global, name);
1257
1452
 
1258
1453
  default:
1259
- return todo(`cannot generate literal of type ${typeof decl.value}`);
1454
+ return todo(scope, `cannot generate literal of type ${typeof decl.value}`, true);
1260
1455
  }
1261
1456
  };
1262
1457
 
@@ -1265,6 +1460,8 @@ const countLeftover = wasm => {
1265
1460
 
1266
1461
  for (let i = 0; i < wasm.length; i++) {
1267
1462
  const inst = wasm[i];
1463
+ if (inst[0] == null) continue;
1464
+
1268
1465
  if (depth === 0 && (inst[0] === Opcodes.if || inst[0] === Opcodes.block || inst[0] === Opcodes.loop)) {
1269
1466
  if (inst[0] === Opcodes.if) count--;
1270
1467
  if (inst[1] !== Blocktype.void) count++;
@@ -1273,18 +1470,25 @@ const countLeftover = wasm => {
1273
1470
  if (inst[0] === Opcodes.end) depth--;
1274
1471
 
1275
1472
  if (depth === 0)
1276
- if ([Opcodes.throw,Opcodes.drop, Opcodes.local_set, Opcodes.global_set].includes(inst[0])) count--;
1277
- else if ([null, Opcodes.i32_eqz, Opcodes.i64_eqz, Opcodes.f64_ceil, Opcodes.f64_floor, Opcodes.f64_trunc, Opcodes.f64_nearest, Opcodes.f64_sqrt, Opcodes.local_tee, Opcodes.i32_wrap_i64, Opcodes.i64_extend_i32_s, Opcodes.i64_extend_i32_u, Opcodes.f32_demote_f64, Opcodes.f64_promote_f32, Opcodes.f64_convert_i32_s, Opcodes.f64_convert_i32_u, Opcodes.i32_clz, Opcodes.i32_ctz, Opcodes.i32_popcnt, Opcodes.f64_neg, Opcodes.end, Opcodes.i32_trunc_sat_f64_s[0], Opcodes.i32x4_extract_lane, Opcodes.i16x8_extract_lane, Opcodes.i32_load, Opcodes.i64_load, Opcodes.f64_load, Opcodes.v128_load, Opcodes.i32_load16_u, Opcodes.i32_load16_s, Opcodes.memory_grow].includes(inst[0]) && (inst[0] !== 0xfc || inst[1] < 0x0a)) {}
1473
+ if ([Opcodes.throw, Opcodes.drop, Opcodes.local_set, Opcodes.global_set].includes(inst[0])) count--;
1474
+ else if ([null, Opcodes.i32_eqz, Opcodes.i64_eqz, Opcodes.f64_ceil, Opcodes.f64_floor, Opcodes.f64_trunc, Opcodes.f64_nearest, Opcodes.f64_sqrt, Opcodes.local_tee, Opcodes.i32_wrap_i64, Opcodes.i64_extend_i32_s, Opcodes.i64_extend_i32_u, Opcodes.f32_demote_f64, Opcodes.f64_promote_f32, Opcodes.f64_convert_i32_s, Opcodes.f64_convert_i32_u, Opcodes.i32_clz, Opcodes.i32_ctz, Opcodes.i32_popcnt, Opcodes.f64_neg, Opcodes.end, Opcodes.i32_trunc_sat_f64_s[0], Opcodes.i32x4_extract_lane, Opcodes.i16x8_extract_lane, Opcodes.i32_load, Opcodes.i64_load, Opcodes.f64_load, Opcodes.v128_load, Opcodes.i32_load16_u, Opcodes.i32_load16_s, Opcodes.i32_load8_u, Opcodes.i32_load8_s, Opcodes.memory_grow].includes(inst[0]) && (inst[0] !== 0xfc || inst[1] < 0x0a)) {}
1278
1475
  else if ([Opcodes.local_get, Opcodes.global_get, Opcodes.f64_const, Opcodes.i32_const, Opcodes.i64_const, Opcodes.v128_const].includes(inst[0])) count++;
1279
- else if ([Opcodes.i32_store, Opcodes.i64_store, Opcodes.f64_store, Opcodes.i32_store16].includes(inst[0])) count -= 2;
1476
+ else if ([Opcodes.i32_store, Opcodes.i64_store, Opcodes.f64_store, Opcodes.i32_store16, Opcodes.i32_store8].includes(inst[0])) count -= 2;
1280
1477
  else if (Opcodes.memory_copy[0] === inst[0] && Opcodes.memory_copy[1] === inst[1]) count -= 3;
1281
1478
  else if (inst[0] === Opcodes.return) count = 0;
1282
1479
  else if (inst[0] === Opcodes.call) {
1283
1480
  let func = funcs.find(x => x.index === inst[1]);
1284
- if (func) {
1285
- count -= func.params.length;
1286
- } else count--;
1287
- if (func) count += func.returns.length;
1481
+ if (inst[1] === -1) {
1482
+ // todo: count for calling self
1483
+ } else if (!func && inst[1] < importedFuncs.length) {
1484
+ count -= importedFuncs[inst[1]].params;
1485
+ count += importedFuncs[inst[1]].returns;
1486
+ } else {
1487
+ if (func) {
1488
+ count -= func.params.length;
1489
+ } else count--;
1490
+ if (func) count += func.returns.length;
1491
+ }
1288
1492
  } else count--;
1289
1493
 
1290
1494
  // console.log(count, decompile([ inst ]).slice(0, -1));
@@ -1302,7 +1506,7 @@ const disposeLeftover = wasm => {
1302
1506
  const generateExp = (scope, decl) => {
1303
1507
  const expression = decl.expression;
1304
1508
 
1305
- const out = generate(scope, expression);
1509
+ const out = generate(scope, expression, undefined, undefined, true);
1306
1510
  disposeLeftover(out);
1307
1511
 
1308
1512
  return out;
@@ -1360,7 +1564,7 @@ const RTArrayUtil = {
1360
1564
  ]
1361
1565
  };
1362
1566
 
1363
- const generateCall = (scope, decl, _global, _name) => {
1567
+ const generateCall = (scope, decl, _global, _name, unusedValue = false) => {
1364
1568
  /* const callee = decl.callee;
1365
1569
  const args = decl.arguments;
1366
1570
 
@@ -1376,10 +1580,21 @@ const generateCall = (scope, decl, _global, _name) => {
1376
1580
  name = func.name;
1377
1581
  }
1378
1582
 
1379
- if (name === 'eval' && decl.arguments[0].type === 'Literal') {
1583
+ if (name === 'eval' && decl.arguments[0]?.type === 'Literal') {
1380
1584
  // literal eval hack
1381
- const code = decl.arguments[0].value;
1382
- const parsed = parse(code, []);
1585
+ const code = decl.arguments[0]?.value ?? '';
1586
+
1587
+ let parsed;
1588
+ try {
1589
+ parsed = parse(code, []);
1590
+ } catch (e) {
1591
+ if (e.name === 'SyntaxError') {
1592
+ // throw syntax errors of evals at runtime instead
1593
+ return internalThrow(scope, 'SyntaxError', e.message, true);
1594
+ }
1595
+
1596
+ throw e;
1597
+ }
1383
1598
 
1384
1599
  const out = generate(scope, {
1385
1600
  type: 'BlockStatement',
@@ -1393,13 +1608,13 @@ const generateCall = (scope, decl, _global, _name) => {
1393
1608
  const finalStatement = parsed.body[parsed.body.length - 1];
1394
1609
  out.push(
1395
1610
  ...getNodeType(scope, finalStatement),
1396
- setLastType(scope)
1611
+ ...setLastType(scope)
1397
1612
  );
1398
1613
  } else if (countLeftover(out) === 0) {
1399
1614
  out.push(...number(UNDEFINED));
1400
1615
  out.push(
1401
1616
  ...number(TYPES.undefined, Valtype.i32),
1402
- setLastType(scope)
1617
+ ...setLastType(scope)
1403
1618
  );
1404
1619
  }
1405
1620
 
@@ -1421,13 +1636,16 @@ const generateCall = (scope, decl, _global, _name) => {
1421
1636
 
1422
1637
  target = { ...decl.callee };
1423
1638
  target.name = spl.slice(0, -1).join('_');
1639
+
1640
+ // failed to lookup name, abort
1641
+ if (!lookupName(scope, target.name)[0]) protoName = null;
1424
1642
  }
1425
1643
 
1426
1644
  // literal.func()
1427
1645
  if (!name && decl.callee.type === 'MemberExpression') {
1428
1646
  // megahack for /regex/.func()
1429
- if (decl.callee.object.regex) {
1430
- const funcName = decl.callee.property.name;
1647
+ const funcName = decl.callee.property.name;
1648
+ if (decl.callee.object.regex && Object.hasOwn(Rhemyn, funcName)) {
1431
1649
  const func = Rhemyn[funcName](decl.callee.object.regex.pattern, currentFuncIndex++);
1432
1650
 
1433
1651
  funcIndex[func.name] = func.index;
@@ -1443,7 +1661,7 @@ const generateCall = (scope, decl, _global, _name) => {
1443
1661
  Opcodes.i32_from_u,
1444
1662
 
1445
1663
  ...number(TYPES.boolean, Valtype.i32),
1446
- setLastType(scope)
1664
+ ...setLastType(scope)
1447
1665
  ];
1448
1666
  }
1449
1667
 
@@ -1468,23 +1686,47 @@ const generateCall = (scope, decl, _global, _name) => {
1468
1686
  // }
1469
1687
 
1470
1688
  if (protoName) {
1689
+ const protoBC = {};
1690
+
1691
+ const builtinProtoCands = Object.keys(builtinFuncs).filter(x => x.startsWith('__') && x.endsWith('_prototype_' + protoName));
1692
+
1693
+ if (!decl._protoInternalCall && builtinProtoCands.length > 0) {
1694
+ for (const x of builtinProtoCands) {
1695
+ const type = TYPES[x.split('_prototype_')[0].slice(2).toLowerCase()];
1696
+ if (type == null) continue;
1697
+
1698
+ protoBC[type] = generateCall(scope, {
1699
+ callee: {
1700
+ name: x
1701
+ },
1702
+ arguments: [ target, ...decl.arguments ],
1703
+ _protoInternalCall: true
1704
+ });
1705
+ }
1706
+ }
1707
+
1471
1708
  const protoCands = Object.keys(prototypeFuncs).reduce((acc, x) => {
1472
- const f = prototypeFuncs[x][protoName];
1473
- if (f) acc[x] = f;
1709
+ if (Object.hasOwn(prototypeFuncs[x], protoName)) acc[x] = prototypeFuncs[x][protoName];
1474
1710
  return acc;
1475
1711
  }, {});
1476
1712
 
1477
- // no prototype function candidates, ignore
1478
1713
  if (Object.keys(protoCands).length > 0) {
1479
1714
  // use local for cached i32 length as commonly used
1480
1715
  const lengthLocal = localTmp(scope, '__proto_length_cache', Valtype.i32);
1481
1716
  const pointerLocal = localTmp(scope, '__proto_pointer_cache', Valtype.i32);
1482
- const getPointer = [ [ Opcodes.local_get, pointerLocal ] ];
1483
1717
 
1484
1718
  // TODO: long-term, prototypes should be their individual separate funcs
1485
1719
 
1720
+ const rawPointer = [
1721
+ ...generate(scope, target),
1722
+ Opcodes.i32_to_u
1723
+ ];
1724
+
1725
+ const usePointerCache = !Object.values(protoCands).every(x => x.noPointerCache === true);
1726
+ const getPointer = usePointerCache ? [ [ Opcodes.local_get, pointerLocal ] ] : rawPointer;
1727
+
1728
+ let allOptUnused = true;
1486
1729
  let lengthI32CacheUsed = false;
1487
- const protoBC = {};
1488
1730
  for (const x in protoCands) {
1489
1731
  const protoFunc = protoCands[x];
1490
1732
  if (protoFunc.noArgRetLength && decl.arguments.length === 0) {
@@ -1492,7 +1734,7 @@ const generateCall = (scope, decl, _global, _name) => {
1492
1734
  ...RTArrayUtil.getLength(getPointer),
1493
1735
 
1494
1736
  ...number(TYPES.number, Valtype.i32),
1495
- setLastType(scope)
1737
+ ...setLastType(scope)
1496
1738
  ];
1497
1739
  continue;
1498
1740
  }
@@ -1502,6 +1744,7 @@ const generateCall = (scope, decl, _global, _name) => {
1502
1744
  const protoLocal = protoFunc.local ? localTmp(scope, `__${protoName}_tmp`, protoFunc.local) : -1;
1503
1745
  const protoLocal2 = protoFunc.local2 ? localTmp(scope, `__${protoName}_tmp2`, protoFunc.local2) : -1;
1504
1746
 
1747
+ let optUnused = false;
1505
1748
  const protoOut = protoFunc(getPointer, {
1506
1749
  getCachedI32: () => {
1507
1750
  lengthI32CacheUsed = true;
@@ -1516,23 +1759,30 @@ const generateCall = (scope, decl, _global, _name) => {
1516
1759
  return makeArray(scope, {
1517
1760
  rawElements: new Array(length)
1518
1761
  }, _global, _name, true, itemType);
1762
+ }, () => {
1763
+ optUnused = true;
1764
+ return unusedValue;
1519
1765
  });
1520
1766
 
1767
+ if (!optUnused) allOptUnused = false;
1768
+
1521
1769
  protoBC[x] = [
1522
- [ Opcodes.block, valtypeBinary ],
1770
+ [ Opcodes.block, unusedValue && optUnused ? Blocktype.void : valtypeBinary ],
1523
1771
  ...protoOut,
1524
1772
 
1525
1773
  ...number(protoFunc.returnType ?? TYPES.number, Valtype.i32),
1526
- setLastType(scope),
1774
+ ...setLastType(scope),
1527
1775
  [ Opcodes.end ]
1528
1776
  ];
1529
1777
  }
1530
1778
 
1531
- return [
1532
- ...generate(scope, target),
1779
+ // todo: if some cands use optUnused and some don't, we will probably crash
1533
1780
 
1534
- Opcodes.i32_to_u,
1535
- [ Opcodes.local_set, pointerLocal ],
1781
+ return [
1782
+ ...(usePointerCache ? [
1783
+ ...rawPointer,
1784
+ [ Opcodes.local_set, pointerLocal ],
1785
+ ] : []),
1536
1786
 
1537
1787
  ...(!lengthI32CacheUsed ? [] : [
1538
1788
  ...RTArrayUtil.getLengthI32(getPointer),
@@ -1544,13 +1794,22 @@ const generateCall = (scope, decl, _global, _name) => {
1544
1794
 
1545
1795
  // TODO: error better
1546
1796
  default: internalThrow(scope, 'TypeError', `'${protoName}' proto func tried to be called on a type without an impl`)
1547
- }, valtypeBinary),
1797
+ }, allOptUnused && unusedValue ? Blocktype.void : valtypeBinary),
1548
1798
  ];
1549
1799
  }
1800
+
1801
+ if (Object.keys(protoBC).length > 0) {
1802
+ return typeSwitch(scope, getNodeType(scope, target), {
1803
+ ...protoBC,
1804
+
1805
+ // TODO: error better
1806
+ default: internalThrow(scope, 'TypeError', `'${protoName}' proto func tried to be called on a type without an impl`)
1807
+ }, valtypeBinary);
1808
+ }
1550
1809
  }
1551
1810
 
1552
1811
  // TODO: only allows callee as literal
1553
- if (!name) return todo(`only literal callees (got ${decl.callee.type})`);
1812
+ if (!name) return todo(scope, `only literal callees (got ${decl.callee.type})`);
1554
1813
 
1555
1814
  let idx = funcIndex[name] ?? importedFuncs[name];
1556
1815
  if (idx === undefined && builtinFuncs[name]) {
@@ -1583,15 +1842,66 @@ const generateCall = (scope, decl, _global, _name) => {
1583
1842
  idx = -1;
1584
1843
  }
1585
1844
 
1845
+ if (idx === undefined && name.startsWith('__Porffor_wasm_')) {
1846
+ const wasmOps = {
1847
+ // pointer, align, offset
1848
+ i32_load: { imms: 2, args: 1, returns: 1 },
1849
+ // pointer, value, align, offset
1850
+ i32_store: { imms: 2, args: 2, returns: 0 },
1851
+ // pointer, align, offset
1852
+ i32_load8_u: { imms: 2, args: 1, returns: 1 },
1853
+ // pointer, value, align, offset
1854
+ i32_store8: { imms: 2, args: 2, returns: 0 },
1855
+ // pointer, align, offset
1856
+ i32_load16_u: { imms: 2, args: 1, returns: 1 },
1857
+ // pointer, value, align, offset
1858
+ i32_store16: { imms: 2, args: 2, returns: 0 },
1859
+
1860
+ // pointer, align, offset
1861
+ f64_load: { imms: 2, args: 1, returns: 1 },
1862
+ // pointer, value, align, offset
1863
+ f64_store: { imms: 2, args: 2, returns: 0 },
1864
+
1865
+ // value
1866
+ i32_const: { imms: 1, args: 0, returns: 1 },
1867
+
1868
+ // a, b
1869
+ i32_or: { imms: 0, args: 2, returns: 1 },
1870
+ };
1871
+
1872
+ const opName = name.slice('__Porffor_wasm_'.length);
1873
+
1874
+ if (wasmOps[opName]) {
1875
+ const op = wasmOps[opName];
1876
+
1877
+ const argOut = [];
1878
+ for (let i = 0; i < op.args; i++) argOut.push(
1879
+ ...generate(scope, decl.arguments[i]),
1880
+ Opcodes.i32_to
1881
+ );
1882
+
1883
+ // literals only
1884
+ const imms = decl.arguments.slice(op.args).map(x => x.value);
1885
+
1886
+ return [
1887
+ ...argOut,
1888
+ [ Opcodes[opName], ...imms ],
1889
+ ...(new Array(op.returns).fill(Opcodes.i32_from))
1890
+ ];
1891
+ }
1892
+ }
1893
+
1586
1894
  if (idx === undefined) {
1587
- if (scope.locals[name] !== undefined || globals[name] !== undefined || builtinVars[name] !== undefined) return internalThrow(scope, 'TypeError', `${unhackName(name)} is not a function`);
1588
- return internalThrow(scope, 'ReferenceError', `${unhackName(name)} is not defined`);
1895
+ if (scope.locals[name] !== undefined || globals[name] !== undefined || builtinVars[name] !== undefined) return internalThrow(scope, 'TypeError', `${unhackName(name)} is not a function`, true);
1896
+ return internalThrow(scope, 'ReferenceError', `${unhackName(name)} is not defined`, true);
1589
1897
  }
1590
1898
 
1591
1899
  const func = funcs.find(x => x.index === idx);
1592
1900
 
1593
1901
  const userFunc = (funcIndex[name] && !importedFuncs[name] && !builtinFuncs[name] && !internalConstrs[name]) || idx === -1;
1594
- const paramCount = func && (userFunc ? func.params.length / 2 : func.params.length);
1902
+ const typedParams = userFunc || builtinFuncs[name]?.typedParams;
1903
+ const typedReturns = (func ? func.returnType == null : userFunc) || builtinFuncs[name]?.typedReturns;
1904
+ const paramCount = func && (typedParams ? func.params.length / 2 : func.params.length);
1595
1905
 
1596
1906
  let args = decl.arguments;
1597
1907
  if (func && args.length < paramCount) {
@@ -1607,14 +1917,24 @@ const generateCall = (scope, decl, _global, _name) => {
1607
1917
  if (func && func.throws) scope.throws = true;
1608
1918
 
1609
1919
  let out = [];
1610
- for (const arg of args) {
1920
+ for (let i = 0; i < args.length; i++) {
1921
+ const arg = args[i];
1611
1922
  out = out.concat(generate(scope, arg));
1612
- if (userFunc) out = out.concat(getNodeType(scope, arg));
1923
+
1924
+ if (builtinFuncs[name] && builtinFuncs[name].params[i * (typedParams ? 2 : 1)] === Valtype.i32 && valtypeBinary !== Valtype.i32) {
1925
+ out.push(Opcodes.i32_to);
1926
+ }
1927
+
1928
+ if (importedFuncs[name] && name.startsWith('profile')) {
1929
+ out.push(Opcodes.i32_to);
1930
+ }
1931
+
1932
+ if (typedParams) out = out.concat(getNodeType(scope, arg));
1613
1933
  }
1614
1934
 
1615
1935
  out.push([ Opcodes.call, idx ]);
1616
1936
 
1617
- if (!userFunc) {
1937
+ if (!typedReturns) {
1618
1938
  // let type;
1619
1939
  // if (builtinFuncs[name]) type = TYPES[builtinFuncs[name].returnType ?? 'number'];
1620
1940
  // if (internalConstrs[name]) type = internalConstrs[name].type;
@@ -1624,7 +1944,11 @@ const generateCall = (scope, decl, _global, _name) => {
1624
1944
  // ...number(type, Valtype.i32),
1625
1945
  // [ Opcodes.local_set, localTmp(scope, '#last_type', Valtype.i32) ]
1626
1946
  // );
1627
- } else out.push(setLastType(scope));
1947
+ } else out.push(...setLastType(scope));
1948
+
1949
+ if (builtinFuncs[name] && builtinFuncs[name].returns?.[0] === Valtype.i32 && valtypeBinary !== Valtype.i32) {
1950
+ out.push(Opcodes.i32_from);
1951
+ }
1628
1952
 
1629
1953
  return out;
1630
1954
  };
@@ -1632,8 +1956,21 @@ const generateCall = (scope, decl, _global, _name) => {
1632
1956
  const generateNew = (scope, decl, _global, _name) => {
1633
1957
  // hack: basically treat this as a normal call for builtins for now
1634
1958
  const name = mapName(decl.callee.name);
1959
+
1635
1960
  if (internalConstrs[name] && !internalConstrs[name].notConstr) return internalConstrs[name].generate(scope, decl, _global, _name);
1636
- if (!builtinFuncs[name]) return todo(`new statement is not supported yet`); // return todo(`new statement is not supported yet (new ${unhackName(name)})`);
1961
+
1962
+ if (builtinFuncs[name + '$constructor']) {
1963
+ // custom ...$constructor override builtin func
1964
+ return generateCall(scope, {
1965
+ ...decl,
1966
+ callee: {
1967
+ type: 'Identifier',
1968
+ name: name + '$constructor'
1969
+ }
1970
+ }, _global, _name);
1971
+ }
1972
+
1973
+ if (!builtinFuncs[name]) return todo(scope, `new statement is not supported yet`); // return todo(scope, `new statement is not supported yet (new ${unhackName(name)})`);
1637
1974
 
1638
1975
  return generateCall(scope, decl, _global, _name);
1639
1976
  };
@@ -1665,22 +2002,108 @@ const knownType = (scope, type) => {
1665
2002
  return null;
1666
2003
  };
1667
2004
 
2005
+ const brTable = (input, bc, returns) => {
2006
+ const out = [];
2007
+ const keys = Object.keys(bc);
2008
+ const count = keys.length;
2009
+
2010
+ if (count === 1) {
2011
+ // return [
2012
+ // ...input,
2013
+ // ...bc[keys[0]]
2014
+ // ];
2015
+ return bc[keys[0]];
2016
+ }
2017
+
2018
+ if (count === 2) {
2019
+ // just use if else
2020
+ const other = keys.find(x => x !== 'default');
2021
+ return [
2022
+ ...input,
2023
+ ...number(other, Valtype.i32),
2024
+ [ Opcodes.i32_eq ],
2025
+ [ Opcodes.if, returns ],
2026
+ ...bc[other],
2027
+ [ Opcodes.else ],
2028
+ ...bc.default,
2029
+ [ Opcodes.end ]
2030
+ ];
2031
+ }
2032
+
2033
+ for (let i = 0; i < count; i++) {
2034
+ if (i === 0) out.push([ Opcodes.block, returns, 'br table start' ]);
2035
+ else out.push([ Opcodes.block, Blocktype.void ]);
2036
+ }
2037
+
2038
+ const nums = keys.filter(x => +x);
2039
+ const offset = Math.min(...nums);
2040
+ const max = Math.max(...nums);
2041
+
2042
+ const table = [];
2043
+ let br = 1;
2044
+
2045
+ for (let i = offset; i <= max; i++) {
2046
+ // if branch for this num, go to that block
2047
+ if (bc[i]) {
2048
+ table.push(br);
2049
+ br++;
2050
+ continue;
2051
+ }
2052
+
2053
+ // else default
2054
+ table.push(0);
2055
+ }
2056
+
2057
+ out.push(
2058
+ [ Opcodes.block, Blocktype.void ],
2059
+ ...input,
2060
+ ...(offset > 0 ? [
2061
+ ...number(offset, Valtype.i32),
2062
+ [ Opcodes.i32_sub ]
2063
+ ] : []),
2064
+ [ Opcodes.br_table, ...encodeVector(table), 0 ]
2065
+ );
2066
+
2067
+ // if you can guess why we sort the wrong way and then reverse
2068
+ // (instead of just sorting the correct way)
2069
+ // dm me and if you are correct and the first person
2070
+ // I will somehow shout you out or something
2071
+ const orderedBc = keys.sort((a, b) => b - a).reverse();
2072
+
2073
+ br = count - 1;
2074
+ for (const x of orderedBc) {
2075
+ out.push(
2076
+ [ Opcodes.end ],
2077
+ ...bc[x],
2078
+ ...(br === 0 ? [] : [ [ Opcodes.br, br ] ])
2079
+ );
2080
+ br--;
2081
+ }
2082
+
2083
+ return [
2084
+ ...out,
2085
+ [ Opcodes.end, 'br table end' ]
2086
+ ];
2087
+ };
2088
+
1668
2089
  const typeSwitch = (scope, type, bc, returns = valtypeBinary) => {
2090
+ if (!Prefs.bytestring) delete bc[TYPES._bytestring];
2091
+
1669
2092
  const known = knownType(scope, type);
1670
2093
  if (known != null) {
1671
2094
  return bc[known] ?? bc.default;
1672
2095
  }
1673
2096
 
1674
- const tmp = localTmp(scope, '#typeswitch_tmp', Valtype.i32);
2097
+ if (Prefs.typeswitchUseBrtable)
2098
+ return brTable(type, bc, returns);
1675
2099
 
2100
+ const tmp = localTmp(scope, '#typeswitch_tmp', Valtype.i32);
1676
2101
  const out = [
1677
2102
  ...type,
1678
2103
  [ Opcodes.local_set, tmp ],
1679
2104
  [ Opcodes.block, returns ]
1680
2105
  ];
1681
2106
 
1682
- // todo: use br_table?
1683
-
1684
2107
  for (const x in bc) {
1685
2108
  if (x === 'default') continue;
1686
2109
 
@@ -1704,7 +2127,7 @@ const typeSwitch = (scope, type, bc, returns = valtypeBinary) => {
1704
2127
  return out;
1705
2128
  };
1706
2129
 
1707
- const allocVar = (scope, name, global = false) => {
2130
+ const allocVar = (scope, name, global = false, type = true) => {
1708
2131
  const target = global ? globals : scope.locals;
1709
2132
 
1710
2133
  // already declared
@@ -1718,8 +2141,10 @@ const allocVar = (scope, name, global = false) => {
1718
2141
  let idx = global ? globalInd++ : scope.localInd++;
1719
2142
  target[name] = { idx, type: valtypeBinary };
1720
2143
 
1721
- let typeIdx = global ? globalInd++ : scope.localInd++;
1722
- target[name + '#type'] = { idx: typeIdx, type: Valtype.i32 };
2144
+ if (type) {
2145
+ let typeIdx = global ? globalInd++ : scope.localInd++;
2146
+ target[name + '#type'] = { idx: typeIdx, type: Valtype.i32 };
2147
+ }
1723
2148
 
1724
2149
  return idx;
1725
2150
  };
@@ -1734,11 +2159,14 @@ const addVarMetadata = (scope, name, global = false, metadata = {}) => {
1734
2159
  };
1735
2160
 
1736
2161
  const typeAnnoToPorfType = x => {
1737
- if (TYPES[x]) return TYPES[x];
1738
- if (TYPES['_' + x]) return TYPES['_' + x];
2162
+ if (!x) return null;
2163
+ if (TYPES[x.toLowerCase()] != null) return TYPES[x.toLowerCase()];
2164
+ if (TYPES['_' + x.toLowerCase()] != null) return TYPES['_' + x.toLowerCase()];
1739
2165
 
1740
2166
  switch (x) {
1741
2167
  case 'i32':
2168
+ case 'i64':
2169
+ case 'f64':
1742
2170
  return TYPES.number;
1743
2171
  }
1744
2172
 
@@ -1749,7 +2177,7 @@ const extractTypeAnnotation = decl => {
1749
2177
  let a = decl;
1750
2178
  while (a.typeAnnotation) a = a.typeAnnotation;
1751
2179
 
1752
- let type, elementType;
2180
+ let type = null, elementType = null;
1753
2181
  if (a.typeName) {
1754
2182
  type = a.typeName.name;
1755
2183
  } else if (a.type.endsWith('Keyword')) {
@@ -1762,6 +2190,8 @@ const extractTypeAnnotation = decl => {
1762
2190
  const typeName = type;
1763
2191
  type = typeAnnoToPorfType(type);
1764
2192
 
2193
+ if (type === TYPES._bytestring && !Prefs.bytestring) type = TYPES.string;
2194
+
1765
2195
  // if (decl.name) console.log(decl.name, { type, elementType });
1766
2196
 
1767
2197
  return { type, typeName, elementType };
@@ -1778,6 +2208,8 @@ const generateVar = (scope, decl) => {
1778
2208
  for (const x of decl.declarations) {
1779
2209
  const name = mapName(x.id.name);
1780
2210
 
2211
+ if (!name) return todo(scope, 'destructuring is not supported yet');
2212
+
1781
2213
  if (x.init && isFuncType(x.init.type)) {
1782
2214
  // hack for let a = function () { ... }
1783
2215
  x.init.id = { name };
@@ -1793,7 +2225,13 @@ const generateVar = (scope, decl) => {
1793
2225
  continue; // always ignore
1794
2226
  }
1795
2227
 
1796
- let idx = allocVar(scope, name, global);
2228
+ const typed = typedInput && x.id.typeAnnotation;
2229
+ let idx = allocVar(scope, name, global, !(typed && extractTypeAnnotation(x.id).type != null));
2230
+
2231
+ if (typed) {
2232
+ addVarMetadata(scope, name, global, extractTypeAnnotation(x.id));
2233
+ }
2234
+
1797
2235
  if (x.init) {
1798
2236
  out = out.concat(generate(scope, x.init, global, name));
1799
2237
 
@@ -1803,16 +2241,13 @@ const generateVar = (scope, decl) => {
1803
2241
 
1804
2242
  // hack: this follows spec properly but is mostly unneeded 😅
1805
2243
  // out.push(...setType(scope, name, x.init ? getNodeType(scope, x.init) : TYPES.undefined));
1806
-
1807
- if (typedInput && x.id.typeAnnotation) {
1808
- addVarMetadata(scope, name, global, extractTypeAnnotation(x.id));
1809
- }
1810
2244
  }
1811
2245
 
1812
2246
  return out;
1813
2247
  };
1814
2248
 
1815
- const generateAssign = (scope, decl) => {
2249
+ // todo: optimize this func for valueUnused
2250
+ const generateAssign = (scope, decl, _global, _name, valueUnused = false) => {
1816
2251
  const { type, name } = decl.left;
1817
2252
 
1818
2253
  if (type === 'ObjectPattern') {
@@ -1830,9 +2265,9 @@ const generateAssign = (scope, decl) => {
1830
2265
  // hack: .length setter
1831
2266
  if (decl.left.type === 'MemberExpression' && decl.left.property.name === 'length') {
1832
2267
  const name = decl.left.object.name;
1833
- const pointer = arrays.get(name);
2268
+ const pointer = scope.arrays?.get(name);
1834
2269
 
1835
- const aotPointer = pointer != null;
2270
+ const aotPointer = Prefs.aotPointerOpt && pointer != null;
1836
2271
 
1837
2272
  const newValueTmp = localTmp(scope, '__length_setter_tmp');
1838
2273
 
@@ -1857,9 +2292,9 @@ const generateAssign = (scope, decl) => {
1857
2292
  // arr[i]
1858
2293
  if (decl.left.type === 'MemberExpression' && decl.left.computed) {
1859
2294
  const name = decl.left.object.name;
1860
- const pointer = arrays.get(name);
2295
+ const pointer = scope.arrays?.get(name);
1861
2296
 
1862
- const aotPointer = pointer != null;
2297
+ const aotPointer = Prefs.aotPointerOpt && pointer != null;
1863
2298
 
1864
2299
  const newValueTmp = localTmp(scope, '__member_setter_val_tmp');
1865
2300
  const pointerTmp = op === '=' ? -1 : localTmp(scope, '__member_setter_ptr_tmp', Valtype.i32);
@@ -1915,6 +2350,8 @@ const generateAssign = (scope, decl) => {
1915
2350
  ];
1916
2351
  }
1917
2352
 
2353
+ if (!name) return todo(scope, 'destructuring is not supported yet', true);
2354
+
1918
2355
  const [ local, isGlobal ] = lookupName(scope, name);
1919
2356
 
1920
2357
  if (local === undefined) {
@@ -1961,9 +2398,7 @@ const generateAssign = (scope, decl) => {
1961
2398
  ], getType(scope, name), getNodeType(scope, decl.right), isGlobal, name, true),
1962
2399
  [ isGlobal ? Opcodes.global_get : Opcodes.local_get, local.idx ],
1963
2400
 
1964
- getLastType(scope),
1965
- // hack: type is idx+1
1966
- [ isGlobal ? Opcodes.global_set : Opcodes.local_set, local.idx + 1 ],
2401
+ ...setType(scope, name, getLastType(scope))
1967
2402
  ];
1968
2403
  }
1969
2404
 
@@ -1974,9 +2409,7 @@ const generateAssign = (scope, decl) => {
1974
2409
 
1975
2410
  // todo: string concat types
1976
2411
 
1977
- // hack: type is idx+1
1978
- ...number(TYPES.number, Valtype.i32),
1979
- [ isGlobal ? Opcodes.global_set : Opcodes.local_set, local.idx + 1 ],
2412
+ ...setType(scope, name, TYPES.number)
1980
2413
  ];
1981
2414
  };
1982
2415
 
@@ -2022,7 +2455,7 @@ const generateUnary = (scope, decl) => {
2022
2455
  return out;
2023
2456
  }
2024
2457
 
2025
- case 'delete':
2458
+ case 'delete': {
2026
2459
  let toReturn = true, toGenerate = true;
2027
2460
 
2028
2461
  if (decl.argument.type === 'Identifier') {
@@ -2044,38 +2477,60 @@ const generateUnary = (scope, decl) => {
2044
2477
 
2045
2478
  out.push(...number(toReturn ? 1 : 0));
2046
2479
  return out;
2480
+ }
2481
+
2482
+ case 'typeof': {
2483
+ let overrideType, toGenerate = true;
2484
+
2485
+ if (decl.argument.type === 'Identifier') {
2486
+ const out = generateIdent(scope, decl.argument);
2487
+
2488
+ // if ReferenceError (undeclared var), ignore and return undefined
2489
+ if (out[1]) {
2490
+ // does not exist (2 ops from throw)
2491
+ overrideType = number(TYPES.undefined, Valtype.i32);
2492
+ toGenerate = false;
2493
+ }
2494
+ }
2495
+
2496
+ const out = toGenerate ? generate(scope, decl.argument) : [];
2497
+ disposeLeftover(out);
2047
2498
 
2048
- case 'typeof':
2049
- return typeSwitch(scope, getNodeType(scope, decl.argument), {
2499
+ out.push(...typeSwitch(scope, overrideType ?? getNodeType(scope, decl.argument), {
2050
2500
  [TYPES.number]: makeString(scope, 'number', false, '#typeof_result'),
2051
2501
  [TYPES.boolean]: makeString(scope, 'boolean', false, '#typeof_result'),
2052
2502
  [TYPES.string]: makeString(scope, 'string', false, '#typeof_result'),
2053
2503
  [TYPES.undefined]: makeString(scope, 'undefined', false, '#typeof_result'),
2054
2504
  [TYPES.function]: makeString(scope, 'function', false, '#typeof_result'),
2055
2505
 
2506
+ [TYPES._bytestring]: makeString(scope, 'string', false, '#typeof_result'),
2507
+
2056
2508
  // object and internal types
2057
2509
  default: makeString(scope, 'object', false, '#typeof_result'),
2058
- });
2510
+ }));
2511
+
2512
+ return out;
2513
+ }
2059
2514
 
2060
2515
  default:
2061
- return todo(`unary operator ${decl.operator} not implemented yet`);
2516
+ return todo(scope, `unary operator ${decl.operator} not implemented yet`, true);
2062
2517
  }
2063
2518
  };
2064
2519
 
2065
- const generateUpdate = (scope, decl) => {
2520
+ const generateUpdate = (scope, decl, _global, _name, valueUnused = false) => {
2066
2521
  const { name } = decl.argument;
2067
2522
 
2068
2523
  const [ local, isGlobal ] = lookupName(scope, name);
2069
2524
 
2070
2525
  if (local === undefined) {
2071
- return todo(`update expression with undefined variable`);
2526
+ return todo(scope, `update expression with undefined variable`, true);
2072
2527
  }
2073
2528
 
2074
2529
  const idx = local.idx;
2075
2530
  const out = [];
2076
2531
 
2077
2532
  out.push([ isGlobal ? Opcodes.global_get : Opcodes.local_get, idx ]);
2078
- if (!decl.prefix) out.push([ isGlobal ? Opcodes.global_get : Opcodes.local_get, idx ]);
2533
+ if (!decl.prefix && !valueUnused) out.push([ isGlobal ? Opcodes.global_get : Opcodes.local_get, idx ]);
2079
2534
 
2080
2535
  switch (decl.operator) {
2081
2536
  case '++':
@@ -2088,7 +2543,7 @@ const generateUpdate = (scope, decl) => {
2088
2543
  }
2089
2544
 
2090
2545
  out.push([ isGlobal ? Opcodes.global_set : Opcodes.local_set, idx ]);
2091
- if (decl.prefix) out.push([ isGlobal ? Opcodes.global_get : Opcodes.local_get, idx ]);
2546
+ if (decl.prefix && !valueUnused) out.push([ isGlobal ? Opcodes.global_get : Opcodes.local_get, idx ]);
2092
2547
 
2093
2548
  return out;
2094
2549
  };
@@ -2128,7 +2583,7 @@ const generateConditional = (scope, decl) => {
2128
2583
  // note type
2129
2584
  out.push(
2130
2585
  ...getNodeType(scope, decl.consequent),
2131
- setLastType(scope)
2586
+ ...setLastType(scope)
2132
2587
  );
2133
2588
 
2134
2589
  out.push([ Opcodes.else ]);
@@ -2137,7 +2592,7 @@ const generateConditional = (scope, decl) => {
2137
2592
  // note type
2138
2593
  out.push(
2139
2594
  ...getNodeType(scope, decl.alternate),
2140
- setLastType(scope)
2595
+ ...setLastType(scope)
2141
2596
  );
2142
2597
 
2143
2598
  out.push([ Opcodes.end ]);
@@ -2151,15 +2606,17 @@ const generateFor = (scope, decl) => {
2151
2606
  const out = [];
2152
2607
 
2153
2608
  if (decl.init) {
2154
- out.push(...generate(scope, decl.init));
2609
+ out.push(...generate(scope, decl.init, false, undefined, true));
2155
2610
  disposeLeftover(out);
2156
2611
  }
2157
2612
 
2158
2613
  out.push([ Opcodes.loop, Blocktype.void ]);
2159
2614
  depth.push('for');
2160
2615
 
2161
- out.push(...generate(scope, decl.test));
2162
- out.push(Opcodes.i32_to, [ Opcodes.if, Blocktype.void ]);
2616
+ if (decl.test) out.push(...generate(scope, decl.test), Opcodes.i32_to);
2617
+ else out.push(...number(1, Valtype.i32));
2618
+
2619
+ out.push([ Opcodes.if, Blocktype.void ]);
2163
2620
  depth.push('if');
2164
2621
 
2165
2622
  out.push([ Opcodes.block, Blocktype.void ]);
@@ -2167,8 +2624,7 @@ const generateFor = (scope, decl) => {
2167
2624
  out.push(...generate(scope, decl.body));
2168
2625
  out.push([ Opcodes.end ]);
2169
2626
 
2170
- out.push(...generate(scope, decl.update));
2171
- depth.pop();
2627
+ if (decl.update) out.push(...generate(scope, decl.update, false, undefined, true));
2172
2628
 
2173
2629
  out.push([ Opcodes.br, 1 ]);
2174
2630
  out.push([ Opcodes.end ], [ Opcodes.end ]);
@@ -2196,6 +2652,36 @@ const generateWhile = (scope, decl) => {
2196
2652
  return out;
2197
2653
  };
2198
2654
 
2655
+ const generateDoWhile = (scope, decl) => {
2656
+ const out = [];
2657
+
2658
+ out.push([ Opcodes.loop, Blocktype.void ]);
2659
+ depth.push('dowhile');
2660
+
2661
+ // block for break (includes all)
2662
+ out.push([ Opcodes.block, Blocktype.void ]);
2663
+ depth.push('block');
2664
+
2665
+ // block for continue
2666
+ // includes body but not test+loop so we can exit body at anytime
2667
+ // and still test+loop after
2668
+ out.push([ Opcodes.block, Blocktype.void ]);
2669
+ depth.push('block');
2670
+
2671
+ out.push(...generate(scope, decl.body));
2672
+
2673
+ out.push([ Opcodes.end ]);
2674
+ depth.pop();
2675
+
2676
+ out.push(...generate(scope, decl.test), Opcodes.i32_to);
2677
+ out.push([ Opcodes.br_if, 1 ]);
2678
+
2679
+ out.push([ Opcodes.end ], [ Opcodes.end ]);
2680
+ depth.pop(); depth.pop();
2681
+
2682
+ return out;
2683
+ };
2684
+
2199
2685
  const generateForOf = (scope, decl) => {
2200
2686
  const out = [];
2201
2687
 
@@ -2225,8 +2711,17 @@ const generateForOf = (scope, decl) => {
2225
2711
  // setup local for left
2226
2712
  generate(scope, decl.left);
2227
2713
 
2228
- const leftName = decl.left.declarations[0].id.name;
2714
+ let leftName = decl.left.declarations?.[0]?.id?.name;
2715
+ if (!leftName && decl.left.name) {
2716
+ leftName = decl.left.name;
2717
+
2718
+ generateVar(scope, { kind: 'var', _bare: true, declarations: [ { id: { name: leftName } } ] })
2719
+ }
2720
+
2721
+ // if (!leftName) console.log(decl.left?.declarations?.[0]?.id ?? decl.left);
2722
+
2229
2723
  const [ local, isGlobal ] = lookupName(scope, leftName);
2724
+ if (!local) return todo(scope, 'for of failed to get left local (probably destructure)');
2230
2725
 
2231
2726
  depth.push('block');
2232
2727
  depth.push('block');
@@ -2234,13 +2729,15 @@ const generateForOf = (scope, decl) => {
2234
2729
  // // todo: we should only do this for strings but we don't know at compile-time :(
2235
2730
  // hack: this is naughty and will break things!
2236
2731
  let newOut = number(0, Valtype.f64), newPointer = -1;
2237
- if (pages.hasString) {
2732
+ if (pages.hasAnyString) {
2733
+ // todo: we use i16 even for bytestrings which should not make a bad thing happen, just be confusing for debugging?
2238
2734
  0, [ newOut, newPointer ] = makeArray(scope, {
2239
2735
  rawElements: new Array(1)
2240
2736
  }, isGlobal, leftName, true, 'i16');
2241
2737
  }
2242
2738
 
2243
2739
  // set type for local
2740
+ // todo: optimize away counter and use end pointer
2244
2741
  out.push(...typeSwitch(scope, getNodeType(scope, decl.right), {
2245
2742
  [TYPES._array]: [
2246
2743
  ...setType(scope, leftName, TYPES.number),
@@ -2325,6 +2822,56 @@ const generateForOf = (scope, decl) => {
2325
2822
  [ Opcodes.end ],
2326
2823
  [ Opcodes.end ]
2327
2824
  ],
2825
+ [TYPES._bytestring]: [
2826
+ ...setType(scope, leftName, TYPES._bytestring),
2827
+
2828
+ [ Opcodes.loop, Blocktype.void ],
2829
+
2830
+ // setup new/out array
2831
+ ...newOut,
2832
+ [ Opcodes.drop ],
2833
+
2834
+ ...number(0, Valtype.i32), // base 0 for store after
2835
+
2836
+ // load current string ind {arg}
2837
+ [ Opcodes.local_get, pointer ],
2838
+ [ Opcodes.local_get, counter ],
2839
+ [ Opcodes.i32_add ],
2840
+ [ Opcodes.i32_load8_u, 0, ...unsignedLEB128(ValtypeSize.i32) ],
2841
+
2842
+ // store to new string ind 0
2843
+ [ Opcodes.i32_store8, 0, ...unsignedLEB128(newPointer + ValtypeSize.i32) ],
2844
+
2845
+ // return new string (page)
2846
+ ...number(newPointer),
2847
+
2848
+ [ isGlobal ? Opcodes.global_set : Opcodes.local_set, local.idx ],
2849
+
2850
+ [ Opcodes.block, Blocktype.void ],
2851
+ [ Opcodes.block, Blocktype.void ],
2852
+ ...generate(scope, decl.body),
2853
+ [ Opcodes.end ],
2854
+
2855
+ // increment iter pointer
2856
+ // [ Opcodes.local_get, pointer ],
2857
+ // ...number(1, Valtype.i32),
2858
+ // [ Opcodes.i32_add ],
2859
+ // [ Opcodes.local_set, pointer ],
2860
+
2861
+ // increment counter by 1
2862
+ [ Opcodes.local_get, counter ],
2863
+ ...number(1, Valtype.i32),
2864
+ [ Opcodes.i32_add ],
2865
+ [ Opcodes.local_tee, counter ],
2866
+
2867
+ // loop if counter != length
2868
+ [ Opcodes.local_get, length ],
2869
+ [ Opcodes.i32_ne ],
2870
+ [ Opcodes.br_if, 1 ],
2871
+
2872
+ [ Opcodes.end ],
2873
+ [ Opcodes.end ]
2874
+ ],
2328
2875
  default: internalThrow(scope, 'TypeError', `Tried for..of on non-iterable type`)
2329
2876
  }, Blocktype.void));
2330
2877
 
@@ -2335,28 +2882,65 @@ const generateForOf = (scope, decl) => {
2335
2882
  return out;
2336
2883
  };
2337
2884
 
2885
+ // find the nearest loop in depth map by type
2338
2886
  const getNearestLoop = () => {
2339
2887
  for (let i = depth.length - 1; i >= 0; i--) {
2340
- if (depth[i] === 'while' || depth[i] === 'for' || depth[i] === 'forof') return i;
2888
+ if (['while', 'dowhile', 'for', 'forof'].includes(depth[i])) return i;
2341
2889
  }
2342
2890
 
2343
2891
  return -1;
2344
2892
  };
2345
2893
 
2346
2894
  const generateBreak = (scope, decl) => {
2347
- const nearestLoop = depth.length - getNearestLoop();
2895
+ const target = decl.label ? scope.labels.get(decl.label.name) : getNearestLoop();
2896
+ const type = depth[target];
2897
+
2898
+ // different loop types have different branch offsets
2899
+ // as they have different wasm block/loop/if structures
2900
+ // we need to use the right offset by type to branch to the one we want
2901
+ // for a break: exit the loop without executing anything else inside it
2902
+ const offset = ({
2903
+ for: 2, // loop > if (wanted branch) > block (we are here)
2904
+ while: 2, // loop > if (wanted branch) (we are here)
2905
+ dowhile: 2, // loop > block (wanted branch) > block (we are here)
2906
+ forof: 2, // loop > block (wanted branch) > block (we are here)
2907
+ if: 1 // break inside if, branch 0 to skip the rest of the if
2908
+ })[type];
2909
+
2348
2910
  return [
2349
- [ Opcodes.br, ...signedLEB128(nearestLoop - 2) ]
2911
+ [ Opcodes.br, ...signedLEB128(depth.length - target - offset) ]
2350
2912
  ];
2351
2913
  };
2352
2914
 
2353
2915
  const generateContinue = (scope, decl) => {
2354
- const nearestLoop = depth.length - getNearestLoop();
2916
+ const target = decl.label ? scope.labels.get(decl.label.name) : getNearestLoop();
2917
+ const type = depth[target];
2918
+
2919
+ // different loop types have different branch offsets
2920
+ // as they have different wasm block/loop/if structures
2921
+ // we need to use the right offset by type to branch to the one we want
2922
+ // for a continue: do test for the loop, and then loop depending on that success
2923
+ const offset = ({
2924
+ for: 3, // loop (wanted branch) > if > block (we are here)
2925
+ while: 1, // loop (wanted branch) > if (we are here)
2926
+ dowhile: 3, // loop > block > block (wanted branch) (we are here)
2927
+ forof: 3 // loop > block > block (wanted branch) (we are here)
2928
+ })[type];
2929
+
2355
2930
  return [
2356
- [ Opcodes.br, ...signedLEB128(nearestLoop - 3) ]
2931
+ [ Opcodes.br, ...signedLEB128(depth.length - target - offset) ]
2357
2932
  ];
2358
2933
  };
2359
2934
 
2935
+ const generateLabel = (scope, decl) => {
2936
+ scope.labels ??= new Map();
2937
+
2938
+ const name = decl.label.name;
2939
+ scope.labels.set(name, depth.length);
2940
+
2941
+ return generate(scope, decl.body);
2942
+ };
2943
+
2360
2944
  const generateThrow = (scope, decl) => {
2361
2945
  scope.throws = true;
2362
2946
 
@@ -2365,7 +2949,7 @@ const generateThrow = (scope, decl) => {
2365
2949
  // hack: throw new X("...") -> throw "..."
2366
2950
  if (!message && (decl.argument.type === 'NewExpression' || decl.argument.type === 'CallExpression')) {
2367
2951
  constructor = decl.argument.callee.name;
2368
- message = decl.argument.arguments[0].value;
2952
+ message = decl.argument.arguments[0]?.value ?? '';
2369
2953
  }
2370
2954
 
2371
2955
  if (tags.length === 0) tags.push({
@@ -2377,6 +2961,9 @@ const generateThrow = (scope, decl) => {
2377
2961
  let exceptId = exceptions.push({ constructor, message }) - 1;
2378
2962
  let tagIdx = tags[0].idx;
2379
2963
 
2964
+ scope.exceptions ??= [];
2965
+ scope.exceptions.push(exceptId);
2966
+
2380
2967
  // todo: write a description of how this works lol
2381
2968
 
2382
2969
  return [
@@ -2386,7 +2973,7 @@ const generateThrow = (scope, decl) => {
2386
2973
  };
2387
2974
 
2388
2975
  const generateTry = (scope, decl) => {
2389
- if (decl.finalizer) return todo('try finally not implemented yet');
2976
+ if (decl.finalizer) return todo(scope, 'try finally not implemented yet');
2390
2977
 
2391
2978
  const out = [];
2392
2979
 
@@ -2417,29 +3004,35 @@ const generateAssignPat = (scope, decl) => {
2417
3004
  // TODO
2418
3005
  // if identifier declared, use that
2419
3006
  // else, use default (right)
2420
- return todo('assignment pattern (optional arg)');
3007
+ return todo(scope, 'assignment pattern (optional arg)');
2421
3008
  };
2422
3009
 
2423
3010
  let pages = new Map();
2424
- const allocPage = (reason, type) => {
3011
+ const allocPage = (scope, reason, type) => {
2425
3012
  if (pages.has(reason)) return pages.get(reason).ind;
2426
3013
 
2427
3014
  if (reason.startsWith('array:')) pages.hasArray = true;
2428
3015
  if (reason.startsWith('string:')) pages.hasString = true;
3016
+ if (reason.startsWith('bytestring:')) pages.hasByteString = true;
3017
+ if (reason.includes('string:')) pages.hasAnyString = true;
2429
3018
 
2430
3019
  const ind = pages.size;
2431
3020
  pages.set(reason, { ind, type });
2432
3021
 
2433
- if (allocLog) log('alloc', `allocated new page of memory (${ind}) | ${reason} (type: ${type})`);
3022
+ scope.pages ??= new Map();
3023
+ scope.pages.set(reason, { ind, type });
3024
+
3025
+ if (Prefs.allocLog) log('alloc', `allocated new page of memory (${ind}) | ${reason} (type: ${type})`);
2434
3026
 
2435
3027
  return ind;
2436
3028
  };
2437
3029
 
3030
+ // todo: add scope.pages
2438
3031
  const freePage = reason => {
2439
3032
  const { ind } = pages.get(reason);
2440
3033
  pages.delete(reason);
2441
3034
 
2442
- if (allocLog) log('alloc', `freed page of memory (${ind}) | ${reason}`);
3035
+ if (Prefs.allocLog) log('alloc', `freed page of memory (${ind}) | ${reason}`);
2443
3036
 
2444
3037
  return ind;
2445
3038
  };
@@ -2459,38 +3052,51 @@ const StoreOps = {
2459
3052
  f64: Opcodes.f64_store,
2460
3053
 
2461
3054
  // expects i32 input!
2462
- i16: Opcodes.i32_store16
3055
+ i8: Opcodes.i32_store8,
3056
+ i16: Opcodes.i32_store16,
2463
3057
  };
2464
3058
 
2465
3059
  let data = [];
2466
3060
 
2467
- const compileBytes = (val, itemType, signed = true) => {
3061
+ const compileBytes = (val, itemType) => {
2468
3062
  // todo: this is a mess and needs confirming / ????
2469
3063
  switch (itemType) {
2470
3064
  case 'i8': return [ val % 256 ];
2471
- case 'i16': return [ val % 256, Math.floor(val / 256) ];
2472
-
2473
- case 'i32':
2474
- case 'i64':
2475
- return enforceFourBytes(signedLEB128(val));
3065
+ case 'i16': return [ val % 256, (val / 256 | 0) % 256 ];
3066
+ case 'i16': return [ val % 256, (val / 256 | 0) % 256 ];
3067
+ case 'i32': return [...new Uint8Array(new Int32Array([ val ]).buffer)];
3068
+ // todo: i64
2476
3069
 
2477
3070
  case 'f64': return ieee754_binary64(val);
2478
3071
  }
2479
3072
  };
2480
3073
 
3074
+ const getAllocType = itemType => {
3075
+ switch (itemType) {
3076
+ case 'i8': return 'bytestring';
3077
+ case 'i16': return 'string';
3078
+
3079
+ default: return 'array';
3080
+ }
3081
+ };
3082
+
2481
3083
  const makeArray = (scope, decl, global = false, name = '$undeclared', initEmpty = false, itemType = valtype) => {
2482
3084
  const out = [];
2483
3085
 
3086
+ scope.arrays ??= new Map();
3087
+
2484
3088
  let firstAssign = false;
2485
- if (!arrays.has(name) || name === '$undeclared') {
3089
+ if (!scope.arrays.has(name) || name === '$undeclared') {
2486
3090
  firstAssign = true;
2487
3091
 
2488
3092
  // todo: can we just have 1 undeclared array? probably not? but this is not really memory efficient
2489
3093
  const uniqueName = name === '$undeclared' ? name + Math.random().toString().slice(2) : name;
2490
- arrays.set(name, allocPage(`${itemType === 'i16' ? 'string' : 'array'}: ${uniqueName}`, itemType) * pageSize);
3094
+
3095
+ if (Prefs.scopedPageNames) scope.arrays.set(name, allocPage(scope, `${scope.name} | ${getAllocType(itemType)}: ${uniqueName}`, itemType) * pageSize);
3096
+ else scope.arrays.set(name, allocPage(scope, `${getAllocType(itemType)}: ${uniqueName}`, itemType) * pageSize);
2491
3097
  }
2492
3098
 
2493
- const pointer = arrays.get(name);
3099
+ const pointer = scope.arrays.get(name);
2494
3100
 
2495
3101
  const useRawElements = !!decl.rawElements;
2496
3102
  const elements = useRawElements ? decl.rawElements : decl.elements;
@@ -2498,19 +3104,25 @@ const makeArray = (scope, decl, global = false, name = '$undeclared', initEmpty
2498
3104
  const valtype = itemTypeToValtype[itemType];
2499
3105
  const length = elements.length;
2500
3106
 
2501
- if (firstAssign && useRawElements) {
2502
- let bytes = compileBytes(length, 'i32');
3107
+ if (firstAssign && useRawElements && !Prefs.noData) {
3108
+ // if length is 0 memory/data will just be 0000... anyway
3109
+ if (length !== 0) {
3110
+ let bytes = compileBytes(length, 'i32');
2503
3111
 
2504
- if (!initEmpty) for (let i = 0; i < length; i++) {
2505
- if (elements[i] == null) continue;
3112
+ if (!initEmpty) for (let i = 0; i < length; i++) {
3113
+ if (elements[i] == null) continue;
2506
3114
 
2507
- bytes.push(...compileBytes(elements[i], itemType));
2508
- }
3115
+ bytes.push(...compileBytes(elements[i], itemType));
3116
+ }
2509
3117
 
2510
- data.push({
2511
- offset: pointer,
2512
- bytes
2513
- });
3118
+ const ind = data.push({
3119
+ offset: pointer,
3120
+ bytes
3121
+ }) - 1;
3122
+
3123
+ scope.data ??= [];
3124
+ scope.data.push(ind);
3125
+ }
2514
3126
 
2515
3127
  // local value as pointer
2516
3128
  out.push(...number(pointer));
@@ -2533,7 +3145,7 @@ const makeArray = (scope, decl, global = false, name = '$undeclared', initEmpty
2533
3145
  out.push(
2534
3146
  ...number(0, Valtype.i32),
2535
3147
  ...(useRawElements ? number(elements[i], Valtype[valtype]) : generate(scope, elements[i])),
2536
- [ storeOp, Math.log2(ValtypeSize[itemType]) - 1, ...unsignedLEB128(pointer + ValtypeSize.i32 + i * ValtypeSize[itemType]) ]
3148
+ [ storeOp, (Math.log2(ValtypeSize[itemType]) || 1) - 1, ...unsignedLEB128(pointer + ValtypeSize.i32 + i * ValtypeSize[itemType]) ]
2537
3149
  );
2538
3150
  }
2539
3151
 
@@ -2543,31 +3155,56 @@ const makeArray = (scope, decl, global = false, name = '$undeclared', initEmpty
2543
3155
  return [ out, pointer ];
2544
3156
  };
2545
3157
 
2546
- const makeString = (scope, str, global = false, name = '$undeclared') => {
3158
+ const byteStringable = str => {
3159
+ if (!Prefs.bytestring) return false;
3160
+
3161
+ for (let i = 0; i < str.length; i++) {
3162
+ if (str.charCodeAt(i) > 0xFF) return false;
3163
+ }
3164
+
3165
+ return true;
3166
+ };
3167
+
3168
+ const makeString = (scope, str, global = false, name = '$undeclared', forceBytestring = undefined) => {
2547
3169
  const rawElements = new Array(str.length);
3170
+ let byteStringable = Prefs.bytestring;
2548
3171
  for (let i = 0; i < str.length; i++) {
2549
- rawElements[i] = str.charCodeAt(i);
3172
+ const c = str.charCodeAt(i);
3173
+ rawElements[i] = c;
3174
+
3175
+ if (byteStringable && c > 0xFF) byteStringable = false;
2550
3176
  }
2551
3177
 
3178
+ if (byteStringable && forceBytestring === false) byteStringable = false;
3179
+
2552
3180
  return makeArray(scope, {
2553
3181
  rawElements
2554
- }, global, name, false, 'i16')[0];
3182
+ }, global, name, false, byteStringable ? 'i8' : 'i16')[0];
2555
3183
  };
2556
3184
 
2557
- let arrays = new Map();
2558
3185
  const generateArray = (scope, decl, global = false, name = '$undeclared', initEmpty = false) => {
2559
3186
  return makeArray(scope, decl, global, name, initEmpty, valtype)[0];
2560
3187
  };
2561
3188
 
2562
3189
  export const generateMember = (scope, decl, _global, _name) => {
2563
3190
  const name = decl.object.name;
2564
- const pointer = arrays.get(name);
3191
+ const pointer = scope.arrays?.get(name);
2565
3192
 
2566
- const aotPointer = pointer != null;
3193
+ const aotPointer = Prefs.aotPointerOpt && pointer != null;
2567
3194
 
2568
3195
  // hack: .length
2569
3196
  if (decl.property.name === 'length') {
2570
- // if (![TYPES._array, TYPES.string].includes(type)) return number(UNDEFINED);
3197
+ const func = funcs.find(x => x.name === name);
3198
+ if (func) {
3199
+ const userFunc = funcIndex[name] && !importedFuncs[name] && !builtinFuncs[name] && !internalConstrs[name];
3200
+ const typedParams = userFunc || builtinFuncs[name]?.typedParams;
3201
+ return number(typedParams ? func.params.length / 2 : func.params.length);
3202
+ }
3203
+
3204
+ if (builtinFuncs[name]) return number(builtinFuncs[name].typedParams ? (builtinFuncs[name].params.length / 2) : builtinFuncs[name].params.length);
3205
+ if (importedFuncs[name]) return number(importedFuncs[name].params);
3206
+ if (internalConstrs[name]) return number(internalConstrs[name].length ?? 0);
3207
+
2571
3208
  return [
2572
3209
  ...(aotPointer ? number(0, Valtype.i32) : [
2573
3210
  ...generate(scope, decl.object),
@@ -2579,10 +3216,13 @@ export const generateMember = (scope, decl, _global, _name) => {
2579
3216
  ];
2580
3217
  }
2581
3218
 
3219
+ const object = generate(scope, decl.object);
3220
+ const property = generate(scope, decl.property);
3221
+
2582
3222
  // // todo: we should only do this for strings but we don't know at compile-time :(
2583
3223
  // hack: this is naughty and will break things!
2584
- let newOut = number(0, Valtype.f64), newPointer = -1;
2585
- if (pages.hasString) {
3224
+ let newOut = number(0, valtypeBinary), newPointer = -1;
3225
+ if (pages.hasAnyString) {
2586
3226
  0, [ newOut, newPointer ] = makeArray(scope, {
2587
3227
  rawElements: new Array(1)
2588
3228
  }, _global, _name, true, 'i16');
@@ -2591,7 +3231,7 @@ export const generateMember = (scope, decl, _global, _name) => {
2591
3231
  return typeSwitch(scope, getNodeType(scope, decl.object), {
2592
3232
  [TYPES._array]: [
2593
3233
  // get index as valtype
2594
- ...generate(scope, decl.property),
3234
+ ...property,
2595
3235
 
2596
3236
  // convert to i32 and turn into byte offset by * valtypeSize (4 for i32, 8 for i64/f64)
2597
3237
  Opcodes.i32_to_u,
@@ -2599,7 +3239,7 @@ export const generateMember = (scope, decl, _global, _name) => {
2599
3239
  [ Opcodes.i32_mul ],
2600
3240
 
2601
3241
  ...(aotPointer ? [] : [
2602
- ...generate(scope, decl.object),
3242
+ ...object,
2603
3243
  Opcodes.i32_to_u,
2604
3244
  [ Opcodes.i32_add ]
2605
3245
  ]),
@@ -2608,7 +3248,7 @@ export const generateMember = (scope, decl, _global, _name) => {
2608
3248
  [ Opcodes.load, Math.log2(ValtypeSize[valtype]) - 1, ...unsignedLEB128((aotPointer ? pointer : 0) + ValtypeSize.i32) ],
2609
3249
 
2610
3250
  ...number(TYPES.number, Valtype.i32),
2611
- setLastType(scope)
3251
+ ...setLastType(scope)
2612
3252
  ],
2613
3253
 
2614
3254
  [TYPES.string]: [
@@ -2618,14 +3258,14 @@ export const generateMember = (scope, decl, _global, _name) => {
2618
3258
 
2619
3259
  ...number(0, Valtype.i32), // base 0 for store later
2620
3260
 
2621
- ...generate(scope, decl.property),
2622
-
3261
+ ...property,
2623
3262
  Opcodes.i32_to_u,
3263
+
2624
3264
  ...number(ValtypeSize.i16, Valtype.i32),
2625
3265
  [ Opcodes.i32_mul ],
2626
3266
 
2627
3267
  ...(aotPointer ? [] : [
2628
- ...generate(scope, decl.object),
3268
+ ...object,
2629
3269
  Opcodes.i32_to_u,
2630
3270
  [ Opcodes.i32_add ]
2631
3271
  ]),
@@ -2640,10 +3280,38 @@ export const generateMember = (scope, decl, _global, _name) => {
2640
3280
  ...number(newPointer),
2641
3281
 
2642
3282
  ...number(TYPES.string, Valtype.i32),
2643
- setLastType(scope)
3283
+ ...setLastType(scope)
3284
+ ],
3285
+ [TYPES._bytestring]: [
3286
+ // setup new/out array
3287
+ ...newOut,
3288
+ [ Opcodes.drop ],
3289
+
3290
+ ...number(0, Valtype.i32), // base 0 for store later
3291
+
3292
+ ...property,
3293
+ Opcodes.i32_to_u,
3294
+
3295
+ ...(aotPointer ? [] : [
3296
+ ...object,
3297
+ Opcodes.i32_to_u,
3298
+ [ Opcodes.i32_add ]
3299
+ ]),
3300
+
3301
+ // load current string ind {arg}
3302
+ [ Opcodes.i32_load8_u, 0, ...unsignedLEB128((aotPointer ? pointer : 0) + ValtypeSize.i32) ],
3303
+
3304
+ // store to new string ind 0
3305
+ [ Opcodes.i32_store8, 0, ...unsignedLEB128(newPointer + ValtypeSize.i32) ],
3306
+
3307
+ // return new string (page)
3308
+ ...number(newPointer),
3309
+
3310
+ ...number(TYPES._bytestring, Valtype.i32),
3311
+ ...setLastType(scope)
2644
3312
  ],
2645
3313
 
2646
- default: [ [ Opcodes.unreachable ] ]
3314
+ default: internalThrow(scope, 'TypeError', 'Member expression is not supported for non-string non-array yet', true)
2647
3315
  });
2648
3316
  };
2649
3317
 
@@ -2653,25 +3321,36 @@ const objectHack = node => {
2653
3321
  if (!node) return node;
2654
3322
 
2655
3323
  if (node.type === 'MemberExpression') {
2656
- if (node.computed || node.optional) return node;
3324
+ const out = (() => {
3325
+ if (node.computed || node.optional) return;
2657
3326
 
2658
- let objectName = node.object.name;
3327
+ let objectName = node.object.name;
2659
3328
 
2660
- // if object is not identifier or another member exp, give up
2661
- if (node.object.type !== 'Identifier' && node.object.type !== 'MemberExpression') return node;
3329
+ // if object is not identifier or another member exp, give up
3330
+ if (node.object.type !== 'Identifier' && node.object.type !== 'MemberExpression') return;
3331
+ if (objectName && ['undefined', 'null', 'NaN', 'Infinity'].includes(objectName)) return;
2662
3332
 
2663
- if (!objectName) objectName = objectHack(node.object).name.slice(2);
3333
+ if (!objectName) objectName = objectHack(node.object)?.name?.slice?.(2);
2664
3334
 
2665
- // if .length, give up (hack within a hack!)
2666
- if (node.property.name === 'length') return node;
3335
+ // if .length, give up (hack within a hack!)
3336
+ if (node.property.name === 'length') {
3337
+ node.object = objectHack(node.object);
3338
+ return;
3339
+ }
2667
3340
 
2668
- const name = '__' + objectName + '_' + node.property.name;
2669
- if (codeLog) log('codegen', `object hack! ${node.object.name}.${node.property.name} -> ${name}`);
3341
+ // no object name, give up
3342
+ if (!objectName) return;
2670
3343
 
2671
- return {
2672
- type: 'Identifier',
2673
- name
2674
- };
3344
+ const name = '__' + objectName + '_' + node.property.name;
3345
+ if (Prefs.codeLog) log('codegen', `object hack! ${node.object.name}.${node.property.name} -> ${name}`);
3346
+
3347
+ return {
3348
+ type: 'Identifier',
3349
+ name
3350
+ };
3351
+ })();
3352
+
3353
+ if (out) return out;
2675
3354
  }
2676
3355
 
2677
3356
  for (const x in node) {
@@ -2685,8 +3364,8 @@ const objectHack = node => {
2685
3364
  };
2686
3365
 
2687
3366
  const generateFunc = (scope, decl) => {
2688
- if (decl.async) return todo('async functions are not supported');
2689
- if (decl.generator) return todo('generator functions are not supported');
3367
+ if (decl.async) return todo(scope, 'async functions are not supported');
3368
+ if (decl.generator) return todo(scope, 'generator functions are not supported');
2690
3369
 
2691
3370
  const name = decl.id ? decl.id.name : `anonymous_${randId()}`;
2692
3371
  const params = decl.params ?? [];
@@ -2702,6 +3381,11 @@ const generateFunc = (scope, decl) => {
2702
3381
  name
2703
3382
  };
2704
3383
 
3384
+ if (typedInput && decl.returnType) {
3385
+ innerScope.returnType = extractTypeAnnotation(decl.returnType).type;
3386
+ innerScope.returns = [ valtypeBinary ];
3387
+ }
3388
+
2705
3389
  for (let i = 0; i < params.length; i++) {
2706
3390
  allocVar(innerScope, params[i].name, false);
2707
3391
 
@@ -2723,13 +3407,13 @@ const generateFunc = (scope, decl) => {
2723
3407
  const func = {
2724
3408
  name,
2725
3409
  params: Object.values(innerScope.locals).slice(0, params.length * 2).map(x => x.type),
2726
- returns: innerScope.returns,
2727
- locals: innerScope.locals,
2728
- throws: innerScope.throws,
2729
- index: currentFuncIndex++
3410
+ index: currentFuncIndex++,
3411
+ ...innerScope
2730
3412
  };
2731
3413
  funcIndex[name] = func.index;
2732
3414
 
3415
+ if (name === 'main') func.gotLastType = true;
3416
+
2733
3417
  // quick hack fixes
2734
3418
  for (const inst of wasm) {
2735
3419
  if (inst[0] === Opcodes.call && inst[1] === -1) {
@@ -2781,7 +3465,7 @@ const internalConstrs = {
2781
3465
 
2782
3466
  // todo: check in wasm instead of here
2783
3467
  const literalValue = arg.value ?? 0;
2784
- if (literalValue < 0 || !Number.isFinite(literalValue) || literalValue > 4294967295) return internalThrow(scope, 'RangeThrow', 'Invalid array length');
3468
+ if (literalValue < 0 || !Number.isFinite(literalValue) || literalValue > 4294967295) return internalThrow(scope, 'RangeThrow', 'Invalid array length', true);
2785
3469
 
2786
3470
  return [
2787
3471
  ...number(0, Valtype.i32),
@@ -2792,7 +3476,8 @@ const internalConstrs = {
2792
3476
  ...number(pointer)
2793
3477
  ];
2794
3478
  },
2795
- type: TYPES._array
3479
+ type: TYPES._array,
3480
+ length: 1
2796
3481
  },
2797
3482
 
2798
3483
  __Array_of: {
@@ -2804,7 +3489,98 @@ const internalConstrs = {
2804
3489
  }, global, name);
2805
3490
  },
2806
3491
  type: TYPES._array,
3492
+ notConstr: true,
3493
+ length: 0
3494
+ },
3495
+
3496
+ __Porffor_fastOr: {
3497
+ generate: (scope, decl) => {
3498
+ const out = [];
3499
+
3500
+ for (let i = 0; i < decl.arguments.length; i++) {
3501
+ out.push(
3502
+ ...generate(scope, decl.arguments[i]),
3503
+ Opcodes.i32_to_u,
3504
+ ...(i > 0 ? [ [ Opcodes.i32_or ] ] : [])
3505
+ );
3506
+ }
3507
+
3508
+ out.push(Opcodes.i32_from_u);
3509
+
3510
+ return out;
3511
+ },
3512
+ type: TYPES.boolean,
3513
+ notConstr: true
3514
+ },
3515
+
3516
+ __Porffor_fastAnd: {
3517
+ generate: (scope, decl) => {
3518
+ const out = [];
3519
+
3520
+ for (let i = 0; i < decl.arguments.length; i++) {
3521
+ out.push(
3522
+ ...generate(scope, decl.arguments[i]),
3523
+ Opcodes.i32_to_u,
3524
+ ...(i > 0 ? [ [ Opcodes.i32_and ] ] : [])
3525
+ );
3526
+ }
3527
+
3528
+ out.push(Opcodes.i32_from_u);
3529
+
3530
+ return out;
3531
+ },
3532
+ type: TYPES.boolean,
2807
3533
  notConstr: true
3534
+ },
3535
+
3536
+ Boolean: {
3537
+ generate: (scope, decl) => {
3538
+ // todo: boolean object when used as constructor
3539
+ const arg = decl.arguments[0] ?? DEFAULT_VALUE;
3540
+ return truthy(scope, generate(scope, arg), getNodeType(scope, arg));
3541
+ },
3542
+ type: TYPES.boolean,
3543
+ length: 1
3544
+ },
3545
+
3546
+ __Math_max: {
3547
+ generate: (scope, decl) => {
3548
+ const out = [
3549
+ ...number(-Infinity)
3550
+ ];
3551
+
3552
+ for (let i = 0; i < decl.arguments.length; i++) {
3553
+ out.push(
3554
+ ...generate(scope, decl.arguments[i]),
3555
+ [ Opcodes.f64_max ]
3556
+ );
3557
+ }
3558
+
3559
+ return out;
3560
+ },
3561
+ type: TYPES.number,
3562
+ notConstr: true,
3563
+ length: 2
3564
+ },
3565
+
3566
+ __Math_min: {
3567
+ generate: (scope, decl) => {
3568
+ const out = [
3569
+ ...number(Infinity)
3570
+ ];
3571
+
3572
+ for (let i = 0; i < decl.arguments.length; i++) {
3573
+ out.push(
3574
+ ...generate(scope, decl.arguments[i]),
3575
+ [ Opcodes.f64_min ]
3576
+ );
3577
+ }
3578
+
3579
+ return out;
3580
+ },
3581
+ type: TYPES.number,
3582
+ notConstr: true,
3583
+ length: 2
2808
3584
  }
2809
3585
  };
2810
3586
 
@@ -2833,7 +3609,6 @@ export default program => {
2833
3609
  funcs = [];
2834
3610
  funcIndex = {};
2835
3611
  depth = [];
2836
- arrays = new Map();
2837
3612
  pages = new Map();
2838
3613
  data = [];
2839
3614
  currentFuncIndex = importedFuncs.length;
@@ -2847,6 +3622,10 @@ export default program => {
2847
3622
 
2848
3623
  const valtypeInd = ['i32', 'i64', 'f64'].indexOf(valtype);
2849
3624
 
3625
+ globalThis.pageSize = PageSize;
3626
+ const pageSizeOpt = process.argv.find(x => x.startsWith('-page-size='));
3627
+ if (pageSizeOpt) pageSize = parseInt(pageSizeOpt.split('=')[1]) * 1024;
3628
+
2850
3629
  // set generic opcodes for current valtype
2851
3630
  Opcodes.const = [ Opcodes.i32_const, Opcodes.i64_const, Opcodes.f64_const ][valtypeInd];
2852
3631
  Opcodes.eq = [ Opcodes.i32_eq, Opcodes.i64_eq, Opcodes.f64_eq ][valtypeInd];
@@ -2855,10 +3634,10 @@ export default program => {
2855
3634
  Opcodes.add = [ Opcodes.i32_add, Opcodes.i64_add, Opcodes.f64_add ][valtypeInd];
2856
3635
  Opcodes.sub = [ Opcodes.i32_sub, Opcodes.i64_sub, Opcodes.f64_sub ][valtypeInd];
2857
3636
 
2858
- Opcodes.i32_to = [ [ null ], [ Opcodes.i32_wrap_i64 ], Opcodes.i32_trunc_sat_f64_s ][valtypeInd];
2859
- Opcodes.i32_to_u = [ [ null ], [ Opcodes.i32_wrap_i64 ], Opcodes.i32_trunc_sat_f64_u ][valtypeInd];
2860
- Opcodes.i32_from = [ [ null ], [ Opcodes.i64_extend_i32_s ], [ Opcodes.f64_convert_i32_s ] ][valtypeInd];
2861
- Opcodes.i32_from_u = [ [ null ], [ Opcodes.i64_extend_i32_u ], [ Opcodes.f64_convert_i32_u ] ][valtypeInd];
3637
+ Opcodes.i32_to = [ [], [ Opcodes.i32_wrap_i64 ], Opcodes.i32_trunc_sat_f64_s ][valtypeInd];
3638
+ Opcodes.i32_to_u = [ [], [ Opcodes.i32_wrap_i64 ], Opcodes.i32_trunc_sat_f64_u ][valtypeInd];
3639
+ Opcodes.i32_from = [ [], [ Opcodes.i64_extend_i32_s ], [ Opcodes.f64_convert_i32_s ] ][valtypeInd];
3640
+ Opcodes.i32_from_u = [ [], [ Opcodes.i64_extend_i32_u ], [ Opcodes.f64_convert_i32_u ] ][valtypeInd];
2862
3641
 
2863
3642
  Opcodes.load = [ Opcodes.i32_load, Opcodes.i64_load, Opcodes.f64_load ][valtypeInd];
2864
3643
  Opcodes.store = [ Opcodes.i32_store, Opcodes.i64_store, Opcodes.f64_store ][valtypeInd];
@@ -2871,10 +3650,6 @@ export default program => {
2871
3650
 
2872
3651
  program.id = { name: 'main' };
2873
3652
 
2874
- globalThis.pageSize = PageSize;
2875
- const pageSizeOpt = process.argv.find(x => x.startsWith('-page-size='));
2876
- if (pageSizeOpt) pageSize = parseInt(pageSizeOpt.split('=')[1]) * 1024;
2877
-
2878
3653
  const scope = {
2879
3654
  locals: {},
2880
3655
  localInd: 0
@@ -2885,7 +3660,7 @@ export default program => {
2885
3660
  body: program.body
2886
3661
  };
2887
3662
 
2888
- if (process.argv.includes('-ast-log')) console.log(program.body.body);
3663
+ if (Prefs.astLog) console.log(JSON.stringify(program.body.body, null, 2));
2889
3664
 
2890
3665
  generateFunc(scope, program);
2891
3666
 
@@ -2902,7 +3677,11 @@ export default program => {
2902
3677
  }
2903
3678
 
2904
3679
  if (lastInst[0] === Opcodes.end || lastInst[0] === Opcodes.local_set || lastInst[0] === Opcodes.global_set) {
2905
- main.returns = [];
3680
+ if (lastInst[0] === Opcodes.local_set && lastInst[1] === main.locals['#last_type'].idx) {
3681
+ main.wasm.splice(main.wasm.length - 1, 1);
3682
+ } else {
3683
+ main.returns = [];
3684
+ }
2906
3685
  }
2907
3686
 
2908
3687
  if (lastInst[0] === Opcodes.call) {