# All files / src/syntax-sugar sizeof.js

100% Statements 23/23
87.5% Branches 14/16
100% Functions 3/3
100% Lines 23/23

    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
    5723x
    23x
    23x

    23x

    87x

    87x
    87x
    196x

    196x
    176x

    20x
    20x
    20x
    20x
    20x
    20x
    20x

    20x
    10x
    10x
    10x

    10x

    10x

     import invariant from 'invariant';
    import Syntax from '../Syntax';
    import { OBJECT_SIZE } from '../semantics/metadata';

    const sizes = {
      i64: 8,
      f64: 8,
      i32: 4,
      f32: 4,
    };

    export default function sizeofPlugin() {
      return {
        semantics() {
          return {
            FunctionCall: next => args => {
              const [sizeof, context] = args;

              if (sizeof.value !== 'sizeof') {
                return next(args);
              }

              const { locals, globals, userTypes, functions } = context;
              const [target] = sizeof.params;
              const local = locals[target.value];
              const { type = '' } = local || {};
              const global = globals[target.value];
              const userType = userTypes[target.value] || userTypes[type];
              const func = functions[target.value];

              if (userType != null) {
                const metaSize = userType.meta[OBJECT_SIZE];
                invariant(metaSize, 'Object size information is missing');
                return {
                  ...sizeof,
                  value: metaSize,
                  params: [],
                  type: 'i32',
                  Type: Syntax.Constant,
                };
              }

              const node = local || global || func;

              return {
                ...sizeof,
                value: sizes[node ? node.type : target.value] || 4,
                type: 'i32',
                params: [],
                Type: Syntax.Constant,
              };
            },
          };
        },
      };
    }