All files / src/generator utils.js

100% Statements 27/27
100% Branches 15/15
100% Functions 4/4
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  23x 23x 23x 23x 23x 23x 23x       23x 503x 503x 503x   503x             502x 502x   502x               23x 131x   4x   4x   9x     114x       23x 281x     23x   131x       23x 23x  
// @flow
import { builtinTypes } from 'walt-syntax';
import opcode from '../emitter/opcode';
import curry from 'curry';
import invariant from 'invariant';
import { I32, I64, F32, F64 } from '../emitter/value_type';
import { LOCAL_INDEX, GLOBAL_INDEX, TYPE_CONST } from '../semantics/metadata';
import print from '../utils/print-node';
import type { IntermediateVariableType } from './flow/types';
import type { NodeType } from '../flow/types';
 
export const scopeOperation = curry((op, node) => {
  const local = node.meta[LOCAL_INDEX];
  const _global = node.meta[GLOBAL_INDEX];
  const index = local != null ? local : _global;
 
  invariant(
    index != null,
    `Undefined index for scope Operation. Possibly missing metadata. op: ${JSON.stringify(
      op
    )} node: ${print(node)}`
  );
 
  const kind = local != null ? op + 'Local' : op + 'Global';
  const params = [Number(index)];
 
  return {
    kind: opcode[kind],
    params,
    debug: `${node.value}<${node.meta.ALIAS || node.type}>`,
  };
});
 
// clean this up
export const getType = (str: ?string): number => {
  switch (str) {
    case builtinTypes.f32:
      return F32;
    case builtinTypes.f64:
      return F64;
    case builtinTypes.i64:
      return I64;
    case builtinTypes.i32:
    default:
      return I32;
  }
};
 
export const isBuiltinType = (type: ?string): boolean => {
  return typeof type === 'string' && builtinTypes[type] != null;
};
 
export const generateValueType = (
  node: NodeType
): IntermediateVariableType => ({
  mutable: node.meta[TYPE_CONST] ? 0 : 1,
  type: getType(node.type),
});
export const setInScope = scopeOperation('Set');
export const getInScope = scopeOperation('Get');