more
This commit is contained in:
dopeuni444
2025-07-31 12:23:33 +04:00
parent 20b46678b7
commit b5a22951ae
3401 changed files with 331100 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Mauro Bringolf
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,42 @@
export default function parse(input) {
input = input.toUpperCase();
var splitIndex = input.indexOf("P");
var mantissa, exponent;
if (splitIndex !== -1) {
mantissa = input.substring(0, splitIndex);
exponent = parseInt(input.substring(splitIndex + 1));
} else {
mantissa = input;
exponent = 0;
}
var dotIndex = mantissa.indexOf(".");
if (dotIndex !== -1) {
var integerPart = parseInt(mantissa.substring(0, dotIndex), 16);
var sign = Math.sign(integerPart);
integerPart = sign * integerPart;
var fractionLength = mantissa.length - dotIndex - 1;
var fractionalPart = parseInt(mantissa.substring(dotIndex + 1), 16);
var fraction = fractionLength > 0 ? fractionalPart / Math.pow(16, fractionLength) : 0;
if (sign === 0) {
if (fraction === 0) {
mantissa = sign;
} else {
if (Object.is(sign, -0)) {
mantissa = -fraction;
} else {
mantissa = fraction;
}
}
} else {
mantissa = sign * (integerPart + fraction);
}
} else {
mantissa = parseInt(mantissa, 16);
}
return mantissa * (splitIndex !== -1 ? Math.pow(2, exponent) : 1);
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,63 @@
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
export var RuntimeError = /*#__PURE__*/function (_Error) {
_inherits(RuntimeError, _Error);
var _super = _createSuper(RuntimeError);
function RuntimeError() {
_classCallCheck(this, RuntimeError);
return _super.apply(this, arguments);
}
return RuntimeError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
export var CompileError = /*#__PURE__*/function (_Error2) {
_inherits(CompileError, _Error2);
var _super2 = _createSuper(CompileError);
function CompileError() {
_classCallCheck(this, CompileError);
return _super2.apply(this, arguments);
}
return CompileError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
export var LinkError = /*#__PURE__*/function (_Error3) {
_inherits(LinkError, _Error3);
var _super3 = _createSuper(LinkError);
function LinkError() {
_classCallCheck(this, LinkError);
return _super3.apply(this, arguments);
}
return LinkError;
}( /*#__PURE__*/_wrapNativeSuper(Error));

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,65 @@
// this are dev dependencies
var diff = require("jest-diff");
var _require = require("jest-diff/build/constants"),
NO_DIFF_MESSAGE = _require.NO_DIFF_MESSAGE;
var _require2 = require("@webassemblyjs/wasm-parser"),
decode = _require2.decode;
var oldConsoleLog = console.log;
export function compareArrayBuffers(l, r) {
/**
* Decode left
*/
var bufferL = "";
console.log = function () {
for (var _len = arguments.length, texts = new Array(_len), _key = 0; _key < _len; _key++) {
texts[_key] = arguments[_key];
}
return bufferL += texts.join("") + "\n";
};
try {
decode(l, {
dump: true
});
} catch (e) {
console.error(bufferL);
console.error(e);
throw e;
}
/**
* Decode right
*/
var bufferR = "";
console.log = function () {
for (var _len2 = arguments.length, texts = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
texts[_key2] = arguments[_key2];
}
return bufferR += texts.join("") + "\n";
};
try {
decode(r, {
dump: true
});
} catch (e) {
console.error(bufferR);
console.error(e);
throw e;
}
console.log = oldConsoleLog;
var out = diff(bufferL, bufferR);
if (out !== null && out !== NO_DIFF_MESSAGE) {
throw new Error("\n" + out);
}
}

View File

@@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.compareArrayBuffers = compareArrayBuffers;
// this are dev dependencies
var diff = require("jest-diff");
var _require = require("jest-diff/build/constants"),
NO_DIFF_MESSAGE = _require.NO_DIFF_MESSAGE;
var _require2 = require("@webassemblyjs/wasm-parser"),
decode = _require2.decode;
var oldConsoleLog = console.log;
function compareArrayBuffers(l, r) {
/**
* Decode left
*/
var bufferL = "";
console.log = function () {
for (var _len = arguments.length, texts = new Array(_len), _key = 0; _key < _len; _key++) {
texts[_key] = arguments[_key];
}
return bufferL += texts.join("") + "\n";
};
try {
decode(l, {
dump: true
});
} catch (e) {
console.error(bufferL);
console.error(e);
throw e;
}
/**
* Decode right
*/
var bufferR = "";
console.log = function () {
for (var _len2 = arguments.length, texts = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
texts[_key2] = arguments[_key2];
}
return bufferR += texts.join("") + "\n";
};
try {
decode(r, {
dump: true
});
} catch (e) {
console.error(bufferR);
console.error(e);
throw e;
}
console.log = oldConsoleLog;
var out = diff(bufferL, bufferR);
if (out !== null && out !== NO_DIFF_MESSAGE) {
throw new Error("\n" + out);
}
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,92 @@
import Long from "@xtuc/long";
import parseHexFloat from "@webassemblyjs/floating-point-hex-parser";
import { CompileError } from "@webassemblyjs/helper-api-error";
export function parse32F(sourceString) {
if (isHexLiteral(sourceString)) {
return parseHexFloat(sourceString);
}
if (isInfLiteral(sourceString)) {
return sourceString[0] === "-" ? -1 : 1;
}
if (isNanLiteral(sourceString)) {
return (sourceString[0] === "-" ? -1 : 1) * (sourceString.includes(":") ? parseInt(sourceString.substring(sourceString.indexOf(":") + 1), 16) : 0x400000);
}
return parseFloat(sourceString);
}
export function parse64F(sourceString) {
if (isHexLiteral(sourceString)) {
return parseHexFloat(sourceString);
}
if (isInfLiteral(sourceString)) {
return sourceString[0] === "-" ? -1 : 1;
}
if (isNanLiteral(sourceString)) {
return (sourceString[0] === "-" ? -1 : 1) * (sourceString.includes(":") ? parseInt(sourceString.substring(sourceString.indexOf(":") + 1), 16) : 0x8000000000000);
}
if (isHexLiteral(sourceString)) {
return parseHexFloat(sourceString);
}
return parseFloat(sourceString);
}
export function parse32I(sourceString) {
var value = 0;
if (isHexLiteral(sourceString)) {
value = ~~parseInt(sourceString, 16);
} else if (isDecimalExponentLiteral(sourceString)) {
throw new Error("This number literal format is yet to be implemented.");
} else {
value = parseInt(sourceString, 10);
}
return value;
}
export function parseU32(sourceString) {
var value = parse32I(sourceString);
if (value < 0) {
throw new CompileError("Illegal value for u32: " + sourceString);
}
return value;
}
export function parse64I(sourceString) {
// $FlowIgnore
var _long;
if (isHexLiteral(sourceString)) {
_long = Long.fromString(sourceString, false, 16);
} else if (isDecimalExponentLiteral(sourceString)) {
throw new Error("This number literal format is yet to be implemented.");
} else {
_long = Long.fromString(sourceString);
}
return {
high: _long.high,
low: _long.low
};
}
var NAN_WORD = /^\+?-?nan/;
var INF_WORD = /^\+?-?inf/;
export function isInfLiteral(sourceString) {
return INF_WORD.test(sourceString.toLowerCase());
}
export function isNanLiteral(sourceString) {
return NAN_WORD.test(sourceString.toLowerCase());
}
function isDecimalExponentLiteral(sourceString) {
return !isHexLiteral(sourceString) && sourceString.toUpperCase().includes("E");
}
function isHexLiteral(sourceString) {
return sourceString.substring(0, 2).toUpperCase() === "0X" || sourceString.substring(0, 3).toUpperCase() === "-0X";
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,415 @@
var illegalop = "illegal";
var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d];
var moduleVersion = [0x01, 0x00, 0x00, 0x00];
function invertMap(obj) {
var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) {
return k;
};
var result = {};
var keys = Object.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[keyModifierFn(obj[keys[i]])] = keys[i];
}
return result;
}
function createSymbolObject(name
/*: string */
, object
/*: string */
)
/*: Symbol*/
{
var numberOfArgs
/*: number*/
= arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
return {
name: name,
object: object,
numberOfArgs: numberOfArgs
};
}
function createSymbol(name
/*: string */
)
/*: Symbol*/
{
var numberOfArgs
/*: number*/
= arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return {
name: name,
numberOfArgs: numberOfArgs
};
}
var types = {
func: 0x60,
result: 0x40
};
var exportTypes = {
0x00: "Func",
0x01: "Table",
0x02: "Memory",
0x03: "Global"
};
var exportTypesByName = invertMap(exportTypes);
var valtypes = {
// numtype
0x7f: "i32",
0x7e: "i64",
0x7d: "f32",
0x7c: "f64",
// vectype
0x7b: "v128",
// reftype
0x70: "anyfunc",
0x6f: "externref"
};
var valtypesByString = invertMap(valtypes);
var tableTypes = {
0x70: "anyfunc",
0x6f: "externref"
};
var blockTypes = Object.assign({}, valtypes, {
// https://webassembly.github.io/spec/core/binary/types.html#binary-blocktype
0x40: null,
// https://webassembly.github.io/spec/core/binary/types.html#binary-valtype
0x7f: "i32",
0x7e: "i64",
0x7d: "f32",
0x7c: "f64"
});
var globalTypes = {
0x00: "const",
0x01: "var"
};
var globalTypesByString = invertMap(globalTypes);
var importTypes = {
0x00: "func",
0x01: "table",
0x02: "memory",
0x03: "global"
};
var sections = {
custom: 0,
type: 1,
"import": 2,
func: 3,
table: 4,
memory: 5,
global: 6,
"export": 7,
start: 8,
element: 9,
code: 10,
data: 11
};
var symbolsByByte = {
0x00: createSymbol("unreachable"),
0x01: createSymbol("nop"),
0x02: createSymbol("block"),
0x03: createSymbol("loop"),
0x04: createSymbol("if"),
0x05: createSymbol("else"),
0x06: illegalop,
0x07: illegalop,
0x08: illegalop,
0x09: illegalop,
0x0a: illegalop,
0x0b: createSymbol("end"),
0x0c: createSymbol("br", 1),
0x0d: createSymbol("br_if", 1),
0x0e: createSymbol("br_table"),
0x0f: createSymbol("return"),
0x10: createSymbol("call", 1),
0x11: createSymbol("call_indirect", 2),
0x12: illegalop,
0x13: illegalop,
0x14: illegalop,
0x15: illegalop,
0x16: illegalop,
0x17: illegalop,
0x18: illegalop,
0x19: illegalop,
0x1a: createSymbol("drop"),
0x1b: createSymbol("select"),
0x1c: illegalop,
0x1d: illegalop,
0x1e: illegalop,
0x1f: illegalop,
0x20: createSymbol("get_local", 1),
0x21: createSymbol("set_local", 1),
0x22: createSymbol("tee_local", 1),
0x23: createSymbol("get_global", 1),
0x24: createSymbol("set_global", 1),
0x25: createSymbol("table.get", 1),
0x26: createSymbol("table.set", 1),
0x27: illegalop,
0x28: createSymbolObject("load", "u32", 1),
0x29: createSymbolObject("load", "u64", 1),
0x2a: createSymbolObject("load", "f32", 1),
0x2b: createSymbolObject("load", "f64", 1),
0x2c: createSymbolObject("load8_s", "u32", 1),
0x2d: createSymbolObject("load8_u", "u32", 1),
0x2e: createSymbolObject("load16_s", "u32", 1),
0x2f: createSymbolObject("load16_u", "u32", 1),
0x30: createSymbolObject("load8_s", "u64", 1),
0x31: createSymbolObject("load8_u", "u64", 1),
0x32: createSymbolObject("load16_s", "u64", 1),
0x33: createSymbolObject("load16_u", "u64", 1),
0x34: createSymbolObject("load32_s", "u64", 1),
0x35: createSymbolObject("load32_u", "u64", 1),
0x36: createSymbolObject("store", "u32", 1),
0x37: createSymbolObject("store", "u64", 1),
0x38: createSymbolObject("store", "f32", 1),
0x39: createSymbolObject("store", "f64", 1),
0x3a: createSymbolObject("store8", "u32", 1),
0x3b: createSymbolObject("store16", "u32", 1),
0x3c: createSymbolObject("store8", "u64", 1),
0x3d: createSymbolObject("store16", "u64", 1),
0x3e: createSymbolObject("store32", "u64", 1),
0x3f: createSymbolObject("current_memory"),
0x40: createSymbolObject("grow_memory"),
0x41: createSymbolObject("const", "i32", 1),
0x42: createSymbolObject("const", "i64", 1),
0x43: createSymbolObject("const", "f32", 1),
0x44: createSymbolObject("const", "f64", 1),
0x45: createSymbolObject("eqz", "i32"),
0x46: createSymbolObject("eq", "i32"),
0x47: createSymbolObject("ne", "i32"),
0x48: createSymbolObject("lt_s", "i32"),
0x49: createSymbolObject("lt_u", "i32"),
0x4a: createSymbolObject("gt_s", "i32"),
0x4b: createSymbolObject("gt_u", "i32"),
0x4c: createSymbolObject("le_s", "i32"),
0x4d: createSymbolObject("le_u", "i32"),
0x4e: createSymbolObject("ge_s", "i32"),
0x4f: createSymbolObject("ge_u", "i32"),
0x50: createSymbolObject("eqz", "i64"),
0x51: createSymbolObject("eq", "i64"),
0x52: createSymbolObject("ne", "i64"),
0x53: createSymbolObject("lt_s", "i64"),
0x54: createSymbolObject("lt_u", "i64"),
0x55: createSymbolObject("gt_s", "i64"),
0x56: createSymbolObject("gt_u", "i64"),
0x57: createSymbolObject("le_s", "i64"),
0x58: createSymbolObject("le_u", "i64"),
0x59: createSymbolObject("ge_s", "i64"),
0x5a: createSymbolObject("ge_u", "i64"),
0x5b: createSymbolObject("eq", "f32"),
0x5c: createSymbolObject("ne", "f32"),
0x5d: createSymbolObject("lt", "f32"),
0x5e: createSymbolObject("gt", "f32"),
0x5f: createSymbolObject("le", "f32"),
0x60: createSymbolObject("ge", "f32"),
0x61: createSymbolObject("eq", "f64"),
0x62: createSymbolObject("ne", "f64"),
0x63: createSymbolObject("lt", "f64"),
0x64: createSymbolObject("gt", "f64"),
0x65: createSymbolObject("le", "f64"),
0x66: createSymbolObject("ge", "f64"),
0x67: createSymbolObject("clz", "i32"),
0x68: createSymbolObject("ctz", "i32"),
0x69: createSymbolObject("popcnt", "i32"),
0x6a: createSymbolObject("add", "i32"),
0x6b: createSymbolObject("sub", "i32"),
0x6c: createSymbolObject("mul", "i32"),
0x6d: createSymbolObject("div_s", "i32"),
0x6e: createSymbolObject("div_u", "i32"),
0x6f: createSymbolObject("rem_s", "i32"),
0x70: createSymbolObject("rem_u", "i32"),
0x71: createSymbolObject("and", "i32"),
0x72: createSymbolObject("or", "i32"),
0x73: createSymbolObject("xor", "i32"),
0x74: createSymbolObject("shl", "i32"),
0x75: createSymbolObject("shr_s", "i32"),
0x76: createSymbolObject("shr_u", "i32"),
0x77: createSymbolObject("rotl", "i32"),
0x78: createSymbolObject("rotr", "i32"),
0x79: createSymbolObject("clz", "i64"),
0x7a: createSymbolObject("ctz", "i64"),
0x7b: createSymbolObject("popcnt", "i64"),
0x7c: createSymbolObject("add", "i64"),
0x7d: createSymbolObject("sub", "i64"),
0x7e: createSymbolObject("mul", "i64"),
0x7f: createSymbolObject("div_s", "i64"),
0x80: createSymbolObject("div_u", "i64"),
0x81: createSymbolObject("rem_s", "i64"),
0x82: createSymbolObject("rem_u", "i64"),
0x83: createSymbolObject("and", "i64"),
0x84: createSymbolObject("or", "i64"),
0x85: createSymbolObject("xor", "i64"),
0x86: createSymbolObject("shl", "i64"),
0x87: createSymbolObject("shr_s", "i64"),
0x88: createSymbolObject("shr_u", "i64"),
0x89: createSymbolObject("rotl", "i64"),
0x8a: createSymbolObject("rotr", "i64"),
0x8b: createSymbolObject("abs", "f32"),
0x8c: createSymbolObject("neg", "f32"),
0x8d: createSymbolObject("ceil", "f32"),
0x8e: createSymbolObject("floor", "f32"),
0x8f: createSymbolObject("trunc", "f32"),
0x90: createSymbolObject("nearest", "f32"),
0x91: createSymbolObject("sqrt", "f32"),
0x92: createSymbolObject("add", "f32"),
0x93: createSymbolObject("sub", "f32"),
0x94: createSymbolObject("mul", "f32"),
0x95: createSymbolObject("div", "f32"),
0x96: createSymbolObject("min", "f32"),
0x97: createSymbolObject("max", "f32"),
0x98: createSymbolObject("copysign", "f32"),
0x99: createSymbolObject("abs", "f64"),
0x9a: createSymbolObject("neg", "f64"),
0x9b: createSymbolObject("ceil", "f64"),
0x9c: createSymbolObject("floor", "f64"),
0x9d: createSymbolObject("trunc", "f64"),
0x9e: createSymbolObject("nearest", "f64"),
0x9f: createSymbolObject("sqrt", "f64"),
0xa0: createSymbolObject("add", "f64"),
0xa1: createSymbolObject("sub", "f64"),
0xa2: createSymbolObject("mul", "f64"),
0xa3: createSymbolObject("div", "f64"),
0xa4: createSymbolObject("min", "f64"),
0xa5: createSymbolObject("max", "f64"),
0xa6: createSymbolObject("copysign", "f64"),
0xa7: createSymbolObject("wrap/i64", "i32"),
0xa8: createSymbolObject("trunc_s/f32", "i32"),
0xa9: createSymbolObject("trunc_u/f32", "i32"),
0xaa: createSymbolObject("trunc_s/f64", "i32"),
0xab: createSymbolObject("trunc_u/f64", "i32"),
0xac: createSymbolObject("extend_s/i32", "i64"),
0xad: createSymbolObject("extend_u/i32", "i64"),
0xae: createSymbolObject("trunc_s/f32", "i64"),
0xaf: createSymbolObject("trunc_u/f32", "i64"),
0xb0: createSymbolObject("trunc_s/f64", "i64"),
0xb1: createSymbolObject("trunc_u/f64", "i64"),
0xb2: createSymbolObject("convert_s/i32", "f32"),
0xb3: createSymbolObject("convert_u/i32", "f32"),
0xb4: createSymbolObject("convert_s/i64", "f32"),
0xb5: createSymbolObject("convert_u/i64", "f32"),
0xb6: createSymbolObject("demote/f64", "f32"),
0xb7: createSymbolObject("convert_s/i32", "f64"),
0xb8: createSymbolObject("convert_u/i32", "f64"),
0xb9: createSymbolObject("convert_s/i64", "f64"),
0xba: createSymbolObject("convert_u/i64", "f64"),
0xbb: createSymbolObject("promote/f32", "f64"),
0xbc: createSymbolObject("reinterpret/f32", "i32"),
0xbd: createSymbolObject("reinterpret/f64", "i64"),
0xbe: createSymbolObject("reinterpret/i32", "f32"),
0xbf: createSymbolObject("reinterpret/i64", "f64"),
0xc0: createSymbolObject("extend8_s", "i32"),
0xc1: createSymbolObject("extend16_s", "i32"),
0xc2: createSymbolObject("extend8_s", "i64"),
0xc3: createSymbolObject("extend16_s", "i64"),
0xc4: createSymbolObject("extend32_s", "i64"),
0xd0: createSymbol("ref.null"),
0xd1: createSymbol("ref.is_null"),
0xd2: createSymbol("ref.func", 1),
0xfc0a: createSymbol("memory.copy"),
0xfc0b: createSymbol("memory.fill"),
// Table instructions
// https://webassembly.github.io/spec/core/binary/instructions.html#table-instructions
0xfc0c: createSymbol("table.init", 2),
0xfc0d: createSymbol("elem.drop", 1),
0xfc0e: createSymbol("table.copy", 2),
0xfc0f: createSymbol("table.grow", 1),
0xfc10: createSymbol("table.size", 1),
0xfc11: createSymbol("table.fill", 1),
// Atomic Memory Instructions
0xfe00: createSymbol("memory.atomic.notify", 1),
0xfe01: createSymbol("memory.atomic.wait32", 1),
0xfe02: createSymbol("memory.atomic.wait64", 1),
0xfe10: createSymbolObject("atomic.load", "i32", 1),
0xfe11: createSymbolObject("atomic.load", "i64", 1),
0xfe12: createSymbolObject("atomic.load8_u", "i32", 1),
0xfe13: createSymbolObject("atomic.load16_u", "i32", 1),
0xfe14: createSymbolObject("atomic.load8_u", "i64", 1),
0xfe15: createSymbolObject("atomic.load16_u", "i64", 1),
0xfe16: createSymbolObject("atomic.load32_u", "i64", 1),
0xfe17: createSymbolObject("atomic.store", "i32", 1),
0xfe18: createSymbolObject("atomic.store", "i64", 1),
0xfe19: createSymbolObject("atomic.store8_u", "i32", 1),
0xfe1a: createSymbolObject("atomic.store16_u", "i32", 1),
0xfe1b: createSymbolObject("atomic.store8_u", "i64", 1),
0xfe1c: createSymbolObject("atomic.store16_u", "i64", 1),
0xfe1d: createSymbolObject("atomic.store32_u", "i64", 1),
0xfe1e: createSymbolObject("atomic.rmw.add", "i32", 1),
0xfe1f: createSymbolObject("atomic.rmw.add", "i64", 1),
0xfe20: createSymbolObject("atomic.rmw8_u.add_u", "i32", 1),
0xfe21: createSymbolObject("atomic.rmw16_u.add_u", "i32", 1),
0xfe22: createSymbolObject("atomic.rmw8_u.add_u", "i64", 1),
0xfe23: createSymbolObject("atomic.rmw16_u.add_u", "i64", 1),
0xfe24: createSymbolObject("atomic.rmw32_u.add_u", "i64", 1),
0xfe25: createSymbolObject("atomic.rmw.sub", "i32", 1),
0xfe26: createSymbolObject("atomic.rmw.sub", "i64", 1),
0xfe27: createSymbolObject("atomic.rmw8_u.sub_u", "i32", 1),
0xfe28: createSymbolObject("atomic.rmw16_u.sub_u", "i32", 1),
0xfe29: createSymbolObject("atomic.rmw8_u.sub_u", "i64", 1),
0xfe2a: createSymbolObject("atomic.rmw16_u.sub_u", "i64", 1),
0xfe2b: createSymbolObject("atomic.rmw32_u.sub_u", "i64", 1),
0xfe2c: createSymbolObject("atomic.rmw.and", "i32", 1),
0xfe2d: createSymbolObject("atomic.rmw.and", "i64", 1),
0xfe2e: createSymbolObject("atomic.rmw8_u.and_u", "i32", 1),
0xfe2f: createSymbolObject("atomic.rmw16_u.and_u", "i32", 1),
0xfe30: createSymbolObject("atomic.rmw8_u.and_u", "i64", 1),
0xfe31: createSymbolObject("atomic.rmw16_u.and_u", "i64", 1),
0xfe32: createSymbolObject("atomic.rmw32_u.and_u", "i64", 1),
0xfe33: createSymbolObject("atomic.rmw.or", "i32", 1),
0xfe34: createSymbolObject("atomic.rmw.or", "i64", 1),
0xfe35: createSymbolObject("atomic.rmw8_u.or_u", "i32", 1),
0xfe36: createSymbolObject("atomic.rmw16_u.or_u", "i32", 1),
0xfe37: createSymbolObject("atomic.rmw8_u.or_u", "i64", 1),
0xfe38: createSymbolObject("atomic.rmw16_u.or_u", "i64", 1),
0xfe39: createSymbolObject("atomic.rmw32_u.or_u", "i64", 1),
0xfe3a: createSymbolObject("atomic.rmw.xor", "i32", 1),
0xfe3b: createSymbolObject("atomic.rmw.xor", "i64", 1),
0xfe3c: createSymbolObject("atomic.rmw8_u.xor_u", "i32", 1),
0xfe3d: createSymbolObject("atomic.rmw16_u.xor_u", "i32", 1),
0xfe3e: createSymbolObject("atomic.rmw8_u.xor_u", "i64", 1),
0xfe3f: createSymbolObject("atomic.rmw16_u.xor_u", "i64", 1),
0xfe40: createSymbolObject("atomic.rmw32_u.xor_u", "i64", 1),
0xfe41: createSymbolObject("atomic.rmw.xchg", "i32", 1),
0xfe42: createSymbolObject("atomic.rmw.xchg", "i64", 1),
0xfe43: createSymbolObject("atomic.rmw8_u.xchg_u", "i32", 1),
0xfe44: createSymbolObject("atomic.rmw16_u.xchg_u", "i32", 1),
0xfe45: createSymbolObject("atomic.rmw8_u.xchg_u", "i64", 1),
0xfe46: createSymbolObject("atomic.rmw16_u.xchg_u", "i64", 1),
0xfe47: createSymbolObject("atomic.rmw32_u.xchg_u", "i64", 1),
0xfe48: createSymbolObject("atomic.rmw.cmpxchg", "i32", 1),
0xfe49: createSymbolObject("atomic.rmw.cmpxchg", "i64", 1),
0xfe4a: createSymbolObject("atomic.rmw8_u.cmpxchg_u", "i32", 1),
0xfe4b: createSymbolObject("atomic.rmw16_u.cmpxchg_u", "i32", 1),
0xfe4c: createSymbolObject("atomic.rmw8_u.cmpxchg_u", "i64", 1),
0xfe4d: createSymbolObject("atomic.rmw16_u.cmpxchg_u", "i64", 1),
0xfe4e: createSymbolObject("atomic.rmw32_u.cmpxchg_u", "i64", 1)
};
var symbolsByName = invertMap(symbolsByByte, function (obj) {
if (typeof obj.object === "string") {
return "".concat(obj.object, ".").concat(obj.name);
}
return obj.name;
});
export default {
symbolsByByte: symbolsByByte,
sections: sections,
magicModuleHeader: magicModuleHeader,
moduleVersion: moduleVersion,
types: types,
valtypes: valtypes,
exportTypes: exportTypes,
blockTypes: blockTypes,
tableTypes: tableTypes,
globalTypes: globalTypes,
importTypes: importTypes,
valtypesByString: valtypesByString,
globalTypesByString: globalTypesByString,
exportTypesByName: exportTypesByName,
symbolsByName: symbolsByName
};
export { getSectionForNode } from "./section";

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,107 @@
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
import { encodeNode } from "@webassemblyjs/wasm-gen";
import { overrideBytesInBuffer } from "@webassemblyjs/helper-buffer";
import constants from "@webassemblyjs/helper-wasm-bytecode";
import * as t from "@webassemblyjs/ast";
function findLastSection(ast, forSection) {
var targetSectionId = constants.sections[forSection]; // $FlowIgnore: metadata can not be empty
var moduleSections = ast.body[0].metadata.sections;
var lastSection;
var lastId = 0;
for (var i = 0, len = moduleSections.length; i < len; i++) {
var section = moduleSections[i]; // Ignore custom section since they can actually occur everywhere
if (section.section === "custom") {
continue;
}
var sectionId = constants.sections[section.section];
if (targetSectionId > lastId && targetSectionId < sectionId) {
return lastSection;
}
lastId = sectionId;
lastSection = section;
}
return lastSection;
}
export function createEmptySection(ast, uint8Buffer, section) {
// previous section after which we are going to insert our section
var lastSection = findLastSection(ast, section);
var start, end;
/**
* It's the first section
*/
if (lastSection == null || lastSection.section === "custom") {
start = 8
/* wasm header size */
;
end = start;
} else {
start = lastSection.startOffset + lastSection.size.value + 1;
end = start;
} // section id
start += 1;
var sizeStartLoc = {
line: -1,
column: start
};
var sizeEndLoc = {
line: -1,
column: start + 1
}; // 1 byte for the empty vector
var size = t.withLoc(t.numberLiteralFromRaw(1), sizeEndLoc, sizeStartLoc);
var vectorOfSizeStartLoc = {
line: -1,
column: sizeEndLoc.column
};
var vectorOfSizeEndLoc = {
line: -1,
column: sizeEndLoc.column + 1
};
var vectorOfSize = t.withLoc(t.numberLiteralFromRaw(0), vectorOfSizeEndLoc, vectorOfSizeStartLoc);
var sectionMetadata = t.sectionMetadata(section, start, size, vectorOfSize);
var sectionBytes = encodeNode(sectionMetadata);
uint8Buffer = overrideBytesInBuffer(uint8Buffer, start - 1, end, sectionBytes); // Add section into the AST for later lookups
if (_typeof(ast.body[0].metadata) === "object") {
// $FlowIgnore: metadata can not be empty
ast.body[0].metadata.sections.push(sectionMetadata);
t.sortSectionMetadata(ast.body[0]);
}
/**
* Update AST
*/
// Once we hit our section every that is after needs to be shifted by the delta
var deltaBytes = +sectionBytes.length;
var encounteredSection = false;
t.traverse(ast, {
SectionMetadata: function SectionMetadata(path) {
if (path.node.section === section) {
encounteredSection = true;
return;
}
if (encounteredSection === true) {
t.shiftSection(ast, path.node, deltaBytes);
}
}
});
return {
uint8Buffer: uint8Buffer,
sectionMetadata: sectionMetadata
};
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,33 @@
import { write, read } from "@xtuc/ieee754";
/**
* According to https://webassembly.github.io/spec/binary/values.html#binary-float
* n = 32/8
*/
export var NUMBER_OF_BYTE_F32 = 4;
/**
* According to https://webassembly.github.io/spec/binary/values.html#binary-float
* n = 64/8
*/
export var NUMBER_OF_BYTE_F64 = 8;
export var SINGLE_PRECISION_MANTISSA = 23;
export var DOUBLE_PRECISION_MANTISSA = 52;
export function encodeF32(v) {
var buffer = [];
write(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
return buffer;
}
export function encodeF64(v) {
var buffer = [];
write(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
return buffer;
}
export function decodeF32(bytes) {
var buffer = new Uint8Array(bytes);
return read(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
}
export function decodeF64(bytes) {
var buffer = new Uint8Array(bytes);
return read(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
}

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.encodeF32 = encodeF32;
exports.encodeF64 = encodeF64;
exports.decodeF32 = decodeF32;
exports.decodeF64 = decodeF64;
exports.DOUBLE_PRECISION_MANTISSA = exports.SINGLE_PRECISION_MANTISSA = exports.NUMBER_OF_BYTE_F64 = exports.NUMBER_OF_BYTE_F32 = void 0;
var _ieee = require("@xtuc/ieee754");
/**
* According to https://webassembly.github.io/spec/binary/values.html#binary-float
* n = 32/8
*/
var NUMBER_OF_BYTE_F32 = 4;
/**
* According to https://webassembly.github.io/spec/binary/values.html#binary-float
* n = 64/8
*/
exports.NUMBER_OF_BYTE_F32 = NUMBER_OF_BYTE_F32;
var NUMBER_OF_BYTE_F64 = 8;
exports.NUMBER_OF_BYTE_F64 = NUMBER_OF_BYTE_F64;
var SINGLE_PRECISION_MANTISSA = 23;
exports.SINGLE_PRECISION_MANTISSA = SINGLE_PRECISION_MANTISSA;
var DOUBLE_PRECISION_MANTISSA = 52;
exports.DOUBLE_PRECISION_MANTISSA = DOUBLE_PRECISION_MANTISSA;
function encodeF32(v) {
var buffer = [];
(0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
return buffer;
}
function encodeF64(v) {
var buffer = [];
(0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
return buffer;
}
function decodeF32(bytes) {
var buffer = new Uint8Array(bytes);
return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
}
function decodeF64(bytes) {
var buffer = new Uint8Array(bytes);
return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
}

View File

@@ -0,0 +1,145 @@
// Copyright 2012 The Obvious Corporation.
/*
* bits: Bitwise buffer utilities. The utilities here treat a buffer
* as a little-endian bigint, so the lowest-order bit is bit #0 of
* `buffer[0]`, and the highest-order bit is bit #7 of
* `buffer[buffer.length - 1]`.
*/
/*
* Modules used
*/
"use strict";
/*
* Exported bindings
*/
/**
* Extracts the given number of bits from the buffer at the indicated
* index, returning a simple number as the result. If bits are requested
* that aren't covered by the buffer, the `defaultBit` is used as their
* value.
*
* The `bitLength` must be no more than 32. The `defaultBit` if not
* specified is taken to be `0`.
*/
export function extract(buffer, bitIndex, bitLength, defaultBit) {
if (bitLength < 0 || bitLength > 32) {
throw new Error("Bad value for bitLength.");
}
if (defaultBit === undefined) {
defaultBit = 0;
} else if (defaultBit !== 0 && defaultBit !== 1) {
throw new Error("Bad value for defaultBit.");
}
var defaultByte = defaultBit * 0xff;
var result = 0; // All starts are inclusive. The {endByte, endBit} pair is exclusive, but
// if endBit !== 0, then endByte is inclusive.
var lastBit = bitIndex + bitLength;
var startByte = Math.floor(bitIndex / 8);
var startBit = bitIndex % 8;
var endByte = Math.floor(lastBit / 8);
var endBit = lastBit % 8;
if (endBit !== 0) {
// `(1 << endBit) - 1` is the mask of all bits up to but not including
// the endBit.
result = get(endByte) & (1 << endBit) - 1;
}
while (endByte > startByte) {
endByte--;
result = result << 8 | get(endByte);
}
result >>>= startBit;
return result;
function get(index) {
var result = buffer[index];
return result === undefined ? defaultByte : result;
}
}
/**
* Injects the given bits into the given buffer at the given index. Any
* bits in the value beyond the length to set are ignored.
*/
export function inject(buffer, bitIndex, bitLength, value) {
if (bitLength < 0 || bitLength > 32) {
throw new Error("Bad value for bitLength.");
}
var lastByte = Math.floor((bitIndex + bitLength - 1) / 8);
if (bitIndex < 0 || lastByte >= buffer.length) {
throw new Error("Index out of range.");
} // Just keeping it simple, until / unless profiling shows that this
// is a problem.
var atByte = Math.floor(bitIndex / 8);
var atBit = bitIndex % 8;
while (bitLength > 0) {
if (value & 1) {
buffer[atByte] |= 1 << atBit;
} else {
buffer[atByte] &= ~(1 << atBit);
}
value >>= 1;
bitLength--;
atBit = (atBit + 1) % 8;
if (atBit === 0) {
atByte++;
}
}
}
/**
* Gets the sign bit of the given buffer.
*/
export function getSign(buffer) {
return buffer[buffer.length - 1] >>> 7;
}
/**
* Gets the zero-based bit number of the highest-order bit with the
* given value in the given buffer.
*
* If the buffer consists entirely of the other bit value, then this returns
* `-1`.
*/
export function highOrder(bit, buffer) {
var length = buffer.length;
var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte
while (length > 0 && buffer[length - 1] === fullyWrongByte) {
length--;
}
if (length === 0) {
// Degenerate case. The buffer consists entirely of ~bit.
return -1;
}
var byteToCheck = buffer[length - 1];
var result = length * 8 - 1;
for (var i = 7; i > 0; i--) {
if ((byteToCheck >> i & 1) === bit) {
break;
}
result--;
}
return result;
}

View File

@@ -0,0 +1,228 @@
// Copyright 2012 The Obvious Corporation.
/*
* bufs: Buffer utilities.
*/
/*
* Module variables
*/
/** Pool of buffers, where `bufPool[x].length === x`. */
var bufPool = [];
/** Maximum length of kept temporary buffers. */
var TEMP_BUF_MAXIMUM_LENGTH = 20;
/** Minimum exactly-representable 64-bit int. */
var MIN_EXACT_INT64 = -0x8000000000000000;
/** Maximum exactly-representable 64-bit int. */
var MAX_EXACT_INT64 = 0x7ffffffffffffc00;
/** Maximum exactly-representable 64-bit uint. */
var MAX_EXACT_UINT64 = 0xfffffffffffff800;
/**
* The int value consisting just of a 1 in bit #32 (that is, one more
* than the maximum 32-bit unsigned value).
*/
var BIT_32 = 0x100000000;
/**
* The int value consisting just of a 1 in bit #64 (that is, one more
* than the maximum 64-bit unsigned value).
*/
var BIT_64 = 0x10000000000000000;
/*
* Helper functions
*/
/**
* Masks off all but the lowest bit set of the given number.
*/
function lowestBit(num) {
return num & -num;
}
/**
* Gets whether trying to add the second number to the first is lossy
* (inexact). The first number is meant to be an accumulated result.
*/
function isLossyToAdd(accum, num) {
if (num === 0) {
return false;
}
var lowBit = lowestBit(num);
var added = accum + lowBit;
if (added === accum) {
return true;
}
if (added - lowBit !== accum) {
return true;
}
return false;
}
/*
* Exported functions
*/
/**
* Allocates a buffer of the given length, which is initialized
* with all zeroes. This returns a buffer from the pool if it is
* available, or a freshly-allocated buffer if not.
*/
export function alloc(length) {
var result = bufPool[length];
if (result) {
bufPool[length] = undefined;
} else {
result = new Uint8Array(length);
}
result.fill(0);
return result;
}
/**
* Releases a buffer back to the pool.
*/
export function free(buffer) {
var length = buffer.length;
if (length < TEMP_BUF_MAXIMUM_LENGTH) {
bufPool[length] = buffer;
}
}
/**
* Resizes a buffer, returning a new buffer. Returns the argument if
* the length wouldn't actually change. This function is only safe to
* use if the given buffer was allocated within this module (since
* otherwise the buffer might possibly be shared externally).
*/
export function resize(buffer, length) {
if (length === buffer.length) {
return buffer;
}
var newBuf = alloc(length);
for (var i = 0; i <= buffer.length; i++) {
newBuf[i] = buffer[i];
}
free(buffer);
return newBuf;
}
/**
* Reads an arbitrary signed int from a buffer.
*/
export function readInt(buffer) {
var length = buffer.length;
var positive = buffer[length - 1] < 0x80;
var result = positive ? 0 : -1;
var lossy = false; // Note: We can't use bit manipulation here, since that stops
// working if the result won't fit in a 32-bit int.
if (length < 7) {
// Common case which can't possibly be lossy (because the result has
// no more than 48 bits, and loss only happens with 54 or more).
for (var i = length - 1; i >= 0; i--) {
result = result * 0x100 + buffer[i];
}
} else {
for (var _i = length - 1; _i >= 0; _i--) {
var one = buffer[_i];
result *= 0x100;
if (isLossyToAdd(result, one)) {
lossy = true;
}
result += one;
}
}
return {
value: result,
lossy: lossy
};
}
/**
* Reads an arbitrary unsigned int from a buffer.
*/
export function readUInt(buffer) {
var length = buffer.length;
var result = 0;
var lossy = false; // Note: See above in re bit manipulation.
if (length < 7) {
// Common case which can't possibly be lossy (see above).
for (var i = length - 1; i >= 0; i--) {
result = result * 0x100 + buffer[i];
}
} else {
for (var _i2 = length - 1; _i2 >= 0; _i2--) {
var one = buffer[_i2];
result *= 0x100;
if (isLossyToAdd(result, one)) {
lossy = true;
}
result += one;
}
}
return {
value: result,
lossy: lossy
};
}
/**
* Writes a little-endian 64-bit signed int into a buffer.
*/
export function writeInt64(value, buffer) {
if (value < MIN_EXACT_INT64 || value > MAX_EXACT_INT64) {
throw new Error("Value out of range.");
}
if (value < 0) {
value += BIT_64;
}
writeUInt64(value, buffer);
}
/**
* Writes a little-endian 64-bit unsigned int into a buffer.
*/
export function writeUInt64(value, buffer) {
if (value < 0 || value > MAX_EXACT_UINT64) {
throw new Error("Value out of range.");
}
var lowWord = value % BIT_32;
var highWord = Math.floor(value / BIT_32);
buffer[0] = lowWord & 0xff;
buffer[1] = lowWord >> 8 & 0xff;
buffer[2] = lowWord >> 16 & 0xff;
buffer[3] = lowWord >> 24 & 0xff;
buffer[4] = highWord & 0xff;
buffer[5] = highWord >> 8 & 0xff;
buffer[6] = highWord >> 16 & 0xff;
buffer[7] = highWord >> 24 & 0xff;
}

View File

@@ -0,0 +1,156 @@
// Copyright 2012 The Obvious Corporation.
/*
* bits: Bitwise buffer utilities. The utilities here treat a buffer
* as a little-endian bigint, so the lowest-order bit is bit #0 of
* `buffer[0]`, and the highest-order bit is bit #7 of
* `buffer[buffer.length - 1]`.
*/
/*
* Modules used
*/
"use strict";
/*
* Exported bindings
*/
/**
* Extracts the given number of bits from the buffer at the indicated
* index, returning a simple number as the result. If bits are requested
* that aren't covered by the buffer, the `defaultBit` is used as their
* value.
*
* The `bitLength` must be no more than 32. The `defaultBit` if not
* specified is taken to be `0`.
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extract = extract;
exports.inject = inject;
exports.getSign = getSign;
exports.highOrder = highOrder;
function extract(buffer, bitIndex, bitLength, defaultBit) {
if (bitLength < 0 || bitLength > 32) {
throw new Error("Bad value for bitLength.");
}
if (defaultBit === undefined) {
defaultBit = 0;
} else if (defaultBit !== 0 && defaultBit !== 1) {
throw new Error("Bad value for defaultBit.");
}
var defaultByte = defaultBit * 0xff;
var result = 0; // All starts are inclusive. The {endByte, endBit} pair is exclusive, but
// if endBit !== 0, then endByte is inclusive.
var lastBit = bitIndex + bitLength;
var startByte = Math.floor(bitIndex / 8);
var startBit = bitIndex % 8;
var endByte = Math.floor(lastBit / 8);
var endBit = lastBit % 8;
if (endBit !== 0) {
// `(1 << endBit) - 1` is the mask of all bits up to but not including
// the endBit.
result = get(endByte) & (1 << endBit) - 1;
}
while (endByte > startByte) {
endByte--;
result = result << 8 | get(endByte);
}
result >>>= startBit;
return result;
function get(index) {
var result = buffer[index];
return result === undefined ? defaultByte : result;
}
}
/**
* Injects the given bits into the given buffer at the given index. Any
* bits in the value beyond the length to set are ignored.
*/
function inject(buffer, bitIndex, bitLength, value) {
if (bitLength < 0 || bitLength > 32) {
throw new Error("Bad value for bitLength.");
}
var lastByte = Math.floor((bitIndex + bitLength - 1) / 8);
if (bitIndex < 0 || lastByte >= buffer.length) {
throw new Error("Index out of range.");
} // Just keeping it simple, until / unless profiling shows that this
// is a problem.
var atByte = Math.floor(bitIndex / 8);
var atBit = bitIndex % 8;
while (bitLength > 0) {
if (value & 1) {
buffer[atByte] |= 1 << atBit;
} else {
buffer[atByte] &= ~(1 << atBit);
}
value >>= 1;
bitLength--;
atBit = (atBit + 1) % 8;
if (atBit === 0) {
atByte++;
}
}
}
/**
* Gets the sign bit of the given buffer.
*/
function getSign(buffer) {
return buffer[buffer.length - 1] >>> 7;
}
/**
* Gets the zero-based bit number of the highest-order bit with the
* given value in the given buffer.
*
* If the buffer consists entirely of the other bit value, then this returns
* `-1`.
*/
function highOrder(bit, buffer) {
var length = buffer.length;
var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte
while (length > 0 && buffer[length - 1] === fullyWrongByte) {
length--;
}
if (length === 0) {
// Degenerate case. The buffer consists entirely of ~bit.
return -1;
}
var byteToCheck = buffer[length - 1];
var result = length * 8 - 1;
for (var i = 7; i > 0; i--) {
if ((byteToCheck >> i & 1) === bit) {
break;
}
result--;
}
return result;
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,67 @@
function con(b) {
if ((b & 0xc0) === 0x80) {
return b & 0x3f;
} else {
throw new Error("invalid UTF-8 encoding");
}
}
function code(min, n) {
if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) {
throw new Error("invalid UTF-8 encoding");
} else {
return n;
}
}
export function decode(bytes) {
return _decode(bytes).map(function (x) {
return String.fromCharCode(x);
}).join("");
}
function _decode(bytes) {
var result = [];
while (bytes.length > 0) {
var b1 = bytes[0];
if (b1 < 0x80) {
result.push(code(0x0, b1));
bytes = bytes.slice(1);
continue;
}
if (b1 < 0xc0) {
throw new Error("invalid UTF-8 encoding");
}
var b2 = bytes[1];
if (b1 < 0xe0) {
result.push(code(0x80, ((b1 & 0x1f) << 6) + con(b2)));
bytes = bytes.slice(2);
continue;
}
var b3 = bytes[2];
if (b1 < 0xf0) {
result.push(code(0x800, ((b1 & 0x0f) << 12) + (con(b2) << 6) + con(b3)));
bytes = bytes.slice(3);
continue;
}
var b4 = bytes[3];
if (b1 < 0xf8) {
result.push(code(0x10000, (((b1 & 0x07) << 18) + con(b2) << 12) + (con(b3) << 6) + con(b4)));
bytes = bytes.slice(4);
continue;
}
throw new Error("invalid UTF-8 encoding");
}
return result;
}

View File

@@ -0,0 +1,74 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.decode = decode;
function con(b) {
if ((b & 0xc0) === 0x80) {
return b & 0x3f;
} else {
throw new Error("invalid UTF-8 encoding");
}
}
function code(min, n) {
if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) {
throw new Error("invalid UTF-8 encoding");
} else {
return n;
}
}
function decode(bytes) {
return _decode(bytes).map(function (x) {
return String.fromCharCode(x);
}).join("");
}
function _decode(bytes) {
var result = [];
while (bytes.length > 0) {
var b1 = bytes[0];
if (b1 < 0x80) {
result.push(code(0x0, b1));
bytes = bytes.slice(1);
continue;
}
if (b1 < 0xc0) {
throw new Error("invalid UTF-8 encoding");
}
var b2 = bytes[1];
if (b1 < 0xe0) {
result.push(code(0x80, ((b1 & 0x1f) << 6) + con(b2)));
bytes = bytes.slice(2);
continue;
}
var b3 = bytes[2];
if (b1 < 0xf0) {
result.push(code(0x800, ((b1 & 0x0f) << 12) + (con(b2) << 6) + con(b3)));
bytes = bytes.slice(3);
continue;
}
var b4 = bytes[3];
if (b1 < 0xf8) {
result.push(code(0x10000, (((b1 & 0x07) << 18) + con(b2) << 12) + (con(b3) << 6) + con(b4)));
bytes = bytes.slice(4);
continue;
}
throw new Error("invalid UTF-8 encoding");
}
return result;
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,306 @@
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { encodeNode } from "@webassemblyjs/wasm-gen";
import { encodeU32 } from "@webassemblyjs/wasm-gen/lib/encoder";
import { isFunc, isGlobal, assertHasLoc, orderedInsertNode, getSectionMetadata, traverse, getEndOfSection } from "@webassemblyjs/ast";
import { resizeSectionByteSize, resizeSectionVecSize, createEmptySection, removeSections } from "@webassemblyjs/helper-wasm-section";
import { overrideBytesInBuffer } from "@webassemblyjs/helper-buffer";
import { getSectionForNode } from "@webassemblyjs/helper-wasm-bytecode";
function shiftLocNodeByDelta(node, delta) {
assertHasLoc(node); // $FlowIgnore: assertHasLoc ensures that
node.loc.start.column += delta; // $FlowIgnore: assertHasLoc ensures that
node.loc.end.column += delta;
}
function applyUpdate(ast, uint8Buffer, _ref) {
var _ref2 = _slicedToArray(_ref, 2),
oldNode = _ref2[0],
newNode = _ref2[1];
var deltaElements = 0;
assertHasLoc(oldNode);
var sectionName = getSectionForNode(newNode);
var replacementByteArray = encodeNode(newNode);
/**
* Replace new node as bytes
*/
uint8Buffer = overrideBytesInBuffer(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that
oldNode.loc.start.column, // $FlowIgnore: assertHasLoc ensures that
oldNode.loc.end.column, replacementByteArray);
/**
* Update function body size if needed
*/
if (sectionName === "code") {
// Find the parent func
traverse(ast, {
Func: function Func(_ref3) {
var node = _ref3.node;
var funcHasThisIntr = node.body.find(function (n) {
return n === newNode;
}) !== undefined; // Update func's body size if needed
if (funcHasThisIntr === true) {
// These are the old functions locations informations
assertHasLoc(node);
var oldNodeSize = encodeNode(oldNode).length;
var bodySizeDeltaBytes = replacementByteArray.length - oldNodeSize;
if (bodySizeDeltaBytes !== 0) {
var newValue = node.metadata.bodySize + bodySizeDeltaBytes;
var newByteArray = encodeU32(newValue); // function body size byte
// FIXME(sven): only handles one byte u32
var start = node.loc.start.column;
var end = start + 1;
uint8Buffer = overrideBytesInBuffer(uint8Buffer, start, end, newByteArray);
}
}
}
});
}
/**
* Update section size
*/
var deltaBytes = replacementByteArray.length - (oldNode.loc.end.column - oldNode.loc.start.column); // Init location informations
newNode.loc = {
start: {
line: -1,
column: -1
},
end: {
line: -1,
column: -1
}
}; // Update new node end position
// $FlowIgnore: assertHasLoc ensures that
newNode.loc.start.column = oldNode.loc.start.column; // $FlowIgnore: assertHasLoc ensures that
newNode.loc.end.column = // $FlowIgnore: assertHasLoc ensures that
oldNode.loc.start.column + replacementByteArray.length;
return {
uint8Buffer: uint8Buffer,
deltaBytes: deltaBytes,
deltaElements: deltaElements
};
}
function applyDelete(ast, uint8Buffer, node) {
var deltaElements = -1; // since we removed an element
assertHasLoc(node);
var sectionName = getSectionForNode(node);
if (sectionName === "start") {
var sectionMetadata = getSectionMetadata(ast, "start");
/**
* The start section only contains one element,
* we need to remove the whole section
*/
uint8Buffer = removeSections(ast, uint8Buffer, "start");
var _deltaBytes = -(sectionMetadata.size.value + 1);
/* section id */
return {
uint8Buffer: uint8Buffer,
deltaBytes: _deltaBytes,
deltaElements: deltaElements
};
} // replacement is nothing
var replacement = [];
uint8Buffer = overrideBytesInBuffer(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that
node.loc.start.column, // $FlowIgnore: assertHasLoc ensures that
node.loc.end.column, replacement);
/**
* Update section
*/
// $FlowIgnore: assertHasLoc ensures that
var deltaBytes = -(node.loc.end.column - node.loc.start.column);
return {
uint8Buffer: uint8Buffer,
deltaBytes: deltaBytes,
deltaElements: deltaElements
};
}
function applyAdd(ast, uint8Buffer, node) {
var deltaElements = +1; // since we added an element
var sectionName = getSectionForNode(node);
var sectionMetadata = getSectionMetadata(ast, sectionName); // Section doesn't exists, we create an empty one
if (typeof sectionMetadata === "undefined") {
var res = createEmptySection(ast, uint8Buffer, sectionName);
uint8Buffer = res.uint8Buffer;
sectionMetadata = res.sectionMetadata;
}
/**
* check that the expressions were ended
*/
if (isFunc(node)) {
// $FlowIgnore
var body = node.body;
if (body.length === 0 || body[body.length - 1].id !== "end") {
throw new Error("expressions must be ended");
}
}
if (isGlobal(node)) {
// $FlowIgnore
var body = node.init;
if (body.length === 0 || body[body.length - 1].id !== "end") {
throw new Error("expressions must be ended");
}
}
/**
* Add nodes
*/
var newByteArray = encodeNode(node); // The size of the section doesn't include the storage of the size itself
// we need to manually add it here
var start = getEndOfSection(sectionMetadata);
var end = start;
/**
* Update section
*/
var deltaBytes = newByteArray.length;
uint8Buffer = overrideBytesInBuffer(uint8Buffer, start, end, newByteArray);
node.loc = {
start: {
line: -1,
column: start
},
end: {
line: -1,
column: start + deltaBytes
}
}; // for func add the additional metadata in the AST
if (node.type === "Func") {
// the size is the first byte
// FIXME(sven): handle LEB128 correctly here
var bodySize = newByteArray[0];
node.metadata = {
bodySize: bodySize
};
}
if (node.type !== "IndexInFuncSection") {
orderedInsertNode(ast.body[0], node);
}
return {
uint8Buffer: uint8Buffer,
deltaBytes: deltaBytes,
deltaElements: deltaElements
};
}
export function applyOperations(ast, uint8Buffer, ops) {
ops.forEach(function (op) {
var state;
var sectionName;
switch (op.kind) {
case "update":
state = applyUpdate(ast, uint8Buffer, [op.oldNode, op.node]);
sectionName = getSectionForNode(op.node);
break;
case "delete":
state = applyDelete(ast, uint8Buffer, op.node);
sectionName = getSectionForNode(op.node);
break;
case "add":
state = applyAdd(ast, uint8Buffer, op.node);
sectionName = getSectionForNode(op.node);
break;
default:
throw new Error("Unknown operation");
}
/**
* Resize section vec size.
* If the length of the LEB-encoded size changes, this can change
* the byte length of the section and the offset for nodes in the
* section. So we do this first before resizing section byte size
* or shifting following operations' nodes.
*/
if (state.deltaElements !== 0 && sectionName !== "start") {
var oldBufferLength = state.uint8Buffer.length;
state.uint8Buffer = resizeSectionVecSize(ast, state.uint8Buffer, sectionName, state.deltaElements); // Infer bytes added/removed by comparing buffer lengths
state.deltaBytes += state.uint8Buffer.length - oldBufferLength;
}
/**
* Resize section byte size.
* If the length of the LEB-encoded size changes, this can change
* the offset for nodes in the section. So we do this before
* shifting following operations' nodes.
*/
if (state.deltaBytes !== 0 && sectionName !== "start") {
var _oldBufferLength = state.uint8Buffer.length;
state.uint8Buffer = resizeSectionByteSize(ast, state.uint8Buffer, sectionName, state.deltaBytes); // Infer bytes added/removed by comparing buffer lengths
state.deltaBytes += state.uint8Buffer.length - _oldBufferLength;
}
/**
* Shift following operation's nodes
*/
if (state.deltaBytes !== 0) {
ops.forEach(function (op) {
// We don't need to handle add ops, they are positioning independent
switch (op.kind) {
case "update":
shiftLocNodeByDelta(op.oldNode, state.deltaBytes);
break;
case "delete":
shiftLocNodeByDelta(op.node, state.deltaBytes);
break;
}
});
}
uint8Buffer = state.uint8Buffer;
});
return uint8Buffer;
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,312 @@
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
import * as leb from "@webassemblyjs/leb128";
import * as ieee754 from "@webassemblyjs/ieee754";
import * as utf8 from "@webassemblyjs/utf8";
import constants from "@webassemblyjs/helper-wasm-bytecode";
import { encodeNode } from "../index";
function assertNotIdentifierNode(n) {
if (n.type === "Identifier") {
throw new Error("Unsupported node Identifier");
}
}
export function encodeVersion(v) {
var bytes = constants.moduleVersion;
bytes[0] = v;
return bytes;
}
export function encodeHeader() {
return constants.magicModuleHeader;
}
export function encodeU32(v) {
var uint8view = new Uint8Array(leb.encodeU32(v));
var array = _toConsumableArray(uint8view);
return array;
}
export function encodeI32(v) {
var uint8view = new Uint8Array(leb.encodeI32(v));
var array = _toConsumableArray(uint8view);
return array;
}
export function encodeI64(v) {
var uint8view = new Uint8Array(leb.encodeI64(v));
var array = _toConsumableArray(uint8view);
return array;
}
export function encodeVec(elements) {
var size = encodeU32(elements.length);
return [].concat(_toConsumableArray(size), _toConsumableArray(elements));
}
export function encodeValtype(v) {
var _byte = constants.valtypesByString[v];
if (typeof _byte === "undefined") {
throw new Error("Unknown valtype: " + v);
}
return parseInt(_byte, 10);
}
export function encodeMutability(v) {
var _byte2 = constants.globalTypesByString[v];
if (typeof _byte2 === "undefined") {
throw new Error("Unknown mutability: " + v);
}
return parseInt(_byte2, 10);
}
export function encodeUTF8Vec(str) {
return encodeVec(utf8.encode(str));
}
export function encodeLimits(n) {
var out = [];
if (typeof n.max === "number") {
out.push(0x01);
out.push.apply(out, _toConsumableArray(encodeU32(n.min))); // $FlowIgnore: ensured by the typeof
out.push.apply(out, _toConsumableArray(encodeU32(n.max)));
} else {
out.push(0x00);
out.push.apply(out, _toConsumableArray(encodeU32(n.min)));
}
return out;
}
export function encodeModuleImport(n) {
var out = [];
out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.module)));
out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));
switch (n.descr.type) {
case "GlobalType":
{
out.push(0x03); // $FlowIgnore: GlobalType ensure that these props exists
out.push(encodeValtype(n.descr.valtype)); // $FlowIgnore: GlobalType ensure that these props exists
out.push(encodeMutability(n.descr.mutability));
break;
}
case "Memory":
{
out.push(0x02); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
break;
}
case "Table":
{
out.push(0x01);
out.push(0x70); // element type
// $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
break;
}
case "FuncImportDescr":
{
out.push(0x00); // $FlowIgnore
assertNotIdentifierNode(n.descr.id); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
break;
}
default:
throw new Error("Unsupport operation: encode module import of type: " + n.descr.type);
}
return out;
}
export function encodeSectionMetadata(n) {
var out = [];
var sectionId = constants.sections[n.section];
if (typeof sectionId === "undefined") {
throw new Error("Unknown section: " + n.section);
}
if (n.section === "start") {
/**
* This is not implemented yet because it's a special case which
* doesn't have a vector in its section.
*/
throw new Error("Unsupported section encoding of type start");
}
out.push(sectionId);
out.push.apply(out, _toConsumableArray(encodeU32(n.size.value)));
out.push.apply(out, _toConsumableArray(encodeU32(n.vectorOfSize.value)));
return out;
}
export function encodeCallInstruction(n) {
var out = [];
assertNotIdentifierNode(n.index);
out.push(0x10); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.index.value)));
return out;
}
export function encodeCallIndirectInstruction(n) {
var out = []; // $FlowIgnore
assertNotIdentifierNode(n.index);
out.push(0x11); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); // add a reserved byte
out.push(0x00);
return out;
}
export function encodeModuleExport(n) {
var out = [];
assertNotIdentifierNode(n.descr.id);
var exportTypeByteString = constants.exportTypesByName[n.descr.exportType];
if (typeof exportTypeByteString === "undefined") {
throw new Error("Unknown export of type: " + n.descr.exportType);
}
var exportTypeByte = parseInt(exportTypeByteString, 10);
out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));
out.push(exportTypeByte); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
return out;
}
export function encodeTypeInstruction(n) {
var out = [0x60];
var params = n.functype.params.map(function (x) {
return x.valtype;
}).map(encodeValtype);
var results = n.functype.results.map(encodeValtype);
out.push.apply(out, _toConsumableArray(encodeVec(params)));
out.push.apply(out, _toConsumableArray(encodeVec(results)));
return out;
}
export function encodeInstr(n) {
var out = [];
var instructionName = n.id;
if (typeof n.object === "string") {
instructionName = "".concat(n.object, ".").concat(String(n.id));
}
var byteString = constants.symbolsByName[instructionName];
if (typeof byteString === "undefined") {
throw new Error("encodeInstr: unknown instruction " + JSON.stringify(instructionName));
}
var _byte3 = parseInt(byteString, 10);
out.push(_byte3);
if (n.args) {
n.args.forEach(function (arg) {
var encoder = encodeU32; // find correct encoder
if (n.object === "i32") {
encoder = encodeI32;
}
if (n.object === "i64") {
encoder = encodeI64;
}
if (n.object === "f32") {
encoder = ieee754.encodeF32;
}
if (n.object === "f64") {
encoder = ieee754.encodeF64;
}
if (arg.type === "NumberLiteral" || arg.type === "FloatLiteral" || arg.type === "LongNumberLiteral") {
// $FlowIgnore
out.push.apply(out, _toConsumableArray(encoder(arg.value)));
} else {
throw new Error("Unsupported instruction argument encoding " + JSON.stringify(arg.type));
}
});
}
return out;
}
function encodeExpr(instrs) {
var out = [];
instrs.forEach(function (instr) {
// $FlowIgnore
var n = encodeNode(instr);
out.push.apply(out, _toConsumableArray(n));
});
return out;
}
export function encodeStringLiteral(n) {
return encodeUTF8Vec(n.value);
}
export function encodeGlobal(n) {
var out = [];
var _n$globalType = n.globalType,
valtype = _n$globalType.valtype,
mutability = _n$globalType.mutability;
out.push(encodeValtype(valtype));
out.push(encodeMutability(mutability));
out.push.apply(out, _toConsumableArray(encodeExpr(n.init)));
return out;
}
export function encodeFuncBody(n) {
var out = [];
out.push(-1); // temporary function body size
// FIXME(sven): get the func locals?
var localBytes = encodeVec([]);
out.push.apply(out, _toConsumableArray(localBytes));
var funcBodyBytes = encodeExpr(n.body);
out[0] = funcBodyBytes.length + localBytes.length;
out.push.apply(out, _toConsumableArray(funcBodyBytes));
return out;
}
export function encodeIndexInFuncSection(n) {
assertNotIdentifierNode(n.index); // $FlowIgnore
return encodeU32(n.index.value);
}
export function encodeElem(n) {
var out = [];
assertNotIdentifierNode(n.table); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.table.value)));
out.push.apply(out, _toConsumableArray(encodeExpr(n.offset))); // $FlowIgnore
var funcs = n.funcs.reduce(function (acc, x) {
return [].concat(_toConsumableArray(acc), _toConsumableArray(encodeU32(x.value)));
}, []);
out.push.apply(out, _toConsumableArray(encodeVec(funcs)));
return out;
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,57 @@
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import { decode } from "@webassemblyjs/wasm-parser";
import { shrinkPaddedLEB128 as makeShrinkPaddedLEB128 } from "./leb128.js";
var OptimizerError = /*#__PURE__*/function (_Error) {
_inherits(OptimizerError, _Error);
var _super = _createSuper(OptimizerError);
function OptimizerError(name, initalError) {
var _this;
_classCallCheck(this, OptimizerError);
_this = _super.call(this, "Error while optimizing: " + name + ": " + initalError.message);
_this.stack = initalError.stack;
return _this;
}
return OptimizerError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
var decoderOpts = {
ignoreCodeSection: true,
ignoreDataSection: true
};
export function shrinkPaddedLEB128(uint8Buffer) {
try {
var ast = decode(uint8Buffer.buffer, decoderOpts);
return makeShrinkPaddedLEB128(ast, uint8Buffer);
} catch (e) {
throw new OptimizerError("shrinkPaddedLEB128", e);
}
}

View File

@@ -0,0 +1,66 @@
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.shrinkPaddedLEB128 = shrinkPaddedLEB128;
var _wasmParser = require("@webassemblyjs/wasm-parser");
var _leb = require("./leb128.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var OptimizerError = /*#__PURE__*/function (_Error) {
_inherits(OptimizerError, _Error);
var _super = _createSuper(OptimizerError);
function OptimizerError(name, initalError) {
var _this;
_classCallCheck(this, OptimizerError);
_this = _super.call(this, "Error while optimizing: " + name + ": " + initalError.message);
_this.stack = initalError.stack;
return _this;
}
return OptimizerError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
var decoderOpts = {
ignoreCodeSection: true,
ignoreDataSection: true
};
function shrinkPaddedLEB128(uint8Buffer) {
try {
var ast = (0, _wasmParser.decode)(uint8Buffer.buffer, decoderOpts);
return (0, _leb.shrinkPaddedLEB128)(ast, uint8Buffer);
} catch (e) {
throw new OptimizerError("shrinkPaddedLEB128", e);
}
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Sven Sauleau <sven@sauleau.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,920 @@
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { isAnonymous, isInstruction } from "@webassemblyjs/ast";
import Long from "@xtuc/long";
var compact = false;
var space = " ";
var quote = function quote(str) {
return "\"".concat(str, "\"");
};
function indent(nb) {
return Array(nb).fill(space + space).join("");
} // TODO(sven): allow arbitrary ast nodes
export function print(n) {
if (n.type === "Program") {
return printProgram(n, 0);
} else {
throw new Error("Unsupported node in print of type: " + String(n.type));
}
}
function printProgram(n, depth) {
return n.body.reduce(function (acc, child) {
if (child.type === "Module") {
acc += printModule(child, depth + 1);
}
if (child.type === "Func") {
acc += printFunc(child, depth + 1);
}
if (child.type === "BlockComment") {
acc += printBlockComment(child);
}
if (child.type === "LeadingComment") {
acc += printLeadingComment(child);
}
if (compact === false) {
acc += "\n";
}
return acc;
}, "");
}
function printTypeInstruction(n) {
var out = "";
out += "(";
out += "type";
out += space;
if (n.id != null) {
out += printIndex(n.id);
out += space;
}
out += "(";
out += "func";
n.functype.params.forEach(function (param) {
out += space;
out += "(";
out += "param";
out += space;
out += printFuncParam(param);
out += ")";
});
n.functype.results.forEach(function (result) {
out += space;
out += "(";
out += "result";
out += space;
out += result;
out += ")";
});
out += ")"; // func
out += ")";
return out;
}
function printModule(n, depth) {
var out = "(";
out += "module";
if (typeof n.id === "string") {
out += space;
out += n.id;
}
if (compact === false) {
out += "\n";
} else {
out += space;
}
n.fields.forEach(function (field) {
if (compact === false) {
out += indent(depth);
}
switch (field.type) {
case "Func":
{
out += printFunc(field, depth + 1);
break;
}
case "TypeInstruction":
{
out += printTypeInstruction(field);
break;
}
case "Table":
{
out += printTable(field);
break;
}
case "Global":
{
out += printGlobal(field, depth + 1);
break;
}
case "ModuleExport":
{
out += printModuleExport(field);
break;
}
case "ModuleImport":
{
out += printModuleImport(field);
break;
}
case "Memory":
{
out += printMemory(field);
break;
}
case "BlockComment":
{
out += printBlockComment(field);
break;
}
case "LeadingComment":
{
out += printLeadingComment(field);
break;
}
case "Start":
{
out += printStart(field);
break;
}
case "Elem":
{
out += printElem(field, depth);
break;
}
case "Data":
{
out += printData(field, depth);
break;
}
default:
throw new Error("Unsupported node in printModule: " + String(field.type));
}
if (compact === false) {
out += "\n";
}
});
out += ")";
return out;
}
function printData(n, depth) {
var out = "";
out += "(";
out += "data";
out += space;
out += printIndex(n.memoryIndex);
out += space;
out += printInstruction(n.offset, depth);
out += space;
out += '"';
n.init.values.forEach(function (_byte) {
// Avoid non-displayable characters
if (_byte <= 31 || _byte == 34 || _byte == 92 || _byte >= 127) {
out += "\\";
out += ("00" + _byte.toString(16)).substr(-2);
} else if (_byte > 255) {
throw new Error("Unsupported byte in data segment: " + _byte);
} else {
out += String.fromCharCode(_byte);
}
});
out += '"';
out += ")";
return out;
}
function printElem(n, depth) {
var out = "";
out += "(";
out += "elem";
out += space;
out += printIndex(n.table);
var _n$offset = _slicedToArray(n.offset, 1),
firstOffset = _n$offset[0];
out += space;
out += "(";
out += "offset";
out += space;
out += printInstruction(firstOffset, depth);
out += ")";
n.funcs.forEach(function (func) {
out += space;
out += printIndex(func);
});
out += ")";
return out;
}
function printStart(n) {
var out = "";
out += "(";
out += "start";
out += space;
out += printIndex(n.index);
out += ")";
return out;
}
function printLeadingComment(n) {
// Don't print leading comments in compact mode
if (compact === true) {
return "";
}
var out = "";
out += ";;";
out += n.value;
out += "\n";
return out;
}
function printBlockComment(n) {
// Don't print block comments in compact mode
if (compact === true) {
return "";
}
var out = "";
out += "(;";
out += n.value;
out += ";)";
out += "\n";
return out;
}
function printSignature(n) {
var out = "";
n.params.forEach(function (param) {
out += space;
out += "(";
out += "param";
out += space;
out += printFuncParam(param);
out += ")";
});
n.results.forEach(function (result) {
out += space;
out += "(";
out += "result";
out += space;
out += result;
out += ")";
});
return out;
}
function printModuleImportDescr(n) {
var out = "";
if (n.type === "FuncImportDescr") {
out += "(";
out += "func";
if (isAnonymous(n.id) === false) {
out += space;
out += printIdentifier(n.id);
}
out += printSignature(n.signature);
out += ")";
}
if (n.type === "GlobalType") {
out += "(";
out += "global";
out += space;
out += printGlobalType(n);
out += ")";
}
if (n.type === "Table") {
out += printTable(n);
}
return out;
}
function printModuleImport(n) {
var out = "";
out += "(";
out += "import";
out += space;
out += quote(n.module);
out += space;
out += quote(n.name);
out += space;
out += printModuleImportDescr(n.descr);
out += ")";
return out;
}
function printGlobalType(n) {
var out = "";
if (n.mutability === "var") {
out += "(";
out += "mut";
out += space;
out += n.valtype;
out += ")";
} else {
out += n.valtype;
}
return out;
}
function printGlobal(n, depth) {
var out = "";
out += "(";
out += "global";
out += space;
if (n.name != null && isAnonymous(n.name) === false) {
out += printIdentifier(n.name);
out += space;
}
out += printGlobalType(n.globalType);
out += space;
n.init.forEach(function (i) {
out += printInstruction(i, depth + 1);
});
out += ")";
return out;
}
function printTable(n) {
var out = "";
out += "(";
out += "table";
out += space;
if (n.name != null && isAnonymous(n.name) === false) {
out += printIdentifier(n.name);
out += space;
}
out += printLimit(n.limits);
out += space;
out += n.elementType;
out += ")";
return out;
}
function printFuncParam(n) {
var out = "";
if (typeof n.id === "string") {
out += "$" + n.id;
out += space;
}
out += n.valtype;
return out;
}
function printFunc(n, depth) {
var out = "";
out += "(";
out += "func";
if (n.name != null) {
if (n.name.type === "Identifier" && isAnonymous(n.name) === false) {
out += space;
out += printIdentifier(n.name);
}
}
if (n.signature.type === "Signature") {
out += printSignature(n.signature);
} else {
var index = n.signature;
out += space;
out += "(";
out += "type";
out += space;
out += printIndex(index);
out += ")";
}
if (n.body.length > 0) {
// func is empty since we ignore the default end instruction
if (n.body.length === 1 && n.body[0].id === "end") {
out += ")";
return out;
}
if (compact === false) {
out += "\n";
}
n.body.forEach(function (i) {
if (i.id !== "end") {
out += indent(depth);
out += printInstruction(i, depth);
if (compact === false) {
out += "\n";
}
}
});
out += indent(depth - 1) + ")";
} else {
out += ")";
}
return out;
}
function printInstruction(n, depth) {
switch (n.type) {
case "Instr":
// $FlowIgnore
return printGenericInstruction(n, depth + 1);
case "BlockInstruction":
// $FlowIgnore
return printBlockInstruction(n, depth + 1);
case "IfInstruction":
// $FlowIgnore
return printIfInstruction(n, depth + 1);
case "CallInstruction":
// $FlowIgnore
return printCallInstruction(n, depth + 1);
case "CallIndirectInstruction":
// $FlowIgnore
return printCallIndirectIntruction(n, depth + 1);
case "LoopInstruction":
// $FlowIgnore
return printLoopInstruction(n, depth + 1);
default:
throw new Error("Unsupported instruction: " + JSON.stringify(n.type));
}
}
function printCallIndirectIntruction(n, depth) {
var out = "";
out += "(";
out += "call_indirect";
if (n.signature.type === "Signature") {
out += printSignature(n.signature);
} else if (n.signature.type === "Identifier") {
out += space;
out += "(";
out += "type";
out += space;
out += printIdentifier(n.signature);
out += ")";
} else {
throw new Error("CallIndirectInstruction: unsupported signature " + JSON.stringify(n.signature.type));
}
out += space;
if (n.intrs != null) {
// $FlowIgnore
n.intrs.forEach(function (i, index) {
// $FlowIgnore
out += printInstruction(i, depth + 1); // $FlowIgnore
if (index !== n.intrs.length - 1) {
out += space;
}
});
}
out += ")";
return out;
}
function printLoopInstruction(n, depth) {
var out = "";
out += "(";
out += "loop";
if (n.label != null && isAnonymous(n.label) === false) {
out += space;
out += printIdentifier(n.label);
}
if (typeof n.resulttype === "string") {
out += space;
out += "(";
out += "result";
out += space;
out += n.resulttype;
out += ")";
}
if (n.instr.length > 0) {
n.instr.forEach(function (e) {
if (compact === false) {
out += "\n";
}
out += indent(depth);
out += printInstruction(e, depth + 1);
});
if (compact === false) {
out += "\n";
out += indent(depth - 1);
}
}
out += ")";
return out;
}
function printCallInstruction(n, depth) {
var out = "";
out += "(";
out += "call";
out += space;
out += printIndex(n.index);
if (_typeof(n.instrArgs) === "object") {
// $FlowIgnore
n.instrArgs.forEach(function (arg) {
out += space;
out += printFuncInstructionArg(arg, depth + 1);
});
}
out += ")";
return out;
}
function printIfInstruction(n, depth) {
var out = "";
out += "(";
out += "if";
if (n.testLabel != null && isAnonymous(n.testLabel) === false) {
out += space;
out += printIdentifier(n.testLabel);
}
if (typeof n.result === "string") {
out += space;
out += "(";
out += "result";
out += space;
out += n.result;
out += ")";
}
if (n.test.length > 0) {
out += space;
n.test.forEach(function (i) {
out += printInstruction(i, depth + 1);
});
}
if (n.consequent.length > 0) {
if (compact === false) {
out += "\n";
}
out += indent(depth);
out += "(";
out += "then";
depth++;
n.consequent.forEach(function (i) {
if (compact === false) {
out += "\n";
}
out += indent(depth);
out += printInstruction(i, depth + 1);
});
depth--;
if (compact === false) {
out += "\n";
out += indent(depth);
}
out += ")";
} else {
if (compact === false) {
out += "\n";
out += indent(depth);
}
out += "(";
out += "then";
out += ")";
}
if (n.alternate.length > 0) {
if (compact === false) {
out += "\n";
}
out += indent(depth);
out += "(";
out += "else";
depth++;
n.alternate.forEach(function (i) {
if (compact === false) {
out += "\n";
}
out += indent(depth);
out += printInstruction(i, depth + 1);
});
depth--;
if (compact === false) {
out += "\n";
out += indent(depth);
}
out += ")";
} else {
if (compact === false) {
out += "\n";
out += indent(depth);
}
out += "(";
out += "else";
out += ")";
}
if (compact === false) {
out += "\n";
out += indent(depth - 1);
}
out += ")";
return out;
}
function printBlockInstruction(n, depth) {
var out = "";
out += "(";
out += "block";
if (n.label != null && isAnonymous(n.label) === false) {
out += space;
out += printIdentifier(n.label);
}
if (typeof n.result === "string") {
out += space;
out += "(";
out += "result";
out += space;
out += n.result;
out += ")";
}
if (n.instr.length > 0) {
n.instr.forEach(function (i) {
if (compact === false) {
out += "\n";
}
out += indent(depth);
out += printInstruction(i, depth + 1);
});
if (compact === false) {
out += "\n";
}
out += indent(depth - 1);
out += ")";
} else {
out += ")";
}
return out;
}
function printGenericInstruction(n, depth) {
var out = "";
out += "(";
if (typeof n.object === "string") {
out += n.object;
out += ".";
}
out += n.id;
n.args.forEach(function (arg) {
out += space;
out += printFuncInstructionArg(arg, depth + 1);
});
if (n.namedArgs !== undefined) {
for (var key in n.namedArgs) {
out += space + key + "=";
out += printFuncInstructionArg(n.namedArgs[key], depth + 1);
}
}
out += ")";
return out;
}
function printLongNumberLiteral(n) {
if (typeof n.raw === "string") {
return n.raw;
}
var _n$value = n.value,
low = _n$value.low,
high = _n$value.high;
var v = new Long(low, high);
return v.toString();
}
function printFloatLiteral(n) {
if (typeof n.raw === "string") {
return n.raw;
}
return String(n.value);
}
function printFuncInstructionArg(n, depth) {
var out = "";
if (n.type === "NumberLiteral") {
out += printNumberLiteral(n);
}
if (n.type === "LongNumberLiteral") {
out += printLongNumberLiteral(n);
}
if (n.type === "Identifier" && isAnonymous(n) === false) {
out += printIdentifier(n);
}
if (n.type === "ValtypeLiteral") {
out += n.name;
}
if (n.type === "FloatLiteral") {
out += printFloatLiteral(n);
}
if (isInstruction(n)) {
out += printInstruction(n, depth + 1);
}
return out;
}
function printNumberLiteral(n) {
if (typeof n.raw === "string") {
return n.raw;
}
return String(n.value);
}
function printModuleExport(n) {
var out = "";
out += "(";
out += "export";
out += space;
out += quote(n.name);
if (n.descr.exportType === "Func") {
out += space;
out += "(";
out += "func";
out += space;
out += printIndex(n.descr.id);
out += ")";
} else if (n.descr.exportType === "Global") {
out += space;
out += "(";
out += "global";
out += space;
out += printIndex(n.descr.id);
out += ")";
} else if (n.descr.exportType === "Memory") {
out += space;
out += "(";
out += "memory";
out += space;
out += printIndex(n.descr.id);
out += ")";
} else if (n.descr.exportType === "Table") {
out += space;
out += "(";
out += "table";
out += space;
out += printIndex(n.descr.id);
out += ")";
} else {
throw new Error("printModuleExport: unknown type: " + n.descr.exportType);
}
out += ")";
return out;
}
function printIdentifier(n) {
return "$" + n.value;
}
function printIndex(n) {
if (n.type === "Identifier") {
return printIdentifier(n);
} else if (n.type === "NumberLiteral") {
return printNumberLiteral(n);
} else {
throw new Error("Unsupported index: " + n.type);
}
}
function printMemory(n) {
var out = "";
out += "(";
out += "memory";
if (n.id != null) {
out += space;
out += printIndex(n.id);
out += space;
}
out += printLimit(n.limits);
out += ")";
return out;
}
function printLimit(n) {
var out = "";
out += n.min + "";
if (n.max != null) {
out += space;
out += String(n.max);
if (n.shared === true) {
out += " shared";
}
}
return out;
}