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

overlookmotel / livepack / 6864299412

14 Nov 2023 01:27PM UTC coverage: 90.441% (-0.09%) from 90.526%
6864299412

push

github

overlookmotel
Avoid string concatenation in passing assertions [perf]

4644 of 4995 branches covered (0.0%)

Branch coverage included in aggregate %.

19 of 23 new or added lines in 5 files covered. (82.61%)

16 existing lines in 4 files now uncovered.

12585 of 14055 relevant lines covered (89.54%)

12924.85 hits per line

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

95.78
/lib/serialize/parseFunction.js
1
/* --------------------
62✔
2
 * livepack module
62✔
3
 * Parse function code
62✔
4
 * ------------------*/
62✔
5

62✔
6
'use strict';
62✔
7

62✔
8
// Modules
62✔
9
const pathJoin = require('path').join,
62✔
10
        {isString} = require('is-it-type'),
62✔
11
        mapValues = require('lodash/mapValues'),
62✔
12
        t = require('@babel/types');
62✔
13

62✔
14
// Imports
62✔
15
const {isJsIdentifier, isNumberKey, setAddFrom} = require('./utils.js'),
62✔
16
        {
62✔
17
                isReservedVarName, createArrayOrPush, combineArraysWithDedup,
62✔
18
                getProp, getProps, setProp, traverseAll
62✔
19
        } = require('../shared/functions.js'),
62✔
20
        {
62✔
21
                SUPER_CALL, SUPER_EXPRESSION, CONST_VIOLATION_CONST, CONST_VIOLATION_FUNCTION_SILENT
62✔
22
        } = require('../shared/constants.js'),
62✔
23
        assertBug = require('../shared/assertBug.js');
62✔
24

62✔
25
// Constants
62✔
26
const RUNTIME_DIR_PATH = pathJoin(__dirname, '../runtime/');
62✔
27

62✔
28
// Exports
62✔
29

62✔
30
/**
62✔
31
 * Assemble AST for function code, identify Identifier nodes referring to internal/external variables,
62✔
32
 * replace const violations, transpile `super`, get other info about function.
62✔
33
 * Most of this information is pre-prepared by instrumentation, just needs some late processing here.
62✔
34
 *
62✔
35
 * @this {Object} Serializer
62✔
36
 * @param {Function} fn - Function
62✔
37
 * @param {number} fnId - Function ID
62✔
38
 * @param {Function} getFunctionInfo - Function info getter function
62✔
39
 * @param {boolean} isClass - `true` if is a class
62✔
40
 * @param {boolean} isAsync - `true` if is an async function
62✔
41
 * @param {boolean} isGenerator - `true` if is a generator function
62✔
42
 * @param {string} filename - File path
62✔
43
 * @returns {Object} - Function definition object with props:
62✔
44
 *   {Object} .node - AST node for function
62✔
45
 *   {Map} .scopeDefs - Scope definitions map, keyed by block ID
62✔
46
 *   {Object} .externalVars - Object keyed by var name, values are arrays of identifier nodes
62✔
47
 *   {Object} .internalVars - Object keyed by var name, values are arrays of identifier nodes
62✔
48
 *   {Set<string>} .globalVarNames - Set of names of global vars used
62✔
49
 *   {Set<string>} .functionNames - Set of function names used
62✔
50
 *   {string} .name - `.name` of created function
62✔
51
 *   {number} .numParams - `.length` of created function
62✔
52
 *   {boolean} .isClass - `true` if is class
62✔
53
 *   {boolean} .isAsync - `true` if is async function
62✔
54
 *   {boolean} .isGenerator - `true` if is generator
62✔
55
 *   {boolean} .isArrow - `true` if is arrow function
62✔
56
 *   {boolean} .isMethod - `true` if is a method
62✔
57
 *   {boolean|null} .isStrict - `true` if is strict mode, `false` if sloppy, `null` if indeterminate
62✔
58
 *     (classes and runtime functions are indeterminate)
62✔
59
 *   {boolean} .containsEval - `true` if contains direct `eval()`
62✔
60
 *   {Array<string>|undefined} .argNames - Array of `arguments` var names
62✔
61
 * @throws {Error} - If function contains `import`
62✔
62
 */
62✔
63
module.exports = function parseFunction(
62✔
64
        fn, fnId, getFunctionInfo, isClass, isAsync, isGenerator, filename
29,424✔
65
) {
29,424✔
66
        // Get function info and AST from info getter function
29,424✔
67
        const [fnInfoJson, getChildFnInfos, getSources] = getFunctionInfo();
29,424✔
68
        const fnInfo = JSON.parse(fnInfoJson);
29,424✔
69

29,424✔
70
        // Throw error if function contains `import()`
29,424✔
71
        if (fnInfo.containsImport) {
29,424!
72
                const fnName = Object.getOwnPropertyDescriptor(fn, 'name')?.value,
×
73
                        fnDesc = (isString(fnName) && fnName !== '') ? `function '${fnName}'` : 'anonymous function';
×
74
                throw new Error(`Cannot serialize function containing \`import\` (${fnDesc} in '${filename}')`);
×
75
        }
×
76

29,424✔
77
        // Assemble scope definitions
29,424✔
78
        const scopeDefs = new Map(),
29,424✔
79
                externalVars = Object.create(null);
29,424✔
80
        for (const {blockId, blockName, vars} of fnInfo.scopes) {
29,424✔
81
                scopeDefs.set(blockId, {
17,684✔
82
                        blockName,
17,684✔
83
                        vars: mapValues(vars, (varProps, varName) => {
17,684✔
84
                                externalVars[varName] = [];
23,732✔
85
                                return {isReadFrom: !!varProps.isReadFrom, isAssignedTo: !!varProps.isAssignedTo};
23,732✔
86
                        })
17,684✔
87
                });
17,684✔
88
        }
17,684✔
89

29,424✔
90
        // Add child functions into AST, get external/internal var nodes, and get amendments to be made
29,424✔
91
        // (const violations / incidences of `super` to be transpiled)
29,424✔
92
        const internalVars = Object.create(null),
29,424✔
93
                globalVarNames = new Set(),
29,424✔
94
                functionNames = new Set(),
29,424✔
95
                amendments = [];
29,424✔
96
        resolveFunctionInfo(
29,424✔
97
                fnInfo, getChildFnInfos, false, fnId, scopeDefs,
29,424✔
98
                externalVars, internalVars, globalVarNames, functionNames, amendments
29,424✔
99
        );
29,424✔
100

29,424✔
101
        let node = fnInfo.ast;
29,424✔
102

29,424✔
103
        // If source maps enabled, add source files to `sourceFiles` map and set `loc.filename` for all nodes.
29,424✔
104
        // Create `copyLoc()` function to copy location info for AST nodes befing replaced.
29,424✔
105
        let copyLoc;
29,424✔
106
        if (this.options.sourceMaps) {
29,424✔
107
                const {filesHaveSourcesFor} = this;
29,340✔
108
                if (!filesHaveSourcesFor.has(filename)) {
29,340✔
109
                        Object.assign(this.sourceFiles, JSON.parse(getSources()));
18,742✔
110
                        filesHaveSourcesFor.add(filename);
18,742✔
111
                }
18,742✔
112

29,340✔
113
                traverseAll(node, ({loc}) => {
29,340✔
114
                        if (loc && !loc.filename) loc.filename = filename;
211,424✔
115
                });
29,340✔
116

29,340✔
117
                copyLoc = (destNode, srcNode) => {
29,340✔
118
                        destNode.start = srcNode.start;
8,416✔
119
                        destNode.end = srcNode.end;
8,416✔
120
                        destNode.loc = srcNode.loc;
8,416✔
121
                        return destNode;
8,416✔
122
                };
29,340✔
123
        } else {
29,424✔
124
                copyLoc = destNode => destNode;
84✔
125
        }
84✔
126

29,424✔
127
        // Get whether strict mode and remove use strict directive
29,424✔
128
        let isStrict;
29,424✔
129
        if (!isClass) {
29,424✔
130
                isStrict = !!fnInfo.isStrict;
25,584✔
131
                if (isStrict) {
25,584✔
132
                        removeUseStrictDirective(node);
20,330✔
133
                } else if (filename.startsWith(RUNTIME_DIR_PATH)) {
25,584✔
134
                        // Runtime functions are treated as indeterminate strict/sloppy mode unless explicitly strict
976✔
135
                        isStrict = null;
976✔
136
                }
976✔
137
        }
25,584✔
138

29,424✔
139
        // Create `super` var node if required
29,424✔
140
        let superVarNode;
29,424✔
141
        if (externalVars.super) {
29,424✔
142
                superVarNode = t.identifier('super');
2,624✔
143
                externalVars.super[0] = superVarNode;
2,624✔
144
                globalVarNames.add('Reflect');
2,624✔
145
                globalVarNames.add('Object');
2,624✔
146
        }
2,624✔
147

29,424✔
148
        // Conform function/class, get function name
29,424✔
149
        let isMethod, name, thisVarNode, constructorStatementNodes, firstSuperStatementIndex,
29,424✔
150
                paramNodes = node.params;
29,424✔
151
        const {type} = node,
29,424✔
152
                isArrow = type === 'ArrowFunctionExpression',
29,424✔
153
                containsEval = !!fnInfo.containsEval;
29,424✔
154
        if (isArrow) {
29,424✔
155
                // Arrow function
11,480✔
156
                name = '';
11,480✔
157
                isMethod = false;
11,480✔
158

11,480✔
159
                // If contains `super`, needs `this` too
11,480✔
160
                if (externalVars.super) {
11,480✔
161
                        thisVarNode = t.identifier('this');
256✔
162
                        externalVars.this.push(thisVarNode);
256✔
163
                }
256✔
164
        } else {
29,424✔
165
                // Class, method or function declaration/expression.
17,944✔
166
                // Get function name.
17,944✔
167
                name = (Object.getOwnPropertyDescriptor(fn, 'name') || {}).value;
17,944✔
168
                if (!isString(name)) name = '';
17,944✔
169

17,944✔
170
                // Identify if method and convert class method to object method
17,944✔
171
                if (type === 'ClassMethod') {
17,944✔
172
                        node.type = 'ObjectMethod';
2,160✔
173
                        node.static = undefined;
2,160✔
174
                        isMethod = true;
2,160✔
175
                } else if (type === 'ObjectMethod') {
17,944✔
176
                        isMethod = true;
2,000✔
177
                }
2,000✔
178

17,944✔
179
                if (isMethod) {
17,944✔
180
                        // Class/object method.
4,160✔
181
                        // Convert getter/setter to plain method, and disable computed keys.
4,160✔
182
                        node.kind = 'method';
4,160✔
183
                        node.computed = false;
4,160✔
184

4,160✔
185
                        // Wrap in object.
4,160✔
186
                        // NB: Must be defined as method, to avoid it having prototype.
4,160✔
187
                        let keyNode, accessComputed;
4,160✔
188
                        if (!name) {
4,160!
189
                                name = 'a';
×
190
                                keyNode = t.identifier('a');
×
191
                                accessComputed = false;
×
192
                        } else if (isJsIdentifier(name)) {
4,160✔
193
                                keyNode = t.identifier(name);
3,168✔
194
                                accessComputed = false;
3,168✔
195
                        } else {
4,160✔
196
                                keyNode = isNumberKey(name) ? t.numericLiteral(name * 1) : t.stringLiteral(name);
992✔
197
                                accessComputed = true;
992✔
198
                        }
992✔
199

4,160✔
200
                        node.key = copyLoc(keyNode, node.key || {});
4,160!
201
                        node = t.memberExpression(t.objectExpression([node]), keyNode, accessComputed);
4,160✔
202

4,160✔
203
                        // `this` within method is actual `this`
4,160✔
204
                        thisVarNode = t.thisExpression();
4,160✔
205
                } else {
17,944✔
206
                        // Set function name
13,784✔
207
                        const idNode = node.id;
13,784✔
208
                        if (containsEval) {
13,784✔
209
                                // Function contains `eval()`.
928✔
210
                                // Cannot change name from original as would create a new var in scope of `eval()`.
928✔
211
                                // If is a named function expression, name must be retained, to maintain const violation
928✔
212
                                // error behavior (error in strict mode, silent failure in sloppy mode).
928✔
213
                                // If is a named function declaration, name must be removed to allow read/write access
928✔
214
                                // to external var holding function in upper scope.
928✔
215
                                if (idNode) {
928✔
216
                                        name = idNode.name;
160✔
217
                                        if (externalVars[name]) name = '';
160✔
218
                                } else {
928✔
219
                                        name = '';
768✔
220
                                }
768✔
221
                        } else if (
13,784✔
222
                                name && (!isJsIdentifier(name) || isReservedVarName(name) || globalVarNames.has(name))
12,856✔
223
                        ) {
12,856✔
224
                                // Name cannot be used as is illegal, or would block access to a global var
212✔
225
                                name = '';
212✔
226
                        }
212✔
227

13,784✔
228
                        if (!name) {
13,784✔
229
                                node.id = null;
6,168✔
230
                        } else {
13,784✔
231
                                if (!idNode || idNode.name !== name) {
7,616✔
232
                                        node.id = t.identifier(name);
852✔
233
                                        if (idNode) copyLoc(node.id, idNode);
852✔
234
                                }
852✔
235
                                functionNames.add(name);
7,616✔
236
                        }
7,616✔
237

13,784✔
238
                        if (isClass) {
13,784✔
239
                                // Class
3,840✔
240
                                if (type === 'ClassDeclaration') node.type = 'ClassExpression';
3,840✔
241

3,840✔
242
                                // Classes have indeterminate strict/sloppy status - never require conforming to strict/sloppy
3,840✔
243
                                // as they're automatically strict.
3,840✔
244
                                isStrict = null;
3,840✔
245

3,840✔
246
                                // Remove all members except constructor and prototype properties
3,840✔
247
                                let constructorNode;
3,840✔
248
                                const classBodyNode = node.body;
3,840✔
249
                                const memberNodes = classBodyNode.body = classBodyNode.body.filter((memberNode) => {
3,840✔
250
                                        if (!memberNode) return false;
3,600✔
251
                                        const memberType = memberNode.type;
1,472✔
252
                                        if (memberType === 'ClassMethod') {
1,472✔
253
                                                constructorNode = memberNode;
1,472✔
254
                                                return true;
1,472✔
255
                                        }
1,472✔
256
                                        if (memberType === 'StaticBlock') return false;
×
257
                                        return !memberNode.static;
×
258
                                });
3,840✔
259
                                paramNodes = constructorNode ? constructorNode.params : [];
3,840✔
260

3,840✔
261
                                if (fnInfo.hasSuperClass) {
3,840✔
262
                                        // Remove `extends`
1,344✔
263
                                        node.superClass = null;
1,344✔
264

1,344✔
265
                                        // Add constructor if none present
1,344✔
266
                                        if (!constructorNode) {
1,344✔
267
                                                // `constructor(...args) {
992✔
268
                                                //   return Reflect.construct(Object.getPrototypeOf(super$0), args, super$0);
992✔
269
                                                // }`
992✔
270
                                                const argsVarNode = t.identifier('args');
992✔
271
                                                internalVars.args = [argsVarNode];
992✔
272
                                                // TODO: Can using `.unshift()` interfere with replacing const violations further on?
992✔
273
                                                // Indexes of any class properties will be altered.
992✔
274
                                                memberNodes.unshift(t.classMethod(
992✔
275
                                                        'constructor',
992✔
276
                                                        t.identifier('constructor'),
992✔
277
                                                        [t.restElement(argsVarNode)],
992✔
278
                                                        t.blockStatement([
992✔
279
                                                                t.returnStatement(
992✔
280
                                                                        t.callExpression(
992✔
281
                                                                                t.memberExpression(t.identifier('Reflect'), t.identifier('construct')),
992✔
282
                                                                                [
992✔
283
                                                                                        t.callExpression(
992✔
284
                                                                                                t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
992✔
285
                                                                                                [superVarNode]
992✔
286
                                                                                        ),
992✔
287
                                                                                        argsVarNode,
992✔
288
                                                                                        superVarNode
992✔
289
                                                                                ]
992✔
290
                                                                        )
992✔
291
                                                                )
992✔
292
                                                        ])
992✔
293
                                                ));
992✔
294
                                        } else {
1,344✔
295
                                                // Class has constructor - prepare for transpiling `super()`
352✔
296
                                                const thisInternalVars = internalVars.this;
352✔
297
                                                if (thisInternalVars) {
352✔
298
                                                        // Constructor contains `this` or `super` expression (e.g. `super.foo()`).
256✔
299
                                                        // Var for `this$0` is going to be needed.
256✔
300
                                                        thisVarNode = t.identifier('this');
256✔
301
                                                        thisInternalVars.push(thisVarNode);
256✔
302
                                                }
256✔
303

352✔
304
                                                firstSuperStatementIndex = fnInfo.firstSuperStatementIndex;
352✔
305
                                                constructorStatementNodes = constructorNode.body.body;
352✔
306
                                        }
352✔
307
                                } else {
3,840✔
308
                                        // Class which doesn't extend a super class. `this` within constructor is actual `this`.
2,496✔
309
                                        thisVarNode = t.thisExpression();
2,496✔
310
                                }
2,496✔
311
                        } else {
13,784✔
312
                                // Function declaration/expression. `this` is actual `this`.
9,944✔
313
                                if (type === 'FunctionDeclaration') node.type = 'FunctionExpression';
9,944✔
314
                                thisVarNode = t.thisExpression();
9,944✔
315
                        }
9,944✔
316
                }
13,784✔
317
        }
17,944✔
318

29,424✔
319
        // Replace const violations + `super`.
29,424✔
320
        // Amendments are in reverse order:
29,424✔
321
        // - Nested functions before their parent.
29,424✔
322
        // - Within a function, deeper nested expressions/statements before their parent.
29,424✔
323
        // - Within a function, later statements before earlier statements.
29,424✔
324
        // Reverse order ensures correct handling of nested amendments
29,424✔
325
        // e.g. 2 const violations `c = c2 = 1` or const violation + super `super.foo(c = 1)`.
29,424✔
326
        const superIsProto = isClass || fnInfo.superIsProto || false;
29,424✔
327
        for (const amendment of amendments) {
29,424✔
328
                const {type: amendmentType, trail, trailNodes} = amendment;
2,464✔
329
                if (amendmentType === SUPER_CALL) {
2,464✔
330
                        replaceSuperCall(
416✔
331
                                trail, trailNodes, superVarNode, thisVarNode, firstSuperStatementIndex, copyLoc
416✔
332
                        );
416✔
333
                } else if (amendmentType === SUPER_EXPRESSION) {
2,464✔
334
                        replaceSuperExpression(
1,296✔
335
                                trail, trailNodes, superVarNode, thisVarNode, superIsProto, internalVars, copyLoc
1,296✔
336
                        );
1,296✔
337
                } else if (amendmentType === CONST_VIOLATION_FUNCTION_SILENT) {
2,048✔
338
                        replaceConstViolation(trail, trailNodes, true, internalVars, copyLoc);
16✔
339
                } else {
752✔
340
                        // amendmentType === CONST_VIOLATION_CONST || amendmentType === CONST_VIOLATION_FUNCTION_THROWING
736✔
341
                        replaceConstViolation(trail, trailNodes, false, internalVars, copyLoc);
736✔
342
                }
736✔
343
        }
2,464✔
344

29,424✔
345
        // If is class extending a super class, insert `let this$0;` and `return this$0;` statements
29,424✔
346
        // if required
29,424✔
347
        if (constructorStatementNodes && thisVarNode) {
29,424✔
348
                // Add `let this$0` at start of constructor
256✔
349
                if (firstSuperStatementIndex === undefined) {
256✔
350
                        constructorStatementNodes.unshift(
48✔
351
                                t.variableDeclaration('let', [t.variableDeclarator(thisVarNode, null)])
48✔
352
                        );
48✔
353
                }
48✔
354

256✔
355
                // Add `return this$0` to end of constructor
256✔
356
                if (!fnInfo.returnsSuper) constructorStatementNodes.push(t.returnStatement(thisVarNode));
256✔
357
        }
256✔
358

29,424✔
359
        // Determine what value of `fn.length` will be
29,424✔
360
        let numParams = 0;
29,424✔
361
        for (const {type: paramNodeType} of paramNodes) {
29,424✔
362
                if (paramNodeType === 'RestElement' || paramNodeType === 'AssignmentPattern') break;
5,550✔
363
                numParams++;
4,990✔
364
        }
4,990✔
365

29,424✔
366
        // Return function definition object
29,424✔
367
        return {
29,424✔
368
                node,
29,424✔
369
                scopeDefs,
29,424✔
370
                externalVars,
29,424✔
371
                internalVars,
29,424✔
372
                globalVarNames,
29,424✔
373
                functionNames,
29,424✔
374
                name,
29,424✔
375
                numParams,
29,424✔
376
                isClass,
29,424✔
377
                isAsync,
29,424✔
378
                isGenerator,
29,424✔
379
                isArrow,
29,424✔
380
                isMethod,
29,424✔
381
                isStrict,
29,424✔
382
                containsEval,
29,424✔
383
                argNames: fnInfo.argNames
29,424✔
384
        };
29,424✔
385
};
62✔
386

62✔
387
/**
62✔
388
 * Remove 'use strict' directive from function.
62✔
389
 * @param {Object} fnNode - Function AST node
62✔
390
 * @returns {undefined}
62✔
391
 */
62✔
392
function removeUseStrictDirective(fnNode) {
20,330✔
393
        const bodyNode = fnNode.body;
20,330✔
394
        if (bodyNode.type !== 'BlockStatement') return;
20,330✔
395
        const directiveNodes = bodyNode.directives;
14,312✔
396
        if (directiveNodes.length === 0) return;
18,844✔
397
        const index = directiveNodes.findIndex(directiveNode => directiveNode.value.value === 'use strict');
962✔
398
        if (index === -1) return;
1,728✔
399

802✔
400
        // Relocate any comments attached to directive
802✔
401
        const directiveNode = directiveNodes[index];
802✔
402
        const commentNodes = [
802✔
403
                ...(directiveNode.leadingComments || []),
20,330✔
404
                ...(directiveNode.trailingComments || [])
20,330✔
405
        ];
20,330✔
406
        if (commentNodes.length !== 0) {
20,330✔
407
                const statementNodes = bodyNode.body;
16✔
408
                if (index !== 0) {
16!
409
                        directiveNodes[index - 1].trailingComments = combineArraysWithDedup(
×
410
                                directiveNodes[index - 1].trailingComments, commentNodes
×
411
                        );
×
412
                } else if (index !== directiveNodes.length - 1) {
16!
413
                        directiveNodes[index + 1].leadingComments = combineArraysWithDedup(
×
414
                                commentNodes, directiveNodes[index + 1].leadingComments
×
415
                        );
×
416
                } else if (statementNodes.length !== 0) {
16✔
417
                        statementNodes[0].leadingComments = combineArraysWithDedup(
16✔
418
                                commentNodes, statementNodes[0].leadingComments
16✔
419
                        );
16✔
420
                } else {
16!
421
                        bodyNode.innerComments = combineArraysWithDedup(bodyNode.innerComments, commentNodes);
×
422
                }
×
423
        }
16✔
424

802✔
425
        // Remove directive
802✔
426
        directiveNodes.splice(index, 1);
802✔
427
}
20,330✔
428

62✔
429
/**
62✔
430
 * Replace const violation expression with expression which throws.
62✔
431
 * e.g. `c = f()` -> `f(), (() => {const c = 0; c = 0;})()`
62✔
432
 * If is silent violation (function expression name assigned to in sloppy mode),
62✔
433
 * just remove the assignment.
62✔
434
 * e.g. `c += f()` -> `c + f()`
62✔
435
 *
62✔
436
 * @param {Array<string|number>} trail - Keys trail
62✔
437
 * @param {Array<Object>} trailNodes - Trail nodes
62✔
438
 * @param {boolean} isSilent - `true` if is a silent violation (i.e. doesn't throw)
62✔
439
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
440
 * @param {Function} copyLoc - Function to copy location from old to new AST node
62✔
441
 * @returns {undefined}
62✔
442
 */
62✔
443
function replaceConstViolation(trail, trailNodes, isSilent, internalVars, copyLoc) {
752✔
444
        const trailLen = trail.length,
752✔
445
                node = trailNodes[trailLen],
752✔
446
                parentNode = trailNodes[trailLen - 1];
752✔
447
        function replaceParent(replacementNode) {
752✔
448
                trailNodes[trailLen - 2][trail[trailLen - 2]] = copyLoc(replacementNode, parentNode);
576✔
449
        }
576✔
450

752✔
451
        const {type} = parentNode;
752✔
452
        if (type === 'AssignmentExpression') {
752✔
453
                const {operator} = parentNode;
480✔
454
                if (operator === '=') {
480✔
455
                        // `c = x` -> `x, throw()`
416✔
456
                        replaceParent(
416✔
457
                                createConstViolationThrowNode(parentNode.right, node.name, isSilent, internalVars)
416✔
458
                        );
416✔
459
                } else if (['&&=', '||=', '??='].includes(operator)) {
480✔
460
                        // `c &&= x` -> `c && (x, throw())`
32✔
461
                        replaceParent(
32✔
462
                                t.logicalExpression(
32✔
463
                                        operator.slice(0, -1),
32✔
464
                                        node,
32✔
465
                                        createConstViolationThrowNode(parentNode.right, node.name, isSilent, internalVars)
32✔
466
                                )
32✔
467
                        );
32✔
468
                } else {
32✔
469
                        // Other assignment operator e.g. `+=`, `-=`, `>>>=`
32✔
470
                        // `c += x` -> `c + x, throw()`
32✔
471
                        replaceParent(
32✔
472
                                createConstViolationThrowNode(
32✔
473
                                        t.binaryExpression(operator.slice(0, -1), node, parentNode.right),
32✔
474
                                        node.name, isSilent, internalVars
32✔
475
                                )
32✔
476
                        );
32✔
477
                }
32✔
478
        } else if (type === 'UpdateExpression') {
752✔
479
                // `c++` -> `(n => n++)(c), throw()`
32✔
480
                // `--c` -> `(n => --n)(c), throw()`
32✔
481
                // See https://github.com/overlookmotel/livepack/issues/528#issuecomment-1773242897
32✔
482
                const varNode = createTempVarNode(node.name, internalVars),
32✔
483
                        replacementNode = t.callExpression(
32✔
484
                                t.arrowFunctionExpression(
32✔
485
                                        [varNode], t.updateExpression(parentNode.operator, varNode, parentNode.prefix)
32✔
486
                                ),
32✔
487
                                [node]
32✔
488
                        );
32✔
489
                replaceParent(createConstViolationThrowNode(replacementNode, node.name, isSilent, internalVars));
32✔
490
        } else if (type === 'AssignmentPattern') {
272✔
491
                // `[c = x] = []`
64✔
492
                // -> `[(e => ({set a(v) {v === void 0 && e(); const c = 0; c = 0;}}))(() => x).a] = []`
64✔
493
                // `{c = x} = {}`
64✔
494
                // -> `{c: (e => ({set a(v) {v === void 0 && e(); const c = 0; c = 0;}}))(() => x).a} = {}`
64✔
495
                replaceParent(
64✔
496
                        createConstViolationThrowPatternNode(node.name, parentNode.right, isSilent, internalVars)
64✔
497
                );
64✔
498
        } else if (
240✔
499
                type === 'ForOfStatement' || type === 'ForInStatement'
176✔
500
                || type === 'ObjectProperty' || type === 'RestElement'
176✔
501
                || trailNodes[trailLen - 2].type === 'ArrayPattern'
176✔
502
        ) {
176✔
503
                // `for (c of [1]) { foo(); }`
176✔
504
                // -> `for ({ set a(v) { const c = 0; c = 0; } }.a of [1]) { foo(); }`
176✔
505
                // `{x: c} = {}` -> `{x: {set a(v) { const c = 0; c = 0; }}.a} = {}`
176✔
506
                // `[...c] = []` -> `[...{set a(v) { const c = 0; c = 0; }}.a] = []`
176✔
507
                // `{...c} = {}` -> `{...{set a(v) { const c = 0; c = 0; }}.a} = {}`
176✔
508
                // `[c] = [1]` -> `[{set a(v) { const c = 0; c = 0; }}.a] = [1]`
176✔
509
                parentNode[trail[trailLen - 1]] = copyLoc(
176✔
510
                        createConstViolationThrowAssignNode(node.name, isSilent, internalVars), node
176✔
511
                );
176✔
512
        } else {
176!
NEW
513
                assertBug(false, `Unexpected const violation node type ${type}`);
×
UNCOV
514
        }
×
515
}
752✔
516

62✔
517
/**
62✔
518
 * Create expression node which throws 'Assignment to constant variable' TypeError.
62✔
519
 * @param {Object} node - AST node to wrap
62✔
520
 * @param {string} name - Var name
62✔
521
 * @param {boolean} isSilent - `true` if violation does not throw
62✔
522
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
523
 * @returns {Object} - AST Node object
62✔
524
 */
62✔
525
function createConstViolationThrowNode(node, name, isSilent, internalVars) {
512✔
526
        // If silent failure, return node unchanged
512✔
527
        if (isSilent) return node;
512✔
528

496✔
529
        // `(x, (() => { const c = 0; c = 0; })())`
496✔
530
        return t.sequenceExpression([
496✔
531
                node,
496✔
532
                t.callExpression(
496✔
533
                        t.arrowFunctionExpression([], createConstViolationThrowBlockNode(name, internalVars)), []
496✔
534
                )
496✔
535
        ]);
496✔
536
}
512✔
537

62✔
538
/**
62✔
539
 * Create expression node which throws when assigned to.
62✔
540
 * @param {string} name - Var name
62✔
541
 * @param {boolean} isSilent - `true` if violation does not throw
62✔
542
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
543
 * @returns {Object} - AST Node object
62✔
544
 */
62✔
545
function createConstViolationThrowAssignNode(name, isSilent, internalVars) {
176✔
546
        // If silent failure, return expression which assignment to is a no-op
176✔
547
        if (isSilent) {
176!
548
                // `{}.a`
×
549
                return t.memberExpression(t.objectExpression([]), t.identifier('a'));
×
550
        }
×
551

176✔
552
        // `{ set a(v) { const c = 0; c = 0; } }.a`
176✔
553
        return t.memberExpression(
176✔
554
                t.objectExpression([
176✔
555
                        t.objectMethod(
176✔
556
                                'set',
176✔
557
                                t.identifier('a'),
176✔
558
                                [createTempVarNode(name === 'v' ? '_v' : 'v', internalVars)],
176!
559
                                createConstViolationThrowBlockNode(name, internalVars)
176✔
560
                        )
176✔
561
                ]),
176✔
562
                t.identifier('a')
176✔
563
        );
176✔
564
}
176✔
565

62✔
566
/**
62✔
567
 * Create expression node to replace an assignment pattern which:
62✔
568
 * 1. Evaluates right hand side of pattern expression only if incoming assignment value is `undefined`
62✔
569
 * 2. Throws when assigned to
62✔
570
 *
62✔
571
 * @param {string} name - Var name
62✔
572
 * @param {Object} rightNode - AST Node for right-hand side of assignment pattern
62✔
573
 * @param {boolean} isSilent - `true` if violation does not throw
62✔
574
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
575
 * @returns {Object} - AST Node object
62✔
576
 */
62✔
577
function createConstViolationThrowPatternNode(name, rightNode, isSilent, internalVars) {
64✔
578
        const valueVarNode = createTempVarNode(name === 'v' ? '_v' : 'v', internalVars),
64!
579
                rightGetterVarNode = createTempVarNode(name === 'e' ? '_e' : 'e', internalVars);
64!
580

64✔
581
        // `v === void 0 && e()`
64✔
582
        const statementNodes = [t.expressionStatement(t.logicalExpression(
64✔
583
                '&&',
64✔
584
                t.binaryExpression('===', valueVarNode, t.unaryExpression('void', t.numericLiteral(0))),
64✔
585
                t.callExpression(rightGetterVarNode, [])
64✔
586
        ))];
64✔
587

64✔
588
        if (!isSilent) statementNodes.push(...createConstViolationThrowStatementNodes(name, internalVars));
64✔
589

64✔
590
        // `(e => ({ set a(v) { v === void 0 && e(); const c = 0; c = 0; }}))(() => x).a`
64✔
591
        return t.memberExpression(
64✔
592
                t.callExpression(
64✔
593
                        t.arrowFunctionExpression(
64✔
594
                                [rightGetterVarNode],
64✔
595
                                t.objectExpression([
64✔
596
                                        t.objectMethod('set', t.identifier('a'), [valueVarNode], t.blockStatement(statementNodes))
64✔
597
                                ])
64✔
598
                        ),
64✔
599
                        [t.arrowFunctionExpression([], rightNode)]
64✔
600
                ),
64✔
601
                t.identifier('a')
64✔
602
        );
64✔
603
}
64✔
604

62✔
605
/**
62✔
606
 * Create block statement which throws 'Assignment to constant variable' TypeError.
62✔
607
 * @param {string} name - Var name
62✔
608
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
609
 * @returns {Object} - AST Node object
62✔
610
 */
62✔
611
function createConstViolationThrowBlockNode(name, internalVars) {
672✔
612
        // `{ const c = 0; c = 0; }`
672✔
613
        return t.blockStatement(createConstViolationThrowStatementNodes(name, internalVars));
672✔
614
}
672✔
615

62✔
616
/**
62✔
617
 * Create statements which throw 'Assignment to constant variable' TypeError.
62✔
618
 * @param {string} name - Var name
62✔
619
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
620
 * @returns {Array<Object>} - Array of AST Node objects
62✔
621
 */
62✔
622
function createConstViolationThrowStatementNodes(name, internalVars) {
736✔
623
        // `const c = 0; c = 0;`
736✔
624
        const varNode = createTempVarNode(name, internalVars);
736✔
625
        return [
736✔
626
                t.variableDeclaration('const', [t.variableDeclarator(varNode, t.numericLiteral(0))]),
736✔
627
                t.expressionStatement(t.assignmentExpression('=', varNode, t.numericLiteral(0)))
736✔
628
        ];
736✔
629
}
736✔
630

62✔
631
/**
62✔
632
 * Replace `super()` call with transpiled version.
62✔
633
 * @param {Array<string|number>} trail - Keys trail
62✔
634
 * @param {Array<Object>} trailNodes - Trail nodes
62✔
635
 * @param {Object} superVarNode - Var node for home object for `super`
62✔
636
 * @param {Object} [thisVarNode] - Var node for `this` (Identifier)
62✔
637
 * @param {number} [firstSuperStatementIndex] - Index of first top-level `super()` statement
62✔
638
 * @param {Function} copyLoc - Function to copy location from old to new AST node
62✔
639
 * @returns {undefined}
62✔
640
 */
62✔
641
function replaceSuperCall(
416✔
642
        trail, trailNodes, superVarNode, thisVarNode, firstSuperStatementIndex, copyLoc
416✔
643
) {
416✔
644
        const trailLen = trail.length,
416✔
645
                callNode = trailNodes[trailLen - 1];
416✔
646

416✔
647
        // Convert to `super(x, y)` -> `Reflect.construct(Object.getPrototypeOf(super$0), [x, y], super$0)`.
416✔
648
        // NB: Cannot optimize `super(...x)` to `Reflect.construct(Object.getPrototypeOf(super$0), x, super$0)`
416✔
649
        // in case `x` is an iterator not an array.
416✔
650
        const argumentsNodes = callNode.arguments;
416✔
651
        callNode.callee = copyLoc(
416✔
652
                t.memberExpression(t.identifier('Reflect'), t.identifier('construct')),
416✔
653
                callNode.callee
416✔
654
        );
416✔
655
        callNode.arguments = [
416✔
656
                t.callExpression(
416✔
657
                        t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
416✔
658
                        [superVarNode]
416✔
659
                ),
416✔
660
                t.arrayExpression(argumentsNodes),
416✔
661
                superVarNode
416✔
662
        ];
416✔
663

416✔
664
        // If is `return super()`, just substitute transpiled super
416✔
665
        // `return super(x)` -> `return Reflect.construct(Object.getPrototypeOf(super$0), [x], super$0)`
416✔
666
        const grandParentNode = trailNodes[trailLen - 2],
416✔
667
                grandParentType = grandParentNode.type;
416✔
668
        if (grandParentType === 'ReturnStatement') {
416✔
669
                if (thisVarNode) {
16!
670
                        grandParentNode[trail[trailLen - 2]] = copyLoc(
×
671
                                t.assignmentExpression('=', thisVarNode, callNode),
×
672
                                callNode
×
673
                        );
×
674
                }
×
675
                return;
16✔
676
        }
16✔
677

400✔
678
        // If is a top-level statement in constructor
400✔
679
        // (i.e. is statement which is purely `super()`, directly in constructor body block):
400✔
680
        // - Last statement: `return Reflect.construct(...)`
400✔
681
        //   or if `this` used in constructor: `return this$0 = Reflect.construct(...)`
400✔
682
        // - First statement: `const this$0 = Reflect.construct(...)`
400✔
683
        // - Any other statement: `this$0 = Reflect.construct(...)`
400✔
684
        if (grandParentType === 'ExpressionStatement') {
400✔
685
                const fnType = trailNodes[0].type;
384✔
686
                if ((fnType === 'ClassDeclaration' || fnType === 'ClassExpression') && trail.length === 8) {
384✔
687
                        // Top-level statement in constructor
336✔
688
                        const statementNodes = trailNodes[5],
336✔
689
                                statementIndex = trail[5];
336✔
690
                        if (statementIndex === statementNodes.length - 1) {
336✔
691
                                // Last statement in constructor
96✔
692
                                // `return Reflect.construct(...);` or `return this$0 = Reflect.construct(...);`
96✔
693
                                statementNodes[statementIndex] = copyLoc(
96✔
694
                                        t.returnStatement(thisVarNode ? t.assignmentExpression('=', thisVarNode, callNode) : callNode),
96✔
695
                                        callNode
96✔
696
                                );
96✔
697
                                return;
96✔
698
                        }
96✔
699

240✔
700
                        if (statementIndex === firstSuperStatementIndex) {
320✔
701
                                // First `super()` statement - replace with `const this$0 = Reflect.construct(...);`
208✔
702
                                statementNodes[statementIndex] = copyLoc(
208✔
703
                                        t.variableDeclaration('const', [t.variableDeclarator(thisVarNode, callNode)]),
208✔
704
                                        grandParentNode
208✔
705
                                );
208✔
706
                                return;
208✔
707
                        }
208✔
708
                }
336✔
709
        }
384✔
710

96✔
711
        // Replace with `this$0 = Reflect.construct(...)`
96✔
712
        grandParentNode[trail[trailLen - 2]] = copyLoc(
96✔
713
                t.assignmentExpression('=', thisVarNode, callNode), callNode
96✔
714
        );
96✔
715
}
416✔
716

62✔
717
/**
62✔
718
 * Replace `super` expression with transpiled version.
62✔
719
 * `super.prop` / `super[prop]` / `super.prop(...)` / `super[prop](...)` /
62✔
720
 * `super.prop = ...` / `super[prop] = ...`
62✔
721
 *
62✔
722
 * @param {Array<string|number>} trail - Keys trail
62✔
723
 * @param {Array<Object>} trailNodes - Trail nodes
62✔
724
 * @param {Object} superVarNode - Var node for home object for `super`
62✔
725
 * @param {Object} [thisVarNode] - Var node for `this` (may be Identifier or ThisExpression)
62✔
726
 * @param {boolean} superIsProto - `true` if `super` is within context of class prototype method
62✔
727
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
728
 * @param {Function} copyLoc - Function to copy location from old to new AST node
62✔
729
 * @returns {undefined}
62✔
730
 */
62✔
731
function replaceSuperExpression(
1,296✔
732
        trail, trailNodes, superVarNode, thisVarNode, superIsProto, internalVars, copyLoc
1,296✔
733
) {
1,296✔
734
        const trailLen = trail.length,
1,296✔
735
                expressionNode = trailNodes[trailLen - 1];
1,296✔
736

1,296✔
737
        // `super.prop` -> `Reflect.get(Object.getPrototypeOf(super$0.prototype), 'prop', this$0)`
1,296✔
738
        // or in static class method `Reflect.get(Object.getPrototypeOf(super$0), 'prop', this$0)`
1,296✔
739
        let propNode = expressionNode.property;
1,296✔
740
        if (!expressionNode.computed) propNode = copyLoc(t.stringLiteral(propNode.name), propNode);
1,296✔
741

1,296✔
742
        let replacementNode = t.callExpression(
1,296✔
743
                t.memberExpression(t.identifier('Reflect'), t.identifier('get')),
1,296✔
744
                [
1,296✔
745
                        t.callExpression(
1,296✔
746
                                t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
1,296✔
747
                                [
1,296✔
748
                                        superIsProto
1,296✔
749
                                                ? t.memberExpression(superVarNode, t.identifier('prototype'))
1,296✔
750
                                                : superVarNode
1,296✔
751
                                ]
1,296✔
752
                        ),
1,296✔
753
                        propNode,
1,296✔
754
                        thisVarNode
1,296✔
755
                ]
1,296✔
756
        );
1,296✔
757

1,296✔
758
        // `super.prop = ...` -> `Reflect.set(Object.getPrototypeOf(super$0.prototype), 'prop', value, this$0)`
1,296✔
759
        const parentNode = trailNodes[trailLen - 2],
1,296✔
760
                parentKey = trail[trailLen - 2],
1,296✔
761
                parentType = parentNode.type;
1,296✔
762
        if (parentType === 'AssignmentExpression' && parentKey === 'left') {
1,296✔
763
                // Convert `Reflect.get(...)` to `Reflect.set(...)`
224✔
764
                replacementNode.callee.property.name = 'set';
224✔
765

224✔
766
                const valueNode = parentNode.right,
224✔
767
                        grandParentNode = trailNodes[trailLen - 3];
224✔
768
                if (grandParentNode.type === 'ExpressionStatement') {
224✔
769
                        // Standalone expression - add value to `Reflect.set()` arguments
208✔
770
                        replacementNode.arguments.splice(2, 0, valueNode);
208✔
771
                } else {
208✔
772
                        // Not standalone expression - wrap in function which return values.
16✔
773
                        // This avoids evaluating the value expression twice.
16✔
774
                        // `x = super.foo = y();` =>
16✔
775
                        // `x = ((key, value) => (Reflect.set(..., key, value, this$0), value))('foo', y());`
16✔
776
                        // NB: Key is passed to function as argument too as it could be a complex expression
16✔
777
                        // referencing many vars. Evaluating it outside the temp closure ensures no var name clashes.
16✔
778
                        const keyVarNode = createTempVarNode('key', internalVars),
16✔
779
                                valueVarNode = createTempVarNode('value', internalVars);
16✔
780
                        replacementNode.arguments[1] = keyVarNode;
16✔
781
                        replacementNode.arguments.splice(2, 0, valueVarNode);
16✔
782
                        replacementNode = t.callExpression(
16✔
783
                                t.arrowFunctionExpression(
16✔
784
                                        [keyVarNode, valueVarNode],
16✔
785
                                        t.sequenceExpression([replacementNode, valueVarNode])
16✔
786
                                ),
16✔
787
                                [propNode, valueNode]
16✔
788
                        );
16✔
789
                }
16✔
790

224✔
791
                grandParentNode[trail[trailLen - 3]] = copyLoc(replacementNode, parentNode);
224✔
792
                return;
224✔
793
        }
224✔
794

1,072✔
795
        // `super.prop(x, y)` -> `Reflect.get(...).call(this$0, x, y)`
1,072✔
796
        if (parentType === 'CallExpression') {
1,296✔
797
                replacementNode = t.memberExpression(replacementNode, t.identifier('call'));
784✔
798
                parentNode.arguments.unshift(thisVarNode);
784✔
799
        }
784✔
800
        copyLoc(replacementNode, expressionNode);
1,072✔
801

1,072✔
802
        parentNode[parentKey] = replacementNode;
1,072✔
803
}
1,296✔
804

62✔
805
/**
62✔
806
 * Create temp var node and add to internal vars.
62✔
807
 * @param {string} name - Var name
62✔
808
 * @param {Object} internalVars - Map of internal vars, keyed by var name
62✔
809
 * @returns {Object} - Identifier AST node
62✔
810
 */
62✔
811
function createTempVarNode(name, internalVars) {
1,104✔
812
        const node = t.identifier(name);
1,104✔
813
        createArrayOrPush(internalVars, name, node);
1,104✔
814
        return node;
1,104✔
815
}
1,104✔
816

62✔
817
/**
62✔
818
 * Add ASTs of nested functions to AST.
62✔
819
 * A function which has other functions nested within it will have left those nodes defined as `null`
62✔
820
 * in JSON-serialized AST. Get those child functions' ASTs from their own `getFnInfo()` functions
62✔
821
 * and insert them into the parent AST.
62✔
822
 * @param {Object} fnInfo - Function info object which was encoded as JSON to fn info getter function
62✔
823
 * @param {Array<Function>} getInfos - Function info getter functions for child functions
62✔
824
 * @param {boolean} isNestedFunction - `true` if is nested function
62✔
825
 * @param {number} fnId - Block ID of function being serialized
62✔
826
 * @param {Map} scopeDefs - Scope definitions map, keyed by block ID
62✔
827
 * @param {Object} externalVars - Map of var name to array of var nodes
62✔
828
 * @param {Object} internalVars - Map of var name to array of var nodes
62✔
829
 * @param {Set<string>} globalVarNames - Set of global var names
62✔
830
 * @param {Set<string>} functionNames - Set of function names
62✔
831
 * @param {Array<Object>} amendments - Array of amendments (const violations or `super`)
62✔
832
 * @returns {undefined}
62✔
833
 */
62✔
834
function resolveFunctionInfo(
34,756✔
835
        fnInfo, getInfos, isNestedFunction, fnId, scopeDefs,
34,756✔
836
        externalVars, internalVars, globalVarNames, functionNames, amendments
34,756✔
837
) {
34,756✔
838
        // Init internal vars.
34,756✔
839
        // Converting trails to nodes needs to be done after child functions added into AST
34,756✔
840
        // because some vars recorded as internal to this function may be within the ASTs of child functions.
34,756✔
841
        // These are class `extends` clauses and computed method keys.
34,756✔
842
        // Initializing properties of `internalVars` needs to happen before processing child functions,
34,756✔
843
        // as external vars in child functions can become internal vars in this function.
34,756✔
844
        const internalVarTrails = [];
34,756✔
845
        for (const [varName, trails] of Object.entries(fnInfo.internalVars)) {
34,756✔
846
                if (!internalVars[varName]) internalVars[varName] = [];
10,498✔
847
                internalVarTrails.push({varName, trails});
10,498✔
848
        }
10,498✔
849

34,756✔
850
        // Process child functions
34,756✔
851
        const fnNode = fnInfo.ast;
34,756✔
852
        fnInfo.childFns.forEach((trail, index) => {
34,756✔
853
                const [childJson, childGetInfos] = getInfos[index](),
5,332✔
854
                        childInfo = JSON.parse(childJson);
5,332✔
855
                resolveFunctionInfo(
5,332✔
856
                        childInfo, childGetInfos, true, fnId, scopeDefs,
5,332✔
857
                        externalVars, internalVars, globalVarNames, functionNames, amendments
5,332✔
858
                );
5,332✔
859

5,332✔
860
                // Insert child function's AST into this function's AST
5,332✔
861
                setProp(fnNode, trail, childInfo.ast);
5,332✔
862
        });
34,756✔
863

34,756✔
864
        // Record function name
34,756✔
865
        if (isNestedFunction) {
34,756✔
866
                const idNode = fnNode.id;
5,332✔
867
                if (idNode) functionNames.add(idNode.name);
5,332✔
868
        }
5,332✔
869

34,756✔
870
        // Get external var nodes
34,756✔
871
        for (const scope of fnInfo.scopes) {
34,756✔
872
                const {blockId} = scope;
22,390✔
873
                if (blockId < fnId) {
22,390✔
874
                        // External var
19,348✔
875
                        for (const [varName, {isReadFrom, isAssignedTo, trails}] of Object.entries(scope.vars)) {
19,348✔
876
                                if (isNestedFunction) {
27,156✔
877
                                        const scopeDefVar = scopeDefs.get(blockId).vars[varName];
3,424✔
878
                                        if (isReadFrom) scopeDefVar.isReadFrom = true;
3,424✔
879
                                        if (isAssignedTo) scopeDefVar.isAssignedTo = true;
3,424✔
880
                                }
3,424✔
881

27,156✔
882
                                externalVars[varName].push(...trailsToNodes(fnNode, trails, varName));
27,156✔
883
                        }
27,156✔
884
                } else {
22,390✔
885
                        // Var which is external to current function, but internal to function being serialized
3,042✔
886
                        for (const [varName, {isFunction, trails}] of Object.entries(scope.vars)) {
3,042✔
887
                                if (!isFunction) internalVars[varName]?.push(...trailsToNodes(fnNode, trails, varName));
3,364✔
888
                        }
3,364✔
889
                }
3,042✔
890
        }
22,390✔
891

34,756✔
892
        // Get internal var nodes
34,756✔
893
        for (const {varName, trails} of internalVarTrails) {
34,756✔
894
                internalVars[varName].push(...trailsToNodes(fnNode, trails, varName));
10,498✔
895
        }
10,498✔
896

34,756✔
897
        // Get global var names
34,756✔
898
        if (fnInfo.globalVarNames) setAddFrom(globalVarNames, fnInfo.globalVarNames);
34,756✔
899

34,756✔
900
        // Get amendments (const violations and `super`).
34,756✔
901
        // Ignore amendments which refer to internal vars.
34,756✔
902
        const thisAmendments = fnInfo.amendments;
34,756✔
903
        if (thisAmendments) {
34,756✔
904
                for (const [type, blockId, ...trail] of thisAmendments) {
2,432✔
905
                        if (blockId < fnId) {
2,640✔
906
                                amendments.push({type, trail, trailNodes: getProps(fnNode, trail)});
2,464✔
907
                        } else if (type === CONST_VIOLATION_CONST) {
2,640✔
908
                                // Const violation where var is internal to function. Add to internal vars instead.
32✔
909
                                // Ignore CONST_VIOLATION_FUNCTION_THROWING and CONST_VIOLATION_FUNCTION_SILENT violation types
32✔
910
                                // because they refer to function names, which are not treated as internal vars.
32✔
911
                                const node = getProp(fnNode, trail);
32✔
912
                                internalVars[node.name].push(node);
32✔
913
                        }
32✔
914
                }
2,640✔
915
        }
2,432✔
916
}
34,756✔
917

62✔
918
/**
62✔
919
 * Get nodes for trails.
62✔
920
 * Convert `ThisExpression`s to `Identifier`s.
62✔
921
 * @param {Object} fnNode - AST node for function
62✔
922
 * @param {Array<Array>} trails - Trails
62✔
923
 * @param {string} varName - Var name
62✔
924
 * @returns {Array<Object>} - AST nodes specified by trails
62✔
925
 */
62✔
926
function trailsToNodes(fnNode, trails, varName) {
39,338✔
927
        return varName === 'this'
39,338✔
928
                ? trails.map((trail) => {
39,338✔
929
                        const node = getProp(fnNode, trail);
480✔
930
                        node.type = 'Identifier';
480✔
931
                        node.name = 'this';
480✔
932
                        return node;
480✔
933
                })
1,184✔
934
                : trails.map(trail => getProp(fnNode, trail));
39,338✔
935
}
39,338✔
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

© 2025 Coveralls, Inc