All files / json-expression/src/operators bitwise.ts

90.9% Statements 20/22
100% Branches 0/0
92.85% Functions 13/14
87.5% Lines 14/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 603x 3x     3x   3x           19x     7x 2x                 23x     7x 2x                 23x     7x 2x                 6x                
import * as util from '../util';
import {Expression, type ExpressionResult} from '../codegen-steps';
import type * as types from '../types';
 
const toInt = util.int;
 
export const bitwiseOperators: types.OperatorDefinition<any>[] = [
  [
    '&',
    ['bitAnd'],
    -1,
    (expr: types.ExprBitAnd, ctx) => {
      return expr.slice(2).reduce((acc, e) => acc & toInt(ctx.eval(e, ctx)), toInt(ctx.eval(expr[1], ctx)));
    },
    (ctx: types.OperatorCodegenCtx<types.ExprBitAnd>): ExpressionResult => {
      const js = ctx.operands.map((expr) => `(~~(${expr}))`).join('&');
      return new Expression(js);
    },
  ] as types.OperatorDefinition<types.ExprBitAnd>,
 
  [
    '|',
    ['bitOr'],
    -1,
    (expr: types.ExprBitOr, ctx) => {
      return expr.slice(2).reduce((acc, e) => acc | toInt(ctx.eval(e, ctx)), toInt(ctx.eval(expr[1], ctx)));
    },
    (ctx: types.OperatorCodegenCtx<types.ExprBitOr>): ExpressionResult => {
      const js = ctx.operands.map((expr) => `(~~(${expr}))`).join('|');
      return new Expression(js);
    },
  ] as types.OperatorDefinition<types.ExprBitOr>,
 
  [
    '^',
    ['bitXor'],
    -1,
    (expr: types.ExprBitXor, ctx) => {
      return expr.slice(2).reduce((acc, e) => acc ^ toInt(ctx.eval(e, ctx)), toInt(ctx.eval(expr[1], ctx)));
    },
    (ctx: types.OperatorCodegenCtx<types.ExprBitXor>): ExpressionResult => {
      const js = ctx.operands.map((expr) => `(~~(${expr}))`).join('^');
      return new Expression(js);
    },
  ] as types.OperatorDefinition<types.ExprBitXor>,
 
  [
    '~',
    ['bitNot'],
    1,
    (expr: types.ExprBitNot, ctx) => {
      return ~toInt(ctx.eval(expr[1], ctx));
    },
    (ctx: types.OperatorCodegenCtx<types.ExprBitNot>): ExpressionResult => {
      const js = `~(${ctx.operands[0]})`;
      return new Expression(js);
    },
  ] as types.OperatorDefinition<types.ExprBitNot>,
];