CanadaHonk / porffor
- четверг, 8 августа 2024 г. в 00:00:02
A from-scratch experimental AOT JS engine, written in JS
A from-scratch experimental AOT optimizing JS/TS -> Wasm/C engine/compiler/runtime in JS. Research project, not yet intended for serious use.
Porffor is a very unique JS engine, due many wildly different approaches. It is seriously limited, but what it can do, it does pretty well. Key differences:
Porffor is primarily built from scratch, the only thing that is not is the parser (using 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.
Expect nothing to work! Only very limited JS is currently supported. See files in bench
for examples.
npm install -g porffor@latest
. It's that easy (hopefully) :)
porf
. Just run it with no script file argument.
porf path/to/script.js
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.
Warning
Compiling to native binaries uses 2c, Porffor's own Wasm -> C compiler, which is experimental.
porf native path/to/script.js out(.exe)
. You can specify the compiler with --compiler=clang|gcc|zig
(clang
by default), and which optimization level to use with --cO=Ofast|O3|O2|O1|O0
(Ofast
by default). Output binaries are also stripped by default.
Warning
Compiling to C uses 2c, Porffor's own Wasm -> C compiler, which is experimental.
porf c path/to/script.js (out.c)
. When not including an output file, it will be printed to stdout instead.
Warning
Very experimental WIP feature!
porf profile path/to/script.js
Warning
Very experimental WIP feature!
porf debug path/to/script.js
Warning
Very experimental WIP feature!
porf debug-wasm path/to/script.js
--parser=acorn|@babel/parser|meriyah|hermes-parser
(default: acorn
) to set which parser to use--parse-types
to enable parsing type annotations/typescript. if -parser
is unset, changes default to @babel/parser
. does not type check--opt-types
to perform optimizations using type annotations as compiler hints. does not type check--valtype=i32|i64|f64
(default: f64
) to set valtype-O0
to disable opt-O1
(default) to enable basic opt (simplify insts, treeshake wasm imports)-O2
to enable advanced opt (inlining). unstable!-O3
to enable advanceder opt (precompute const math). unstable!eval()
/Function()
etc (since it is AOT)Asur is Porffor's own Wasm engine; it is an intentionally simple interpreter written in JS. It is very WIP. See its readme for more details.
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 for more details.
2c is Porffor's own Wasm -> C compiler, using generated Wasm bytecode and internal info to generate specific and efficient/fast C code. Little boilerplate/preluded code or required external files, just for CLI binaries (not like wasm2c very much).
See optimizations for opts implemented/supported.
These include some early (stage 1/0) and/or dead (last commit years ago) proposals but I think they are pretty neat, so.
Math.clamp
Proposal: Math.clamp
(stage 0 - last commit april 2023)Math
Extensions Proposal: Math.scale
, Math.radians
, Math.degrees
, Math.RAD_PER_DEG
, Math.DEG_PER_RAD
(stage 1 - last commit september 2020)Math.signbit
Proposal: Math.signbit
(stage 1 - last commit february 2020)return
let
/const
/var
)+-/*%
)&|
)==
, !=
, etc)>
, <
, >=
, etc)!
, +
, -
)&&
, ||
)let a, b = 0
)let [a, ...b] = foo
)var
/none in top scope)if
and if ... else
const foo = function() { ... }
)undefined
/null
a++
, ++b
, c--
, etc)for
loops (for (let i = 0; i < N; i++)
, etc)console.log
while
loopsbreak
and continue
+=
, -=
, >>=
, &&=
, etc)cond ? a : b
)return
)throw
(literals only, hack for new Error
)try { ... } catch { ... }
(no error given)f(a, b); f(0); f(1, 2, 3);
)typeof
ReferenceError
), not functions (TypeError
)[]
(eg let arr = [ 1, 2, 3 ]
)arr[ind]
(eg arr[0]
)'hello world'
)str[ind]
(eg str[0]
)+
) (eg 'a' + 'b'
)!'' == true
)'a' == 'a'
, 'a' != 'b'
)??
)for...of
(arrays and strings)for...in
arr[0] = 2
, arr[0] += 2
, etc)Array(5)
, new Array(1, 2, 3)
)foo: while (...)
)do...while
loops(foo = 'bar') => { ... }
)(...foo) => { ... }
)this
new Foo
)class A {}
)await promise
)NaN
and Infinity
isNaN()
and isFinite()
Number
(MAX_VALUE
, MIN_VALUE
, MAX_SAFE_INTEGER
, MIN_SAFE_INTEGER
, POSITIVE_INFINITY
, NEGATIVE_INFINITY
, EPSILON
, NaN
, isNaN
, isFinite
, isInteger
, isSafeInteger
)Math
funcs (sqrt
, abs
, floor
, sign
, round
, trunc
, clz32
, fround
, random
, exp
, log
, log2
, log10
, pow
, expm1
, log1p
, sqrt
, cbrt
, hypot
, sin
, cos
, tan
, sinh
, cosh
, tanh
, asinh
, acosh
, atanh
, asin
, acos
, atan
, atan2
)globalThis
supportBoolean
and Number
eval
for literalsMath.random()
using self-made xorshift128+ PRNGperformance
(now()
, timeOrigin
)Array.prototype
(at
, push
, pop
, shift
, fill
, slice
, indexOf
, lastIndexOf
, includes
, with
, reverse
, toReversed
, forEach
, filter
, map
, find
, findLast
, findIndex
, findLastIndex
, every
, some
, reduce
, reduceRight
, join
, toString
)Array
(of
, isArray
)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
, trim
)crypto
(randomUUID
)escape
btoa
Number.prototype
(toString
, toFixed
, toExponential
)parseInt
Date
Uint8Array
, Int32Array
, etc)Promise
asm`...
` "macro"Porffor uses a unique versioning system, here's an example: 0.18.2+2aa3f0589
. Let's break it down:
0
- major, always 0
as Porffor is not ready yet18
- minor, total Test262 pass percentage (floored to nearest int)2
- micro, build number for that minor (incremented each publish/git push)2aa3f0589
- commit hashFor the features it supports most of the time, Porffor is blazingly fast compared to most interpreters and common engines running without JIT. For those with JIT, it is usually slower by default, but can catch up with compiler arguments and typed input, even more so when compiling to native binaries.
Mostly for reducing size. I 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.
--tail-call
)local.set
, local.get
-> local.tee
i32.const 0
, i32.eq
-> i32.eqz
i64.extend_i32_s
, i32.wrap_i64
-> ``f64.convert_i32_u
, i32.trunc_sat_f64_s
-> ``return
, end
-> end
f64.const
, i32.trunc_sat_f64_s ->
i32.const`)br
s inside)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 >14% (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.
compiler
: contains the compiler itself
2c.js
: porffor's custom wasm-to-c engineallocators.js
: static and dynamic allocators to power various language featuresassemble.js
: assembles wasm ops and metadata into a wasm module/filebuiltins.js
: all manually written built-ins of the engine (spec, custom. vars, funcs)builtins_object.js
: all the various built-in objects (think String
, globalThis
, etc.)builtins_precompiled.js
: dynamically generated builtins from the builtins/
foldercodegen.js
: code (wasm) generation, ast -> wasm. The bulk of the effortcyclone.js
: wasm partial constant evaluator (it is fast and dangerous hence "cyclone")decompile.js
: basic wasm decompiler for debug infodiagram.js
: produces Mermaid graphsembedding.js
: utils for embedding constsencoding.js
: utils for encoding things as bytes as wasm expectsexpression.js
: mapping most operators to an opcode (advanced are as built-ins eg f64_%
)havoc.js
: wasm rewrite library (it wreaks havoc upon wasm bytecode hence "havoc")index.js
: doing all the compiler steps, takes code in, wasm outopt.js
: self-made wasm bytecode optimizerparse.js
: parser simply wrapping acornpgo.js
: a profile guided optimizerprecompile.js
: the tool to generate builtins_precompied.js
prefs.js
: a utility to read command line argumentsprototype.js
: some builtin prototype functionstypes.js
: definitions for each of the builtin typeswasmSpec.js
: "enums"/info from wasm specwrap.js
: wrapper for compiler which instantiates and produces nice exportsrunner
: contains utils for running JS with the compiler
index.js
: the main file, you probably want to use thisinfo.js
: runs with extra info printedrepl.js
: basic repl (uses node:repl
)rhemyn
: contains Rhemyn - our regex engine (used by Porffor)
compile.js
: compiles regex ast into wasm bytecodeparse.js
: own regex parsertest
: contains many test files for majority of supported features
test262
: test262 runner and utils
Currently, Porffor is seriously limited in features and functionality, however it has some key benefits:
No particular order and no guarentees, just what could happen soon™
escape()
optimizationThere 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).
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.
purple
in Welsh is porffor
. Why purple?
Yes!
No. they are not alike at all internally and have very different goals/ideals: