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

overlookmotel / livepack / 6963313779

22 Nov 2023 10:24PM UTC coverage: 90.246% (-0.05%) from 90.293%
6963313779

push

github

overlookmotel
Record frozen function names in instrumentation

4733 of 5094 branches covered (0.0%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 1 file covered. (100.0%)

8 existing lines in 1 file now uncovered.

12652 of 14170 relevant lines covered (89.29%)

12760.57 hits per line

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

83.62
/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
        visitFunctionParamsAndBody,
62✔
16
        removeUnnecessaryUseStrictDirectives,
62✔
17
        createFunction,
62✔
18
        getFunctionType,
62✔
19
        escapeFilename,
62✔
20
        withStrictModeState,
62✔
21
        hoistSloppyFunctionDeclarations,
62✔
22
        instrumentFunctionOrClassConstructor,
62✔
23
        insertTrackerComment,
62✔
24
        createFunctionInfoFunction
62✔
25
};
62✔
26

62✔
27
// Modules
62✔
28
const mapValues = require('lodash/mapValues'),
62✔
29
        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
        {insertTrackerCodeIntoFunctionBody, insertTrackerCodeIntoFunctionParams} = 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) {
11,242✔
61
        // Tracker comment is inserted later to avoid it getting relocated if function has complex params
11,242✔
62
        // which are later relocated to inside function body
11,242✔
63
        visitFunction(node, parent, key, undefined, false, node.body.type === 'BlockStatement', state);
11,242✔
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,314✔
75
        // Visit function
4,314✔
76
        const fnName = node.id.name;
4,314✔
77
        const fn = visitFunction(node, parent, key, fnName, true, true, state);
4,314✔
78

4,314✔
79
        // Create binding for function name
4,314✔
80
        // TODO: Whether the value of the function is hoisted depends on whether is a top level statement
4,314✔
81
        // (including in a labeled statement)
4,314✔
82
        // `() => { console.log(typeof x); function x() {} }` -> Logs 'function'
4,314✔
83
        // `() => { console.log(typeof x); q: function x() {} }` -> Logs 'function'
4,314✔
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[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!
UNCOV
112
}
×
UNCOV
113

×
UNCOV
114
/**
×
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) {
3,054✔
123
        // If not anonymous, create and enter name block
3,054✔
124
        let nameBlock, fnName;
3,054✔
125
        const idNode = node.id;
3,054✔
126
        if (idNode) {
3,054✔
127
                fnName = idNode.name;
850!
128
                nameBlock = createAndEnterFunctionOrClassNameBlock(fnName, true, state);
850✔
129
        }
850✔
130

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

3,054✔
134
        if (nameBlock) {
3,054✔
135
                // Exit name block
850✔
136
                state.currentBlock = nameBlock.parent;
850✔
137

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

3,054✔
144
        // Insert tracker comment
3,054✔
145
        insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state);
3,054✔
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,758✔
156
        const block = createAndEnterBlock(fnName, false, state);
1,758!
157
        createBinding(block, fnName, {isConst: true, isSilentConst, isFrozenName: true}, state);
1,758✔
158
        state.currentFunction?.reservedVarNames.add(fnName);
1,758✔
159
        return block;
1,758✔
160
}
1,758✔
161

2✔
162
/**
2✔
163
 * Visit function declaration, function expression or arrow function.
2!
UNCOV
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) {
18,610✔
174
        return withStrictModeState(
18,610✔
175
                node, hasBodyBlock, state,
18,610✔
176
                (isStrict, isEnteringStrict) => visitFunctionOrMethod(
18,610✔
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)
10!
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(
27,818✔
197
        fnNode, parent, key, fnName, isStrict, isEnteringStrict, isFullFunction, hasBodyBlock, state
27,818✔
198
) {
27,818✔
199
        // Create params block. If is full function, create bindings for `this` + `new.target`.
27,818✔
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 + body
×
225
        const argNames = visitFunctionParamsAndBody(fn, fnNode, paramsBlock, bodyBlock, isStrict, state);
14✔
226

14✔
227
        // If is full function, create binding for `arguments` in params block.
27,818✔
228
        // Param called `arguments` takes precedence.
27,818✔
229
        if (isFullFunction) {
27,818✔
230
                if (!paramsBlock.bindings.arguments) createArgumentsBinding(paramsBlock, isStrict, argNames);
16,576✔
231
                state.currentThisBlock = parentThisBlock;
16,576✔
232
        }
16,576✔
233

27,818✔
234
        // Serialize AST
27,818✔
235
        fn.astJson = serializeFunctionAst(fnNode, hasBodyBlock, isStrict, isEnteringStrict);
27,818✔
236

27,818✔
237
        // Exit function
27,818✔
238
        state.currentBlock = paramsBlock.parent;
27,818✔
239
        state.currentFunction = fn.parent;
27,818✔
240
        state.trail = parentTrail;
27,818✔
241

27,818✔
242
        // Temporarily remove from AST so is not included in parent function's serialized AST
27,818✔
243
        parent[key] = null;
27,818✔
244

27,818✔
245
        // Queue instrumentation of function in 2nd pass
27,818✔
246
        state.secondPass(instrumentFunction, fnNode, fn, parent, key, paramsBlock, bodyBlock, state);
27,818✔
247

27,818✔
248
        return fn;
27,818✔
249
}
27,818✔
250

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

2,308✔
285
                                        // Make params block the vars block. Tracker call and scope ID var will go in params.
2,308✔
286
                                        if (bodyBlock) paramsBlock.varsBlock = bodyBlock.varsBlock = paramsBlock;
2,308✔
287
                                }
2,308✔
288
                        }
2,460✔
289

2,682✔
290
                        AssigneeLet(paramNode, state, paramNodes, index);
2,682✔
291
                }
2,682✔
292
        }, state);
28,278✔
293

28,278✔
294
        // Record index of first complex param
28,278✔
295
        fn.firstComplexParamIndex = firstComplexParamIndex;
28,278✔
296

28,278✔
297
        // Visit body
28,278✔
298
        if (bodyBlock) {
28,278✔
299
                state.currentBlock = bodyBlock;
20,914✔
300
                const parentHoistBlock = state.currentHoistBlock;
20,914✔
301
                state.currentHoistBlock = bodyBlock;
20,914✔
302
                visitKey(fnNode, 'body', FunctionBodyBlock, state);
20,914✔
303
                state.currentHoistBlock = parentHoistBlock;
20,914✔
304
        } else {
28,278✔
305
                visitKey(fnNode, 'body', Expression, state);
7,364✔
306
        }
7,364✔
307

28,278✔
308
        // Return array of params which are linked to `arguments`
28,278✔
309
        return argNames;
28,278✔
310
}
28,278✔
311

62✔
312
/**
62✔
313
 * Visitor for function body block.
62✔
314
 * @param {Object} node - Function body block AST node
62✔
315
 * @param {Object} state - State object
62✔
316
 * @returns {undefined}
62✔
317
 */
62✔
318
function FunctionBodyBlock(node, state) {
20,914✔
319
        visitKeyContainer(node, 'body', Statement, state);
20,914✔
320
}
20,914✔
321

62✔
322
/**
62✔
323
 * Serialize function AST to JSON.
62✔
324
 * Remove unnecessary 'use strict' directives if present.
62✔
325
 * Do not mutate the node passed in, to ensure these changes only affect the serialized AST,
62✔
326
 * and not the instrumented output.
62✔
327
 * @param {Object} fnNode - Function AST node
62✔
328
 * @param {boolean} hasBodyBlock - `true` if has body block (only arrow functions can not)
62✔
329
 * @param {boolean} isStrict - `true` if function is strict mode
28✔
330
 * @param {boolean} isEnteringStrict - `true` if function transitions into strict mode
28✔
331
 *   (and therefore needs to retain a 'use strict' directive)
×
UNCOV
332
 * @returns {string} - Function AST as JSON
×
333
 */
28✔
334
function serializeFunctionAst(fnNode, hasBodyBlock, isStrict, isEnteringStrict) {
27,818✔
335
        // Remove unnecessary 'use strict' directives
27,818✔
336
        if (hasBodyBlock && isStrict) {
27,818✔
337
                const alteredFnNode = removeUnnecessaryUseStrictDirectives(fnNode, !isEnteringStrict);
16,886✔
338
                if (alteredFnNode) fnNode = alteredFnNode;
16,886✔
339
        }
16,886✔
340

27,818✔
341
        // Stringify AST to JSON
27,818✔
342
        return JSON.stringify(fnNode);
27,818✔
343
}
27,818✔
344

28✔
345
/**
28✔
346
 * Remove unnecessary 'use strict' directives from function body.
28✔
347
 * Relocate any comments from deleted directives.
28✔
348
 * Do not mutate input - clone if needs alteration.
28✔
349
 * Return `undefined` if no alteration necessary.
8✔
350
 * @param {Object} fnNode - Function AST node
8✔
351
 * @param {boolean} needsNoDirective - `true` if function already strict mode from outer environment
8✔
352
 * @returns {Object|undefined} - Altered function AST node, or `undefined` if no directives removed
×
353
 */
×
354
function removeUnnecessaryUseStrictDirectives(fnNode, needsNoDirective) {
17,346✔
355
        // If no directives, return `undefined`
17,346!
356
        let bodyNode = fnNode.body;
17,346✔
357
        const directiveNodes = bodyNode.directives;
17,346✔
358
        if (directiveNodes.length === 0) return undefined;
17,346✔
359

350✔
360
        // Remove unnecessary directives
350✔
361
        const newDirectiveNodes = [],
350✔
362
                commentNodes = [];
350✔
363
        for (let directiveNode of directiveNodes) {
5,058✔
364
                if (directiveNode.value.value === 'use strict') {
386!
365
                        if (needsNoDirective) {
314✔
366
                                commentNodes.push(
22✔
367
                                        ...(directiveNode.leadingComments || []),
22✔
368
                                        ...(directiveNode.trailingComments || [])
22✔
369
                                );
22✔
370
                                continue;
22✔
371
                        }
22✔
372
                        needsNoDirective = true;
292✔
373
                }
292✔
374

364✔
375
                // Add any comments removed from previous directives
364✔
376
                if (commentNodes.length !== 0) {
386!
377
                        directiveNode = {
×
378
                                ...directiveNode,
×
379
                                leadingComments: combineArraysWithDedup(commentNodes, directiveNode.leadingComments)
×
380
                        };
×
381
                        commentNodes.length = 0;
✔
382
                }
×
383

364✔
384
                newDirectiveNodes.push(directiveNode);
364✔
385
        }
364✔
386

350✔
387
        // If no directives need to be removed, return `undefined`
350✔
388
        if (newDirectiveNodes.length === directiveNodes.length) return undefined;
478✔
389

22✔
390
        // Clone function node
22✔
391
        bodyNode = {...bodyNode, directives: newDirectiveNodes};
22✔
392
        fnNode = {...fnNode, body: bodyNode};
22✔
393

22✔
394
        // Add any remaining comments to first statement / last directive / function body
22✔
395
        if (commentNodes.length !== 0) {
436!
396
                let statementNodes = bodyNode.body;
×
397
                if (statementNodes.length !== 0) {
×
398
                        statementNodes = bodyNode.body = [...statementNodes];
✔
399
                        const firstStatementNode = statementNodes[0];
24✔
400
                        statementNodes[0] = {
24✔
401
                                ...firstStatementNode,
24✔
402
                                leadingComments: combineArraysWithDedup(commentNodes, firstStatementNode.leadingComments)
24✔
403
                        };
×
404
                } else if (newDirectiveNodes.length !== 0) {
24✔
405
                        const lastDirectiveNode = newDirectiveNodes[newDirectiveNodes.length - 1];
×
406
                        newDirectiveNodes[newDirectiveNodes.length - 1] = {
×
407
                                ...lastDirectiveNode,
×
408
                                trailingComments: combineArraysWithDedup(lastDirectiveNode.trailingComments, commentNodes)
×
409
                        };
×
410
                } else {
×
411
                        bodyNode.innerComments = combineArraysWithDedup(bodyNode.innerComments, commentNodes);
×
412
                }
×
413
        }
×
414

22✔
415
        // Return clone of function node
22✔
416
        return fnNode;
22✔
417
}
17,346✔
418

62✔
419
/**
62✔
420
 * Create object representing function.
62✔
421
 * @param {number} id - Function ID
62✔
422
 * @param {Object} node - Function/method/class AST node
62✔
423
 * @param {boolean} isStrict - `true` if function is strict mode
62✔
424
 * @param {Object} state - State object
62✔
425
 * @returns {Object} - Function object
26✔
426
 */
26✔
427
function createFunction(id, node, isStrict, state) {
28,904✔
428
        const parentFunction = state.currentFunction;
28,904✔
429
        const fn = {
28,904✔
430
                id,
28,904✔
431
                node,
28,904✔
432
                astJson: undefined,
28,904✔
433
                isStrict,
28,904✔
434
                parent: parentFunction,
28,904✔
435
                children: [],
×
436
                trail: parentFunction ? [...state.trail] : undefined,
28,904✔
437
                bindings: [],
28,904✔
438
                externalVars: new Map(), // Keyed by block
28,904✔
439
                scopes: undefined,
28,904✔
440
                globalVarNames: new Set(),
28,904✔
441
                reservedVarNames: new Set(),
28,904✔
442
                amendments: [],
28,904✔
443
                superIsProto: false,
28,904!
444
                containsEval: false,
28,904✔
445
                containsImport: false,
28,904✔
446
                hasSuperClass: false,
28,904✔
447
                firstSuperStatementIndex: undefined,
28,904✔
448
                returnsSuper: false,
28,904✔
449
                firstComplexParamIndex: undefined
28,904✔
450
        };
28,904✔
451

28,904✔
452
        if (parentFunction) parentFunction.children.push(fn);
28,904✔
453

28,904✔
454
        state.functions.push(fn);
28,904✔
455
        state.fileContainsFunctionsOrEval = true;
28,904✔
456

28,904✔
457
        return fn;
28,904✔
458
}
28,904✔
459

62✔
460
/**
62✔
461
 * Get type code for function.
62✔
462
 * @param {Object} fnNode - Function AST node
62✔
463
 * @returns {string} - Function type code
62✔
464
 */
62✔
465
function getFunctionType(fnNode) {
16,576✔
466
        return fnNode.async
16,576✔
467
                ? fnNode.generator
16,576✔
468
                        ? FN_TYPE_ASYNC_GENERATOR_FUNCTION
176✔
469
                        : FN_TYPE_ASYNC_FUNCTION
24✔
470
                : fnNode.generator
24✔
471
                        ? FN_TYPE_GENERATOR_FUNCTION
24✔
472
                        : FN_TYPE_FUNCTION;
24✔
473
}
24✔
474

24✔
475
/**
24✔
476
 * Escape filename so it can be safely included in tracker comment.
24✔
477
 * @param {string} filename - File path
24✔
478
 * @returns {string} - Filename escaped
24✔
479
 */
24✔
480
function escapeFilename(filename) {
6,812✔
481
        // Encode filename as JSON to escape non-ascii chars.
6,812✔
482
        // Convert `*/` to `*\/` so does not terminate comment early.
6,812✔
483
        // `JSON.parse('"*\/"')` is `'*/'` so it needs no special unescaping.
6,812!
484
        return JSON.stringify(filename).slice(1, -1).replace(/\*\//g, '*\\/');
6,812✔
485
}
6,812✔
486

×
487
/**
×
488
 * Determine if function is strict mode. If it is, set `state.isStrict` flag.
×
489
 * Call visitor with strict/sloppy mode flags.
×
490
 * @param {Object} fnNode - Function or method AST node
×
491
 * @param {boolean} hasBodyBlock - `true` if has body block (only arrow functions can not)
×
492
 * @param {Object} state - State object
×
493
 * @param {Function} visit - Visitor function
×
494
 * @returns {*} - Visitor function's return value
×
495
 */
×
496
function withStrictModeState(fnNode, hasBodyBlock, state, visit) {
23,518✔
497
        // Get if strict mode
23,518✔
498
        let {isStrict} = state,
23,518✔
499
                isEnteringStrict = false;
23,518✔
500
        if (!isStrict && hasBodyBlock && hasUseStrictDirective(fnNode.body)) {
23,518✔
501
                isStrict = isEnteringStrict = state.isStrict = true;
292✔
502
        }
292✔
503

23,518✔
504
        // Call visitor
23,518✔
505
        const res = visit(isStrict, isEnteringStrict);
23,518✔
506

23,518✔
507
        // If entered strict mode, exit it again
23,518✔
508
        if (isEnteringStrict) state.isStrict = false;
23,518✔
509

23,518✔
510
        // Return visitor's return value
23,518✔
511
        return res;
23,518✔
512
}
23,518✔
513

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

62✔
541
/**
62✔
542
 * Hoist function declaration, if it can be hoisted.
62✔
543
 * Should only be called for functions which:
62✔
544
 *   1. are not already in the top block in parent function / program
62✔
545
 *   2. are not async or generator functions
36✔
546
 *
36✔
547
 * @param {Object} declaration - Declaration object
36✔
548
 * @param {string} declaration.varName - Function name
36✔
549
 * @param {Object} declaration.binding - Binding object for binding in block where originally declared
36✔
550
 * @param {Object} declaration.block - Block object for block where originally declared
36!
551
 * @param {Object} declaration.hoistBlock - Block object for block where could be hoisted to
36✔
552
 * @param {Object} [declaration.parentFn] - Function object for parent function
36✔
553
 * @returns {undefined}
36✔
554
 */
36✔
555
function hoistSloppyFunctionDeclaration(declaration) {
32✔
556
        const {varName, hoistBlock} = declaration;
32✔
557

32✔
558
        // Do not hoist if existing const, let or class declaration binding in hoist block
32✔
559
        const hoistBlockBinding = hoistBlock.bindings[varName];
32!
560
        if (hoistBlockBinding && !hoistBlockBinding.isVar) return;
32!
561

32✔
562
        // If parent function's params include var with same name, do not hoist.
32✔
563
        // NB: `hoistBlock.parent` here is either parent function params block or file block.
32✔
564
        // In CommonJS code, file block is CommonJS wrapper function's params, and in any other context
32✔
565
        // file block contains no bindings except `this`. So it's safe to treat as a params block in all cases.
22✔
566
        // NB: `paramsBlockBinding.argNames` check is to avoid the pseudo-param `arguments` blocking hoisting.
×
567
        const paramsBlockBinding = hoistBlock.parent.bindings[varName];
22!
568
        if (paramsBlockBinding && !paramsBlockBinding.argNames) return;
22!
569

22✔
570
        // If any binding in intermediate blocks, do not hoist.
22✔
571
        // NB: This includes function declarations which will be themselves hoisted.
32✔
572
        let inBetweenBlock = declaration.block.parent;
32✔
573
        while (inBetweenBlock !== hoistBlock) {
32!
574
                if (inBetweenBlock.bindings[varName]) return;
4✔
575
                inBetweenBlock = inBetweenBlock.parent;
4✔
576
        }
4✔
577

4✔
578
        // Can be hoisted
4✔
579
        if (!hoistBlockBinding) {
4!
580
                hoistBlock.bindings[varName] = {...declaration.binding, isVar: true};
4✔
581
        } else if (!hoistBlockBinding.isFrozenName) {
4✔
582
                // Existing binding is a `var` declaration.
4✔
583
                // Flag binding as frozen so `var` declarations' identifiers don't get renamed.
4✔
584
                hoistBlockBinding.isFrozenName = true;
4✔
585
                hoistBlockBinding.trails.length = 0;
32✔
586
        }
32✔
587
}
32✔
588

62✔
589
/**
62✔
590
 * Instrument function.
62✔
591
 * @param {Object} node - Function or method AST node
62✔
592
 * @param {Object} fn - Function object
62✔
593
 * @param {Object|Array} parent - Parent AST node/container
62✔
594
 * @param {string|number} key - Node's key on parent AST node/container
62✔
595
 * @param {Object} paramsBlock - Function's params block object
62✔
596
 * @param {Object} [bodyBlock] - Function's body block object (if it has one, arrow functions may not)
62✔
597
 * @param {Object} state - State object
16✔
598
 * @returns {undefined}
16✔
599
 */
16✔
600
function instrumentFunction(node, fn, parent, key, paramsBlock, bodyBlock, state) {
27,818✔
601
        // Restore to original place in AST
27,818✔
602
        parent[key] = node;
×
603

×
604
        instrumentFunctionOrClassConstructor(node, fn, paramsBlock, bodyBlock, state);
27,818✔
605

27,818✔
606
        if (node.type === 'ArrowFunctionExpression') insertArrowFunctionTrackerComment(fn, node, state);
27,818!
607
}
27,818✔
608

×
609
/**
×
610
 * Instrument function, method or class constructor.
16✔
611
 *   - Insert `livepack_tracker()` call in function body.
16✔
612
 *   - Insert block vars (`livepack_scopeId`, `livepack_temp`) in function body or params.
16!
613
 *   - Create function info function containing function AST, details of internal and external vars etc.
62✔
614
 *
62✔
615
 * @param {Object} node - Function, method, or class constructor AST node
62✔
616
 * @param {Object} fn - Function object
62✔
617
 * @param {Object} paramsBlock - Function's params block object
62✔
618
 * @param {Object} bodyBlock - Function's body block object
62✔
619
 * @param {Object} state - State object
62✔
620
 * @returns {undefined}
62✔
621
 */
62✔
622
function instrumentFunctionOrClassConstructor(node, fn, paramsBlock, bodyBlock, state) {
28,904✔
623
        // NB `bodyBlock` here may actually be params block if is an arrow function with no body.
28,904✔
624
        // Sort scopes in ascending order of block ID.
28,904✔
625
        const scopes = [...fn.externalVars].map(([block, vars]) => ({block, vars}))
28,904✔
626
                .sort((scope1, scope2) => (scope1.block.id > scope2.block.id ? 1 : -1));
28,904✔
627
        fn.scopes = scopes;
28,904✔
628

28,904✔
629
        // Add external vars to parent function where external to that function too
28,904✔
630
        const parentFunction = fn.parent;
28,904✔
631
        if (parentFunction) {
28,904✔
632
                // External vars
17,442✔
633
                const {id: parentFunctionId, externalVars: parentExternalVars} = parentFunction;
17,442✔
634
                for (const {block, vars} of scopes) {
2✔
635
                        if (block.id >= parentFunctionId) break;
2✔
636
                        for (const [varName, {binding}] of Object.entries(vars)) {
2✔
637
                                getOrCreateExternalVar(parentExternalVars, block, varName, binding);
2✔
638
                        }
2✔
639
                }
2✔
640
        }
2✔
641

2✔
642
        // Insert tracker call and block vars (`livepack_scopeId` and `livepack_temp`) into function.
2!
643
        // If function has complex params, insert into params. Otherwise, into function body.
28,904✔
644
        const trackerNode = createTrackerCall(fn.id, scopes, state);
28,904✔
645

28,904✔
646
        const {firstComplexParamIndex} = fn;
28,904✔
647
        if (firstComplexParamIndex === undefined) {
28,904✔
648
                insertTrackerCodeIntoFunctionBody(node, paramsBlock, bodyBlock, trackerNode, state);
26,596✔
649
        } else {
28,904✔
650
                insertTrackerCodeIntoFunctionParams(
2,308✔
651
                        node, paramsBlock, bodyBlock, trackerNode, firstComplexParamIndex, state
2,308✔
652
                );
2,308✔
653
        }
2,308✔
654
}
28,904✔
655

62✔
656
/**
62✔
657
 * Create tracker call.
62✔
658
 * @param {number} fnId - Function ID
62✔
659
 * @param {Array<Object>} scopes - Array of scope objects in ascending order of block ID
62✔
660
 * @param {Object} state - State object
62✔
661
 * @returns {undefined}
62✔
662
 */
62✔
663
function createTrackerCall(fnId, scopes, state) {
28,904✔
664
        // `livepack_tracker(livepack_getFnInfo_3, () => [[livepack_scopeId_2, x]]);`
28,904✔
665
        return t.callExpression(state.trackerVarNode, [
×
666
                createFnInfoVarNode(fnId, state),
×
667
                t.arrowFunctionExpression([], t.arrayExpression(
×
668
                        scopes.map(scope => t.arrayExpression([
✔
669
                                scope.block.varsBlock.scopeIdVarNode,
23,348✔
670
                                ...Object.values(scope.vars).map(blockVar => blockVar.binding.varNode)
23,348✔
671
                        ]))
×
672
                ))
×
673
        ]);
×
674
}
×
675

×
676
/**
×
677
 * Insert tracker comment into function declaration/expression.
×
678
 * @param {Object} fn - Function object
×
679
 * @param {Object} node - Function declaration or expression AST node
×
680
 * @param {Object} state - State object
×
681
 * @returns {undefined}
×
682
 */
×
683
function insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state) {
7,368✔
684
        // Insert tracker comment before identifier, or before 1st param or before function body
7,368✔
685
        const commentHolderNode = node.id || (node.params.length !== 0 ? node.params[0] : node.body);
7,368✔
686
        insertTrackerComment(fn.id, getFunctionType(node), commentHolderNode, 'leading', state);
7,368✔
687
}
7,368✔
688

×
689
/**
×
690
 * Insert tracker comment into arrow function.
×
691
 * @param {Object} fn - Function object
×
692
 * @param {Object} node - Arrow function AST node
×
693
 * @param {Object} state - State object
×
694
 * @returns {undefined}
×
695
 */
×
696
function insertArrowFunctionTrackerComment(fn, node, state) {
11,242✔
697
        // Insert tracker comment before first param. If no params, before function body.
11,242✔
698
        const paramNodes = node.params;
11,242✔
699
        insertTrackerComment(
11,242✔
700
                fn.id, node.async ? FN_TYPE_ASYNC_FUNCTION : FN_TYPE_FUNCTION,
11,242✔
701
                paramNodes.length !== 0 ? paramNodes[0] : node.body, 'leading', state
11,242✔
702
        );
11,242✔
703
}
11,242✔
704

×
705
/**
×
706
 * Insert tracker comment.
×
707
 * @param {number} fnId - Function ID
×
708
 * @param {string} fnType - Function type
×
709
 * @param {Object} commentHolderNode - AST node to attach comment to
×
710
 * @param {string} commentType - 'leading' / 'inner' / 'trailing'
62✔
711
 * @param {Object} state - State object
62✔
712
 * @returns {undefined}
62✔
713
 */
62✔
714
function insertTrackerComment(fnId, fnType, commentHolderNode, commentType, state) {
28,904✔
715
        insertComment(
28,904✔
716
                commentHolderNode, commentType,
28,904✔
717
                `${TRACKER_COMMENT_PREFIX}${fnId};${fnType};${state.filenameEscaped}`
28,904✔
718
        );
28,904✔
719
}
28,904✔
720

62✔
721
/**
62✔
722
 * Create function info function containing function AST, details of internal and external vars etc.
62✔
723
 * @param {Object} fn - Function object
62✔
724
 * @param {Object} state - State object
62✔
725
 * @returns {Object} - AST node for function info function
62✔
726
 */
26✔
727
function createFunctionInfoFunction(fn, state) {
28,904✔
728
        // Compile internal vars and reserved var names
28,904✔
729
        const internalVars = Object.create(null),
28,904✔
730
                {reservedVarNames} = fn;
28,904✔
731
        for (const {name: varName, trails, isFrozenName} of fn.bindings) {
✔
UNCOV
732
                if (isFrozenName) {
✔
733
                        reservedVarNames.add(varName);
1,492✔
734
                } else {
45,114✔
735
                        const internalVar = internalVars[varName] || (internalVars[varName] = []);
43,622✔
736
                        internalVar.push(...trails);
43,622✔
737
                }
43,622✔
738
        }
45,114✔
739

28,904✔
740
        // Compile amendments.
28,904✔
741
        // Reverse order so deepest are first.
28,904✔
742
        // Remove the need for an internal var if binding has frozen name.
28,904✔
743
        let amendments;
28,904✔
744
        if (fn.amendments.length > 0) {
28,904✔
745
                amendments = fn.amendments.map(({type, blockId, trail, binding}) => {
1,518✔
746
                        if (type === CONST_VIOLATION_NEEDS_VAR && binding.isFrozenName) {
1,608!
747
                                type = CONST_VIOLATION_NEEDS_NO_VAR;
×
748
                        }
×
749
                        return [type, blockId, ...trail];
1,608✔
750
                }).reverse();
1,518✔
751
        }
1,518✔
752

28,904✔
753
        // Create JSON function info string
28,904✔
754
        const {children} = fn;
28,904✔
755
        let argNames;
28,904✔
756
        let json = JSON.stringify({
28,904✔
757
                scopes: fn.scopes.map(({block, vars}) => ({
28,904✔
758
                        blockId: block.id,
23,348✔
759
                        blockName: block.name,
23,348✔
760
                        vars: mapValues(vars, (varProps, varName) => {
23,348✔
761
                                if (varName === 'arguments') argNames = varProps.binding.argNames;
40,188✔
762
                                return {
36✔
763
                                        isReadFrom: varProps.isReadFrom || undefined,
36✔
764
                                        isAssignedTo: varProps.isAssignedTo || undefined,
36✔
765
                                        isFrozenName: varProps.isFrozenName || undefined,
36✔
766
                                        isFrozenInternalName: varProps.binding.isFrozenName || undefined,
36✔
767
                                        trails: varProps.trails
×
768
                                };
×
769
                        })
×
770
                })),
×
771
                isStrict: fn.isStrict || undefined,
36✔
772
                superIsProto: fn.superIsProto || undefined,
36✔
773
                containsEval: fn.containsEval || undefined,
36✔
774
                containsImport: fn.containsImport || undefined,
36✔
775
                argNames,
36✔
776
                internalVars,
36✔
777
                reservedVarNames: reservedVarNames.size !== 0 ? [...reservedVarNames] : undefined,
36✔
778
                globalVarNames: fn.globalVarNames.size !== 0 ? [...fn.globalVarNames] : undefined,
8✔
779
                amendments,
8✔
780
                hasSuperClass: fn.hasSuperClass || undefined,
8✔
781
                firstSuperStatementIndex: fn.firstSuperStatementIndex,
36✔
782
                returnsSuper: fn.returnsSuper || undefined,
✔
783
                childFns: children.map(childFn => childFn.trail)
✔
784
        });
×
785

×
786
        // Add AST JSON to JSON
×
UNCOV
787
        json = `${json.slice(0, -1)},"ast":${fn.astJson}}`;
×
UNCOV
788

×
789
        // Create function returning JSON string and references to function info function for child fns.
36✔
790
        // Make output as single-quoted string for shorter output (not escaping every `"`).
36!
791
        return t.functionDeclaration(createFnInfoVarNode(fn.id, state), [], t.blockStatement([
×
792
                t.returnStatement(t.arrayExpression([
×
793
                        stringLiteralWithSingleQuotes(json),
×
794
                        t.arrayExpression(children.map(childFn => createFnInfoVarNode(childFn.id, state))),
✔
795
                        state.getSourcesNode
×
796
                ]))
×
797
        ]));
×
798
}
×
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