# All files / src/generator memory-assignment.js

100% Statements 16/16
75% Branches 3/4
100% Functions 1/1
100% Lines 16/16

    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
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    22x
    22x
    22x
    22x

    22x
    29x
    29x
    29x

    29x

    29x

    15x

    15x

    29x

    29x

    29x

    29x

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

    const generateMemoryAssignment: GeneratorType = (node, parent) => {
      const targetNode = node.params[0];
      const isArray = targetNode.params[0].meta[TYPE_ARRAY];
      let type = node.type;

      const block = node.params[0].params
        .map(mapSyntax(parent))
        .reduce(mergeBlock, []);

      if (isArray != null) {
        // For array types, the index is multiplied by the contained object size
        block.push.apply(block, [
          // TODO: fix this for user-defined types
          { 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.apply(
        block,
        node.params
          .slice(1)
          .map(mapSyntax(parent))
          .reduce(mergeBlock, [])
      );

      // The last piece is the WASM opcode. Either load or store
      block.push({
        kind: opcode[(type || "i32") + "Store"],
        params: [
          // Alignment
          // TODO: make this extendible
          2,
          // Memory. Always 0 in the WASM MVP
          0,
        ],
      });

      return block;
    };

    export default generateMemoryAssignment;