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

100% Statements 63/63
100% Branches 9/9
100% Functions 14/14
100% Lines 63/63

    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

    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x

    21x
    21x
    21x

    21x

    21x
    147x

    147x

    147x
    147x

    147x

    151x

    66x
    66x
    66x

    66x

    147x

    147x

    4x

    143x

    133x

    147x

    147x

    21x

    147x

    147x
    147x
    147x
    147x
    147x

    147x

    147x

    147x

    147x

    62x
    62x

    25x

    25x
    25x

    240x

    2x
    2x

    8x

    33x
    33x
    33x

    160x
    160x

    1x

    159x

    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 { parseDeclaration } from "./declaration";
    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 } 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]: (unaryNode, transform) => {
          const lhs = unaryNode.params[0];
          // Recurse into RHS and determine types
          const rhs = transform(unaryNode.params[1]);
          return {
            ...unaryNode,
            type: rhs.type,
            params: [
              {
                ...lhs,
                type: rhs.type,
              },
              rhs,
            ],
            Type: Syntax.BinaryExpression,
          };
        },
        // 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.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);