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

overlookmotel / livepack / 6050306021

01 Sep 2023 01:57PM UTC coverage: 89.915% (+0.02%) from 89.891%
6050306021

push

github

overlookmotel
Instrument: Shorten code [refactor]

2707 of 2918 branches covered (0.0%)

Branch coverage included in aggregate %.

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

12450 of 13939 relevant lines covered (89.32%)

6528.64 hits per line

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

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

31✔
6
'use strict';
31✔
7

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

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

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

31✔
28
// Exports
31✔
29

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

14,624✔
70
        // Throw error if function contains `import()`
14,624✔
71
        if (fnInfo.containsImport) {
14,624!
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

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

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

14,624✔
101
        let node = fnInfo.ast;
14,624✔
102

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

14,582✔
113
                traverseAll(node, ({loc}) => {
14,582✔
114
                        if (loc && !loc.filename) loc.filename = filename;
104,760✔
115
                });
14,582✔
116

14,582✔
117
                copyLoc = (destNode, srcNode) => {
14,582✔
118
                        destNode.start = srcNode.start;
4,200✔
119
                        destNode.end = srcNode.end;
4,200✔
120
                        destNode.loc = srcNode.loc;
4,200✔
121
                        return destNode;
4,200✔
122
                };
14,582✔
123
        } else {
14,624✔
124
                copyLoc = destNode => destNode;
42✔
125
        }
42✔
126

14,624✔
127
        // Get whether strict mode and remove use strict directive
14,624✔
128
        let isStrict;
14,624✔
129
        if (!isClass) {
14,624✔
130
                isStrict = !!fnInfo.isStrict;
12,704✔
131
                if (isStrict) {
12,704✔
132
                        removeUseStrictDirective(node);
10,093✔
133
                } else if (filename.startsWith(RUNTIME_DIR_PATH)) {
12,704✔
134
                        // Runtime functions are treated as indeterminate strict/sloppy mode unless explicitly strict
488✔
135
                        isStrict = null;
488✔
136
                }
488✔
137
        }
12,704✔
138

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

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

5,660✔
159
                // If contains `super`, needs `this` too
5,660✔
160
                if (externalVars.super) {
5,660✔
161
                        thisVarNode = t.identifier('this');
128✔
162
                        externalVars.this.push(thisVarNode);
128✔
163
                }
128✔
164
        } else {
14,624✔
165
                // Class, method or function declaration/expression.
8,964✔
166
                // Get function name.
8,964✔
167
                name = (Object.getOwnPropertyDescriptor(fn, 'name') || {}).value;
8,964✔
168
                if (!isString(name)) name = '';
8,964✔
169

8,964✔
170
                // Identify if method and convert class method to object method
8,964✔
171
                if (type === 'ClassMethod') {
8,964✔
172
                        node.type = 'ObjectMethod';
1,080✔
173
                        node.static = undefined;
1,080✔
174
                        isMethod = true;
1,080✔
175
                } else if (type === 'ObjectMethod') {
8,964✔
176
                        isMethod = true;
992✔
177
                }
992✔
178

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

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

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

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

6,892✔
228
                        if (!name) {
6,892✔
229
                                node.id = null;
3,084✔
230
                        } else {
6,892✔
231
                                if (!idNode || idNode.name !== name) {
3,808✔
232
                                        node.id = t.identifier(name);
426✔
233
                                        if (idNode) copyLoc(node.id, idNode);
426✔
234
                                }
426✔
235
                                functionNames.add(name);
3,808✔
236
                        }
3,808✔
237

6,892✔
238
                        if (isClass) {
6,892✔
239
                                // Class
1,920✔
240
                                if (type === 'ClassDeclaration') node.type = 'ClassExpression';
1,920✔
241

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

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

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

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

176✔
304
                                                firstSuperStatementIndex = fnInfo.firstSuperStatementIndex;
176✔
305
                                                constructorStatementNodes = constructorNode.body.body;
176✔
306
                                        }
176✔
307
                                } else {
1,920✔
308
                                        // Class which doesn't extend a super class. `this` within constructor is actual `this`.
1,248✔
309
                                        thisVarNode = t.thisExpression();
1,248✔
310
                                }
1,248✔
311
                        } else {
6,892✔
312
                                // Function declaration/expression. `this` is actual `this`.
4,972✔
313
                                if (type === 'FunctionDeclaration') node.type = 'FunctionExpression';
4,972✔
314
                                thisVarNode = t.thisExpression();
4,972✔
315
                        }
4,972✔
316
                }
6,892✔
317
        }
8,964✔
318

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

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

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

14,624✔
359
        // Determine what value of `fn.length` will be
14,624✔
360
        let numParams = 0;
14,624✔
361
        for (const {type: paramNodeType} of paramNodes) {
14,624✔
362
                if (paramNodeType === 'RestElement' || paramNodeType === 'AssignmentPattern') break;
2,775✔
363
                numParams++;
2,495✔
364
        }
2,495✔
365

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

31✔
387
/**
31✔
388
 * Remove 'use strict' directive from function.
31✔
389
 * @param {Object} fnNode - Function AST node
31✔
390
 * @returns {undefined}
31✔
391
 */
31✔
392
function removeUseStrictDirective(fnNode) {
10,093✔
393
        const bodyNode = fnNode.body;
10,093✔
394
        if (bodyNode.type !== 'BlockStatement') return;
10,093✔
395
        const directiveNodes = bodyNode.directives;
7,116✔
396
        if (directiveNodes.length === 0) return;
9,382✔
397
        const index = directiveNodes.findIndex(directiveNode => directiveNode.value.value === 'use strict');
481✔
398
        if (index === -1) return;
864✔
399

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

401✔
425
        // Remove directive
401✔
426
        directiveNodes.splice(index, 1);
401✔
427
}
10,093✔
428

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

376✔
451
        const {type} = parentNode;
376✔
452
        if (type === 'AssignmentExpression') {
376✔
453
                const {operator} = parentNode;
240✔
454
                if (operator === '=') {
240✔
455
                        // `c = x` -> `x, throw()`
208✔
456
                        replaceParent(
208✔
457
                                createConstViolationThrowNode(parentNode.right, node.name, isSilent, internalVars)
208✔
458
                        );
208✔
459
                } else if (['&&=', '||=', '??='].includes(operator)) {
240✔
460
                        // `c &&= x` -> `c && (x, throw())`
16✔
461
                        replaceParent(
16✔
462
                                t.logicalExpression(
16✔
463
                                        operator.slice(0, -1),
16✔
464
                                        node,
16✔
465
                                        createConstViolationThrowNode(parentNode.right, node.name, isSilent, internalVars)
16✔
466
                                )
16✔
467
                        );
16✔
468
                } else {
16✔
469
                        // Other assignment operator e.g. `+=`, `-=`, `>>>=`
16✔
470
                        // `c += x` -> `c + x, throw()`
16✔
471
                        replaceParent(
16✔
472
                                createConstViolationThrowNode(
16✔
473
                                        t.binaryExpression(operator.slice(0, -1), node, parentNode.right),
16✔
474
                                        node.name, isSilent, internalVars
16✔
475
                                )
16✔
476
                        );
16✔
477
                }
16✔
478
        } else if (type === 'UpdateExpression') {
376✔
479
                // `c++` -> `+c, throw()`
16✔
480
                replaceParent(
16✔
481
                        createConstViolationThrowNode(t.unaryExpression('+', node), node.name, isSilent, internalVars)
16✔
482
                );
16✔
483
        } else if (type === 'AssignmentPattern') {
136✔
484
                // `[c = x] = []`
32✔
485
                // -> `[(e => ({set a(v) {v === void 0 && e(); const c = 0; c = 0;}}))(() => x).a] = []`
32✔
486
                // `{c = x} = {}`
32✔
487
                // -> `{c: (e => ({set a(v) {v === void 0 && e(); const c = 0; c = 0;}}))(() => x).a} = {}`
32✔
488
                replaceParent(
32✔
489
                        createConstViolationThrowPatternNode(node.name, parentNode.right, isSilent, internalVars)
32✔
490
                );
32✔
491
        } else {
120✔
492
                assertBug(
88✔
493
                        type === 'ForOfStatement' || type === 'ForInStatement'
88✔
494
                                || type === 'ObjectProperty' || type === 'RestElement'
88✔
495
                                || trailNodes[trailLen - 2].type === 'ArrayPattern',
88✔
496
                        `Unexpected const violation node type ${type}`
88✔
497
                );
88✔
498

88✔
499
                // `for (c of [1]) { foo(); }`
88✔
500
                // -> `for ({ set a(v) { const c = 0; c = 0; } }.a of [1]) { foo(); }`
88✔
501
                // `{x: c} = {}` -> `{x: {set a(v) { const c = 0; c = 0; }}.a} = {}`
88✔
502
                // `[...c] = []` -> `[...{set a(v) { const c = 0; c = 0; }}.a] = []`
88✔
503
                // `{...c} = {}` -> `{...{set a(v) { const c = 0; c = 0; }}.a} = {}`
88✔
504
                // `[c] = [1]` -> `[{set a(v) { const c = 0; c = 0; }}.a] = [1]`
88✔
505
                parentNode[trail[trailLen - 1]] = copyLoc(
88✔
506
                        createConstViolationThrowAssignNode(node.name, isSilent, internalVars), node
88✔
507
                );
88✔
508
        }
88✔
509
}
376✔
510

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

248✔
523
        // `(x, (() => { const c = 0; c = 0; })())`
248✔
524
        return t.sequenceExpression([
248✔
525
                node,
248✔
526
                t.callExpression(
248✔
527
                        t.arrowFunctionExpression([], createConstViolationThrowBlockNode(name, internalVars)), []
248✔
528
                )
248✔
529
        ]);
248✔
530
}
256✔
531

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

88✔
546
        // `{ set a(v) { const c = 0; c = 0; } }.a`
88✔
547
        return t.memberExpression(
88✔
548
                t.objectExpression([
88✔
549
                        t.objectMethod(
88✔
550
                                'set',
88✔
551
                                t.identifier('a'),
88✔
552
                                [createTempVarNode(name === 'v' ? '_v' : 'v', internalVars)],
88!
553
                                createConstViolationThrowBlockNode(name, internalVars)
88✔
554
                        )
88✔
555
                ]),
88✔
556
                t.identifier('a')
88✔
557
        );
88✔
558
}
88✔
559

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

32✔
575
        // `v === void 0 && e()`
32✔
576
        const statementNodes = [t.expressionStatement(t.logicalExpression(
32✔
577
                '&&',
32✔
578
                t.binaryExpression('===', valueVarNode, t.unaryExpression('void', t.numericLiteral(0))),
32✔
579
                t.callExpression(rightGetterVarNode, [])
32✔
580
        ))];
32✔
581

32✔
582
        if (!isSilent) statementNodes.push(...createConstViolationThrowStatementNodes(name, internalVars));
32✔
583

32✔
584
        // `(e => ({ set a(v) { v === void 0 && e(); const c = 0; c = 0; }}))(() => x).a`
32✔
585
        return t.memberExpression(
32✔
586
                t.callExpression(
32✔
587
                        t.arrowFunctionExpression(
32✔
588
                                [rightGetterVarNode],
32✔
589
                                t.objectExpression([
32✔
590
                                        t.objectMethod('set', t.identifier('a'), [valueVarNode], t.blockStatement(statementNodes))
32✔
591
                                ])
32✔
592
                        ),
32✔
593
                        [t.arrowFunctionExpression([], rightNode)]
32✔
594
                ),
32✔
595
                t.identifier('a')
32✔
596
        );
32✔
597
}
32✔
598

31✔
599
/**
31✔
600
 * Create block statement which throws 'Assignment to constant variable' TypeError.
31✔
601
 * @param {string} name - Var name
31✔
602
 * @param {Object} internalVars - Map of internal vars, keyed by var name
31✔
603
 * @returns {Object} - AST Node object
31✔
604
 */
31✔
605
function createConstViolationThrowBlockNode(name, internalVars) {
336✔
606
        // `{ const c = 0; c = 0; }`
336✔
607
        return t.blockStatement(createConstViolationThrowStatementNodes(name, internalVars));
336✔
608
}
336✔
609

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

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

208✔
641
        // Convert to `super(x, y)` -> `Reflect.construct(Object.getPrototypeOf(super$0), [x, y], super$0)`.
208✔
642
        // NB Cannot optimize `super(...x)` to `Reflect.construct(Object.getPrototypeOf(super$0), x, super$0)`
208✔
643
        // in case `x` is an iterator not an array.
208✔
644
        const argumentsNodes = callNode.arguments;
208✔
645
        callNode.callee = copyLoc(
208✔
646
                t.memberExpression(t.identifier('Reflect'), t.identifier('construct')),
208✔
647
                callNode.callee
208✔
648
        );
208✔
649
        callNode.arguments = [
208✔
650
                t.callExpression(
208✔
651
                        t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
208✔
652
                        [superVarNode]
208✔
653
                ),
208✔
654
                t.arrayExpression(argumentsNodes),
208✔
655
                superVarNode
208✔
656
        ];
208✔
657

208✔
658
        // If is `return super()`, just substitute transpiled super
208✔
659
        // `return super(x)` -> `return Reflect.construct(Object.getPrototypeOf(super$0), [x], super$0)`
208✔
660
        const grandParentNode = trailNodes[trailLen - 2],
208✔
661
                grandParentType = grandParentNode.type;
208✔
662
        if (grandParentType === 'ReturnStatement') {
208✔
663
                if (thisVarNode) {
8!
664
                        grandParentNode[trail[trailLen - 2]] = copyLoc(
×
665
                                t.assignmentExpression('=', thisVarNode, callNode),
×
666
                                callNode
×
667
                        );
×
668
                }
×
669
                return;
8✔
670
        }
8✔
671

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

120✔
694
                        if (statementIndex === firstSuperStatementIndex) {
160✔
695
                                // First `super()` statement - replace with `const this$0 = Reflect.construct(...);`
104✔
696
                                statementNodes[statementIndex] = copyLoc(
104✔
697
                                        t.variableDeclaration('const', [t.variableDeclarator(thisVarNode, callNode)]),
104✔
698
                                        grandParentNode
104✔
699
                                );
104✔
700
                                return;
104✔
701
                        }
104✔
702
                }
168✔
703
        }
192✔
704

48✔
705
        // Replace with `this$0 = Reflect.construct(...)`
48✔
706
        grandParentNode[trail[trailLen - 2]] = copyLoc(
48✔
707
                t.assignmentExpression('=', thisVarNode, callNode), callNode
48✔
708
        );
48✔
709
}
208✔
710

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

648✔
731
        // `super.prop` -> `Reflect.get(Object.getPrototypeOf(super$0.prototype), 'prop', this$0)`
648✔
732
        // or in static class method `Reflect.get(Object.getPrototypeOf(super$0), 'prop', this$0)`
648✔
733
        let propNode = expressionNode.property;
648✔
734
        if (!expressionNode.computed) propNode = copyLoc(t.stringLiteral(propNode.name), propNode);
648✔
735

648✔
736
        let replacementNode = t.callExpression(
648✔
737
                t.memberExpression(t.identifier('Reflect'), t.identifier('get')),
648✔
738
                [
648✔
739
                        t.callExpression(
648✔
740
                                t.memberExpression(t.identifier('Object'), t.identifier('getPrototypeOf')),
648✔
741
                                [
648✔
742
                                        superIsProto
648✔
743
                                                ? t.memberExpression(superVarNode, t.identifier('prototype'))
648✔
744
                                                : superVarNode
648✔
745
                                ]
648✔
746
                        ),
648✔
747
                        propNode,
648✔
748
                        thisVarNode
648✔
749
                ]
648✔
750
        );
648✔
751

648✔
752
        // `super.prop = ...` -> `Reflect.set(Object.getPrototypeOf(super$0.prototype), 'prop', value, this$0)`
648✔
753
        const parentNode = trailNodes[trailLen - 2],
648✔
754
                parentKey = trail[trailLen - 2],
648✔
755
                parentType = parentNode.type;
648✔
756
        if (parentType === 'AssignmentExpression' && parentKey === 'left') {
648✔
757
                // Convert `Reflect.get(...)` to `Reflect.set(...)`
112✔
758
                replacementNode.callee.property.name = 'set';
112✔
759

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

112✔
785
                grandParentNode[trail[trailLen - 3]] = copyLoc(replacementNode, parentNode);
112✔
786
                return;
112✔
787
        }
112✔
788

536✔
789
        // `super.prop(x, y)` -> `Reflect.get(...).call(this$0, x, y)`
536✔
790
        if (parentType === 'CallExpression') {
648✔
791
                replacementNode = t.memberExpression(replacementNode, t.identifier('call'));
392✔
792
                parentNode.arguments.unshift(thisVarNode);
392✔
793
        }
392✔
794
        copyLoc(replacementNode, expressionNode);
536✔
795

536✔
796
        parentNode[parentKey] = replacementNode;
536✔
797
}
648✔
798

31✔
799
/**
31✔
800
 * Create temp var node and add to internal vars.
31✔
801
 * @param {string} name - Var name
31✔
802
 * @param {Object} internalVars - Map of internal vars, keyed by var name
31✔
803
 * @returns {Object} - Identifier AST node
31✔
804
 */
31✔
805
function createTempVarNode(name, internalVars) {
536✔
806
        const node = t.identifier(name);
536✔
807
        createArrayOrPush(internalVars, name, node);
536✔
808
        return node;
536✔
809
}
536✔
810

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

17,234✔
844
        // Process child functions
17,234✔
845
        const fnNode = fnInfo.ast;
17,234✔
846
        fnInfo.childFns.forEach((trail, index) => {
17,234✔
847
                const [childJson, childGetInfos] = getInfos[index](),
2,610✔
848
                        childInfo = JSON.parse(childJson);
2,610✔
849
                resolveFunctionInfo(
2,610✔
850
                        childInfo, childGetInfos, true, fnId, scopeDefs,
2,610✔
851
                        externalVars, internalVars, globalVarNames, functionNames, amendments
2,610✔
852
                );
2,610✔
853

2,610✔
854
                // Insert child function's AST into this function's AST
2,610✔
855
                setProp(fnNode, trail, childInfo.ast);
2,610✔
856
        });
17,234✔
857

17,234✔
858
        // Record function name
17,234✔
859
        if (isNestedFunction) {
17,234✔
860
                const idNode = fnNode.id;
2,610✔
861
                if (idNode) functionNames.add(idNode.name);
2,610✔
862
        }
2,610✔
863

17,234✔
864
        // Get external var nodes
17,234✔
865
        for (const scope of fnInfo.scopes) {
17,234✔
866
                const {blockId} = scope;
11,163✔
867
                if (blockId < fnId) {
11,163✔
868
                        // External var
9,650✔
869
                        for (const [varName, {isReadFrom, isAssignedTo, trails}] of Object.entries(scope.vars)) {
9,650✔
870
                                if (isNestedFunction) {
13,554✔
871
                                        const scopeDefVar = scopeDefs.get(blockId).vars[varName];
1,712✔
872
                                        if (isReadFrom) scopeDefVar.isReadFrom = true;
1,712✔
873
                                        if (isAssignedTo) scopeDefVar.isAssignedTo = true;
1,712✔
874
                                }
1,712✔
875

13,554✔
876
                                externalVars[varName].push(...trailsToNodes(fnNode, trails, varName));
13,554✔
877
                        }
13,554✔
878
                } else {
11,163✔
879
                        // Var which is external to current function, but internal to function being serialized
1,513✔
880
                        for (const [varName, {trails}] of Object.entries(scope.vars)) {
1,513✔
881
                                const internalVarNodes = internalVars[varName];
1,674✔
882
                                if (internalVarNodes) internalVarNodes.push(...trailsToNodes(fnNode, trails, varName));
1,674✔
883
                        }
1,674✔
884
                }
1,513✔
885
        }
11,163✔
886

17,234✔
887
        // Get internal var nodes
17,234✔
888
        for (const {varName, trails} of internalVarTrails) {
17,234✔
889
                internalVars[varName].push(...trailsToNodes(fnNode, trails, varName));
5,217✔
890
        }
5,217✔
891

17,234✔
892
        // Get global var names
17,234✔
893
        const thisGlobalVarNames = fnInfo.globalVarNames;
17,234✔
894
        if (thisGlobalVarNames) setAddFrom(globalVarNames, thisGlobalVarNames);
17,234✔
895

17,234✔
896
        // Get amendments (const violations and `super`).
17,234✔
897
        // Ignore amendments which refer to internal vars.
17,234✔
898
        const thisAmendments = fnInfo.amendments;
17,234✔
899
        if (thisAmendments) {
17,234✔
900
                for (const [type, blockId, ...trail] of thisAmendments) {
1,216✔
901
                        if (blockId < fnId) {
1,320✔
902
                                amendments.push({type, trail, trailNodes: getProps(fnNode, trail)});
1,232✔
903
                        } else if (type === CONST_VIOLATION_CONST) {
1,320✔
904
                                // Const violation where var is internal to function. Add to internal vars instead.
16✔
905
                                // Ignore CONST_VIOLATION_FUNCTION_THROWING and CONST_VIOLATION_FUNCTION_SILENT violation types
16✔
906
                                // because they refer to function names, which are not treated as internal vars.
16✔
907
                                const node = getProp(fnNode, trail);
16✔
908
                                internalVars[node.name].push(node);
16✔
909
                        }
16✔
910
                }
1,320✔
911
        }
1,216✔
912
}
17,234✔
913

31✔
914
/**
31✔
915
 * Get nodes for trails.
31✔
916
 * Convert `ThisExpression`s to `Identifier`s.
31✔
917
 * @param {Object} fnNode - AST node for function
31✔
918
 * @param {Array<Array>} trails - Trails
31✔
919
 * @param {string} varName - Var name
31✔
920
 * @returns {Array<Object>} - AST nodes specified by trails
31✔
921
 */
31✔
922
function trailsToNodes(fnNode, trails, varName) {
19,613✔
923
        return varName === 'this'
19,613✔
924
                ? trails.map((trail) => {
19,613✔
925
                        const node = getProp(fnNode, trail);
240✔
926
                        node.type = 'Identifier';
240✔
927
                        node.name = 'this';
240✔
928
                        return node;
240✔
929
                })
592✔
930
                : trails.map(trail => getProp(fnNode, trail));
19,613✔
931
}
19,613✔
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