source: trip-planner-front/node_modules/@webassemblyjs/wasm-parser/esm/decoder.js@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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