AsyncWebAssemblyParser.js 1.8 KB

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