AsyncWebAssemblyParser.js
1.9 KB
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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const t = require("@webassemblyjs/ast");
const { decode } = require("@webassemblyjs/wasm-parser");
const Parser = require("../Parser");
const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
const decoderOpts = {
ignoreCodeSection: true,
ignoreDataSection: true,
// this will avoid having to lookup with identifiers in the ModuleContext
ignoreCustomNameSection: true
};
class WebAssemblyParser extends Parser {
/**
* @param {{}=} options parser options
*/
constructor(options) {
super();
this.hooks = Object.freeze({});
this.options = options;
}
/**
* @param {string | Buffer | PreparsedAst} source the source to parse
* @param {ParserState} state the parser state
* @returns {ParserState} the parser state
*/
parse(source, state) {
if (!Buffer.isBuffer(source)) {
throw new Error("WebAssemblyParser input must be a Buffer");
}
// flag it as async module
state.module.buildInfo.strict = true;
state.module.buildMeta.exportsType = "namespace";
state.module.buildMeta.async = true;
// parse it
const program = decode(source, decoderOpts);
const module = program.body[0];
/** @type {Array<string>} */
const exports = [];
t.traverse(module, {
ModuleExport({ node }) {
exports.push(node.name);
},
ModuleImport({ node }) {
const dep = new WebAssemblyImportDependency(
node.module,
node.name,
node.descr,
false
);
state.module.addDependency(dep);
}
});
state.module.addDependency(new StaticExportsDependency(exports, false));
return state;
}
}
module.exports = WebAssemblyParser;