# All files / src/generator type.js

100% Statements 26/26
100% Branches 12/12
100% Functions 5/5
100% Lines 26/26

    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

    22x
    22x
    22x
    22x

    22x
    357x

    34x

    18x

    15x

    290x

    22x

    229x
    229x

    229x
    229x

    104x
    104x
    104x

    229x

    31x
    31x

    31x

    31x

    31x

    40x

    31x

     // @flow
    /**
     * Generate an Intermediate version for a WebAssembly function type
     **/
    import invariant from "invariant";
    import Syntax from "../Syntax";
    import walkNode from "../utils/walk-node";
    import { I32, F32, F64, I64 } from "../emitter/value_type";
    import type { IntermediateTypeDefinitionType, NodeType } from "./flow/types";

    // clean this up
    export const getType = (str: string): number => {
      switch (str) {
        case "f32":
          return F32;
        case "f64":
          return F64;
        case "i64":
          return I64;
        case "i32":
        case "Function":
        default:
          return I32;
      }
    };

    export const generateImplicitFunctionType = (
      functionNode: NodeType
    ): IntermediateTypeDefinitionType => {
      const [argsNode] = functionNode.params;
      const resultType = functionNode.type ? getType(functionNode.type) : null;

      const params = [];
      walkNode({
        [Syntax.Pair]: pairNode => {
          const typeNode = pairNode.params[1];
          invariant(typeNode, "Undefined type in a argument expression");
          params.push(getType(typeNode.value));
        },
      })(argsNode);

      return {
        params,
        result: resultType,
        id: functionNode.value,
      };
    };

    export default function generateType(
      node: NodeType
    ): IntermediateTypeDefinitionType {
      const id = node.value;
      invariant(
        typeof id === "string",
        `Generator: A type must have a valid string identifier, node: ${JSON.stringify(
          node
        )}`
      );

      const [args, result] = node.params;

      // Collect the function params and result by walking the tree of nodes
      const params = [];

      walkNode({
        [Syntax.Type]: (t, __) => {
          params.push(getType(t.value));
        },
      })(args);

      return {
        id,
        params,
        result: result.type && result.type !== "void" ? getType(result.type) : null,
      };
    }