# All files / src/generator array-subscript.js

100% Statements 15/15
100% Branches 2/2
100% Functions 1/1
100% Lines 15/15

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    24x
    24x

    24x
    24x

    24x
    50x
    50x
    50x
    50x

    50x

    15x

    15x

    50x

    50x

    50x

     // @flow
    import opcode from "../emitter/opcode";
    import mergeBlock from "./merge-block";
    import type { GeneratorType } from "./flow/types";
    import { TYPE_ARRAY } from "../semantics/metadata";
    import mapSyntax from "./map-syntax";

    const generateArraySubscript: GeneratorType = (node, parent) => {
      const identifier = node.params[0];
      const isArray = identifier.meta[TYPE_ARRAY];
      const block = node.params.map(mapSyntax(parent)).reduce(mergeBlock, []);
      let type = node.type;

      if (isArray != null) {
        // For array types, the index is multiplied by the contained object size
        block.push.apply(block, [
          { kind: opcode.i32Const, params: [2] },
          { kind: opcode.i32Shl, params: [] },
        ]);
        type = isArray;
      }

      // The sequence of opcodes to perfrom a memory load is
      // get(Local|Global) base, i32Const offset[, i32Const size, i32Mul ], i32Add
      block.push({ kind: opcode.i32Add, params: [] });

      block.push({
        kind: opcode[String(type) + "Load"],
        params: [
          // Alignment
          2,
          // Memory. Always 0 in the WASM MVP
          0,
        ],
      });

      return block;
    };

    export default generateArraySubscript;