All files / src/generator type.js

100% Statements 27/27
100% Branches 12/12
100% Functions 6/6
100% Lines 27/27
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        21x 21x 21x 21x       21x 382x   28x   16x   7x       331x       21x     265x 265x   265x 265x   99x 99x 99x       265x                   27x 27x             27x     27x   27x   38x       5x       27x            
// @flow
/**
 * Generate an Intermediate version for a WebAssembly function type
 **/
import invariant from 'invariant';
import Syntax from 'walt-syntax';
import walkNode from 'walt-parser-tools/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));
    },
    // Generate Identifiers as UserType pointers, so i32s
    [Syntax.Identifier]: (t, __) => {
      params.push(getType(t.value));
    },
  })(args);
 
  return {
    id,
    params,
    result: result.type && result.type !== 'void' ? getType(result.type) : null,
  };
}