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

overlookmotel / livepack / 6923877558

20 Nov 2023 12:21AM UTC coverage: 90.488% (+0.03%) from 90.46%
6923877558

push

github

overlookmotel
Rename var [refactor]

4694 of 5042 branches covered (0.0%)

Branch coverage included in aggregate %.

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

2 existing lines in 1 file now uncovered.

12610 of 14081 relevant lines covered (89.55%)

12871.67 hits per line

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

85.96
/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,314✔
74
        // Visit function
4,314✔
75
        const fnName = node.id.name;
4,314✔
76
        const fn = visitFunction(node, parent, key, fnName, true, true, state);
4,314✔
77

4,314✔
78
        // Create binding for function name
4,314✔
79
        // TODO: Whether the value of the function is hoisted depends on whether is a top level statement
4,314✔
80
        // (including in a labeled statement)
4,314✔
81
        // `() => { console.log(typeof x); function x() {} }` -> Logs 'function'
4,314✔
82
        // `() => { console.log(typeof x); q: function x() {} }` -> Logs 'function'
4,314✔
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
                // Flag binding as a function so `var` declarations' identifiers don't get renamed.
8✔
104
                binding.isFunction = true;
8✔
105
                binding.trails.length = 0;
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}
8!
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,610✔
171
        return withStrictModeState(
18,610✔
172
                node, hasBodyBlock, state,
18,610✔
173
                (isStrict, isEnteringStrict) => visitFunctionOrMethod(
18,610✔
174
                        node, parent, key, fnName, isStrict, isEnteringStrict, isFullFunction, hasBodyBlock, state
18,610✔
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,818✔
194
        fnNode, parent, key, fnName, isStrict, isEnteringStrict, isFullFunction, hasBodyBlock, state
27,818✔
195
) {
27,818✔
196
        // Create params block. If is full function, create bindings for `this` + `new.target`.
27,818✔
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,818✔
225
        // Param called `arguments` takes precedence.
27,818✔
226
        if (isFullFunction) {
27,818✔
227
                if (!paramsBlock.bindings.arguments) createArgumentsBinding(paramsBlock, isStrict, argNames);
16,576✔
228
                state.currentThisBlock = parentThisBlock;
16,576✔
229
        }
16,576✔
230

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

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

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

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

27,818✔
245
        return fn;
27,818✔
246
}
27,818✔
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,278✔
263
        // Visit params and find first complex param (i.e. param which is not just an identifier).
28,278✔
264
        // Do not consider `...x` to be complex.
28,278✔
265
        // Also get array of params which are linked to `arguments`.
28,278✔
266
        // i.e. `((x) => { arguments[0] = 2; return x; })(1) === 2`
28,278✔
267
        // `arguments` is only linked in sloppy mode functions with no complex params.
28,278✔
268
        const argNames = [];
28,278✔
269
        let hasLinkedArguments = !isStrict,
28,278✔
270
                firstComplexParamIndex;
28,278✔
271
        visitKeyContainer(fnNode, 'params', (paramNode, _state, paramNodes, index) => {
28,278✔
272
                if (paramNode.type === 'Identifier') {
22,520✔
273
                        if (hasLinkedArguments) argNames.push(paramNode.name);
19,838✔
274
                        IdentifierLet(paramNode, state, paramNodes, index);
19,838✔
275
                } else {
22,520✔
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,278✔
290

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

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

28,278✔
305
        // Return array of params which are linked to `arguments`
28,278✔
306
        return argNames;
28,278✔
307
}
28,278✔
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,912✔
316
        visitKeyContainer(node, 'body', Statement, state);
20,912✔
317
}
20,912✔
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,818✔
332
        // Remove unnecessary 'use strict' directives
27,818✔
333
        if (hasBodyBlock && isStrict) {
27,818✔
334
                const alteredFnNode = removeUnnecessaryUseStrictDirectives(fnNode, !isEnteringStrict);
16,884✔
335
                if (alteredFnNode) fnNode = alteredFnNode;
16,884✔
336
        }
16,884✔
337

27,818✔
338
        // Stringify AST to JSON
27,818✔
339
        return JSON.stringify(fnNode);
27,818✔
340
}
27,818✔
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,344✔
352
        // If no directives, return `undefined`
17,344!
353
        let bodyNode = fnNode.body;
17,344✔
354
        const directiveNodes = bodyNode.directives;
17,344✔
355
        if (directiveNodes.length === 0) return undefined;
17,344✔
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,344✔
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,904✔
425
        const parentFunction = state.currentFunction;
28,904✔
426
        const fn = {
28,904✔
427
                id,
28,904✔
428
                node,
28,904✔
429
                astJson: undefined,
28,904✔
430
                isStrict,
28,904✔
431
                parent: parentFunction,
×
432
                children: [],
×
433
                trail: parentFunction ? [...state.trail] : undefined,
28,904✔
434
                bindings: [],
28,904✔
435
                externalVars: new Map(), // Keyed by block
28,904✔
436
                scopes: undefined,
28,904✔
437
                globalVarNames: new Set(),
28,904✔
438
                amendments: [],
28,904✔
439
                superIsProto: false,
28,904✔
440
                containsEval: false,
28,904!
441
                containsImport: false,
28,904✔
442
                hasSuperClass: false,
28,904✔
443
                firstSuperStatementIndex: undefined,
28,904✔
444
                returnsSuper: false,
28,904✔
445
                hasThisBindingForSuper: false,
28,904✔
446
                firstComplexParamIndex: undefined
28,904✔
447
        };
28,904✔
448

28,904✔
449
        if (parentFunction) parentFunction.children.push(fn);
28,904✔
450

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

28,904✔
454
        return fn;
28,904✔
455
}
28,904✔
456

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

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

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

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

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

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

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

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

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

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

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

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

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

×
601
        instrumentFunctionOrClassConstructor(node, fn, paramsBlock, bodyBlock, state);
27,818✔
602

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

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

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

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

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

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

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

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

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

62✔
718
/**
62✔
719
 * Create function info function containing function AST, details of internal and external vars etc.
62✔
720
 * @param {Object} fn - Function object
62✔
721
 * @param {Object} state - State object
62✔
722
 * @returns {Object} - AST node for function info function
26✔
723
 */
26✔
724
function createFunctionInfoFunction(fn, state) {
28,904✔
725
        // Compile internal vars
28,904✔
726
        const internalVars = Object.create(null);
28,904✔
727
        for (const {name: varName, trails, isFunction} of fn.bindings) {
28,904✔
728
                // Function name bindings are not usually added to `fn.bindings`,
×
729
                // but can be included if binding is initially a `var` statement e.g. `var x; function x() {}`.
46,240✔
730
                // So skip them here.
46,240✔
731
                if (isFunction) continue;
46,240✔
732
                const internalVar = internalVars[varName] || (internalVars[varName] = []);
46,240✔
733
                internalVar.push(...trails);
46,240✔
734
        }
46,240✔
735

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

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

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

© 2026 Coveralls, Inc