# All files / src/semantics/map-function index.js

100% Statements 71/71
100% Branches 11/11
100% Functions 16/16
100% Lines 71/71

    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
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294

    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x

    23x
    23x
    23x

    23x

    23x
    165x

    165x

    165x
    165x

    165x

    169x

    75x
    75x
    75x

    75x

    165x

    165x

    4x

    161x

    151x

    165x

    165x

    23x

    165x

    165x
    165x
    165x
    165x
    165x

    165x

    165x

    165x

    165x

    71x
    71x

    279x

    2x
    2x

    11x

    58x
    58x
    58x

    786x
    786x
    58x

    58x

    58x

    49x
    49x
    49x

    177x
    177x

    1x

    176x

    4x
    4x
    4x

    4x

     // @flow
    /**
     * Function Semantics Parser.
     *
     * This is where 80% of the semantic logic lives. Pretty much everything in
     * WebAssembly is performed in some function. Most of the heavy logic is offloaded
     * to smaller parsers in here.
     */
    import Syntax from "../../Syntax";
    import curry from "curry";
    import mapNode from "../../utils/map-node";
    import { stringEncoder } from "../../utils/string";
    import { parseDeclaration } from "./declaration";
    import mapCharacterLiteral from "../map-char";
    import mapUnary from "../map-unary";
    import makeArraySubscript from "./map-subscript";
    import makeMapIdentifier from "./map-identifier";
    import makeSizeof from "./map-sizeof";
    import makeAssignment from "./map-assignment";
    import makeFunctionCall from "./map-function-call";
    import makeClosure, {
      injectEnvironmentMaybe,
      transformClosedDeclaration,
      getEnclosedVariables,
    } from "../closure";
    import makePair from "./map-pair";
    import walkNode from "../../utils/walk-node";
    import { balanceTypesInMathExpression } from "./patch-typecasts";
    import { collapseClosureIdentifier, CLOSURE_BASE } from "../closure";
    import {
      FUNCTION_INDEX,
      CLOSURE_TYPE,
      FUNCTION_METADATA,
      STATIC_STRING,
    } from "../metadata";
    import type { NodeType } from "../../flow/types";

    /**
     * Initialize function node and patch it's type and meta
     */
    const initialize = (options, node: NodeType): [NodeType, any, any] => {
      const { functions, types } = options;
      // All of the local variables need to be mapped
      const locals = {};
      // Count the number of arguments to help with generating bytecode
      let argumentsCount = 0;
      const closures = {
        // Capture all enclosed variables if any
        variables: getEnclosedVariables(node),
        // All of the closure offsets need to be tracked
        offsets: {},
        envSize: 0,
      };

      // Walk the node and calculate closure env size and closure offsets
      const fun = walkNode({
        // Function arguments need to be accounted for as well
        [Syntax.FunctionArguments]: (args, _) => {
          walkNode({
            [Syntax.Pair]: pairNode => {
              argumentsCount += 1;
              const [identifierNode, typeNode] = pairNode.params;
              const withTypeApplied = {
                ...identifierNode,
                type: typeNode.value,
              };
              parseDeclaration(
                false,
                { ...options, locals, closures },
                withTypeApplied,
                _
              );
            },
          })(args);
        },
        [Syntax.Declaration]: parseDeclaration(false, {
          ...options,
          locals,
          closures,
        }),
        [Syntax.ImmutableDeclaration]: parseDeclaration(true, {
          ...options,
          locals,
          closures,
        }),
      })({
        ...node,
        type: (() => {
          const typeDef = node.params[1];
          // Identifier, can match Struct type, Function Type or Lambda. Check lambda
          if (
            types[typeDef.value] != null &&
            types[typeDef.value].meta[CLOSURE_TYPE]
          ) {
            // Lmbdas are 64-bit Integers when used in source
            return "i64";
          }

          // Everything non-lambda just return the type
          return typeDef.type;
        })(),
        meta: {
          ...node.meta,
          [FUNCTION_INDEX]: Object.keys(functions).length,
          [FUNCTION_METADATA]: {
            locals,
            get argumentsCount() {
              return argumentsCount;
            },
          },
        },
        // If we are generating closures for this function, then we need to inject a
        // declaration for the environment local. This local cannot be referenced or
        // changed via source code.
        params: injectEnvironmentMaybe(
          {
            mapFunctionCall: makeFunctionCall({
              ...options,
              locals,
              mapIdentifier: makeMapIdentifier({ locals, ...options }),
              mapSizeof: makeSizeof({ locals, ...options }),
            }),
            ...closures,
          },
          node.params
        ),
      });
      functions[node.value] = fun;

      return [fun, locals, closures];
    };

    const mapFunctionNode = (options, node, topLevelTransform) => {
      // Initialize our function node
      const [fun, locals, closures] = initialize(options, node);

      // Construct all the mapping functions
      const mapIdentifier = makeMapIdentifier({ ...options, locals });
      const mapArraySubscript = makeArraySubscript({ ...options, locals });
      const mapSizeof = makeSizeof({ ...options, locals });
      const mapAssignment = makeAssignment({ ...options, locals });
      const mapClosure = makeClosure({
        ...options,
        fun,
        locals,
        closures,
      });
      const mapPair = makePair({
        ...options,
        locals,
        mapIdentifier,
        mapClosure,
        topLevelTransform,
      });
      const mapFunctonCall = makeFunctionCall({
        ...options,
        locals,
        mapIdentifier,
        mapSizeof,
      });

      return mapNode({
        // Patch function arguments so that they mirror locals
        [Syntax.FunctionArguments]: (args, _) => {
          return mapNode({
            [Syntax.Pair]: pairNode => {
              const [identifierNode, typeNode] = pairNode.params;
              return {
                ...pairNode,
                params: [locals[identifierNode.value], typeNode],
              };
            },
          })(args);
        },
        [Syntax.Declaration]: transformClosedDeclaration({
          ...options,
          locals,
          closures,
        }),
        [Syntax.ImmutableDeclaration]: transformClosedDeclaration({
          ...options,
          locals,
          closures,
        }),
        [Syntax.Identifier]: mapIdentifier,
        [Syntax.FunctionCall]: mapFunctonCall,
        [Syntax.Pair]: mapPair,
        // Unary expressions need to be patched so that the LHS type matches the RHS
        [Syntax.UnaryExpression]: mapUnary,
        // All binary expressions are patched
        [Syntax.BinaryExpression]: (binaryNode, transform) => {
          return balanceTypesInMathExpression({
            ...binaryNode,
            params: binaryNode.params.map(transform),
          });
        },
        [Syntax.TernaryExpression]: (ternaryNode, transform) => {
          const params = ternaryNode.params.map(transform);
          return {
            ...ternaryNode,
            type: params[0].type,
            params,
          };
        },
        [Syntax.Select]: (binaryNode, transform) => {
          return balanceTypesInMathExpression({
            ...binaryNode,
            params: binaryNode.params.map(transform),
          });
        },
        [Syntax.CharacterLiteral]: mapCharacterLiteral,
        [Syntax.StringLiteral]: (stringLiteral, transform) => {
          const { statics } = options;
          const { value } = stringLiteral;
          const index = statics[value]
            ? statics[value].value
            : Object.values(statics)
                .map(({ meta: { [STATIC_STRING]: data } }: any) => data)
                .reduce((a, v) => a + v.size, 4);
          const transformed = transform({
            ...stringLiteral,
            value: String(index),
            meta: {
              ...stringLiteral.meta,
              [STATIC_STRING]: stringEncoder(value),
            },
            Type: Syntax.Constant,
          });
          // it really does not matter when we write the key in
          statics[stringLiteral.value] = transformed;

          return transformed;
        },
        [Syntax.Assignment]: mapAssignment,
        [Syntax.MemoryAssignment]: (inputNode, transform) => {
          const params = inputNode.params.map(transform);
          const { type } = params[0];
          return { ...inputNode, params, type };
        },
        [Syntax.ReturnStatement]: returnNode => {
          const [expression] = returnNode.params;
          if (
            expression != null &&
            expression.Type === Syntax.Constant &&
            expression.type !== fun.type
          ) {
            return {
              ...returnNode,
              params: [
                {
                  ...expression,
                  value: ":",
                  Type: Syntax.Pair,
                  params: [
                    expression,
                    {
                      ...expression,
                      value: String(fun.type),
                      type: fun.type,
                      Type: Syntax.Type,
                      params: [],
                    },
                  ],
                },
              ],
            };
          }
          return returnNode;
        },
        [Syntax.ArraySubscript]: mapArraySubscript,
        [Syntax.Sizeof]: mapSizeof,
        [Syntax.Closure]: (closure, transform) => {
          const mappedClosure = mapClosure(closure, topLevelTransform);
          const [decl] = mappedClosure.params;
          options.hoist.push(decl);

          return transform(
            collapseClosureIdentifier(
              { ...locals[CLOSURE_BASE], meta: [] },
              mapIdentifier({
                ...decl,
                params: [],
                type: "i32",
                Type: Syntax.Identifier,
                meta: [],
              })
            )
          );
        },
      })(fun);
    };

    export default curry(mapFunctionNode);