# All files / src/utils print-node.js

92.13% Statements 117/127
70.27% Branches 26/37
90.63% Functions 29/32
92.06% Lines 116/126

    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
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235

    22x
    22x
    22x
    22x
    22x

    22x
    46950x
    46950x
    46950x
    46950x

    46950x
    1x

    46949x

    22x
    11x
    11x

    4x

    2x

    11x

    22x
    11x

    11x

    22x
    4x
    4x

    7008x

    1x
    1x

    2x
    2x

    2x

    2x

    2x
    2x
    2x

    1x

    470x
    448x
    448x
    448x

    22x

    46950x
    46950x
    46950x
    46950x

    2x

    52231x
    52231x

    33413x

    7x
    7x

    7x
    7x

    17224x
    17224x
    17224x

    181x
    181x

    181x
    181x

    1x
    1x

    1x

    1x
    1x

    13653x
    13653x
    13653x
    13653x
    13653x

    1099x
    1099x
    1099x

    339x
    339x
    339x

    578x
    578x
    578x
    578x
    578x

    14x
    14x
    14x
    14x
    14x

    16346x
    16346x
    16346x
    16346x
    16346x
    16346x
    16346x
    13279x
    13279x
    13279x

    16346x

    22x
    7008x

    7008x
    7008x
    7008x
    7008x
    7008x
    338605x
    338605x
    338605x
    338605x
    338605x

    7008x

    7008x
    7008x
    7008x
    338605x

    338605x

    7008x

     /* istanbul ignore file */
    // @flow
    import walkNode from "./walk-node";
    import Syntax from "../Syntax";
    import { GLOBAL_INDEX, TYPE_CONST } from "../semantics/metadata";
    import { opcodeFromOperator, getTypecastOpcode } from "../emitter/opcode";
    import { parseBounds } from "./resizable-limits";
    import type { NodeType, TypeCastType } from "../flow/types";

    const getText = (node: NodeType): string => {
      const value = node.value || "??";
      const hasType = node.type;
      const type = hasType || "i32";
      const op = opcodeFromOperator({ value, type });

      if (!hasType) {
        return op.text.replace("i32", "??");
      }

      return op.text;
    };

    const parseParams = (node: NodeType): string => {
      const params = [];
      walkNode({
        [Syntax.Pair]: (pair, _) => {
          params.push(`${pair.params[0].value} ${pair.params[1].value}`);
        },
        [Syntax.Type]: p => {
          params.push(p.value);
        },
      })(node);
      return params.length ? " param(" + params.join(" ") + ")" : "";
    };

    const parseResult = (node: ?NodeType): string => {
      Iif (node == null) {
        return "";
      }
      return " (result " + (node.type || "??") + ")";
    };

    const typedefString = (node: NodeType): string => {
      const [paramsNode, resultNode] = node.params;
      return (
        "(type " +
        node.value +
        ` (func${parseParams(paramsNode)}${parseResult(resultNode)}))`
      );
    };

    const getPrinters = add => ({
      [Syntax.Import]: (node, _print) => {
        const [nodes, mod] = node.params;
        walkNode({
          [Syntax.Pair]: ({ params }, _) => {
            const { value: field } = params[0];
            const type = params[1];

            Iif (type.value === "Memory") {
              const memory = parseBounds(type);
              add(
                `(import "${mod.value}" "${field}" (memory ${memory.initial}${
                  memory.max ? memory.max : ""
                }))`
              );
            } else {
              add(`(import "${mod.value}" "${field}" ${typedefString(type)})`);
            }
          },
        })(nodes);
      },
      [Syntax.Export]: (node, print) => {
        add("(export", 2);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.GenericType]: (node, _print) => {
        add("(type-generic " + node.value + ")", 0, 0, " pseudo type");
      },
      [Syntax.FunctionCall]: (node, print) => {
        if (node.params.length > 0) {
          add(`(call ${node.value}`, 2);
          node.params.forEach(print);
          add(")", 0, -2);
        } else {
          add(`(call ${node.value})`);
        }
      },
      [Syntax.BinaryExpression]: (node: NodeType, print) => {
        const text = getText(node);
        add("(" + text, 2);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.ArraySubscript]: (node: NodeType, print) => {
        add("(i32.add", 2);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.Typedef]: (node, _) => {
        add(typedefString(node));
      },
      [Syntax.Identifier]: node => {
        const scope = node.meta[GLOBAL_INDEX] != null ? "global" : "local";
        add(`(get_${scope} ${node.value})`);
      },
      [Syntax.Constant]: node => {
        add(`(${String(node.type)}.const ${node.value})`);
      },
      [Syntax.FunctionDeclaration]: (node, print) => {
        const [params, result, ...rest] = node.params;
        add(`(func ${node.value}${parseParams(params)}${parseResult(result)}`, 2);

        rest.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.ReturnStatement]: (node, print) => {
        add("(return", 2);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.Declaration]: (node, print) => {
        const mutability = node.meta[TYPE_CONST] != null ? "immutable" : "mutable";
        add(
          "(local " + node.value + " " + String(node.type),
          2,
          0,
          ` ${mutability}`
        );
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.ImmutableDeclaration]: (node, print) => {
        const scope = node.meta[GLOBAL_INDEX] != null ? "global" : "local";
        Iif (node.type === "Memory") {
          const memory = parseBounds(node);
          add(`(memory ${memory.initial}${memory.max ? ` ${memory.max}` : ""})`);
        } else {
          add(
            `(${scope} ` + node.value + " " + String(node.type),
            2,
            0,
            " immutable"
          );
          node.params.forEach(print);
          add(")", 0, -2);
        }
      },
      [Syntax.Type]: node => {
        add(node.value);
      },
      [Syntax.TypeCast]: (node: TypeCastType, print) => {
        const from = node.params[0];
        const op = getTypecastOpcode(String(node.type), from.type);
        add("(" + op.text, 2);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.ArraySubscript]: (node, print) => {
        add("(" + String(node.type) + ".load", 2, 0);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.MemoryAssignment]: (node, print) => {
        add("(" + String(node.type) + ".store", 2, 0);
        node.params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.Assignment]: (node, print) => {
        const [target, ...params] = node.params;
        const scope = target.meta[GLOBAL_INDEX] != null ? "global" : "local";
        add(`(set_${scope} ${target.value}`, 2);
        params.forEach(print);
        add(")", 0, -2);
      },
      [Syntax.TernaryExpression]: (node, print) => {
        const [condition, options] = node.params;
        add("(select", 2);
        print(options);
        print(condition);
        add(")", 0, -2);
      },
      [Syntax.IfThenElse]: (node, print) => {
        const [condition, then, ...rest] = node.params;
        add("(if", 2);
        print(condition);
        add("(then", 2);
        print(then);
        add(")", 0, -2);
        if (rest.length > 0) {
          add("(else", 2);
          rest.forEach(print);
          add(")", 0, -2);
        }
        add(")", 0, -2);
      },
      [Syntax.ObjectLiteral]: (_, __) => {},
    });

    const printNode = (node?: NodeType): string => {
      Iif (node == null) {
        return "";
      }

      let depth = 0;
      const offsets = [];
      const pieces = [];
      const comments = [];
      const add = (piece, post = 0, pre = 0, comment = "") => {
        depth += pre;
        comments.push(comment);
        pieces.push(piece);
        offsets.push(depth + piece.length);
        depth += post;
      };

      walkNode(getPrinters(add))(node);

      const max = Math.max(...offsets);
      const edge = max + 4;
      const result = pieces.reduce((acc, val, i) => {
        acc +=
          val.padStart(offsets[i], " ").padEnd(edge, " ") +
          ";" +
          comments[i] +
          "\n";
        return acc;
      }, "");

      return result;
    };

    export default printNode;