# All files / src/semantics/closure index.js

100% Statements 62/62
100% Branches 14/14
100% Functions 17/17
100% Lines 62/62

    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
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    23x
    23x
    23x
    23x
    23x

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

    23x
    9x

    3x

    23x

    4x

    23x

    16x

    23x
    165x
    165x
    17x
    11x

    165x
    5x

    165x

    4x
    4x

    4x

    4x

    4x
    4x

    165x

    23x

    165x
    4x
    4x

    161x

    23x
    128x
    128x

    128x
    4x

    124x
    5x
    5x

    119x

    4x
    4x

    4x

    4x

    4x

    5x
    5x
    4x
    4x

    1x

    17x
    7x
    7x

    10x

    4x

     // @flow
    import Syntax from "../../Syntax";
    import curry from "curry";
    import mapNode from "../../utils/map-node";
    import walkNode from "../../utils/walk-node";
    import { expressionFragment } from "../../parser/fragment";
    import type { NodeType } from "../../flow/types";

    export const CLOSURE_FREE = "closure-free";
    export const CLOSURE_MALLOC = "closure-malloc";
    export const CLOSURE_BASE = "closure_base";
    export const CLOSURE_INNER = "closure_inner";
    export const CLOSURE_GET = "closure--get";
    export const CLOSURE_SET = "closure--set";

    /**
     * "expand" an identifier Node into two nodes, the least significant word which
     * is the table index and into most signifact word Node which is the closure
     * pointer
     *
     */
    export const expandClosureIdentifier = (identifier: NodeType): NodeType[] => {
      const bareIdentifier = () => ({ ...identifier, params: [] });
      // regular params, we APPEND function pointer math to list of params
      return [
        {
          ...identifier,
          value: ":",
          meta: {},
          Type: Syntax.Pair,
          params: [
            bareIdentifier(),
            {
              ...identifier,
              value: "i32",
              type: "i32",
              meta: {},
              params: [],
              Type: Syntax.Type,
            },
          ],
        },
        ...identifier.params,
        {
          ...identifier,
          value: ":",
          Type: Syntax.Pair,
          meta: {},
          params: [
            {
              ...identifier,
              value: ">>",
              meta: {},
              Type: Syntax.BinaryExpression,
              params: [
                bareIdentifier(),
                {
                  ...identifier,
                  value: "32",
                  type: "i32",
                  meta: {},
                  params: [],
                  Type: Syntax.Constant,
                },
              ],
            },
            {
              ...identifier,
              meta: {},
              value: "i32",
              type: "i32",
              params: [],
              Type: Syntax.Type,
            },
          ],
        },
      ];
    };

    export const collapseClosureIdentifier = (
      closure: NodeType,
      pointer: NodeType
    ): NodeType => {
      return {
        ...closure,
        value: "+",
        Type: Syntax.BinaryExpression,
        params: [
          {
            ...closure,
            value: ":",
            meta: {},
            Type: Syntax.Pair,
            params: [
              { ...closure, Type: Syntax.Identifier, params: [] },
              {
                ...closure,
                value: "i64",
                type: "i64",
                Type: Syntax.Type,
                params: [],
              },
            ],
          },
          {
            ...pointer,
            value: "<<",
            Type: Syntax.BinaryExpression,
            params: [
              pointer,
              {
                ...pointer,
                value: "32",
                type: "i64",
                meta: {},
                params: [],
                Type: Syntax.Constant,
              },
            ],
          },
        ],
      };
    };

    export const mapIdentifierToOffset = (
      base: NodeType,
      offset: number
    ): NodeType => expressionFragment(`${offset} + ${base.value}`);

    /**
     * Walks over a function ndoe and finds any enclosed variables in any closure in
     * its body. This is used to create an environment object for all of the closures
     */
    export const getEnclosedVariables = (fun: NodeType): { [string]: NodeType } => {
      const variables = {};
      const encloseMaybe = curry((locals, identifier, _) => {
        if (locals[identifier.value] == null) {
          variables[identifier.value] = identifier;
        }
      });
      const ignore = curry((locals, identifier, _) => {
        locals[identifier.value] = identifier;
      });
      walkNode({
        // Only map over closures, ignore everything else
        [Syntax.Closure]: (closure, _) => {
          const locals = {};
          const ignoreLocals = ignore(locals);
          // Walk over the closure body enclose upper scope variables if necessary
          walkNode({
            // All arguments and local declarations are ignored. This means that
            // variable name shadowing does not enclose upper scope vars
            [Syntax.FunctionArguments]: (fnArgs, __) => {
              walkNode({
                [Syntax.Pair]: (pair: NodeType) => {
                  const [identifier] = pair.params;
                  ignoreLocals(identifier, null);
                },
              })(fnArgs);
            },
            [Syntax.Declaration]: ignoreLocals,
            [Syntax.ImmutableDeclaration]: ignoreLocals,
            // Maybe enclose over an upper scope identifier
            [Syntax.Identifier]: encloseMaybe(locals),
          })(closure);
        },
      })(fun);

      return variables;
    };

    /**
     * Modifies a function parameter list and injects an environment declaration if
     * necessary
     */
    export const injectEnvironmentMaybe = (
      {
        mapFunctionCall,
        variables,
      }: {
        mapFunctionCall: NodeType => NodeType,
        variables: { [string]: NodeType },
      },
      params: NodeType[]
    ): NodeType[] => {
      if (Object.keys(variables).length > 0) {
        const start: NodeType = params[2];
        return [
          ...params.slice(0, 2),
          {
            ...start,
            value: CLOSURE_BASE,
            type: "i32",
            Type: Syntax.Declaration,
            params: [
              mapFunctionCall({
                ...start,
                type: "i32",
                meta: {},
                value: CLOSURE_MALLOC,
                Type: Syntax.FunctionCall,
                params: [
                  {
                    ...start,
                    params: [],
                    type: "i32",
                    value: "0",
                    Type: Syntax.Constant,
                  },
                ],
              }),
            ],
          },
          ...params.slice(2),
        ];
      }

      return params;
    };

    export const transformClosedDeclaration = curry((options, decl, transform) => {
      const { closures, locals } = options;
      const [init] = decl.params;

      // We don't know the size of the environment until all locals are walked. This
      // means we need to patch in the size of the env here where we can map nodes
      if (decl.value === CLOSURE_BASE) {
        return {
          ...locals[decl.value],
          params: [
            {
              ...init,
              params: [
                {
                  ...init.params[0],
                  value: closures.envSize,
                },
              ],
            },
          ].map(transform),
        };
      }

      // If the value is enclosed and has an initializer we need to transform it into
      // a memory operation. AKA a function call to the closure plugin
      if (init && closures.variables[decl.value] != null) {
        const { offsets } = closures;
        return transform({
          ...init,
          value: `${CLOSURE_SET}-${decl.type}`,
          params: [
            {
              ...mapIdentifierToOffset(
                { ...init, value: CLOSURE_BASE },
                offsets[decl.value]
              ),
            },
            init,
          ],
          meta: {},
          Type: Syntax.FunctionCall,
        });
      }

      // Not a closure of any kind, return the local
      return {
        ...locals[decl.value],
        params: locals[decl.value].params.map(transform),
      };
    });

    export default curry(function mapClosure(options, node, topLevelTransform) {
      const { locals, closures, fun } = options;
      const { variables, offsets } = closures;

      const patched = mapNode({
        [Syntax.FunctionDeclaration]: decl => {
          // add a name
          return {
            ...decl,
            value: `internalClosure--${fun.value}`,
          };
        },
        [Syntax.FunctionArguments]: (args, _) => {
          return {
            ...args,
            params: [
              {
                ...args,
                value: ":",
                params: [
                  {
                    ...args,
                    value: CLOSURE_INNER,
                    params: [],
                    Type: Syntax.Identifier,
                  },
                  {
                    ...args,
                    value: "i32",
                    type: "i32",
                    params: [],
                    Type: Syntax.Type,
                  },
                ],
                Type: Syntax.Pair,
              },
              ...args.params,
            ],
          };
        },
        // Every assignment becomes a set function call
        [Syntax.Assignment]: assignment => {
          const [rhs, lhs] = assignment.params;
          if (variables[rhs.value] != null) {
            const local = locals[rhs.value];
            return {
              ...assignment,
              value: `closure--set-${local.type}`,
              params: [
                mapIdentifierToOffset(
                  { ...rhs, value: String(CLOSURE_INNER) },
                  offsets[local.value]
                ),
                lhs,
              ],
              meta: {},
              Type: Syntax.FunctionCall,
            };
          }
          return assignment;
        },
        // Every lookup becomes a get function call
        [Syntax.Identifier]: (identifier, _) => {
          if (variables[identifier.value] != null) {
            const local = locals[identifier.value];
            return {
              ...identifier,
              value: `closure--get-${local.type}`,
              params: [
                mapIdentifierToOffset(
                  { ...identifier, value: CLOSURE_INNER },
                  offsets[local.value]
                ),
              ],
              Type: Syntax.FunctionCall,
            };
          }

          return identifier;
        },
      })(node);

      // Magic
      return topLevelTransform(patched);
    });