porffor 0.2.0-767de65 → 0.2.0-80c08d4

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.
@@ -0,0 +1,248 @@
1
+ # Contributing to Porffor
2
+
3
+ Hello! Thanks for your potential interest in contributing to Porffor :)
4
+
5
+ This document hopes to help you understand Porffor-specific TS, specifically for writing built-ins (inside `compiler/builtins/*.ts` eg `btoa`, `String.prototype.trim`, ...). This guide isn't really meant for modifying the compiler itself yet (eg `compiler/codegen.js`), as built-ins are ~easier to implement and more useful at the moment.
6
+
7
+ I mostly presume decent JS knowledge, with some basic TS too but nothing complicated. Knowing low-level stuff generally (pointers, etc) and/or Wasm (bytecode) is also a plus but hopefully not required.
8
+
9
+ If you have any questions you can ask in [the Porffor Discord](https://discord.gg/6crs9Znx9R), please feel free to ask anything if you get stuck :)
10
+
11
+ Please read this entire document before beginning as there are important things throughout.
12
+
13
+ <br>
14
+
15
+ ## Setup
16
+
17
+ 1. Clone the repo and enter the repo (`git clone https://github.com/CanadaHonk/porffor.git`)
18
+ 2. `npm install`
19
+
20
+ ### Precompile
21
+
22
+ **If you update any file inside `compiler/builtins` you will need to do this for it to update inside Porffor otherwise your changes will have no effect.** Run `node compiler/precompile.js` to precompile. It may error during this, if so, you might have an error in your code or there could be a compiler error with Porffor (feel free to ask for help as soon as you encounter any errors with it).
23
+
24
+ <br>
25
+
26
+ ## Types
27
+
28
+ Porffor has usual JS types (or at least the ones it supports), but also internal types for various reasons.
29
+
30
+ ### ByteString
31
+
32
+ The most important and widely used internal type is ByteString (also called `bytestring` or `_bytestring` in code). Regular strings in Porffor are UTF-16 encoded, so each character uses 2 bytes. ByteStrings are special strings which are used when the characters in a string only use ASCII/LATIN-1 characters, so the lower byte of the UTF-16 characters are unused. Instead of wasting memory with all the unused memory, ByteStrings instead use 1 byte per character. This halves memory usage of such strings and also makes operating on them faster. The downside is that many Porffor built-ins have to be written twice, slightly different, for both `String` and `ByteString` types.
33
+
34
+ ### i32
35
+
36
+ This is complicated internally but essentially, only use it for pointers. (This is not signed or unsigned, instead it is the Wasm valtype `i32` so the signage is ~instruction dependant).
37
+
38
+ <br>
39
+
40
+ ## Pointers
41
+
42
+ Pointers are the main (and most difficult) unique feature you ~need to understand when dealing with objects (arrays, strings, ...).
43
+
44
+ We'll explain things per common usage you will likely need to know:
45
+
46
+ ## Commonly used Wasm code
47
+
48
+ ### Get a pointer
49
+
50
+ ```js
51
+ Porffor.wasm`local.get ${foobar}`
52
+ ```
53
+
54
+ Gets the pointer to the variable `foobar`. You don't really need to worry about how it works in detail, but essentially it gets the pointer as a number (type) instead of as the object it is.
55
+
56
+ ### Store a character in a ByteString
57
+
58
+ ```js
59
+ Porffor.wasm.i32.store8(pointer, characterCode, 0, 4)
60
+ ```
61
+
62
+ Stores the character code `characterCode` at the pointer `pointer` **for a ByteString**.[^1]
63
+
64
+ ### Store a character in a String
65
+
66
+ ```js
67
+ Porffor.wasm.i32.store16(pointer, characterCode, 0, 4)
68
+ ```
69
+
70
+ Stores the character code `characterCode` at the pointer `pointer` **for a String**.[^1]
71
+
72
+ ### Load a character from a ByteString
73
+
74
+ ```js
75
+ Porffor.wasm.i32.load8_u(pointer, 0, 4)
76
+ ```
77
+
78
+ Loads the character code at the pointer `pointer` **for a ByteString**.[^1]
79
+
80
+ ### Load a character from a String
81
+
82
+ ```js
83
+ Porffor.wasm.i32.load16_u(pointer, 0, 4)
84
+ ```
85
+
86
+ Loads the character code at the pointer `pointer` **for a String**.[^1]
87
+
88
+ ### Manually store the length of an object
89
+
90
+ ```js
91
+ Porffor.wasm.i32.store(pointer, length, 0, 0)
92
+ ```
93
+
94
+ Stores the length `length` at pointer `pointer`, setting the length of an object. This is mostly unneeded today as you can just do `obj.length = length`. [^2]
95
+
96
+ <br>
97
+
98
+ ## Example
99
+
100
+ Here is the code for `ByteString.prototype.toUpperCase()`:
101
+
102
+ ```ts
103
+ export const ___bytestring_prototype_toUpperCase = (_this: bytestring) => {
104
+ const len: i32 = _this.length;
105
+
106
+ let out: bytestring = '';
107
+ Porffor.wasm.i32.store(out, len, 0, 0);
108
+
109
+ let i: i32 = Porffor.wasm`local.get ${_this}`,
110
+ j: i32 = Porffor.wasm`local.get ${out}`;
111
+
112
+ const endPtr: i32 = i + len;
113
+ while (i < endPtr) {
114
+ let chr: i32 = Porffor.wasm.i32.load8_u(i++, 0, 4);
115
+
116
+ if (chr >= 97) if (chr <= 122) chr -= 32;
117
+
118
+ Porffor.wasm.i32.store8(j++, chr, 0, 4);
119
+ }
120
+
121
+ return out;
122
+ };
123
+ ```
124
+
125
+ Now let's go through it section by section:
126
+
127
+ ```ts
128
+ export const ___bytestring_prototype_toUpperCase = (_this: bytestring) => {
129
+ ```
130
+
131
+ Here we define a built-in for Porffor. Notably:
132
+ - We do not use `a.b.c`, instead we use `__a_b_c`
133
+ - The ByteString type is actually `_bytestring`, as internal types have an extra `_` at the beginning (this is due to be fixed/simplified soon(tm))
134
+ - We use a `_this` argument, as `this` does not exist in Porffor yet
135
+ - We use an arrow function
136
+
137
+ ---
138
+
139
+ ```ts
140
+ const len: i32 = _this.length;
141
+
142
+ let out: bytestring = '';
143
+ Porffor.wasm.i32.store(out, len, 0, 0);
144
+ ```
145
+
146
+ This sets up the `out` variable we are going to write to for the output of this function. We set the length in advance to be the same as `_this`, as `foo.length == foo.toLowerCase().length`, because we will later be manually writing to it using Wasm intrinsics, which will not update the length themselves.
147
+
148
+ ---
149
+
150
+ ```ts
151
+ let i: i32 = Porffor.wasm`local.get ${_this}`,
152
+ j: i32 = Porffor.wasm`local.get ${out}`;
153
+ ```
154
+
155
+ Get the pointers for `_this` and `out` as `i32`s (~`number`s).
156
+
157
+ ---
158
+
159
+ ```ts
160
+ const endPtr: i32 = i + len;
161
+ while (i < endPtr) {
162
+ ```
163
+
164
+ Set up an end target pointer as the pointer variable for `_this` plus the length of it. Loop below until that pointer reaches the end target, so we iterate through the entire string.
165
+
166
+ ---
167
+
168
+ ```ts
169
+ let chr: i32 = Porffor.wasm.i32.load8_u(i++, 0, 4);
170
+ ```
171
+
172
+ Read the character (code) from the current `_this` pointer variable, and increment it so next iteration it reads the next character, etc.
173
+
174
+ ---
175
+
176
+ ```ts
177
+ if (chr >= 97) if (chr <= 122) chr -= 32;
178
+ ```
179
+
180
+ If the character code is >= 97 (`a`) and <= 122 (`z`), decrease it by 32, making it an upper case character. eg: 97 (`a`) - 32 = 65 (`A`).
181
+
182
+ ---
183
+
184
+ ```ts
185
+ Porffor.wasm.i32.store8(j++, chr, 0, 4);
186
+ ```
187
+
188
+ Store the character code into the `out` pointer variable, and increment it.
189
+
190
+ <br>
191
+
192
+ ## Porffor-specific TS notes
193
+
194
+ - For declaring variables, you must use explicit type annotations currently (eg `let a: number = 1`, not `let a = 1`)
195
+ - You might spot `Porffor.fastOr`/`Porffor.fastAnd`, these are non-short circuiting versions of `||`/`&&`, taking any number of conditions as arguments. You shouldn't don't need to use or worry about these.
196
+ - **There are ~no objects, you cannot use them/literals.**
197
+ - Attempt to avoid string/array-heavy code and use more variables instead if possible, easier on memory and CPU/perf.
198
+
199
+ <br>
200
+
201
+ ## Formatting/linting
202
+
203
+ There is 0 setup for this (right now). You can try looking through the other built-ins files but do not worry about it a lot, I honestly do not mind going through and cleaning up after a PR as long as the code itself is good :^)
204
+
205
+ <br>
206
+
207
+ ## Commit (message) style
208
+
209
+ You should ideally have one commit per notable change (using amend/force push). Commit messages should be like `${file}: ${description}`. Don't be afraid to use long titles if needed, but try and be short if possible. Bonus points for detail in commit description. ~~Gold star for jokes in description too.~~
210
+
211
+ Examples:
212
+ ```
213
+ builtins/date: impl toJSON
214
+ builtins/date: fix ToIntegerOrInfinity returning -0
215
+ codegen: fix inline wasm for unreachable
216
+ builtins/array: wip toReversed
217
+ builtins/tostring_number: impl radix
218
+ ```
219
+
220
+ <br>
221
+
222
+ ## Test262
223
+
224
+ Make sure you have Test262 cloned already **inside of `test262/`** (`git clone https://github.com/tc39/test262.git test262/test262`).
225
+
226
+ Run `node test262` to run all the tests and get an output of total overall test results. The main thing you want to pay attention to is the emoji summary (lol):
227
+ ```
228
+ 🧪 50005 | 🤠 7007 (-89) | ❌ 1914 (-32) | 💀 13904 (-61) | 📝 23477 (-120) | ⏰ 2 | 🏗 2073 (+302) | 💥 1628
229
+ ```
230
+
231
+ To break this down:
232
+ 🧪 total 🤠 pass ❌ fail 💀 runtime error 📝 todo (error) ⏰ timeout 🏗️ wasm compile error 💥 compile error
233
+
234
+ The diff compared to the last commit (with test262 data) is shown in brackets. Basically, you can passes 🤠 up, and errors 💀📝🏗💥 down. It is fine if some errors change balance/etc, as long as they are not new failures.
235
+
236
+ It will also log new passes/fails. Be careful as sometimes the overall passes can increase, but other files have also regressed into failures which you might miss. Also keep in mind some tests may have been false positives before, but we can investigate the diff together :)
237
+
238
+ ### Debugging tips
239
+
240
+ - Use `node test262 path/to/tests` to run specific test262 dirs/files (eg `node test262 built-ins/Date`).
241
+ - Use `--log-errors` to log the errors of individual tests.
242
+ - Use `--debug-asserts` to log expected/actual of assertion failures (experimental).
243
+
244
+ <br>
245
+
246
+ [^1]: The `0, 4` args are necessary for the Wasm instruction, but you don't need to worry about them (`0` alignment, `4` byte offset for length).
247
+
248
+ [^2]: The `0, 4` args are necessary for the Wasm instruction, but you don't need to worry about them (`0` alignment, `0` byte offset).
package/README.md CHANGED
@@ -14,60 +14,75 @@ Porffor is primarily built from scratch, the only thing that is not is the parse
14
14
  Expect nothing to work! Only very limited JS is currently supported. See files in `bench` for examples.
15
15
 
16
16
  ### Setup
17
- 1. Clone this repo (`git clone https://github.com/CanadaHonk/porffor.git`)
18
- 2. `npm install` - for parser(s)
17
+ **`npm install -g porffor`**. It's that easy (hopefully) :)
19
18
 
20
- ### Running a file
21
- The repos comes with easy alias files for Unix and Windows, which you can use like so:
22
- - Unix: `./porf path/to/script.js`
23
- - Windows: `.\porf path/to/script.js`
19
+ ### Trying a REPL
20
+ **`porf`**. Just run it with no script file argument.
24
21
 
25
- Please note that further examples below will just use `./porf`, you need to use `.\porf` on Windows. You can also swap out `node` in the alias to use another runtime like Deno (`deno run -A`) or Bun (`bun ...`), or just use it yourself (eg `node runner/index.js ...`, `bun runner/index.js ...`). Node and Bun should work great, Deno support is WIP.
22
+ ### Running a JS file
23
+ **`porf path/to/script.js`**
26
24
 
27
- ### Trying a REPL
28
- **`./porf`**. Just run it with no script file argument.
25
+ ### Compiling to Wasm
26
+ **`porf wasm path/to/script.js out.wasm`**. Currently it does not use an import standard like WASI, so it is mostly unusable on its own.
29
27
 
30
28
  ### Compiling to native binaries
31
29
  > [!WARNING]
32
30
  > Compiling to native binaries uses [2c](#2c), Porffor's own Wasm -> C compiler, which is experimental.
33
31
 
34
- **`./porf native path/to/script.js out(.exe)`**. You can specify the compiler with `-compiler=clang/zig/gcc`, and which opt level to use with `-cO=O3` (`Ofast` by default). Output binaries are also stripped by default.
32
+ **`porf native path/to/script.js out(.exe)`**. You can specify the compiler with `--compiler=clang/zig/gcc`, and which opt level to use with `--cO=O3` (`Ofast` by default). Output binaries are also stripped by default.
35
33
 
36
34
  ### Compiling to C
37
35
  > [!WARNING]
38
36
  > Compiling to C uses [2c](#2c), Porffor's own Wasm -> C compiler, which is experimental.
39
37
 
40
- **`./porf c path/to/script.js (out.c)`**. When not including an output file, it will be printed to stdout instead.
38
+ **`porf c path/to/script.js (out.c)`**. When not including an output file, it will be printed to stdout instead.
39
+
40
+ ### Profiling a JS file
41
+ > [!WARNING]
42
+ > Very experimental WIP feature!
43
+
44
+ **`porf profile path/to/script.js`**
45
+
46
+ ### Debugging a JS file
47
+ > [!WARNING]
48
+ > Very experimental WIP feature!
49
+
50
+ **`porf debug path/to/script.js`**
51
+
52
+ ### Profiling the generated Wasm of a JS file
53
+ > [!WARNING]
54
+ > Very experimental WIP feature!
55
+
56
+ **`porf debug-wasm path/to/script.js`**
41
57
 
42
- ### Compiling to a Wasm binary
43
- **`./porf compile path/to/script.js out.wasm`**. Currently it does not use an import standard like WASI, so it is mostly unusable.
44
58
 
45
59
  ### Options
46
- - `-target=wasm|c|native` (default: `wasm`) to set target output (native compiles c output to binary, see args below)
47
- - `-target=c|native` only:
48
- - `-o=out.c|out.exe|out` to set file to output c or binary
49
- - `-target=native` only:
50
- - `-compiler=clang` to set compiler binary (path/name) to use to compile
51
- - `-cO=O3` to set compiler opt argument
52
- - `-parser=acorn|@babel/parser|meriyah|hermes-parser` (default: `acorn`) to set which parser to use
53
- - `-parse-types` to enable parsing type annotations/typescript. if `-parser` is unset, changes default to `@babel/parser`. does not type check
54
- - `-opt-types` to perform optimizations using type annotations as compiler hints. does not type check
55
- - `-valtype=i32|i64|f64` (default: `f64`) to set valtype
60
+ - `--parser=acorn|@babel/parser|meriyah|hermes-parser` (default: `acorn`) to set which parser to use
61
+ - `--parse-types` to enable parsing type annotations/typescript. if `-parser` is unset, changes default to `@babel/parser`. does not type check
62
+ - `--opt-types` to perform optimizations using type annotations as compiler hints. does not type check
63
+ - `--valtype=i32|i64|f64` (default: `f64`) to set valtype
56
64
  - `-O0` to disable opt
57
65
  - `-O1` (default) to enable basic opt (simplify insts, treeshake wasm imports)
58
66
  - `-O2` to enable advanced opt (inlining). unstable
59
67
  - `-O3` to enable advanceder opt (precompute const math). unstable
60
- - `-no-run` to not run wasm output, just compile
61
- - `-opt-log` to log some opts
62
- - `-code-log` to log some codegen (you probably want `-funcs`)
63
- - `-regex-log` to log some regex
64
- - `-funcs` to log funcs
65
- - `-ast-log` to log AST
66
- - `-opt-funcs` to log funcs after opt
67
- - `-sections` to log sections as hex
68
- - `-opt-no-inline` to not inline any funcs
69
- - `-tail-call` to enable tail calls (experimental + not widely implemented)
70
- - `-compile-hints` to enable V8 compilation hints (experimental + doesn't seem to do much?)
68
+ - `--no-run` to not run wasm output, just compile
69
+ - `--opt-log` to log some opts
70
+ - `--code-log` to log some codegen (you probably want `-funcs`)
71
+ - `--regex-log` to log some regex
72
+ - `--funcs` to log funcs
73
+ - `--ast-log` to log AST
74
+ - `--opt-funcs` to log funcs after opt
75
+ - `--sections` to log sections as hex
76
+ - `--opt-no-inline` to not inline any funcs
77
+ - `--tail-call` to enable tail calls (experimental + not widely implemented)
78
+ - `--compile-hints` to enable V8 compilation hints (experimental + doesn't seem to do much?)
79
+
80
+ ### Running in the repo
81
+ The repo comes with easy alias files for Unix and Windows, which you can use like so:
82
+ - Unix: `./porf path/to/script.js`
83
+ - Windows: `.\porf path/to/script.js`
84
+
85
+ Please note that further examples below will just use `./porf`, you need to use `.\porf` on Windows. You can also swap out `node` in the alias to use another runtime like Deno (`deno run -A`) or Bun (`bun ...`), or just use it yourself (eg `node runner/index.js ...`, `bun runner/index.js ...`). Node and Bun should work great, Deno support is WIP.
71
86
 
72
87
  ## Limitations
73
88
  - No full object support yet
@@ -151,23 +166,28 @@ These include some early (stage 1/0) and/or dead (last commit years ago) proposa
151
166
  - Array member setting (`arr[0] = 2`, `arr[0] += 2`, etc)
152
167
  - Array constructor (`Array(5)`, `new Array(1, 2, 3)`)
153
168
  - Labelled statements (`foo: while (...)`)
169
+ - `do...while` loops
154
170
 
155
171
  ### Built-ins
156
172
 
157
- - `NaN` and `Infinity` (f64 only)
158
- - `isNaN()` and `isFinite()` (f64 only)
159
- - Most of `Number` (`MAX_VALUE`, `MIN_VALUE`, `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, `EPSILON`, `NaN`, `isNaN`, `isFinite`, `isInteger`, `isSafeInteger`) (some f64 only)
160
- - Some `Math` funcs (`sqrt`, `abs`, `floor`, `sign`, `round`, `trunc`, `clz32`, `fround`, `random`) (f64 only)
173
+ - `NaN` and `Infinity`
174
+ - `isNaN()` and `isFinite()`
175
+ - Most of `Number` (`MAX_VALUE`, `MIN_VALUE`, `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, `EPSILON`, `NaN`, `isNaN`, `isFinite`, `isInteger`, `isSafeInteger`)
176
+ - Some `Math` funcs (`sqrt`, `abs`, `floor`, `sign`, `round`, `trunc`, `clz32`, `fround`, `random`)
161
177
  - Basic `globalThis` support
162
178
  - Basic `Boolean` and `Number`
163
179
  - Basic `eval` for literals
164
180
  - `Math.random()` using self-made xorshift128+ PRNG
165
- - Some of `performance` (`now()`)
166
- - Some of `Array.prototype` (`at`, `push`, `pop`, `shift`, `fill`)
181
+ - Some of `performance` (`now()`, `timeOrigin`)
182
+ - Some of `Array.prototype` (`at`, `push`, `pop`, `shift`, `fill`, `slice`, `indexOf`, `lastIndexOf`, `includes`, `with`, `reverse`, `toReversed`)
167
183
  - Some of `Array` (`of`, `isArray`)
168
- - Some of `String.prototype` (`at`, `charAt`, `charCodeAt`)
184
+ - Most of `String.prototype` (`at`, `charAt`, `charCodeAt`, `toUpperCase`, `toLowerCase`, `startsWith`, `endsWith`, `indexOf`, `lastIndexOf`, `includes`, `padStart`, `padEnd`, `substring`, `substr`, `slice`, `trimStart`, `trimEnd`, `trim`, `toString`, `big`, `blink`, `bold`, `fixed`, `italics`, `small`, `strike`, `sub`, `sup`, `trimLeft`, `trimRight`, )
169
185
  - Some of `crypto` (`randomUUID`)
170
186
  - `escape`
187
+ - `btoa`
188
+ - Most of `Number.prototype` (`toString`, `toFixed`, `toExponential`)
189
+ - `parseInt`
190
+ - Spec-compliant `Date`
171
191
 
172
192
  ### Custom
173
193
 
@@ -185,7 +205,7 @@ Mostly for reducing size. I do not really care about compiler perf/time as long
185
205
  ### Traditional opts
186
206
  - Inlining functions (WIP, limited)
187
207
  - Inline const math ops
188
- - Tail calls (behind flag `-tail-call`)
208
+ - Tail calls (behind flag `--tail-call`)
189
209
 
190
210
  ### Wasm transforms
191
211
  - `local.set`, `local.get` -> `local.tee`
@@ -271,8 +291,6 @@ No particular order and no guarentees, just what could happen soon™
271
291
  - Run precompiled Wasm file if given
272
292
  - Docs
273
293
  - Update codebase readme section
274
- - REPL
275
- - Basic polyfill of `node:repl` for non-Node runtimes to work
276
294
  - Cool proposals
277
295
  - [Optional Chaining Assignment](https://github.com/tc39/proposal-optional-chaining-assignment)
278
296
  - [Modulus and Additional Integer Math](https://github.com/tc39/proposal-integer-and-modulus-math)
@@ -292,6 +310,15 @@ No particular order and no guarentees, just what could happen soon™
292
310
  ## VSCode extension
293
311
  There is a vscode extension in `vscode-ext` which tweaks JS syntax highlighting to be nicer with porffor features (eg highlighting wasm inside of inline asm).
294
312
 
313
+ ## Wasm proposals used
314
+ Porffor intentionally does not use Wasm proposals which are not commonly implemented yet (eg GC) so it can be used in as many places as possible.
315
+
316
+ - Multi-value **(required)**
317
+ - Non-trapping float-to-int conversions **(required)**
318
+ - Bulk memory operations (required, but uncommonly used)
319
+ - Exception handling (optional, for errors)
320
+ - Tail calls (opt-in, off by default)
321
+
295
322
  ## Isn't this the same as AssemblyScript/other Wasm langs?
296
323
  No. they are not alike at all internally and have very different goals/ideals:
297
324
  - Porffor is made as a generic JS engine, not for Wasm stuff specifically
package/asur/index.js CHANGED
@@ -985,7 +985,7 @@ const stringifyOp = ({ types, funcs, codes, imports, globals }, op, porfFunc = o
985
985
  if (!porfFunc.invLocals) porfFunc.invLocals = inv(porfFunc.locals, x => x.idx);
986
986
 
987
987
  if (op.func != null) {
988
- str += ` \x1b[90m${op.func >= imports.length ? `${noHighlight(codes[op.func - imports.length].bc.porfFunc.name)}` : `${({ p: 'print', c: 'printChar', t: 'time', y: 'profile1', z: 'profile2' })[imports[op.func].name]}`}`;
988
+ str += ` \x1b[90m${op.func >= imports.length ? `${noHighlight(codes[op.func - imports.length].bc.porfFunc.name)}` : `${({ p: 'print', c: 'printChar', t: 'time', u: 'timeOrigin', y: 'profile1', z: 'profile2' })[imports[op.func].name]}`}`;
989
989
  const type = types[op.func >= imports.length ? funcs[op.func - imports.length] : imports[op.func].typeIdx];
990
990
  str += ` (${type.params.map(x => noHighlight(invValtype[x])).join(', ')}) -> (${type.returns.map(x => noHighlight(invValtype[x])).join(', ')})`;
991
991
  str += '\x1b[0m';
@@ -1244,7 +1244,7 @@ paused = _paused;`);
1244
1244
  });
1245
1245
 
1246
1246
  export const instantiate = async (binary, importImpls) => {
1247
- const _vm = process?.argv?.includes('-wasm-debug') ? await wasmDebugVm() : vm;
1247
+ const _vm = process?.argv?.includes('--wasm-debug') ? await wasmDebugVm() : vm;
1248
1248
 
1249
1249
  const parsed = parse(binary);
1250
1250
  const exports = {};
@@ -45,7 +45,7 @@ export default (funcs, globals, tags, pages, data, flags) => {
45
45
 
46
46
  let importFuncs = [];
47
47
 
48
- if (optLevel < 1) {
48
+ if (optLevel < 1 || !Prefs.treeshakeWasmImports) {
49
49
  importFuncs = importedFuncs;
50
50
  } else {
51
51
  let imports = new Map();
@@ -154,7 +154,7 @@ export default (funcs, globals, tags, pages, data, flags) => {
154
154
 
155
155
  const exports = funcs.filter(x => x.export).map((x, i) => [ ...encodeString(x.name === 'main' ? 'm' : x.name), ExportDesc.func, x.index ]);
156
156
 
157
- if (Prefs.alwaysMemory && pages.size === 0) pages.set('-always-memory', 0);
157
+ if (Prefs.alwaysMemory && pages.size === 0) pages.set('--always-memory', 0);
158
158
  if (optLevel === 0) pages.set('O0 precaution', 0);
159
159
 
160
160
  const usesMemory = pages.size > 0;
@@ -1,5 +1,5 @@
1
1
  export default () => {
2
- let out = `// @porf -funsafe-no-unlikely-proto-checks -valtype=i32
2
+ let out = `// @porf --funsafe-no-unlikely-proto-checks --valtype=i32
3
3
  `;
4
4
 
5
5
  const annexB_noArgs = (a0, a1) => out += `
@@ -1,6 +1,5 @@
1
- // @porf -funsafe-no-unlikely-proto-checks -valtype=i32
1
+ // @porf --funsafe-no-unlikely-proto-checks --valtype=i32
2
2
 
3
- // todo: trimLeft, trimRight
4
3
  export const __String_prototype_trimLeft = (_this: string) => {
5
4
  return __String_prototype_trimStart(_this);
6
5
  };
@@ -1,4 +1,4 @@
1
- // @porf -funsafe-no-unlikely-proto-checks
1
+ // @porf --funsafe-no-unlikely-proto-checks
2
2
 
3
3
  export const __Array_isArray = (x: unknown): boolean =>
4
4
  // Porffor.wasm`local.get ${x+1}` == Porffor.TYPES._array;
@@ -1,82 +1,4 @@
1
- // @porf -funsafe-no-unlikely-proto-checks -valtype=i32
2
-
3
- // while (len >= 8) {
4
- // Porffor.wasm`
5
- // local tmp i64
6
- // local.get ${i}
7
- // i64.load 0 4
8
- // local.set tmp
9
-
10
- // local k i64
11
- // i64.const 0
12
- // local.set k
13
-
14
- // loop 64
15
- // local.get ${j}
16
-
17
- // local.get ${keyStrPtr}
18
-
19
- // local.get tmp
20
-
21
- // ;; k * 6
22
- // i64.const 58
23
-
24
- // local.get k
25
- // i64.const 6
26
- // i64.mul
27
-
28
- // i64.sub
29
-
30
- // ;; tmp >> (58 - (k * 6))
31
- // i64.shr_u
32
-
33
- // ;; (tmp >> (58 - (k * 6))) & 0x3f
34
- // i64.const 63
35
- // i64.and
36
-
37
- // i32.wrap_i64
38
-
39
- // ;; keyStrPtr + ...
40
- // i32.add
41
-
42
- // ;; load character from keyStr
43
- // i32.load8_u 0 4
44
-
45
- // ;; store in output at j
46
- // i32.store8 0 4
47
-
48
- // local.get ${j}
49
- // i32.const 1
50
- // i32.add
51
- // local.set ${j}
52
-
53
- // local.get k
54
- // i64.const 1
55
- // i64.add
56
- // local.tee k
57
-
58
- // i64.const 8
59
- // i64.lt_s
60
- // br_if 0
61
- // end
62
-
63
- // `;
64
-
65
- // // len -= 6;
66
- // i += 6;
67
- // }
68
-
69
- // // while (k < 8) {
70
- // // Porffor.wasm.i32.store8(j++, Porffor.wasm.i32.load8_u(keyStrPtr + Porffor.wasm.i32.wrap_i64(Porffor.wasm.i64.and(
71
- // // Porffor.wasm.i64.shr_u(tmp, Porffor.wasm.i64.extend_i32_u(58 - k * 6)),
72
- // // Porffor.wasm.i64.const(0x3f)
73
- // // )), 0, 4), 0, 4);
74
- // // k += 1;
75
- // // }
76
-
77
- // i += 6;
78
- // len -= 6;
79
- // }
1
+ // @porf --funsafe-no-unlikely-proto-checks --valtype=i32
80
2
 
81
3
  export const btoa = (input: bytestring): bytestring => {
82
4
  const keyStr: bytestring = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
@@ -89,6 +11,8 @@ export const btoa = (input: bytestring): bytestring => {
89
11
  let i: i32 = Porffor.wasm`local.get ${input}`,
90
12
  j: i32 = Porffor.wasm`local.get ${output}`;
91
13
 
14
+ // todo/perf: add some per 6 char variant using bitwise magic
15
+
92
16
  const endPtr = i + len;
93
17
  while (i < endPtr) {
94
18
  const chr1: i32 = Porffor.wasm.i32.load8_u(i++, 0, 4);
@@ -116,6 +40,7 @@ export const btoa = (input: bytestring): bytestring => {
116
40
  return output;
117
41
  };
118
42
 
43
+ // todo: impl atob by converting below to "porf ts"
119
44
  /* var atob = function (input) {
120
45
  const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
121
46
 
@@ -1,4 +1,4 @@
1
- // @porf -funsafe-no-unlikely-proto-checks -valtype=i32
1
+ // @porf --funsafe-no-unlikely-proto-checks --valtype=i32
2
2
 
3
3
  export const __crypto_randomUUID = (): bytestring => {
4
4
  let bytes: bytestring = '................';