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

98.13% Statements 105/107
91.67% Branches 44/48
100% Functions 20/20
98.1% Lines 103/105

    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

    23x
    23x
    23x
    23x
    23x

    23x

    23x

    87x

    174x
    254x
    254x

    254x

    249x
    2x

    247x

    5x
    5x

    5x

    5x

    5x
    5x
    5x

    5x

    87x

    87x
    87x
    87x

    87x
    86x

    1x
    1x

    1x

    1x

    87x
    4x

    4x

    4x
    4x

    4x

    4x

    4x

    87x
    179x
    179x
    179x
    175x

    4x
    4x
    4x

    4x
    4x

    4x

    4x
    4x

    1x

    17x
    11x

    4x
    4x

    4x

    4x

    4x
    21x
    4x
    4x

    17x

    4x

    87x
    179x
    179x
    179x
    4x

    175x

    87x
    88x
    88x
    88x

    88x
    83x

    5x
    1x

    4x

    4x
    4x

    87x
    668x
    668x

    668x
    661x

    7x

    7x

    87x
    199x
    199x
    199x
    199x

    3x

    7x

    3x
    3x

    3x

    196x

    87x

     /**
     * Closure plugin.
     *
     * Here be dragons
     *
     */
    import Syntax from '../Syntax';
    import parser from '../parser';
    import hasNode from '../utils/has-node';
    import walkNode from '../utils/walk-node';
    import {
      expressionFragment as expression,
      statementFragment as statement,
    } from '../parser/fragment';
    import { sizes } from '../types';

    const sum = (a, b) => a + b;

    export default function() {
      const semantics = () => {
        // Declaration parser, re-used for mutable/immutable declarations
        const declarationParser = next => (args, transform) => {
          const [node, context] = args;
          const { environment, types } = context;

          // Not a closure scan and not an environment variable
          if (!context.isParsingClosure || !environment[node.value]) {
            // Check if the declaration is a lambda, as we will need to unroll this
            // into an i64
            if (types[node.type] && types[node.type].meta.CLOSURE_TYPE) {
              return next([
                {
                  ...node,
                  type: 'i64',
                  meta: {
                    ...node.meta,
                    CLOSURE_INSTANCE: true,
                    ALIAS: node.type,
                  },
                },
                context,
              ]);
            }
            return next(args);
          }

          const parsed = next(args);
          environment[parsed.value] = {
            ...parsed,
            meta: {
              ...parsed.meta,
              ENV_OFFSET: Object.values(context.envSize).reduce(sum, 0),
            },
          };
          context.envSize[parsed.value] = sizes[parsed.type] || 4;

          // If the variable is declared but has no initializer we simply nullify the
          // node as there is nothing else to do here.
          Iif (!parsed.params.length) {
            return null;
          }

          const [lhs] = parsed.params;
          const ref = environment[parsed.value];
          const call = expression(
            `__closure_set_${ref.type}(__env_ptr + ${ref.meta.ENV_OFFSET})`
          );
          return transform([
            {
              ...call,
              params: [...call.params, lhs],
            },
            context,
          ]);
        };

        const closureImportsHeader = parser(`
          // Start Closure Imports Header
          import {
            __closure_malloc: ClosureGeti32,
            __closure_free: ClosureFree,
            __closure_get_i32: ClosureGeti32,
            __closure_get_f32: ClosureGetf32,
            __closure_get_i64: ClosureGeti64,
            __closure_get_f64: ClosureGetf64,
            __closure_set_i32: ClosureSeti32,
            __closure_set_f32: ClosureSetf32,
            __closure_set_i64: ClosureSeti64,
            __closure_set_f64: ClosureSetf64
          } from 'walt-plugin-closure';
          type ClosureFree = (i32) => void;
          type ClosureGeti32 = (i32) => i32;
          type ClosureGetf32 = (i32) => f32;
          type ClosureGeti64 = (i32) => i64;
          type ClosureGetf64 = (i32) => f64;
          type ClosureSeti32 = (i32, i32) => void;
          type ClosureSetf32 = (i32, f32) => void;
          type ClosureSeti64 = (i32, i64) => void;
          type ClosureSetf64 = (i32, f64) => void;
          // End Closure Imports Header
        `).params;

        return {
          Program: next => args => {
            const [program, context] = args;

            if (!hasNode(Syntax.Closure, program)) {
              return next(args);
            }

            const closures = [];
            const parsedProgram = next([
              {
                ...program,
                params: [...closureImportsHeader, ...program.params],
              },
              { ...context, closures },
            ]);

            const result = {
              ...parsedProgram,
              params: [...parsedProgram.params, ...closures],
            };

            return result;
          },
          Closure: _next => (args, transform) => {
            const [closure, context] = args;

            Iif (!context.isParsingClosure) {
              return closure;
            }

            // NOTE: All variables should really be kept in a single "scope" object

            const [declaration] = closure.params;
            const [fnArgs, result, ...rest] = declaration.params;
            // Create the real function node to be compiled which was originally a
            // closure EXPRESSION inside it's parent function. Once this run we will
            // have a function table reference which we will reference in the output
            // of this method.
            const real = transform([
              {
                ...declaration,
                value: `__closure_${context.isParsingClosure}_0`,
                // Each closure now needs to have a pointer to it's environment. We inject
                // that that at the front of the arguments list as an i32 local.
                //
                // Let the rest of the function parser continue as normal
                params: [
                  {
                    ...fnArgs,
                    // Parens are necessary around a fragment as it has to be a complete
                    // expression, a ; would also likely work and be discarded but that would
                    // be even odder in the context of function arguments
                    params: [expression('(__env_ptr : i32)'), ...fnArgs.params],
                  },
                  result,
                  ...rest,
                ],
              },
              context,
            ]);

            // Before we complete our work here, we have to attach the 'real' function
            // created above to the output of the program so that it can become part
            // of the final WASM output.
            context.closures.push(real);

            return transform([
              expression(`(${real.value} | ((__env_ptr : i64) << 32)))`),
              context,
            ]);
          },
          FunctionDeclaration: next => (args, transform) => {
            const [node, context] = args;
            const { globals } = context;
            if (context.isParsingClosure || !hasNode(Syntax.Closure, node)) {
              return next(args);
            }

            const environment = {};
            const envSize = {};
            walkNode({
              Closure(closure, _) {
                // All closures have their own __env_ptr passed in at call site
                const declarations = { __env_ptr: true };
                walkNode({
                  // We need to make sure we ignore the arguments to the closure.
                  // Otherwise they will be treaded as "closed over" variables
                  FunctionArguments(closureArgs, _ignore) {
                    walkNode({
                      Pair(pair) {
                        const [identifier] = pair.params;
                        declarations[identifier.value] = identifier;
                      },
                    })(closureArgs);
                  },
                  Declaration(decl, __) {
                    declarations[decl.value] = decl;
                  },
                  Identifier(id) {
                    if (!declarations[id.value] && !globals[id.value]) {
                      environment[id.value] = id;
                    }
                  },
                })(closure);
              },
            })(node);

            // We will initialize with an empty env for now and patch this once we
            // know the sizes of all environment variables
            const injectedEnv = statement('const __env_ptr : i32 = 0;');
            const [fnArgs, result, ...rest] = node.params;

            const closureContext = {
              ...context,
              environment,
              envSize,
              isParsingClosure: node.value,
            };
            const fun = next([
              { ...node, params: [fnArgs, result, injectedEnv, ...rest] },
              closureContext,
            ]);

            fun.params = fun.params.map(p => {
              if (p.Type === Syntax.Declaration && p.value === '__env_ptr') {
                const size = Object.values(envSize).reduce(sum, 0);
                return transform([
                  statement(`const __env_ptr : i32 = __closure_malloc(${size});`),
                  { ...context, locals: {} },
                ]);
              }

              return p;
            });

            return fun;
          },
          Declaration: declarationParser,
          ImmutableDeclaration: declarationParser,
          FunctionResult: next => args => {
            const [node, context] = args;
            const { types } = context;
            if (types[node.value] && types[node.value].meta.CLOSURE_TYPE) {
              return next([
                {
                  ...node,
                  type: 'i64',
                  value: 'i64',
                  meta: {
                    ...node.meta,
                    ALIAS: node.type,
                  },
                },
                context,
              ]);
            }
            return next(args);
          },
          Assignment: next => (args, transform) => {
            const [node, context] = args;
            const { locals, globals, environment } = context;
            const [rhs, lhs] = node.params;

            if (!context.isParsingClosure) {
              return next(args);
            }

            // Closures are functions and have their own locals
            if (locals[rhs.value] || globals[rhs.value]) {
              return next(args);
            }

            const { type, meta: { ENV_OFFSET: offset } } = environment[rhs.value];

            const call = expression(`__closure_set_${type}(__env_ptr + ${offset})`);
            return transform([
              {
                ...call,
                params: [...call.params, lhs],
              },
              context,
            ]);
          },
          Identifier: next => (args, transform) => {
            const [node, context] = args;
            const { environment } = context;

            if (!context.isParsingClosure || !environment[node.value]) {
              return next(args);
            }

            const { type, meta: { ENV_OFFSET: offset } } = environment[node.value];

            return transform([
              expression(`__closure_get_${type}(__env_ptr + ${offset})`),
              context,
            ]);
          },
          FunctionCall: next => (args, transform) => {
            const [call, context] = args;
            const { locals, types } = context;
            const local = locals[call.value];
            if (local && local.meta.CLOSURE_INSTANCE) {
              // Unfortunately, we cannot create a statement for this within the
              // possible syntax so we need to manually structure an indirect call node

              const params = [
                expression(`((${local.value} >> 32) : i32)`),
                ...call.params,
                expression(`(${local.value} : i32)`),
              ].map(p => transform([p, context]));

              const typedef = types[local.meta.ALIAS];
              const typeIndex = Object.keys(types).indexOf(typedef.value);

              return {
                ...call,
                meta: {
                  ...local.meta,
                  ...call.meta,
                  TYPE_INDEX: typeIndex,
                },
                type: typedef != null ? typedef.type : call.type,
                params,
                Type: Syntax.IndirectFunctionCall,
              };
            }

            return next(args);
          },
        };
      };

      return {
        semantics,
      };
    }