porffor 0.0.0-828ee15 → 0.0.0-ba812f2

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/README.md CHANGED
@@ -1,11 +1,10 @@
1
1
  # porffor
2
- a basic experimental wip *aot* optimizing js -> wasm engine/compiler/runtime in js. not serious/intended for (real) use. (this is a straight forward, honest readme)<br>
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
3
  age: ~1 month
4
4
 
5
5
  ## design
6
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
7
  - 100% aot compiled *(not jit)*
8
- - everything is a number
9
8
  - no constant runtime/preluded code
10
9
  - least Wasm imports possible (only stdio)
11
10
 
@@ -18,6 +17,12 @@ porffor is mostly built from scratch, the only thing that is not is the parser (
18
17
  - no variables between scopes (except args and globals)
19
18
  - literal callees only in calls (eg `print()` works, `a = print; a()` does not)
20
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
+
21
26
  ## supported
22
27
  see [optimizations](#optimizations) for opts implemented/supported.
23
28
 
@@ -76,6 +81,8 @@ these include some early (stage 1/0) and/or dead (last commit years ago) proposa
76
81
  - string member (char) access via `str[ind]` (eg `str[0]`)
77
82
  - string concat (`+`) (eg `'a' + 'b'`)
78
83
  - truthy/falsy (eg `!'' == true`)
84
+ - string comparison (eg `'a' == 'a'`, `'a' != 'b'`)
85
+ - nullish coalescing operator (`??`)
79
86
 
80
87
  ### built-ins
81
88
 
@@ -99,18 +106,27 @@ these include some early (stage 1/0) and/or dead (last commit years ago) proposa
99
106
  - intrinsic functions (see below)
100
107
  - inlining wasm via ``asm`...``\` "macro"
101
108
 
102
- ## soon todo
109
+ ## todo
110
+ no particular order and no guarentees, just what could happen soon™
111
+
103
112
  - arrays
104
113
  - member setting (`arr[0] = 2`)
105
114
  - more of `Array` prototype
106
115
  - arrays/strings inside arrays
116
+ - destructuring
117
+ - for .. of
107
118
  - strings
108
119
  - member setting
109
- - equality
120
+ - objects
121
+ - basic object expressions (eg `{}`, `{ a: 0 }`)
122
+ - wasm
123
+ - *basic* wasm engine (interpreter) in js
110
124
  - more math operators (`**`, etc)
111
125
  - `do { ... } while (...)`
126
+ - rewrite `console.log` to work with strings/arrays
112
127
  - exceptions
113
- - `try { } finally {}`
128
+ - rewrite to use actual strings (optional?)
129
+ - `try { } finally { }`
114
130
  - rethrowing inside catch
115
131
  - optimizations
116
132
  - rewrite local indexes per func for smallest local header and remove unused idxs
@@ -118,8 +134,10 @@ these include some early (stage 1/0) and/or dead (last commit years ago) proposa
118
134
  - remove const ifs (`if (true)`, etc)
119
135
  - use data segments for initing arrays
120
136
 
121
- ## test262
122
- 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.
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
+ ![Screenshot of comparison chart](https://github.com/CanadaHonk/porffor/assets/19228318/76c75264-cc68-4be1-8891-c06dc389d97a)
123
141
 
124
142
  ## optimizations
125
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).
@@ -135,6 +153,7 @@ mostly for reducing size. do not really care about compiler perf/time as long as
135
153
  - `i64.extend_i32_s`, `i32.wrap_i64` -> ``
136
154
  - `f64.convert_i32_u`, `i32.trunc_sat_f64_s` -> ``
137
155
  - `return`, `end` -> `end`
156
+ - change const, convert to const of converted valtype (eg `f64.const`, `i32.trunc_sat_f64_s -> `i32.const`)
138
157
  - remove some redundant sets/gets
139
158
  - remove unneeded single just used vars
140
159
  - remove unneeded blocks (no `br`s inside)
@@ -144,6 +163,9 @@ mostly for reducing size. do not really care about compiler perf/time as long as
144
163
  - type cache/index (no repeated types)
145
164
  - no main func if empty (and other exports)
146
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
+
147
169
  ## codebase
148
170
  - `compiler`: contains the compiler itself
149
171
  - `builtins.js`: all built-ins of the engine (spec, custom. vars, funcs)
@@ -164,6 +186,10 @@ mostly for reducing size. do not really care about compiler perf/time as long as
164
186
  - `info.js`: runs with extra info printed
165
187
  - `repl.js`: basic repl (uses `node:repl`)
166
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
+
167
193
  - `test`: contains many test files for majority of supported features
168
194
  - `test262`: test262 runner and utils
169
195
 
@@ -181,8 +207,13 @@ basically nothing will work :). see files in `test` for examples.
181
207
  you can also use deno (`deno run -A ...` instead of `node ...`), or bun (`bun ...` instead of `node ...`)
182
208
 
183
209
  ### flags
184
- - `-raw` for no info logs (just raw js output)
185
- - `-valtype=i32|i64|f64` to set valtype, f64 by default
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
186
217
  - `-O0` to disable opt
187
218
  - `-O1` (default) to enable basic opt (simplify insts, treeshake wasm imports)
188
219
  - `-O2` to enable advanced opt (inlining)
@@ -190,11 +221,13 @@ you can also use deno (`deno run -A ...` instead of `node ...`), or bun (`bun ..
190
221
  - `-no-run` to not run wasm output, just compile
191
222
  - `-opt-log` to log some opts
192
223
  - `-code-log` to log some codegen (you probably want `-funcs`)
193
- - `-funcs` to log funcs (internal representations)
224
+ - `-regex-log` to log some regex
225
+ - `-funcs` to log funcs
194
226
  - `-opt-funcs` to log funcs after opt
195
227
  - `-sections` to log sections as hex
196
228
  - `-opt-no-inline` to not inline any funcs
197
- - `-tail-call` to enable tail calls (not widely implemented)
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?)
198
231
 
199
232
  ## vscode extension
200
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).
package/c ADDED
Binary file
package/c.exe ADDED
Binary file
package/compiler/2c.js ADDED
@@ -0,0 +1,257 @@
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
+ import fs from 'fs';
6
+
7
+ const CValtype = {
8
+ i8: 'char',
9
+ i16: 'unsigned short', // presume all i16 stuff is unsigned
10
+ i32: 'long',
11
+ i32_u: 'unsigned long',
12
+ i64: 'long long',
13
+ i64_u: 'unsigned long long',
14
+
15
+ f32: 'float',
16
+ f64: 'double',
17
+
18
+ undefined: 'void'
19
+ };
20
+
21
+ const inv = (obj, keyMap = x => x) => Object.keys(obj).reduce((acc, x) => { acc[keyMap(obj[x])] = x; return acc; }, {});
22
+ const invOpcodes = inv(Opcodes);
23
+
24
+ for (const x in CValtype) {
25
+ if (Valtype[x]) CValtype[Valtype[x]] = CValtype[x];
26
+ }
27
+
28
+ const todo = msg => {
29
+ class TodoError extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = 'TodoError';
33
+ }
34
+ }
35
+
36
+ throw new TodoError(`todo: ${msg}`);
37
+ };
38
+
39
+ export default ({ funcs, globals, tags, exceptions, pages }) => {
40
+ const invOperatorOpcode = inv(operatorOpcode[valtype]);
41
+ const invGlobals = inv(globals, x => x.idx);
42
+
43
+ const includes = new Map();
44
+ let out = '';
45
+
46
+ for (const x in globals) {
47
+ const g = globals[x];
48
+
49
+ out += `${CValtype[g.type]} ${x}`;
50
+ if (x.init) out += ` ${x.init}`;
51
+ out += ';\n';
52
+ }
53
+
54
+ for (const [ x, p ] of pages) {
55
+ out += `${CValtype[p.type]} ${x.replace(': ', '_').replace(/[^0-9a-zA-Z_]/g, '')}[100]`;
56
+ out += ';\n';
57
+ }
58
+
59
+ if (out) out += '\n';
60
+
61
+ for (const f of funcs) {
62
+ const invLocals = inv(f.locals, x => x.idx);
63
+ if (f.returns.length > 1) todo('funcs returning >1 value unsupported');
64
+
65
+ const sanitize = str => str.replace(/[^0-9a-zA-Z_]/g, _ => String.fromCharCode(97 + _.charCodeAt(0) % 32));
66
+
67
+ const returns = f.returns.length === 1;
68
+
69
+ const shouldInline = ['f64_%'].includes(f.name);
70
+ 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`;
71
+
72
+ let depth = 1;
73
+ const line = (str, semi = true) => out += `${' '.repeat(depth * 2)}${str}${semi ? ';' : ''}\n`;
74
+
75
+ 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);
76
+ for (const x of localKeys) {
77
+ const l = f.locals[x];
78
+ line(`${CValtype[l.type]} ${x}`);
79
+ }
80
+
81
+ if (localKeys.length !== 0) out += '\n';
82
+
83
+ let vals = [];
84
+ const endNeedsCurly = [], ignoreEnd = [];
85
+ let beginLoop = false, lastCond = false, ifTernary = false;
86
+ for (let _ = 0; _ < f.wasm.length; _++) {
87
+ const i = f.wasm[_];
88
+
89
+ if (invOperatorOpcode[i[0]]) {
90
+ const b = vals.pop();
91
+ const a = vals.pop();
92
+
93
+ let op = invOperatorOpcode[i[0]];
94
+ if (op.length === 3) op = op.slice(0, 2);
95
+
96
+ if (['==', '!=', '>', '>=', '<', '<='].includes(op)) lastCond = true;
97
+ else lastCond = false;
98
+
99
+ vals.push(`${a} ${op} ${b}`);
100
+ continue;
101
+ }
102
+
103
+ // misc insts
104
+ if (i[0] === 0xfc) {
105
+ switch (i[1]) {
106
+ // i32_trunc_sat_f64_s
107
+ case 0x02:
108
+ vals.push(`(${CValtype.i32})${vals.pop()}`);
109
+ break;
110
+
111
+ // i32_trunc_sat_f64_u
112
+ case 0x03:
113
+ vals.push(`(${CValtype.i32})(${CValtype.i32_u})${vals.pop()}`);
114
+ break;
115
+ }
116
+
117
+ lastCond = false;
118
+ continue;
119
+ }
120
+
121
+ switch (i[0]) {
122
+ case Opcodes.i32_const:
123
+ vals.push(read_signedLEB128(i.slice(1)).toString());
124
+ break;
125
+
126
+ case Opcodes.f64_const:
127
+ vals.push(read_ieee754_binary64(i.slice(1)).toExponential());
128
+ break;
129
+
130
+ case Opcodes.local_get:
131
+ vals.push(`${invLocals[i[1]]}`);
132
+ break;
133
+
134
+ case Opcodes.local_set:
135
+ line(`${invLocals[i[1]]} = ${vals.pop()}`);
136
+ break;
137
+
138
+ case Opcodes.local_tee:
139
+ vals.push(`${invLocals[i[1]]} = ${vals.pop()}`);
140
+ break;
141
+
142
+ case Opcodes.f64_trunc:
143
+ // vals.push(`trunc(${vals.pop()})`);
144
+ vals.push(`(int)(${vals.pop()})`); // this is ~10x faster with clang. what the fuck.
145
+ break;
146
+
147
+ case Opcodes.return:
148
+ line(`return${returns ? ` ${vals.pop()}` : ''}`);
149
+ break;
150
+
151
+ case Opcodes.if:
152
+ let cond = vals.pop();
153
+ if (!lastCond) {
154
+ if (cond.startsWith('(long)')) cond = `${cond.slice(6)} == 1e+0`;
155
+ else cond += ' == 1';
156
+ }
157
+
158
+ ifTernary = i[1] !== Blocktype.void;
159
+ if (ifTernary) {
160
+ ifTernary = cond;
161
+ break;
162
+ }
163
+
164
+ if (beginLoop) {
165
+ beginLoop = false;
166
+ line(`while (${cond}) {`, false);
167
+
168
+ depth++;
169
+ endNeedsCurly.push(true);
170
+ ignoreEnd.push(false, true);
171
+ break;
172
+ }
173
+
174
+ line(`if (${cond}) {`, false);
175
+
176
+ depth++;
177
+ endNeedsCurly.push(true);
178
+ ignoreEnd.push(false);
179
+ break;
180
+
181
+ case Opcodes.else:
182
+ if (ifTernary) break;
183
+
184
+ depth--;
185
+ line(`} else {`, false);
186
+ depth++;
187
+ break;
188
+
189
+ case Opcodes.loop:
190
+ // not doing properly, fake a while loop
191
+ beginLoop = true;
192
+ break;
193
+
194
+ case Opcodes.end:
195
+ if (ignoreEnd.pop()) break;
196
+
197
+ if (ifTernary) {
198
+ const b = vals.pop();
199
+ const a = vals.pop();
200
+ vals.push(`${ifTernary} ? ${a} : ${b}`);
201
+ break;
202
+ }
203
+
204
+ depth--;
205
+ if (endNeedsCurly.pop() === true) line('}', false);
206
+ break;
207
+
208
+ case Opcodes.call:
209
+ let func = funcs.find(x => x.index === i[1]);
210
+ if (!func) {
211
+ const importFunc = importFuncs[i[1]];
212
+ switch (importFunc.name) {
213
+ case 'print':
214
+ line(`printf("%f\\n", ${vals.pop()})`);
215
+ includes.set('stdio.h', true);
216
+ break;
217
+ }
218
+ break;
219
+ }
220
+
221
+ let args = [];
222
+ for (let j = 0; j < func.params.length; j++) args.unshift(vals.pop());
223
+
224
+ if (func.returns.length === 1) vals.push(`${sanitize(func.name)}(${args.join(', ')})`)
225
+ else line(`${sanitize(func.name)}(${args.join(', ')})`);
226
+
227
+ break;
228
+
229
+ case Opcodes.drop:
230
+ line(vals.pop());
231
+ break;
232
+
233
+ case Opcodes.br:
234
+ // ignore
235
+ // reset "stack"
236
+ vals = [];
237
+ break;
238
+
239
+ default:
240
+ log('2c', `unimplemented op: ${invOpcodes[i[0]]}`);
241
+ // todo(`unimplemented op: ${invOpcodes[i[0]]}`);
242
+ }
243
+
244
+ lastCond = false;
245
+ }
246
+
247
+ if (vals.length === 1 && returns) {
248
+ line(`return ${vals.pop()}`);
249
+ }
250
+
251
+ out += '}\n\n';
252
+ }
253
+
254
+ out = [...includes.keys()].map(x => `#include <${x}>`).join('\n') + '\n\n' + out;
255
+
256
+ return out;
257
+ };
@@ -568,7 +568,6 @@ export const BuiltinFuncs = function() {
568
568
  params: [ Valtype.i32 ],
569
569
  locals: [],
570
570
  returns: [ Valtype.v128 ],
571
- memory: true,
572
571
  wasm: [
573
572
  [ Opcodes.local_get, 0 ],
574
573
  [ ...Opcodes.v128_load, 0, 0 ]