1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const t = require("@webassemblyjs/ast");
|
---|
9 | const { decode } = require("@webassemblyjs/wasm-parser");
|
---|
10 | const Parser = require("../Parser");
|
---|
11 | const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
|
---|
12 | const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
|
---|
13 |
|
---|
14 | /** @typedef {import("../Parser").ParserState} ParserState */
|
---|
15 | /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
|
---|
16 |
|
---|
17 | const decoderOpts = {
|
---|
18 | ignoreCodeSection: true,
|
---|
19 | ignoreDataSection: true,
|
---|
20 |
|
---|
21 | // this will avoid having to lookup with identifiers in the ModuleContext
|
---|
22 | ignoreCustomNameSection: true
|
---|
23 | };
|
---|
24 |
|
---|
25 | class WebAssemblyParser extends Parser {
|
---|
26 | constructor(options) {
|
---|
27 | super();
|
---|
28 | this.hooks = Object.freeze({});
|
---|
29 | this.options = options;
|
---|
30 | }
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * @param {string | Buffer | PreparsedAst} source the source to parse
|
---|
34 | * @param {ParserState} state the parser state
|
---|
35 | * @returns {ParserState} the parser state
|
---|
36 | */
|
---|
37 | parse(source, state) {
|
---|
38 | if (!Buffer.isBuffer(source)) {
|
---|
39 | throw new Error("WebAssemblyParser input must be a Buffer");
|
---|
40 | }
|
---|
41 |
|
---|
42 | // flag it as async module
|
---|
43 | state.module.buildInfo.strict = true;
|
---|
44 | state.module.buildMeta.exportsType = "namespace";
|
---|
45 | state.module.buildMeta.async = true;
|
---|
46 |
|
---|
47 | // parse it
|
---|
48 | const program = decode(source, decoderOpts);
|
---|
49 | const module = program.body[0];
|
---|
50 |
|
---|
51 | const exports = [];
|
---|
52 | t.traverse(module, {
|
---|
53 | ModuleExport({ node }) {
|
---|
54 | exports.push(node.name);
|
---|
55 | },
|
---|
56 |
|
---|
57 | ModuleImport({ node }) {
|
---|
58 | const dep = new WebAssemblyImportDependency(
|
---|
59 | node.module,
|
---|
60 | node.name,
|
---|
61 | node.descr,
|
---|
62 | false
|
---|
63 | );
|
---|
64 |
|
---|
65 | state.module.addDependency(dep);
|
---|
66 | }
|
---|
67 | });
|
---|
68 |
|
---|
69 | state.module.addDependency(new StaticExportsDependency(exports, false));
|
---|
70 |
|
---|
71 | return state;
|
---|
72 | }
|
---|
73 | }
|
---|
74 |
|
---|
75 | module.exports = WebAssemblyParser;
|
---|