-
Notifications
You must be signed in to change notification settings - Fork 90
/
index.js
108 lines (83 loc) · 2.51 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// @flow
import { decode } from "@webassemblyjs/wasm-parser";
import { traverse } from "@webassemblyjs/ast";
import { cloneNode } from "@webassemblyjs/ast/lib/clone";
import { shrinkPaddedLEB128 } from "@webassemblyjs/wasm-opt";
import constants from "@webassemblyjs/helper-wasm-bytecode";
import { applyOperations } from "./apply";
function hashNode(node: Node): string {
return JSON.stringify(node);
}
function preprocess(ab: ArrayBuffer): ArrayBuffer {
const optBin = shrinkPaddedLEB128(new Uint8Array(ab));
return optBin.buffer;
}
function sortBySectionOrder(nodes: Array<Node>) {
nodes.sort((a, b) => {
const sectionA = constants.getSectionForNode(a);
const sectionB = constants.getSectionForNode(b);
const aId = constants.sections[sectionA];
const bId = constants.sections[sectionB];
if (typeof aId !== "number" || typeof bId !== "number") {
throw new Error("Section id not found");
}
// $FlowIgnore ensured above
return aId > bId;
});
}
export function edit(ab: ArrayBuffer, visitors: Object): ArrayBuffer {
ab = preprocess(ab);
const ast = decode(ab);
return editWithAST(ast, ab, visitors);
}
export function editWithAST(
ast: Program,
ab: ArrayBuffer,
visitors: Object
): ArrayBuffer {
const operations: Array<Operation> = [];
let uint8Buffer = new Uint8Array(ab);
let nodeBefore;
function before(type: string, path: NodePath<*>) {
nodeBefore = cloneNode(path.node);
}
function after(type: string, path: NodePath<*>) {
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
});
}
}
traverse(ast, visitors, before, after);
uint8Buffer = applyOperations(ast, uint8Buffer, operations);
return uint8Buffer.buffer;
}
export function add(ab: ArrayBuffer, newNodes: Array<Node>): ArrayBuffer {
ab = preprocess(ab);
const ast = decode(ab);
return addWithAST(ast, ab, newNodes);
}
export function addWithAST(
ast: Program,
ab: ArrayBuffer,
newNodes: Array<Node>
): ArrayBuffer {
// Sort nodes by insertion order
sortBySectionOrder(newNodes);
let uint8Buffer = new Uint8Array(ab);
// Map node into operations
const operations = newNodes.map(n => ({
kind: "add",
node: n
}));
uint8Buffer = applyOperations(ast, uint8Buffer, operations);
return uint8Buffer.buffer;
}