This commit is contained in:
2024-12-17 14:36:15 -08:00
parent b2dbf46d28
commit 06d106de53
17731 changed files with 3037186 additions and 144 deletions

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cloneNode = cloneNode;
function cloneNode(n) {
// $FlowIgnore
return Object.assign({}, n);
}

View File

@@ -0,0 +1,670 @@
"use strict";
var definitions = {};
function defineType(typeName, metadata) {
definitions[typeName] = metadata;
}
defineType("Module", {
spec: {
wasm: "https://webassembly.github.io/spec/core/binary/modules.html#binary-module",
wat: "https://webassembly.github.io/spec/core/text/modules.html#text-module"
},
doc: "A module consists of a sequence of sections (termed fields in the text format).",
unionType: ["Node"],
fields: {
id: {
maybe: true,
type: "string"
},
fields: {
array: true,
type: "Node"
},
metadata: {
optional: true,
type: "ModuleMetadata"
}
}
});
defineType("ModuleMetadata", {
unionType: ["Node"],
fields: {
sections: {
array: true,
type: "SectionMetadata"
},
functionNames: {
optional: true,
array: true,
type: "FunctionNameMetadata"
},
localNames: {
optional: true,
array: true,
type: "ModuleMetadata"
},
producers: {
optional: true,
array: true,
type: "ProducersSectionMetadata"
}
}
});
defineType("ModuleNameMetadata", {
unionType: ["Node"],
fields: {
value: {
type: "string"
}
}
});
defineType("FunctionNameMetadata", {
unionType: ["Node"],
fields: {
value: {
type: "string"
},
index: {
type: "number"
}
}
});
defineType("LocalNameMetadata", {
unionType: ["Node"],
fields: {
value: {
type: "string"
},
localIndex: {
type: "number"
},
functionIndex: {
type: "number"
}
}
});
defineType("BinaryModule", {
unionType: ["Node"],
fields: {
id: {
maybe: true,
type: "string"
},
blob: {
array: true,
type: "string"
}
}
});
defineType("QuoteModule", {
unionType: ["Node"],
fields: {
id: {
maybe: true,
type: "string"
},
string: {
array: true,
type: "string"
}
}
});
defineType("SectionMetadata", {
unionType: ["Node"],
fields: {
section: {
type: "SectionName"
},
startOffset: {
type: "number"
},
size: {
type: "NumberLiteral"
},
vectorOfSize: {
comment: "Size of the vector in the section (if any)",
type: "NumberLiteral"
}
}
});
defineType("ProducersSectionMetadata", {
unionType: ["Node"],
fields: {
producers: {
array: true,
type: "ProducerMetadata"
}
}
});
defineType("ProducerMetadata", {
unionType: ["Node"],
fields: {
language: {
type: "ProducerMetadataVersionedName",
array: true
},
processedBy: {
type: "ProducerMetadataVersionedName",
array: true
},
sdk: {
type: "ProducerMetadataVersionedName",
array: true
}
}
});
defineType("ProducerMetadataVersionedName", {
unionType: ["Node"],
fields: {
name: {
type: "string"
},
version: {
type: "string"
}
}
});
/*
Instructions
*/
defineType("LoopInstruction", {
unionType: ["Node", "Block", "Instruction"],
fields: {
id: {
constant: true,
type: "string",
value: "loop"
},
label: {
maybe: true,
type: "Identifier"
},
resulttype: {
maybe: true,
type: "Valtype"
},
instr: {
array: true,
type: "Instruction"
}
}
});
defineType("Instr", {
unionType: ["Node", "Expression", "Instruction"],
fields: {
id: {
type: "string"
},
object: {
optional: true,
type: "Valtype"
},
args: {
array: true,
type: "Expression"
},
namedArgs: {
optional: true,
type: "Object"
}
}
});
defineType("IfInstruction", {
unionType: ["Node", "Instruction"],
fields: {
id: {
constant: true,
type: "string",
value: "if"
},
testLabel: {
comment: "only for WAST",
type: "Identifier"
},
test: {
array: true,
type: "Instruction"
},
result: {
maybe: true,
type: "Valtype"
},
consequent: {
array: true,
type: "Instruction"
},
alternate: {
array: true,
type: "Instruction"
}
}
});
/*
Concrete value types
*/
defineType("StringLiteral", {
unionType: ["Node", "Expression"],
fields: {
value: {
type: "string"
}
}
});
defineType("NumberLiteral", {
unionType: ["Node", "NumericLiteral", "Expression"],
fields: {
value: {
type: "number"
},
raw: {
type: "string"
}
}
});
defineType("LongNumberLiteral", {
unionType: ["Node", "NumericLiteral", "Expression"],
fields: {
value: {
type: "LongNumber"
},
raw: {
type: "string"
}
}
});
defineType("FloatLiteral", {
unionType: ["Node", "NumericLiteral", "Expression"],
fields: {
value: {
type: "number"
},
nan: {
optional: true,
type: "boolean"
},
inf: {
optional: true,
type: "boolean"
},
raw: {
type: "string"
}
}
});
defineType("Elem", {
unionType: ["Node"],
fields: {
table: {
type: "Index"
},
offset: {
array: true,
type: "Instruction"
},
funcs: {
array: true,
type: "Index"
}
}
});
defineType("IndexInFuncSection", {
unionType: ["Node"],
fields: {
index: {
type: "Index"
}
}
});
defineType("ValtypeLiteral", {
unionType: ["Node", "Expression"],
fields: {
name: {
type: "Valtype"
}
}
});
defineType("TypeInstruction", {
unionType: ["Node", "Instruction"],
fields: {
id: {
maybe: true,
type: "Index"
},
functype: {
type: "Signature"
}
}
});
defineType("Start", {
unionType: ["Node"],
fields: {
index: {
type: "Index"
}
}
});
defineType("GlobalType", {
unionType: ["Node", "ImportDescr"],
fields: {
valtype: {
type: "Valtype"
},
mutability: {
type: "Mutability"
}
}
});
defineType("LeadingComment", {
unionType: ["Node"],
fields: {
value: {
type: "string"
}
}
});
defineType("BlockComment", {
unionType: ["Node"],
fields: {
value: {
type: "string"
}
}
});
defineType("Data", {
unionType: ["Node"],
fields: {
memoryIndex: {
type: "Memidx"
},
offset: {
type: "Instruction"
},
init: {
type: "ByteArray"
}
}
});
defineType("Global", {
unionType: ["Node"],
fields: {
globalType: {
type: "GlobalType"
},
init: {
array: true,
type: "Instruction"
},
name: {
maybe: true,
type: "Identifier"
}
}
});
defineType("Table", {
unionType: ["Node", "ImportDescr"],
fields: {
elementType: {
type: "TableElementType"
},
limits: {
assertNodeType: true,
type: "Limit"
},
name: {
maybe: true,
type: "Identifier"
},
elements: {
array: true,
optional: true,
type: "Index"
}
}
});
defineType("Memory", {
unionType: ["Node", "ImportDescr"],
fields: {
limits: {
type: "Limit"
},
id: {
maybe: true,
type: "Index"
}
}
});
defineType("FuncImportDescr", {
unionType: ["Node", "ImportDescr"],
fields: {
id: {
type: "Identifier"
},
signature: {
type: "Signature"
}
}
});
defineType("ModuleImport", {
unionType: ["Node"],
fields: {
module: {
type: "string"
},
name: {
type: "string"
},
descr: {
type: "ImportDescr"
}
}
});
defineType("ModuleExportDescr", {
unionType: ["Node"],
fields: {
exportType: {
type: "ExportDescrType"
},
id: {
type: "Index"
}
}
});
defineType("ModuleExport", {
unionType: ["Node"],
fields: {
name: {
type: "string"
},
descr: {
type: "ModuleExportDescr"
}
}
});
defineType("Limit", {
unionType: ["Node"],
fields: {
min: {
type: "number"
},
max: {
optional: true,
type: "number"
},
// Threads proposal, shared memory
shared: {
optional: true,
type: "boolean"
}
}
});
defineType("Signature", {
unionType: ["Node"],
fields: {
params: {
array: true,
type: "FuncParam"
},
results: {
array: true,
type: "Valtype"
}
}
});
defineType("Program", {
unionType: ["Node"],
fields: {
body: {
array: true,
type: "Node"
}
}
});
defineType("Identifier", {
unionType: ["Node", "Expression"],
fields: {
value: {
type: "string"
},
raw: {
optional: true,
type: "string"
}
}
});
defineType("BlockInstruction", {
unionType: ["Node", "Block", "Instruction"],
fields: {
id: {
constant: true,
type: "string",
value: "block"
},
label: {
maybe: true,
type: "Identifier"
},
instr: {
array: true,
type: "Instruction"
},
result: {
maybe: true,
type: "Valtype"
}
}
});
defineType("CallInstruction", {
unionType: ["Node", "Instruction"],
fields: {
id: {
constant: true,
type: "string",
value: "call"
},
index: {
type: "Index"
},
instrArgs: {
array: true,
optional: true,
type: "Expression"
},
numeric: {
type: "Index",
optional: true
}
}
});
defineType("CallIndirectInstruction", {
unionType: ["Node", "Instruction"],
fields: {
id: {
constant: true,
type: "string",
value: "call_indirect"
},
signature: {
type: "SignatureOrTypeRef"
},
intrs: {
array: true,
optional: true,
type: "Expression"
}
}
});
defineType("ByteArray", {
unionType: ["Node"],
fields: {
values: {
array: true,
type: "Byte"
}
}
});
defineType("Func", {
unionType: ["Node", "Block"],
fields: {
name: {
maybe: true,
type: "Index"
},
signature: {
type: "SignatureOrTypeRef"
},
body: {
array: true,
type: "Instruction"
},
isExternal: {
comment: "means that it has been imported from the outside js",
optional: true,
type: "boolean"
},
metadata: {
optional: true,
type: "FuncMetadata"
}
}
});
/**
* Intrinsics
*/
defineType("InternalBrUnless", {
unionType: ["Node", "Intrinsic"],
fields: {
target: {
type: "number"
}
}
});
defineType("InternalGoto", {
unionType: ["Node", "Intrinsic"],
fields: {
target: {
type: "number"
}
}
});
defineType("InternalCallExtern", {
unionType: ["Node", "Intrinsic"],
fields: {
target: {
type: "number"
}
}
}); // function bodies are terminated by an `end` instruction but are missing a
// return instruction
//
// Since we can't inject a new instruction we are injecting a new instruction.
defineType("InternalEndAndReturn", {
unionType: ["Node", "Intrinsic"],
fields: {}
});
module.exports = definitions;

View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
numberLiteralFromRaw: true,
withLoc: true,
withRaw: true,
funcParam: true,
indexLiteral: true,
memIndexLiteral: true,
instruction: true,
objectInstruction: true,
traverse: true,
signatures: true,
cloneNode: true,
moduleContextFromModuleAST: true
};
Object.defineProperty(exports, "numberLiteralFromRaw", {
enumerable: true,
get: function get() {
return _nodeHelpers.numberLiteralFromRaw;
}
});
Object.defineProperty(exports, "withLoc", {
enumerable: true,
get: function get() {
return _nodeHelpers.withLoc;
}
});
Object.defineProperty(exports, "withRaw", {
enumerable: true,
get: function get() {
return _nodeHelpers.withRaw;
}
});
Object.defineProperty(exports, "funcParam", {
enumerable: true,
get: function get() {
return _nodeHelpers.funcParam;
}
});
Object.defineProperty(exports, "indexLiteral", {
enumerable: true,
get: function get() {
return _nodeHelpers.indexLiteral;
}
});
Object.defineProperty(exports, "memIndexLiteral", {
enumerable: true,
get: function get() {
return _nodeHelpers.memIndexLiteral;
}
});
Object.defineProperty(exports, "instruction", {
enumerable: true,
get: function get() {
return _nodeHelpers.instruction;
}
});
Object.defineProperty(exports, "objectInstruction", {
enumerable: true,
get: function get() {
return _nodeHelpers.objectInstruction;
}
});
Object.defineProperty(exports, "traverse", {
enumerable: true,
get: function get() {
return _traverse.traverse;
}
});
Object.defineProperty(exports, "signatures", {
enumerable: true,
get: function get() {
return _signatures.signatures;
}
});
Object.defineProperty(exports, "cloneNode", {
enumerable: true,
get: function get() {
return _clone.cloneNode;
}
});
Object.defineProperty(exports, "moduleContextFromModuleAST", {
enumerable: true,
get: function get() {
return _astModuleToModuleContext.moduleContextFromModuleAST;
}
});
var _nodes = require("./nodes");
Object.keys(_nodes).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _nodes[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _nodes[key];
}
});
});
var _nodeHelpers = require("./node-helpers.js");
var _traverse = require("./traverse");
var _signatures = require("./signatures");
var _utils = require("./utils");
Object.keys(_utils).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _utils[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _utils[key];
}
});
});
var _clone = require("./clone");
var _astModuleToModuleContext = require("./transform/ast-module-to-module-context");

View File

@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.numberLiteralFromRaw = numberLiteralFromRaw;
exports.instruction = instruction;
exports.objectInstruction = objectInstruction;
exports.withLoc = withLoc;
exports.withRaw = withRaw;
exports.funcParam = funcParam;
exports.indexLiteral = indexLiteral;
exports.memIndexLiteral = memIndexLiteral;
var _helperNumbers = require("@webassemblyjs/helper-numbers");
var _nodes = require("./nodes");
function numberLiteralFromRaw(rawValue) {
var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32";
var original = rawValue; // Remove numeric separators _
if (typeof rawValue === "string") {
rawValue = rawValue.replace(/_/g, "");
}
if (typeof rawValue === "number") {
return (0, _nodes.numberLiteral)(rawValue, String(original));
} else {
switch (instructionType) {
case "i32":
{
return (0, _nodes.numberLiteral)((0, _helperNumbers.parse32I)(rawValue), String(original));
}
case "u32":
{
return (0, _nodes.numberLiteral)((0, _helperNumbers.parseU32)(rawValue), String(original));
}
case "i64":
{
return (0, _nodes.longNumberLiteral)((0, _helperNumbers.parse64I)(rawValue), String(original));
}
case "f32":
{
return (0, _nodes.floatLiteral)((0, _helperNumbers.parse32F)(rawValue), (0, _helperNumbers.isNanLiteral)(rawValue), (0, _helperNumbers.isInfLiteral)(rawValue), String(original));
}
// f64
default:
{
return (0, _nodes.floatLiteral)((0, _helperNumbers.parse64F)(rawValue), (0, _helperNumbers.isNanLiteral)(rawValue), (0, _helperNumbers.isInfLiteral)(rawValue), String(original));
}
}
}
}
function instruction(id) {
var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var namedArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return (0, _nodes.instr)(id, undefined, args, namedArgs);
}
function objectInstruction(id, object) {
var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var namedArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return (0, _nodes.instr)(id, object, args, namedArgs);
}
/**
* Decorators
*/
function withLoc(n, end, start) {
var loc = {
start: start,
end: end
};
n.loc = loc;
return n;
}
function withRaw(n, raw) {
n.raw = raw;
return n;
}
function funcParam(valtype, id) {
return {
id: id,
valtype: valtype
};
}
function indexLiteral(value) {
// $FlowIgnore
var x = numberLiteralFromRaw(value, "u32");
return x;
}
function memIndexLiteral(value) {
// $FlowIgnore
var x = numberLiteralFromRaw(value, "u32");
return x;
}

View File

@@ -0,0 +1,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPath = createPath;
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function findParent(_ref, cb) {
var parentPath = _ref.parentPath;
if (parentPath == null) {
throw new Error("node is root");
}
var currentPath = parentPath;
while (cb(currentPath) !== false) {
// Hit the root node, stop
// $FlowIgnore
if (currentPath.parentPath == null) {
return null;
} // $FlowIgnore
currentPath = currentPath.parentPath;
}
return currentPath.node;
}
function insertBefore(context, newNode) {
return insert(context, newNode);
}
function insertAfter(context, newNode) {
return insert(context, newNode, 1);
}
function insert(_ref2, newNode) {
var node = _ref2.node,
inList = _ref2.inList,
parentPath = _ref2.parentPath,
parentKey = _ref2.parentKey;
var indexOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
if (!inList) {
throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || "unknown"));
}
if (!(parentPath != null)) {
throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || "unknown"));
}
// $FlowIgnore
var parentList = parentPath.node[parentKey];
var indexInList = parentList.findIndex(function (n) {
return n === node;
});
parentList.splice(indexInList + indexOffset, 0, newNode);
}
function remove(_ref3) {
var node = _ref3.node,
parentKey = _ref3.parentKey,
parentPath = _ref3.parentPath;
if (!(parentPath != null)) {
throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || "unknown"));
}
// $FlowIgnore
var parentNode = parentPath.node; // $FlowIgnore
var parentProperty = parentNode[parentKey];
if (Array.isArray(parentProperty)) {
// $FlowIgnore
parentNode[parentKey] = parentProperty.filter(function (n) {
return n !== node;
});
} else {
// $FlowIgnore
delete parentNode[parentKey];
}
node._deleted = true;
}
function stop(context) {
context.shouldStop = true;
}
function replaceWith(context, newNode) {
// $FlowIgnore
var parentNode = context.parentPath.node; // $FlowIgnore
var parentProperty = parentNode[context.parentKey];
if (Array.isArray(parentProperty)) {
var indexInList = parentProperty.findIndex(function (n) {
return n === context.node;
});
parentProperty.splice(indexInList, 1, newNode);
} else {
// $FlowIgnore
parentNode[context.parentKey] = newNode;
}
context.node._deleted = true;
context.node = newNode;
} // bind the context to the first argument of node operations
function bindNodeOperations(operations, context) {
var keys = Object.keys(operations);
var boundOperations = {};
keys.forEach(function (key) {
boundOperations[key] = operations[key].bind(null, context);
});
return boundOperations;
}
function createPathOperations(context) {
// $FlowIgnore
return bindNodeOperations({
findParent: findParent,
replaceWith: replaceWith,
remove: remove,
insertBefore: insertBefore,
insertAfter: insertAfter,
stop: stop
}, context);
}
function createPath(context) {
var path = _objectSpread({}, context); // $FlowIgnore
Object.assign(path, createPathOperations(path)); // $FlowIgnore
return path;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,207 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.signatures = void 0;
function sign(input, output) {
return [input, output];
}
var u32 = "u32";
var i32 = "i32";
var i64 = "i64";
var f32 = "f32";
var f64 = "f64";
var vector = function vector(t) {
var vecType = [t]; // $FlowIgnore
vecType.vector = true;
return vecType;
};
var controlInstructions = {
unreachable: sign([], []),
nop: sign([], []),
// block ?
// loop ?
// if ?
// if else ?
br: sign([u32], []),
br_if: sign([u32], []),
br_table: sign(vector(u32), []),
"return": sign([], []),
call: sign([u32], []),
call_indirect: sign([u32], [])
};
var parametricInstructions = {
drop: sign([], []),
select: sign([], [])
};
var variableInstructions = {
get_local: sign([u32], []),
set_local: sign([u32], []),
tee_local: sign([u32], []),
get_global: sign([u32], []),
set_global: sign([u32], [])
};
var memoryInstructions = {
"i32.load": sign([u32, u32], [i32]),
"i64.load": sign([u32, u32], []),
"f32.load": sign([u32, u32], []),
"f64.load": sign([u32, u32], []),
"i32.load8_s": sign([u32, u32], [i32]),
"i32.load8_u": sign([u32, u32], [i32]),
"i32.load16_s": sign([u32, u32], [i32]),
"i32.load16_u": sign([u32, u32], [i32]),
"i64.load8_s": sign([u32, u32], [i64]),
"i64.load8_u": sign([u32, u32], [i64]),
"i64.load16_s": sign([u32, u32], [i64]),
"i64.load16_u": sign([u32, u32], [i64]),
"i64.load32_s": sign([u32, u32], [i64]),
"i64.load32_u": sign([u32, u32], [i64]),
"i32.store": sign([u32, u32], []),
"i64.store": sign([u32, u32], []),
"f32.store": sign([u32, u32], []),
"f64.store": sign([u32, u32], []),
"i32.store8": sign([u32, u32], []),
"i32.store16": sign([u32, u32], []),
"i64.store8": sign([u32, u32], []),
"i64.store16": sign([u32, u32], []),
"i64.store32": sign([u32, u32], []),
current_memory: sign([], []),
grow_memory: sign([], [])
};
var numericInstructions = {
"i32.const": sign([i32], [i32]),
"i64.const": sign([i64], [i64]),
"f32.const": sign([f32], [f32]),
"f64.const": sign([f64], [f64]),
"i32.eqz": sign([i32], [i32]),
"i32.eq": sign([i32, i32], [i32]),
"i32.ne": sign([i32, i32], [i32]),
"i32.lt_s": sign([i32, i32], [i32]),
"i32.lt_u": sign([i32, i32], [i32]),
"i32.gt_s": sign([i32, i32], [i32]),
"i32.gt_u": sign([i32, i32], [i32]),
"i32.le_s": sign([i32, i32], [i32]),
"i32.le_u": sign([i32, i32], [i32]),
"i32.ge_s": sign([i32, i32], [i32]),
"i32.ge_u": sign([i32, i32], [i32]),
"i64.eqz": sign([i64], [i64]),
"i64.eq": sign([i64, i64], [i32]),
"i64.ne": sign([i64, i64], [i32]),
"i64.lt_s": sign([i64, i64], [i32]),
"i64.lt_u": sign([i64, i64], [i32]),
"i64.gt_s": sign([i64, i64], [i32]),
"i64.gt_u": sign([i64, i64], [i32]),
"i64.le_s": sign([i64, i64], [i32]),
"i64.le_u": sign([i64, i64], [i32]),
"i64.ge_s": sign([i64, i64], [i32]),
"i64.ge_u": sign([i64, i64], [i32]),
"f32.eq": sign([f32, f32], [i32]),
"f32.ne": sign([f32, f32], [i32]),
"f32.lt": sign([f32, f32], [i32]),
"f32.gt": sign([f32, f32], [i32]),
"f32.le": sign([f32, f32], [i32]),
"f32.ge": sign([f32, f32], [i32]),
"f64.eq": sign([f64, f64], [i32]),
"f64.ne": sign([f64, f64], [i32]),
"f64.lt": sign([f64, f64], [i32]),
"f64.gt": sign([f64, f64], [i32]),
"f64.le": sign([f64, f64], [i32]),
"f64.ge": sign([f64, f64], [i32]),
"i32.clz": sign([i32], [i32]),
"i32.ctz": sign([i32], [i32]),
"i32.popcnt": sign([i32], [i32]),
"i32.add": sign([i32, i32], [i32]),
"i32.sub": sign([i32, i32], [i32]),
"i32.mul": sign([i32, i32], [i32]),
"i32.div_s": sign([i32, i32], [i32]),
"i32.div_u": sign([i32, i32], [i32]),
"i32.rem_s": sign([i32, i32], [i32]),
"i32.rem_u": sign([i32, i32], [i32]),
"i32.and": sign([i32, i32], [i32]),
"i32.or": sign([i32, i32], [i32]),
"i32.xor": sign([i32, i32], [i32]),
"i32.shl": sign([i32, i32], [i32]),
"i32.shr_s": sign([i32, i32], [i32]),
"i32.shr_u": sign([i32, i32], [i32]),
"i32.rotl": sign([i32, i32], [i32]),
"i32.rotr": sign([i32, i32], [i32]),
"i64.clz": sign([i64], [i64]),
"i64.ctz": sign([i64], [i64]),
"i64.popcnt": sign([i64], [i64]),
"i64.add": sign([i64, i64], [i64]),
"i64.sub": sign([i64, i64], [i64]),
"i64.mul": sign([i64, i64], [i64]),
"i64.div_s": sign([i64, i64], [i64]),
"i64.div_u": sign([i64, i64], [i64]),
"i64.rem_s": sign([i64, i64], [i64]),
"i64.rem_u": sign([i64, i64], [i64]),
"i64.and": sign([i64, i64], [i64]),
"i64.or": sign([i64, i64], [i64]),
"i64.xor": sign([i64, i64], [i64]),
"i64.shl": sign([i64, i64], [i64]),
"i64.shr_s": sign([i64, i64], [i64]),
"i64.shr_u": sign([i64, i64], [i64]),
"i64.rotl": sign([i64, i64], [i64]),
"i64.rotr": sign([i64, i64], [i64]),
"f32.abs": sign([f32], [f32]),
"f32.neg": sign([f32], [f32]),
"f32.ceil": sign([f32], [f32]),
"f32.floor": sign([f32], [f32]),
"f32.trunc": sign([f32], [f32]),
"f32.nearest": sign([f32], [f32]),
"f32.sqrt": sign([f32], [f32]),
"f32.add": sign([f32, f32], [f32]),
"f32.sub": sign([f32, f32], [f32]),
"f32.mul": sign([f32, f32], [f32]),
"f32.div": sign([f32, f32], [f32]),
"f32.min": sign([f32, f32], [f32]),
"f32.max": sign([f32, f32], [f32]),
"f32.copysign": sign([f32, f32], [f32]),
"f64.abs": sign([f64], [f64]),
"f64.neg": sign([f64], [f64]),
"f64.ceil": sign([f64], [f64]),
"f64.floor": sign([f64], [f64]),
"f64.trunc": sign([f64], [f64]),
"f64.nearest": sign([f64], [f64]),
"f64.sqrt": sign([f64], [f64]),
"f64.add": sign([f64, f64], [f64]),
"f64.sub": sign([f64, f64], [f64]),
"f64.mul": sign([f64, f64], [f64]),
"f64.div": sign([f64, f64], [f64]),
"f64.min": sign([f64, f64], [f64]),
"f64.max": sign([f64, f64], [f64]),
"f64.copysign": sign([f64, f64], [f64]),
"i32.wrap/i64": sign([i64], [i32]),
"i32.trunc_s/f32": sign([f32], [i32]),
"i32.trunc_u/f32": sign([f32], [i32]),
"i32.trunc_s/f64": sign([f32], [i32]),
"i32.trunc_u/f64": sign([f64], [i32]),
"i64.extend_s/i32": sign([i32], [i64]),
"i64.extend_u/i32": sign([i32], [i64]),
"i64.trunc_s/f32": sign([f32], [i64]),
"i64.trunc_u/f32": sign([f32], [i64]),
"i64.trunc_s/f64": sign([f64], [i64]),
"i64.trunc_u/f64": sign([f64], [i64]),
"f32.convert_s/i32": sign([i32], [f32]),
"f32.convert_u/i32": sign([i32], [f32]),
"f32.convert_s/i64": sign([i64], [f32]),
"f32.convert_u/i64": sign([i64], [f32]),
"f32.demote/f64": sign([f64], [f32]),
"f64.convert_s/i32": sign([i32], [f64]),
"f64.convert_u/i32": sign([i32], [f64]),
"f64.convert_s/i64": sign([i64], [f64]),
"f64.convert_u/i64": sign([i64], [f64]),
"f64.promote/f32": sign([f32], [f64]),
"i32.reinterpret/f32": sign([f32], [i32]),
"i64.reinterpret/f64": sign([f64], [i64]),
"f32.reinterpret/i32": sign([i32], [f32]),
"f64.reinterpret/i64": sign([i64], [f64])
};
var signatures = Object.assign({}, controlInstructions, parametricInstructions, variableInstructions, memoryInstructions, numericInstructions);
exports.signatures = signatures;

View File

@@ -0,0 +1,389 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.moduleContextFromModuleAST = moduleContextFromModuleAST;
exports.ModuleContext = void 0;
var _nodes = require("../../nodes.js");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function moduleContextFromModuleAST(m) {
var moduleContext = new ModuleContext();
if (!(m.type === "Module")) {
throw new Error('m.type === "Module"' + " error: " + (undefined || "unknown"));
}
m.fields.forEach(function (field) {
switch (field.type) {
case "Start":
{
moduleContext.setStart(field.index);
break;
}
case "TypeInstruction":
{
moduleContext.addType(field);
break;
}
case "Func":
{
moduleContext.addFunction(field);
break;
}
case "Global":
{
moduleContext.defineGlobal(field);
break;
}
case "ModuleImport":
{
switch (field.descr.type) {
case "GlobalType":
{
moduleContext.importGlobal(field.descr.valtype, field.descr.mutability);
break;
}
case "Memory":
{
moduleContext.addMemory(field.descr.limits.min, field.descr.limits.max);
break;
}
case "FuncImportDescr":
{
moduleContext.importFunction(field.descr);
break;
}
case "Table":
{
// FIXME(sven): not implemented yet
break;
}
default:
throw new Error("Unsupported ModuleImport of type " + JSON.stringify(field.descr.type));
}
break;
}
case "Memory":
{
moduleContext.addMemory(field.limits.min, field.limits.max);
break;
}
}
});
return moduleContext;
}
/**
* Module context for type checking
*/
var ModuleContext = /*#__PURE__*/function () {
function ModuleContext() {
_classCallCheck(this, ModuleContext);
this.funcs = [];
this.funcsOffsetByIdentifier = [];
this.types = [];
this.globals = [];
this.globalsOffsetByIdentifier = [];
this.mems = []; // Current stack frame
this.locals = [];
this.labels = [];
this["return"] = [];
this.debugName = "unknown";
this.start = null;
}
/**
* Set start segment
*/
_createClass(ModuleContext, [{
key: "setStart",
value: function setStart(index) {
this.start = index.value;
}
/**
* Get start function
*/
}, {
key: "getStart",
value: function getStart() {
return this.start;
}
/**
* Reset the active stack frame
*/
}, {
key: "newContext",
value: function newContext(debugName, expectedResult) {
this.locals = [];
this.labels = [expectedResult];
this["return"] = expectedResult;
this.debugName = debugName;
}
/**
* Functions
*/
}, {
key: "addFunction",
value: function addFunction(func) {
/* eslint-disable */
// $FlowIgnore
var _ref = func.signature || {},
_ref$params = _ref.params,
args = _ref$params === void 0 ? [] : _ref$params,
_ref$results = _ref.results,
result = _ref$results === void 0 ? [] : _ref$results;
/* eslint-enable */
args = args.map(function (arg) {
return arg.valtype;
});
this.funcs.push({
args: args,
result: result
});
if (typeof func.name !== "undefined") {
// $FlowIgnore
this.funcsOffsetByIdentifier[func.name.value] = this.funcs.length - 1;
}
}
}, {
key: "importFunction",
value: function importFunction(funcimport) {
if ((0, _nodes.isSignature)(funcimport.signature)) {
// eslint-disable-next-line prefer-const
var _funcimport$signature = funcimport.signature,
args = _funcimport$signature.params,
result = _funcimport$signature.results;
args = args.map(function (arg) {
return arg.valtype;
});
this.funcs.push({
args: args,
result: result
});
} else {
if (!(0, _nodes.isNumberLiteral)(funcimport.signature)) {
throw new Error('isNumberLiteral(funcimport.signature)' + " error: " + (undefined || "unknown"));
}
var typeId = funcimport.signature.value;
if (!this.hasType(typeId)) {
throw new Error('this.hasType(typeId)' + " error: " + (undefined || "unknown"));
}
var signature = this.getType(typeId);
this.funcs.push({
args: signature.params.map(function (arg) {
return arg.valtype;
}),
result: signature.results
});
}
if (typeof funcimport.id !== "undefined") {
// imports are first, we can assume their index in the array
this.funcsOffsetByIdentifier[funcimport.id.value] = this.funcs.length - 1;
}
}
}, {
key: "hasFunction",
value: function hasFunction(index) {
return typeof this.getFunction(index) !== "undefined";
}
}, {
key: "getFunction",
value: function getFunction(index) {
if (typeof index !== "number") {
throw new Error("getFunction only supported for number index");
}
return this.funcs[index];
}
}, {
key: "getFunctionOffsetByIdentifier",
value: function getFunctionOffsetByIdentifier(name) {
if (!(typeof name === "string")) {
throw new Error('typeof name === "string"' + " error: " + (undefined || "unknown"));
}
return this.funcsOffsetByIdentifier[name];
}
/**
* Labels
*/
}, {
key: "addLabel",
value: function addLabel(result) {
this.labels.unshift(result);
}
}, {
key: "hasLabel",
value: function hasLabel(index) {
return this.labels.length > index && index >= 0;
}
}, {
key: "getLabel",
value: function getLabel(index) {
return this.labels[index];
}
}, {
key: "popLabel",
value: function popLabel() {
this.labels.shift();
}
/**
* Locals
*/
}, {
key: "hasLocal",
value: function hasLocal(index) {
return typeof this.getLocal(index) !== "undefined";
}
}, {
key: "getLocal",
value: function getLocal(index) {
return this.locals[index];
}
}, {
key: "addLocal",
value: function addLocal(type) {
this.locals.push(type);
}
/**
* Types
*/
}, {
key: "addType",
value: function addType(type) {
if (!(type.functype.type === "Signature")) {
throw new Error('type.functype.type === "Signature"' + " error: " + (undefined || "unknown"));
}
this.types.push(type.functype);
}
}, {
key: "hasType",
value: function hasType(index) {
return this.types[index] !== undefined;
}
}, {
key: "getType",
value: function getType(index) {
return this.types[index];
}
/**
* Globals
*/
}, {
key: "hasGlobal",
value: function hasGlobal(index) {
return this.globals.length > index && index >= 0;
}
}, {
key: "getGlobal",
value: function getGlobal(index) {
return this.globals[index].type;
}
}, {
key: "getGlobalOffsetByIdentifier",
value: function getGlobalOffsetByIdentifier(name) {
if (!(typeof name === "string")) {
throw new Error('typeof name === "string"' + " error: " + (undefined || "unknown"));
}
// $FlowIgnore
return this.globalsOffsetByIdentifier[name];
}
}, {
key: "defineGlobal",
value: function defineGlobal(global) {
var type = global.globalType.valtype;
var mutability = global.globalType.mutability;
this.globals.push({
type: type,
mutability: mutability
});
if (typeof global.name !== "undefined") {
// $FlowIgnore
this.globalsOffsetByIdentifier[global.name.value] = this.globals.length - 1;
}
}
}, {
key: "importGlobal",
value: function importGlobal(type, mutability) {
this.globals.push({
type: type,
mutability: mutability
});
}
}, {
key: "isMutableGlobal",
value: function isMutableGlobal(index) {
return this.globals[index].mutability === "var";
}
}, {
key: "isImmutableGlobal",
value: function isImmutableGlobal(index) {
return this.globals[index].mutability === "const";
}
/**
* Memories
*/
}, {
key: "hasMemory",
value: function hasMemory(index) {
return this.mems.length > index && index >= 0;
}
}, {
key: "addMemory",
value: function addMemory(min, max) {
this.mems.push({
min: min,
max: max
});
}
}, {
key: "getMemory",
value: function getMemory(index) {
return this.mems[index];
}
}]);
return ModuleContext;
}();
exports.ModuleContext = ModuleContext;

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transform = transform;
var t = require("../../index"); // func and call_indirect instructions can either define a signature inline, or
// reference a signature, e.g.
//
// ;; inline signature
// (func (result i64)
// (i64.const 2)
// )
// ;; signature reference
// (type (func (result i64)))
// (func (type 0)
// (i64.const 2))
// )
//
// this AST transform denormalises the type references, making all signatures within the module
// inline.
function transform(ast) {
var typeInstructions = [];
t.traverse(ast, {
TypeInstruction: function TypeInstruction(_ref) {
var node = _ref.node;
typeInstructions.push(node);
}
});
if (!typeInstructions.length) {
return;
}
function denormalizeSignature(signature) {
// signature referenced by identifier
if (signature.type === "Identifier") {
var identifier = signature;
var typeInstruction = typeInstructions.find(function (t) {
return t.id.type === identifier.type && t.id.value === identifier.value;
});
if (!typeInstruction) {
throw new Error("A type instruction reference was not found ".concat(JSON.stringify(signature)));
}
return typeInstruction.functype;
} // signature referenced by index
if (signature.type === "NumberLiteral") {
var signatureRef = signature;
var _typeInstruction = typeInstructions[signatureRef.value];
return _typeInstruction.functype;
}
return signature;
}
t.traverse(ast, {
Func: function (_Func) {
function Func(_x) {
return _Func.apply(this, arguments);
}
Func.toString = function () {
return _Func.toString();
};
return Func;
}(function (_ref2) {
var node = _ref2.node;
node.signature = denormalizeSignature(node.signature);
}),
CallIndirectInstruction: function CallIndirectInstruction(_ref3) {
var node = _ref3.node;
node.signature = denormalizeSignature(node.signature);
}
});
}

View File

@@ -0,0 +1,238 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transform = transform;
var _index = require("../../index");
var _astModuleToModuleContext = require("../ast-module-to-module-context");
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; }
// FIXME(sven): do the same with all block instructions, must be more generic here
function newUnexpectedFunction(i) {
return new Error("unknown function at offset: " + i);
}
function transform(ast) {
var module = null;
(0, _index.traverse)(ast, {
Module: function (_Module) {
function Module(_x) {
return _Module.apply(this, arguments);
}
Module.toString = function () {
return _Module.toString();
};
return Module;
}(function (path) {
module = path.node;
})
});
if (module == null) {
throw new Error("Module not foudn in program");
}
var moduleContext = (0, _astModuleToModuleContext.moduleContextFromModuleAST)(module); // Transform the actual instruction in function bodies
(0, _index.traverse)(ast, {
Func: function (_Func) {
function Func(_x2) {
return _Func.apply(this, arguments);
}
Func.toString = function () {
return _Func.toString();
};
return Func;
}(function (path) {
transformFuncPath(path, moduleContext);
}),
Start: function (_Start) {
function Start(_x3) {
return _Start.apply(this, arguments);
}
Start.toString = function () {
return _Start.toString();
};
return Start;
}(function (path) {
var index = path.node.index;
if ((0, _index.isIdentifier)(index) === true) {
var offsetInModule = moduleContext.getFunctionOffsetByIdentifier(index.value);
if (typeof offsetInModule === "undefined") {
throw newUnexpectedFunction(index.value);
} // Replace the index Identifier
// $FlowIgnore: reference?
path.node.index = (0, _index.numberLiteralFromRaw)(offsetInModule);
}
})
});
}
function transformFuncPath(funcPath, moduleContext) {
var funcNode = funcPath.node;
var signature = funcNode.signature;
if (signature.type !== "Signature") {
throw new Error("Function signatures must be denormalised before execution");
}
var params = signature.params; // Add func locals in the context
params.forEach(function (p) {
return moduleContext.addLocal(p.valtype);
});
(0, _index.traverse)(funcNode, {
Instr: function (_Instr) {
function Instr(_x4) {
return _Instr.apply(this, arguments);
}
Instr.toString = function () {
return _Instr.toString();
};
return Instr;
}(function (instrPath) {
var instrNode = instrPath.node;
/**
* Local access
*/
if (instrNode.id === "get_local" || instrNode.id === "set_local" || instrNode.id === "tee_local") {
var _instrNode$args = _slicedToArray(instrNode.args, 1),
firstArg = _instrNode$args[0];
if (firstArg.type === "Identifier") {
var offsetInParams = params.findIndex(function (_ref) {
var id = _ref.id;
return id === firstArg.value;
});
if (offsetInParams === -1) {
throw new Error("".concat(firstArg.value, " not found in ").concat(instrNode.id, ": not declared in func params"));
} // Replace the Identifer node by our new NumberLiteral node
instrNode.args[0] = (0, _index.numberLiteralFromRaw)(offsetInParams);
}
}
/**
* Global access
*/
if (instrNode.id === "get_global" || instrNode.id === "set_global") {
var _instrNode$args2 = _slicedToArray(instrNode.args, 1),
_firstArg = _instrNode$args2[0];
if ((0, _index.isIdentifier)(_firstArg) === true) {
var globalOffset = moduleContext.getGlobalOffsetByIdentifier( // $FlowIgnore: reference?
_firstArg.value);
if (typeof globalOffset === "undefined") {
// $FlowIgnore: reference?
throw new Error("global ".concat(_firstArg.value, " not found in module"));
} // Replace the Identifer node by our new NumberLiteral node
instrNode.args[0] = (0, _index.numberLiteralFromRaw)(globalOffset);
}
}
/**
* Labels lookup
*/
if (instrNode.id === "br") {
var _instrNode$args3 = _slicedToArray(instrNode.args, 1),
_firstArg2 = _instrNode$args3[0];
if ((0, _index.isIdentifier)(_firstArg2) === true) {
// if the labels is not found it is going to be replaced with -1
// which is invalid.
var relativeBlockCount = -1; // $FlowIgnore: reference?
instrPath.findParent(function (_ref2) {
var node = _ref2.node;
if ((0, _index.isBlock)(node)) {
relativeBlockCount++; // $FlowIgnore: reference?
var name = node.label || node.name;
if (_typeof(name) === "object") {
// $FlowIgnore: isIdentifier ensures that
if (name.value === _firstArg2.value) {
// Found it
return false;
}
}
}
if ((0, _index.isFunc)(node)) {
return false;
}
}); // Replace the Identifer node by our new NumberLiteral node
instrNode.args[0] = (0, _index.numberLiteralFromRaw)(relativeBlockCount);
}
}
}),
/**
* Func lookup
*/
CallInstruction: function (_CallInstruction) {
function CallInstruction(_x5) {
return _CallInstruction.apply(this, arguments);
}
CallInstruction.toString = function () {
return _CallInstruction.toString();
};
return CallInstruction;
}(function (_ref3) {
var node = _ref3.node;
var index = node.index;
if ((0, _index.isIdentifier)(index) === true) {
var offsetInModule = moduleContext.getFunctionOffsetByIdentifier(index.value);
if (typeof offsetInModule === "undefined") {
throw newUnexpectedFunction(index.value);
} // Replace the index Identifier
// $FlowIgnore: reference?
node.index = (0, _index.numberLiteralFromRaw)(offsetInModule);
}
})
});
}

View File

@@ -0,0 +1,105 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.traverse = traverse;
var _nodePath = require("./node-path");
var _nodes = require("./nodes");
// recursively walks the AST starting at the given node. The callback is invoked for
// and object that has a 'type' property.
function walk(context, callback) {
var stop = false;
function innerWalk(context, callback) {
if (stop) {
return;
}
var node = context.node;
if (node === undefined) {
console.warn("traversing with an empty context");
return;
}
if (node._deleted === true) {
return;
}
var path = (0, _nodePath.createPath)(context);
callback(node.type, path);
if (path.shouldStop) {
stop = true;
return;
}
Object.keys(node).forEach(function (prop) {
var value = node[prop];
if (value === null || value === undefined) {
return;
}
var valueAsArray = Array.isArray(value) ? value : [value];
valueAsArray.forEach(function (childNode) {
if (typeof childNode.type === "string") {
var childContext = {
node: childNode,
parentKey: prop,
parentPath: path,
shouldStop: false,
inList: Array.isArray(value)
};
innerWalk(childContext, callback);
}
});
});
}
innerWalk(context, callback);
}
var noop = function noop() {};
function traverse(node, visitors) {
var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop;
var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop;
Object.keys(visitors).forEach(function (visitor) {
if (!_nodes.nodeAndUnionTypes.includes(visitor)) {
throw new Error("Unexpected visitor ".concat(visitor));
}
});
var context = {
node: node,
inList: false,
shouldStop: false,
parentPath: null,
parentKey: null
};
walk(context, function (type, path) {
if (typeof visitors[type] === "function") {
before(type, path);
visitors[type](path);
after(type, path);
}
var unionTypes = _nodes.unionTypesMap[type];
if (!unionTypes) {
throw new Error("Unexpected node type ".concat(type));
}
unionTypes.forEach(function (unionType) {
if (typeof visitors[unionType] === "function") {
before(unionType, path);
visitors[unionType](path);
after(unionType, path);
}
});
});
}

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1,315 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isAnonymous = isAnonymous;
exports.getSectionMetadata = getSectionMetadata;
exports.getSectionMetadatas = getSectionMetadatas;
exports.sortSectionMetadata = sortSectionMetadata;
exports.orderedInsertNode = orderedInsertNode;
exports.assertHasLoc = assertHasLoc;
exports.getEndOfSection = getEndOfSection;
exports.shiftLoc = shiftLoc;
exports.shiftSection = shiftSection;
exports.signatureForOpcode = signatureForOpcode;
exports.getUniqueNameGenerator = getUniqueNameGenerator;
exports.getStartByteOffset = getStartByteOffset;
exports.getEndByteOffset = getEndByteOffset;
exports.getFunctionBeginingByteOffset = getFunctionBeginingByteOffset;
exports.getEndBlockByteOffset = getEndBlockByteOffset;
exports.getStartBlockByteOffset = getStartBlockByteOffset;
var _signatures = require("./signatures");
var _traverse = require("./traverse");
var _helperWasmBytecode = _interopRequireWildcard(require("@webassemblyjs/helper-wasm-bytecode"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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; }
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 isAnonymous(ident) {
return ident.raw === "";
}
function getSectionMetadata(ast, name) {
var section;
(0, _traverse.traverse)(ast, {
SectionMetadata: function (_SectionMetadata) {
function SectionMetadata(_x) {
return _SectionMetadata.apply(this, arguments);
}
SectionMetadata.toString = function () {
return _SectionMetadata.toString();
};
return SectionMetadata;
}(function (_ref) {
var node = _ref.node;
if (node.section === name) {
section = node;
}
})
});
return section;
}
function getSectionMetadatas(ast, name) {
var sections = [];
(0, _traverse.traverse)(ast, {
SectionMetadata: function (_SectionMetadata2) {
function SectionMetadata(_x2) {
return _SectionMetadata2.apply(this, arguments);
}
SectionMetadata.toString = function () {
return _SectionMetadata2.toString();
};
return SectionMetadata;
}(function (_ref2) {
var node = _ref2.node;
if (node.section === name) {
sections.push(node);
}
})
});
return sections;
}
function sortSectionMetadata(m) {
if (m.metadata == null) {
console.warn("sortSectionMetadata: no metadata to sort");
return;
} // $FlowIgnore
m.metadata.sections.sort(function (a, b) {
var aId = _helperWasmBytecode["default"].sections[a.section];
var bId = _helperWasmBytecode["default"].sections[b.section];
if (typeof aId !== "number" || typeof bId !== "number") {
throw new Error("Section id not found");
}
return aId - bId;
});
}
function orderedInsertNode(m, n) {
assertHasLoc(n);
var didInsert = false;
if (n.type === "ModuleExport") {
m.fields.push(n);
return;
}
m.fields = m.fields.reduce(function (acc, field) {
var fieldEndCol = Infinity;
if (field.loc != null) {
// $FlowIgnore
fieldEndCol = field.loc.end.column;
} // $FlowIgnore: assertHasLoc ensures that
if (didInsert === false && n.loc.start.column < fieldEndCol) {
didInsert = true;
acc.push(n);
}
acc.push(field);
return acc;
}, []); // Handles empty modules or n is the last element
if (didInsert === false) {
m.fields.push(n);
}
}
function assertHasLoc(n) {
if (n.loc == null || n.loc.start == null || n.loc.end == null) {
throw new Error("Internal failure: node (".concat(JSON.stringify(n.type), ") has no location information"));
}
}
function getEndOfSection(s) {
assertHasLoc(s.size);
return s.startOffset + s.size.value + (s.size.loc.end.column - s.size.loc.start.column);
}
function shiftLoc(node, delta) {
// $FlowIgnore
node.loc.start.column += delta; // $FlowIgnore
node.loc.end.column += delta;
}
function shiftSection(ast, node, delta) {
if (node.type !== "SectionMetadata") {
throw new Error("Can not shift node " + JSON.stringify(node.type));
}
node.startOffset += delta;
if (_typeof(node.size.loc) === "object") {
shiftLoc(node.size, delta);
} // Custom sections doesn't have vectorOfSize
if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") {
shiftLoc(node.vectorOfSize, delta);
}
var sectionName = node.section; // shift node locations within that section
(0, _traverse.traverse)(ast, {
Node: function Node(_ref3) {
var node = _ref3.node;
var section = (0, _helperWasmBytecode.getSectionForNode)(node);
if (section === sectionName && _typeof(node.loc) === "object") {
shiftLoc(node, delta);
}
}
});
}
function signatureForOpcode(object, name) {
var opcodeName = name;
if (object !== undefined && object !== "") {
opcodeName = object + "." + name;
}
var sign = _signatures.signatures[opcodeName];
if (sign == undefined) {
// TODO: Uncomment this when br_table and others has been done
//throw new Error("Invalid opcode: "+opcodeName);
return [object, object];
}
return sign[0];
}
function getUniqueNameGenerator() {
var inc = {};
return function () {
var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp";
if (!(prefix in inc)) {
inc[prefix] = 0;
} else {
inc[prefix] = inc[prefix] + 1;
}
return prefix + "_" + inc[prefix];
};
}
function getStartByteOffset(n) {
// $FlowIgnore
if (typeof n.loc === "undefined" || typeof n.loc.start === "undefined") {
throw new Error( // $FlowIgnore
"Can not get byte offset without loc informations, node: " + String(n.id));
}
return n.loc.start.column;
}
function getEndByteOffset(n) {
// $FlowIgnore
if (typeof n.loc === "undefined" || typeof n.loc.end === "undefined") {
throw new Error("Can not get byte offset without loc informations, node: " + n.type);
}
return n.loc.end.column;
}
function getFunctionBeginingByteOffset(n) {
if (!(n.body.length > 0)) {
throw new Error('n.body.length > 0' + " error: " + (undefined || "unknown"));
}
var _n$body = _slicedToArray(n.body, 1),
firstInstruction = _n$body[0];
return getStartByteOffset(firstInstruction);
}
function getEndBlockByteOffset(n) {
// $FlowIgnore
if (!(n.instr.length > 0 || n.body.length > 0)) {
throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown"));
}
var lastInstruction;
if (n.instr) {
// $FlowIgnore
lastInstruction = n.instr[n.instr.length - 1];
}
if (n.body) {
// $FlowIgnore
lastInstruction = n.body[n.body.length - 1];
}
if (!(_typeof(lastInstruction) === "object")) {
throw new Error('typeof lastInstruction === "object"' + " error: " + (undefined || "unknown"));
}
// $FlowIgnore
return getStartByteOffset(lastInstruction);
}
function getStartBlockByteOffset(n) {
// $FlowIgnore
if (!(n.instr.length > 0 || n.body.length > 0)) {
throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown"));
}
var fistInstruction;
if (n.instr) {
// $FlowIgnore
var _n$instr = _slicedToArray(n.instr, 1);
fistInstruction = _n$instr[0];
}
if (n.body) {
// $FlowIgnore
var _n$body2 = _slicedToArray(n.body, 1);
fistInstruction = _n$body2[0];
}
if (!(_typeof(fistInstruction) === "object")) {
throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown"));
}
// $FlowIgnore
return getStartByteOffset(fistInstruction);
}

View File

@@ -0,0 +1,219 @@
const definitions = require("../src/definitions");
const flatMap = require("array.prototype.flatmap");
const {
typeSignature,
iterateProps,
mapProps,
filterProps,
unique,
} = require("./util");
const stdout = process.stdout;
const jsTypes = ["string", "number", "boolean"];
const quote = (value) => `"${value}"`;
function params(fields) {
const optionalDefault = (field) =>
field.default ? ` = ${field.default}` : "";
return mapProps(fields)
.map((field) => `${typeSignature(field)}${optionalDefault(field)}`)
.join(",");
}
function assertParamType({ assertNodeType, array, name, type }) {
if (array) {
// TODO - assert contents of array?
return `assert(typeof ${name} === "object" && typeof ${name}.length !== "undefined")\n`;
} else {
if (jsTypes.includes(type)) {
return `assert(
typeof ${name} === "${type}",
"Argument ${name} must be of type ${type}, given: " + typeof ${name}
)`;
}
if (assertNodeType === true) {
return `assert(
${name}.type === "${type}",
"Argument ${name} must be of type ${type}, given: " + ${name}.type
)`;
}
return "";
}
}
function assertParam(meta) {
const paramAssertion = assertParamType(meta);
if (paramAssertion === "") {
return "";
}
if (meta.maybe || meta.optional) {
return `
if (${meta.name} !== null && ${meta.name} !== undefined) {
${paramAssertion};
}
`;
} else {
return paramAssertion;
}
}
function assertParams(fields) {
return mapProps(fields).map(assertParam).join("\n");
}
function buildObject(typeDef) {
const optionalField = (meta) => {
if (meta.array) {
// omit optional array properties if the constructor function was supplied
// with an empty array
return `
if (typeof ${meta.name} !== "undefined" && ${meta.name}.length > 0) {
node.${meta.name} = ${meta.name};
}
`;
} else if (meta.type === "Object") {
// omit optional object properties if they have no keys
return `
if (typeof ${meta.name} !== "undefined" && Object.keys(${meta.name}).length !== 0) {
node.${meta.name} = ${meta.name};
}
`;
} else if (meta.type === "boolean") {
// omit optional boolean properties if they are not true
return `
if (${meta.name} === true) {
node.${meta.name} = true;
}
`;
} else {
return `
if (typeof ${meta.name} !== "undefined") {
node.${meta.name} = ${meta.name};
}
`;
}
};
const fields = mapProps(typeDef.fields)
.filter((f) => !f.optional && !f.constant)
.map((f) => f.name);
const constants = mapProps(typeDef.fields)
.filter((f) => f.constant)
.map((f) => `${f.name}: "${f.value}"`);
return `
const node: ${typeDef.flowTypeName || typeDef.name} = {
type: "${typeDef.name}",
${constants.concat(fields).join(",")}
}
${mapProps(typeDef.fields)
.filter((f) => f.optional)
.map(optionalField)
.join("")}
`;
}
function lowerCamelCase(name) {
return name.substring(0, 1).toLowerCase() + name.substring(1);
}
function generate() {
stdout.write(`
// @flow
// THIS FILE IS AUTOGENERATED
// see scripts/generateNodeUtils.js
import { assert } from "mamacro";
function isTypeOf(t: string) {
return (n: Node) => n.type === t;
}
function assertTypeOf(t: string) {
return (n: Node) => assert(n.type === t);
}
`);
// Node builders
iterateProps(definitions, (typeDefinition) => {
stdout.write(`
export function ${lowerCamelCase(typeDefinition.name)} (
${params(filterProps(typeDefinition.fields, (f) => !f.constant))}
): ${typeDefinition.name} {
${assertParams(filterProps(typeDefinition.fields, (f) => !f.constant))}
${buildObject(typeDefinition)}
return node;
}
`);
});
// Node testers
iterateProps(definitions, (typeDefinition) => {
stdout.write(`
export const is${typeDefinition.name}: ((n: Node) => boolean) =
isTypeOf("${typeDefinition.name}");
`);
});
// Node union type testers
const unionTypes = unique(
flatMap(
mapProps(definitions).filter((d) => d.unionType),
(d) => d.unionType
)
);
unionTypes.forEach((unionType) => {
stdout.write(
`
export const is${unionType} = (node: Node): boolean => ` +
mapProps(definitions)
.filter((d) => d.unionType && d.unionType.includes(unionType))
.map((d) => `is${d.name}(node) `)
.join("||") +
";\n\n"
);
});
// Node assertion
iterateProps(definitions, (typeDefinition) => {
stdout.write(`
export const assert${typeDefinition.name}: ((n: Node) => void) =
assertTypeOf("${typeDefinition.name}");
`);
});
// a map from node type to its set of union types
stdout.write(
`
export const unionTypesMap = {` +
mapProps(definitions)
.filter((d) => d.unionType)
.map((t) => `"${t.name}": [${t.unionType.map(quote).join(",")}]\n`) +
`};
`
);
// an array of all node and union types
stdout.write(
`
export const nodeAndUnionTypes = [` +
mapProps(definitions)
.map((t) => `"${t.name}"`)
.concat(unionTypes.map(quote))
.join(",") +
`];`
);
}
generate();

View File

@@ -0,0 +1,48 @@
const definitions = require("../src/definitions");
const flatMap = require("array.prototype.flatmap");
const { typeSignature, mapProps, iterateProps, unique } = require("./util");
const stdout = process.stdout;
function params(fields) {
return mapProps(fields).map(typeSignature).join(",");
}
function generate() {
stdout.write(`
// @flow
/* eslint no-unused-vars: off */
// THIS FILE IS AUTOGENERATED
// see scripts/generateTypeDefinitions.js
`);
// generate union types
const unionTypes = unique(
flatMap(
mapProps(definitions).filter((d) => d.unionType),
(d) => d.unionType
)
);
unionTypes.forEach((unionType) => {
stdout.write(
`type ${unionType} = ` +
mapProps(definitions)
.filter((d) => d.unionType && d.unionType.includes(unionType))
.map((d) => d.name)
.join("|") +
";\n\n"
);
});
// generate the type definitions
iterateProps(definitions, (typeDef) => {
stdout.write(`type ${typeDef.name} = {
...BaseNode,
type: "${typeDef.name}",
${params(typeDef.fields)}
};\n\n`);
});
}
generate();

View File

@@ -0,0 +1,38 @@
function iterateProps(obj, iterator) {
Object.keys(obj).forEach((key) => iterator({ ...obj[key], name: key }));
}
function mapProps(obj) {
return Object.keys(obj).map((key) => ({ ...obj[key], name: key }));
}
function filterProps(obj, filter) {
const ret = {};
Object.keys(obj).forEach((key) => {
if (filter(obj[key])) {
ret[key] = obj[key];
}
});
return ret;
}
function typeSignature(meta) {
const type = meta.array ? `Array<${meta.type}>` : meta.type;
if (meta.optional) {
return `${meta.name}?: ${type}`;
} else if (meta.maybe) {
return `${meta.name}: ?${type}`;
} else {
return `${meta.name}: ${type}`;
}
}
const unique = (items) => Array.from(new Set(items));
module.exports = {
iterateProps,
mapProps,
filterProps,
typeSignature,
unique,
};

View File

@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = parse;
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,78 @@
"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.LinkError = exports.CompileError = exports.RuntimeError = void 0;
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 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));
exports.RuntimeError = RuntimeError;
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));
exports.CompileError = CompileError;
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));
exports.LinkError = LinkError;

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,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overrideBytesInBuffer = overrideBytesInBuffer;
exports.makeBuffer = makeBuffer;
exports.fromHexdump = fromHexdump;
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; }
function concatUint8Arrays() {
for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {
arrays[_key] = arguments[_key];
}
var totalLength = arrays.reduce(function (a, b) {
return a + b.length;
}, 0);
var result = new Uint8Array(totalLength);
var offset = 0;
for (var _i = 0, _arrays = arrays; _i < _arrays.length; _i++) {
var arr = _arrays[_i];
if (arr instanceof Uint8Array === false) {
throw new Error("arr must be of type Uint8Array");
}
result.set(arr, offset);
offset += arr.length;
}
return result;
}
function overrideBytesInBuffer(buffer, startLoc, endLoc, newBytes) {
var beforeBytes = buffer.slice(0, startLoc);
var afterBytes = buffer.slice(endLoc, buffer.length); // replacement is empty, we can omit it
if (newBytes.length === 0) {
return concatUint8Arrays(beforeBytes, afterBytes);
}
var replacement = Uint8Array.from(newBytes);
return concatUint8Arrays(beforeBytes, replacement, afterBytes);
}
function makeBuffer() {
for (var _len2 = arguments.length, splitedBytes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
splitedBytes[_key2] = arguments[_key2];
}
// $FlowIgnore
var bytes = [].concat.apply([], splitedBytes);
return new Uint8Array(bytes).buffer;
}
function fromHexdump(str) {
var lines = str.split("\n"); // remove any leading left whitespace
lines = lines.map(function (line) {
return line.trim();
});
var bytes = lines.reduce(function (acc, line) {
var cols = line.split(" "); // remove the offset, left column
cols.shift();
cols = cols.filter(function (x) {
return x !== "";
});
var bytes = cols.map(function (x) {
return parseInt(x, 16);
});
acc.push.apply(acc, _toConsumableArray(bytes));
return acc;
}, []);
return new Uint8Array(bytes);
}

View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parse32F = parse32F;
exports.parse64F = parse64F;
exports.parse32I = parse32I;
exports.parseU32 = parseU32;
exports.parse64I = parse64I;
exports.isInfLiteral = isInfLiteral;
exports.isNanLiteral = isNanLiteral;
var _long2 = _interopRequireDefault(require("@xtuc/long"));
var _floatingPointHexParser = _interopRequireDefault(require("@webassemblyjs/floating-point-hex-parser"));
var _helperApiError = require("@webassemblyjs/helper-api-error");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function parse32F(sourceString) {
if (isHexLiteral(sourceString)) {
return (0, _floatingPointHexParser["default"])(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);
}
function parse64F(sourceString) {
if (isHexLiteral(sourceString)) {
return (0, _floatingPointHexParser["default"])(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 (0, _floatingPointHexParser["default"])(sourceString);
}
return parseFloat(sourceString);
}
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;
}
function parseU32(sourceString) {
var value = parse32I(sourceString);
if (value < 0) {
throw new _helperApiError.CompileError("Illegal value for u32: " + sourceString);
}
return value;
}
function parse64I(sourceString) {
// $FlowIgnore
var _long;
if (isHexLiteral(sourceString)) {
_long = _long2["default"].fromString(sourceString, false, 16);
} else if (isDecimalExponentLiteral(sourceString)) {
throw new Error("This number literal format is yet to be implemented.");
} else {
_long = _long2["default"].fromString(sourceString);
}
return {
high: _long.high,
low: _long.low
};
}
var NAN_WORD = /^\+?-?nan/;
var INF_WORD = /^\+?-?inf/;
function isInfLiteral(sourceString) {
return INF_WORD.test(sourceString.toLowerCase());
}
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,430 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getSectionForNode", {
enumerable: true,
get: function get() {
return _section.getSectionForNode;
}
});
exports["default"] = void 0;
var _section = require("./section");
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;
});
var _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
};
exports["default"] = _default;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getSectionForNode = getSectionForNode;
function getSectionForNode(n) {
switch (n.type) {
case "ModuleImport":
return "import";
case "CallInstruction":
case "CallIndirectInstruction":
case "Func":
case "Instr":
return "code";
case "ModuleExport":
return "export";
case "Start":
return "start";
case "TypeInstruction":
return "type";
case "IndexInFuncSection":
return "func";
case "Global":
return "global";
// No section
default:
return;
}
}

View File

@@ -0,0 +1,123 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createEmptySection = createEmptySection;
var _wasmGen = require("@webassemblyjs/wasm-gen");
var _helperBuffer = require("@webassemblyjs/helper-buffer");
var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));
var t = _interopRequireWildcard(require("@webassemblyjs/ast"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
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 findLastSection(ast, forSection) {
var targetSectionId = _helperWasmBytecode["default"].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 = _helperWasmBytecode["default"].sections[section.section];
if (targetSectionId > lastId && targetSectionId < sectionId) {
return lastSection;
}
lastId = sectionId;
lastSection = section;
}
return lastSection;
}
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 = (0, _wasmGen.encodeNode)(sectionMetadata);
uint8Buffer = (0, _helperBuffer.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,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "resizeSectionByteSize", {
enumerable: true,
get: function get() {
return _resize.resizeSectionByteSize;
}
});
Object.defineProperty(exports, "resizeSectionVecSize", {
enumerable: true,
get: function get() {
return _resize.resizeSectionVecSize;
}
});
Object.defineProperty(exports, "createEmptySection", {
enumerable: true,
get: function get() {
return _create.createEmptySection;
}
});
Object.defineProperty(exports, "removeSections", {
enumerable: true,
get: function get() {
return _remove.removeSections;
}
});
var _resize = require("./resize");
var _create = require("./create");
var _remove = require("./remove");

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.removeSections = removeSections;
var _ast = require("@webassemblyjs/ast");
var _helperBuffer = require("@webassemblyjs/helper-buffer");
function removeSections(ast, uint8Buffer, section) {
var sectionMetadatas = (0, _ast.getSectionMetadatas)(ast, section);
if (sectionMetadatas.length === 0) {
throw new Error("Section metadata not found");
}
return sectionMetadatas.reverse().reduce(function (uint8Buffer, sectionMetadata) {
var startsIncludingId = sectionMetadata.startOffset - 1;
var ends = section === "start" ? sectionMetadata.size.loc.end.column + 1 : sectionMetadata.startOffset + sectionMetadata.size.value + 1;
var delta = -(ends - startsIncludingId);
/**
* update AST
*/
// Once we hit our section every that is after needs to be shifted by the delta
var encounteredSection = false;
(0, _ast.traverse)(ast, {
SectionMetadata: function SectionMetadata(path) {
if (path.node.section === section) {
encounteredSection = true;
return path.remove();
}
if (encounteredSection === true) {
(0, _ast.shiftSection)(ast, path.node, delta);
}
}
}); // replacement is nothing
var replacement = [];
return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, startsIncludingId, ends, replacement);
}, uint8Buffer);
}

View File

@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resizeSectionByteSize = resizeSectionByteSize;
exports.resizeSectionVecSize = resizeSectionVecSize;
var _wasmGen = require("@webassemblyjs/wasm-gen");
var _ast = require("@webassemblyjs/ast");
var _helperBuffer = require("@webassemblyjs/helper-buffer");
function resizeSectionByteSize(ast, uint8Buffer, section, deltaBytes) {
var sectionMetadata = (0, _ast.getSectionMetadata)(ast, section);
if (typeof sectionMetadata === "undefined") {
throw new Error("Section metadata not found");
}
if (typeof sectionMetadata.size.loc === "undefined") {
throw new Error("SectionMetadata " + section + " has no loc");
} // keep old node location to be overriden
var start = sectionMetadata.size.loc.start.column;
var end = sectionMetadata.size.loc.end.column;
var newSectionSize = sectionMetadata.size.value + deltaBytes;
var newBytes = (0, _wasmGen.encodeU32)(newSectionSize);
/**
* update AST
*/
sectionMetadata.size.value = newSectionSize;
var oldu32EncodedLen = end - start;
var newu32EncodedLen = newBytes.length; // the new u32 has a different encoded length
if (newu32EncodedLen !== oldu32EncodedLen) {
var deltaInSizeEncoding = newu32EncodedLen - oldu32EncodedLen;
sectionMetadata.size.loc.end.column = start + newu32EncodedLen;
deltaBytes += deltaInSizeEncoding; // move the vec size pointer size the section size is now smaller
sectionMetadata.vectorOfSize.loc.start.column += deltaInSizeEncoding;
sectionMetadata.vectorOfSize.loc.end.column += deltaInSizeEncoding;
} // Once we hit our section every that is after needs to be shifted by the delta
var encounteredSection = false;
(0, _ast.traverse)(ast, {
SectionMetadata: function SectionMetadata(path) {
if (path.node.section === section) {
encounteredSection = true;
return;
}
if (encounteredSection === true) {
(0, _ast.shiftSection)(ast, path.node, deltaBytes);
}
}
});
return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newBytes);
}
function resizeSectionVecSize(ast, uint8Buffer, section, deltaElements) {
var sectionMetadata = (0, _ast.getSectionMetadata)(ast, section);
if (typeof sectionMetadata === "undefined") {
throw new Error("Section metadata not found");
}
if (typeof sectionMetadata.vectorOfSize.loc === "undefined") {
throw new Error("SectionMetadata " + section + " has no loc");
} // Section has no vector
if (sectionMetadata.vectorOfSize.value === -1) {
return uint8Buffer;
} // keep old node location to be overriden
var start = sectionMetadata.vectorOfSize.loc.start.column;
var end = sectionMetadata.vectorOfSize.loc.end.column;
var newValue = sectionMetadata.vectorOfSize.value + deltaElements;
var newBytes = (0, _wasmGen.encodeU32)(newValue); // Update AST
sectionMetadata.vectorOfSize.value = newValue;
sectionMetadata.vectorOfSize.loc.end.column = start + newBytes.length;
return (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newBytes);
}

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,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,246 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.alloc = alloc;
exports.free = free;
exports.resize = resize;
exports.readInt = readInt;
exports.readUInt = readUInt;
exports.writeInt64 = writeInt64;
exports.writeUInt64 = writeUInt64;
// 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.
*/
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.
*/
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).
*/
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.
*/
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.
*/
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.
*/
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.
*/
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,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.decodeInt64 = decodeInt64;
exports.decodeUInt64 = decodeUInt64;
exports.decodeInt32 = decodeInt32;
exports.decodeUInt32 = decodeUInt32;
exports.encodeU32 = encodeU32;
exports.encodeI32 = encodeI32;
exports.encodeI64 = encodeI64;
exports.MAX_NUMBER_OF_BYTE_U64 = exports.MAX_NUMBER_OF_BYTE_U32 = void 0;
var _leb = _interopRequireDefault(require("./leb"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* According to https://webassembly.github.io/spec/core/binary/values.html#binary-int
* max = ceil(32/7)
*/
var MAX_NUMBER_OF_BYTE_U32 = 5;
/**
* According to https://webassembly.github.io/spec/core/binary/values.html#binary-int
* max = ceil(64/7)
*/
exports.MAX_NUMBER_OF_BYTE_U32 = MAX_NUMBER_OF_BYTE_U32;
var MAX_NUMBER_OF_BYTE_U64 = 10;
exports.MAX_NUMBER_OF_BYTE_U64 = MAX_NUMBER_OF_BYTE_U64;
function decodeInt64(encodedBuffer, index) {
return _leb["default"].decodeInt64(encodedBuffer, index);
}
function decodeUInt64(encodedBuffer, index) {
return _leb["default"].decodeUInt64(encodedBuffer, index);
}
function decodeInt32(encodedBuffer, index) {
return _leb["default"].decodeInt32(encodedBuffer, index);
}
function decodeUInt32(encodedBuffer, index) {
return _leb["default"].decodeUInt32(encodedBuffer, index);
}
function encodeU32(v) {
return _leb["default"].encodeUInt32(v);
}
function encodeI32(v) {
return _leb["default"].encodeInt32(v);
}
function encodeI64(v) {
return _leb["default"].encodeInt64(v);
}

View File

@@ -0,0 +1,347 @@
// Copyright 2012 The Obvious Corporation.
/*
* leb: LEB128 utilities.
*/
/*
* Modules used
*/
"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["default"] = void 0;
var _long = _interopRequireDefault(require("@xtuc/long"));
var bits = _interopRequireWildcard(require("./bits"));
var bufs = _interopRequireWildcard(require("./bufs"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/*
* Module variables
*/
/** The minimum possible 32-bit signed int. */
var MIN_INT32 = -0x80000000;
/** The maximum possible 32-bit signed int. */
var MAX_INT32 = 0x7fffffff;
/** The maximum possible 32-bit unsigned int. */
var MAX_UINT32 = 0xffffffff;
/** The minimum possible 64-bit signed int. */
// const MIN_INT64 = -0x8000000000000000;
/**
* The maximum possible 64-bit signed int that is representable as a
* JavaScript number.
*/
// const MAX_INT64 = 0x7ffffffffffffc00;
/**
* The maximum possible 64-bit unsigned int that is representable as a
* JavaScript number.
*/
// const MAX_UINT64 = 0xfffffffffffff800;
/*
* Helper functions
*/
/**
* Determines the number of bits required to encode the number
* represented in the given buffer as a signed value. The buffer is
* taken to represent a signed number in little-endian form.
*
* The number of bits to encode is the (zero-based) bit number of the
* highest-order non-sign-matching bit, plus two. For example:
*
* 11111011 01110101
* high low
*
* The sign bit here is 1 (that is, it's a negative number). The highest
* bit number that doesn't match the sign is bit #10 (where the lowest-order
* bit is bit #0). So, we have to encode at least 12 bits total.
*
* As a special degenerate case, the numbers 0 and -1 each require just one bit.
*/
function signedBitCount(buffer) {
return bits.highOrder(bits.getSign(buffer) ^ 1, buffer) + 2;
}
/**
* Determines the number of bits required to encode the number
* represented in the given buffer as an unsigned value. The buffer is
* taken to represent an unsigned number in little-endian form.
*
* The number of bits to encode is the (zero-based) bit number of the
* highest-order 1 bit, plus one. For example:
*
* 00011000 01010011
* high low
*
* The highest-order 1 bit here is bit #12 (where the lowest-order bit
* is bit #0). So, we have to encode at least 13 bits total.
*
* As a special degenerate case, the number 0 requires 1 bit.
*/
function unsignedBitCount(buffer) {
var result = bits.highOrder(1, buffer) + 1;
return result ? result : 1;
}
/**
* Common encoder for both signed and unsigned ints. This takes a
* bigint-ish buffer, returning an LEB128-encoded buffer.
*/
function encodeBufferCommon(buffer, signed) {
var signBit;
var bitCount;
if (signed) {
signBit = bits.getSign(buffer);
bitCount = signedBitCount(buffer);
} else {
signBit = 0;
bitCount = unsignedBitCount(buffer);
}
var byteCount = Math.ceil(bitCount / 7);
var result = bufs.alloc(byteCount);
for (var i = 0; i < byteCount; i++) {
var payload = bits.extract(buffer, i * 7, 7, signBit);
result[i] = payload | 0x80;
} // Mask off the top bit of the last byte, to indicate the end of the
// encoding.
result[byteCount - 1] &= 0x7f;
return result;
}
/**
* Gets the byte-length of the value encoded in the given buffer at
* the given index.
*/
function encodedLength(encodedBuffer, index) {
var result = 0;
while (encodedBuffer[index + result] >= 0x80) {
result++;
}
result++; // to account for the last byte
if (index + result > encodedBuffer.length) {// FIXME(sven): seems to cause false positives
// throw new Error("integer representation too long");
}
return result;
}
/**
* Common decoder for both signed and unsigned ints. This takes an
* LEB128-encoded buffer, returning a bigint-ish buffer.
*/
function decodeBufferCommon(encodedBuffer, index, signed) {
index = index === undefined ? 0 : index;
var length = encodedLength(encodedBuffer, index);
var bitLength = length * 7;
var byteLength = Math.ceil(bitLength / 8);
var result = bufs.alloc(byteLength);
var outIndex = 0;
while (length > 0) {
bits.inject(result, outIndex, 7, encodedBuffer[index]);
outIndex += 7;
index++;
length--;
}
var signBit;
var signByte;
if (signed) {
// Sign-extend the last byte.
var lastByte = result[byteLength - 1];
var endBit = outIndex % 8;
if (endBit !== 0) {
var shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints.
lastByte = result[byteLength - 1] = lastByte << shift >> shift & 0xff;
}
signBit = lastByte >> 7;
signByte = signBit * 0xff;
} else {
signBit = 0;
signByte = 0;
} // Slice off any superfluous bytes, that is, ones that add no meaningful
// bits (because the value would be the same if they were removed).
while (byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit)) {
byteLength--;
}
result = bufs.resize(result, byteLength);
return {
value: result,
nextIndex: index
};
}
/*
* Exported bindings
*/
function encodeIntBuffer(buffer) {
return encodeBufferCommon(buffer, true);
}
function decodeIntBuffer(encodedBuffer, index) {
return decodeBufferCommon(encodedBuffer, index, true);
}
function encodeInt32(num) {
var buf = new Uint8Array(4);
buf[0] = num & 0xff;
buf[1] = num >> 8 & 0xff;
buf[2] = num >> 16 & 0xff;
buf[3] = num >> 24 & 0xff;
var result = encodeIntBuffer(buf);
return result;
}
function decodeInt32(encodedBuffer, index) {
var result = decodeIntBuffer(encodedBuffer, index);
var parsed = bufs.readInt(result.value);
var value = parsed.value;
bufs.free(result.value);
if (value < MIN_INT32 || value > MAX_INT32) {
throw new Error("integer too large");
}
return {
value: value,
nextIndex: result.nextIndex
};
}
function encodeInt64(num) {
var buf = bufs.alloc(8);
bufs.writeInt64(num, buf);
var result = encodeIntBuffer(buf);
bufs.free(buf);
return result;
}
function decodeInt64(encodedBuffer, index) {
var result = decodeIntBuffer(encodedBuffer, index); // sign-extend if necessary
var length = result.value.length;
if (result.value[length - 1] >> 7) {
result.value = bufs.resize(result.value, 8);
result.value.fill(255, length);
}
var value = _long["default"].fromBytesLE(result.value, false);
bufs.free(result.value);
return {
value: value,
nextIndex: result.nextIndex,
lossy: false
};
}
function encodeUIntBuffer(buffer) {
return encodeBufferCommon(buffer, false);
}
function decodeUIntBuffer(encodedBuffer, index) {
return decodeBufferCommon(encodedBuffer, index, false);
}
function encodeUInt32(num) {
var buf = new Uint8Array(4);
buf[0] = num & 0xff;
buf[1] = num >> 8 & 0xff;
buf[2] = num >> 16 & 0xff;
buf[3] = num >> 24 & 0xff;
var result = encodeUIntBuffer(buf);
return result;
}
function decodeUInt32(encodedBuffer, index) {
var result = decodeUIntBuffer(encodedBuffer, index);
var parsed = bufs.readUInt(result.value);
var value = parsed.value;
bufs.free(result.value);
if (value > MAX_UINT32) {
throw new Error("integer too large");
}
return {
value: value,
nextIndex: result.nextIndex
};
}
function encodeUInt64(num) {
var buf = bufs.alloc(8);
bufs.writeUInt64(num, buf);
var result = encodeUIntBuffer(buf);
bufs.free(buf);
return result;
}
function decodeUInt64(encodedBuffer, index) {
var result = decodeUIntBuffer(encodedBuffer, index);
var value = _long["default"].fromBytesLE(result.value, true);
bufs.free(result.value);
return {
value: value,
nextIndex: result.nextIndex,
lossy: false
};
}
var _default = {
decodeInt32: decodeInt32,
decodeInt64: decodeInt64,
decodeIntBuffer: decodeIntBuffer,
decodeUInt32: decodeUInt32,
decodeUInt64: decodeUInt64,
decodeUIntBuffer: decodeUIntBuffer,
encodeInt32: encodeInt32,
encodeInt64: encodeInt64,
encodeIntBuffer: encodeIntBuffer,
encodeUInt32: encodeUInt32,
encodeUInt64: encodeUInt64,
encodeUIntBuffer: encodeUIntBuffer
};
exports["default"] = _default;

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,67 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.encode = encode;
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 _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function con(n) {
return 0x80 | n & 0x3f;
}
function encode(str) {
var arr = str.split("").map(function (x) {
return x.charCodeAt(0);
});
return _encode(arr);
}
function _encode(arr) {
if (arr.length === 0) {
return [];
}
var _arr = _toArray(arr),
n = _arr[0],
ns = _arr.slice(1);
if (n < 0) {
throw new Error("utf8");
}
if (n < 0x80) {
return [n].concat(_toConsumableArray(_encode(ns)));
}
if (n < 0x800) {
return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns)));
}
if (n < 0x10000) {
return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns)));
}
if (n < 0x110000) {
return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns)));
}
throw new Error("utf8");
}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "decode", {
enumerable: true,
get: function get() {
return _decoder.decode;
}
});
Object.defineProperty(exports, "encode", {
enumerable: true,
get: function get() {
return _encoder.encode;
}
});
var _decoder = require("./decoder");
var _encoder = require("./encoder");

View File

@@ -0,0 +1,318 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.applyOperations = applyOperations;
var _wasmGen = require("@webassemblyjs/wasm-gen");
var _encoder = require("@webassemblyjs/wasm-gen/lib/encoder");
var _ast = require("@webassemblyjs/ast");
var _helperWasmSection = require("@webassemblyjs/helper-wasm-section");
var _helperBuffer = require("@webassemblyjs/helper-buffer");
var _helperWasmBytecode = require("@webassemblyjs/helper-wasm-bytecode");
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; }
function shiftLocNodeByDelta(node, delta) {
(0, _ast.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;
(0, _ast.assertHasLoc)(oldNode);
var sectionName = (0, _helperWasmBytecode.getSectionForNode)(newNode);
var replacementByteArray = (0, _wasmGen.encodeNode)(newNode);
/**
* Replace new node as bytes
*/
uint8Buffer = (0, _helperBuffer.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
(0, _ast.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
(0, _ast.assertHasLoc)(node);
var oldNodeSize = (0, _wasmGen.encodeNode)(oldNode).length;
var bodySizeDeltaBytes = replacementByteArray.length - oldNodeSize;
if (bodySizeDeltaBytes !== 0) {
var newValue = node.metadata.bodySize + bodySizeDeltaBytes;
var newByteArray = (0, _encoder.encodeU32)(newValue); // function body size byte
// FIXME(sven): only handles one byte u32
var start = node.loc.start.column;
var end = start + 1;
uint8Buffer = (0, _helperBuffer.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
(0, _ast.assertHasLoc)(node);
var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node);
if (sectionName === "start") {
var sectionMetadata = (0, _ast.getSectionMetadata)(ast, "start");
/**
* The start section only contains one element,
* we need to remove the whole section
*/
uint8Buffer = (0, _helperWasmSection.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 = (0, _helperBuffer.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 = (0, _helperWasmBytecode.getSectionForNode)(node);
var sectionMetadata = (0, _ast.getSectionMetadata)(ast, sectionName); // Section doesn't exists, we create an empty one
if (typeof sectionMetadata === "undefined") {
var res = (0, _helperWasmSection.createEmptySection)(ast, uint8Buffer, sectionName);
uint8Buffer = res.uint8Buffer;
sectionMetadata = res.sectionMetadata;
}
/**
* check that the expressions were ended
*/
if ((0, _ast.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 ((0, _ast.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 = (0, _wasmGen.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 = (0, _ast.getEndOfSection)(sectionMetadata);
var end = start;
/**
* Update section
*/
var deltaBytes = newByteArray.length;
uint8Buffer = (0, _helperBuffer.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") {
(0, _ast.orderedInsertNode)(ast.body[0], node);
}
return {
uint8Buffer: uint8Buffer,
deltaBytes: deltaBytes,
deltaElements: deltaElements
};
}
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 = (0, _helperWasmBytecode.getSectionForNode)(op.node);
break;
case "delete":
state = applyDelete(ast, uint8Buffer, op.node);
sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node);
break;
case "add":
state = applyAdd(ast, uint8Buffer, op.node);
sectionName = (0, _helperWasmBytecode.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 = (0, _helperWasmSection.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 = (0, _helperWasmSection.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,134 @@
"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.edit = edit;
exports.editWithAST = editWithAST;
exports.add = add;
exports.addWithAST = addWithAST;
var _wasmParser = require("@webassemblyjs/wasm-parser");
var _ast = require("@webassemblyjs/ast");
var _clone = require("@webassemblyjs/ast/lib/clone");
var _wasmOpt = require("@webassemblyjs/wasm-opt");
var _helperWasmBytecode = _interopRequireWildcard(require("@webassemblyjs/helper-wasm-bytecode"));
var _apply = require("./apply");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
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 hashNode(node) {
return JSON.stringify(node);
}
function preprocess(ab) {
var optBin = (0, _wasmOpt.shrinkPaddedLEB128)(new Uint8Array(ab));
return optBin.buffer;
}
function sortBySectionOrder(nodes) {
var originalOrder = new Map();
var _iterator = _createForOfIteratorHelper(nodes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var node = _step.value;
originalOrder.set(node, originalOrder.size);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
nodes.sort(function (a, b) {
var sectionA = (0, _helperWasmBytecode.getSectionForNode)(a);
var sectionB = (0, _helperWasmBytecode.getSectionForNode)(b);
var aId = _helperWasmBytecode["default"].sections[sectionA];
var bId = _helperWasmBytecode["default"].sections[sectionB];
if (typeof aId !== "number" || typeof bId !== "number") {
throw new Error("Section id not found");
}
if (aId === bId) {
// $FlowIgnore originalOrder is filled for all nodes
return originalOrder.get(a) - originalOrder.get(b);
}
return aId - bId;
});
}
function edit(ab, visitors) {
ab = preprocess(ab);
var ast = (0, _wasmParser.decode)(ab);
return editWithAST(ast, ab, visitors);
}
function editWithAST(ast, ab, visitors) {
var operations = [];
var uint8Buffer = new Uint8Array(ab);
var nodeBefore;
function before(type, path) {
nodeBefore = (0, _clone.cloneNode)(path.node);
}
function after(type, path) {
if (path.node._deleted === true) {
operations.push({
kind: "delete",
node: path.node
}); // $FlowIgnore
} else if (hashNode(nodeBefore) !== hashNode(path.node)) {
operations.push({
kind: "update",
oldNode: nodeBefore,
node: path.node
});
}
}
(0, _ast.traverse)(ast, visitors, before, after);
uint8Buffer = (0, _apply.applyOperations)(ast, uint8Buffer, operations);
return uint8Buffer.buffer;
}
function add(ab, newNodes) {
ab = preprocess(ab);
var ast = (0, _wasmParser.decode)(ab);
return addWithAST(ast, ab, newNodes);
}
function addWithAST(ast, ab, newNodes) {
// Sort nodes by insertion order
sortBySectionOrder(newNodes);
var uint8Buffer = new Uint8Array(ab); // Map node into operations
var operations = newNodes.map(function (n) {
return {
kind: "add",
node: n
};
});
uint8Buffer = (0, _apply.applyOperations)(ast, uint8Buffer, operations);
return uint8Buffer.buffer;
}

View File

@@ -0,0 +1,372 @@
"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.encodeVersion = encodeVersion;
exports.encodeHeader = encodeHeader;
exports.encodeU32 = encodeU32;
exports.encodeI32 = encodeI32;
exports.encodeI64 = encodeI64;
exports.encodeVec = encodeVec;
exports.encodeValtype = encodeValtype;
exports.encodeMutability = encodeMutability;
exports.encodeUTF8Vec = encodeUTF8Vec;
exports.encodeLimits = encodeLimits;
exports.encodeModuleImport = encodeModuleImport;
exports.encodeSectionMetadata = encodeSectionMetadata;
exports.encodeCallInstruction = encodeCallInstruction;
exports.encodeCallIndirectInstruction = encodeCallIndirectInstruction;
exports.encodeModuleExport = encodeModuleExport;
exports.encodeTypeInstruction = encodeTypeInstruction;
exports.encodeInstr = encodeInstr;
exports.encodeStringLiteral = encodeStringLiteral;
exports.encodeGlobal = encodeGlobal;
exports.encodeFuncBody = encodeFuncBody;
exports.encodeIndexInFuncSection = encodeIndexInFuncSection;
exports.encodeElem = encodeElem;
var leb = _interopRequireWildcard(require("@webassemblyjs/leb128"));
var ieee754 = _interopRequireWildcard(require("@webassemblyjs/ieee754"));
var utf8 = _interopRequireWildcard(require("@webassemblyjs/utf8"));
var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));
var _index = require("../index");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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; }
function assertNotIdentifierNode(n) {
if (n.type === "Identifier") {
throw new Error("Unsupported node Identifier");
}
}
function encodeVersion(v) {
var bytes = _helperWasmBytecode["default"].moduleVersion;
bytes[0] = v;
return bytes;
}
function encodeHeader() {
return _helperWasmBytecode["default"].magicModuleHeader;
}
function encodeU32(v) {
var uint8view = new Uint8Array(leb.encodeU32(v));
var array = _toConsumableArray(uint8view);
return array;
}
function encodeI32(v) {
var uint8view = new Uint8Array(leb.encodeI32(v));
var array = _toConsumableArray(uint8view);
return array;
}
function encodeI64(v) {
var uint8view = new Uint8Array(leb.encodeI64(v));
var array = _toConsumableArray(uint8view);
return array;
}
function encodeVec(elements) {
var size = encodeU32(elements.length);
return [].concat(_toConsumableArray(size), _toConsumableArray(elements));
}
function encodeValtype(v) {
var _byte = _helperWasmBytecode["default"].valtypesByString[v];
if (typeof _byte === "undefined") {
throw new Error("Unknown valtype: " + v);
}
return parseInt(_byte, 10);
}
function encodeMutability(v) {
var _byte2 = _helperWasmBytecode["default"].globalTypesByString[v];
if (typeof _byte2 === "undefined") {
throw new Error("Unknown mutability: " + v);
}
return parseInt(_byte2, 10);
}
function encodeUTF8Vec(str) {
return encodeVec(utf8.encode(str));
}
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;
}
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;
}
function encodeSectionMetadata(n) {
var out = [];
var sectionId = _helperWasmBytecode["default"].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;
}
function encodeCallInstruction(n) {
var out = [];
assertNotIdentifierNode(n.index);
out.push(0x10); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.index.value)));
return out;
}
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;
}
function encodeModuleExport(n) {
var out = [];
assertNotIdentifierNode(n.descr.id);
var exportTypeByteString = _helperWasmBytecode["default"].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;
}
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;
}
function encodeInstr(n) {
var out = [];
var instructionName = n.id;
if (typeof n.object === "string") {
instructionName = "".concat(n.object, ".").concat(String(n.id));
}
var byteString = _helperWasmBytecode["default"].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 = (0, _index.encodeNode)(instr);
out.push.apply(out, _toConsumableArray(n));
});
return out;
}
function encodeStringLiteral(n) {
return encodeUTF8Vec(n.value);
}
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;
}
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;
}
function encodeIndexInFuncSection(n) {
assertNotIdentifierNode(n.index); // $FlowIgnore
return encodeU32(n.index.value);
}
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,68 @@
"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.encodeNode = encodeNode;
exports.encodeU32 = void 0;
var encoder = _interopRequireWildcard(require("./encoder"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function encodeNode(n) {
switch (n.type) {
case "ModuleImport":
// $FlowIgnore: ModuleImport ensure that the node is well formated
return encoder.encodeModuleImport(n);
case "SectionMetadata":
// $FlowIgnore: SectionMetadata ensure that the node is well formated
return encoder.encodeSectionMetadata(n);
case "CallInstruction":
// $FlowIgnore: SectionMetadata ensure that the node is well formated
return encoder.encodeCallInstruction(n);
case "CallIndirectInstruction":
// $FlowIgnore: SectionMetadata ensure that the node is well formated
return encoder.encodeCallIndirectInstruction(n);
case "TypeInstruction":
return encoder.encodeTypeInstruction(n);
case "Instr":
// $FlowIgnore
return encoder.encodeInstr(n);
case "ModuleExport":
// $FlowIgnore: SectionMetadata ensure that the node is well formated
return encoder.encodeModuleExport(n);
case "Global":
// $FlowIgnore
return encoder.encodeGlobal(n);
case "Func":
return encoder.encodeFuncBody(n);
case "IndexInFuncSection":
return encoder.encodeIndexInFuncSection(n);
case "StringLiteral":
return encoder.encodeStringLiteral(n);
case "Elem":
return encoder.encodeElem(n);
default:
throw new Error("Unsupported encoding for node of type: " + JSON.stringify(n.type));
}
}
var encodeU32 = encoder.encodeU32;
exports.encodeU32 = encodeU32;

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,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.shrinkPaddedLEB128 = shrinkPaddedLEB128;
var _ast = require("@webassemblyjs/ast");
var _encoder = require("@webassemblyjs/wasm-gen/lib/encoder");
var _helperBuffer = require("@webassemblyjs/helper-buffer");
function shiftFollowingSections(ast, _ref, deltaInSizeEncoding) {
var section = _ref.section;
// Once we hit our section every that is after needs to be shifted by the delta
var encounteredSection = false;
(0, _ast.traverse)(ast, {
SectionMetadata: function SectionMetadata(path) {
if (path.node.section === section) {
encounteredSection = true;
return;
}
if (encounteredSection === true) {
(0, _ast.shiftSection)(ast, path.node, deltaInSizeEncoding);
}
}
});
}
function shrinkPaddedLEB128(ast, uint8Buffer) {
(0, _ast.traverse)(ast, {
SectionMetadata: function SectionMetadata(_ref2) {
var node = _ref2.node;
/**
* Section size
*/
{
var newu32Encoded = (0, _encoder.encodeU32)(node.size.value);
var newu32EncodedLen = newu32Encoded.length;
var start = node.size.loc.start.column;
var end = node.size.loc.end.column;
var oldu32EncodedLen = end - start;
if (newu32EncodedLen !== oldu32EncodedLen) {
var deltaInSizeEncoding = oldu32EncodedLen - newu32EncodedLen;
uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newu32Encoded);
shiftFollowingSections(ast, node, -deltaInSizeEncoding);
}
}
}
});
return uint8Buffer;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,262 @@
"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.decode = decode;
var decoder = _interopRequireWildcard(require("./decoder"));
var t = _interopRequireWildcard(require("@webassemblyjs/ast"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/**
* TODO(sven): I added initial props, but we should rather fix
* https://github.com/xtuc/webassemblyjs/issues/405
*/
var defaultDecoderOpts = {
dump: false,
ignoreCodeSection: false,
ignoreDataSection: false,
ignoreCustomNameSection: false
}; // traverses the AST, locating function name metadata, which is then
// used to update index-based identifiers with function names
function restoreFunctionNames(ast) {
var functionNames = [];
t.traverse(ast, {
FunctionNameMetadata: function FunctionNameMetadata(_ref) {
var node = _ref.node;
functionNames.push({
name: node.value,
index: node.index
});
}
});
if (functionNames.length === 0) {
return;
}
t.traverse(ast, {
Func: function (_Func) {
function Func(_x) {
return _Func.apply(this, arguments);
}
Func.toString = function () {
return _Func.toString();
};
return Func;
}(function (_ref2) {
var node = _ref2.node;
// $FlowIgnore
var nodeName = node.name;
var indexBasedFunctionName = nodeName.value;
var index = Number(indexBasedFunctionName.replace("func_", ""));
var functionName = functionNames.find(function (f) {
return f.index === index;
});
if (functionName) {
var oldValue = nodeName.value;
nodeName.value = functionName.name; // $FlowIgnore
nodeName.numeric = oldValue; // $FlowIgnore
delete nodeName.raw;
}
}),
// Also update the reference in the export
ModuleExport: function (_ModuleExport) {
function ModuleExport(_x2) {
return _ModuleExport.apply(this, arguments);
}
ModuleExport.toString = function () {
return _ModuleExport.toString();
};
return ModuleExport;
}(function (_ref3) {
var node = _ref3.node;
if (node.descr.exportType === "Func") {
// $FlowIgnore
var nodeName = node.descr.id;
var index = nodeName.value;
var functionName = functionNames.find(function (f) {
return f.index === index;
});
if (functionName) {
node.descr.id = t.identifier(functionName.name);
}
}
}),
ModuleImport: function (_ModuleImport) {
function ModuleImport(_x3) {
return _ModuleImport.apply(this, arguments);
}
ModuleImport.toString = function () {
return _ModuleImport.toString();
};
return ModuleImport;
}(function (_ref4) {
var node = _ref4.node;
if (node.descr.type === "FuncImportDescr") {
// $FlowIgnore
var indexBasedFunctionName = node.descr.id;
var index = Number(indexBasedFunctionName.replace("func_", ""));
var functionName = functionNames.find(function (f) {
return f.index === index;
});
if (functionName) {
// $FlowIgnore
node.descr.id = t.identifier(functionName.name);
}
}
}),
CallInstruction: function (_CallInstruction) {
function CallInstruction(_x4) {
return _CallInstruction.apply(this, arguments);
}
CallInstruction.toString = function () {
return _CallInstruction.toString();
};
return CallInstruction;
}(function (nodePath) {
var node = nodePath.node;
var index = node.index.value;
var functionName = functionNames.find(function (f) {
return f.index === index;
});
if (functionName) {
var oldValue = node.index;
node.index = t.identifier(functionName.name);
node.numeric = oldValue; // $FlowIgnore
delete node.raw;
}
})
});
}
function restoreLocalNames(ast) {
var localNames = [];
t.traverse(ast, {
LocalNameMetadata: function LocalNameMetadata(_ref5) {
var node = _ref5.node;
localNames.push({
name: node.value,
localIndex: node.localIndex,
functionIndex: node.functionIndex
});
}
});
if (localNames.length === 0) {
return;
}
t.traverse(ast, {
Func: function (_Func2) {
function Func(_x5) {
return _Func2.apply(this, arguments);
}
Func.toString = function () {
return _Func2.toString();
};
return Func;
}(function (_ref6) {
var node = _ref6.node;
var signature = node.signature;
if (signature.type !== "Signature") {
return;
} // $FlowIgnore
var nodeName = node.name;
var indexBasedFunctionName = nodeName.value;
var functionIndex = Number(indexBasedFunctionName.replace("func_", ""));
signature.params.forEach(function (param, paramIndex) {
var paramName = localNames.find(function (f) {
return f.localIndex === paramIndex && f.functionIndex === functionIndex;
});
if (paramName && paramName.name !== "") {
param.id = paramName.name;
}
});
})
});
}
function restoreModuleName(ast) {
t.traverse(ast, {
ModuleNameMetadata: function (_ModuleNameMetadata) {
function ModuleNameMetadata(_x6) {
return _ModuleNameMetadata.apply(this, arguments);
}
ModuleNameMetadata.toString = function () {
return _ModuleNameMetadata.toString();
};
return ModuleNameMetadata;
}(function (moduleNameMetadataPath) {
// update module
t.traverse(ast, {
Module: function (_Module) {
function Module(_x7) {
return _Module.apply(this, arguments);
}
Module.toString = function () {
return _Module.toString();
};
return Module;
}(function (_ref7) {
var node = _ref7.node;
var name = moduleNameMetadataPath.node.value; // compatiblity with wast-parser
if (name === "") {
name = null;
}
node.id = name;
})
});
})
});
}
function decode(buf, customOpts) {
var opts = Object.assign({}, defaultDecoderOpts, customOpts);
var ast = decoder.decode(buf, opts);
if (opts.ignoreCustomNameSection === false) {
restoreFunctionNames(ast);
restoreLocalNames(ast);
restoreModuleName(ast);
}
return ast;
}

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1,931 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.print = print;
var _ast = require("@webassemblyjs/ast");
var _long = _interopRequireDefault(require("@xtuc/long"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
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; }
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
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 ((0, _ast.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 && (0, _ast.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 && (0, _ast.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" && (0, _ast.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 && (0, _ast.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 && (0, _ast.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 && (0, _ast.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["default"](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" && (0, _ast.isAnonymous)(n) === false) {
out += printIdentifier(n);
}
if (n.type === "ValtypeLiteral") {
out += n.name;
}
if (n.type === "FloatLiteral") {
out += printFloatLiteral(n);
}
if ((0, _ast.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;
}