65881867632d356c701be8e3bdf1bf42de67900fd794e1ebcd7e756794e44e8e2f0e90fa693cec66decfb36f86464bfc1f85d79a18d856ed1b4502a47a3c9a 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var t = require("../../index"); // func and call_indirect instructions can either define a signature inline, or
  2. // reference a signature, e.g.
  3. //
  4. // ;; inline signature
  5. // (func (result i64)
  6. // (i64.const 2)
  7. // )
  8. // ;; signature reference
  9. // (type (func (result i64)))
  10. // (func (type 0)
  11. // (i64.const 2))
  12. // )
  13. //
  14. // this AST transform denormalises the type references, making all signatures within the module
  15. // inline.
  16. export function transform(ast) {
  17. var typeInstructions = [];
  18. t.traverse(ast, {
  19. TypeInstruction: function TypeInstruction(_ref) {
  20. var node = _ref.node;
  21. typeInstructions.push(node);
  22. }
  23. });
  24. if (!typeInstructions.length) {
  25. return;
  26. }
  27. function denormalizeSignature(signature) {
  28. // signature referenced by identifier
  29. if (signature.type === "Identifier") {
  30. var identifier = signature;
  31. var typeInstruction = typeInstructions.find(function (t) {
  32. return t.id.type === identifier.type && t.id.value === identifier.value;
  33. });
  34. if (!typeInstruction) {
  35. throw new Error("A type instruction reference was not found ".concat(JSON.stringify(signature)));
  36. }
  37. return typeInstruction.functype;
  38. } // signature referenced by index
  39. if (signature.type === "NumberLiteral") {
  40. var signatureRef = signature;
  41. var _typeInstruction = typeInstructions[signatureRef.value];
  42. return _typeInstruction.functype;
  43. }
  44. return signature;
  45. }
  46. t.traverse(ast, {
  47. Func: function (_Func) {
  48. function Func(_x) {
  49. return _Func.apply(this, arguments);
  50. }
  51. Func.toString = function () {
  52. return _Func.toString();
  53. };
  54. return Func;
  55. }(function (_ref2) {
  56. var node = _ref2.node;
  57. node.signature = denormalizeSignature(node.signature);
  58. }),
  59. CallIndirectInstruction: function CallIndirectInstruction(_ref3) {
  60. var node = _ref3.node;
  61. node.signature = denormalizeSignature(node.signature);
  62. }
  63. });
  64. }