All files / src/generator import.js

100% Statements 33/33
100% Branches 13/13
100% Functions 5/5
100% Lines 33/33
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           21x     21x 36x   8x   1x         2x   25x       21x 36x 36x 2x     34x           23x 23x 23x     23x   36x   36x 36x   36x   36x 36x 36x 11x   25x     36x   36x                       23x    
// @flow
import Syntax from 'walt-syntax';
import walkNode from 'walt-parser-tools/walk-node';
import { stringToType } from '../emitter/value_type';
import { parseBounds } from '../utils/resizable-limits';
import {
  EXTERN_FUNCTION,
  EXTERN_MEMORY,
  EXTERN_GLOBAL,
  EXTERN_TABLE,
} from '../emitter/external_kind';
import { TYPE_INDEX } from '../semantics/metadata';
import type { IntermediateImportType, NodeType } from './flow/types';
 
export const getKindConstant = (value: string) => {
  switch (value) {
    case 'Memory':
      return EXTERN_MEMORY;
    case 'Table':
      return EXTERN_TABLE;
    case 'i32':
    case 'f32':
    case 'i64':
    case 'f64':
      return EXTERN_GLOBAL;
    default:
      return EXTERN_FUNCTION;
  }
};
 
const getFieldName = node => {
  let name = node.value;
  if (node.meta.AS != null) {
    return node.meta.AS;
  }
 
  return name;
};
 
export default function generateImportFromNode(
  node: NodeType
): IntermediateImportType[] {
  const [importsNode, moduleStringLiteralNode] = node.params;
  const { value: module } = moduleStringLiteralNode;
  const imports: IntermediateImportType[] = [];
 
  // Look for Pair Types, encode them into imports array
  walkNode({
    [Syntax.Pair]: (pairNode, _) => {
      const [fieldIdentifierNode, typeOrIdentifierNode] = pairNode.params;
 
      const field = getFieldName(fieldIdentifierNode);
      const { value: importTypeValue } = typeOrIdentifierNode;
 
      const kind = getKindConstant(importTypeValue);
 
      const typeIndex = (() => {
        const typeIndexMeta = typeOrIdentifierNode.meta[TYPE_INDEX];
        if (typeIndexMeta) {
          return typeIndexMeta;
        }
        return null;
      })();
      const bounds =
        importTypeValue === 'Memory' ? parseBounds(typeOrIdentifierNode) : {};
 
      imports.push({
        module,
        field,
        global: kind === EXTERN_GLOBAL,
        kind,
        type: stringToType[importTypeValue],
        typeIndex,
        ...bounds,
      });
    },
  })(importsNode);
 
  return imports;
}