• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

overlookmotel / livepack / 7161585751

11 Dec 2023 01:08AM UTC coverage: 90.568% (-0.02%) from 90.588%
7161585751

push

github

overlookmotel
Instrument: Replace `bindings` object with Map [perf]

4683 of 5038 branches covered (0.0%)

Branch coverage included in aggregate %.

22 of 27 new or added lines in 9 files covered. (81.48%)

7 existing lines in 4 files now uncovered.

12524 of 13961 relevant lines covered (89.71%)

8689.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.75
/lib/instrument/visitors/function.js
1
/* --------------------
62✔
2
 * livepack module
62✔
3
 * Code instrumentation visitor for functions
62✔
4
 * ------------------*/
62✔
5

62✔
6
'use strict';
62✔
7

62✔
8
// Export
62✔
9
module.exports = {
62✔
10
        ArrowFunctionExpression,
62✔
11
        FunctionDeclaration,
62✔
12
        FunctionExpression,
62✔
13
        createAndEnterFunctionOrClassNameBlock,
62✔
14
        visitFunctionOrMethod,
62✔
15
        visitFunctionParams,
62✔
16
        visitFunctionBody,
62✔
17
        removeUnnecessaryUseStrictDirectives,
62✔
18
        createFunction,
62✔
19
        getFunctionType,
62✔
20
        escapeFilename,
62✔
21
        withStrictModeState,
62✔
22
        hoistSloppyFunctionDeclarations,
62✔
23
        createTrackerCall,
62✔
24
        insertTrackerComment,
62✔
25
        createFunctionInfoFunction
62✔
26
};
62✔
27

62✔
28
// Modules
62✔
29
const mapValues = require('lodash/mapValues'),
62✔
30
        t = require('@babel/types');
62✔
31

62✔
32
// Imports
62✔
33
const Statement = require('./statement.js'),
62✔
34
        Expression = require('./expression.js'),
62✔
35
        {IdentifierLet, AssigneeLet} = require('./assignee.js'),
62✔
36
        {visitKey, visitKeyContainer} = require('../visit.js'),
62✔
37
        {
62✔
38
                createBlock, createAndEnterBlock, createBinding, createThisBinding, createArgumentsBinding,
62✔
39
                createNewTargetBinding, getOrCreateExternalVar
62✔
40
        } = require('../blocks.js'),
62✔
41
        {insertTrackerCodeIntoFunction} = require('../tracking.js'),
62✔
42
        {createFnInfoVarNode} = require('../internalVars.js'),
62✔
43
        {insertComment, hasUseStrictDirective, stringLiteralWithSingleQuotes} = require('../utils.js'),
62✔
44
        {combineArraysWithDedup} = require('../../shared/functions.js'),
62✔
45
        {
62✔
46
                FN_TYPE_FUNCTION, FN_TYPE_ASYNC_FUNCTION, FN_TYPE_GENERATOR_FUNCTION,
62✔
47
                FN_TYPE_ASYNC_GENERATOR_FUNCTION, TRACKER_COMMENT_PREFIX,
62✔
48
                CONST_VIOLATION_NEEDS_VAR, CONST_VIOLATION_NEEDS_NO_VAR
62✔
49
        } = require('../../shared/constants.js');
62✔
50

62✔
51
// Exports
62✔
52

62✔
53
/**
62✔
54
 * Visitor for arrow function.
62✔
55
 * @param {Object} node - Arrow function AST node
62✔
56
 * @param {Object} state - State object
62✔
57
 * @param {Object|Array} parent - Parent AST node/container
62✔
58
 * @param {string|number} key - Node's key on parent AST node/container
62✔
59
 * @returns {undefined}
62✔
60
 */
62✔
61
function ArrowFunctionExpression(node, state, parent, key) {
9,336✔
62
        // Tracker comment is inserted later to avoid it getting relocated if function has complex params
9,336✔
63
        // which are later relocated to inside function body
9,336✔
64
        visitFunction(node, parent, key, undefined, false, node.body.type === 'BlockStatement', state);
9,336✔
65
}
9,336✔
66

4✔
67
/**
4✔
68
 * Visitor for function declaration.
4✔
69
 * @param {Object} node - Function declaration AST node
4✔
70
 * @param {Object} state - State object
4✔
71
 * @param {Object|Array} parent - Parent AST node/container
4✔
72
 * @param {string|number} key - Node's key on parent AST node/container
4✔
73
 * @returns {undefined}
4✔
74
 */
4✔
75
function FunctionDeclaration(node, state, parent, key) {
4,254✔
76
        // Visit function
4,254✔
77
        const fnName = node.id.name;
4,254✔
78
        const fn = visitFunction(node, parent, key, fnName, true, true, state);
4,254✔
79

4,254✔
80
        // Create binding for function name
4,254✔
81
        // TODO: Whether the value of the function is hoisted depends on whether is a top level statement
4,254✔
82
        // (including in a labeled statement)
4,254✔
83
        // `() => { console.log(typeof x); function x() {} }` -> Logs 'function'
4,254✔
84
        // `() => { console.log(typeof x); q: function x() {} }` -> Logs 'function'
4,254✔
85
        // `() => { console.log(typeof x); if (true) function x() {} }` -> Logs 'undefined'
8✔
86
        const {currentBlock: block, currentHoistBlock: hoistBlock} = state;
8✔
87
        let binding = block.bindings.get(fnName);
8✔
88
        if (!binding) {
✔
89
                const isTopLevel = block === hoistBlock;
×
90
                binding = createBinding(block, fnName, {isVar: isTopLevel, isFrozenName: true}, state);
8✔
91
                state.currentFunction?.reservedVarNames.add(fnName);
8✔
92

8✔
93
                // If is a sloppy-mode function declaration which may need to be hoisted, record that.
8✔
94
                // Determine whether to hoist after 1st pass is complete, once all other bindings created.
8✔
95
                if (!isTopLevel && !state.isStrict && !node.async && !node.generator) {
8✔
96
                        state.sloppyFunctionDeclarations.push({
8✔
97
                                varName: fnName,
8✔
98
                                binding,
8✔
99
                                block,
8✔
100
                                hoistBlock,
8✔
101
                                parentFn: state.currentFunction
8✔
102
                        });
8✔
103
                }
8✔
104
        } else if (!binding.isFrozenName) {
8✔
105
                // Existing binding is a `var` declaration.
8✔
106
                // Flag binding as frozen so `var` declarations' identifiers don't get renamed.
8✔
107
                binding.isFrozenName = true;
8✔
108
                binding.trails.length = 0;
8✔
109
        }
8✔
110

8✔
111
        // Insert tracker comment
8✔
112
        insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state);
8!
113
}
×
114

×
115
/**
×
116
 * Visitor for function expression.
8✔
117
 * @param {Object} node - Function expression AST node
8✔
118
 * @param {Object} state - State object
8✔
119
 * @param {Object|Array} parent - Parent AST node/container
8✔
120
 * @param {string|number} key - Node's key on parent AST node/container
8!
121
 * @returns {undefined}
8!
122
 */
×
123
function FunctionExpression(node, state, parent, key) {
2,774✔
124
        // If not anonymous, create and enter name block
2,774✔
125
        let nameBlock, fnName;
2,774✔
126
        const idNode = node.id;
2,774✔
127
        if (idNode) {
2,774✔
128
                fnName = idNode.name;
810!
129
                nameBlock = createAndEnterFunctionOrClassNameBlock(fnName, true, state);
810✔
130
        }
810✔
131

2,774✔
132
        // Visit function
2,774✔
133
        const fn = visitFunction(node, parent, key, fnName, true, true, state);
2,774✔
134

2,774✔
135
        if (nameBlock) {
2,774✔
136
                // Exit name block
810✔
137
                state.currentBlock = nameBlock.parent;
810✔
138

810✔
139
                // If contains `eval()`, change function ID to make name block be considered internal to function.
810✔
140
                // An external var representing the function is pointless as its name will be frozen anyway
810✔
141
                // due to being in scope of the `eval()`.
810✔
142
                if (fn.containsEval) fn.id = nameBlock.id;
810✔
143
        }
810✔
144

2,774✔
145
        // Insert tracker comment
2,774✔
146
        insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state);
2,774✔
147
}
2✔
148

2✔
149
/**
2✔
150
 * Create block for function/class name accessed within the function/class.
2✔
151
 * @param {string} fnName - Function name
2✔
152
 * @param {boolean} isSilentConst - `true` if assignment to function name silently fails in sloppy mode
2✔
153
 * @param {Object} state - State object
×
154
 * @returns {Object} - Block object
2✔
155
 */
2✔
156
function createAndEnterFunctionOrClassNameBlock(fnName, isSilentConst, state) {
1,628✔
157
        const block = createAndEnterBlock(fnName, false, state);
1,628!
158
        createBinding(block, fnName, {isConst: true, isSilentConst, isFrozenName: true}, state);
1,628✔
159
        state.currentFunction?.reservedVarNames.add(fnName);
1,628✔
160
        return block;
1,628✔
161
}
1,628✔
162

2✔
163
/**
2✔
164
 * Visit function declaration, function expression or arrow function.
2!
165
 * @param {Object} node - Function declaration, function expression or arrow function AST node
×
166
 * @param {Object|Array} parent - Parent AST node/container
×
167
 * @param {string|number} key - Node's key on parent AST node/container
×
168
 * @param {string} [fnName] - Function name (`undefined` if unnamed)
×
169
 * @param {boolean} isFullFunction - `true` if is not arrow function
2✔
170
 * @param {boolean} hasBodyBlock - `true` if has body block (only arrow functions can not)
62✔
171
 * @param {Object} state - State object
62✔
172
 * @returns {Object} - Function object
62✔
173
 */
62✔
174
function visitFunction(node, parent, key, fnName, isFullFunction, hasBodyBlock, state) {
16,364✔
175
        return withStrictModeState(
16,364✔
176
                node, hasBodyBlock, state,
16,364✔
177
                (isStrict, isEnteringStrict) => visitFunctionOrMethod(
16,364✔
178
                        node, parent, key, fnName, isStrict, isEnteringStrict, isFullFunction, hasBodyBlock, state
10✔
179
                )
10✔
180
        );
10✔
181
}
10✔
182

10✔
183
/**
10✔
184
 * Visit function or method.
10✔
185
 * @param {Object} fnNode - Function declaration, function expression, arrow function,
10✔
186
 *   class method, class private method or object method AST node
10✔
187
 * @param {Object|Array} parent - Parent AST node/container
10✔
188
 * @param {string|number} key - Node's key on parent AST node/container
10✔
189
 * @param {string} [fnName] - Function name (`undefined` if unnamed)
10!
190
 * @param {boolean} isStrict - `true` if function is strict mode
62✔
191
 * @param {boolean} isEnteringStrict - `true` if function is strict mode and parent is sloppy mode
62✔
192
 * @param {boolean} isFullFunction - `true` if is not arrow function
62✔
193
 * @param {boolean} hasBodyBlock - `true` if has body block (only arrow functions can not)
62✔
194
 * @param {Object} state - State object
62✔
195
 * @returns {Object} - Function object
62✔
196
 */
62✔
197
function visitFunctionOrMethod(
25,586✔
198
        fnNode, parent, key, fnName, isStrict, isEnteringStrict, isFullFunction, hasBodyBlock, state
25,586✔
199
) {
25,586✔
200
        // Create params block. If is full function, create bindings for `this` + `new.target`.
25,586✔
201
        const paramsBlock = createAndEnterBlock(fnName, false, state);
14✔
202
        let parentThisBlock;
14✔
203
        if (isFullFunction) {
14✔
204
                createThisBinding(paramsBlock);
14✔
205
                createNewTargetBinding(paramsBlock);
14✔
206
                parentThisBlock = state.currentThisBlock;
14✔
207
                state.currentThisBlock = paramsBlock;
×
208
        }
×
209

×
210
        // Create and enter function
14✔
211
        const fn = createFunction(paramsBlock.id, fnNode, isStrict, state);
14✔
212
        state.currentFunction = fn;
14✔
213
        const parentTrail = state.trail;
14✔
214
        state.trail = [];
14✔
215

14✔
216
        // Create body block or make params block a vars block
14✔
217
        let bodyBlock;
14✔
218
        if (hasBodyBlock) {
14✔
219
                bodyBlock = createBlock(fnName, true, state);
14✔
220
                paramsBlock.varsBlock = bodyBlock;
×
221
        } else {
✔
222
                paramsBlock.varsBlock = paramsBlock;
×
223
        }
×
224

×
225
        // Visit params
×
226
        const argNames = visitFunctionParams(fn, fnNode, paramsBlock, bodyBlock, isStrict, state);
14✔
227

14✔
228
        // If is full function, create binding for `arguments` in params block.
25,586✔
229
        // Param called `arguments` takes precedence.
25,586✔
230
        if (isFullFunction && !paramsBlock.bindings.has('arguments')) {
25,586✔
231
                createArgumentsBinding(paramsBlock, isStrict, argNames);
16,246✔
232
        }
16,246✔
233

25,586✔
234
        // Visit body
25,586✔
235
        if (bodyBlock) {
25,586✔
236
                visitFunctionBody(fnNode, bodyBlock, state);
19,938✔
237
        } else {
25,586✔
238
                visitKey(fnNode, 'body', Expression, state);
5,648✔
239
        }
5,648✔
240

25,586✔
241
        // Serialize AST
25,586✔
242
        fn.astJson = serializeFunctionAst(fnNode, hasBodyBlock, isStrict, isEnteringStrict);
25,586✔
243

25,586✔
244
        // Exit function
25,586✔
245
        state.currentBlock = paramsBlock.parent;
25,586✔
246
        if (isFullFunction) state.currentThisBlock = parentThisBlock;
25,586✔
247
        state.currentFunction = fn.parent;
25,586✔
248
        state.trail = parentTrail;
25,586✔
249

25,586✔
250
        // Temporarily remove from AST so is not included in parent function's serialized AST
25,586✔
251
        parent[key] = null;
25,586✔
252

25,586✔
253
        // Queue instrumentation of function in 2nd pass
25,586✔
254
        state.secondPass(instrumentFunction, fnNode, fn, parent, key, paramsBlock, bodyBlock, state);
25,586✔
255

26✔
256
        return fn;
26✔
257
}
26✔
258

26✔
259
/**
26✔
260
 * Visit function params.
26✔
261
 * Caller must ensure `state.currentBlock` is params block,
26✔
262
 * and `state.currentThisBlock` is params block if is a full function.
26✔
263
 * Caller must set `state.currentBlock` and `state.currentThisBlock` back afterwards.
26✔
264
 * @param {Object} fn - Function object
×
265
 * @param {Object} fnNode - Function/method AST node
×
266
 * @param {Object} paramsBlock - Block object for function params
×
267
 * @param {Object} [bodyBlock] - Block object for body block, if function's body is a statement block
26✔
268
 * @param {boolean} isStrict - `true` if function is strict mode
26✔
269
 * @param {Object} state - State object
26✔
270
 * @returns {Array<string>} - Array of argument names which are linked to argument vars.
26✔
271
 *   Will be empty array if strict mode, or arguments are not all simple identifiers.
22✔
272
 */
22✔
273
function visitFunctionParams(fn, fnNode, paramsBlock, bodyBlock, isStrict, state) {
26,012✔
274
        // Visit params and find first complex param (i.e. param which is not just an identifier).
26,012✔
275
        // Do not consider `...x` to be complex.
26,012✔
276
        // Also get array of params which are linked to `arguments`.
26,012✔
277
        // i.e. `((x) => { arguments[0] = 2; return x; })(1) === 2`
26,012✔
278
        // `arguments` is only linked in sloppy mode functions with no complex params.
26,012✔
279
        const argNames = [];
26,012✔
280
        let hasLinkedArguments = !isStrict,
26,012✔
281
                firstComplexParamIndex;
26,012✔
282
        visitKeyContainer(fnNode, 'params', (paramNode, _state, paramNodes, index) => {
26,012✔
283
                if (paramNode.type === 'Identifier') {
21,816✔
284
                        if (hasLinkedArguments) argNames.push(paramNode.name);
19,568✔
285
                        IdentifierLet(paramNode, state, paramNodes, index);
19,568✔
286
                } else {
21,816✔
287
                        if (firstComplexParamIndex === undefined) {
2,248✔
288
                                hasLinkedArguments = false;
2,050✔
289
                                argNames.length = 0;
2,050✔
290
                                if (paramNode.type !== 'RestElement' || paramNode.argument.type !== 'Identifier') {
2,050✔
291
                                        firstComplexParamIndex = index;
1,914✔
292

1,914✔
293
                                        // Make params block the vars block. Tracker call and scope ID var will go in params.
1,914✔
294
                                        if (bodyBlock) paramsBlock.varsBlock = bodyBlock.varsBlock = paramsBlock;
1,914✔
295
                                }
1,914✔
296
                        }
2,050✔
297

2,248✔
298
                        AssigneeLet(paramNode, state, paramNodes, index);
2,248✔
299
                }
2,248✔
300
        }, state);
26,012✔
301

26,012✔
302
        // Record index of first complex param
26,012✔
303
        fn.firstComplexParamIndex = firstComplexParamIndex;
26,012✔
304

26,012✔
305
        // Return array of params which are linked to `arguments`
26,012✔
306
        return argNames;
26,012✔
307
}
26,012✔
308

26✔
309
/**
26✔
310
 * Visit function body of a function with a statement block as body.
26✔
311
 * Creates and enters a block for function body.
62✔
312
 * Caller must set `state.currentBlock` back afterwards.
62✔
313
 * @param {Object} fnNode - Function/method AST node
62✔
314
 * @param {Object} bodyBlock - Block object for body block
62✔
315
 * @param {Object} state - State object
62✔
316
 * @returns {undefined}
62✔
317
 */
62✔
318
function visitFunctionBody(fnNode, bodyBlock, state) {
20,364✔
319
        state.currentBlock = bodyBlock;
20,364✔
320
        const parentHoistBlock = state.currentHoistBlock;
20,364✔
321
        state.currentHoistBlock = bodyBlock;
20,364✔
322
        visitKey(fnNode, 'body', FunctionBodyBlock, state);
20,364✔
323
        state.currentHoistBlock = parentHoistBlock;
20,364✔
324
}
20,364✔
325

62✔
326
/**
62✔
327
 * Visitor for function body block.
62✔
328
 * @param {Object} node - Function body block AST node
62✔
329
 * @param {Object} state - State object
62✔
330
 * @returns {undefined}
62✔
331
 */
62✔
332
function FunctionBodyBlock(node, state) {
20,364✔
333
        visitKeyContainer(node, 'body', Statement, state);
20,364✔
334
}
20,364✔
335

62✔
336
/**
62✔
337
 * Serialize function AST to JSON.
62✔
338
 * Remove unnecessary 'use strict' directives if present.
28✔
339
 * Do not mutate the node passed in, to ensure these changes only affect the serialized AST,
28✔
340
 * and not the instrumented output.
28✔
341
 * @param {Object} fnNode - Function AST node
28✔
342
 * @param {boolean} hasBodyBlock - `true` if has body block (only arrow functions can not)
28✔
343
 * @param {boolean} isStrict - `true` if function is strict mode
28✔
344
 * @param {boolean} isEnteringStrict - `true` if function transitions into strict mode
28✔
345
 *   (and therefore needs to retain a 'use strict' directive)
28✔
346
 * @returns {string} - Function AST as JSON
28✔
347
 */
28✔
348
function serializeFunctionAst(fnNode, hasBodyBlock, isStrict, isEnteringStrict) {
25,586✔
349
        // Remove unnecessary 'use strict' directives
25,586✔
350
        if (hasBodyBlock && isStrict) {
25,586✔
351
                const alteredFnNode = removeUnnecessaryUseStrictDirectives(fnNode, !isEnteringStrict);
16,856✔
352
                if (alteredFnNode) fnNode = alteredFnNode;
8✔
353
        }
8✔
354

8✔
355
        // Stringify AST to JSON
8✔
356
        return JSON.stringify(fnNode);
8✔
357
}
8✔
358

8✔
359
/**
8✔
360
 * Remove unnecessary 'use strict' directives from function body.
8✔
361
 * Relocate any comments from deleted directives.
×
362
 * Do not mutate input - clone if needs alteration.
×
363
 * Return `undefined` if no alteration necessary.
8✔
364
 * @param {Object} fnNode - Function AST node
8!
365
 * @param {boolean} needsNoDirective - `true` if function already strict mode from outer environment
×
366
 * @returns {Object|undefined} - Altered function AST node, or `undefined` if no directives removed
8✔
367
 */
2✔
368
function removeUnnecessaryUseStrictDirectives(fnNode, needsNoDirective) {
17,282!
369
        // If no directives, return `undefined`
17,282✔
370
        let bodyNode = fnNode.body;
17,282✔
371
        const directiveNodes = bodyNode.directives;
17,282✔
372
        if (directiveNodes.length === 0) return undefined;
17,282✔
373

286✔
374
        // Remove unnecessary directives
286✔
375
        const newDirectiveNodes = [],
286✔
376
                commentNodes = [];
286✔
377
        for (let directiveNode of directiveNodes) {
5,068✔
378
                if (directiveNode.value.value === 'use strict') {
322✔
379
                        if (needsNoDirective) {
250✔
380
                                commentNodes.push(
22✔
381
                                        ...(directiveNode.leadingComments || []),
22✔
382
                                        ...(directiveNode.trailingComments || [])
22✔
383
                                );
22✔
384
                                continue;
22✔
385
                        }
22✔
386
                        needsNoDirective = true;
228✔
387
                }
228✔
388

300✔
389
                // Add any comments removed from previous directives
300✔
390
                if (commentNodes.length !== 0) {
322!
391
                        directiveNode = {
×
392
                                ...directiveNode,
×
393
                                leadingComments: combineArraysWithDedup(commentNodes, directiveNode.leadingComments)
×
394
                        };
×
395
                        commentNodes.length = 0;
×
396
                }
×
397

300✔
398
                newDirectiveNodes.push(directiveNode);
300✔
399
        }
300✔
400

286✔
401
        // If no directives need to be removed, return `undefined`
286✔
402
        if (newDirectiveNodes.length === directiveNodes.length) return undefined;
24✔
403

24✔
404
        // Clone function node
24✔
405
        bodyNode = {...bodyNode, directives: newDirectiveNodes};
24✔
406
        fnNode = {...fnNode, body: bodyNode};
24✔
407

×
408
        // Add any remaining comments to first statement / last directive / function body
24✔
409
        if (commentNodes.length !== 0) {
24!
410
                let statementNodes = bodyNode.body;
24✔
411
                if (statementNodes.length !== 0) {
24✔
412
                        statementNodes = bodyNode.body = [...statementNodes];
24✔
413
                        const firstStatementNode = statementNodes[0];
×
414
                        statementNodes[0] = {
×
415
                                ...firstStatementNode,
×
416
                                leadingComments: combineArraysWithDedup(commentNodes, firstStatementNode.leadingComments)
✔
417
                        };
24✔
418
                } else if (newDirectiveNodes.length !== 0) {
24✔
419
                        const lastDirectiveNode = newDirectiveNodes[newDirectiveNodes.length - 1];
24✔
420
                        newDirectiveNodes[newDirectiveNodes.length - 1] = {
24✔
421
                                ...lastDirectiveNode,
24✔
422
                                trailingComments: combineArraysWithDedup(lastDirectiveNode.trailingComments, commentNodes)
×
423
                        };
×
424
                } else {
×
425
                        bodyNode.innerComments = combineArraysWithDedup(bodyNode.innerComments, commentNodes);
×
426
                }
×
427
        }
×
428

22✔
429
        // Return clone of function node
22✔
430
        return fnNode;
22✔
431
}
17,282✔
432

62✔
433
/**
62✔
434
 * Create object representing function.
62✔
435
 * @param {number} id - Function ID
62✔
436
 * @param {Object} node - Function/method/class AST node
62✔
437
 * @param {boolean} isStrict - `true` if function is strict mode
62✔
438
 * @param {Object} state - State object
62✔
439
 * @returns {Object} - Function object
62✔
440
 */
62✔
441
function createFunction(id, node, isStrict, state) {
26,588✔
442
        const parentFunction = state.currentFunction;
26,588✔
443
        const fn = {
26,588✔
444
                id,
26,588✔
445
                node,
26,588✔
446
                astJson: undefined,
26,588✔
447
                isStrict,
26✔
448
                parent: parentFunction,
26✔
449
                children: [],
26✔
450
                trail: parentFunction ? [...state.trail] : undefined,
26✔
451
                bindings: [],
26✔
452
                externalVars: new Map(), // Keyed by block
26✔
453
                scopes: undefined,
26✔
454
                globalVarNames: new Set(),
26✔
455
                reservedVarNames: new Set(),
×
456
                amendments: [],
26✔
457
                superIsProto: false,
26✔
458
                containsEval: false,
26✔
459
                containsImport: false,
26✔
460
                hasSuperClass: false,
26✔
461
                firstComplexParamIndex: undefined
22✔
462
        };
22✔
463

22✔
464
        if (parentFunction) parentFunction.children.push(fn);
22✔
465

22✔
466
        state.functions.push(fn);
22!
467
        state.fileContainsFunctionsOrEval = true;
26✔
468

26✔
469
        return fn;
26✔
470
}
26✔
471

26✔
472
/**
26✔
473
 * Get type code for function.
62✔
474
 * @param {Object} fnNode - Function AST node
62✔
475
 * @returns {string} - Function type code
62✔
476
 */
62✔
477
function getFunctionType(fnNode) {
16,250✔
478
        return fnNode.async
16,250✔
479
                ? fnNode.generator
16,250✔
480
                        ? FN_TYPE_ASYNC_GENERATOR_FUNCTION
180✔
481
                        : FN_TYPE_ASYNC_FUNCTION
180✔
482
                : fnNode.generator
16,250✔
483
                        ? FN_TYPE_GENERATOR_FUNCTION
16,070✔
484
                        : FN_TYPE_FUNCTION;
16,250✔
485
}
16,250✔
486

62✔
487
/**
62✔
488
 * Escape filename so it can be safely included in tracker comment.
62✔
489
 * @param {string} filename - File path
62✔
490
 * @returns {string} - Filename escaped
62✔
491
 */
24✔
492
function escapeFilename(filename) {
4,320✔
493
        // Encode filename as JSON to escape non-ascii chars.
4,320✔
494
        // Convert `*/` to `*\/` so does not terminate comment early.
4,320✔
495
        // `JSON.parse('"*\/"')` is `'*/'` so it needs no special unescaping.
4,320✔
496
        return JSON.stringify(filename).slice(1, -1).replace(/\*\//g, '*\\/');
4,320✔
497
}
4,320✔
498

24✔
499
/**
24✔
500
 * Determine if function is strict mode. If it is, set `state.isStrict` flag.
24✔
501
 * Call visitor with strict/sloppy mode flags.
24!
502
 * @param {Object} fnNode - Function or method AST node
×
503
 * @param {boolean} hasBodyBlock - `true` if has body block (only arrow functions can not)
×
504
 * @param {Object} state - State object
×
505
 * @param {Function} visit - Visitor function
×
506
 * @returns {*} - Visitor function's return value
×
507
 */
×
508
function withStrictModeState(fnNode, hasBodyBlock, state, visit) {
21,334✔
509
        // Get if strict mode
21,334✔
510
        let {isStrict} = state,
21,334✔
511
                isEnteringStrict = false;
21,334✔
512
        if (!isStrict && hasBodyBlock && hasUseStrictDirective(fnNode.body)) {
21,334✔
513
                isStrict = isEnteringStrict = state.isStrict = true;
228✔
514
        }
228✔
515

21,334✔
516
        // Call visitor
21,334✔
517
        const res = visit(isStrict, isEnteringStrict);
21,334✔
518

21,334✔
519
        // If entered strict mode, exit it again
21,334✔
520
        if (isEnteringStrict) state.isStrict = false;
21,334✔
521

21,334✔
522
        // Return visitor's return value
21,334✔
523
        return res;
21,334✔
524
}
21,334✔
525

×
526
/**
×
527
 * Hoist sloppy function declarations if they can be hoisted.
×
528
 * Function declarations are hoisted to the top block in parent function body or program
×
529
 * if they are defined in sloppy mode (i.e. outside environment is sloppy mode, regardless of
×
530
 * whether function itself strict mode) and they are not async or generator functions.
×
531
 *
×
532
 * They can only be hoisted if:
×
533
 *   1. No `const`, `let` or class declaration with same name in block they'd be hoisted to.
×
534
 *   2. No parameter in parent function with same name.
×
535
 *   3. No other bindings in intermediate blocks
×
536
 *      (including other function declarations which are themselves hoisted)
×
537
 *
×
538
 * When a function declaration is hoisted, it produces two separate bindings:
×
539
 *   1. Binding in block where originally defined.
×
540
 *   2. Binding in block it's hoisted to.
×
541
 *
×
542
 * See https://github.com/babel/babel/pull/14203#issuecomment-1038187168
×
543
 *
×
544
 * @param {Object} state - State object
×
545
 * @returns {undefined}
×
546
 */
×
547
function hoistSloppyFunctionDeclarations(state) {
3,288✔
548
        for (const declaration of state.sloppyFunctionDeclarations) {
3,288✔
549
                hoistSloppyFunctionDeclaration(declaration);
16✔
550
        }
16✔
551
}
3,288✔
552

×
553
/**
×
554
 * Hoist function declaration, if it can be hoisted.
×
555
 * Should only be called for functions which:
62✔
556
 *   1. are not already in the top block in parent function / program
62✔
557
 *   2. are not async or generator functions
62✔
558
 *
62✔
559
 * @param {Object} declaration - Declaration object
62✔
560
 * @param {string} declaration.varName - Function name
62✔
561
 * @param {Object} declaration.binding - Binding object for binding in block where originally declared
62✔
562
 * @param {Object} declaration.block - Block object for block where originally declared
36✔
563
 * @param {Object} declaration.hoistBlock - Block object for block where could be hoisted to
36✔
564
 * @param {Object} [declaration.parentFn] - Function object for parent function
36✔
565
 * @returns {undefined}
36✔
566
 */
36✔
567
function hoistSloppyFunctionDeclaration(declaration) {
16!
568
        const {varName, hoistBlock} = declaration;
16✔
569

16✔
570
        // Do not hoist if existing const, let or class declaration binding in hoist block
16✔
571
        const hoistBlockBinding = hoistBlock.bindings.get(varName);
16✔
572
        if (hoistBlockBinding && !hoistBlockBinding.isVar) return;
16!
573

16✔
574
        // If parent function's params include var with same name, do not hoist.
16✔
575
        // NB: `hoistBlock.parent` here is either parent function params block or file block.
16!
576
        // In CommonJS code, file block is CommonJS wrapper function's params, and in any other context
16✔
577
        // file block contains no bindings except `this`. So it's safe to treat as a params block in all cases.
16✔
578
        // NB: `paramsBlockBinding.argNames` check is to avoid the pseudo-param `arguments` blocking hoisting.
22✔
579
        const paramsBlockBinding = hoistBlock.parent.bindings.get(varName);
22✔
580
        if (paramsBlockBinding && !paramsBlockBinding.argNames) return;
×
581

×
582
        // If any binding in intermediate blocks, do not hoist.
22✔
583
        // NB: This includes function declarations which will be themselves hoisted.
22!
584
        let inBetweenBlock = declaration.block.parent;
22✔
585
        while (inBetweenBlock !== hoistBlock) {
22!
NEW
586
                if (inBetweenBlock.bindings.has(varName)) return;
×
587
                inBetweenBlock = inBetweenBlock.parent;
×
588
        }
×
589

16✔
590
        // Can be hoisted
16✔
591
        if (!hoistBlockBinding) {
16!
NEW
592
                hoistBlock.bindings.set(varName, {...declaration.binding, isVar: true});
✔
593
        } else if (!hoistBlockBinding.isFrozenName) {
4✔
594
                // Existing binding is a `var` declaration.
4✔
595
                // Flag binding as frozen so `var` declarations' identifiers don't get renamed.
4✔
596
                hoistBlockBinding.isFrozenName = true;
4✔
597
                hoistBlockBinding.trails.length = 0;
4✔
598
        }
4✔
599
}
4✔
600

4✔
601
/**
4✔
602
 * Instrument function.
4✔
603
 * @param {Object} node - Function or method AST node
4✔
604
 * @param {Object} fn - Function object
4✔
605
 * @param {Object|Array} parent - Parent AST node/container
62✔
606
 * @param {string|number} key - Node's key on parent AST node/container
62✔
607
 * @param {Object} paramsBlock - Function's params block object
62✔
608
 * @param {Object} [bodyBlock] - Function's body block object (if it has one, arrow functions may not)
62✔
609
 * @param {Object} state - State object
62✔
610
 * @returns {undefined}
62✔
611
 */
62✔
612
function instrumentFunction(node, fn, parent, key, paramsBlock, bodyBlock, state) {
25,586✔
613
        // Restore to original place in AST
16✔
614
        parent[key] = node;
16✔
615

16✔
616
        // Insert tracker call and block vars (`livepack_scopeId` and `livepack_temp`) into function.
16✔
617
        // NB: `bodyBlock` here may actually be params block if is an arrow function with no body.
16✔
618
        const trackerNode = createTrackerCall(fn, state);
16✔
619
        insertTrackerCodeIntoFunction(fn, node, paramsBlock, bodyBlock, trackerNode, state);
16!
620

×
621
        if (node.type === 'ArrowFunctionExpression') insertArrowFunctionTrackerComment(fn, node, state);
16!
622
}
16✔
623

16✔
624
/**
16✔
625
 * Create tracker call.
16✔
626
 * Create scopes array, and copy external vars down to parent function.
16✔
627
 * @param {Object} fn - Function object
16!
628
 * @param {Object} state - State object
16✔
629
 * @returns {Object} - AST node for tracker call
62✔
630
 */
62✔
631
function createTrackerCall(fn, state) {
26,588✔
632
        // Sort scopes in ascending order of block ID
26,588✔
633
        const scopes = [...fn.externalVars].map(([block, vars]) => ({block, vars}))
26,588✔
634
                .sort((scope1, scope2) => (scope1.block.id > scope2.block.id ? 1 : -1));
26,588✔
635
        fn.scopes = scopes;
26,588✔
636

26,588✔
637
        // Add external vars to parent function where external to that function too
26,588✔
638
        const parentFunction = fn.parent;
26,588✔
639
        if (parentFunction) {
26,588✔
640
                // External vars
17,188✔
641
                for (const {block, vars} of scopes) {
17,188✔
642
                        if (block.id >= parentFunction.id) break;
11,662✔
643
                        for (const [varName, {binding}] of Object.entries(vars)) {
11,662✔
644
                                getOrCreateExternalVar(parentFunction, block, varName, binding);
10,464✔
645
                        }
10,464✔
646
                }
5,950✔
647
        }
17,188✔
648

26,588✔
649
        // `livepack_tracker(livepack_getFnInfo_3, () => [[livepack_scopeId_2, x]])`
26,588✔
650
        return t.callExpression(state.trackerVarNode, [
26,588✔
651
                createFnInfoVarNode(fn.id, state),
26,588✔
652
                t.arrowFunctionExpression([], t.arrayExpression(
26,588✔
653
                        scopes.map(scope => t.arrayExpression([
26,588✔
654
                                scope.block.varsBlock.scopeIdVarNode,
19,310✔
655
                                ...Object.values(scope.vars).map(blockVar => blockVar.binding.varNode)
2✔
656
                        ]))
2✔
657
                ))
2✔
658
        ]);
2✔
659
}
2✔
660

2✔
661
/**
2✔
662
 * Insert tracker comment into function declaration/expression.
2✔
UNCOV
663
 * @param {Object} fn - Function object
×
664
 * @param {Object} node - Function declaration or expression AST node
2✔
665
 * @param {Object} state - State object
2!
666
 * @returns {undefined}
×
667
 */
62✔
668
function insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state) {
7,028✔
669
        // Insert tracker comment before identifier, or before 1st param or before function body
7,028✔
670
        const commentHolderNode = node.id || (node.params.length !== 0 ? node.params[0] : node.body);
7,028✔
671
        insertTrackerComment(fn.id, getFunctionType(node), commentHolderNode, 'leading', state);
7,028✔
672
}
7,028✔
673

62✔
674
/**
62✔
675
 * Insert tracker comment into arrow function.
62✔
676
 * @param {Object} fn - Function object
62✔
677
 * @param {Object} node - Arrow function AST node
62✔
678
 * @param {Object} state - State object
62✔
679
 * @returns {undefined}
62✔
680
 */
62✔
681
function insertArrowFunctionTrackerComment(fn, node, state) {
9,336✔
682
        // Insert tracker comment before first param. If no params, before function body.
9,336✔
683
        const paramNodes = node.params;
9,336✔
684
        insertTrackerComment(
×
685
                fn.id, node.async ? FN_TYPE_ASYNC_FUNCTION : FN_TYPE_FUNCTION,
✔
686
                paramNodes.length !== 0 ? paramNodes[0] : node.body, 'leading', state
✔
687
        );
×
688
}
×
689

×
690
/**
×
691
 * Insert tracker comment.
×
692
 * @param {number} fnId - Function ID
×
693
 * @param {string} fnType - Function type
×
694
 * @param {Object} commentHolderNode - AST node to attach comment to
×
695
 * @param {string} commentType - 'leading' / 'inner' / 'trailing'
×
696
 * @param {Object} state - State object
×
697
 * @returns {undefined}
×
698
 */
×
699
function insertTrackerComment(fnId, fnType, commentHolderNode, commentType, state) {
26,588✔
700
        insertComment(
26,588✔
701
                commentHolderNode, commentType,
26,588✔
702
                `${TRACKER_COMMENT_PREFIX}${fnId};${fnType};${state.filenameEscaped}`
26,588✔
703
        );
26,588✔
704
}
26,588✔
705

×
706
/**
×
707
 * Create function info function containing function AST, details of internal and external vars etc.
×
708
 * @param {Object} fn - Function object
×
709
 * @param {Object} state - State object
×
710
 * @returns {Object} - AST node for function info function
×
711
 */
×
712
function createFunctionInfoFunction(fn, state) {
26,588✔
713
        // Compile internal vars and reserved var names
26,588✔
714
        const internalVars = Object.create(null),
26,588✔
715
                {reservedVarNames} = fn;
26,588✔
716
        for (const {name: varName, trails, isFrozenName} of fn.bindings) {
26,588✔
717
                if (isFrozenName) {
44,082✔
718
                        reservedVarNames.add(varName);
1,500✔
719
                } else {
44,082✔
720
                        const internalVar = internalVars[varName] || (internalVars[varName] = []);
42,582✔
721
                        internalVar.push(...trails);
42,582✔
722
                }
42,582✔
723
        }
44,082✔
724

26,588✔
725
        // Compile amendments.
26,588✔
726
        // Reverse order so deepest are first.
26,588✔
727
        // Remove the need for an internal var if binding has frozen name.
26,588✔
728
        let amendments;
26,588✔
729
        if (fn.amendments.length > 0) {
26,588✔
730
                amendments = fn.amendments.map(({type, blockId, trail, binding}) => {
1,286✔
731
                        if (type === CONST_VIOLATION_NEEDS_VAR && binding.isFrozenName) {
1,366!
732
                                type = CONST_VIOLATION_NEEDS_NO_VAR;
×
733
                        }
×
734
                        return [type, blockId, ...trail];
1,366✔
735
                }).reverse();
1,286✔
736
        }
1,286✔
737

26,588✔
738
        // Create JSON function info string
26,588✔
739
        const {children} = fn;
26,588✔
740
        let argNames;
26,588✔
741
        let json = JSON.stringify({
26,588✔
742
                scopes: fn.scopes.map(({block, vars}) => ({
26,588✔
743
                        blockId: block.id,
19,310✔
744
                        blockName: block.name,
19,310✔
745
                        vars: mapValues(vars, (varProps, varName) => {
19,310✔
746
                                if (varName === 'arguments') argNames = varProps.binding.argNames;
33,572✔
747
                                return {
33,572✔
748
                                        isReadFrom: varProps.isReadFrom || undefined,
33,572✔
749
                                        isAssignedTo: varProps.isAssignedTo || undefined,
33,572✔
750
                                        isFrozenInternalName: varProps.binding.isFrozenName || undefined,
33,572✔
751
                                        trails: varProps.trails
26✔
752
                                };
26✔
753
                        })
26✔
754
                })),
26✔
755
                isStrict: fn.isStrict || undefined,
26✔
756
                superIsProto: fn.superIsProto || undefined,
26✔
757
                containsEval: fn.containsEval || undefined,
26✔
758
                containsImport: fn.containsImport || undefined,
✔
759
                argNames,
×
760
                internalVars,
×
761
                reservedVarNames: reservedVarNames.size !== 0 ? [...reservedVarNames] : undefined,
26✔
762
                globalVarNames: fn.globalVarNames.size !== 0 ? [...fn.globalVarNames] : undefined,
26✔
763
                amendments,
26✔
764
                hasSuperClass: fn.hasSuperClass || undefined,
26✔
765
                childFns: children.map(childFn => childFn.trail)
26✔
766
        });
26✔
767

26✔
768
        // Add AST JSON to JSON
26✔
769
        json = `${json.slice(0, -1)},"ast":${fn.astJson}}`;
26✔
770

26✔
771
        // Create function returning JSON string and references to function info function for child fns.
26✔
772
        // Make output as single-quoted string for shorter output (not escaping every `"`).
26,588✔
773
        return t.functionDeclaration(createFnInfoVarNode(fn.id, state), [], t.blockStatement([
26,588✔
774
                t.returnStatement(t.arrayExpression([
26,588✔
775
                        stringLiteralWithSingleQuotes(json),
26,588✔
776
                        t.arrayExpression(children.map(childFn => createFnInfoVarNode(childFn.id, state))),
26,588✔
777
                        state.getSourcesNode
36✔
778
                ]))
36✔
779
        ]));
36✔
780
}
36✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc