source: imaps-frontend/node_modules/@webassemblyjs/wasm-parser/esm/decoder.js

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

F4 Finalna Verzija

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