WebAssemblyJavascriptGenerator.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const { UsageState } = require("../ExportsInfo");
  8. const Generator = require("../Generator");
  9. const InitFragment = require("../InitFragment");
  10. const RuntimeGlobals = require("../RuntimeGlobals");
  11. const Template = require("../Template");
  12. const ModuleDependency = require("../dependencies/ModuleDependency");
  13. const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency");
  14. const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
  15. /** @typedef {import("webpack-sources").Source} Source */
  16. /** @typedef {import("../Dependency")} Dependency */
  17. /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
  18. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  19. /** @typedef {import("../NormalModule")} NormalModule */
  20. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  21. const TYPES = new Set(["webassembly"]);
  22. class WebAssemblyJavascriptGenerator extends Generator {
  23. /**
  24. * @param {NormalModule} module fresh module
  25. * @returns {Set<string>} available types (do not mutate)
  26. */
  27. getTypes(module) {
  28. return TYPES;
  29. }
  30. /**
  31. * @param {NormalModule} module the module
  32. * @param {string=} type source type
  33. * @returns {number} estimate size of the module
  34. */
  35. getSize(module, type) {
  36. return 95 + module.dependencies.length * 5;
  37. }
  38. /**
  39. * @param {NormalModule} module module for which the code should be generated
  40. * @param {GenerateContext} generateContext context for generate
  41. * @returns {Source} generated code
  42. */
  43. generate(module, generateContext) {
  44. const {
  45. runtimeTemplate,
  46. moduleGraph,
  47. chunkGraph,
  48. runtimeRequirements,
  49. runtime
  50. } = generateContext;
  51. /** @type {InitFragment[]} */
  52. const initFragments = [];
  53. const exportsInfo = moduleGraph.getExportsInfo(module);
  54. let needExportsCopy = false;
  55. const importedModules = new Map();
  56. const initParams = [];
  57. let index = 0;
  58. for (const dep of module.dependencies) {
  59. const moduleDep =
  60. dep && dep instanceof ModuleDependency ? dep : undefined;
  61. if (moduleGraph.getModule(dep)) {
  62. let importData = importedModules.get(moduleGraph.getModule(dep));
  63. if (importData === undefined) {
  64. importedModules.set(
  65. moduleGraph.getModule(dep),
  66. (importData = {
  67. importVar: `m${index}`,
  68. index,
  69. request: (moduleDep && moduleDep.userRequest) || undefined,
  70. names: new Set(),
  71. reexports: []
  72. })
  73. );
  74. index++;
  75. }
  76. if (dep instanceof WebAssemblyImportDependency) {
  77. importData.names.add(dep.name);
  78. if (dep.description.type === "GlobalType") {
  79. const exportName = dep.name;
  80. const importedModule = moduleGraph.getModule(dep);
  81. if (importedModule) {
  82. const usedName = moduleGraph
  83. .getExportsInfo(importedModule)
  84. .getUsedName(exportName, runtime);
  85. if (usedName) {
  86. initParams.push(
  87. runtimeTemplate.exportFromImport({
  88. moduleGraph,
  89. module: importedModule,
  90. request: dep.request,
  91. importVar: importData.importVar,
  92. originModule: module,
  93. exportName: dep.name,
  94. asiSafe: true,
  95. isCall: false,
  96. callContext: null,
  97. defaultInterop: true,
  98. initFragments,
  99. runtime,
  100. runtimeRequirements
  101. })
  102. );
  103. }
  104. }
  105. }
  106. }
  107. if (dep instanceof WebAssemblyExportImportedDependency) {
  108. importData.names.add(dep.name);
  109. const usedName = moduleGraph
  110. .getExportsInfo(module)
  111. .getUsedName(dep.exportName, runtime);
  112. if (usedName) {
  113. runtimeRequirements.add(RuntimeGlobals.exports);
  114. const exportProp = `${module.exportsArgument}[${JSON.stringify(
  115. usedName
  116. )}]`;
  117. const defineStatement = Template.asString([
  118. `${exportProp} = ${runtimeTemplate.exportFromImport({
  119. moduleGraph,
  120. module: moduleGraph.getModule(dep),
  121. request: dep.request,
  122. importVar: importData.importVar,
  123. originModule: module,
  124. exportName: dep.name,
  125. asiSafe: true,
  126. isCall: false,
  127. callContext: null,
  128. defaultInterop: true,
  129. initFragments,
  130. runtime,
  131. runtimeRequirements
  132. })};`,
  133. `if(WebAssembly.Global) ${exportProp} = ` +
  134. `new WebAssembly.Global({ value: ${JSON.stringify(
  135. dep.valueType
  136. )} }, ${exportProp});`
  137. ]);
  138. importData.reexports.push(defineStatement);
  139. needExportsCopy = true;
  140. }
  141. }
  142. }
  143. }
  144. const importsCode = Template.asString(
  145. Array.from(
  146. importedModules,
  147. ([module, { importVar, request, reexports }]) => {
  148. const importStatement = runtimeTemplate.importStatement({
  149. module,
  150. chunkGraph,
  151. request,
  152. importVar,
  153. originModule: module,
  154. runtimeRequirements
  155. });
  156. return importStatement[0] + importStatement[1] + reexports.join("\n");
  157. }
  158. )
  159. );
  160. const copyAllExports =
  161. exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused &&
  162. !needExportsCopy;
  163. // need these globals
  164. runtimeRequirements.add(RuntimeGlobals.module);
  165. runtimeRequirements.add(RuntimeGlobals.moduleId);
  166. runtimeRequirements.add(RuntimeGlobals.wasmInstances);
  167. if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
  168. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  169. runtimeRequirements.add(RuntimeGlobals.exports);
  170. }
  171. if (!copyAllExports) {
  172. runtimeRequirements.add(RuntimeGlobals.exports);
  173. }
  174. // create source
  175. const source = new RawSource(
  176. [
  177. '"use strict";',
  178. "// Instantiate WebAssembly module",
  179. `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`,
  180. exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused
  181. ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});`
  182. : "",
  183. // this must be before import for circular dependencies
  184. "// export exports from WebAssembly module",
  185. copyAllExports
  186. ? `${module.moduleArgument}.exports = wasmExports;`
  187. : "for(var name in wasmExports) " +
  188. `if(name) ` +
  189. `${module.exportsArgument}[name] = wasmExports[name];`,
  190. "// exec imports from WebAssembly module (for esm order)",
  191. importsCode,
  192. "",
  193. "// exec wasm module",
  194. `wasmExports[""](${initParams.join(", ")})`
  195. ].join("\n")
  196. );
  197. return InitFragment.addToSource(source, initFragments, generateContext);
  198. }
  199. }
  200. module.exports = WebAssemblyJavascriptGenerator;