jz 0.6.0 → 0.8.0

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 (63) hide show
  1. package/README.md +99 -72
  2. package/bench/README.md +253 -100
  3. package/bench/bench.svg +58 -81
  4. package/cli.js +85 -12
  5. package/dist/interop.js +1 -0
  6. package/dist/jz.js +6196 -0
  7. package/index.d.ts +126 -0
  8. package/index.js +222 -35
  9. package/interop.js +240 -141
  10. package/layout.js +34 -18
  11. package/module/array.js +99 -111
  12. package/module/collection.js +124 -30
  13. package/module/console.js +1 -1
  14. package/module/core.js +163 -19
  15. package/module/json.js +3 -3
  16. package/module/math.js +162 -3
  17. package/module/number.js +268 -13
  18. package/module/object.js +37 -5
  19. package/module/regex.js +8 -7
  20. package/module/simd.js +37 -5
  21. package/module/string.js +203 -168
  22. package/module/typedarray.js +565 -112
  23. package/package.json +26 -7
  24. package/src/abi/string.js +29 -29
  25. package/src/ast.js +19 -2
  26. package/src/autoload.js +3 -0
  27. package/src/compile/analyze-scans.js +174 -11
  28. package/src/compile/analyze.js +101 -4
  29. package/src/compile/cse-load.js +200 -0
  30. package/src/compile/emit-assign.js +82 -20
  31. package/src/compile/emit.js +592 -51
  32. package/src/compile/index.js +504 -89
  33. package/src/compile/infer.js +36 -1
  34. package/src/compile/loop-divmod.js +109 -0
  35. package/src/compile/loop-model.js +91 -0
  36. package/src/compile/loop-square.js +102 -0
  37. package/src/compile/narrow.js +275 -41
  38. package/src/compile/peel-stencil.js +215 -0
  39. package/src/compile/plan/advise.js +55 -1
  40. package/src/compile/plan/common.js +29 -0
  41. package/src/compile/plan/index.js +8 -1
  42. package/src/compile/plan/inline.js +180 -22
  43. package/src/compile/plan/literals.js +313 -24
  44. package/src/compile/plan/scope.js +115 -39
  45. package/src/compile/program-facts.js +21 -2
  46. package/src/ctx.js +96 -19
  47. package/src/helper-counters.js +137 -0
  48. package/src/ir.js +157 -20
  49. package/src/kind-traits.js +34 -3
  50. package/src/kind.js +79 -4
  51. package/src/op-policy.js +5 -2
  52. package/src/ops.js +119 -0
  53. package/src/optimize/index.js +1274 -151
  54. package/src/optimize/recurse.js +182 -0
  55. package/src/optimize/vectorize.js +4187 -253
  56. package/src/prepare/index.js +75 -14
  57. package/src/prepare/lift-iife.js +149 -0
  58. package/src/reps.js +6 -2
  59. package/src/static.js +9 -0
  60. package/src/type.js +63 -51
  61. package/src/wat/assemble.js +286 -21
  62. package/src/widen.js +21 -0
  63. package/src/wat/optimize.js +0 -3760
package/bench/bench.svg CHANGED
@@ -1,112 +1,89 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 500" width="720" height="500" role="img" aria-label="jz benchmark — each ball runs back and forth at a rate proportional to that engine's speed; jz is the 1.00× baseline, lower is faster">
2
- <rect width="720" height="500" rx="12" fill="#ffffff"/>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 424" width="720" height="424" style="color-scheme:light dark" role="img" aria-label="JZ benchmark — every rival compiled to WebAssembly, run in V8 · native C = reference; geometric mean across 38 benchmark cases · lower is faster, JZ = 1.00× baseline; each ball's speed is proportional to that engine's geometric-mean runtime across the corpus">
3
2
 
4
3
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
5
- <rect x="174" y="43.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
6
- <line x1="174" y1="38" x2="174" y2="52" stroke="#ced4da" stroke-width="2"/>
7
- <line x1="650" y1="38" x2="650" y2="52" stroke="#ced4da" stroke-width="2"/>
8
- <text x="156" y="41" text-anchor="end" font-size="14" font-weight="700" fill="#000000">jz</text>
9
- <text x="156" y="56" text-anchor="end" font-size="10" fill="#aeb4ba">→ wasm</text>
10
- <text x="662" y="49" font-size="13" font-weight="700" fill="#000000">1.00×</text>
11
- <circle cx="182.0" cy="45" r="8" fill="#000000">
4
+ <rect x="174" y="43.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
5
+ <line x1="174" y1="38" x2="174" y2="52" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
6
+ <line x1="650" y1="38" x2="650" y2="52" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
7
+ <text x="156" y="41" text-anchor="end" font-size="14" font-weight="700" fill="currentColor" fill-opacity="1">JZ</text>
8
+ <text x="156" y="56" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">-O3</text>
9
+ <text x="662" y="49" font-size="13" font-weight="700" fill="currentColor" fill-opacity="1">1.00×</text>
10
+ <circle cx="182.0" cy="45" r="8" fill="currentColor" fill-opacity="1">
12
11
  <animate attributeName="cx" dur="1.6s" repeatCount="indefinite" calcMode="linear"
13
12
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-0.00s"/>
14
13
  </circle>
15
14
  </g>
16
15
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
17
- <rect x="174" y="93.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
18
- <line x1="174" y1="88" x2="174" y2="102" stroke="#ced4da" stroke-width="2"/>
19
- <line x1="650" y1="88" x2="650" y2="102" stroke="#ced4da" stroke-width="2"/>
20
- <text x="156" y="91" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">Rust</text>
21
- <text x="156" y="106" text-anchor="end" font-size="10" fill="#aeb4ba">rustc -O3</text>
22
- <text x="662" y="99" font-size="13" font-weight="500" fill="#868e96">1.07×</text>
23
- <circle cx="182.0" cy="95" r="8" fill="#adb5bd">
24
- <animate attributeName="cx" dur="1.7111717105322697s" repeatCount="indefinite" calcMode="linear"
16
+ <rect x="174" y="93.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
17
+ <line x1="174" y1="88" x2="174" y2="102" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
18
+ <line x1="650" y1="88" x2="650" y2="102" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
19
+ <text x="156" y="91" text-anchor="end" font-size="14" font-weight="500" fill="currentColor" fill-opacity="0.82">native C</text>
20
+ <text x="156" y="106" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">clang -O3 · ref</text>
21
+ <text x="662" y="99" font-size="13" font-weight="500" fill="currentColor" fill-opacity="0.6">1.01×</text>
22
+ <circle cx="182.0" cy="95" r="8" fill="currentColor" fill-opacity="0.4">
23
+ <animate attributeName="cx" dur="1.6171275085641825s" repeatCount="indefinite" calcMode="linear"
25
24
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-0.41s"/>
26
25
  </circle>
27
26
  </g>
28
27
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
29
- <rect x="174" y="143.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
30
- <line x1="174" y1="138" x2="174" y2="152" stroke="#ced4da" stroke-width="2"/>
31
- <line x1="650" y1="138" x2="650" y2="152" stroke="#ced4da" stroke-width="2"/>
32
- <text x="156" y="141" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">Zig</text>
33
- <text x="156" y="156" text-anchor="end" font-size="10" fill="#aeb4ba">ReleaseFast</text>
34
- <text x="662" y="149" font-size="13" font-weight="500" fill="#868e96">1.31×</text>
35
- <circle cx="182.0" cy="145" r="8" fill="#adb5bd">
36
- <animate attributeName="cx" dur="2.097403438402887s" repeatCount="indefinite" calcMode="linear"
28
+ <rect x="174" y="143.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
29
+ <line x1="174" y1="138" x2="174" y2="152" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
30
+ <line x1="650" y1="138" x2="650" y2="152" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
31
+ <text x="156" y="141" text-anchor="end" font-size="14" font-weight="500" fill="currentColor" fill-opacity="0.82">C</text>
32
+ <text x="156" y="156" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">clang → wasm</text>
33
+ <text x="662" y="149" font-size="13" font-weight="500" fill="currentColor" fill-opacity="0.6">2.01×</text>
34
+ <circle cx="182.0" cy="145" r="8" fill="currentColor" fill-opacity="0.4">
35
+ <animate attributeName="cx" dur="3.214848718379708s" repeatCount="indefinite" calcMode="linear"
37
36
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-0.82s"/>
38
37
  </circle>
39
38
  </g>
40
39
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
41
- <rect x="174" y="193.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
42
- <line x1="174" y1="188" x2="174" y2="202" stroke="#ced4da" stroke-width="2"/>
43
- <line x1="650" y1="188" x2="650" y2="202" stroke="#ced4da" stroke-width="2"/>
44
- <text x="156" y="191" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">Bun</text>
45
- <text x="156" y="206" text-anchor="end" font-size="10" fill="#aeb4ba">JSC</text>
46
- <text x="662" y="199" font-size="13" font-weight="500" fill="#868e96">1.51×</text>
47
- <circle cx="182.0" cy="195" r="8" fill="#adb5bd">
48
- <animate attributeName="cx" dur="2.4126551201460966s" repeatCount="indefinite" calcMode="linear"
40
+ <rect x="174" y="193.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
41
+ <line x1="174" y1="188" x2="174" y2="202" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
42
+ <line x1="650" y1="188" x2="650" y2="202" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
43
+ <text x="156" y="191" text-anchor="end" font-size="14" font-weight="500" fill="currentColor" fill-opacity="0.82">Rust</text>
44
+ <text x="156" y="206" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">rustc → wasm</text>
45
+ <text x="662" y="199" font-size="13" font-weight="500" fill="currentColor" fill-opacity="0.6">2.05×</text>
46
+ <circle cx="182.0" cy="195" r="8" fill="currentColor" fill-opacity="0.4">
47
+ <animate attributeName="cx" dur="3.2852220400953436s" repeatCount="indefinite" calcMode="linear"
49
48
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-1.23s"/>
50
49
  </circle>
51
50
  </g>
52
51
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
53
- <rect x="174" y="243.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
54
- <line x1="174" y1="238" x2="174" y2="252" stroke="#ced4da" stroke-width="2"/>
55
- <line x1="650" y1="238" x2="650" y2="252" stroke="#ced4da" stroke-width="2"/>
56
- <text x="156" y="241" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">Go</text>
57
- <text x="156" y="256" text-anchor="end" font-size="10" fill="#aeb4ba">gc</text>
58
- <text x="662" y="249" font-size="13" font-weight="500" fill="#868e96">1.62×</text>
59
- <circle cx="182.0" cy="245" r="8" fill="#adb5bd">
60
- <animate attributeName="cx" dur="2.599256056991375s" repeatCount="indefinite" calcMode="linear"
52
+ <rect x="174" y="243.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
53
+ <line x1="174" y1="238" x2="174" y2="252" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
54
+ <line x1="650" y1="238" x2="650" y2="252" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
55
+ <text x="156" y="241" text-anchor="end" font-size="14" font-weight="500" fill="currentColor" fill-opacity="0.82">AssemblyScript</text>
56
+ <text x="156" y="256" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">asc -O3</text>
57
+ <text x="662" y="249" font-size="13" font-weight="500" fill="currentColor" fill-opacity="0.6">2.10×</text>
58
+ <circle cx="182.0" cy="245" r="8" fill="currentColor" fill-opacity="0.4">
59
+ <animate attributeName="cx" dur="3.3536253223690404s" repeatCount="indefinite" calcMode="linear"
61
60
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-1.64s"/>
62
61
  </circle>
63
62
  </g>
64
63
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
65
- <rect x="174" y="293.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
66
- <line x1="174" y1="288" x2="174" y2="302" stroke="#ced4da" stroke-width="2"/>
67
- <line x1="650" y1="288" x2="650" y2="302" stroke="#ced4da" stroke-width="2"/>
68
- <text x="156" y="291" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">V8</text>
69
- <text x="156" y="306" text-anchor="end" font-size="10" fill="#aeb4ba">Node</text>
70
- <text x="662" y="299" font-size="13" font-weight="500" fill="#868e96">1.98×</text>
71
- <circle cx="182.0" cy="295" r="8" fill="#adb5bd">
72
- <animate attributeName="cx" dur="3.161748945741268s" repeatCount="indefinite" calcMode="linear"
64
+ <rect x="174" y="293.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
65
+ <line x1="174" y1="288" x2="174" y2="302" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
66
+ <line x1="650" y1="288" x2="650" y2="302" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
67
+ <text x="156" y="291" text-anchor="end" font-size="14" font-weight="500" fill="currentColor" fill-opacity="0.82">V8</text>
68
+ <text x="156" y="306" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">Node (JS)</text>
69
+ <text x="662" y="299" font-size="13" font-weight="500" fill="currentColor" fill-opacity="0.6">2.33×</text>
70
+ <circle cx="182.0" cy="295" r="8" fill="currentColor" fill-opacity="0.4">
71
+ <animate attributeName="cx" dur="3.72980153913452s" repeatCount="indefinite" calcMode="linear"
73
72
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-2.05s"/>
74
73
  </circle>
75
74
  </g>
76
75
  <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
77
- <rect x="174" y="343.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
78
- <line x1="174" y1="338" x2="174" y2="352" stroke="#ced4da" stroke-width="2"/>
79
- <line x1="650" y1="338" x2="650" y2="352" stroke="#ced4da" stroke-width="2"/>
80
- <text x="156" y="341" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">AssemblyScript</text>
81
- <text x="156" y="356" text-anchor="end" font-size="10" fill="#aeb4ba">asc -O3</text>
82
- <text x="662" y="349" font-size="13" font-weight="500" fill="#868e96">2.02×</text>
83
- <circle cx="182.0" cy="345" r="8" fill="#adb5bd">
84
- <animate attributeName="cx" dur="3.234040602137033s" repeatCount="indefinite" calcMode="linear"
76
+ <rect x="174" y="343.5" width="476" height="3" rx="1.5" fill="currentColor" fill-opacity="0.1"/>
77
+ <line x1="174" y1="338" x2="174" y2="352" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
78
+ <line x1="650" y1="338" x2="650" y2="352" stroke="currentColor" stroke-opacity="0.3" stroke-width="2"/>
79
+ <text x="156" y="341" text-anchor="end" font-size="14" font-weight="500" fill="currentColor" fill-opacity="0.82">Porffor</text>
80
+ <text x="156" y="356" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.46">runs 4 / 38</text>
81
+ <text x="662" y="349" font-size="13" font-weight="500" fill="currentColor" fill-opacity="0.6">3.76×</text>
82
+ <circle cx="182.0" cy="345" r="8" fill="currentColor" fill-opacity="0.4">
83
+ <animate attributeName="cx" dur="6.023170795143817s" repeatCount="indefinite" calcMode="linear"
85
84
  keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-2.46s"/>
86
85
  </circle>
87
86
  </g>
88
- <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
89
- <rect x="174" y="393.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
90
- <line x1="174" y1="388" x2="174" y2="402" stroke="#ced4da" stroke-width="2"/>
91
- <line x1="650" y1="388" x2="650" y2="402" stroke="#ced4da" stroke-width="2"/>
92
- <text x="156" y="391" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">Porffor</text>
93
- <text x="156" y="406" text-anchor="end" font-size="10" fill="#aeb4ba">runs 3 / 13</text>
94
- <text x="662" y="399" font-size="13" font-weight="500" fill="#868e96">3.08×</text>
95
- <circle cx="182.0" cy="395" r="8" fill="#adb5bd">
96
- <animate attributeName="cx" dur="4.926330541139543s" repeatCount="indefinite" calcMode="linear"
97
- keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-2.87s"/>
98
- </circle>
99
- </g>
100
- <g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
101
- <rect x="174" y="443.5" width="476" height="3" rx="1.5" fill="#edf0f2"/>
102
- <line x1="174" y1="438" x2="174" y2="452" stroke="#ced4da" stroke-width="2"/>
103
- <line x1="650" y1="438" x2="650" y2="452" stroke="#ced4da" stroke-width="2"/>
104
- <text x="156" y="441" text-anchor="end" font-size="14" font-weight="500" fill="#343a40">NumPy</text>
105
- <text x="156" y="456" text-anchor="end" font-size="10" fill="#aeb4ba">Python</text>
106
- <text x="662" y="449" font-size="13" font-weight="500" fill="#868e96">8.31×</text>
107
- <circle cx="182.0" cy="445" r="8" fill="#adb5bd">
108
- <animate attributeName="cx" dur="10s" repeatCount="indefinite" calcMode="linear"
109
- keyTimes="0;0.5;1" values="182.0;642.0;182.0" begin="-3.28s"/>
110
- </circle>
111
- </g>
87
+ <text x="360" y="390" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif" font-size="11" font-weight="600" fill="currentColor" fill-opacity="0.72">every rival compiled to WebAssembly, run in V8 · native C = reference</text>
88
+ <text x="360" y="408" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif" font-size="11" fill="currentColor" fill-opacity="0.5">geometric mean across 38 benchmark cases · lower is faster, JZ = 1.00× baseline</text>
112
89
  </svg>
package/cli.js CHANGED
@@ -4,10 +4,17 @@
4
4
  * JZ CLI - Command-line interface for JZ compiler
5
5
  */
6
6
 
7
- import { readFileSync, writeFileSync } from 'fs'
8
- import { resolve } from 'path'
7
+ import { readFileSync, writeFileSync, mkdirSync } from 'fs'
8
+ import { resolve, dirname } from 'path'
9
9
  import { pathToFileURL } from 'url'
10
10
  import jz, { compile } from './index.js'
11
+
12
+ // Write to `file`, creating its parent directory first. `jz src.js -o dist/out.wasm`
13
+ // must not fail just because `dist/` doesn't exist yet — a fresh checkout where the
14
+ // output dir is gitignored (watr's `dist/`, jz's own build dir) is the common case,
15
+ // and every compiler that takes `-o path/file` is expected to make the path. Without
16
+ // this the CLI dies with `ENOENT: open 'dist/out.wasm'` (the watr CI build failure).
17
+ const writeOut = (file, data) => { mkdirSync(dirname(resolve(file)), { recursive: true }); writeFileSync(file, data) }
11
18
  import transform from './transform.js'
12
19
  import { resolveModuleGraph } from './src/resolve.js'
13
20
  import { createRequire } from 'module'
@@ -36,8 +43,10 @@ Examples:
36
43
  jz program.js --wat # → program.wat
37
44
  jz program.js -o out.wasm # custom output name
38
45
  jz program.js -o - # write to stdout
39
- jz program.js -O3 # aggressive optimization
46
+ jz program.js -O3 # optimize for speed
40
47
  jz program.js -Os # optimize for size
48
+ jz program.js -D DEBUG=false # inject a compile-time constant
49
+ jz program.js --memory 64 # 64 initial pages (4 MB)
41
50
  jz program.js --host wasi # emit WASI Preview 1 imports
42
51
  jz --strict program.js # strict mode
43
52
  jz --jzify lib.js # → lib.jz
@@ -45,11 +54,22 @@ Examples:
45
54
 
46
55
  Options:
47
56
  --output, -o <file> Output file (.wat, .wasm, or - for stdout)
48
- -O<n>, --optimize <n> Optimization level: 0 off, 1 size-only, 2 default,
49
- 3 aggressive. Aliases: -Os/size, -Ob/balanced, -Of/speed.
57
+ -O<n>, --optimize <n> Optimization level: 0 off, 1 minimal, 2 default (all
58
+ stable passes), 3 speed. -Os optimizes for size.
59
+ --define, -D <K=V> Inject a compile-time constant (VALUE parsed as JSON,
60
+ else string). Repeatable.
50
61
  --host <js|wasi> Runtime-service lowering (default js)
62
+ --memory <pages> Initial memory size in 64 KiB pages
63
+ --max-memory <pages> Cap memory growth at this many pages (default unbounded)
64
+ --import-memory Import env.memory instead of exporting own memory
51
65
  --no-alloc Omit _alloc/_clear allocator exports (standalone wasm)
66
+ --no-simd Disable auto-vectorization (no v128) for non-SIMD engines
67
+ --why-not-simd Report, per loop, why the auto-vectorizer declined it
68
+ --experimental-stencil Enable neighbour-load stencil vectorization (a[i±1]; opt-in)
69
+ --experimental-outer-strip Strip-mine pixel loops over an inner reduction to f64x2 (opt-in)
70
+ --no-tail-call Use ordinary call frames instead of return_call
52
71
  --names Emit wasm name section for profilers/debuggers
72
+ --stats Print compile-phase timings to stderr
53
73
  --strict Pure canonical subset: reject full-JS syntax + dynamic fallbacks
54
74
  --jzify Transform JS to jz source (no compilation)
55
75
  --eval, -e Evaluate expression or file
@@ -116,22 +136,52 @@ async function handleJzify(args) {
116
136
  if (outputFile === '-') {
117
137
  process.stdout.write(out)
118
138
  } else {
119
- writeFileSync(outputFile, out)
139
+ writeOut(outputFile, out)
120
140
  console.log(`${inputFile} → ${outputFile} (${out.length} chars)`)
121
141
  }
122
142
  }
123
143
 
124
- // -O<n>/-Os/-Ob/-Of and --optimize <val>value accepted by compile()'s `optimize` opt
125
- const OPT_ALIAS = { s: 'size', b: 'balanced', f: 'speed' }
144
+ // -O<n> numeric levels (0–3); -Os size preset. The 'size'/'speed' strings are
145
+ // also accepted via `--optimize <name>` for parity with the JS API (-O3 = speed).
146
+ const OPT_ALIAS = { s: 'size' }
126
147
  function parseOptimize(v) {
127
148
  if (v == null) return undefined
128
149
  if (/^\d+$/.test(v)) return +v
129
150
  return OPT_ALIAS[v] ?? v
130
151
  }
131
152
 
153
+ // -D NAME=VALUE / --define NAME=VALUE → [key, value]. VALUE is parsed as JSON when
154
+ // it can be (numbers, booleans, null, JSON arrays/objects); otherwise a bare string.
155
+ function parseDefine(s) {
156
+ const eq = s.indexOf('=')
157
+ if (eq === -1) throw new Error(`--define expects NAME=VALUE (got '${s}')`)
158
+ let value
159
+ try { value = JSON.parse(s.slice(eq + 1)) } catch { value = s.slice(eq + 1) }
160
+ return [s.slice(0, eq), value]
161
+ }
162
+
163
+ function parsePages(v, flag) {
164
+ const n = parseInt(v, 10)
165
+ if (!Number.isInteger(n) || n < 1) throw new Error(`${flag} expects a positive integer page count (64 KiB/page)`)
166
+ return n
167
+ }
168
+
169
+ // --stats: dump top-level compile-phase timings to stderr (stdout stays clean for
170
+ // `-o -`). Sub-phase (optMod:*) detail is left to the programmatic `profile` sink.
171
+ function printStats(profile) {
172
+ const rows = Object.entries(profile.totals || {}).filter(([n]) => !n.includes(':'))
173
+ if (!rows.length) return
174
+ const width = Math.max(5, ...rows.map(([n]) => n.length))
175
+ const total = rows.reduce((sum, [, ms]) => sum + ms, 0)
176
+ console.error('compile stats (ms):')
177
+ for (const [name, ms] of rows) console.error(` ${name.padEnd(width)} ${ms.toFixed(2)}`)
178
+ console.error(` ${'total'.padEnd(width)} ${total.toFixed(2)}`)
179
+ }
180
+
132
181
  async function handleCompile(args) {
133
182
  let inputFile = null, outputFile = null, wat = false, strict = false, resolveNode = false, importsFile = null
134
- let optimize, host, alloc = true, names = false
183
+ let optimize, host, alloc = true, names = false, stats = false, noSimd = false, noTailCall = false
184
+ let memory, maxMemory, importMemory = false, define, whyNotSimd = false, experimentalStencil = false, experimentalOuterStrip = false
135
185
 
136
186
  for (let i = 0; i < args.length; i++) {
137
187
  const a = args[i]
@@ -140,11 +190,22 @@ async function handleCompile(args) {
140
190
  else if (a === '--strict') strict = true
141
191
  else if (a === '--resolve') resolveNode = true
142
192
  else if (a === '--imports') importsFile = args[++i]
193
+ else if (a === '--define' || a === '-D') { const [k, v] = parseDefine(args[++i]); (define ||= {})[k] = v }
194
+ else if (a.startsWith('-D') && a.length > 2) { const [k, v] = parseDefine(a.slice(2)); (define ||= {})[k] = v }
143
195
  else if (a === '--optimize' || a === '-O') optimize = parseOptimize(args[++i])
144
196
  else if (/^-O.+/.test(a)) optimize = parseOptimize(a.slice(2))
145
197
  else if (a === '--host') host = args[++i]
198
+ else if (a === '--memory') memory = parsePages(args[++i], '--memory')
199
+ else if (a === '--max-memory') maxMemory = parsePages(args[++i], '--max-memory')
200
+ else if (a === '--import-memory') importMemory = true
146
201
  else if (a === '--no-alloc') alloc = false
202
+ else if (a === '--no-simd') noSimd = true
203
+ else if (a === '--why-not-simd') whyNotSimd = true
204
+ else if (a === '--experimental-stencil') experimentalStencil = true
205
+ else if (a === '--experimental-outer-strip') experimentalOuterStrip = true
206
+ else if (a === '--no-tail-call') noTailCall = true
147
207
  else if (a === '--names') names = true
208
+ else if (a === '--stats') stats = true
148
209
  else if (!inputFile) inputFile = a
149
210
  }
150
211
 
@@ -161,6 +222,7 @@ async function handleCompile(args) {
161
222
  // `.jz` files are treated as strict; `--strict` forces it for any extension.
162
223
  if (inputFile.endsWith('.jz')) strict = true
163
224
  const warnings = { entries: [] }
225
+ const profile = stats ? {} : null
164
226
  const opts = {
165
227
  wat,
166
228
  warnings,
@@ -168,8 +230,18 @@ async function handleCompile(args) {
168
230
  importMetaUrl: pathToFileURL(resolve(inputFile)).href,
169
231
  ...(optimize !== undefined && { optimize }),
170
232
  ...(host && { host }),
233
+ ...(memory !== undefined && { memory }),
234
+ ...(maxMemory !== undefined && { maxMemory }),
235
+ ...(importMemory && { importMemory: true }),
171
236
  ...(alloc === false && { alloc: false }),
172
- ...(names && { profile: { names: true } }),
237
+ ...(noSimd && { noSimd: true }),
238
+ ...(whyNotSimd && { whyNotSimd: true }),
239
+ ...(experimentalStencil && { experimentalStencil: true }),
240
+ ...(experimentalOuterStrip && { experimentalOuterStrip: true }),
241
+ ...(noTailCall && { noTailCall: true }),
242
+ ...(define && { define }),
243
+ ...(names && { names: true }),
244
+ ...(profile && { profile }),
173
245
  ...(Object.keys(modules).length && { modules }),
174
246
  }
175
247
 
@@ -182,14 +254,15 @@ async function handleCompile(args) {
182
254
 
183
255
  for (const w of warnings.entries)
184
256
  console.warn(formatWarning(w))
257
+ if (profile) printStats(profile)
185
258
 
186
259
  if (outputFile === '-') {
187
260
  process.stdout.write(result)
188
261
  } else if (wat) {
189
- writeFileSync(outputFile, result)
262
+ writeOut(outputFile, result)
190
263
  console.log(`${inputFile} → ${outputFile} (${result.length} chars)`)
191
264
  } else {
192
- writeFileSync(outputFile, result)
265
+ writeOut(outputFile, result)
193
266
  console.log(`${inputFile} → ${outputFile} (${result.byteLength} bytes)`)
194
267
  }
195
268
  }
@@ -0,0 +1 @@
1
+ var ge=new TextDecoder;function ne(t={}){let e=null,a=(i,f)=>{let m=i===1?globalThis.process?.stdout:globalThis.process?.stderr;if(m&&typeof m.write=="function")try{m.write(f);return}catch{}let d=f.replace(/\n$/,"");(i===1?console.log:console.warn)(d)},u=t.write||a;return{wasi_snapshot_preview1:{fd_read(i,f,m,d){let x=new DataView(e.buffer),A=0;for(let h=0;h<m;h++){let _=x.getUint32(f+h*8,!0),S=x.getUint32(f+h*8+4,!0),E=new Uint8Array(e.buffer,_,S);A+=t.read&&t.read(i,E)||0}return x.setUint32(d,A,!0),0},fd_write(i,f,m,d){let x=new DataView(e.buffer),A=0;for(let h=0;h<m;h++){let _=x.getUint32(f+h*8,!0),S=x.getUint32(f+h*8+4,!0);u(i,ge.decode(new Uint8Array(e.buffer,_,S))),A+=S}return x.setUint32(d,A,!0),0},clock_time_get(i,f,m){let d=new DataView(e.buffer),x=BigInt(Math.round(i===0?Date.now()*1e6:performance.now()*1e6));return d.setBigInt64(m,x,!0),0},random_get(i,f){let m=new Uint8Array(e.buffer,i,f);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(m);else for(let d=0;d<f;d++)m[d]=Math.random()*256|0;return 0},proc_exit(){},environ_sizes_get(i,f){let m=new DataView(e.buffer);return m.setUint32(i,0,!0),m.setUint32(f,0,!0),0},environ_get(){return 0}},_setMemory(i){e=i}}}var re=t=>{if(!t.exports.__timer_tick)return;let e=t.exports.__timer_tick,a=!1,u=setInterval(()=>{let i=e();i>0&&(a=!0),a&&i<=0&&clearInterval(u)},1)};var N={PTR_ADDR:1020,START:1024},T={TAG_SHIFT:47,TAG_MASK:15,AUX_SHIFT:32,AUX_MASK:32767,OFFSET_MASK:4294967295,NAN_PREFIX:32760,NAN_PREFIX_BITS:0x7FF8000000000000n,SSO_BIT:16384,SLICE_BIT:8192,SLICE_LEN_MASK:8191},U={ATOM:0,ARRAY:1,BUFFER:2,TYPED:3,STRING:4,OBJECT:6,HASH:7,SET:8,MAP:9,CLOSURE:10,EXTERNAL:11},B={NULL:1,UNDEF:2,FALSE:4,TRUE:5},Ne=1<<U.ARRAY|1<<U.HASH|1<<U.SET|1<<U.MAP,Oe=BigInt(T.TAG_SHIFT),Re=BigInt(T.TAG_MASK),Le=BigInt(T.AUX_SHIFT),De=BigInt(T.AUX_MASK),Pe=BigInt(T.OFFSET_MASK);var P=(t,e)=>(T.NAN_PREFIX<<16|(t&T.TAG_MASK)<<T.TAG_SHIFT-32|e&T.AUX_MASK)>>>0,oe=t=>t>>>T.TAG_SHIFT-32&T.TAG_MASK,J=t=>t&T.AUX_MASK;var W={[B.NULL]:P(U.ATOM,B.NULL),[B.UNDEF]:P(U.ATOM,B.UNDEF),[B.FALSE]:P(U.ATOM,B.FALSE),[B.TRUE]:P(U.ATOM,B.TRUE)};var Q=new TextEncoder,Ae=new TextDecoder,de=(t,e)=>{let a=WebAssembly.Module.imports(t).some(u=>u.module==="wasi_snapshot_preview1");return{needsWasi:a,wasiImports:a?ne(e):null}},xe=t=>new Set(WebAssembly.Module.imports(t).filter(e=>e.module==="env"&&e.kind==="function").map(e=>e.name)),Ie=(t,e)=>{let a=()=>new DataView(t.buffer),u=e?()=>e.value:()=>a().getInt32(N.PTR_ADDR,!0),i=e?A=>{e.value=A}:A=>a().setInt32(N.PTR_ADDR,A,!0),f=e?e.value:N.START;return{alloc:A=>{let h=u()+7&-8,_=h+A;return _>t.buffer.byteLength&&t.grow(Math.ceil((_-t.buffer.byteLength)/65536)),i(_),h},reset:()=>i(f),initHeapPtr:()=>{if(e)return;let A=a();A.getInt32(N.PTR_ADDR,!0)<N.START&&A.setInt32(N.PTR_ADDR,N.START,!0)}}},V=(t,e)=>{let a=WebAssembly.Module.customSections(t,e);return a.length?new Uint8Array(a[0]):null},we=t=>{let e=new TextDecoder,a=0;return{pos:()=>a,seek:u=>{a=u},eof:()=>a>=t.length,u8:()=>t[a++],varint:()=>{let u=0,i=0;for(;;){let f=t[a++];if(u|=(f&127)<<i,!(f&128))return u;i+=7}},str:u=>{let i=e.decode(t.subarray(a,a+u));return a+=u,i},bytes:u=>{let i=t.subarray(a,a+u);return a+=u,i}}},H=0xffffffffn,ae=new ArrayBuffer(8),z=new Uint32Array(ae),fe=new Float64Array(ae),C=t=>(fe[0]=t,BigInt(z[1])<<32n|BigInt(z[0]>>>0)),D=t=>(z[0]=Number(t&H),z[1]=Number(t>>32n&H),fe[0]),Y=t=>Number(t>>32n&H),Z=t=>(Y(t)&2146959360)===2146959360,R=t=>typeof t=="bigint"?t:C(t),le=BigInt(W[B.NULL])<<32n,$=BigInt(W[B.UNDEF])<<32n,he=BigInt(W[B.FALSE])<<32n,_e=BigInt(W[B.TRUE])<<32n,O=t=>t===null?le:t===void 0?$:t,be=t=>{let e=0n;for(let a=0;a<t.length;a++)e|=BigInt(t.charCodeAt(a))<<BigInt(a*7);return e|=BigInt(t.length)<<42n,M(4,Number(e>>32n)|T.SSO_BIT,Number(e&0xFFFFFFFFn))},te=t=>typeof t=="bigint"?t:C(t),M=(t,e,a)=>BigInt(P(t,e))<<32n|BigInt(a>>>0),L=t=>Number(te(t)&H),ee=t=>oe(Y(te(t))),v=t=>J(Y(te(t))),ue=t=>{let e=J(Y(t)),a=e>>>10&7,u=BigInt(e)<<32n|BigInt(Number(t&H)),i="";for(let f=0;f<a;f++)i+=String.fromCharCode(Number(u>>BigInt(f*7)&0x7fn));return i},j=t=>{if(Array.isArray(t))return t.map(j);if(typeof t=="number"){if(t===t)return t;t=C(t)}else if(typeof t!="bigint")return t;if(!Z(t))return D(t);if(ee(t)===4&&v(t)&T.SSO_BIT)return ue(t);if(L(t)===0){if(t===le)return null;if(t===$)return;if(t===he)return!1;if(t===_e)return!0}return D(t)},q=(t,e)=>t.mem?t.mem.read(e):j(e),X={Int8Array:[0,1,"getInt8","setInt8"],Uint8Array:[1,1,"getUint8","setUint8"],Int16Array:[2,2,"getInt16","setInt16"],Uint16Array:[3,2,"getUint16","setUint16"],Int32Array:[4,4,"getInt32","setInt32"],Uint32Array:[5,4,"getUint32","setUint32"],Float32Array:[6,4,"getFloat32","setFloat32"],Float64Array:[7,8,"getFloat64","setFloat64"]},se=Object.values(X),K=new WeakSet,G=t=>{if(t instanceof WebAssembly.Memory&&K.has(t))return t;if(!t||typeof t=="object"&&!(t instanceof WebAssembly.Memory)&&!t.instance&&!t.exports&&!t.memory){let r=new WebAssembly.Memory({initial:t?.initial||1,...t?.maximum?{maximum:t.maximum}:{},...t?.shared?{shared:t.shared}:{}});return G(r)}let e,a,u,i;if(t instanceof WebAssembly.Memory)e=t,a=null,u=null,i=null;else{let r=t?.instance?.exports||t?.exports||t;if(e=t?.exports?.memory||r.memory,!e)return{read:j,wrapVal:O,scalar:!0};a={...r,memory:e},u=t.extMap||null,i=t.module||null}let f=()=>new DataView(e.buffer),{alloc:m,reset:d,initHeapPtr:x}=Ie(e,a?.__heap),A=a?._alloc||m;x();let h=(r,s,p)=>{let y=A(16+p),n=f();return n.setBigInt64(y,0n,!0),n.setInt32(y+8,r,!0),n.setInt32(y+12,s,!0),y+16},_=e.schemas||[],S=i&&V(i,"jz:schema");if(S){let r=we(S),s=()=>{let n=r.u8();return n===0?null:n===1?[null,s()]:r.str(r.varint())},p=r.varint(),y=[];for(let n=0;n<p;n++){let o=r.varint(),c=[];for(let l=0;l<o;l++)c.push(s());y.push(c)}for(let n of y){let o=n.join(",");_.some(c=>c.join(",")===o)||_.push(n)}}if(K.has(e))return e.schemas=_,a?._alloc&&(A=a._alloc,e.alloc=A),e.reset=d,u&&(e._extMap=u),e;e.schemas=_,e._extMap=u,e.Array=r=>{let s=r.length,p=h(s,s,s*8),y=new BigInt64Array(s);for(let o=0;o<s;o++)y[o]=R(e.wrapVal(r[o]));let n=new BigInt64Array(e.buffer,p,s);for(let o=0;o<s;o++)n[o]=y[o];return M(1,0,p)},e.String=r=>{if(r.length<=6&&/^[\x00-\x7f]*$/.test(r)){let c=0n;for(let l=0;l<r.length;l++)c|=BigInt(r.charCodeAt(l))<<BigInt(l*7);return c|=BigInt(r.length)<<42n,M(4,Number(c>>32n)|T.SSO_BIT,Number(c&0xFFFFFFFFn))}let s=Q.encode(r),p=s.length,y=A(4+p),n=f();n.setInt32(y,p,!0);let o=y+4;return s.forEach((c,l)=>n.setUint8(o+l,c)),M(4,0,o)},e.Buffer=r=>{let s=r instanceof ArrayBuffer?new Uint8Array(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),p=s.length,y=h(p,p,p);return new Uint8Array(e.buffer).set(s,y),M(2,0,y)},e.wrapVal=function(r){if(r==null)return O(r);if(typeof r=="number"||typeof r=="boolean")return Number(r);if(typeof r=="string")return e.String(r);if(typeof r=="bigint")return Z(r)?r:e.String(r.toString());if(Array.isArray(r))return e.Array(r);if(r instanceof ArrayBuffer)return e.Buffer(r);if(r instanceof DataView)return e.Buffer(r.buffer);let s=r?.constructor?.name;return s&&X[s]?e[s](r):typeof r=="object"||typeof r=="function"?e.External(r):$},e.External=function(r){if(r==null)return O(r);let s=e._extMap;if(!s)return $;let p=s.indexOf(r);return p===-1&&(p=s.length,s.push(r)),M(11,0,p)},e.Object=function(r){let s=Object.keys(r),p=s.join(","),y=e.schemas,n=y.findIndex(I=>I.join(",")===p);if(n===-1){let I=y.reduce((b,F,pe)=>F.length===s.length&&s.every(ye=>F.includes(ye))?b.concat(pe):b,[]);if(I.length===1)n=I[0];else{if(I.length>1)throw Error(`Ambiguous schema for {${p}} \u2014 pass keys in schema order`);if(e._extMap)return e.External(r);throw Error(`No schema for {${p}}`)}}let o=y[n],c=o.length,l=A(c*8),g=new BigInt64Array(c);for(let I=0;I<c;I++){let b=r[o[I]];b==null?b=O(b):typeof b=="string"?b=e.String(b):Array.isArray(b)&&(b=e.Array(b)),g[I]=R(b)}let w=new BigInt64Array(e.buffer,l,c);for(let I=0;I<c;I++)w[I]=g[I];return M(6,n,l)},e.read=function(r){if(Array.isArray(r))return r.map(o=>e.read(o));if(typeof r=="number"){if(r===r)return r;r=C(r)}else if(typeof r!="bigint")return r;if(!Z(r))return D(r);let s=f(),p=ee(r),y=v(r),n=L(r);if(p===0&&n===0){if(y===1)return null;if(y===2)return;if(y===4)return!1;if(y===5)return!0}if(p===11&&e._extMap)return e._extMap[n];if(p===1){let o=n;for(;s.getInt32(o-4,!0)===-1;)o=s.getInt32(o-8,!0);let c=s.getInt32(o-8,!0),l=new Array(c);for(let g=0;g<c;g++)l[g]=e.read(s.getBigInt64(o+g*8,!0));return l}if(p===3){let o=y&7,[,c]=se[o],l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][o];if(y&8){let w=s.getInt32(n,!0),I=s.getInt32(n+4,!0);return new l(e.buffer,I,w/c)}let g=s.getInt32(n-8,!0);return new l(e.buffer,n,g/c)}if(p===2){let o=s.getInt32(n-8,!0),c=new ArrayBuffer(o);return new Uint8Array(c).set(new Uint8Array(e.buffer,n,o)),c}if(p===4){if(y&T.SSO_BIT)return ue(r);let o=s.getInt32(n-4,!0);return Ae.decode(new Uint8Array(e.buffer,n,o))}if(p===6){let o=e.schemas[y];if(!o)return r;let c={};for(let l=0;l<o.length;l++)c[o[l]]=e.read(s.getBigInt64(n+l*8,!0));return c}if(p===7){let o=s.getInt32(n-8,!0),c=s.getInt32(n-4,!0),l={};for(let g=0,w=0;g<c&&w<o;g++)s.getBigInt64(n+g*24,!0)!==0n&&(l[e.read(s.getBigInt64(n+g*24+8,!0))]=e.read(s.getBigInt64(n+g*24+16,!0)),w++);return l}if(p===8){let o=s.getInt32(n-8,!0),c=s.getInt32(n-4,!0),l=new Set;for(let g=0;g<c&&l.size<o;g++)s.getBigInt64(n+g*16,!0)!==0n&&l.add(e.read(s.getBigInt64(n+g*16+8,!0)));return l}if(p===9){let o=s.getInt32(n-8,!0),c=s.getInt32(n-4,!0),l=new Map;for(let g=0;g<c&&l.size<o;g++)s.getBigInt64(n+g*24,!0)!==0n&&l.set(e.read(s.getBigInt64(n+g*24+8,!0)),e.read(s.getBigInt64(n+g*24+16,!0)));return l}return D(r)},e.write=function(r,s){let p=ee(r),y=L(r),n=f();if(p===1){let o=n.getInt32(y-4,!0);if(s.length>o)throw Error(`write: ${s.length} exceeds capacity ${o}`);n.setInt32(y-8,s.length,!0);for(let c=0;c<s.length;c++)n.setBigInt64(y+c*8,R(O(s[c])),!0)}else if(p===3){let o=v(r),c=o&7,[,l,,g]=se[c],w=s.length*l;if(o&8){let I=n.getInt32(y,!0),b=n.getInt32(y+4,!0);if(w>I)throw Error(`write: ${w} bytes exceeds view size ${I}`);for(let F=0;F<s.length;F++)n[g](b+F*l,s[F],!0)}else{let I=n.getInt32(y-4,!0);if(w>I)throw Error(`write: ${w} bytes exceeds capacity ${I}`);n.setInt32(y-8,w,!0);for(let b=0;b<s.length;b++)n[g](y+b*l,s[b],!0)}}else if(p===6){let o=e.schemas[v(r)];if(!o)throw Error("write: unknown schema");for(let c of Object.keys(s)){let l=o.indexOf(c);l>=0&&n.setBigInt64(y+l*8,R(O(s[c])),!0)}}else throw Error(`write: unsupported type ${p}`)},e.alloc=A,e.reset=d;let E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];for(let[r,[s,p,,y]]of Object.entries(X))e[r]=n=>{let o=n.length,c=o*p,l=h(c,c,c);if(E[s]&&n instanceof E[s])new E[s](e.buffer,l,o).set(n);else{let g=f();for(let w=0;w<o;w++)g[y](l+w*p,n[w],!0)}return M(3,s,l)};return e.allocTyped=(r,s)=>{let p=X[r?.name];if(!p)throw Error(`allocTyped: unsupported type ${r?.name??r}`);let[y,n]=p,o=s*n,c=h(o,o,o);return{view:new r(e.buffer,c,s),box:M(3,y,c)}},K.add(e),e},Te=(t,e)=>{let a=new Map,u=e?t:t.module||t,i=e||t.instance||t,f=new TextDecoder,m=V(u,"jz:rest");if(m)try{for(let n of JSON.parse(f.decode(m)))a.set(typeof n=="string"?n:n.name,typeof n=="string"?0:n.fixed)}catch{}let d=new Map,x=V(u,"jz:extparam");if(x)try{for(let n of JSON.parse(f.decode(x))){let o=new Set(n.p);n.d&&(o.def=new Map(Object.entries(n.d).map(([c,l])=>[Number(c),l]))),d.set(n.name,o)}}catch{}let A=new Map,h=V(u,"jz:i64exp");if(h)try{for(let n of JSON.parse(f.decode(h)))A.set(n.name,{p:new Set(n.p||[]),r:!!n.r})}catch{}let _=G(t),S=i.exports.__jz_last_err_bits,E=n=>{if(!(n instanceof WebAssembly.Exception)||!S)throw n;let o=S.value,c=_?_.read(o):j(o);if(c instanceof Error)throw c;let l=new Error(typeof c=="string"?c:String(c));throw l.cause=n,l.thrown=c,l},r={},s=(n,o,c,l)=>n?.has(o)?c===void 0&&n.def?.has(o)?n.def.get(o):c:l(c),p=(n,o,c)=>(l,g)=>{let w=s(o,g,l,c);if(n&&n.p.has(g)){if(typeof w=="string"){if(w.length>6||!/^[\x00-\x7f]*$/.test(w))throw new Error("jz: string arg too long or non-ASCII for memoryless module \u2014 compile with a string operation to enable heap marshaling");return be(w)}return R(w)}return typeof w=="bigint"?D(w):w};if(!_||_.scalar){for(let[n,o]of Object.entries(i.exports)){if(typeof o!="function"){r[n]=o;continue}let c=d.get(n),l=A.get(n),g=o.length;r[n]=(...w)=>{for(;w.length<g;)w.push(void 0);try{let I=o(...w.map(p(l,c,O)));return typeof I=="bigint"&&!(l&&l.r)?I:j(I)}catch(I){E(I)}}}return r}let y=_.wrapVal.bind(_);for(let[n,o]of Object.entries(i.exports))if(a.has(n)&&typeof o=="function"){let c=a.get(n),l=d.get(n),g=A.get(n);r[n]=(...w)=>{let I=w.slice(0,c).map(p(g,l,y));for(;I.length<c;){let F=I.length;I.push(g&&g.p.has(F)?$:D($))}let b=_.Array(w.slice(c));I.push(g&&g.p.has(c)?b:D(b));try{let F=o.apply(null,I);return typeof F=="bigint"&&!(g&&g.r)?F:_.read(F)}catch(F){E(F)}}}else if(typeof o=="function"){let c=d.get(n),l=A.get(n),g=o.length;r[n]=(...w)=>{for(;w.length<g;)w.push(void 0);try{let I=o.apply(null,w.map(p(l,c,y)));return typeof I=="bigint"&&!(l&&l.r)?I:_.read(I)}catch(I){E(I)}}}else r[n]=o;return r},Fe=t=>{let e={extMap:[null],mem:null};return t._interp=t._interp||{},t._interp.__ext_prop=(a,u)=>{let i=e.extMap[L(a)],f=e.mem.read(u);return R(e.mem.wrapVal(typeof i[f]=="function"?i[f].bind(i):i[f]))},t._interp.__ext_has=(a,u)=>e.mem.read(u)in e.extMap[L(a)]?1:0,t._interp.__ext_set=(a,u,i)=>(e.extMap[L(a)][e.mem.read(u)]=e.mem.read(i),1),t._interp.__ext_call=(a,u,i)=>{let f=e.extMap[L(a)],m=e.mem.read(u),d=e.mem.read(i);return R(e.mem.wrapVal(f[m].apply(f,d)))},e},Be=(t,e,a)=>{let u=xe(t);if(u.size){if(e.env||(e.env={}),u.has("print")&&!e.env.print){let i=["","",""],f=[],m=x=>{(x===2?console.error:console.log)(i[x]),i[x]=""},d=(x,A,h)=>{let _=q(a,x);i[A]+=String(_),h===32?i[A]+=" ":h===10&&m(A)};e.env.print=(x,A,h)=>{a.mem?d(x,A,h):f.push([x,A,h])},a.flushPrint=()=>{for(let x of f)d(...x);f.length=0}}if(u.has("now")&&!e.env.now&&(e.env.now=i=>i===1&&typeof performance<"u"?performance.now():Date.now()),u.has("rngSeed")&&!e.env.rngSeed&&(e.env.rngSeed=()=>{let i=new Uint32Array(1);return globalThis.crypto?.getRandomValues?globalThis.crypto.getRandomValues(i):i[0]=Math.random()*4294967296>>>0,i[0]|0}),u.has("parseFloat")&&!e.env.parseFloat&&(e.env.parseFloat=i=>{let f=q(a,i);return parseFloat(f)}),u.has("parseInt")&&!e.env.parseInt&&(e.env.parseInt=(i,f)=>{let m=q(a,i);return parseInt(m,f||void 0)}),u.has("setTimeout")||u.has("clearTimeout")){let i=new Map,f=1;u.has("setTimeout")&&!e.env.setTimeout&&(e.env.setTimeout=(m,d,x)=>{let A=f++,h=()=>a.invoke?.(m);if(x){let _=setInterval(h,d);i.set(A,()=>clearInterval(_))}else{let _=setTimeout(()=>{i.delete(A),h()},d);i.set(A,()=>clearTimeout(_))}return A}),u.has("clearTimeout")&&!e.env.clearTimeout&&(e.env.clearTimeout=m=>{let d=i.get(m);return d&&(d(),i.delete(m)),0})}}},ie={length:t=>t.length,charCodeAt:(t,e)=>t.charCodeAt(e)},ce=!1,k=!1,me=()=>{if(ce)return k;ce=!0;try{let t=new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,111,1,127,2,24,1,15,...Q.encode("wasm:js-string"),6,...Q.encode("length"),0,0]),e=new WebAssembly.Module(t,{builtins:["js-string"]});new WebAssembly.Instance(e,{}),k=!0}catch{k=!1}return k},Se=(t,e,a)=>{let{needsWasi:u,wasiImports:i}=de(t,e),f=i||{};if(e._interp&&(f.env={...f.env,...e._interp}),!me())for(let m of WebAssembly.Module.imports(t))m.module==="wasm:js-string"&&ie[m.name]&&(f["wasm:js-string"]||(f["wasm:js-string"]={}),f["wasm:js-string"][m.name]=ie[m.name]);if(e.imports)for(let[m,d]of Object.entries(e.imports)){f[m]||(f[m]={});for(let x of Object.getOwnPropertyNames(d)){let A=d[x],h=typeof A=="function"?A:A&&typeof A=="object"?A.fn:null;typeof h=="function"&&(f[m][x]=(..._)=>{let S=_.map(r=>a.mem?a.mem.read(r):j(r)),E=h.call(d,...S);return R(a.mem?a.mem.wrapVal(E):O(E))})}}Be(t,f,a),e.memory instanceof WebAssembly.Memory&&(K.has(e.memory)||(e.memory=G(e.memory)),f.env||(f.env={}),f.env.memory=e.memory);for(let m of WebAssembly.Module.imports(t))if(m.kind==="global"&&m.module==="env"){let d=globalThis[m.name];if(d!==void 0){f.env||(f.env={});let x=a.extMap.indexOf(d);x===-1&&(x=a.extMap.length,a.extMap.push(d)),f.env[m.name]=new WebAssembly.Global({value:"i64",mutable:!1},M(11,0,x))}}return{imports:f,needsWasi:u}},Ee=(t,e,a,u,i,f)=>{u&&a._setMemory(e.exports.memory),f.invoke=e.exports.__invoke_closure||null,re(e);let m=i.memory instanceof WebAssembly.Memory?i.memory:e.exports.memory,d={module:t,instance:e,exports:{...e.exports,memory:m},extMap:f.extMap},x=G(d);return f.mem=x,f.flushPrint?.(),{exports:Te(d),memory:x?.scalar?null:x,instance:e,module:t}},Me=t=>{if(t instanceof WebAssembly.Module)return t;if(me())try{return new WebAssembly.Module(t,{builtins:["js-string"]})}catch{return new WebAssembly.Module(t)}return new WebAssembly.Module(t)},He=(t,e={})=>{let a=Fe(e),u=Me(t),{imports:i,needsWasi:f}=Se(u,e,a),m=Object.keys(i).some(x=>x!=="_setMemory"),d=new WebAssembly.Instance(u,m?i:void 0);return Ee(u,d,i,f,e,a)};export{he as FALSE_NAN,le as NULL_NAN,_e as TRUE_NAN,$ as UNDEF_NAN,v as aux,O as coerce,C as f64ToI64,D as i64ToF64,He as instantiate,G as memory,L as offset,M as ptr,Me as toModule,ee as type,Te as wrap};