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

overlookmotel / livepack / 7305779414

23 Dec 2023 02:56AM UTC coverage: 90.551% (-0.03%) from 90.578%
7305779414

push

github

overlookmotel
Capture `module` objects when function declaration called `module` at top level [fix]

Fixes #566.

4680 of 5034 branches covered (0.0%)

Branch coverage included in aggregate %.

15 of 15 new or added lines in 3 files covered. (100.0%)

35 existing lines in 15 files now uncovered.

12473 of 13909 relevant lines covered (89.68%)

8705.64 hits per line

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

85.81
/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 t = require('@babel/types');
62✔
30

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

62✔
50
// Exports
62✔
51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

25,454✔
233
        // Visit body
25,454✔
234
        if (bodyBlock) {
25,454✔
235
                visitFunctionBody(fnNode, bodyBlock, state);
19,776✔
236
        } else {
25,454✔
237
                visitKey(fnNode, 'body', Expression, state);
5,678✔
238
        }
5,678✔
239

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

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

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

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

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

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

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

2,270✔
297
                        AssigneeLet(paramNode, state, paramNodes, index);
2,270✔
298
                }
2,270✔
299
        }, state);
25,880✔
300

25,880✔
301
        // Record index of first complex param
25,880✔
302
        fn.firstComplexParamIndex = firstComplexParamIndex;
25,880✔
303

25,880✔
304
        // Return array of params which are linked to `arguments`
25,880✔
305
        return argNames;
25,880✔
306
}
25,880✔
307

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

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

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

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

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

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

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

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

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

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

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

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

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

22✔
463
        if (parentFunction) parentFunction.children.push(fn);
22!
UNCOV
464

×
465
        state.functions.push(fn);
26✔
466
        state.fileContainsFunctionsOrEval = true;
26✔
467

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

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

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

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

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

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

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

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

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

16✔
569
        // Do not hoist if existing const, let or class declaration binding in hoist block.
16✔
570
        // Also exit if binding exists and already has frozen name. In that case, function may or may not be
16✔
571
        // hoisted, but it doesn't matter either way, as only implication of hoisting is to freeze var name.
16✔
572
        const hoistBlockBinding = hoistBlock.bindings.get(varName);
16!
573
        if (hoistBlockBinding && (!hoistBlockBinding.isVar || hoistBlockBinding.isFrozenName)) return;
16!
574

16✔
575
        // If parent function's params include var with same name, do not hoist.
16✔
576
        // NB: `hoistBlock.parent` here is either parent function params block or file block.
16✔
577
        // In CommonJS code, file block is CommonJS wrapper function's params, and in any other context
22✔
578
        // file block contains no bindings except `this`. So it's safe to treat as a params block in all cases.
22✔
579
        // NB: `paramsBlockBinding.argNames` check is to avoid the pseudo-param `arguments` blocking hoisting.
22!
580
        // An actual param called `arguments` *does* prevent hoisting.
22✔
581
        // e.g. `function f(arguments) { { function arguments() {} } return arguments; }`
16✔
582
        // returns the value outer function is called with, not the inner function.
16✔
583
        const paramsBlockBinding = hoistBlock.parent.bindings.get(varName);
16✔
584
        if (paramsBlockBinding && !paramsBlockBinding.argNames) return;
4!
585

4✔
586
        // If any binding in intermediate blocks, do not hoist.
4✔
587
        // NB: This includes function declarations which will be themselves hoisted.
4✔
588
        let inBetweenBlock = declaration.block.parent;
4✔
589
        while (inBetweenBlock !== hoistBlock) {
4!
590
                if (inBetweenBlock.bindings.has(varName)) return;
4✔
591
                inBetweenBlock = inBetweenBlock.parent;
4✔
592
        }
4✔
593

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

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

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

25,454✔
625
        if (node.type === 'ArrowFunctionExpression') insertArrowFunctionTrackerComment(fn, node, state);
25,454✔
626
}
25,454✔
627

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

26,456✔
641
        // Add external vars to parent function where external to that function too
26,456✔
642
        const parentFunction = fn.parent;
26,456✔
643
        if (parentFunction) {
26,456✔
644
                // External vars
17,178✔
645
                for (const {block, vars} of scopes) {
17,178✔
646
                        if (block.id >= parentFunction.id) break;
11,608✔
647
                        for (const [varName, {binding}] of vars) {
2✔
648
                                getOrCreateExternalVar(parentFunction, block, varName, binding);
2✔
649
                        }
2✔
650
                }
2✔
651
        }
2✔
652

2✔
653
        // `livepack_tracker(livepack_getFnInfo_3, () => [[livepack_scopeId_2, x]])`
2✔
654
        return t.callExpression(state.trackerVarNode, [
2✔
655
                createFnInfoVarNode(fn.id, state),
2!
UNCOV
656
                t.arrowFunctionExpression([], t.arrayExpression(
×
657
                        scopes.map(scope => t.arrayExpression([
26,456✔
658
                                scope.block.varsBlock.scopeIdVarNode,
19,122✔
659
                                ...[...scope.vars.values()].map(blockVar => blockVar.binding.varNode)
19,122✔
660
                        ]))
26,456✔
661
                ))
26,456✔
662
        ]);
26,456✔
663
}
26,456✔
664

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

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

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

×
710
/**
×
711
 * Create function info function containing function AST, details of internal and external vars etc.
×
712
 * @param {Object} fn - Function object
×
713
 * @param {Object} state - State object
×
714
 * @returns {Object} - AST node for function info function
×
715
 */
×
716
function createFunctionInfoFunction(fn, state) {
26,456✔
717
        // Compile internal vars and reserved var names
26,456✔
718
        const internalVars = new Map(),
26,456✔
719
                {reservedVarNames} = fn;
26,456✔
720
        for (const {name: varName, trails, isFrozenName} of fn.bindings) {
26,456✔
721
                if (isFrozenName) {
43,492✔
722
                        reservedVarNames.add(varName);
1,596✔
723
                } else {
43,492✔
724
                        const internalVar = internalVars.get(varName);
41,896✔
725
                        if (internalVar) {
41,896✔
726
                                internalVar.push(...trails);
516✔
727
                        } else {
41,896✔
728
                                internalVars.set(varName, [...trails]);
41,380✔
729
                        }
41,380✔
730
                }
41,896✔
731
        }
43,492✔
732

26,456✔
733
        // Compile amendments.
26,456✔
734
        // Reverse order so deepest are first.
26,456✔
735
        // Remove the need for an internal var if binding has frozen name.
26,456✔
736
        let amendments;
26,456✔
737
        if (fn.amendments.length > 0) {
26,456✔
738
                amendments = fn.amendments.map(({type, blockId, trail, binding}) => {
1,292✔
739
                        if (type === CONST_VIOLATION_NEEDS_VAR && binding.isFrozenName) {
1,372!
740
                                type = CONST_VIOLATION_NEEDS_NO_VAR;
×
741
                        }
×
742
                        return [type, blockId, ...trail];
1,372✔
743
                }).reverse();
1,292✔
744
        }
1,292✔
745

26,456✔
746
        // Create JSON function info string
26,456✔
747
        const {children} = fn;
26,456✔
748
        let argNames;
26,456✔
749
        let json = JSON.stringify({
26,456✔
750
                scopes: fn.scopes.map(({block, vars}) => ({
26,456✔
751
                        blockId: block.id,
19,122✔
752
                        blockName: block.name,
19,122✔
753
                        vars: Object.fromEntries([...vars].map(([varName, varProps]) => {
19,122✔
754
                                if (varName === 'arguments') argNames = varProps.binding.argNames;
33,058✔
755
                                return [
33,058✔
756
                                        varName,
33,058✔
757
                                        {
33,058✔
758
                                                isReadFrom: varProps.isReadFrom || undefined,
33,058✔
759
                                                isAssignedTo: varProps.isAssignedTo || undefined,
33,058✔
760
                                                isFrozenInternalName: varProps.binding.isFrozenName || undefined,
26✔
761
                                                trails: varProps.trails
26✔
762
                                        }
26✔
763
                                ];
26✔
764
                        }))
26✔
765
                })),
26✔
766
                isStrict: fn.isStrict || undefined,
26✔
767
                superIsProto: fn.superIsProto || undefined,
26✔
768
                containsEval: fn.containsEval || undefined,
✔
769
                containsImport: fn.containsImport || undefined,
26✔
770
                argNames,
26✔
771
                internalVars: Object.fromEntries(internalVars),
26✔
772
                reservedVarNames: reservedVarNames.size !== 0 ? [...reservedVarNames] : undefined,
26✔
773
                globalVarNames: fn.globalVarNames.size !== 0 ? [...fn.globalVarNames] : undefined,
26✔
774
                amendments,
26✔
775
                hasSuperClass: fn.hasSuperClass || undefined,
26✔
776
                childFns: children.map(childFn => childFn.trail)
26✔
777
        });
26✔
778

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

4✔
782
        // Create function returning JSON string and references to function info function for child fns.
26,456✔
783
        // Make output as single-quoted string for shorter output (not escaping every `"`).
26,456✔
784
        return t.functionDeclaration(createFnInfoVarNode(fn.id, state), [], t.blockStatement([
26,456✔
785
                t.returnStatement(t.arrayExpression([
26,456✔
786
                        stringLiteralWithSingleQuotes(json),
36✔
787
                        t.arrayExpression(children.map(childFn => createFnInfoVarNode(childFn.id, state))),
36✔
788
                        state.getSourcesNode
36✔
789
                ]))
×
790
        ]));
×
791
}
×
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