Projekt

Obecné

Profil

Stáhnout (52.9 KB) Statistiky
| Větev: | Revize:
1
"use strict";
2

    
3
Object.defineProperty(exports, "__esModule", {
4
  value: true
5
});
6
exports.decode = decode;
7

    
8
var _helperApiError = require("@webassemblyjs/helper-api-error");
9

    
10
var ieee754 = _interopRequireWildcard(require("@webassemblyjs/ieee754"));
11

    
12
var utf8 = _interopRequireWildcard(require("@webassemblyjs/utf8"));
13

    
14
var t = _interopRequireWildcard(require("@webassemblyjs/ast"));
15

    
16
var _leb = require("@webassemblyjs/leb128");
17

    
18
var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));
19

    
20
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21

    
22
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
23

    
24
function _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); } }
25

    
26
function toHex(n) {
27
  return "0x" + Number(n).toString(16);
28
}
29

    
30
function byteArrayEq(l, r) {
31
  if (l.length !== r.length) {
32
    return false;
33
  }
34

    
35
  for (var i = 0; i < l.length; i++) {
36
    if (l[i] !== r[i]) {
37
      return false;
38
    }
39
  }
40

    
41
  return true;
42
}
43

    
44
function decode(ab, opts) {
45
  var buf = new Uint8Array(ab);
46
  var getUniqueName = t.getUniqueNameGenerator();
47
  var offset = 0;
48

    
49
  function getPosition() {
50
    return {
51
      line: -1,
52
      column: offset
53
    };
54
  }
55

    
56
  function dump(b, msg) {
57
    if (opts.dump === false) return;
58
    var pad = "\t\t\t\t\t\t\t\t\t\t";
59
    var str = "";
60

    
61
    if (b.length < 5) {
62
      str = b.map(toHex).join(" ");
63
    } else {
64
      str = "...";
65
    }
66

    
67
    console.log(toHex(offset) + ":\t", str, pad, ";", msg);
68
  }
69

    
70
  function dumpSep(msg) {
71
    if (opts.dump === false) return;
72
    console.log(";", msg);
73
  }
74
  /**
75
   * TODO(sven): we can atually use a same structure
76
   * we are adding incrementally new features
77
   */
78

    
79

    
80
  var state = {
81
    elementsInFuncSection: [],
82
    elementsInExportSection: [],
83
    elementsInCodeSection: [],
84

    
85
    /**
86
     * Decode memory from:
87
     * - Memory section
88
     */
89
    memoriesInModule: [],
90

    
91
    /**
92
     * Decoded types from:
93
     * - Type section
94
     */
95
    typesInModule: [],
96

    
97
    /**
98
     * Decoded functions from:
99
     * - Function section
100
     * - Import section
101
     */
102
    functionsInModule: [],
103

    
104
    /**
105
     * Decoded tables from:
106
     * - Table section
107
     */
108
    tablesInModule: [],
109

    
110
    /**
111
     * Decoded globals from:
112
     * - Global section
113
     */
114
    globalsInModule: []
115
  };
116

    
117
  function isEOF() {
118
    return offset >= buf.length;
119
  }
120

    
121
  function eatBytes(n) {
122
    offset = offset + n;
123
  }
124

    
125
  function readBytesAtOffset(_offset, numberOfBytes) {
126
    var arr = [];
127

    
128
    for (var i = 0; i < numberOfBytes; i++) {
129
      arr.push(buf[_offset + i]);
130
    }
131

    
132
    return arr;
133
  }
134

    
135
  function readBytes(numberOfBytes) {
136
    return readBytesAtOffset(offset, numberOfBytes);
137
  }
138

    
139
  function readF64() {
140
    var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64);
141
    var value = ieee754.decodeF64(bytes);
142

    
143
    if (Math.sign(value) * value === Infinity) {
144
      return {
145
        value: Math.sign(value),
146
        inf: true,
147
        nextIndex: ieee754.NUMBER_OF_BYTE_F64
148
      };
149
    }
150

    
151
    if (isNaN(value)) {
152
      var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1;
153
      var mantissa = 0;
154

    
155
      for (var i = 0; i < bytes.length - 2; ++i) {
156
        mantissa += bytes[i] * Math.pow(256, i);
157
      }
158

    
159
      mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2);
160
      return {
161
        value: sign * mantissa,
162
        nan: true,
163
        nextIndex: ieee754.NUMBER_OF_BYTE_F64
164
      };
165
    }
166

    
167
    return {
168
      value: value,
169
      nextIndex: ieee754.NUMBER_OF_BYTE_F64
170
    };
171
  }
172

    
173
  function readF32() {
174
    var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32);
175
    var value = ieee754.decodeF32(bytes);
176

    
177
    if (Math.sign(value) * value === Infinity) {
178
      return {
179
        value: Math.sign(value),
180
        inf: true,
181
        nextIndex: ieee754.NUMBER_OF_BYTE_F32
182
      };
183
    }
184

    
185
    if (isNaN(value)) {
186
      var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1;
187
      var mantissa = 0;
188

    
189
      for (var i = 0; i < bytes.length - 2; ++i) {
190
        mantissa += bytes[i] * Math.pow(256, i);
191
      }
192

    
193
      mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2);
194
      return {
195
        value: sign * mantissa,
196
        nan: true,
197
        nextIndex: ieee754.NUMBER_OF_BYTE_F32
198
      };
199
    }
200

    
201
    return {
202
      value: value,
203
      nextIndex: ieee754.NUMBER_OF_BYTE_F32
204
    };
205
  }
206

    
207
  function readUTF8String() {
208
    var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using
209
    // readBytesAtOffset below. This keeps readUTF8String neutral with respect
210
    // to the current offset, just like the other readX functions.
211

    
212
    var strlen = lenu32.value;
213
    dump([strlen], "string length");
214
    var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen);
215
    var value = utf8.decode(bytes);
216
    return {
217
      value: value,
218
      nextIndex: strlen + lenu32.nextIndex
219
    };
220
  }
221
  /**
222
   * Decode an unsigned 32bits integer
223
   *
224
   * The length will be handled by the leb librairy, we pass the max number of
225
   * byte.
226
   */
227

    
228

    
229
  function readU32() {
230
    var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32);
231
    var buffer = Buffer.from(bytes);
232
    return (0, _leb.decodeUInt32)(buffer);
233
  }
234

    
235
  function readVaruint32() {
236
    // where 32 bits = max 4 bytes
237
    var bytes = readBytes(4);
238
    var buffer = Buffer.from(bytes);
239
    return (0, _leb.decodeUInt32)(buffer);
240
  }
241

    
242
  function readVaruint7() {
243
    // where 7 bits = max 1 bytes
244
    var bytes = readBytes(1);
245
    var buffer = Buffer.from(bytes);
246
    return (0, _leb.decodeUInt32)(buffer);
247
  }
248
  /**
249
   * Decode a signed 32bits interger
250
   */
251

    
252

    
253
  function read32() {
254
    var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32);
255
    var buffer = Buffer.from(bytes);
256
    return (0, _leb.decodeInt32)(buffer);
257
  }
258
  /**
259
   * Decode a signed 64bits integer
260
   */
261

    
262

    
263
  function read64() {
264
    var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64);
265
    var buffer = Buffer.from(bytes);
266
    return (0, _leb.decodeInt64)(buffer);
267
  }
268

    
269
  function readU64() {
270
    var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64);
271
    var buffer = Buffer.from(bytes);
272
    return (0, _leb.decodeUInt64)(buffer);
273
  }
274

    
275
  function readByte() {
276
    return readBytes(1)[0];
277
  }
278

    
279
  function parseModuleHeader() {
280
    if (isEOF() === true || offset + 4 > buf.length) {
281
      throw new Error("unexpected end");
282
    }
283

    
284
    var header = readBytes(4);
285

    
286
    if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) {
287
      throw new _helperApiError.CompileError("magic header not detected");
288
    }
289

    
290
    dump(header, "wasm magic header");
291
    eatBytes(4);
292
  }
293

    
294
  function parseVersion() {
295
    if (isEOF() === true || offset + 4 > buf.length) {
296
      throw new Error("unexpected end");
297
    }
298

    
299
    var version = readBytes(4);
300

    
301
    if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) {
302
      throw new _helperApiError.CompileError("unknown binary version");
303
    }
304

    
305
    dump(version, "wasm version");
306
    eatBytes(4);
307
  }
308

    
309
  function parseVec(cast) {
310
    var u32 = readU32();
311
    var length = u32.value;
312
    eatBytes(u32.nextIndex);
313
    dump([length], "number");
314

    
315
    if (length === 0) {
316
      return [];
317
    }
318

    
319
    var elements = [];
320

    
321
    for (var i = 0; i < length; i++) {
322
      var byte = readByte();
323
      eatBytes(1);
324
      var value = cast(byte);
325
      dump([byte], value);
326

    
327
      if (typeof value === "undefined") {
328
        throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value");
329
      }
330

    
331
      elements.push(value);
332
    }
333

    
334
    return elements;
335
  } // Type section
336
  // https://webassembly.github.io/spec/binary/modules.html#binary-typesec
337

    
338

    
339
  function parseTypeSection(numberOfTypes) {
340
    var typeInstructionNodes = [];
341
    dump([numberOfTypes], "num types");
342

    
343
    for (var i = 0; i < numberOfTypes; i++) {
344
      var _startLoc = getPosition();
345

    
346
      dumpSep("type " + i);
347
      var type = readByte();
348
      eatBytes(1);
349

    
350
      if (type == _helperWasmBytecode.default.types.func) {
351
        dump([type], "func");
352
        var paramValtypes = parseVec(function (b) {
353
          return _helperWasmBytecode.default.valtypes[b];
354
        });
355
        var params = paramValtypes.map(function (v) {
356
          return t.funcParam(
357
          /*valtype*/
358
          v);
359
        });
360
        var result = parseVec(function (b) {
361
          return _helperWasmBytecode.default.valtypes[b];
362
        });
363
        typeInstructionNodes.push(function () {
364
          var endLoc = getPosition();
365
          return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc);
366
        }());
367
        state.typesInModule.push({
368
          params: params,
369
          result: result
370
        });
371
      } else {
372
        throw new Error("Unsupported type: " + toHex(type));
373
      }
374
    }
375

    
376
    return typeInstructionNodes;
377
  } // Import section
378
  // https://webassembly.github.io/spec/binary/modules.html#binary-importsec
379

    
380

    
381
  function parseImportSection(numberOfImports) {
382
    var imports = [];
383

    
384
    for (var i = 0; i < numberOfImports; i++) {
385
      dumpSep("import header " + i);
386

    
387
      var _startLoc2 = getPosition();
388
      /**
389
       * Module name
390
       */
391

    
392

    
393
      var moduleName = readUTF8String();
394
      eatBytes(moduleName.nextIndex);
395
      dump([], "module name (".concat(moduleName.value, ")"));
396
      /**
397
       * Name
398
       */
399

    
400
      var name = readUTF8String();
401
      eatBytes(name.nextIndex);
402
      dump([], "name (".concat(name.value, ")"));
403
      /**
404
       * Import descr
405
       */
406

    
407
      var descrTypeByte = readByte();
408
      eatBytes(1);
409
      var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte];
410
      dump([descrTypeByte], "import kind");
411

    
412
      if (typeof descrType === "undefined") {
413
        throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte));
414
      }
415

    
416
      var importDescr = void 0;
417

    
418
      if (descrType === "func") {
419
        var indexU32 = readU32();
420
        var typeindex = indexU32.value;
421
        eatBytes(indexU32.nextIndex);
422
        dump([typeindex], "type index");
423
        var signature = state.typesInModule[typeindex];
424

    
425
        if (typeof signature === "undefined") {
426
          throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")"));
427
        }
428

    
429
        var id = getUniqueName("func");
430
        importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result));
431
        state.functionsInModule.push({
432
          id: t.identifier(name.value),
433
          signature: signature,
434
          isExternal: true
435
        });
436
      } else if (descrType === "global") {
437
        importDescr = parseGlobalType();
438
        var globalNode = t.global(importDescr, []);
439
        state.globalsInModule.push(globalNode);
440
      } else if (descrType === "table") {
441
        importDescr = parseTableType(i);
442
      } else if (descrType === "mem") {
443
        var memoryNode = parseMemoryType(0);
444
        state.memoriesInModule.push(memoryNode);
445
        importDescr = memoryNode;
446
      } else {
447
        throw new _helperApiError.CompileError("Unsupported import of type: " + descrType);
448
      }
449

    
450
      imports.push(function () {
451
        var endLoc = getPosition();
452
        return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2);
453
      }());
454
    }
455

    
456
    return imports;
457
  } // Function section
458
  // https://webassembly.github.io/spec/binary/modules.html#function-section
459

    
460

    
461
  function parseFuncSection(numberOfFunctions) {
462
    dump([numberOfFunctions], "num funcs");
463

    
464
    for (var i = 0; i < numberOfFunctions; i++) {
465
      var indexU32 = readU32();
466
      var typeindex = indexU32.value;
467
      eatBytes(indexU32.nextIndex);
468
      dump([typeindex], "type index");
469
      var signature = state.typesInModule[typeindex];
470

    
471
      if (typeof signature === "undefined") {
472
        throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")"));
473
      } // preserve anonymous, a name might be resolved later
474

    
475

    
476
      var id = t.withRaw(t.identifier(getUniqueName("func")), "");
477
      state.functionsInModule.push({
478
        id: id,
479
        signature: signature,
480
        isExternal: false
481
      });
482
    }
483
  } // Export section
484
  // https://webassembly.github.io/spec/binary/modules.html#export-section
485

    
486

    
487
  function parseExportSection(numberOfExport) {
488
    dump([numberOfExport], "num exports"); // Parse vector of exports
489

    
490
    for (var i = 0; i < numberOfExport; i++) {
491
      var _startLoc3 = getPosition();
492
      /**
493
       * Name
494
       */
495

    
496

    
497
      var name = readUTF8String();
498
      eatBytes(name.nextIndex);
499
      dump([], "export name (".concat(name.value, ")"));
500
      /**
501
       * exportdescr
502
       */
503

    
504
      var typeIndex = readByte();
505
      eatBytes(1);
506
      dump([typeIndex], "export kind");
507
      var indexu32 = readU32();
508
      var index = indexu32.value;
509
      eatBytes(indexu32.nextIndex);
510
      dump([index], "export index");
511
      var id = void 0,
512
          signature = void 0;
513

    
514
      if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") {
515
        var func = state.functionsInModule[index];
516

    
517
        if (typeof func === "undefined") {
518
          throw new _helperApiError.CompileError("unknown function (".concat(index, ")"));
519
        }
520

    
521
        id = t.numberLiteralFromRaw(index, String(index));
522
        signature = func.signature;
523
      } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") {
524
        var table = state.tablesInModule[index];
525

    
526
        if (typeof table === "undefined") {
527
          throw new _helperApiError.CompileError("unknown table ".concat(index));
528
        }
529

    
530
        id = t.numberLiteralFromRaw(index, String(index));
531
        signature = null;
532
      } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") {
533
        var memNode = state.memoriesInModule[index];
534

    
535
        if (typeof memNode === "undefined") {
536
          throw new _helperApiError.CompileError("unknown memory ".concat(index));
537
        }
538

    
539
        id = t.numberLiteralFromRaw(index, String(index));
540
        signature = null;
541
      } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") {
542
        var global = state.globalsInModule[index];
543

    
544
        if (typeof global === "undefined") {
545
          throw new _helperApiError.CompileError("unknown global ".concat(index));
546
        }
547

    
548
        id = t.numberLiteralFromRaw(index, String(index));
549
        signature = null;
550
      } else {
551
        console.warn("Unsupported export type: " + toHex(typeIndex));
552
        return;
553
      }
554

    
555
      var endLoc = getPosition();
556
      state.elementsInExportSection.push({
557
        name: name.value,
558
        type: _helperWasmBytecode.default.exportTypes[typeIndex],
559
        signature: signature,
560
        id: id,
561
        index: index,
562
        endLoc: endLoc,
563
        startLoc: _startLoc3
564
      });
565
    }
566
  } // Code section
567
  // https://webassembly.github.io/spec/binary/modules.html#code-section
568

    
569

    
570
  function parseCodeSection(numberOfFuncs) {
571
    dump([numberOfFuncs], "number functions"); // Parse vector of function
572

    
573
    for (var i = 0; i < numberOfFuncs; i++) {
574
      var _startLoc4 = getPosition();
575

    
576
      dumpSep("function body " + i); // the u32 size of the function code in bytes
577
      // Ignore it for now
578

    
579
      var bodySizeU32 = readU32();
580
      eatBytes(bodySizeU32.nextIndex);
581
      dump([bodySizeU32.value], "function body size");
582
      var code = [];
583
      /**
584
       * Parse locals
585
       */
586

    
587
      var funcLocalNumU32 = readU32();
588
      var funcLocalNum = funcLocalNumU32.value;
589
      eatBytes(funcLocalNumU32.nextIndex);
590
      dump([funcLocalNum], "num locals");
591
      var locals = [];
592

    
593
      for (var _i = 0; _i < funcLocalNum; _i++) {
594
        var _startLoc5 = getPosition();
595

    
596
        var localCountU32 = readU32();
597
        var localCount = localCountU32.value;
598
        eatBytes(localCountU32.nextIndex);
599
        dump([localCount], "num local");
600
        var valtypeByte = readByte();
601
        eatBytes(1);
602
        var type = _helperWasmBytecode.default.valtypes[valtypeByte];
603
        var args = [];
604

    
605
        for (var _i2 = 0; _i2 < localCount; _i2++) {
606
          args.push(t.valtypeLiteral(type));
607
        }
608

    
609
        var localNode = function () {
610
          var endLoc = getPosition();
611
          return t.withLoc(t.instruction("local", args), endLoc, _startLoc5);
612
        }();
613

    
614
        locals.push(localNode);
615
        dump([valtypeByte], type);
616

    
617
        if (typeof type === "undefined") {
618
          throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte));
619
        }
620
      }
621

    
622
      code.push.apply(code, locals); // Decode instructions until the end
623

    
624
      parseInstructionBlock(code);
625
      var endLoc = getPosition();
626
      state.elementsInCodeSection.push({
627
        code: code,
628
        locals: locals,
629
        endLoc: endLoc,
630
        startLoc: _startLoc4,
631
        bodySize: bodySizeU32.value
632
      });
633
    }
634
  }
635

    
636
  function parseInstructionBlock(code) {
637
    while (true) {
638
      var _startLoc6 = getPosition();
639

    
640
      var instructionAlreadyCreated = false;
641
      var instructionByte = readByte();
642
      eatBytes(1);
643

    
644
      if (instructionByte === 0xfe) {
645
        throw new _helperApiError.CompileError("Atomic instructions are not implemented");
646
      }
647

    
648
      var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte];
649

    
650
      if (typeof instruction === "undefined") {
651
        throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte));
652
      }
653

    
654
      if (typeof instruction.object === "string") {
655
        dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name));
656
      } else {
657
        dump([instructionByte], instruction.name);
658
      }
659
      /**
660
       * End of the function
661
       */
662

    
663

    
664
      if (instruction.name === "end") {
665
        var node = function () {
666
          var endLoc = getPosition();
667
          return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6);
668
        }();
669

    
670
        code.push(node);
671
        break;
672
      }
673

    
674
      var args = [];
675

    
676
      if (instruction.name === "loop") {
677
        var _startLoc7 = getPosition();
678

    
679
        var blocktypeByte = readByte();
680
        eatBytes(1);
681
        var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte];
682
        dump([blocktypeByte], "blocktype");
683

    
684
        if (typeof blocktype === "undefined") {
685
          throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(blocktypeByte));
686
        }
687

    
688
        var instr = [];
689
        parseInstructionBlock(instr); // preserve anonymous
690

    
691
        var label = t.withRaw(t.identifier(getUniqueName("loop")), "");
692

    
693
        var loopNode = function () {
694
          var endLoc = getPosition();
695
          return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7);
696
        }();
697

    
698
        code.push(loopNode);
699
        instructionAlreadyCreated = true;
700
      } else if (instruction.name === "if") {
701
        var _startLoc8 = getPosition();
702

    
703
        var _blocktypeByte = readByte();
704

    
705
        eatBytes(1);
706
        var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte];
707
        dump([_blocktypeByte], "blocktype");
708

    
709
        if (typeof _blocktype === "undefined") {
710
          throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte));
711
        }
712

    
713
        var testIndex = t.withRaw(t.identifier(getUniqueName("if")), "");
714
        var ifBody = [];
715
        parseInstructionBlock(ifBody); // Defaults to no alternate
716

    
717
        var elseIndex = 0;
718

    
719
        for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) {
720
          var _instr = ifBody[elseIndex];
721

    
722
          if (_instr.type === "Instr" && _instr.id === "else") {
723
            break;
724
          }
725
        }
726

    
727
        var consequentInstr = ifBody.slice(0, elseIndex);
728
        var alternate = ifBody.slice(elseIndex + 1); // wast sugar
729

    
730
        var testInstrs = [];
731

    
732
        var ifNode = function () {
733
          var endLoc = getPosition();
734
          return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8);
735
        }();
736

    
737
        code.push(ifNode);
738
        instructionAlreadyCreated = true;
739
      } else if (instruction.name === "block") {
740
        var _startLoc9 = getPosition();
741

    
742
        var _blocktypeByte2 = readByte();
743

    
744
        eatBytes(1);
745
        var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2];
746
        dump([_blocktypeByte2], "blocktype");
747

    
748
        if (typeof _blocktype2 === "undefined") {
749
          throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2));
750
        }
751

    
752
        var _instr2 = [];
753
        parseInstructionBlock(_instr2); // preserve anonymous
754

    
755
        var _label = t.withRaw(t.identifier(getUniqueName("block")), "");
756

    
757
        var blockNode = function () {
758
          var endLoc = getPosition();
759
          return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9);
760
        }();
761

    
762
        code.push(blockNode);
763
        instructionAlreadyCreated = true;
764
      } else if (instruction.name === "call") {
765
        var indexu32 = readU32();
766
        var index = indexu32.value;
767
        eatBytes(indexu32.nextIndex);
768
        dump([index], "index");
769

    
770
        var callNode = function () {
771
          var endLoc = getPosition();
772
          return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6);
773
        }();
774

    
775
        code.push(callNode);
776
        instructionAlreadyCreated = true;
777
      } else if (instruction.name === "call_indirect") {
778
        var _startLoc10 = getPosition();
779

    
780
        var indexU32 = readU32();
781
        var typeindex = indexU32.value;
782
        eatBytes(indexU32.nextIndex);
783
        dump([typeindex], "type index");
784
        var signature = state.typesInModule[typeindex];
785

    
786
        if (typeof signature === "undefined") {
787
          throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")"));
788
        }
789

    
790
        var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []);
791

    
792
        var flagU32 = readU32();
793
        var flag = flagU32.value; // 0x00 - reserved byte
794

    
795
        eatBytes(flagU32.nextIndex);
796

    
797
        if (flag !== 0) {
798
          throw new _helperApiError.CompileError("zero flag expected");
799
        }
800

    
801
        code.push(function () {
802
          var endLoc = getPosition();
803
          return t.withLoc(_callNode, endLoc, _startLoc10);
804
        }());
805
        instructionAlreadyCreated = true;
806
      } else if (instruction.name === "br_table") {
807
        var indicesu32 = readU32();
808
        var indices = indicesu32.value;
809
        eatBytes(indicesu32.nextIndex);
810
        dump([indices], "num indices");
811

    
812
        for (var i = 0; i <= indices; i++) {
813
          var _indexu = readU32();
814

    
815
          var _index = _indexu.value;
816
          eatBytes(_indexu.nextIndex);
817
          dump([_index], "index");
818
          args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32"));
819
        }
820
      } else if (instructionByte >= 0x28 && instructionByte <= 0x40) {
821
        /**
822
         * Memory instructions
823
         */
824
        if (instruction.name === "grow_memory" || instruction.name === "current_memory") {
825
          var _indexU = readU32();
826

    
827
          var _index2 = _indexU.value;
828
          eatBytes(_indexU.nextIndex);
829

    
830
          if (_index2 !== 0) {
831
            throw new Error("zero flag expected");
832
          }
833

    
834
          dump([_index2], "index");
835
        } else {
836
          var aligun32 = readU32();
837
          var align = aligun32.value;
838
          eatBytes(aligun32.nextIndex);
839
          dump([align], "align");
840
          var offsetu32 = readU32();
841
          var _offset2 = offsetu32.value;
842
          eatBytes(offsetu32.nextIndex);
843
          dump([_offset2], "offset");
844
        }
845
      } else if (instructionByte >= 0x41 && instructionByte <= 0x44) {
846
        /**
847
         * Numeric instructions
848
         */
849
        if (instruction.object === "i32") {
850
          var value32 = read32();
851
          var value = value32.value;
852
          eatBytes(value32.nextIndex);
853
          dump([value], "i32 value");
854
          args.push(t.numberLiteralFromRaw(value));
855
        }
856

    
857
        if (instruction.object === "u32") {
858
          var valueu32 = readU32();
859
          var _value = valueu32.value;
860
          eatBytes(valueu32.nextIndex);
861
          dump([_value], "u32 value");
862
          args.push(t.numberLiteralFromRaw(_value));
863
        }
864

    
865
        if (instruction.object === "i64") {
866
          var value64 = read64();
867
          var _value2 = value64.value;
868
          eatBytes(value64.nextIndex);
869
          dump([Number(_value2.toString())], "i64 value");
870
          var high = _value2.high,
871
              low = _value2.low;
872
          var _node = {
873
            type: "LongNumberLiteral",
874
            value: {
875
              high: high,
876
              low: low
877
            }
878
          };
879
          args.push(_node);
880
        }
881

    
882
        if (instruction.object === "u64") {
883
          var valueu64 = readU64();
884
          var _value3 = valueu64.value;
885
          eatBytes(valueu64.nextIndex);
886
          dump([Number(_value3.toString())], "u64 value");
887
          var _high = _value3.high,
888
              _low = _value3.low;
889
          var _node2 = {
890
            type: "LongNumberLiteral",
891
            value: {
892
              high: _high,
893
              low: _low
894
            }
895
          };
896
          args.push(_node2);
897
        }
898

    
899
        if (instruction.object === "f32") {
900
          var valuef32 = readF32();
901
          var _value4 = valuef32.value;
902
          eatBytes(valuef32.nextIndex);
903
          dump([_value4], "f32 value");
904
          args.push( // $FlowIgnore
905
          t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4)));
906
        }
907

    
908
        if (instruction.object === "f64") {
909
          var valuef64 = readF64();
910
          var _value5 = valuef64.value;
911
          eatBytes(valuef64.nextIndex);
912
          dump([_value5], "f64 value");
913
          args.push( // $FlowIgnore
914
          t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5)));
915
        }
916
      } else {
917
        for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) {
918
          var u32 = readU32();
919
          eatBytes(u32.nextIndex);
920
          dump([u32.value], "argument " + _i3);
921
          args.push(t.numberLiteralFromRaw(u32.value));
922
        }
923
      }
924

    
925
      if (instructionAlreadyCreated === false) {
926
        if (typeof instruction.object === "string") {
927
          var _node3 = function () {
928
            var endLoc = getPosition();
929
            return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args), endLoc, _startLoc6);
930
          }();
931

    
932
          code.push(_node3);
933
        } else {
934
          var _node4 = function () {
935
            var endLoc = getPosition();
936
            return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6);
937
          }();
938

    
939
          code.push(_node4);
940
        }
941
      }
942
    }
943
  } // https://webassembly.github.io/spec/core/binary/types.html#limits
944

    
945

    
946
  function parseLimits() {
947
    var limitType = readByte();
948
    eatBytes(1);
949
    dump([limitType], "limit type");
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);
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 = _helperWasmBytecode.default.tableTypes[elementTypeByte];
982

    
983
    if (typeof elementType === "undefined") {
984
      throw new _helperApiError.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 = _helperWasmBytecode.default.valtypes[valtypeByte];
996
    dump([valtypeByte], type);
997

    
998
    if (typeof type === "undefined") {
999
      throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte));
1000
    }
1001

    
1002
    var globalTypeByte = readByte();
1003
    eatBytes(1);
1004
    var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte];
1005
    dump([globalTypeByte], "global type (".concat(globalType, ")"));
1006

    
1007
    if (typeof globalType === "undefined") {
1008
      throw new _helperApiError.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 _helperApiError.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 === _helperWasmBytecode.default.sections.custom) {
1311
      sectionIndex = sectionId + 1;
1312
    } else {
1313
      if (sectionId !== _helperWasmBytecode.default.sections.custom) throw new _helperApiError.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperWasmBytecode.default.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 _helperApiError.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 _helperApiError.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
}
(1-1/2)