# All files / src/core unary.js

100% Statements 14/14
80% Branches 4/5
100% Functions 3/3
100% Lines 13/13

    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

    23x

    23x

    81x

    81x
    81x
    86x

    170x
    86x

    1x
    1x

    1x

    1x

    84x

     /**
     * Unary operator plugin.
     *
     * @flow
     */
    import Syntax from 'walt-syntax';
    import type { SemanticPlugin } from '../flow/types';

    const shifts = {
      i64: 63,
      f64: 63,
      i32: 31,
      f32: 32,
    };
    // Unary expressions need to be patched so that the LHS type matches the RHS
    export default function(): SemanticPlugin {
      return {
        semantics({ fragment }) {
          return {
            [Syntax.UnaryExpression]: _ignore => (args, transform) => {
              const [unaryNode, context] = args;
              // While it's counter-intuitive that an unary operation would have two operands
              // it is simpler to always parse them as pseudo-binary and then simplify them here.
              const [lhs, rhs] = unaryNode.params.map(p => transform([p, context]));
              switch (unaryNode.value) {
                // Transform bang
                case '!':
                  const shift = shifts[lhs.type];
                  return transform([
                    fragment(
                      `(((${String(lhs.value)} >> ${shift}) | ((~${String(
                        lhs.value
                      )} + 1) >> ${shift})) + 1)`
                    ),
                    context,
                  ]);
                case '~':
                  const mask = ['i64', 'f64'].includes(
                    transform([lhs, context]).type
                  )
                    ? '0xffffffffffff'
                    : '0xffffff';
                  return transform([
                    fragment(`(${String(lhs.value)} ^ ${mask})`),
                    context,
                  ]);
                default:
                  return transform([
                    {
                      ...unaryNode,
                      type: rhs.type,
                      params: [
                        {
                          ...lhs,
                          type: rhs.type,
                        },
                        rhs,
                      ],
                      Type: Syntax.BinaryExpression,
                    },
                    context,
                  ]);
              }
            },
          };
        },
      };
    }