source: imaps-frontend/node_modules/@webassemblyjs/wasm-parser/lib/decoder.js@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

  • Property mode set to 100644
File size: 60.1 KB
RevLine 
[79a0317]1"use strict";
2
3function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.decode = decode;
9
10var _helperApiError = require("@webassemblyjs/helper-api-error");
11
12var ieee754 = _interopRequireWildcard(require("@webassemblyjs/ieee754"));
13
14var utf8 = _interopRequireWildcard(require("@webassemblyjs/utf8"));
15
16var t = _interopRequireWildcard(require("@webassemblyjs/ast"));
17
18var _leb = require("@webassemblyjs/leb128");
19
20var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));
21
22function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
23
24function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
25
26function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
27
28function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
29
30function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
31
32function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
33
34function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
35
36function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
37
38function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
39
40function toHex(n) {
41 return "0x" + Number(n).toString(16);
42}
43
44function byteArrayEq(l, r) {
45 if (l.length !== r.length) {
46 return false;
47 }
48
49 for (var i = 0; i < l.length; i++) {
50 if (l[i] !== r[i]) {
51 return false;
52 }
53 }
54
55 return true;
56}
57
58function decode(ab, opts) {
59 var buf = new Uint8Array(ab);
60 var getUniqueName = t.getUniqueNameGenerator();
61 var offset = 0;
62
63 function getPosition() {
64 return {
65 line: -1,
66 column: offset
67 };
68 }
69
70 function dump(b, msg) {
71 if (opts.dump === false) return;
72 var pad = "\t\t\t\t\t\t\t\t\t\t";
73 var str = "";
74
75 if (b.length < 5) {
76 str = b.map(toHex).join(" ");
77 } else {
78 str = "...";
79 }
80
81 console.log(toHex(offset) + ":\t", str, pad, ";", msg);
82 }
83
84 function dumpSep(msg) {
85 if (opts.dump === false) return;
86 console.log(";", msg);
87 }
88 /**
89 * TODO(sven): we can atually use a same structure
90 * we are adding incrementally new features
91 */
92
93
94 var state = {
95 elementsInFuncSection: [],
96 elementsInExportSection: [],
97 elementsInCodeSection: [],
98
99 /**
100 * Decode memory from:
101 * - Memory section
102 */
103 memoriesInModule: [],
104
105 /**
106 * Decoded types from:
107 * - Type section
108 */
109 typesInModule: [],
110
111 /**
112 * Decoded functions from:
113 * - Function section
114 * - Import section
115 */
116 functionsInModule: [],
117
118 /**
119 * Decoded tables from:
120 * - Table section
121 */
122 tablesInModule: [],
123
124 /**
125 * Decoded globals from:
126 * - Global section
127 */
128 globalsInModule: []
129 };
130
131 function isEOF() {
132 return offset >= buf.length;
133 }
134
135 function eatBytes(n) {
136 offset = offset + n;
137 }
138
139 function readBytesAtOffset(_offset, numberOfBytes) {
140 var arr = [];
141
142 for (var i = 0; i < numberOfBytes; i++) {
143 arr.push(buf[_offset + i]);
144 }
145
146 return arr;
147 }
148
149 function readBytes(numberOfBytes) {
150 return readBytesAtOffset(offset, numberOfBytes);
151 }
152
153 function readF64() {
154 var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64);
155 var value = ieee754.decodeF64(bytes);
156
157 if (Math.sign(value) * value === Infinity) {
158 return {
159 value: Math.sign(value),
160 inf: true,
161 nextIndex: ieee754.NUMBER_OF_BYTE_F64
162 };
163 }
164
165 if (isNaN(value)) {
166 var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1;
167 var mantissa = 0;
168
169 for (var i = 0; i < bytes.length - 2; ++i) {
170 mantissa += bytes[i] * Math.pow(256, i);
171 }
172
173 mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2);
174 return {
175 value: sign * mantissa,
176 nan: true,
177 nextIndex: ieee754.NUMBER_OF_BYTE_F64
178 };
179 }
180
181 return {
182 value: value,
183 nextIndex: ieee754.NUMBER_OF_BYTE_F64
184 };
185 }
186
187 function readF32() {
188 var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32);
189 var value = ieee754.decodeF32(bytes);
190
191 if (Math.sign(value) * value === Infinity) {
192 return {
193 value: Math.sign(value),
194 inf: true,
195 nextIndex: ieee754.NUMBER_OF_BYTE_F32
196 };
197 }
198
199 if (isNaN(value)) {
200 var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1;
201 var mantissa = 0;
202
203 for (var i = 0; i < bytes.length - 2; ++i) {
204 mantissa += bytes[i] * Math.pow(256, i);
205 }
206
207 mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2);
208 return {
209 value: sign * mantissa,
210 nan: true,
211 nextIndex: ieee754.NUMBER_OF_BYTE_F32
212 };
213 }
214
215 return {
216 value: value,
217 nextIndex: ieee754.NUMBER_OF_BYTE_F32
218 };
219 }
220
221 function readUTF8String() {
222 var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using
223 // readBytesAtOffset below. This keeps readUTF8String neutral with respect
224 // to the current offset, just like the other readX functions.
225
226 var strlen = lenu32.value;
227 dump([strlen], "string length");
228 var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen);
229 var value = utf8.decode(bytes);
230 return {
231 value: value,
232 nextIndex: strlen + lenu32.nextIndex
233 };
234 }
235 /**
236 * Decode an unsigned 32bits integer
237 *
238 * The length will be handled by the leb librairy, we pass the max number of
239 * byte.
240 */
241
242
243 function readU32() {
244 var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32);
245 var buffer = new Uint8Array(bytes);
246 return (0, _leb.decodeUInt32)(buffer);
247 }
248
249 function readVaruint32() {
250 // where 32 bits = max 4 bytes
251 var bytes = readBytes(4);
252 var buffer = new Uint8Array(bytes);
253 return (0, _leb.decodeUInt32)(buffer);
254 }
255
256 function readVaruint7() {
257 // where 7 bits = max 1 bytes
258 var bytes = readBytes(1);
259 var buffer = new Uint8Array(bytes);
260 return (0, _leb.decodeUInt32)(buffer);
261 }
262 /**
263 * Decode a signed 32bits interger
264 */
265
266
267 function read32() {
268 var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32);
269 var buffer = new Uint8Array(bytes);
270 return (0, _leb.decodeInt32)(buffer);
271 }
272 /**
273 * Decode a signed 64bits integer
274 */
275
276
277 function read64() {
278 var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64);
279 var buffer = new Uint8Array(bytes);
280 return (0, _leb.decodeInt64)(buffer);
281 }
282
283 function readU64() {
284 var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64);
285 var buffer = new Uint8Array(bytes);
286 return (0, _leb.decodeUInt64)(buffer);
287 }
288
289 function readByte() {
290 return readBytes(1)[0];
291 }
292
293 function parseModuleHeader() {
294 if (isEOF() === true || offset + 4 > buf.length) {
295 throw new Error("unexpected end");
296 }
297
298 var header = readBytes(4);
299
300 if (byteArrayEq(_helperWasmBytecode["default"].magicModuleHeader, header) === false) {
301 throw new _helperApiError.CompileError("magic header not detected");
302 }
303
304 dump(header, "wasm magic header");
305 eatBytes(4);
306 }
307
308 function parseVersion() {
309 if (isEOF() === true || offset + 4 > buf.length) {
310 throw new Error("unexpected end");
311 }
312
313 var version = readBytes(4);
314
315 if (byteArrayEq(_helperWasmBytecode["default"].moduleVersion, version) === false) {
316 throw new _helperApiError.CompileError("unknown binary version");
317 }
318
319 dump(version, "wasm version");
320 eatBytes(4);
321 }
322
323 function parseVec(cast) {
324 var u32 = readU32();
325 var length = u32.value;
326 eatBytes(u32.nextIndex);
327 dump([length], "number");
328
329 if (length === 0) {
330 return [];
331 }
332
333 var elements = [];
334
335 for (var i = 0; i < length; i++) {
336 var _byte = readByte();
337
338 eatBytes(1);
339 var value = cast(_byte);
340 dump([_byte], value);
341
342 if (typeof value === "undefined") {
343 throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value");
344 }
345
346 elements.push(value);
347 }
348
349 return elements;
350 } // Type section
351 // https://webassembly.github.io/spec/binary/modules.html#binary-typesec
352
353
354 function parseTypeSection(numberOfTypes) {
355 var typeInstructionNodes = [];
356 dump([numberOfTypes], "num types");
357
358 for (var i = 0; i < numberOfTypes; i++) {
359 var _startLoc = getPosition();
360
361 dumpSep("type " + i);
362 var type = readByte();
363 eatBytes(1);
364
365 if (type == _helperWasmBytecode["default"].types.func) {
366 dump([type], "func");
367 var paramValtypes = parseVec(function (b) {
368 var valtype = _helperWasmBytecode["default"].valtypes[b];
369
370 if (valtype === undefined) {
371 throw new Error("unexpected value type ".concat(b));
372 }
373
374 return valtype;
375 });
376 var params = paramValtypes.map(function (v) {
377 return t.funcParam(
378 /*valtype*/
379 v);
380 });
381 var result = parseVec(function (b) {
382 return _helperWasmBytecode["default"].valtypes[b];
383 });
384 typeInstructionNodes.push(function () {
385 var endLoc = getPosition();
386 return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc);
387 }());
388 state.typesInModule.push({
389 params: params,
390 result: result
391 });
392 } else {
393 throw new Error("Unsupported type: " + toHex(type));
394 }
395 }
396
397 return typeInstructionNodes;
398 } // Import section
399 // https://webassembly.github.io/spec/binary/modules.html#binary-importsec
400
401
402 function parseImportSection(numberOfImports) {
403 var imports = [];
404
405 for (var i = 0; i < numberOfImports; i++) {
406 dumpSep("import header " + i);
407
408 var _startLoc2 = getPosition();
409 /**
410 * Module name
411 */
412
413
414 var moduleName = readUTF8String();
415 eatBytes(moduleName.nextIndex);
416 dump([], "module name (".concat(moduleName.value, ")"));
417 /**
418 * Name
419 */
420
421 var name = readUTF8String();
422 eatBytes(name.nextIndex);
423 dump([], "name (".concat(name.value, ")"));
424 /**
425 * Import descr
426 */
427
428 var descrTypeByte = readByte();
429 eatBytes(1);
430 var descrType = _helperWasmBytecode["default"].importTypes[descrTypeByte];
431 dump([descrTypeByte], "import kind");
432
433 if (typeof descrType === "undefined") {
434 throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte));
435 }
436
437 var importDescr = void 0;
438
439 if (descrType === "func") {
440 var indexU32 = readU32();
441 var typeindex = indexU32.value;
442 eatBytes(indexU32.nextIndex);
443 dump([typeindex], "type index");
444 var signature = state.typesInModule[typeindex];
445
446 if (typeof signature === "undefined") {
447 throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")"));
448 }
449
450 var id = getUniqueName("func");
451 importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result));
452 state.functionsInModule.push({
453 id: t.identifier(name.value),
454 signature: signature,
455 isExternal: true
456 });
457 } else if (descrType === "global") {
458 importDescr = parseGlobalType();
459 var globalNode = t.global(importDescr, []);
460 state.globalsInModule.push(globalNode);
461 } else if (descrType === "table") {
462 importDescr = parseTableType(i);
463 } else if (descrType === "memory") {
464 var memoryNode = parseMemoryType(0);
465 state.memoriesInModule.push(memoryNode);
466 importDescr = memoryNode;
467 } else {
468 throw new _helperApiError.CompileError("Unsupported import of type: " + descrType);
469 }
470
471 imports.push(function () {
472 var endLoc = getPosition();
473 return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2);
474 }());
475 }
476
477 return imports;
478 } // Function section
479 // https://webassembly.github.io/spec/binary/modules.html#function-section
480
481
482 function parseFuncSection(numberOfFunctions) {
483 dump([numberOfFunctions], "num funcs");
484
485 for (var i = 0; i < numberOfFunctions; i++) {
486 var indexU32 = readU32();
487 var typeindex = indexU32.value;
488 eatBytes(indexU32.nextIndex);
489 dump([typeindex], "type index");
490 var signature = state.typesInModule[typeindex];
491
492 if (typeof signature === "undefined") {
493 throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")"));
494 } // preserve anonymous, a name might be resolved later
495
496
497 var id = t.withRaw(t.identifier(getUniqueName("func")), "");
498 state.functionsInModule.push({
499 id: id,
500 signature: signature,
501 isExternal: false
502 });
503 }
504 } // Export section
505 // https://webassembly.github.io/spec/binary/modules.html#export-section
506
507
508 function parseExportSection(numberOfExport) {
509 dump([numberOfExport], "num exports"); // Parse vector of exports
510
511 for (var i = 0; i < numberOfExport; i++) {
512 var _startLoc3 = getPosition();
513 /**
514 * Name
515 */
516
517
518 var name = readUTF8String();
519 eatBytes(name.nextIndex);
520 dump([], "export name (".concat(name.value, ")"));
521 /**
522 * exportdescr
523 */
524
525 var typeIndex = readByte();
526 eatBytes(1);
527 dump([typeIndex], "export kind");
528 var indexu32 = readU32();
529 var index = indexu32.value;
530 eatBytes(indexu32.nextIndex);
531 dump([index], "export index");
532 var id = void 0,
533 signature = void 0;
534
535 if (_helperWasmBytecode["default"].exportTypes[typeIndex] === "Func") {
536 var func = state.functionsInModule[index];
537
538 if (typeof func === "undefined") {
539 throw new _helperApiError.CompileError("unknown function (".concat(index, ")"));
540 }
541
542 id = t.numberLiteralFromRaw(index, String(index));
543 signature = func.signature;
544 } else if (_helperWasmBytecode["default"].exportTypes[typeIndex] === "Table") {
545 var table = state.tablesInModule[index];
546
547 if (typeof table === "undefined") {
548 throw new _helperApiError.CompileError("unknown table ".concat(index));
549 }
550
551 id = t.numberLiteralFromRaw(index, String(index));
552 signature = null;
553 } else if (_helperWasmBytecode["default"].exportTypes[typeIndex] === "Memory") {
554 var memNode = state.memoriesInModule[index];
555
556 if (typeof memNode === "undefined") {
557 throw new _helperApiError.CompileError("unknown memory ".concat(index));
558 }
559
560 id = t.numberLiteralFromRaw(index, String(index));
561 signature = null;
562 } else if (_helperWasmBytecode["default"].exportTypes[typeIndex] === "Global") {
563 var global = state.globalsInModule[index];
564
565 if (typeof global === "undefined") {
566 throw new _helperApiError.CompileError("unknown global ".concat(index));
567 }
568
569 id = t.numberLiteralFromRaw(index, String(index));
570 signature = null;
571 } else {
572 console.warn("Unsupported export type: " + toHex(typeIndex));
573 return;
574 }
575
576 var endLoc = getPosition();
577 state.elementsInExportSection.push({
578 name: name.value,
579 type: _helperWasmBytecode["default"].exportTypes[typeIndex],
580 signature: signature,
581 id: id,
582 index: index,
583 endLoc: endLoc,
584 startLoc: _startLoc3
585 });
586 }
587 } // Code section
588 // https://webassembly.github.io/spec/binary/modules.html#code-section
589
590
591 function parseCodeSection(numberOfFuncs) {
592 dump([numberOfFuncs], "number functions"); // Parse vector of function
593
594 for (var i = 0; i < numberOfFuncs; i++) {
595 var _startLoc4 = getPosition();
596
597 dumpSep("function body " + i); // the u32 size of the function code in bytes
598 // Ignore it for now
599
600 var bodySizeU32 = readU32();
601 eatBytes(bodySizeU32.nextIndex);
602 dump([bodySizeU32.value], "function body size");
603 var code = []; // Parse locals
604
605 var funcLocalNumU32 = readU32();
606 var funcLocalNum = funcLocalNumU32.value;
607 eatBytes(funcLocalNumU32.nextIndex);
608 dump([funcLocalNum], "num locals");
609 var locals = [];
610
611 for (var _i = 0; _i < funcLocalNum; _i++) {
612 var _startLoc5 = getPosition();
613
614 var localCountU32 = readU32();
615 var localCount = localCountU32.value;
616 eatBytes(localCountU32.nextIndex);
617 dump([localCount], "num local");
618 var valtypeByte = readByte();
619 eatBytes(1);
620 var type = _helperWasmBytecode["default"].valtypes[valtypeByte];
621 var args = [];
622
623 for (var _i2 = 0; _i2 < localCount; _i2++) {
624 args.push(t.valtypeLiteral(type));
625 }
626
627 var localNode = function () {
628 var endLoc = getPosition();
629 return t.withLoc(t.instruction("local", args), endLoc, _startLoc5);
630 }();
631
632 locals.push(localNode);
633 dump([valtypeByte], type);
634
635 if (typeof type === "undefined") {
636 throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte));
637 }
638 }
639
640 code.push.apply(code, locals); // Decode instructions until the end
641
642 parseInstructionBlock(code);
643 var endLoc = getPosition();
644 state.elementsInCodeSection.push({
645 code: code,
646 locals: locals,
647 endLoc: endLoc,
648 startLoc: _startLoc4,
649 bodySize: bodySizeU32.value
650 });
651 }
652 }
653
654 function parseInstructionBlock(code) {
655 while (true) {
656 var _startLoc6 = getPosition();
657
658 var instructionAlreadyCreated = false;
659 var instructionByte = readByte();
660 eatBytes(1);
661
662 if (instructionByte === 0xfe) {
663 instructionByte = 0xfe00 + readByte();
664 eatBytes(1);
665 } // Table instructions
666 // https://webassembly.github.io/spec/core/binary/instructions.html#table-instructions
667
668
669 if (instructionByte === 0xfc) {
670 instructionByte = 0xfc00 + readByte();
671 eatBytes(1);
672 }
673
674 var instruction = _helperWasmBytecode["default"].symbolsByByte[instructionByte];
675
676 if (typeof instruction === "undefined") {
677 throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte));
678 }
679
680 if (instruction === "illegal") {
681 throw new Error("tried to decode an illegal bytecode: ".concat(toHex(instructionByte)));
682 }
683
684 if (typeof instruction.object === "string") {
685 dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name));
686 } else {
687 dump([instructionByte], instruction.name);
688 }
689 /**
690 * End of the function
691 */
692
693
694 if (instruction.name === "end") {
695 var node = function () {
696 var endLoc = getPosition();
697 return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6);
698 }();
699
700 code.push(node);
701 break;
702 }
703
704 var args = [];
705 var namedArgs = void 0;
706
707 if (instruction.name === "loop") {
708 var _startLoc7 = getPosition();
709
710 var blocktype = parseBlockType();
711 var instr = [];
712 parseInstructionBlock(instr); // preserve anonymous
713
714 var label = t.withRaw(t.identifier(getUniqueName("loop")), "");
715
716 var loopNode = function () {
717 var endLoc = getPosition();
718 return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7);
719 }();
720
721 code.push(loopNode);
722 instructionAlreadyCreated = true;
723 } else if (instruction.name === "if") {
724 var _startLoc8 = getPosition();
725
726 var _blocktype = parseBlockType();
727
728 var testIndex = t.withRaw(t.identifier(getUniqueName("if")), "");
729 var ifBody = [];
730 parseInstructionBlock(ifBody); // Defaults to no alternate
731
732 var elseIndex = 0;
733
734 for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) {
735 var _instr = ifBody[elseIndex];
736
737 if (_instr.type === "Instr" && _instr.id === "else") {
738 break;
739 }
740 }
741
742 var consequentInstr = ifBody.slice(0, elseIndex);
743 var alternate = ifBody.slice(elseIndex + 1); // wast sugar
744
745 var testInstrs = [];
746
747 var ifNode = function () {
748 var endLoc = getPosition();
749 return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8);
750 }();
751
752 code.push(ifNode);
753 instructionAlreadyCreated = true;
754 } else if (instruction.name === "block") {
755 var _startLoc9 = getPosition();
756
757 var _blocktype2 = parseBlockType();
758
759 var _instr2 = [];
760 parseInstructionBlock(_instr2); // preserve anonymous
761
762 var _label = t.withRaw(t.identifier(getUniqueName("block")), "");
763
764 var blockNode = function () {
765 var endLoc = getPosition();
766 return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9);
767 }();
768
769 code.push(blockNode);
770 instructionAlreadyCreated = true;
771 } else if (instruction.name === "call") {
772 var indexu32 = readU32();
773 var index = indexu32.value;
774 eatBytes(indexu32.nextIndex);
775 dump([index], "index");
776
777 var callNode = function () {
778 var endLoc = getPosition();
779 return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6);
780 }();
781
782 code.push(callNode);
783 instructionAlreadyCreated = true;
784 } else if (instruction.name === "call_indirect") {
785 var _startLoc10 = getPosition();
786
787 var indexU32 = readU32();
788 var typeindex = indexU32.value;
789 eatBytes(indexU32.nextIndex);
790 dump([typeindex], "type index");
791 var signature = state.typesInModule[typeindex];
792
793 if (typeof signature === "undefined") {
794 throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")"));
795 }
796
797 var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []);
798
799 var flagU32 = readU32();
800 var flag = flagU32.value; // 0x00 - reserved byte
801
802 eatBytes(flagU32.nextIndex);
803
804 if (flag !== 0) {
805 throw new _helperApiError.CompileError("zero flag expected");
806 }
807
808 code.push(function () {
809 var endLoc = getPosition();
810 return t.withLoc(_callNode, endLoc, _startLoc10);
811 }());
812 instructionAlreadyCreated = true;
813 } else if (instruction.name === "br_table") {
814 var indicesu32 = readU32();
815 var indices = indicesu32.value;
816 eatBytes(indicesu32.nextIndex);
817 dump([indices], "num indices");
818
819 for (var i = 0; i <= indices; i++) {
820 var _indexu = readU32();
821
822 var _index = _indexu.value;
823 eatBytes(_indexu.nextIndex);
824 dump([_index], "index");
825 args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32"));
826 }
827 } else if (instructionByte >= 0x28 && instructionByte <= 0x40) {
828 /**
829 * Memory instructions
830 */
831 if (instruction.name === "grow_memory" || instruction.name === "current_memory") {
832 var _indexU = readU32();
833
834 var _index2 = _indexU.value;
835 eatBytes(_indexU.nextIndex);
836
837 if (_index2 !== 0) {
838 throw new Error("zero flag expected");
839 }
840
841 dump([_index2], "index");
842 } else {
843 var aligun32 = readU32();
844 var align = aligun32.value;
845 eatBytes(aligun32.nextIndex);
846 dump([align], "align");
847 var offsetu32 = readU32();
848 var _offset2 = offsetu32.value;
849 eatBytes(offsetu32.nextIndex);
850 dump([_offset2], "offset");
851 if (namedArgs === undefined) namedArgs = {};
852 namedArgs.offset = t.numberLiteralFromRaw(_offset2);
853 }
854 } else if (instructionByte >= 0x41 && instructionByte <= 0x44) {
855 /**
856 * Numeric instructions
857 */
858 if (instruction.object === "i32") {
859 var value32 = read32();
860 var value = value32.value;
861 eatBytes(value32.nextIndex);
862 dump([value], "i32 value");
863 args.push(t.numberLiteralFromRaw(value));
864 }
865
866 if (instruction.object === "u32") {
867 var valueu32 = readU32();
868 var _value = valueu32.value;
869 eatBytes(valueu32.nextIndex);
870 dump([_value], "u32 value");
871 args.push(t.numberLiteralFromRaw(_value));
872 }
873
874 if (instruction.object === "i64") {
875 var value64 = read64();
876 var _value2 = value64.value;
877 eatBytes(value64.nextIndex);
878 dump([Number(_value2.toString())], "i64 value");
879 var high = _value2.high,
880 low = _value2.low;
881 var _node = {
882 type: "LongNumberLiteral",
883 value: {
884 high: high,
885 low: low
886 }
887 };
888 args.push(_node);
889 }
890
891 if (instruction.object === "u64") {
892 var valueu64 = readU64();
893 var _value3 = valueu64.value;
894 eatBytes(valueu64.nextIndex);
895 dump([Number(_value3.toString())], "u64 value");
896 var _high = _value3.high,
897 _low = _value3.low;
898 var _node2 = {
899 type: "LongNumberLiteral",
900 value: {
901 high: _high,
902 low: _low
903 }
904 };
905 args.push(_node2);
906 }
907
908 if (instruction.object === "f32") {
909 var valuef32 = readF32();
910 var _value4 = valuef32.value;
911 eatBytes(valuef32.nextIndex);
912 dump([_value4], "f32 value");
913 args.push( // $FlowIgnore
914 t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4)));
915 }
916
917 if (instruction.object === "f64") {
918 var valuef64 = readF64();
919 var _value5 = valuef64.value;
920 eatBytes(valuef64.nextIndex);
921 dump([_value5], "f64 value");
922 args.push( // $FlowIgnore
923 t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5)));
924 }
925 } else if (instructionByte >= 0xfe00 && instructionByte <= 0xfeff) {
926 /**
927 * Atomic memory instructions
928 */
929 var align32 = readU32();
930 var _align = align32.value;
931 eatBytes(align32.nextIndex);
932 dump([_align], "align");
933
934 var _offsetu = readU32();
935
936 var _offset3 = _offsetu.value;
937 eatBytes(_offsetu.nextIndex);
938 dump([_offset3], "offset");
939 } else {
940 for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) {
941 var u32 = readU32();
942 eatBytes(u32.nextIndex);
943 dump([u32.value], "argument " + _i3);
944 args.push(t.numberLiteralFromRaw(u32.value));
945 }
946 }
947
948 if (instructionAlreadyCreated === false) {
949 if (typeof instruction.object === "string") {
950 var _node3 = function () {
951 var endLoc = getPosition();
952 return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args, namedArgs), endLoc, _startLoc6);
953 }();
954
955 code.push(_node3);
956 } else {
957 var _node4 = function () {
958 var endLoc = getPosition();
959 return t.withLoc(t.instruction(instruction.name, args, namedArgs), endLoc, _startLoc6);
960 }();
961
962 code.push(_node4);
963 }
964 }
965 }
966 } // https://webassembly.github.io/spec/core/binary/types.html#limits
967
968
969 function parseLimits() {
970 var limitType = readByte();
971 eatBytes(1);
972 var shared = limitType === 0x03;
973 dump([limitType], "limit type" + (shared ? " (shared)" : ""));
974 var min, max;
975
976 if (limitType === 0x01 || limitType === 0x03 // shared limits
977 ) {
978 var u32min = readU32();
979 min = parseInt(u32min.value);
980 eatBytes(u32min.nextIndex);
981 dump([min], "min");
982 var u32max = readU32();
983 max = parseInt(u32max.value);
984 eatBytes(u32max.nextIndex);
985 dump([max], "max");
986 }
987
988 if (limitType === 0x00) {
989 var _u32min = readU32();
990
991 min = parseInt(_u32min.value);
992 eatBytes(_u32min.nextIndex);
993 dump([min], "min");
994 }
995
996 return t.limit(min, max, shared);
997 } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype
998
999
1000 function parseTableType(index) {
1001 var name = t.withRaw(t.identifier(getUniqueName("table")), String(index));
1002 var elementTypeByte = readByte();
1003 eatBytes(1);
1004 dump([elementTypeByte], "element type");
1005 var elementType = _helperWasmBytecode["default"].tableTypes[elementTypeByte];
1006
1007 if (typeof elementType === "undefined") {
1008 throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementTypeByte));
1009 }
1010
1011 var limits = parseLimits();
1012 return t.table(elementType, limits, name);
1013 } // https://webassembly.github.io/spec/binary/types.html#global-types
1014
1015
1016 function parseGlobalType() {
1017 var valtypeByte = readByte();
1018 eatBytes(1);
1019 var type = _helperWasmBytecode["default"].valtypes[valtypeByte];
1020 dump([valtypeByte], type);
1021
1022 if (typeof type === "undefined") {
1023 throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte));
1024 }
1025
1026 var globalTypeByte = readByte();
1027 eatBytes(1);
1028 var globalType = _helperWasmBytecode["default"].globalTypes[globalTypeByte];
1029 dump([globalTypeByte], "global type (".concat(globalType, ")"));
1030
1031 if (typeof globalType === "undefined") {
1032 throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte));
1033 }
1034
1035 return t.globalType(type, globalType);
1036 } // function parseNameModule() {
1037 // const lenu32 = readVaruint32();
1038 // eatBytes(lenu32.nextIndex);
1039 // console.log("len", lenu32);
1040 // const strlen = lenu32.value;
1041 // dump([strlen], "string length");
1042 // const bytes = readBytes(strlen);
1043 // eatBytes(strlen);
1044 // const value = utf8.decode(bytes);
1045 // return [t.moduleNameMetadata(value)];
1046 // }
1047 // this section contains an array of function names and indices
1048
1049
1050 function parseNameSectionFunctions() {
1051 var functionNames = [];
1052 var numberOfFunctionsu32 = readU32();
1053 var numbeOfFunctions = numberOfFunctionsu32.value;
1054 eatBytes(numberOfFunctionsu32.nextIndex);
1055
1056 for (var i = 0; i < numbeOfFunctions; i++) {
1057 var indexu32 = readU32();
1058 var index = indexu32.value;
1059 eatBytes(indexu32.nextIndex);
1060 var name = readUTF8String();
1061 eatBytes(name.nextIndex);
1062 functionNames.push(t.functionNameMetadata(name.value, index));
1063 }
1064
1065 return functionNames;
1066 }
1067
1068 function parseNameSectionLocals() {
1069 var localNames = [];
1070 var numbeOfFunctionsu32 = readU32();
1071 var numbeOfFunctions = numbeOfFunctionsu32.value;
1072 eatBytes(numbeOfFunctionsu32.nextIndex);
1073
1074 for (var i = 0; i < numbeOfFunctions; i++) {
1075 var functionIndexu32 = readU32();
1076 var functionIndex = functionIndexu32.value;
1077 eatBytes(functionIndexu32.nextIndex);
1078 var numLocalsu32 = readU32();
1079 var numLocals = numLocalsu32.value;
1080 eatBytes(numLocalsu32.nextIndex);
1081
1082 for (var _i4 = 0; _i4 < numLocals; _i4++) {
1083 var localIndexu32 = readU32();
1084 var localIndex = localIndexu32.value;
1085 eatBytes(localIndexu32.nextIndex);
1086 var name = readUTF8String();
1087 eatBytes(name.nextIndex);
1088 localNames.push(t.localNameMetadata(name.value, localIndex, functionIndex));
1089 }
1090 }
1091
1092 return localNames;
1093 } // this is a custom section used for name resolution
1094 // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
1095
1096
1097 function parseNameSection(remainingBytes) {
1098 var nameMetadata = [];
1099 var initialOffset = offset;
1100
1101 while (offset - initialOffset < remainingBytes) {
1102 // name_type
1103 var sectionTypeByte = readVaruint7();
1104 eatBytes(sectionTypeByte.nextIndex); // name_payload_len
1105
1106 var subSectionSizeInBytesu32 = readVaruint32();
1107 eatBytes(subSectionSizeInBytesu32.nextIndex);
1108
1109 switch (sectionTypeByte.value) {
1110 // case 0: {
1111 // TODO(sven): re-enable that
1112 // Current status: it seems that when we decode the module's name
1113 // no name_payload_len is used.
1114 //
1115 // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
1116 //
1117 // nameMetadata.push(...parseNameModule());
1118 // break;
1119 // }
1120 case 1:
1121 {
1122 nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionFunctions()));
1123 break;
1124 }
1125
1126 case 2:
1127 {
1128 nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals()));
1129 break;
1130 }
1131
1132 default:
1133 {
1134 // skip unknown subsection
1135 eatBytes(subSectionSizeInBytesu32.value);
1136 }
1137 }
1138 }
1139
1140 return nameMetadata;
1141 } // this is a custom section used for information about the producers
1142 // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md
1143
1144
1145 function parseProducersSection() {
1146 var metadata = t.producersSectionMetadata([]); // field_count
1147
1148 var sectionTypeByte = readVaruint32();
1149 eatBytes(sectionTypeByte.nextIndex);
1150 dump([sectionTypeByte.value], "num of producers");
1151 var fields = {
1152 language: [],
1153 "processed-by": [],
1154 sdk: []
1155 }; // fields
1156
1157 for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) {
1158 // field_name
1159 var fieldName = readUTF8String();
1160 eatBytes(fieldName.nextIndex); // field_value_count
1161
1162 var valueCount = readVaruint32();
1163 eatBytes(valueCount.nextIndex); // field_values
1164
1165 for (var producerI = 0; producerI < valueCount.value; producerI++) {
1166 var producerName = readUTF8String();
1167 eatBytes(producerName.nextIndex);
1168 var producerVersion = readUTF8String();
1169 eatBytes(producerVersion.nextIndex);
1170 fields[fieldName.value].push(t.producerMetadataVersionedName(producerName.value, producerVersion.value));
1171 }
1172
1173 metadata.producers.push(fields[fieldName.value]);
1174 }
1175
1176 return metadata;
1177 }
1178
1179 function parseGlobalSection(numberOfGlobals) {
1180 var globals = [];
1181 dump([numberOfGlobals], "num globals");
1182
1183 for (var i = 0; i < numberOfGlobals; i++) {
1184 var _startLoc11 = getPosition();
1185
1186 var globalType = parseGlobalType();
1187 /**
1188 * Global expressions
1189 */
1190
1191 var init = [];
1192 parseInstructionBlock(init);
1193
1194 var node = function () {
1195 var endLoc = getPosition();
1196 return t.withLoc(t.global(globalType, init), endLoc, _startLoc11);
1197 }();
1198
1199 globals.push(node);
1200 state.globalsInModule.push(node);
1201 }
1202
1203 return globals;
1204 }
1205
1206 function parseElemSection(numberOfElements) {
1207 var elems = [];
1208 dump([numberOfElements], "num elements");
1209
1210 for (var i = 0; i < numberOfElements; i++) {
1211 var _startLoc12 = getPosition();
1212
1213 var tableindexu32 = readU32();
1214 var bitfield = tableindexu32.value;
1215 eatBytes(tableindexu32.nextIndex);
1216 dump([bitfield], "bitfield");
1217
1218 if (bitfield === 0) {
1219 // Parse instructions
1220 var instr = [];
1221 parseInstructionBlock(instr); // Parse ( vector function index ) *
1222
1223 var indicesu32 = readU32();
1224 var indices = indicesu32.value;
1225 eatBytes(indicesu32.nextIndex);
1226 dump([indices], "num indices");
1227 var indexValues = [];
1228
1229 for (var _i5 = 0; _i5 < indices; _i5++) {
1230 var indexu32 = readU32();
1231 var index = indexu32.value;
1232 eatBytes(indexu32.nextIndex);
1233 dump([index], "index");
1234 indexValues.push(t.indexLiteral(index));
1235 }
1236
1237 var elemNode = function () {
1238 var endLoc = getPosition();
1239 return t.withLoc(t.elem(t.indexLiteral(bitfield), instr, indexValues), endLoc, _startLoc12);
1240 }();
1241
1242 elems.push(elemNode);
1243 } else if (bitfield === 1) {
1244 var elemKind = readByte();
1245 eatBytes(1);
1246
1247 if (elemKind !== 0) {
1248 throw new Error("unexpected Elem kind: ".concat(toHex(elemKind)));
1249 } // Parse ( vector function index ) *
1250
1251
1252 var _indicesu = readU32();
1253
1254 var _indices = _indicesu.value;
1255 eatBytes(_indicesu.nextIndex);
1256 dump([_indices], "num indices");
1257 var _indexValues = [];
1258
1259 for (var _i6 = 0; _i6 < _indices; _i6++) {
1260 var _indexu2 = readU32();
1261
1262 var _index3 = _indexu2.value;
1263 eatBytes(_indexu2.nextIndex);
1264 dump([_index3], "index");
1265
1266 _indexValues.push(t.indexLiteral(_index3));
1267 } // TODO: emit a AST node, for now just make it parse.
1268
1269 } else if (bitfield === 2) {
1270 var u32 = readU32();
1271 var tableidx = u32.value;
1272 eatBytes(u32.nextIndex);
1273 dump([tableidx], "tableidx"); // Parse instructions
1274
1275 var _instr3 = [];
1276 parseInstructionBlock(_instr3);
1277
1278 var _elemKind = readByte();
1279
1280 eatBytes(1);
1281
1282 if (_elemKind !== 0) {
1283 throw new Error("unexpected Elem kind: ".concat(toHex(_elemKind)));
1284 } // Parse ( vector function index ) *
1285
1286
1287 var _indicesu2 = readU32();
1288
1289 var _indices2 = _indicesu2.value;
1290 eatBytes(_indicesu2.nextIndex);
1291 dump([_indices2], "num indices");
1292 var _indexValues2 = [];
1293
1294 for (var _i7 = 0; _i7 < _indices2; _i7++) {
1295 var _indexu3 = readU32();
1296
1297 var _index4 = _indexu3.value;
1298 eatBytes(_indexu3.nextIndex);
1299 dump([_index4], "index");
1300
1301 _indexValues2.push(t.indexLiteral(_index4));
1302 }
1303
1304 var _elemNode = function () {
1305 var endLoc = getPosition();
1306 return t.withLoc(t.elem(t.indexLiteral(bitfield), _instr3, _indexValues2), endLoc, _startLoc12);
1307 }();
1308
1309 elems.push(_elemNode);
1310 } else if (bitfield === 3) {
1311 var _elemKind2 = readByte();
1312
1313 eatBytes(1);
1314
1315 if (_elemKind2 !== 0) {
1316 throw new Error("unexpected Elem kind: ".concat(toHex(_elemKind2)));
1317 } // Parse ( vector function index ) *
1318
1319
1320 var countU32 = readU32();
1321 var count = countU32.value;
1322 eatBytes(countU32.nextIndex);
1323 dump([count], "count");
1324
1325 for (var _i8 = 0; _i8 < count; _i8++) {
1326 var _indexu4 = readU32();
1327
1328 var _index5 = _indexu4.value;
1329 eatBytes(_indexu4.nextIndex);
1330 dump([_index5], "index");
1331 } // TODO: emit a AST node, for now just make it parse.
1332
1333 } else if (bitfield === 4) {
1334 var expr = [];
1335 parseInstructionBlock(expr);
1336
1337 var _countU = readU32();
1338
1339 var _count = _countU.value;
1340 eatBytes(_countU.nextIndex);
1341 dump([_count], "count");
1342
1343 for (var _i9 = 0; _i9 < _count; _i9++) {
1344 var code = [];
1345 parseInstructionBlock(code);
1346 } // TODO: emit a AST node, for now just make it parse.
1347
1348 } else if (bitfield === 5) {
1349 var reftype = readByte();
1350 eatBytes(1);
1351 dump([reftype], "reftype");
1352
1353 var _countU2 = readU32();
1354
1355 var _count2 = _countU2.value;
1356 eatBytes(_countU2.nextIndex);
1357 dump([_count2], "count");
1358
1359 for (var _i10 = 0; _i10 < _count2; _i10++) {
1360 var _code = [];
1361 parseInstructionBlock(_code);
1362 } // TODO: emit a AST node, for now just make it parse.
1363
1364 } else if (bitfield === 7) {
1365 var _reftype = readByte();
1366
1367 eatBytes(1);
1368 dump([_reftype], "reftype");
1369
1370 var _countU3 = readU32();
1371
1372 var _count3 = _countU3.value;
1373 eatBytes(_countU3.nextIndex);
1374 dump([_count3], "count");
1375
1376 for (var _i11 = 0; _i11 < _count3; _i11++) {
1377 var _code2 = [];
1378 parseInstructionBlock(_code2);
1379 } // TODO: emit a AST node, for now just make it parse.
1380
1381 } else {
1382 throw new Error("unexpected Elem with bitfield ".concat(toHex(bitfield)));
1383 }
1384 }
1385
1386 return elems;
1387 } // https://webassembly.github.io/spec/core/binary/types.html#memory-types
1388
1389
1390 function parseMemoryType(i) {
1391 var limits = parseLimits();
1392 return t.memory(limits, t.indexLiteral(i));
1393 } // https://webassembly.github.io/spec/binary/modules.html#table-section
1394
1395
1396 function parseTableSection(numberOfElements) {
1397 var tables = [];
1398 dump([numberOfElements], "num elements");
1399
1400 for (var i = 0; i < numberOfElements; i++) {
1401 var tablesNode = parseTableType(i);
1402 state.tablesInModule.push(tablesNode);
1403 tables.push(tablesNode);
1404 }
1405
1406 return tables;
1407 } // https://webassembly.github.io/spec/binary/modules.html#memory-section
1408
1409
1410 function parseMemorySection(numberOfElements) {
1411 var memories = [];
1412 dump([numberOfElements], "num elements");
1413
1414 for (var i = 0; i < numberOfElements; i++) {
1415 var memoryNode = parseMemoryType(i);
1416 state.memoriesInModule.push(memoryNode);
1417 memories.push(memoryNode);
1418 }
1419
1420 return memories;
1421 } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec
1422
1423
1424 function parseStartSection() {
1425 var startLoc = getPosition();
1426 var u32 = readU32();
1427 var startFuncIndex = u32.value;
1428 eatBytes(u32.nextIndex);
1429 dump([startFuncIndex], "index");
1430 return function () {
1431 var endLoc = getPosition();
1432 return t.withLoc(t.start(t.indexLiteral(startFuncIndex)), endLoc, startLoc);
1433 }();
1434 } // https://webassembly.github.io/spec/binary/modules.html#data-section
1435
1436
1437 function parseDataSection(numberOfElements) {
1438 var dataEntries = [];
1439 dump([numberOfElements], "num elements");
1440
1441 for (var i = 0; i < numberOfElements; i++) {
1442 var memoryIndexu32 = readU32();
1443 var memoryIndex = memoryIndexu32.value;
1444 eatBytes(memoryIndexu32.nextIndex);
1445 dump([memoryIndex], "memory index");
1446 var instrs = [];
1447 parseInstructionBlock(instrs);
1448 var hasExtraInstrs = instrs.filter(function (i) {
1449 return i.id !== "end";
1450 }).length !== 1;
1451
1452 if (hasExtraInstrs) {
1453 throw new _helperApiError.CompileError("data section offset must be a single instruction");
1454 }
1455
1456 var bytes = parseVec(function (b) {
1457 return b;
1458 });
1459 dump([], "init");
1460 dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes)));
1461 }
1462
1463 return dataEntries;
1464 } // https://webassembly.github.io/spec/binary/modules.html#binary-section
1465
1466
1467 function parseSection(sectionIndex) {
1468 var sectionId = readByte();
1469 eatBytes(1);
1470
1471 if (sectionId >= sectionIndex || sectionIndex === _helperWasmBytecode["default"].sections.custom) {
1472 sectionIndex = sectionId + 1;
1473 } else {
1474 if (sectionId !== _helperWasmBytecode["default"].sections.custom) throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId));
1475 }
1476
1477 var nextSectionIndex = sectionIndex;
1478 var startOffset = offset;
1479 var startLoc = getPosition();
1480 var u32 = readU32();
1481 var sectionSizeInBytes = u32.value;
1482 eatBytes(u32.nextIndex);
1483
1484 var sectionSizeInBytesNode = function () {
1485 var endLoc = getPosition();
1486 return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc);
1487 }();
1488
1489 switch (sectionId) {
1490 case _helperWasmBytecode["default"].sections.type:
1491 {
1492 dumpSep("section Type");
1493 dump([sectionId], "section code");
1494 dump([sectionSizeInBytes], "section size");
1495
1496 var _startLoc13 = getPosition();
1497
1498 var _u = readU32();
1499
1500 var numberOfTypes = _u.value;
1501 eatBytes(_u.nextIndex);
1502 var metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () {
1503 var endLoc = getPosition();
1504 return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13);
1505 }());
1506 var nodes = parseTypeSection(numberOfTypes);
1507 return {
1508 nodes: nodes,
1509 metadata: metadata,
1510 nextSectionIndex: nextSectionIndex
1511 };
1512 }
1513
1514 case _helperWasmBytecode["default"].sections.table:
1515 {
1516 dumpSep("section Table");
1517 dump([sectionId], "section code");
1518 dump([sectionSizeInBytes], "section size");
1519
1520 var _startLoc14 = getPosition();
1521
1522 var _u2 = readU32();
1523
1524 var numberOfTable = _u2.value;
1525 eatBytes(_u2.nextIndex);
1526 dump([numberOfTable], "num tables");
1527
1528 var _metadata = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () {
1529 var endLoc = getPosition();
1530 return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14);
1531 }());
1532
1533 var _nodes = parseTableSection(numberOfTable);
1534
1535 return {
1536 nodes: _nodes,
1537 metadata: _metadata,
1538 nextSectionIndex: nextSectionIndex
1539 };
1540 }
1541
1542 case _helperWasmBytecode["default"].sections["import"]:
1543 {
1544 dumpSep("section Import");
1545 dump([sectionId], "section code");
1546 dump([sectionSizeInBytes], "section size");
1547
1548 var _startLoc15 = getPosition();
1549
1550 var numberOfImportsu32 = readU32();
1551 var numberOfImports = numberOfImportsu32.value;
1552 eatBytes(numberOfImportsu32.nextIndex);
1553 dump([numberOfImports], "number of imports");
1554
1555 var _metadata2 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () {
1556 var endLoc = getPosition();
1557 return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15);
1558 }());
1559
1560 var _nodes2 = parseImportSection(numberOfImports);
1561
1562 return {
1563 nodes: _nodes2,
1564 metadata: _metadata2,
1565 nextSectionIndex: nextSectionIndex
1566 };
1567 }
1568
1569 case _helperWasmBytecode["default"].sections.func:
1570 {
1571 dumpSep("section Function");
1572 dump([sectionId], "section code");
1573 dump([sectionSizeInBytes], "section size");
1574
1575 var _startLoc16 = getPosition();
1576
1577 var numberOfFunctionsu32 = readU32();
1578 var numberOfFunctions = numberOfFunctionsu32.value;
1579 eatBytes(numberOfFunctionsu32.nextIndex);
1580
1581 var _metadata3 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () {
1582 var endLoc = getPosition();
1583 return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16);
1584 }());
1585
1586 parseFuncSection(numberOfFunctions);
1587 var _nodes3 = [];
1588 return {
1589 nodes: _nodes3,
1590 metadata: _metadata3,
1591 nextSectionIndex: nextSectionIndex
1592 };
1593 }
1594
1595 case _helperWasmBytecode["default"].sections["export"]:
1596 {
1597 dumpSep("section Export");
1598 dump([sectionId], "section code");
1599 dump([sectionSizeInBytes], "section size");
1600
1601 var _startLoc17 = getPosition();
1602
1603 var _u3 = readU32();
1604
1605 var numberOfExport = _u3.value;
1606 eatBytes(_u3.nextIndex);
1607
1608 var _metadata4 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () {
1609 var endLoc = getPosition();
1610 return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17);
1611 }());
1612
1613 parseExportSection(numberOfExport);
1614 var _nodes4 = [];
1615 return {
1616 nodes: _nodes4,
1617 metadata: _metadata4,
1618 nextSectionIndex: nextSectionIndex
1619 };
1620 }
1621
1622 case _helperWasmBytecode["default"].sections.code:
1623 {
1624 dumpSep("section Code");
1625 dump([sectionId], "section code");
1626 dump([sectionSizeInBytes], "section size");
1627
1628 var _startLoc18 = getPosition();
1629
1630 var _u4 = readU32();
1631
1632 var numberOfFuncs = _u4.value;
1633 eatBytes(_u4.nextIndex);
1634
1635 var _metadata5 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () {
1636 var endLoc = getPosition();
1637 return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18);
1638 }());
1639
1640 if (opts.ignoreCodeSection === true) {
1641 var remainingBytes = sectionSizeInBytes - _u4.nextIndex;
1642 eatBytes(remainingBytes); // eat the entire section
1643 } else {
1644 parseCodeSection(numberOfFuncs);
1645 }
1646
1647 var _nodes5 = [];
1648 return {
1649 nodes: _nodes5,
1650 metadata: _metadata5,
1651 nextSectionIndex: nextSectionIndex
1652 };
1653 }
1654
1655 case _helperWasmBytecode["default"].sections.start:
1656 {
1657 dumpSep("section Start");
1658 dump([sectionId], "section code");
1659 dump([sectionSizeInBytes], "section size");
1660
1661 var _metadata6 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode);
1662
1663 var _nodes6 = [parseStartSection()];
1664 return {
1665 nodes: _nodes6,
1666 metadata: _metadata6,
1667 nextSectionIndex: nextSectionIndex
1668 };
1669 }
1670
1671 case _helperWasmBytecode["default"].sections.element:
1672 {
1673 dumpSep("section Element");
1674 dump([sectionId], "section code");
1675 dump([sectionSizeInBytes], "section size");
1676
1677 var _startLoc19 = getPosition();
1678
1679 var numberOfElementsu32 = readU32();
1680 var numberOfElements = numberOfElementsu32.value;
1681 eatBytes(numberOfElementsu32.nextIndex);
1682
1683 var _metadata7 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () {
1684 var endLoc = getPosition();
1685 return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19);
1686 }());
1687
1688 var _nodes7 = parseElemSection(numberOfElements);
1689
1690 return {
1691 nodes: _nodes7,
1692 metadata: _metadata7,
1693 nextSectionIndex: nextSectionIndex
1694 };
1695 }
1696
1697 case _helperWasmBytecode["default"].sections.global:
1698 {
1699 dumpSep("section Global");
1700 dump([sectionId], "section code");
1701 dump([sectionSizeInBytes], "section size");
1702
1703 var _startLoc20 = getPosition();
1704
1705 var numberOfGlobalsu32 = readU32();
1706 var numberOfGlobals = numberOfGlobalsu32.value;
1707 eatBytes(numberOfGlobalsu32.nextIndex);
1708
1709 var _metadata8 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () {
1710 var endLoc = getPosition();
1711 return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20);
1712 }());
1713
1714 var _nodes8 = parseGlobalSection(numberOfGlobals);
1715
1716 return {
1717 nodes: _nodes8,
1718 metadata: _metadata8,
1719 nextSectionIndex: nextSectionIndex
1720 };
1721 }
1722
1723 case _helperWasmBytecode["default"].sections.memory:
1724 {
1725 dumpSep("section Memory");
1726 dump([sectionId], "section code");
1727 dump([sectionSizeInBytes], "section size");
1728
1729 var _startLoc21 = getPosition();
1730
1731 var _numberOfElementsu = readU32();
1732
1733 var _numberOfElements = _numberOfElementsu.value;
1734 eatBytes(_numberOfElementsu.nextIndex);
1735
1736 var _metadata9 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () {
1737 var endLoc = getPosition();
1738 return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21);
1739 }());
1740
1741 var _nodes9 = parseMemorySection(_numberOfElements);
1742
1743 return {
1744 nodes: _nodes9,
1745 metadata: _metadata9,
1746 nextSectionIndex: nextSectionIndex
1747 };
1748 }
1749
1750 case _helperWasmBytecode["default"].sections.data:
1751 {
1752 dumpSep("section Data");
1753 dump([sectionId], "section code");
1754 dump([sectionSizeInBytes], "section size");
1755
1756 var _metadata10 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode);
1757
1758 var _startLoc22 = getPosition();
1759
1760 var _numberOfElementsu2 = readU32();
1761
1762 var _numberOfElements2 = _numberOfElementsu2.value;
1763 eatBytes(_numberOfElementsu2.nextIndex);
1764
1765 _metadata10.vectorOfSize = function () {
1766 var endLoc = getPosition();
1767 return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22);
1768 }();
1769
1770 if (opts.ignoreDataSection === true) {
1771 var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex;
1772
1773 eatBytes(_remainingBytes); // eat the entire section
1774
1775 dumpSep("ignore data (" + sectionSizeInBytes + " bytes)");
1776 return {
1777 nodes: [],
1778 metadata: _metadata10,
1779 nextSectionIndex: nextSectionIndex
1780 };
1781 } else {
1782 var _nodes10 = parseDataSection(_numberOfElements2);
1783
1784 return {
1785 nodes: _nodes10,
1786 metadata: _metadata10,
1787 nextSectionIndex: nextSectionIndex
1788 };
1789 }
1790 }
1791
1792 case _helperWasmBytecode["default"].sections.custom:
1793 {
1794 dumpSep("section Custom");
1795 dump([sectionId], "section code");
1796 dump([sectionSizeInBytes], "section size");
1797 var _metadata11 = [t.sectionMetadata("custom", startOffset, sectionSizeInBytesNode)];
1798 var sectionName = readUTF8String();
1799 eatBytes(sectionName.nextIndex);
1800 dump([], "section name (".concat(sectionName.value, ")"));
1801
1802 var _remainingBytes2 = sectionSizeInBytes - sectionName.nextIndex;
1803
1804 if (sectionName.value === "name") {
1805 var initialOffset = offset;
1806
1807 try {
1808 _metadata11.push.apply(_metadata11, _toConsumableArray(parseNameSection(_remainingBytes2)));
1809 } catch (e) {
1810 console.warn("Failed to decode custom \"name\" section @".concat(offset, "; ignoring (").concat(e.message, ")."));
1811 eatBytes(offset - (initialOffset + _remainingBytes2));
1812 }
1813 } else if (sectionName.value === "producers") {
1814 var _initialOffset = offset;
1815
1816 try {
1817 _metadata11.push(parseProducersSection());
1818 } catch (e) {
1819 console.warn("Failed to decode custom \"producers\" section @".concat(offset, "; ignoring (").concat(e.message, ")."));
1820 eatBytes(offset - (_initialOffset + _remainingBytes2));
1821 }
1822 } else {
1823 // We don't parse the custom section
1824 eatBytes(_remainingBytes2);
1825 dumpSep("ignore custom " + JSON.stringify(sectionName.value) + " section (" + _remainingBytes2 + " bytes)");
1826 }
1827
1828 return {
1829 nodes: [],
1830 metadata: _metadata11,
1831 nextSectionIndex: nextSectionIndex
1832 };
1833 }
1834 }
1835
1836 if (opts.errorOnUnknownSection) {
1837 throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId));
1838 } else {
1839 dumpSep("section " + toHex(sectionId));
1840 dump([sectionId], "section code");
1841 dump([sectionSizeInBytes], "section size");
1842 eatBytes(sectionSizeInBytes);
1843 dumpSep("ignoring (" + sectionSizeInBytes + " bytes)");
1844 return {
1845 nodes: [],
1846 metadata: [],
1847 nextSectionIndex: 0
1848 };
1849 }
1850 }
1851
1852 function parseBlockType() {
1853 var blocktypeByte = readByte();
1854 var blocktype = _helperWasmBytecode["default"].blockTypes[blocktypeByte];
1855
1856 if (typeof blocktype !== "undefined") {
1857 eatBytes(1);
1858 dump([blocktypeByte], "blocktype"); // value type
1859
1860 return blocktype;
1861 } else {
1862 // type index
1863 var u32 = readU32();
1864 eatBytes(u32.nextIndex);
1865 var signature = state.typesInModule[u32.value];
1866 console.log({
1867 signature: signature
1868 });
1869 dump([u32.value], "typeidx");
1870 return u32.value;
1871 }
1872 }
1873
1874 parseModuleHeader();
1875 parseVersion();
1876 var moduleFields = [];
1877 var sectionIndex = 0;
1878 var moduleMetadata = {
1879 sections: [],
1880 functionNames: [],
1881 localNames: [],
1882 producers: []
1883 };
1884 /**
1885 * All the generate declaration are going to be stored in our state
1886 */
1887
1888 while (offset < buf.length) {
1889 var _parseSection = parseSection(sectionIndex),
1890 nodes = _parseSection.nodes,
1891 metadata = _parseSection.metadata,
1892 nextSectionIndex = _parseSection.nextSectionIndex;
1893
1894 moduleFields.push.apply(moduleFields, _toConsumableArray(nodes));
1895 var metadataArray = Array.isArray(metadata) ? metadata : [metadata];
1896 metadataArray.forEach(function (metadataItem) {
1897 // $FlowIgnore
1898 if (metadataItem.type === "FunctionNameMetadata") {
1899 moduleMetadata.functionNames.push(metadataItem); // $FlowIgnore
1900 } else if (metadataItem.type === "LocalNameMetadata") {
1901 moduleMetadata.localNames.push(metadataItem); // $FlowIgnore
1902 } else if (metadataItem.type === "ProducersSectionMetadata") {
1903 moduleMetadata.producers.push(metadataItem);
1904 } else {
1905 moduleMetadata.sections.push(metadataItem);
1906 }
1907 }); // Ignore custom section
1908
1909 if (nextSectionIndex) {
1910 sectionIndex = nextSectionIndex;
1911 }
1912 }
1913 /**
1914 * Transform the state into AST nodes
1915 */
1916
1917
1918 var funcIndex = 0;
1919 state.functionsInModule.forEach(function (func) {
1920 var params = func.signature.params;
1921 var result = func.signature.result;
1922 var body = []; // External functions doesn't provide any code, can skip it here
1923
1924 if (func.isExternal === true) {
1925 return;
1926 }
1927
1928 var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex];
1929
1930 if (opts.ignoreCodeSection === false) {
1931 if (typeof decodedElementInCodeSection === "undefined") {
1932 throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found");
1933 }
1934
1935 body = decodedElementInCodeSection.code;
1936 }
1937
1938 funcIndex++;
1939 var funcNode = t.func(func.id, t.signature(params, result), body);
1940
1941 if (func.isExternal === true) {
1942 funcNode.isExternal = func.isExternal;
1943 } // Add function position in the binary if possible
1944
1945
1946 if (opts.ignoreCodeSection === false) {
1947 var _startLoc23 = decodedElementInCodeSection.startLoc,
1948 endLoc = decodedElementInCodeSection.endLoc,
1949 bodySize = decodedElementInCodeSection.bodySize;
1950 funcNode = t.withLoc(funcNode, endLoc, _startLoc23);
1951 funcNode.metadata = {
1952 bodySize: bodySize
1953 };
1954 }
1955
1956 moduleFields.push(funcNode);
1957 });
1958 state.elementsInExportSection.forEach(function (moduleExport) {
1959 /**
1960 * If the export has no id, we won't be able to call it from the outside
1961 * so we can omit it
1962 */
1963 if (moduleExport.id != null) {
1964 moduleFields.push(t.withLoc(t.moduleExport(moduleExport.name, t.moduleExportDescr(moduleExport.type, moduleExport.id)), moduleExport.endLoc, moduleExport.startLoc));
1965 }
1966 });
1967 dumpSep("end of program");
1968 var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers));
1969 return t.program([module]);
1970}
Note: See TracBrowser for help on using the repository browser.