porffor 0.0.0-05f898f
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.
- package/LICENSE +21 -0
- package/README.md +308 -0
- package/c +0 -0
- package/c.exe +0 -0
- package/compiler/2c.js +350 -0
- package/compiler/builtins/base64.js +92 -0
- package/compiler/builtins.js +769 -0
- package/compiler/codeGen.js +2281 -0
- package/compiler/decompile.js +102 -0
- package/compiler/embedding.js +19 -0
- package/compiler/encoding.js +219 -0
- package/compiler/expression.js +70 -0
- package/compiler/index.js +118 -0
- package/compiler/opt.js +466 -0
- package/compiler/parse.js +9 -0
- package/compiler/prototype.js +271 -0
- package/compiler/sections.js +180 -0
- package/compiler/wasmSpec.js +200 -0
- package/compiler/wrap.js +130 -0
- package/cool.exe +0 -0
- package/g +0 -0
- package/g.exe +0 -0
- package/hi.c +37 -0
- package/out +0 -0
- package/out.exe +0 -0
- package/package.json +23 -0
- package/porf.cmd +2 -0
- package/publish.js +13 -0
- package/r.js +1 -0
- package/rhemyn/README.md +37 -0
- package/rhemyn/compile.js +214 -0
- package/rhemyn/parse.js +321 -0
- package/rhemyn/test/parse.js +59 -0
- package/runner/compare.js +35 -0
- package/runner/index.js +53 -0
- package/runner/info.js +54 -0
- package/runner/profile.js +47 -0
- package/runner/repl.js +99 -0
- package/runner/sizes.js +38 -0
- package/runner/transform.js +15 -0
- package/runner/version.js +10 -0
- package/sw.js +26 -0
- package/t.js +31 -0
- package/tmp.c +58 -0
- package/util/enum.js +20 -0
package/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2023 CanadaHonk
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
@@ -0,0 +1,308 @@
|
|
1
|
+
# porffor
|
2
|
+
a basic experimental wip *aot* optimizing js -> wasm/c engine/compiler/runtime in js. not serious/intended for (real) use. (this is a straight forward, honest readme)<br>
|
3
|
+
age: ~1 month
|
4
|
+
|
5
|
+
## design
|
6
|
+
porffor is a very unique js engine, due a very different approach. it is seriously limited, but what it can do, it does pretty well. key differences:
|
7
|
+
- 100% aot compiled *(not jit)*
|
8
|
+
- no constant runtime/preluded code
|
9
|
+
- least Wasm imports possible (only stdio)
|
10
|
+
|
11
|
+
porffor is mostly built from scratch, the only thing that is not is the parser (using [acorn](https://github.com/acornjs/acorn)). binaryen/etc is not used, we make final wasm binaries ourself. you could imagine it as compiling a language which is a sub (some things unsupported) and super (new/custom apis) set of javascript. not based on any particular spec version, focusing on function/working over spec compliance.
|
12
|
+
|
13
|
+
## limitations
|
14
|
+
- no full object support yet
|
15
|
+
- little built-ins/prototype
|
16
|
+
- no async/promise/await
|
17
|
+
- no variables between scopes (except args and globals)
|
18
|
+
- literal callees only in calls (eg `print()` works, `a = print; a()` does not)
|
19
|
+
|
20
|
+
## rhemyn
|
21
|
+
rhemyn is porffor's own regex engine; it compiles literal regex to wasm bytecode aot (remind you of anything?). it is quite basic and wip. see [its readme](rhemyn/README.md) for more details.
|
22
|
+
|
23
|
+
## 2c
|
24
|
+
2c is porffor's own wasm -> c compiler, using generated wasm bytecode and internal info to generate specific and efficient/fast c code. no boilerplate/preluded code or required external files, just for cli binaries (not like wasm2c very much at all).
|
25
|
+
|
26
|
+
## supported
|
27
|
+
see [optimizations](#optimizations) for opts implemented/supported.
|
28
|
+
|
29
|
+
### proposals
|
30
|
+
these include some early (stage 1/0) and/or dead (last commit years ago) proposals but *I* think they are pretty neat, so.
|
31
|
+
|
32
|
+
#### `Math` proposals (stage 1/0)
|
33
|
+
|
34
|
+
- [`Math.clamp` Proposal](https://github.com/Richienb/proposal-math-clamp): `Math.clamp` (stage 0 - last commit april 2023)
|
35
|
+
- [`Math` Extensions Proposal](https://github.com/rwaldron/proposal-math-extensions): `Math.scale`, `Math.radians`, `Math.degrees`, `Math.RAD_PER_DEG`, `Math.DEG_PER_RAD` (stage 1 - last commit september 2020)
|
36
|
+
- [`Math.signbit` Proposal](https://github.com/tc39/proposal-Math.signbit): `Math.signbit` (stage 1 - last commit february 2020)
|
37
|
+
|
38
|
+
### language
|
39
|
+
|
40
|
+
- number literals
|
41
|
+
- declaring functions
|
42
|
+
- calling functions *literal callees only*
|
43
|
+
- `return`
|
44
|
+
- `let`/`const`/`var` basic declarations
|
45
|
+
- some basic integer operators (`+-/*%`)
|
46
|
+
- some basic integer bitwise operators (`&|`)
|
47
|
+
- equality operators (`==`, `!=`, etc)
|
48
|
+
- gt/lt operators (`>`, `<`, `>=`, etc)
|
49
|
+
- some unary operators (`!`, `+`, `-`)
|
50
|
+
- logical operators (`&&`, `||`)
|
51
|
+
- declaring multiple variables in one (`let a, b = 0`)
|
52
|
+
- global variables (`var`/none in top scope)
|
53
|
+
- functions returning 1 number
|
54
|
+
- bool literals as ints (not real type)
|
55
|
+
- `if` and `if ... else`
|
56
|
+
- anonymous functions
|
57
|
+
- setting functions using vars (`const foo = function() { ... }`)
|
58
|
+
- arrow functions
|
59
|
+
- `undefined`/`null` as ints (hack)
|
60
|
+
- update expressions (`a++`, `++b`, `c--`, etc)
|
61
|
+
- `for` loops (`for (let i = 0; i < N; i++)`, etc)
|
62
|
+
- hack for "chars" as ints (`'X'` -> `88`)
|
63
|
+
- *basic* objects (hack)
|
64
|
+
- `console.log` (hack)
|
65
|
+
- `while` loops
|
66
|
+
- `break` and `continue`
|
67
|
+
- named export funcs
|
68
|
+
- iife support
|
69
|
+
- assignment operators (`+=`, `-=`, `>>=`, `&&=`, etc)
|
70
|
+
- conditional/ternary operator (`cond ? a : b`)
|
71
|
+
- recursive functions
|
72
|
+
- bare returns (`return`)
|
73
|
+
- `throw` (literals only)
|
74
|
+
- basic `try { ... } catch { ... }` (no error given)
|
75
|
+
- calling functions with non-matching arguments (eg `f(a, b); f(0); f(1, 2, 3);`)
|
76
|
+
- `typeof` mostly (static-ish)
|
77
|
+
- runtime errors for undeclared variables (`ReferenceError`), not functions (`TypeError`)
|
78
|
+
- array creation via `[]` (eg `let arr = [ 1, 2, 3 ]`)
|
79
|
+
- array member access via `arr[ind]` (eg `arr[0]`)
|
80
|
+
- string literals (`'hello world'`)
|
81
|
+
- string member (char) access via `str[ind]` (eg `str[0]`)
|
82
|
+
- string concat (`+`) (eg `'a' + 'b'`)
|
83
|
+
- truthy/falsy (eg `!'' == true`)
|
84
|
+
- string comparison (eg `'a' == 'a'`, `'a' != 'b'`)
|
85
|
+
- nullish coalescing operator (`??`)
|
86
|
+
|
87
|
+
### built-ins
|
88
|
+
|
89
|
+
- `NaN` and `Infinity` (f64 only)
|
90
|
+
- `isNaN()` and `isFinite()` (f64 only)
|
91
|
+
- 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)
|
92
|
+
- some `Math` funcs (`Math.sqrt`, `Math.abs`, `Math.floor`, `Math.sign`, `Math.round`, `Math.trunc`, `Math.clz32`, `Math.fround`, `Math.random`) (f64 only)
|
93
|
+
- basic `globalThis` support
|
94
|
+
- basic `Boolean` and `Number`
|
95
|
+
- basic `eval` (literals only)
|
96
|
+
- `Math.random()` using self-made xorshift128+ PRNG
|
97
|
+
- some of `performance` (`now()`)
|
98
|
+
- some of `Array.prototype` (`at`, `push`, `pop`, `shift`)
|
99
|
+
- some of `String.prototype` (`at`, `charAt`, `charCodeAt`)
|
100
|
+
|
101
|
+
### custom
|
102
|
+
|
103
|
+
- basic `assert` func
|
104
|
+
- supports i32, i64, and f64 for valtypes
|
105
|
+
- wip SIMD api (docs needed)
|
106
|
+
- intrinsic functions (see below)
|
107
|
+
- inlining wasm via ``asm`...``\` "macro"
|
108
|
+
|
109
|
+
## todo
|
110
|
+
no particular order and no guarentees, just what could happen soon™
|
111
|
+
|
112
|
+
- arrays
|
113
|
+
- member setting (`arr[0] = 2`)
|
114
|
+
- more of `Array` prototype
|
115
|
+
- arrays/strings inside arrays
|
116
|
+
- destructuring
|
117
|
+
- for .. of
|
118
|
+
- strings
|
119
|
+
- member setting
|
120
|
+
- objects
|
121
|
+
- basic object expressions (eg `{}`, `{ a: 0 }`)
|
122
|
+
- wasm
|
123
|
+
- *basic* wasm engine (interpreter) in js
|
124
|
+
- more math operators (`**`, etc)
|
125
|
+
- `do { ... } while (...)`
|
126
|
+
- rewrite `console.log` to work with strings/arrays
|
127
|
+
- exceptions
|
128
|
+
- rewrite to use actual strings (optional?)
|
129
|
+
- `try { } finally { }`
|
130
|
+
- rethrowing inside catch
|
131
|
+
- optimizations
|
132
|
+
- rewrite local indexes per func for smallest local header and remove unused idxs
|
133
|
+
- smarter inline selection (snapshots?)
|
134
|
+
- remove const ifs (`if (true)`, etc)
|
135
|
+
- use data segments for initing arrays
|
136
|
+
|
137
|
+
## porfformance
|
138
|
+
*for the things it supports*, porffor is blazingly faster compared to most interpreters, and engines running without JIT. for those with JIT, it is not that much slower like a traditional interpreter would be.
|
139
|
+
|
140
|
+

|
141
|
+
|
142
|
+
## optimizations
|
143
|
+
mostly for reducing size. do not really care about compiler perf/time as long as it is reasonable. we do not use/rely on external opt tools (`wasm-opt`, etc), instead doing optimization inside the compiler itself creating even smaller code sizes than `wasm-opt` itself can produce as we have more internal information. (this also enables fast + small runtime use as a potential cursed jit in frontend).
|
144
|
+
|
145
|
+
### traditional opts
|
146
|
+
- inlining functions (wip, limited)
|
147
|
+
- inline const math ops
|
148
|
+
- tail calls (behind flag `-tail-call`)
|
149
|
+
|
150
|
+
### wasm transforms
|
151
|
+
- `local.set`, `local.get` -> `local.tee`
|
152
|
+
- `i32.const 0`, `i32.eq` -> `i32.eqz`
|
153
|
+
- `i64.extend_i32_s`, `i32.wrap_i64` -> ``
|
154
|
+
- `f64.convert_i32_u`, `i32.trunc_sat_f64_s` -> ``
|
155
|
+
- `return`, `end` -> `end`
|
156
|
+
- change const, convert to const of converted valtype (eg `f64.const`, `i32.trunc_sat_f64_s -> `i32.const`)
|
157
|
+
- remove some redundant sets/gets
|
158
|
+
- remove unneeded single just used vars
|
159
|
+
- remove unneeded blocks (no `br`s inside)
|
160
|
+
- remove unused imports
|
161
|
+
|
162
|
+
### wasm module
|
163
|
+
- type cache/index (no repeated types)
|
164
|
+
- no main func if empty (and other exports)
|
165
|
+
|
166
|
+
## test262
|
167
|
+
porffor can run test262 via some hacks/transforms which remove unsupported features whilst still doing the same asserts (eg simpler error messages using literals only). it currently passes >10% (see latest commit desc for latest and details). use `node test262` to test, it will also show a difference of overall results between the last commit and current results.
|
168
|
+
|
169
|
+
## codebase
|
170
|
+
- `compiler`: contains the compiler itself
|
171
|
+
- `builtins.js`: all built-ins of the engine (spec, custom. vars, funcs)
|
172
|
+
- `codeGen.js`: code (wasm) generation, ast -> wasm, the bulk of the effort
|
173
|
+
- `decompile.js`: basic wasm decompiler for debug info
|
174
|
+
- `embedding.js`: utils for embedding consts
|
175
|
+
- `encoding.js`: utils for encoding things as bytes as wasm expects
|
176
|
+
- `expression.js`: mapping most operators to an opcode (advanced are as built-ins eg `f64_%`)
|
177
|
+
- `index.js`: doing all the compiler steps, takes code in, wasm out
|
178
|
+
- `opt.js`: self-made wasm bytecode optimizer
|
179
|
+
- `parse.js`: parser simply wrapping acorn
|
180
|
+
- `sections.js`: assembles wasm ops and metadata into a wasm module/file
|
181
|
+
- `wasmSpec.js`: "enums"/info from wasm spec
|
182
|
+
- `wrap.js`: wrapper for compiler which instantiates and produces nice exports
|
183
|
+
|
184
|
+
- `runner`: contains utils for running js with the compiler
|
185
|
+
- `index.js`: the main file, you probably want to use this
|
186
|
+
- `info.js`: runs with extra info printed
|
187
|
+
- `repl.js`: basic repl (uses `node:repl`)
|
188
|
+
|
189
|
+
- `rhemyn`: contains [rhemyn](#rhemyn) - the regex engine used by porffor
|
190
|
+
- `compile.js`: compiles regex ast into wasm bytecode
|
191
|
+
- `parse.js`: own regex parser
|
192
|
+
|
193
|
+
- `test`: contains many test files for majority of supported features
|
194
|
+
- `test262`: test262 runner and utils
|
195
|
+
|
196
|
+
## usecases
|
197
|
+
basically none (other than giving people headaches). potential as a tiny fast advanced expression evaluator (for math)?
|
198
|
+
|
199
|
+
## usage
|
200
|
+
basically nothing will work :). see files in `test` for examples.
|
201
|
+
|
202
|
+
1. clone repo
|
203
|
+
2. `npm install`
|
204
|
+
3. `node test` to run tests (all should pass)
|
205
|
+
4. `node runner path/to/code.js` to run a file (or `node runner` to use wip repl)
|
206
|
+
|
207
|
+
you can also use deno (`deno run -A ...` instead of `node ...`), or bun (`bun ...` instead of `node ...`)
|
208
|
+
|
209
|
+
### flags
|
210
|
+
- `-target=wasm|c|native` (default: `wasm`) to set target output (native compiles c output to binary, see args below)
|
211
|
+
- `-target=c|native` only:
|
212
|
+
- `-o=out.c|out.exe|out` to set file to output c or binary
|
213
|
+
- `-target=native` only:
|
214
|
+
- `-compiler=clang` to set compiler binary (path/name) to use to compile
|
215
|
+
- `-cO=O3` to set compiler opt argument
|
216
|
+
- `-valtype=i32|i64|f64` (default: `f64`) to set valtype
|
217
|
+
- `-O0` to disable opt
|
218
|
+
- `-O1` (default) to enable basic opt (simplify insts, treeshake wasm imports)
|
219
|
+
- `-O2` to enable advanced opt (inlining)
|
220
|
+
- `-O3` to enable advanceder opt (precompute const math)
|
221
|
+
- `-no-run` to not run wasm output, just compile
|
222
|
+
- `-opt-log` to log some opts
|
223
|
+
- `-code-log` to log some codegen (you probably want `-funcs`)
|
224
|
+
- `-regex-log` to log some regex
|
225
|
+
- `-funcs` to log funcs
|
226
|
+
- `-opt-funcs` to log funcs after opt
|
227
|
+
- `-sections` to log sections as hex
|
228
|
+
- `-opt-no-inline` to not inline any funcs
|
229
|
+
- `-tail-call` to enable tail calls (experimental + not widely implemented)
|
230
|
+
- `-compile-hints` to enable V8 compilation hints (experimental + doesn't seem to do much?)
|
231
|
+
|
232
|
+
## vscode extension
|
233
|
+
there is a vscode extension in `porffor-for-vscode` which tweaks js syntax highlighting to be nicer with porffor features (eg highlighting wasm inside of inline asm).
|
234
|
+
|
235
|
+
## wasm output
|
236
|
+
porffor optimizes for size as much as possible. current output is ~as small as possible (even with manual asm editing) for some simple functions.
|
237
|
+
|
238
|
+
### example
|
239
|
+
this javascript (159 bytes unminified):
|
240
|
+
```js
|
241
|
+
function isPrime(number) {
|
242
|
+
if (number === 1) return false;
|
243
|
+
|
244
|
+
for (let i = 2; i < number; i++) {
|
245
|
+
if (number % i == 0) return false;
|
246
|
+
}
|
247
|
+
|
248
|
+
return true;
|
249
|
+
}
|
250
|
+
```
|
251
|
+
|
252
|
+
compiles into this wasm, in 7.3ms (just compile time), 90 bytes large (including module):
|
253
|
+
```wasm
|
254
|
+
(i32) -> (i32) ;; isPrime
|
255
|
+
local.get 0 ;; number
|
256
|
+
i32.const 1
|
257
|
+
i32.eq
|
258
|
+
if ;; label @2
|
259
|
+
i32.const 0
|
260
|
+
return
|
261
|
+
end
|
262
|
+
i32.const 2
|
263
|
+
local.set 1 ;; i
|
264
|
+
loop ;; label @2
|
265
|
+
local.get 1 ;; i
|
266
|
+
local.get 0 ;; number
|
267
|
+
i32.lt_s
|
268
|
+
if ;; label @3
|
269
|
+
local.get 0 ;; number
|
270
|
+
local.get 1 ;; i
|
271
|
+
i32.rem_s
|
272
|
+
i32.eqz
|
273
|
+
if ;; label @4
|
274
|
+
i32.const 0
|
275
|
+
return
|
276
|
+
end
|
277
|
+
local.get 1 ;; i
|
278
|
+
i32.const 1
|
279
|
+
i32.add
|
280
|
+
local.set 1 ;; i
|
281
|
+
br 1 ;; goto @2
|
282
|
+
end
|
283
|
+
end
|
284
|
+
i32.const 1
|
285
|
+
end
|
286
|
+
```
|
287
|
+
|
288
|
+
## isn't this the same as assemblyscript?
|
289
|
+
no. they are not alike at all internally and have different goals/ideals:
|
290
|
+
- porffor is made as a generic js engine, not for wasm stuff specifically
|
291
|
+
- porffor takes in js, not a different language or typescript like assemblyscript
|
292
|
+
- porffor is made in pure js and compiles itself, not using binaryen/etc
|
293
|
+
- (also I didn't know it existed when I started this)
|
294
|
+
|
295
|
+
## faq
|
296
|
+
|
297
|
+
### 1. why name
|
298
|
+
`purple` in Welsh is `porffor`. why purple?
|
299
|
+
- no other js engine is purple colored
|
300
|
+
- purple is pretty cool
|
301
|
+
- purple apparently represents "ambition", which is.. one word to describe this project
|
302
|
+
- the hard to speak name is also the noise your brain makes in reaction to this idea
|
303
|
+
|
304
|
+
### 2. why at all
|
305
|
+
yes.
|
306
|
+
|
307
|
+
### 3. but what about spec compliance?
|
308
|
+
lol, no. (sorry.)
|
package/c
ADDED
Binary file
|
package/c.exe
ADDED
Binary file
|
package/compiler/2c.js
ADDED
@@ -0,0 +1,350 @@
|
|
1
|
+
import { read_ieee754_binary64, read_signedLEB128 } from './encoding.js';
|
2
|
+
import { Blocktype, Opcodes, Valtype } from './wasmSpec.js';
|
3
|
+
import { operatorOpcode } from './expression.js';
|
4
|
+
|
5
|
+
const CValtype = {
|
6
|
+
i8: 'char',
|
7
|
+
i16: 'unsigned short', // presume all i16 stuff is unsigned
|
8
|
+
i32: 'long',
|
9
|
+
i32_u: 'unsigned long',
|
10
|
+
i64: 'long long',
|
11
|
+
i64_u: 'unsigned long long',
|
12
|
+
|
13
|
+
f32: 'float',
|
14
|
+
f64: 'double',
|
15
|
+
|
16
|
+
undefined: 'void'
|
17
|
+
};
|
18
|
+
|
19
|
+
const inv = (obj, keyMap = x => x) => Object.keys(obj).reduce((acc, x) => { acc[keyMap(obj[x])] = x; return acc; }, {});
|
20
|
+
const invOpcodes = inv(Opcodes);
|
21
|
+
|
22
|
+
for (const x in CValtype) {
|
23
|
+
if (Valtype[x]) CValtype[Valtype[x]] = CValtype[x];
|
24
|
+
}
|
25
|
+
|
26
|
+
const todo = msg => {
|
27
|
+
class TodoError extends Error {
|
28
|
+
constructor(message) {
|
29
|
+
super(message);
|
30
|
+
this.name = 'TodoError';
|
31
|
+
}
|
32
|
+
}
|
33
|
+
|
34
|
+
throw new TodoError(`todo: ${msg}`);
|
35
|
+
};
|
36
|
+
|
37
|
+
const removeBrackets = str => str.startsWith('(') && str.endsWith(')') ? str.slice(1, -1) : str;
|
38
|
+
|
39
|
+
export default ({ funcs, globals, tags, exceptions, pages }) => {
|
40
|
+
const invOperatorOpcode = Object.values(operatorOpcode).reduce((acc, x) => {
|
41
|
+
for (const k in x) {
|
42
|
+
acc[x[k]] = k;
|
43
|
+
}
|
44
|
+
return acc;
|
45
|
+
}, {});
|
46
|
+
const invGlobals = inv(globals, x => x.idx);
|
47
|
+
|
48
|
+
const includes = new Map(), unixIncludes = new Map(), winIncludes = new Map();
|
49
|
+
let out = '';
|
50
|
+
|
51
|
+
for (const x in globals) {
|
52
|
+
const g = globals[x];
|
53
|
+
|
54
|
+
out += `${CValtype[g.type]} ${x} = ${g.init ?? 0}`;
|
55
|
+
out += ';\n';
|
56
|
+
}
|
57
|
+
|
58
|
+
for (const [ x, p ] of pages) {
|
59
|
+
out += `${CValtype[p.type]} ${x.replace(': ', '_').replace(/[^0-9a-zA-Z_]/g, '')}[100]`;
|
60
|
+
out += ';\n';
|
61
|
+
}
|
62
|
+
|
63
|
+
if (out) out += '\n';
|
64
|
+
|
65
|
+
let depth = 1;
|
66
|
+
const line = (str, semi = true) => out += `${' '.repeat(depth * 2)}${str}${semi ? ';' : ''}\n`;
|
67
|
+
const lines = lines => {
|
68
|
+
for (const x of lines) {
|
69
|
+
out += `${' '.repeat(depth * 2)}${x}\n`;
|
70
|
+
}
|
71
|
+
};
|
72
|
+
|
73
|
+
const platformSpecific = (win, unix, add = true) => {
|
74
|
+
let tmp = '';
|
75
|
+
|
76
|
+
if (win) {
|
77
|
+
if (add) out += '#ifdef _WIN32\n';
|
78
|
+
else tmp += '#ifdef _WIN32\n';
|
79
|
+
|
80
|
+
if (add) lines(win.split('\n'));
|
81
|
+
else tmp += win + (win.endsWith('\n') ? '' : '\n');
|
82
|
+
}
|
83
|
+
|
84
|
+
if (unix) {
|
85
|
+
if (add) out += (win ? '#else' : '#ifndef _WIN32') + '\n';
|
86
|
+
else tmp += (win ? '#else' : '#ifndef _WIN32') + '\n';
|
87
|
+
|
88
|
+
if (add) lines(unix.split('\n'));
|
89
|
+
else tmp += unix + (unix.endsWith('\n') ? '' : '\n');
|
90
|
+
}
|
91
|
+
|
92
|
+
if (win || unix)
|
93
|
+
if (add) out += '#endif\n';
|
94
|
+
else tmp += '#endif\n';
|
95
|
+
|
96
|
+
return tmp;
|
97
|
+
};
|
98
|
+
|
99
|
+
for (const f of funcs) {
|
100
|
+
depth = 1;
|
101
|
+
|
102
|
+
const invLocals = inv(f.locals, x => x.idx);
|
103
|
+
if (f.returns.length > 1) todo('funcs returning >1 value unsupported');
|
104
|
+
|
105
|
+
const sanitize = str => str.replace(/[^0-9a-zA-Z_]/g, _ => String.fromCharCode(97 + _.charCodeAt(0) % 32));
|
106
|
+
|
107
|
+
const returns = f.returns.length === 1;
|
108
|
+
|
109
|
+
const shouldInline = f.internal;
|
110
|
+
out += `${f.name === 'main' ? 'int' : CValtype[f.returns[0]]} ${shouldInline ? 'inline ' : ''}${sanitize(f.name)}(${f.params.map((x, i) => `${CValtype[x]} ${invLocals[i]}`).join(', ')}) {\n`;
|
111
|
+
|
112
|
+
const localKeys = Object.keys(f.locals).sort((a, b) => f.locals[a].idx - f.locals[b].idx).slice(f.params.length).sort((a, b) => f.locals[a].idx - f.locals[b].idx);
|
113
|
+
for (const x of localKeys) {
|
114
|
+
const l = f.locals[x];
|
115
|
+
line(`${CValtype[l.type]} ${x} = 0`);
|
116
|
+
}
|
117
|
+
|
118
|
+
if (localKeys.length !== 0) out += '\n';
|
119
|
+
|
120
|
+
let vals = [];
|
121
|
+
const endNeedsCurly = [], ignoreEnd = [];
|
122
|
+
let beginLoop = false, lastCond = false, ifTernary = false;
|
123
|
+
for (let _ = 0; _ < f.wasm.length; _++) {
|
124
|
+
const i = f.wasm[_];
|
125
|
+
|
126
|
+
if (invOperatorOpcode[i[0]]) {
|
127
|
+
const b = vals.pop();
|
128
|
+
const a = vals.pop();
|
129
|
+
|
130
|
+
let op = invOperatorOpcode[i[0]];
|
131
|
+
if (op.length === 3) op = op.slice(0, 2);
|
132
|
+
|
133
|
+
if (['==', '!=', '>', '>=', '<', '<='].includes(op)) lastCond = true;
|
134
|
+
else lastCond = false;
|
135
|
+
|
136
|
+
// vals.push(`${a} ${op} ${b}`);
|
137
|
+
vals.push(`(${removeBrackets(a)} ${op} ${b})`);
|
138
|
+
continue;
|
139
|
+
}
|
140
|
+
|
141
|
+
// misc insts
|
142
|
+
if (i[0] === 0xfc) {
|
143
|
+
switch (i[1]) {
|
144
|
+
// i32_trunc_sat_f64_s
|
145
|
+
case 0x02:
|
146
|
+
vals.push(`(${CValtype.i32})${vals.pop()}`);
|
147
|
+
break;
|
148
|
+
|
149
|
+
// i32_trunc_sat_f64_u
|
150
|
+
case 0x03:
|
151
|
+
vals.push(`(${CValtype.i32})(${CValtype.i32_u})${vals.pop()}`);
|
152
|
+
break;
|
153
|
+
}
|
154
|
+
|
155
|
+
lastCond = false;
|
156
|
+
continue;
|
157
|
+
}
|
158
|
+
|
159
|
+
switch (i[0]) {
|
160
|
+
case Opcodes.i32_const:
|
161
|
+
case Opcodes.i64_const:
|
162
|
+
vals.push(read_signedLEB128(i.slice(1)).toString());
|
163
|
+
break;
|
164
|
+
|
165
|
+
case Opcodes.f64_const:
|
166
|
+
vals.push(read_ieee754_binary64(i.slice(1)).toExponential());
|
167
|
+
break;
|
168
|
+
|
169
|
+
case Opcodes.local_get:
|
170
|
+
vals.push(`${invLocals[i[1]]}`);
|
171
|
+
break;
|
172
|
+
|
173
|
+
case Opcodes.local_set:
|
174
|
+
line(`${invLocals[i[1]]} = ${removeBrackets(vals.pop())}`);
|
175
|
+
break;
|
176
|
+
|
177
|
+
case Opcodes.local_tee:
|
178
|
+
line(`${invLocals[i[1]]} = ${removeBrackets(vals.pop())}`);
|
179
|
+
vals.push(`${invLocals[i[1]]}`);
|
180
|
+
// vals.push(`${invLocals[i[1]]} = ${vals.pop()}`);
|
181
|
+
break;
|
182
|
+
|
183
|
+
case Opcodes.global_get:
|
184
|
+
vals.push(`${invGlobals[i[1]]}`);
|
185
|
+
break;
|
186
|
+
|
187
|
+
case Opcodes.global_set:
|
188
|
+
line(`${invGlobals[i[1]]} = ${removeBrackets(vals.pop())}`);
|
189
|
+
break;
|
190
|
+
|
191
|
+
case Opcodes.f64_trunc:
|
192
|
+
// vals.push(`trunc(${vals.pop()})`);
|
193
|
+
vals.push(`(int)(${removeBrackets(vals.pop())})`); // this is ~10x faster with clang??
|
194
|
+
break;
|
195
|
+
|
196
|
+
case Opcodes.f64_convert_i32_u:
|
197
|
+
case Opcodes.f64_convert_i32_s:
|
198
|
+
case Opcodes.f64_convert_i64_u:
|
199
|
+
case Opcodes.f64_convert_i64_s:
|
200
|
+
// int to double
|
201
|
+
vals.push(`(double)${vals.pop()}`);
|
202
|
+
break;
|
203
|
+
|
204
|
+
case Opcodes.return:
|
205
|
+
line(`return${returns ? ` ${removeBrackets(vals.pop())}` : ''}`);
|
206
|
+
break;
|
207
|
+
|
208
|
+
case Opcodes.if:
|
209
|
+
let cond = removeBrackets(vals.pop());
|
210
|
+
if (!lastCond) {
|
211
|
+
if (cond.startsWith('(long)')) cond = `${cond.slice(6)} == 1e+0`;
|
212
|
+
else cond += ' == 1';
|
213
|
+
}
|
214
|
+
|
215
|
+
ifTernary = i[1] !== Blocktype.void;
|
216
|
+
if (ifTernary) {
|
217
|
+
ifTernary = cond;
|
218
|
+
break;
|
219
|
+
}
|
220
|
+
|
221
|
+
if (beginLoop) {
|
222
|
+
beginLoop = false;
|
223
|
+
line(`while (${cond}) {`, false);
|
224
|
+
|
225
|
+
depth++;
|
226
|
+
endNeedsCurly.push(true);
|
227
|
+
ignoreEnd.push(false, true);
|
228
|
+
break;
|
229
|
+
}
|
230
|
+
|
231
|
+
line(`if (${cond}) {`, false);
|
232
|
+
|
233
|
+
depth++;
|
234
|
+
endNeedsCurly.push(true);
|
235
|
+
ignoreEnd.push(false);
|
236
|
+
break;
|
237
|
+
|
238
|
+
case Opcodes.else:
|
239
|
+
if (ifTernary) break;
|
240
|
+
|
241
|
+
depth--;
|
242
|
+
line(`} else {`, false);
|
243
|
+
depth++;
|
244
|
+
break;
|
245
|
+
|
246
|
+
case Opcodes.loop:
|
247
|
+
// not doing properly, fake a while loop
|
248
|
+
beginLoop = true;
|
249
|
+
break;
|
250
|
+
|
251
|
+
case Opcodes.end:
|
252
|
+
if (ignoreEnd.pop()) break;
|
253
|
+
|
254
|
+
if (ifTernary) {
|
255
|
+
const b = vals.pop();
|
256
|
+
const a = vals.pop();
|
257
|
+
vals.push(`${ifTernary} ? ${a} : ${b}`);
|
258
|
+
break;
|
259
|
+
}
|
260
|
+
|
261
|
+
depth--;
|
262
|
+
if (endNeedsCurly.pop() === true) line('}', false);
|
263
|
+
break;
|
264
|
+
|
265
|
+
case Opcodes.call:
|
266
|
+
let func = funcs.find(x => x.index === i[1]);
|
267
|
+
if (!func) {
|
268
|
+
const importFunc = importFuncs[i[1]];
|
269
|
+
switch (importFunc.name) {
|
270
|
+
case 'print':
|
271
|
+
line(`printf("%f\\n", ${vals.pop()})`);
|
272
|
+
includes.set('stdio.h', true);
|
273
|
+
break;
|
274
|
+
|
275
|
+
case 'time':
|
276
|
+
line(`double _time_out`);
|
277
|
+
/* platformSpecific(
|
278
|
+
`FILETIME _time_filetime;
|
279
|
+
GetSystemTimeAsFileTime(&_time_filetime);
|
280
|
+
|
281
|
+
ULARGE_INTEGER _time_ularge;
|
282
|
+
_time_ularge.LowPart = _time_filetime.dwLowDateTime;
|
283
|
+
_time_ularge.HighPart = _time_filetime.dwHighDateTime;
|
284
|
+
_time_out = (_time_ularge.QuadPart - 116444736000000000i64) / 10000.;`,
|
285
|
+
`struct timespec _time;
|
286
|
+
clock_gettime(CLOCK_MONOTONIC, &_time);
|
287
|
+
_time_out = _time.tv_nsec / 1000000.;`); */
|
288
|
+
platformSpecific(
|
289
|
+
`LARGE_INTEGER _time_freq, _time_t;
|
290
|
+
QueryPerformanceFrequency(&_time_freq);
|
291
|
+
QueryPerformanceCounter(&_time_t);
|
292
|
+
_time_out = ((double)_time_t.QuadPart / _time_freq.QuadPart) * 1000.;`,
|
293
|
+
`struct timespec _time;
|
294
|
+
clock_gettime(CLOCK_MONOTONIC, &_time);
|
295
|
+
_time_out = _time.tv_nsec / 1000000.;`);
|
296
|
+
vals.push(`_time_out`);
|
297
|
+
|
298
|
+
unixIncludes.set('time.h', true);
|
299
|
+
winIncludes.set('windows.h', true);
|
300
|
+
break;
|
301
|
+
|
302
|
+
default:
|
303
|
+
log('2c', `unimplemented import: ${importFunc.name}`);
|
304
|
+
break;
|
305
|
+
}
|
306
|
+
|
307
|
+
break;
|
308
|
+
}
|
309
|
+
|
310
|
+
let args = [];
|
311
|
+
for (let j = 0; j < func.params.length; j++) args.unshift(removeBrackets(vals.pop()));
|
312
|
+
|
313
|
+
if (func.returns.length === 1) vals.push(`${sanitize(func.name)}(${args.join(', ')})`)
|
314
|
+
else line(`${sanitize(func.name)}(${args.join(', ')})`);
|
315
|
+
|
316
|
+
break;
|
317
|
+
|
318
|
+
case Opcodes.drop:
|
319
|
+
line(vals.pop());
|
320
|
+
break;
|
321
|
+
|
322
|
+
case Opcodes.br:
|
323
|
+
// ignore
|
324
|
+
// reset "stack"
|
325
|
+
vals = [];
|
326
|
+
break;
|
327
|
+
|
328
|
+
default:
|
329
|
+
log('2c', `unimplemented op: ${invOpcodes[i[0]]}`);
|
330
|
+
// todo(`unimplemented op: ${invOpcodes[i[0]]}`);
|
331
|
+
}
|
332
|
+
|
333
|
+
lastCond = false;
|
334
|
+
}
|
335
|
+
|
336
|
+
if (vals.length === 1 && returns) {
|
337
|
+
line(`return ${vals.pop()}`);
|
338
|
+
}
|
339
|
+
|
340
|
+
out += '}\n\n';
|
341
|
+
}
|
342
|
+
|
343
|
+
depth = 0;
|
344
|
+
|
345
|
+
const makeIncludes = includes => [...includes.keys()].map(x => `#include <${x}>\n`).join('');
|
346
|
+
|
347
|
+
out = platformSpecific(makeIncludes(winIncludes), makeIncludes(unixIncludes), false) + '\n' + makeIncludes(includes) + '\n' + out;
|
348
|
+
|
349
|
+
return out;
|
350
|
+
};
|