All files / src/core bool.js

100% Statements 17/17
100% Branches 10/10
100% Functions 6/6
100% Lines 16/16
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              23x       90x   180x 209x 1x     208x   90x 90x 636x 636x 619x     17x                   90x 173x 3x     170x                
/**
 * Bool plugin.
 * Converts boolean identifiers to i32 constants, handles declarations with
 * type "bool".
 *
 * @flow
 */
import Syntax from 'walt-syntax';
import type { SemanticPlugin } from '../flow/types';
 
export default function booleanPlugin(): SemanticPlugin {
  return {
    semantics() {
      const declaration = next => ([decl, context]) => {
        if (decl.type === 'bool') {
          return next([{ ...decl, type: 'i32' }, context]);
        }
 
        return next([decl, context]);
      };
      return {
        [Syntax.Identifier]: next => (args, transform) => {
          const [id, context] = args;
          if (!(id.value === 'true' || id.value === 'false')) {
            return next(args);
          }
 
          return transform([
            {
              ...id,
              Type: Syntax.Constant,
              value: id.value === 'true' ? '1' : '0',
              type: 'i32',
            },
            context,
          ]);
        },
        [Syntax.FunctionResult]: next => ([result, context]) => {
          if (result.type === 'bool') {
            return next([{ ...result, type: 'i32' }, context]);
          }
 
          return next([result, context]);
        },
        [Syntax.Declaration]: declaration,
        [Syntax.ImmutableDeclaration]: declaration,
      };
    },
  };
}