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

overlookmotel / livepack / 6914905275

18 Nov 2023 03:56PM UTC coverage: 90.492% (+0.006%) from 90.486%
6914905275

push

github

overlookmotel
Rename var [refactor]

4698 of 5048 branches covered (0.0%)

Branch coverage included in aggregate %.

5 of 5 new or added lines in 2 files covered. (100.0%)

1 existing line in 1 file now uncovered.

12615 of 14084 relevant lines covered (89.57%)

12890.29 hits per line

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

85.39
/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
        } = require('../../shared/constants.js');
62✔
48

62✔
49
// Exports
62✔
50

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

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

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

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

8✔
108
        // Insert tracker comment
8✔
109
        insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state);
8✔
110
}
8✔
111

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

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

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

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

3,054✔
142
        // Insert tracker comment
3,054✔
143
        insertFunctionDeclarationOrExpressionTrackerComment(fn, node, state);
3,054✔
144
}
2✔
145

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

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

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

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

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

×
221
        // Visit params + body
×
222
        const argNames = visitFunctionParamsAndBody(fn, fnNode, paramsBlock, bodyBlock, isStrict, state);
14✔
223

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

27,820✔
231
        // Serialize AST
27,820✔
232
        fn.astJson = serializeFunctionAst(fnNode, hasBodyBlock, isStrict, isEnteringStrict);
27,820✔
233

27,820✔
234
        // Exit function
27,820✔
235
        state.currentBlock = paramsBlock.parent;
27,820✔
236
        state.currentFunction = fn.parent;
27,820✔
237
        state.trail = parentTrail;
27,820✔
238

27,820✔
239
        // Temporarily remove from AST so is not included in parent function's serialized AST
27,820✔
240
        parent[key] = null;
27,820✔
241

27,820✔
242
        // Queue instrumentation of function in 2nd pass
27,820✔
243
        state.secondPass(instrumentFunction, fnNode, fn, parent, key, paramsBlock, bodyBlock, state);
27,820✔
244

27,820✔
245
        return fn;
27,820✔
246
}
27,820✔
247

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

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

2,682✔
287
                        AssigneeLet(paramNode, state, paramNodes, index);
2,682✔
288
                }
2,682✔
289
        }, state);
28,280✔
290

28,280✔
291
        // Record index of first complex param
28,280✔
292
        fn.firstComplexParamIndex = firstComplexParamIndex;
28,280✔
293

28,280✔
294
        // Visit body
28,280✔
295
        if (bodyBlock) {
28,280✔
296
                state.currentBlock = bodyBlock;
20,914✔
297
                const parentHoistBlock = state.currentHoistBlock;
20,914✔
298
                state.currentHoistBlock = bodyBlock;
20,914✔
299
                visitKey(fnNode, 'body', FunctionBodyBlock, state);
20,914✔
300
                state.currentHoistBlock = parentHoistBlock;
20,914✔
301
        } else {
28,280✔
302
                visitKey(fnNode, 'body', Expression, state);
7,366✔
303
        }
7,366✔
304

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

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

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

27,820✔
338
        // Stringify AST to JSON
27,820✔
339
        return JSON.stringify(fnNode);
27,820✔
340
}
27,820✔
341

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

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

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

364✔
381
                newDirectiveNodes.push(directiveNode);
364✔
382
        }
364✔
383

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

22✔
387
        // Clone function node
22✔
388
        bodyNode = {...bodyNode, directives: newDirectiveNodes};
22✔
389
        fnNode = {...fnNode, body: bodyNode};
22✔
390

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

22✔
412
        // Return clone of function node
22✔
413
        return fnNode;
22✔
414
}
17,346✔
415

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

28,906✔
448
        if (parentFunction) parentFunction.children.push(fn);
28,906✔
449

28,906✔
450
        state.functions.push(fn);
28,906✔
451
        state.fileContainsFunctionsOrEval = true;
28,906✔
452

28,906✔
453
        return fn;
28,906✔
454
}
28,906✔
455

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

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

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

23,520✔
500
        // Call visitor
23,520✔
501
        const res = visit(isStrict, isEnteringStrict);
23,520✔
502

23,520✔
503
        // If entered strict mode, exit it again
23,520✔
504
        if (isEnteringStrict) state.isStrict = false;
23,520✔
505

23,520✔
506
        // Return visitor's return value
23,520✔
507
        return res;
23,520✔
508
}
23,520✔
509

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

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

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

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

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

4✔
574
        // Can be hoisted
4✔
575
        if (!hoistBlockBinding) {
4!
576
                hoistBlock.bindings[varName] = {...declaration.binding, isVar: true};
4✔
577
        } else if (!hoistBlockBinding.isFunction) {
4✔
578
                // Existing binding is a `var` declaration.
4✔
579
                // Remove from parent function's `internalVars` so `var` declarations' identifiers don't get renamed.
4✔
580
                hoistBlockBinding.isFunction = true;
4✔
581
                declaration.parentFn?.internalVars.delete(hoistBlockBinding);
32✔
582
        }
32✔
583
}
32✔
584

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

27,820✔
600
        instrumentFunctionOrClassConstructor(node, fn, paramsBlock, bodyBlock, state);
27,820✔
601

27,820✔
602
        if (node.type === 'ArrowFunctionExpression') insertArrowFunctionTrackerComment(fn, node, state);
27,820!
603
}
27,820✔
604

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

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

2✔
638
        // Insert tracker call and block vars (`livepack_scopeId` and `livepack_temp`) into function.
28,906!
639
        // If function has complex params, insert into params. Otherwise, into function body.
28,906✔
640
        const trackerNode = createTrackerCall(fn.id, scopes, state);
28,906✔
641

28,906✔
642
        const {firstComplexParamIndex} = fn;
28,906✔
643
        if (firstComplexParamIndex === undefined) {
28,906✔
644
                insertTrackerCodeIntoFunctionBody(node, paramsBlock, bodyBlock, trackerNode, state);
26,598✔
645
        } else {
28,906✔
646
                insertTrackerCodeIntoFunctionParams(
2,308✔
647
                        node, paramsBlock, bodyBlock, trackerNode, firstComplexParamIndex, state
2,308✔
648
                );
2,308✔
649
        }
2,308✔
650
}
28,906✔
651

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

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

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

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

62✔
717
/**
62✔
718
 * Create function info function containing function AST, details of internal and external vars etc.
62✔
719
 * @param {Object} fn - Function object
62✔
720
 * @param {Object} state - State object
62✔
721
 * @returns {Object} - AST node for function info function
26✔
722
 */
26✔
723
function createFunctionInfoFunction(fn, state) {
28,906✔
724
        // Compile internal vars
28,906✔
725
        const internalVars = Object.create(null);
28,906✔
726
        for (const {varName, trails} of fn.internalVars.values()) {
28,906✔
727
                const internalVar = internalVars[varName] || (internalVars[varName] = []);
45,100✔
728
                internalVar.push(...trails);
45,100✔
729
        }
45,100✔
730

28,906✔
731
        // Create JSON function info string
28,906✔
732
        const {children} = fn;
28,906✔
733
        let argNames;
28,906✔
734
        let json = JSON.stringify({
28,906✔
735
                scopes: fn.scopes.map(({block, vars}) => ({
28,906✔
736
                        blockId: block.id,
23,348✔
737
                        blockName: block.name,
23,348✔
738
                        vars: mapValues(vars, (varProps, varName) => {
23,348✔
739
                                if (varName === 'arguments') argNames = varProps.binding.argNames;
40,190✔
740
                                return {
40,190✔
741
                                        isReadFrom: varProps.isReadFrom || undefined,
40,190✔
742
                                        isAssignedTo: varProps.isAssignedTo || undefined,
40,190✔
743
                                        isFrozenInternalName: varProps.binding.isFunction || undefined,
40,190✔
744
                                        trails: varProps.trails
40,190✔
745
                                };
40,190✔
746
                        })
23,348✔
747
                })),
28,906✔
748
                isStrict: fn.isStrict || undefined,
28,906✔
749
                superIsProto: fn.superIsProto || undefined,
28,906✔
750
                containsEval: fn.containsEval || undefined,
28,906✔
751
                containsImport: fn.containsImport || undefined,
28,906✔
752
                argNames,
28,906✔
753
                internalVars,
28,906✔
754
                globalVarNames: fn.globalVarNames.size !== 0 ? [...fn.globalVarNames] : undefined,
28,906✔
755
                amendments: fn.amendments.length !== 0
36✔
756
                        ? fn.amendments.map(({type, blockId, trail}) => [type, blockId, ...trail]).reverse()
36✔
757
                        : undefined,
36✔
758
                hasSuperClass: fn.hasSuperClass || undefined,
36✔
759
                firstSuperStatementIndex: fn.firstSuperStatementIndex,
36✔
760
                returnsSuper: fn.returnsSuper || undefined,
✔
761
                childFns: children.map(childFn => childFn.trail)
✔
762
        });
36✔
763

36✔
764
        // Add AST JSON to JSON
36✔
765
        json = `${json.slice(0, -1)},"ast":${fn.astJson}}`;
36✔
766

36✔
767
        // Create function returning JSON string and references to function info function for child fns.
36✔
768
        // Make output as single-quoted string for shorter output (not escaping every `"`).
36✔
769
        return t.functionDeclaration(createFnInfoVarNode(fn.id, state), [], t.blockStatement([
8✔
770
                t.returnStatement(t.arrayExpression([
8✔
771
                        stringLiteralWithSingleQuotes(json),
36✔
UNCOV
772
                        t.arrayExpression(children.map(childFn => createFnInfoVarNode(childFn.id, state))),
✔
773
                        state.getSourcesNode
×
774
                ]))
×
775
        ]));
×
776
}
×
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