targeted-mutation 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +111 -2
  4. package/bin/tmt-compile.mjs +46 -0
  5. package/bin/tmt.mjs +117 -0
  6. package/build/typescript-syntax/LICENSE.txt +55 -0
  7. package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
  8. package/build/typescript-syntax/typescript-syntax.cjs +43 -0
  9. package/docs/analysis.md +218 -0
  10. package/docs/compiler.md +462 -0
  11. package/docs/development.md +61 -0
  12. package/docs/how-it-works.svg +188 -0
  13. package/docs/l1.md +94 -0
  14. package/docs/performance.md +647 -0
  15. package/docs/releasing.md +48 -0
  16. package/package.json +49 -4
  17. package/src/analysis.mjs +689 -0
  18. package/src/assertion-session.mjs +93 -0
  19. package/src/assertion-strength.mjs +795 -0
  20. package/src/builtin-mutations.mjs +755 -0
  21. package/src/builtin-switches.mjs +642 -0
  22. package/src/change-undone.mjs +524 -0
  23. package/src/cli-output.mjs +166 -0
  24. package/src/compiler-compat.cjs +108 -0
  25. package/src/compiler-maps.cjs +60 -0
  26. package/src/compiler-routes.cjs +391 -0
  27. package/src/compiler.cjs +98 -0
  28. package/src/compiler.mjs +1 -0
  29. package/src/conventional.mjs +172 -0
  30. package/src/displacement.mjs +19 -0
  31. package/src/extract.mjs +135 -0
  32. package/src/fallback-process.mjs +14 -0
  33. package/src/in-parallel.mjs +20 -0
  34. package/src/lean-replay.mjs +39 -0
  35. package/src/operator-analysis.mjs +123 -0
  36. package/src/playwright.mjs +139 -0
  37. package/src/probe-runtime.mjs +50 -0
  38. package/src/probe.mjs +170 -0
  39. package/src/prototype.mjs +230 -0
  40. package/src/regex-mutations.mjs +102 -0
  41. package/src/runner-process.mjs +59 -0
  42. package/src/runtime-binaries.mjs +50 -0
  43. package/src/scope.mjs +202 -0
  44. package/src/source-text.mjs +49 -0
  45. package/src/standard-plan.mjs +308 -0
  46. package/src/standard-runner.mjs +185 -0
  47. package/src/standard-session.mjs +362 -0
  48. package/src/standard-setup.mjs +20 -0
  49. package/src/targeted-gaps.mjs +85 -0
  50. package/src/threshold.mjs +185 -0
  51. package/src/trace-buffer.mjs +126 -0
  52. package/src/typescript-bindings.mjs +243 -0
  53. package/src/typescript-compiler.mjs +59 -0
  54. package/src/typescript-extraction.mjs +354 -0
  55. package/src/typescript-grammar.mjs +923 -0
  56. package/src/vitest-reporter.mjs +64 -0
  57. package/src/vitest.mjs +262 -0
  58. package/src/witness-analysis.mjs +234 -0
  59. package/src/witness-contracts.mjs +110 -0
  60. package/src/witness-discovery.mjs +239 -0
  61. package/src/witness-fixtures.mjs +149 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
@@ -0,0 +1,755 @@
1
+ import { mutatePattern } from './regex-mutations.mjs';
2
+ import { loadTypeScript } from './typescript-compiler.mjs';
3
+
4
+ // The built-in mutation set follows the StrykerJS mutators, found here in the TypeScript syntax tree.
5
+ // Each mutation names the node it replaces and the enclosing node where a runtime switch can be placed.
6
+ const arithmetic = new Map([['+', '-'], ['-', '+'], ['*', '/'], ['/', '*'], ['%', '*']]);
7
+ const assignment = new Map([['+=', '-='], ['-=', '+='], ['*=', '/='], ['/=', '*='], ['%=', '*='], ['<<=', '>>='], ['>>=', '<<='],
8
+ ['&=', '|='], ['|=', '&='], ['&&=', '||='], ['||=', '&&='], ['??=', '&&=']]);
9
+ const equality = new Map([['<', ['<=', '>=']], ['<=', ['<', '>']], ['>', ['>=', '<=']], ['>=', ['>', '<']],
10
+ ['==', ['!=']], ['!=', ['==']], ['===', ['!==']], ['!==', ['===']]]);
11
+ const logical = new Map([['&&', '||'], ['||', '&&'], ['??', '&&']]);
12
+ const booleanOperators = new Set(['!=', '!==', '&&', '<', '<=', '==', '===', '>', '>=', '||']);
13
+ const methods = new Map([['charAt', null], ['endsWith', 'startsWith'], ['every', 'some'], ['filter', null], ['reverse', null],
14
+ ['slice', null], ['sort', null], ['substr', null], ['substring', null], ['toLocaleLowerCase', 'toLocaleUpperCase'],
15
+ ['toLowerCase', 'toUpperCase'], ['trim', null], ['trimEnd', 'trimStart'], ['min', 'max'], ['setDate', 'setTime'],
16
+ ['setFullYear', 'setMonth'], ['setHours', 'setMinutes'], ['setSeconds', 'setMilliseconds'], ['setUTCDate', 'setTime'],
17
+ ['setUTCFullYear', 'setUTCMonth'], ['setUTCHours', 'setUTCMinutes'], ['setUTCSeconds', 'setUTCMilliseconds']]);
18
+ for (const [name, other] of [...methods]) if (other && name !== 'setUTCDate') methods.set(other, name);
19
+
20
+ // Stands for the call that reads the active shift. The renderer puts the helper's name in its place.
21
+ export const shiftPlaceholder = '\u0000shift\u0000';
22
+
23
+ // The targeted rules: edits whose behaviour on the values a test passes can be told from the operands alone, so a
24
+ // recording run knows in which tests an edit would have gone another way. `ignored-operand` drops what one side
25
+ // of a logical operator decides and still evaluates it.
26
+ export const targetedRules = {
27
+ constant: 'equality-constant/v1', nullish: 'nullish-equality/v1', ignored: 'ignored-operand/v1', fallback: 'nullish-fallback/v1',
28
+ arithmetic: 'arithmetic-swap/v1', extreme: 'extreme-swap/v1', rounding: 'rounding-swap/v1', ends: 'sequence-end/v1',
29
+ order: 'sort-order/v1', awaited: 'await-dropped/v1', copy: 'copy-dropped/v1',
30
+ spreadDrop: 'spread-property-drop/v1', prefixSubstring: 'prefix-to-substring/v1', replaceMultiplicity: 'replace-multiplicity/v1',
31
+ clampBound: 'clamp-bound/v1', literalSetPrune: 'literal-set-prune/v1', mergePrecedence: 'merge-precedence/v1',
32
+ quantifierSwap: 'quantifier-swap/v1', regexAnchor: 'regex-anchor-slack/v1', cleanupDropped: 'cleanup-dropped/v1',
33
+ };
34
+ // Two other operators for each arithmetic one: its inverse, and the one the same operands most often agree on.
35
+ // (Maps: a method may be named like a property every object has.)
36
+ const arithmeticSwaps = new Map([['+', ['-', '*']], ['-', ['+', '/']], ['*', ['/', '+']], ['/', ['*', '%']], ['%', ['/', '+']]]);
37
+ const roundingSwaps = new Map([['floor', ['ceil', 'round', 'trunc']], ['ceil', ['floor', 'round']], ['round', ['floor', 'ceil']], ['trunc', ['floor', 'round']]]);
38
+ const endSwaps = new Map([['find', 'findLast'], ['findLast', 'find'], ['findIndex', 'findLastIndex'], ['findLastIndex', 'findIndex'],
39
+ ['indexOf', 'lastIndexOf'], ['lastIndexOf', 'indexOf']]);
40
+ const ignoredValue = { '&&': 'true', '||': 'false', '??': 'undefined' };
41
+
42
+ export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, ts = loadTypeScript() } = {}) {
43
+ const kind = dialect === 'tsx' ? ts.ScriptKind.TSX : dialect === 'ts' ? ts.ScriptKind.TS : undefined;
44
+ const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
45
+ const K = ts.SyntaxKind;
46
+ const starts = tree.getLineStarts();
47
+ const lineOf = offset => {
48
+ let low = 0;
49
+ let high = starts.length - 1;
50
+ while (low < high) {
51
+ const middle = (low + high + 1) >> 1;
52
+ if (starts[middle] <= offset) low = middle;
53
+ else high = middle - 1;
54
+ }
55
+ return low;
56
+ };
57
+ const begin = node => node.getStart(tree);
58
+ const source = node => text.slice(begin(node), node.end);
59
+ const strip = node => {
60
+ while (node && ts.isParenthesizedExpression(node)) node = node.expression;
61
+ return node;
62
+ };
63
+ // The parent as a parser without parenthesis nodes sees it, with the child that parent holds.
64
+ const up = node => {
65
+ let child = node;
66
+ while (ts.isParenthesizedExpression(child.parent)) child = child.parent;
67
+ return [child.parent, child];
68
+ };
69
+ const operatorOf = node => ts.isBinaryExpression(node) ? text.slice(begin(node.operatorToken), node.operatorToken.end) : undefined;
70
+ const isAssignment = node => ts.isBinaryExpression(node) &&
71
+ node.operatorToken.kind >= K.FirstAssignment && node.operatorToken.kind <= K.LastAssignment;
72
+ const isLogical = node => ts.isBinaryExpression(node) && logical.has(operatorOf(node));
73
+ const isBinary = node => ts.isBinaryExpression(node) && !isAssignment(node) && !isLogical(node) &&
74
+ node.operatorToken.kind !== K.CommaToken;
75
+ const isString = node => ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node);
76
+ const isMember = node => ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node);
77
+ const merges = unit => '+-*/=&|?!<>%'.includes(text[unit] ?? ' ');
78
+ const swapToken = (node, token, replacement) => text.slice(begin(node), begin(token)) + (merges(begin(token) - 1) ? ' ' : '') +
79
+ replacement + (merges(token.end) ? ' ' : '') + text.slice(token.end, node.end);
80
+
81
+ // Array and object literals on the left of an assignment are patterns, not values.
82
+ function isAssignmentTarget(node) {
83
+ const [parent, child] = up(node);
84
+ if (isAssignment(parent) && parent.left === child) return true;
85
+ if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === child) return true;
86
+ if (ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) return isAssignmentTarget(parent);
87
+ if (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isSpreadAssignment(parent)) {
88
+ return isAssignmentTarget(parent.parent);
89
+ }
90
+ return false;
91
+ }
92
+
93
+ function canHoldSwitch(node) {
94
+ const [parent, child] = up(node);
95
+ const chained = (isMember(node) || ts.isCallExpression(node) || ts.isNonNullExpression(node)) && (
96
+ (isMember(parent) && parent.expression === child) || ts.isNonNullExpression(parent) ||
97
+ (ts.isCallExpression(parent) && parent.expression === child));
98
+ return !chained && !ts.isTaggedTemplateExpression(parent) && !ts.isDeleteExpression(parent) &&
99
+ !(isAssignment(parent) && parent.left === child);
100
+ }
101
+
102
+ function containsSuperCall(node) {
103
+ let found = false;
104
+ (function look(inner) {
105
+ if (found) return;
106
+ if (ts.isCallExpression(inner) && inner.expression.kind === K.SuperKeyword) found = true;
107
+ else ts.forEachChild(inner, look);
108
+ })(node);
109
+ return found;
110
+ }
111
+
112
+ // `// Stryker disable` and `// Stryker restore` comments, read the way StrykerJS reads them: a comment counts
113
+ // when it leads a node, it takes effect from that node on, and `next-line` limits it to mutations that start on
114
+ // that node's line. The newest matching rule decides.
115
+ const directive = /^\s?Stryker (disable|restore)(?: (next-line))? ([a-zA-Z, ]+)(?::(.+)?)?/;
116
+ const hasDirectives = text.includes('Stryker ');
117
+ let rule = null;
118
+ let directivesReadTo = 0;
119
+ function readDirectives(node) {
120
+ if (!hasDirectives || node.pos < directivesReadTo) return;
121
+ directivesReadTo = begin(node);
122
+ const comments = [...ts.getTrailingCommentRanges(text, node.pos) ?? [], ...ts.getLeadingCommentRanges(text, node.pos) ?? []];
123
+ for (const comment of comments.sort((a, b) => a.pos - b.pos)) {
124
+ const value = text.slice(comment.pos + 2, comment.kind === K.MultiLineCommentTrivia ? comment.end - 2 : comment.end);
125
+ const match = directive.exec(value);
126
+ if (!match) continue;
127
+ const [, type, scope, names, reason] = match;
128
+ rule = { names: names.split(',').map(name => name.trim().toLowerCase()), line: scope ? lineOf(begin(node)) : undefined,
129
+ reason: type === 'disable' ? (reason ?? 'Ignored using a comment').trim() : undefined, previous: rule };
130
+ }
131
+ }
132
+ function ignoreReason(name, line, from = rule) {
133
+ for (let current = from; current; current = current.previous) {
134
+ if ((current.line === undefined || current.line === line) && (current.names.includes(name.toLowerCase()) || current.names.includes('all'))) {
135
+ return current.reason;
136
+ }
137
+ }
138
+ return undefined;
139
+ }
140
+
141
+ const mutations = [];
142
+ let live = 0;
143
+ // Code that a probe does not evaluate again (the index in `list[list.length - 1]`) holds no edit of its own.
144
+ const unprobed = [];
145
+ function add(name, node, replacement, placement, extra, from) {
146
+ const start = begin(node);
147
+ if (extra?.targeted && unprobed.some(([from, to]) => from <= start && node.end <= to)) return;
148
+ for (let line = lineOf(start); line <= lineOf(node.end); line++) if (!selected(line + 1)) return;
149
+ const ignored = ignoreReason(name, lineOf(start), from);
150
+ // A shift switch is not a mutation of the set, so it does not count for the rules about statement removals.
151
+ if (ignored === undefined && extra?.shift === undefined && extra?.targeted === undefined) live++;
152
+ mutations.push({ name, start, end: node.end, replacement, ...(placement ?? expressionPlacement(node, replacement)), ...extra,
153
+ ...(ignored === undefined ? {} : { ignored }) });
154
+ }
155
+
156
+ let statementStart;
157
+ function expressionPlacement(node, replacement) {
158
+ let holder = node;
159
+ while (!canHoldSwitch(holder)) holder = up(holder)[0];
160
+ const start = begin(holder);
161
+ const [parent, child] = up(holder);
162
+ const statement = ts.isExpressionStatement(holder.parent);
163
+ // An arrow function takes its name from the variable, property or field it initializes.
164
+ const names = ts.isArrowFunction(holder) && parent.initializer === child && parent.name && ts.isIdentifier(parent.name) &&
165
+ (ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) || ts.isPropertyDeclaration(parent));
166
+ const named = names ? parent.name.text : undefined;
167
+ return {
168
+ kind: 'expression', placement: [start, holder.end], statement, leading: !statement && start === statementStart, named,
169
+ // Spaces keep the replacement from merging with a neighbouring token.
170
+ mutated: text.slice(start, begin(node)) + ' ' + replacement + ' ' + text.slice(node.end, holder.end),
171
+ };
172
+ }
173
+
174
+ function skipped(node) {
175
+ // StrykerJS leaves `x as T` alone: a switch inside it would change what the assertion is checked against.
176
+ return ts.isTypeNode(node) || ts.isAsExpression(node) || ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) ||
177
+ ts.isDecorator(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isEnumDeclaration(node) ||
178
+ ts.isTypeParameterDeclaration(node) || node.modifiers?.some(modifier => modifier.kind === K.DeclareKeyword);
179
+ }
180
+
181
+ function binary(node) {
182
+ const operator = operatorOf(node);
183
+ const token = node.operatorToken;
184
+ if (isBinary(node)) {
185
+ const left = strip(node.left);
186
+ const leftKind = isBinary(left) ? strip(left.right) : left;
187
+ if (arithmetic.has(operator) && !isString(strip(node.right)) && !isString(leftKind)) {
188
+ add('ArithmeticOperator', node, swapToken(node, token, arithmetic.get(operator)));
189
+ }
190
+ for (const replacement of equality.get(operator) ?? []) {
191
+ add('EqualityOperator', node, swapToken(node, token, replacement), undefined, { operator: [begin(token), replacement] });
192
+ }
193
+ // The focused analysis moves a comparison's right side by an integer it only knows after a recorded run:
194
+ // another threshold, or one step tighter. One switch per comparison takes that amount at run time.
195
+ if (shifts && ['<', '<=', '>', '>='].includes(operator)) {
196
+ add('ComparisonShift', node, `${text.slice(begin(node), token.end)} ((${source(node.right)}) + ${shiftPlaceholder})`, undefined, { shift: begin(token) });
197
+ }
198
+ } else if (isLogical(node)) {
199
+ // A different precedence would regroup an unparenthesized operand, so operands keep their own group.
200
+ const operand = side => ts.isBinaryExpression(side) ? `(${source(side)})` : source(side);
201
+ add('LogicalOperator', node, `${operand(node.left)} ${logical.get(operator)} ${operand(node.right)}`);
202
+ } else if (assignment.has(operator) && !(isString(strip(node.right)) && !['&&=', '||=', '??='].includes(operator))) {
203
+ add('AssignmentOperator', node, swapToken(node, token, assignment.get(operator)));
204
+ }
205
+ }
206
+
207
+ // Whether only the truth of the expression's value is used: as a condition, under `!`, or as an operand of a
208
+ // logical operator that is itself used that way.
209
+ function onlyTruthUsed(node) {
210
+ for (let [parent, child] = up(node); ; [parent, child] = up(parent)) {
211
+ if (ts.isPrefixUnaryExpression(parent) && parent.operator === K.ExclamationToken) return true;
212
+ if ((ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) && parent.expression === child) return true;
213
+ if ((ts.isForStatement(parent) || ts.isConditionalExpression(parent)) && parent.condition === child) return true;
214
+ if (!isLogical(parent) || operatorOf(parent) === '??') return false;
215
+ }
216
+ }
217
+
218
+ // A right operand that awaits or yields cannot be evaluated inside the function a probe wraps it in, and a
219
+ // direct eval there would declare its variables in that function.
220
+ function staysInPlace(node) {
221
+ let found = false;
222
+ (function look(inner) {
223
+ if (found) return;
224
+ if (ts.isAwaitExpression(inner) || ts.isYieldExpression(inner) ||
225
+ (ts.isCallExpression(inner) && ts.isIdentifier(strip(inner.expression)) && strip(inner.expression).text === 'eval')) found = true;
226
+ else if (!ts.isFunctionLike(inner)) ts.forEachChild(inner, look);
227
+ // A computed name belongs to the code around its method.
228
+ else if (inner.name && ts.isComputedPropertyName(inner.name)) look(inner.name);
229
+ })(node);
230
+ return found;
231
+ }
232
+
233
+ // A written value: evaluating it has no effect and always gives the same.
234
+ function written(node) {
235
+ const inner = strip(node);
236
+ return ts.isNumericLiteral(inner) || ts.isBigIntLiteral(inner) || ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner) ||
237
+ [K.TrueKeyword, K.FalseKeyword, K.NullKeyword].includes(inner.kind) || (ts.isIdentifier(inner) && inner.text === 'undefined') ||
238
+ (ts.isPrefixUnaryExpression(inner) && inner.operator === K.MinusToken && (ts.isNumericLiteral(inner.operand) || ts.isBigIntLiteral(inner.operand)));
239
+ }
240
+ const writtenFalsy = node => {
241
+ const inner = strip(node);
242
+ const number = ts.isPrefixUnaryExpression(inner) ? inner.operand : inner;
243
+ return written(node) && (['false', 'null', 'undefined'].includes(source(inner)) ||
244
+ (ts.isNumericLiteral(number) && Number(number.text) === 0) || (ts.isBigIntLiteral(number) && /^0[box]?0*n$/i.test(number.text)) ||
245
+ ((ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) && inner.text === ''));
246
+ };
247
+
248
+ const nullishLiteral = node => {
249
+ const inner = strip(node);
250
+ return inner.kind === K.NullKeyword ? 'null' : ts.isIdentifier(inner) && inner.text === 'undefined' ? 'undefined' : undefined;
251
+ };
252
+
253
+ // An edit of one expression that a probe can stand for. `operands` are the parts the probe evaluates, in order.
254
+ function probed(node, operator, operands, shared = {}) {
255
+ // The probe stands where the expression stands, inside its own parentheses: what encloses them (a template
256
+ // tag, `delete`) still applies to what the probe gives.
257
+ const statement = ts.isExpressionStatement(node.parent);
258
+ const boolean = onlyTruthUsed(node);
259
+ const spans = operands.map(operand => [begin(operand), operand.end]);
260
+ return (rule, form, replacement, more) => add(rule, node, replacement, { kind: 'observed', placement: [begin(node), node.end], statement,
261
+ leading: !statement && begin(node) === statementStart, mutated: ` ${replacement} ` },
262
+ { targeted: { operator, form, boolean, left: source(operands[0]), ...shared, ...more }, operands: spans });
263
+ }
264
+
265
+ // A different precedence would regroup an unparenthesized operand, so operands keep their own group.
266
+ const grouped = side => ts.isBinaryExpression(side) ? `(${source(side)})` : source(side);
267
+
268
+ function targetedEdits(node) {
269
+ const operator = operatorOf(node);
270
+ const token = node.operatorToken;
271
+ const left = source(node.left);
272
+ const right = source(node.right);
273
+ const boolean = onlyTruthUsed(node);
274
+ const edit = probed(node, operator, [node.left, node.right]);
275
+ if (isBinary(node) && arithmeticSwaps.has(operator)) {
276
+ const leftKind = isBinary(strip(node.left)) ? strip(strip(node.left).right) : strip(node.left);
277
+ // Text is joined with `+`; another operator there is a type error and not a wrong program.
278
+ if (isString(strip(node.right)) || isString(leftKind)) return;
279
+ for (const swap of arithmeticSwaps.get(operator)) edit(targetedRules.arithmetic, swap, `(${grouped(node.left)} ${swap} ${grouped(node.right)})`);
280
+ return;
281
+ }
282
+ if (isBinary(node) && ['===', '!==', '==', '!='].includes(operator)) {
283
+ edit(targetedRules.constant, 'true', `(${left}, ${right}, true)`);
284
+ edit(targetedRules.constant, 'false', `(${left}, ${right}, false)`);
285
+ const written = [nullishLiteral(node.left), nullishLiteral(node.right)];
286
+ // Beside a written null or undefined, the strict and the loose comparison differ for the other of the two.
287
+ if ((written[0] === undefined) === (written[1] === undefined)) return;
288
+ const literalSide = written[0] === undefined ? 1 : 0;
289
+ const other = written[literalSide] === 'null' ? 'undefined' : 'null';
290
+ const subject = literalSide ? left : right;
291
+ if (operator.length === 3) {
292
+ edit(targetedRules.nullish, 'loose', swapToken(node, token, operator.slice(0, 2)), { literalSide, differsFor: other, subject });
293
+ } else {
294
+ const strict = operator + '=';
295
+ edit(targetedRules.nullish, 'strict', swapToken(node, token, strict), { literalSide, differsFor: other, subject });
296
+ edit(targetedRules.nullish, 'other', literalSide ? `${left} ${strict} ${other}` : `${other} ${strict} ${right}`,
297
+ { literalSide, differsFor: written[literalSide], subject });
298
+ }
299
+ } else if (isLogical(node) && !staysInPlace(node.right)) {
300
+ const operand = grouped;
301
+ const more = { thunk: true, ...(written(node.right) ? { pureRight: true } : {}) };
302
+ edit(targetedRules.ignored, 'left', `(${left}, ${right})`, more);
303
+ edit(targetedRules.ignored, 'right', `(${left} ${operator} (${right}, ${ignoredValue[operator]}))`, more);
304
+ // Where only the truth is used, a written falsy fallback makes `??` and `||` the same for every value.
305
+ if (boolean && writtenFalsy(node.right)) return;
306
+ if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, { ...more, evidence: true });
307
+ // Where only the truth of the value is used, nobody writes `??` for `||`.
308
+ else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, { ...more, evidence: true });
309
+ }
310
+ }
311
+
312
+ const rename = (node, name, to) => text.slice(begin(node), begin(name)) + to + text.slice(name.end, node.end);
313
+
314
+ // A file that binds the name Math itself (a parameter, a variable, a function, an import) is not calling the
315
+ // built-in one.
316
+ let bindsMath;
317
+ function ownMath() {
318
+ if (bindsMath === undefined) {
319
+ bindsMath = false;
320
+ if (/\bMath\b(?!\s*(?:\.|\?\.|\[))/.test(text)) {
321
+ (function look(inner) {
322
+ if (bindsMath) return;
323
+ const name = inner.name;
324
+ bindsMath = name !== undefined && ts.isIdentifier(name) && name.text === 'Math' && (ts.isParameter(inner) || ts.isVariableDeclaration(inner) ||
325
+ ts.isBindingElement(inner) || ts.isFunctionDeclaration(inner) || ts.isClassDeclaration(inner) || ts.isFunctionExpression(inner) ||
326
+ ts.isClassExpression(inner) || ts.isImportSpecifier(inner) ||
327
+ ts.isImportClause(inner) || ts.isNamespaceImport(inner));
328
+ if (!bindsMath) ts.forEachChild(inner, look);
329
+ })(tree);
330
+ }
331
+ }
332
+ return bindsMath;
333
+ }
334
+
335
+ function isMathCall(node, expectedName) {
336
+ if (!ts.isCallExpression(node) || ts.isOptionalChain(node) || node.arguments.length !== 2 || node.arguments.some(ts.isSpreadElement)) return false;
337
+ const c = node.expression;
338
+ return ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === 'Math' &&
339
+ ts.isIdentifier(c.name) && c.name.text === expectedName;
340
+ }
341
+
342
+ function hasUnescapedTrailingDollar(pattern) {
343
+ if (!pattern.endsWith('$')) return false;
344
+ let slashes = 0;
345
+ for (let i = pattern.length - 2; i >= 0 && pattern[i] === '\\'; i--) slashes++;
346
+ return slashes % 2 === 0;
347
+ }
348
+
349
+ function compilesRegex(pattern, flags) {
350
+ try { new RegExp(pattern, flags); return true; } catch { return false; }
351
+ }
352
+
353
+ function literalPrimitiveValue(node) {
354
+ const inner = strip(node);
355
+ if (ts.isNumericLiteral(inner)) return { ok: true, value: Number(inner.text) };
356
+ if (ts.isPrefixUnaryExpression(inner) && inner.operator === K.MinusToken && ts.isNumericLiteral(inner.operand)) {
357
+ return { ok: true, value: -Number(inner.operand.text) };
358
+ }
359
+ if (ts.isBigIntLiteral(inner)) return { ok: true, value: BigInt(inner.text.slice(0, -1)) };
360
+ if (ts.isPrefixUnaryExpression(inner) && inner.operator === K.MinusToken && ts.isBigIntLiteral(inner.operand)) {
361
+ return { ok: true, value: -BigInt(inner.operand.text.slice(0, -1)) };
362
+ }
363
+ if (ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) return { ok: true, value: inner.text };
364
+ if (inner.kind === K.TrueKeyword) return { ok: true, value: true };
365
+ if (inner.kind === K.FalseKeyword) return { ok: true, value: false };
366
+ if (inner.kind === K.NullKeyword) return { ok: true, value: null };
367
+ return { ok: false };
368
+ }
369
+
370
+ const skippedMathCalls = new Set();
371
+
372
+ function targetedCall(node) {
373
+ const callee = node.expression;
374
+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name) || ts.isOptionalChain(node) ||
375
+ callee.expression.kind === K.SuperKeyword || node.arguments.some(ts.isSpreadElement)) return;
376
+ const name = callee.name.text;
377
+ const args = node.arguments;
378
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === 'Math') {
379
+ if (ownMath() || skippedMathCalls.has(node)) return;
380
+ if ((name === 'max' || name === 'min') && args.length === 2) {
381
+ const innerName = name === 'max' ? 'min' : 'max';
382
+ const innerPos = isMathCall(strip(args[0]), innerName) ? 0 : isMathCall(strip(args[1]), innerName) ? 1 : -1;
383
+ if (innerPos !== -1 && !staysInPlace(args[0]) && !staysInPlace(args[1])) {
384
+ const inner = strip(args[innerPos]);
385
+ const outerOther = args[1 - innerPos];
386
+ const [ia, ib] = inner.arguments;
387
+ const ordered = innerPos === 0 ? [ia, ib, outerOther] : [outerOther, ia, ib];
388
+ const pures = ordered.map(arg => written(arg) ? 1 : 0);
389
+ const beforeClamp = mutations.length;
390
+ const edit = probed(node, 'clamp', ordered, { clampMeta: { outer: name, inner: innerName, innerPos, pures } });
391
+ edit(targetedRules.clampBound, 'dropOuter', source(inner), { boundKind: name === 'min' ? 'upper' : 'lower' });
392
+ const aLit = written(ia);
393
+ const bLit = written(ib);
394
+ if (aLit !== bLit) {
395
+ const keepIdx = aLit ? 1 : 0;
396
+ const keptNode = inner.arguments[keepIdx];
397
+ const innerReplacement = innerPos === 0 ? `Math.${name}(${source(keptNode)}, ${source(outerOther)})`
398
+ : `Math.${name}(${source(outerOther)}, ${source(keptNode)})`;
399
+ edit(targetedRules.clampBound, keepIdx === 0 ? 'dropInnerB' : 'dropInnerA', innerReplacement,
400
+ { boundKind: innerName === 'min' ? 'upper' : 'lower' });
401
+ }
402
+ if (mutations.length > beforeClamp) skippedMathCalls.add(inner);
403
+ return;
404
+ }
405
+ probed(node, name, [args[0], args[1]])(targetedRules.extreme, name === 'max' ? 'min' : 'max', rename(node, callee.name, name === 'max' ? 'min' : 'max'));
406
+ } else if (roundingSwaps.has(name) && args.length === 1) {
407
+ const edit = probed(node, name, [args[0]]);
408
+ for (const swap of roundingSwaps.get(name)) edit(targetedRules.rounding, swap, rename(node, callee.name, swap));
409
+ }
410
+ } else if ((name === 'sort' || name === 'toSorted') && args.length === 1 && ascending(args[0])) {
411
+ // Without its comparison a sort orders numbers as text: 10 before 9.
412
+ probed(node, name, [callee.expression, args[0]])(targetedRules.order, 'default', text.slice(begin(node), args.pos) + ')');
413
+ } else if (endSwaps.has(name) && args.length === 1) {
414
+ probed(node, name, [callee.expression, args[0]])(targetedRules.ends, endSwaps.get(name), rename(node, callee.name, endSwaps.get(name)));
415
+ } else if (name === 'at' && args.length === 1 && ['0', '-1'].includes(source(args[0]).replace(/\s/g, ''))) {
416
+ const first = source(args[0]) === '0';
417
+ probed(node, first ? 'at0' : 'at-1', [callee.expression])(targetedRules.ends, first ? 'at-1' : 'at0',
418
+ text.slice(begin(node), begin(args[0])) + (first ? '-1' : '0') + text.slice(args[0].end, node.end));
419
+ } else if ((name === 'startsWith' || name === 'endsWith') && args.length === 1 && !staysInPlace(args[0])) {
420
+ probed(node, name, [callee.expression, args[0]])(targetedRules.prefixSubstring, 'includes', rename(node, callee.name, 'includes'));
421
+ } else if ((name === 'replace' || name === 'replaceAll') && args.length === 2 && !ts.isRegularExpressionLiteral(strip(args[0])) &&
422
+ !staysInPlace(args[0]) && !staysInPlace(args[1])) {
423
+ const swapped = name === 'replace' ? 'replaceAll' : 'replace';
424
+ probed(node, name, [callee.expression, args[0], args[1]])(targetedRules.replaceMultiplicity, swapped, rename(node, callee.name, swapped));
425
+ } else if ((name === 'every' || name === 'some') && args.length === 1 && !staysInPlace(args[0])) {
426
+ const swapped = name === 'every' ? 'some' : 'every';
427
+ probed(node, name, [callee.expression, args[0]])(targetedRules.quantifierSwap, swapped, rename(node, callee.name, swapped));
428
+ } else if (name === 'includes' && args.length === 1 && !staysInPlace(args[0])) {
429
+ const recv = strip(callee.expression);
430
+ if (ts.isArrayLiteralExpression(recv) && recv.elements.length >= 2 && recv.elements.length <= 16) {
431
+ const parsed = recv.elements.map(el => ts.isSpreadElement(el) ? { ok: false } : literalPrimitiveValue(el));
432
+ if (parsed.every(entry => entry.ok)) {
433
+ const elems = recv.elements.map(el => source(el));
434
+ // SameValueZero duplicate values cannot change `includes` when only one copy is pruned.
435
+ const sameValueZero = (a, b) => a === b || (a !== a && b !== b);
436
+ const counts = parsed.map(a => parsed.filter(b => sameValueZero(a.value, b.value)).length);
437
+ const prunable = counts.map((count, idx) => count === 1 ? idx : -1).filter(idx => idx >= 0);
438
+ if (prunable.length) {
439
+ const edit = probed(node, 'literalIncludes', [args[0]], { setElems: elems, argName: source(args[0]) });
440
+ for (const j of prunable) {
441
+ const kept = elems.filter((_, idx) => idx !== j);
442
+ edit(targetedRules.literalSetPrune, `prune:${j}`, `[${kept.join(', ')}].includes(${source(args[0])})`, { pruned: elems[j] });
443
+ }
444
+ }
445
+ }
446
+ }
447
+ } else if (name === 'test' && args.length === 1 && !staysInPlace(args[0])) {
448
+ const recv = strip(callee.expression);
449
+ if (recv.kind === K.RegularExpressionLiteral) {
450
+ const raw = source(recv);
451
+ const close = raw.lastIndexOf('/');
452
+ const pattern = raw.slice(1, close);
453
+ const flags = raw.slice(close + 1);
454
+ const alts = [];
455
+ if (pattern.startsWith('^') && compilesRegex(pattern.slice(1), flags)) {
456
+ alts.push(['dropStart', pattern.slice(1)]);
457
+ }
458
+ if (hasUnescapedTrailingDollar(pattern) && compilesRegex(pattern.slice(0, -1), flags)) {
459
+ alts.push(['dropEnd', pattern.slice(0, -1)]);
460
+ }
461
+ if (alts.length) {
462
+ const altMap = Object.fromEntries(alts);
463
+ const edit = probed(node, 'regexTest', [args[0]], { regexMeta: { pattern, flags, alts: altMap }, argName: source(args[0]) });
464
+ for (const [form, altPattern] of alts) {
465
+ edit(targetedRules.regexAnchor, form, `/${altPattern || '(?:)'}/${flags}.test(${source(args[0])})`);
466
+ }
467
+ }
468
+ }
469
+ }
470
+ }
471
+
472
+ // `(a, b) => a - b`: the comparison that puts numbers in ascending order.
473
+ function ascending(node) {
474
+ if (!ts.isArrowFunction(node) || node.parameters.length !== 2 || !node.parameters.every(parameter => ts.isIdentifier(parameter.name) && !parameter.initializer)) return false;
475
+ const body = ts.isBlock(node.body) ? undefined : strip(node.body);
476
+ return body !== undefined && ts.isBinaryExpression(body) && operatorOf(body) === '-' && ts.isIdentifier(strip(body.left)) && ts.isIdentifier(strip(body.right)) &&
477
+ strip(body.left).text === node.parameters[0].name.text && strip(body.right).text === node.parameters[1].name.text;
478
+ }
479
+
480
+ function insideFinallyBlock(node) {
481
+ let cur = node.parent;
482
+ let prev = node;
483
+ while (cur) {
484
+ if (ts.isFunctionLike(cur) || ts.isClassLike(cur)) return false;
485
+ if (ts.isTryStatement(cur) && cur.finallyBlock === prev) return true;
486
+ prev = cur;
487
+ cur = cur.parent;
488
+ }
489
+ return false;
490
+ }
491
+
492
+ // Edits that no recording can judge: they change when something happens or which object is which, not a value.
493
+ function unobservedEdits(node) {
494
+ if (ts.isExpressionStatement(node)) {
495
+ const expr = strip(node.expression);
496
+ const isAwaited = ts.isAwaitExpression(expr);
497
+ const call = isAwaited ? strip(expr.expression) : expr;
498
+ if (ts.isCallExpression(call) && call.expression.kind !== K.SuperKeyword && insideFinallyBlock(node)) {
499
+ add(targetedRules.cleanupDropped, node, ';', { kind: 'statement', placement: [begin(node), node.end], mutated: ' ;' },
500
+ { targeted: { operator: 'cleanup', form: 'dropped', left: source(call) } });
501
+ return;
502
+ }
503
+ // The call goes on alone: what follows no longer waits for it. `void` keeps it an expression whatever it
504
+ // begins with (a parenthesis, a function that is called at once), and the space keeps it off an `else`.
505
+ if (isAwaited && ts.isCallExpression(call)) {
506
+ add(targetedRules.awaited, node, `void ${source(call)};`, { kind: 'statement', placement: [begin(node), node.end], mutated: ` void ${source(call)};` },
507
+ { targeted: { operator: 'await', form: 'dropped', left: source(call) } });
508
+ }
509
+ return;
510
+ }
511
+ // `[...list]` and `{ ...record }` as the whole literal are copies (or iterable/spread conversions):
512
+ // probing records whether the operand is actually an array or a plain object.
513
+ const isArray = ts.isArrayLiteralExpression(node);
514
+ const only = isArray ? node.elements : ts.isObjectLiteralExpression(node) ? node.properties : undefined;
515
+ if (!only || isAssignmentTarget(node)) return;
516
+ if (only.length === 1 && (ts.isSpreadElement(only[0]) || ts.isSpreadAssignment(only[0]))) {
517
+ const original = source(only[0].expression);
518
+ probed(node, isArray ? 'copyArray' : 'copyObject', [only[0].expression])(targetedRules.copy, 'dropped', `(${original})`);
519
+ return;
520
+ }
521
+ // `{ ...a, ...b }`: swap merge precedence to `{ ...b, ...a }`.
522
+ if (!isArray && only.length === 2 && ts.isSpreadAssignment(only[0]) && ts.isSpreadAssignment(only[1]) &&
523
+ !staysInPlace(only[0].expression) && !staysInPlace(only[1].expression)) {
524
+ const a = source(only[0].expression);
525
+ const b = source(only[1].expression);
526
+ const pureMerge = ts.isIdentifier(strip(only[0].expression)) && ts.isIdentifier(strip(only[1].expression)) ? 1 : 0;
527
+ probed(node, 'mergeSpread', [only[0].expression, only[1].expression], { right: b, pureMerge })(
528
+ targetedRules.mergePrecedence, 'swap', `{ ...${b}, ...${a} }`,
529
+ );
530
+ return;
531
+ }
532
+ // `{ ...base, k1: v1, k2: v2 }`: drop one explicit static property at a time.
533
+ if (!isArray && only.length >= 2 && ts.isSpreadAssignment(only[0])) {
534
+ const rest = only.slice(1);
535
+ const keys = [];
536
+ const values = [];
537
+ const pureProps = [];
538
+ const seenKeys = new Set();
539
+ for (const prop of rest) {
540
+ if (!ts.isPropertyAssignment(prop) && !ts.isShorthandPropertyAssignment(prop)) return;
541
+ const name = prop.name;
542
+ let key;
543
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) key = name.text;
544
+ else return;
545
+ if (key === '__proto__' || seenKeys.has(key)) return;
546
+ const valueNode = ts.isShorthandPropertyAssignment(prop) ? prop.name : prop.initializer;
547
+ if (staysInPlace(valueNode)) return;
548
+ // Anonymous functions and classes receive inferred `.name` from their property key in an object literal,
549
+ // including through erased TypeScript wrappers (`as`, `satisfies`, `<T>x`, `!`).
550
+ let innerVal = valueNode;
551
+ while (innerVal && (ts.isParenthesizedExpression(innerVal) || ts.isAsExpression(innerVal) ||
552
+ ts.isSatisfiesExpression(innerVal) || ts.isTypeAssertionExpression(innerVal) || ts.isNonNullExpression(innerVal))) {
553
+ innerVal = innerVal.expression;
554
+ }
555
+ if (ts.isArrowFunction(innerVal) || (ts.isFunctionExpression(innerVal) && !innerVal.name) ||
556
+ (ts.isClassExpression(innerVal) && !innerVal.name)) return;
557
+ seenKeys.add(key);
558
+ keys.push(key);
559
+ values.push(valueNode);
560
+ pureProps.push(written(valueNode) ? 1 : 0);
561
+ }
562
+ const edit = probed(node, 'spreadUpdate', [only[0].expression, ...values], { spreadKeys: keys, pureProps });
563
+ for (let j = 0; j < rest.length; j++) {
564
+ const kept = [only[0], ...rest.filter((_, idx) => idx !== j)];
565
+ edit(targetedRules.spreadDrop, `drop:${j}`, `{ ${kept.map(prop => source(prop)).join(', ')} }`, { key: keys[j] });
566
+ }
567
+ }
568
+ }
569
+
570
+ // A name or a chain of property names: reading it twice gives the same and does nothing else.
571
+ const plainReference = node => ts.isIdentifier(node) || node.kind === K.ThisKeyword ||
572
+ (ts.isPropertyAccessExpression(node) && !node.questionDotToken && ts.isIdentifier(node.name) && plainReference(node.expression));
573
+
574
+ function targetedElement(node) {
575
+ // What the element is used for shows above its parentheses and its non-null assertions.
576
+ let [parent, child] = up(node);
577
+ while (ts.isNonNullExpression(parent)) [parent, child] = up(parent);
578
+ if (ts.isNewExpression(parent) && parent.expression === child) return;
579
+ const written = isAssignmentTarget(child) || ts.isDeleteExpression(parent) ||
580
+ ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && [K.PlusPlusToken, K.MinusMinusToken].includes(parent.operator)) ||
581
+ (isAssignment(parent) && parent.left === child);
582
+ // As a callee the element is called with its sequence as `this`.
583
+ const called = (ts.isCallExpression(parent) && parent.expression === child) || (ts.isTaggedTemplateExpression(parent) && parent.tag === child);
584
+ if (written || called || ts.isOptionalChain(node) || node.expression.kind === K.SuperKeyword) return;
585
+ const index = strip(node.argumentExpression);
586
+ const receiver = source(node.expression);
587
+ if (ts.isNumericLiteral(index) && index.text === '0') {
588
+ probed(node, 'idx0', [node.expression])(targetedRules.ends, 'at-1', `${receiver}.at(-1)`);
589
+ } else if (ts.isBinaryExpression(index) && operatorOf(index) === '-' && ts.isNumericLiteral(strip(index.right)) && strip(index.right).text === '1' &&
590
+ ts.isPropertyAccessExpression(strip(index.left)) && strip(index.left).name.text === 'length' && plainReference(node.expression) &&
591
+ source(strip(index.left).expression) === receiver) {
592
+ probed(node, 'idxLast', [node.expression])(targetedRules.ends, 'idx0', `${receiver}[0]`);
593
+ unprobed.push([begin(node.argumentExpression), node.argumentExpression.end]);
594
+ }
595
+ }
596
+
597
+ function condition(node) {
598
+ const [parent, child] = up(node);
599
+ const loopTest = (ts.isForStatement(parent) && parent.condition === child) ||
600
+ ((ts.isWhileStatement(parent) || ts.isDoStatement(parent)) && parent.expression === child);
601
+ if (loopTest) add('ConditionalExpression', node, 'false');
602
+ else if (ts.isIfStatement(parent) && parent.expression === child) {
603
+ add('ConditionalExpression', node, 'true');
604
+ add('ConditionalExpression', node, 'false');
605
+ } else if ((isBinary(node) || isLogical(node)) && booleanOperators.has(operatorOf(node))) {
606
+ const outer = isLogical(parent) ? operatorOf(parent) : undefined;
607
+ if (outer !== '&&') add('ConditionalExpression', node, 'false');
608
+ if (outer !== '||') add('ConditionalExpression', node, 'true');
609
+ }
610
+ }
611
+
612
+ function block(node) {
613
+ if (ts.isClassStaticBlockDeclaration(node.parent)) return;
614
+ let directives = 0;
615
+ if (ts.isFunctionLike(node.parent)) {
616
+ while (directives < node.statements.length && ts.isExpressionStatement(node.statements[directives]) &&
617
+ ts.isStringLiteral(node.statements[directives].expression)) directives++;
618
+ }
619
+ if (node.statements.length === directives) return;
620
+ if (ts.isConstructorDeclaration(node.parent) && containsSuperCall(node)) {
621
+ const parameterProperty = node.parent.parameters.some(parameter => parameter.modifiers?.some(modifier =>
622
+ [K.PublicKeyword, K.PrivateKeyword, K.ProtectedKeyword, K.ReadonlyKeyword, K.OverrideKeyword].includes(modifier.kind)));
623
+ const initialized = node.parent.parent.members.some(member => ts.isPropertyDeclaration(member) && member.initializer &&
624
+ !ts.isPrivateIdentifier(member.name));
625
+ if (parameterProperty || initialized) return;
626
+ }
627
+ const bodyStart = directives ? node.statements[directives - 1].end : begin(node) + 1;
628
+ add('BlockStatement', node, '{}', { kind: 'block', placement: [begin(node), node.end], bodyStart, bodyEnd: node.end - 1, mutated: '{}',
629
+ functionBody: ts.isFunctionLike(node.parent) });
630
+ }
631
+
632
+ function literal(node) {
633
+ if (ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node)) {
634
+ const empty = ts.isNoSubstitutionTemplateLiteral(node) && node.end - begin(node) === 2;
635
+ add('StringLiteral', node, empty ? '`Stryker was here!`' : '``');
636
+ return;
637
+ }
638
+ const [parent] = up(node);
639
+ const called = ts.isCallExpression(parent) && (parent.expression.kind === K.ImportKeyword ||
640
+ (ts.isIdentifier(parent.expression) && ['require', 'Symbol'].includes(parent.expression.text)));
641
+ const named = parent.name === node || parent.propertyName === node || ts.isComputedPropertyName(parent) || ts.isJsxAttribute(parent) || ts.isExpressionStatement(parent) ||
642
+ ts.isExternalModuleReference(parent) || ts.isModuleDeclaration(parent) || ts.isExportAssignment(parent);
643
+ if (!called && !named) add('StringLiteral', node, node.text.length ? '""' : '"Stryker was here!"');
644
+ if (ts.isNewExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'RegExp' &&
645
+ parent.arguments?.[0] === node) {
646
+ const flags = parent.arguments[1] && ts.isStringLiteral(parent.arguments[1]) ? parent.arguments[1].text : undefined;
647
+ for (const pattern of mutatePattern(node.text, flags)) add('Regex', node, JSON.stringify(pattern));
648
+ }
649
+ }
650
+
651
+ function call(node) {
652
+ const callee = strip(node.expression);
653
+ if (ts.isIdentifier(callee) && callee.text === 'Array' && !ts.isOptionalChain(node)) {
654
+ const prefix = ts.isNewExpression(node) ? 'new Array' : 'Array';
655
+ add('ArrayDeclaration', node, node.arguments?.length ? `${prefix}()` : `${prefix}([])`);
656
+ }
657
+ if (ts.isNewExpression(node) || !ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name)) return;
658
+ const renamed = methods.get(callee.name.text);
659
+ if (renamed === null) add('MethodExpression', node, source(callee.expression));
660
+ else if (renamed !== undefined) {
661
+ add('MethodExpression', node, text.slice(begin(node), begin(callee.name)) + renamed + text.slice(callee.name.end, node.end));
662
+ }
663
+ }
664
+
665
+ function withoutQuestionDot(node) {
666
+ const token = node.questionDotToken;
667
+ const replacement = ts.isPropertyAccessExpression(node) ? '.' : '';
668
+ add('OptionalChaining', node, text.slice(begin(node), begin(token)) + replacement + text.slice(token.end, node.end));
669
+ }
670
+
671
+ // A declaration in a case clause is visible in the clauses after it, so such a clause cannot move into a block.
672
+ const lexical = statement => ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement) ||
673
+ (ts.isVariableStatement(statement) && (statement.declarationList.flags & ts.NodeFlags.BlockScoped) !== 0);
674
+
675
+ function statementMutation(node, replacement, mutated, from) {
676
+ add('CallExpression', node, replacement, { kind: 'statement', placement: [begin(node), node.end], mutated }, undefined, from);
677
+ }
678
+
679
+ // StrykerJS keeps a statement removal beside inner mutations whenever the statement contains a node it skips
680
+ // (a type annotation, type arguments, `as`, a decorator). The built-in set reproduces that so it stays a superset.
681
+ let skips = 0;
682
+ (function visit(node) {
683
+ readDirectives(node);
684
+ // StrykerJS decides a statement's removal when it enters the statement, before comments inside it are read.
685
+ const ruleOnEntry = rule;
686
+ if (skipped(node)) {
687
+ const parent = node.parent;
688
+ const direct = ts.isSatisfiesExpression(parent) || ts.isTypeAssertionExpression(parent) || ts.isHeritageClause(parent);
689
+ // A type written directly after `satisfies` or in `<T>x` is traversed there; only its type arguments are skipped.
690
+ if (!ts.isTypeNode(node) || (direct ? source(node).includes('<') : !ts.isTypeNode(parent))) skips++;
691
+ return;
692
+ }
693
+ const skipsBefore = skips;
694
+ if (ts.isExpressionStatement(node)) statementStart = begin(node.expression);
695
+ const before = mutations.length;
696
+ if (ts.isBinaryExpression(node)) binary(node);
697
+ if (targeted && ts.isBinaryExpression(node)) targetedEdits(node);
698
+ else if (targeted && ts.isCallExpression(node)) targetedCall(node);
699
+ else if (targeted && ts.isElementAccessExpression(node)) targetedElement(node);
700
+ else if (targeted) unobservedEdits(node);
701
+ if (ts.isExpression(node) && !ts.isParenthesizedExpression(node)) condition(node);
702
+ if (ts.isArrayLiteralExpression(node) && !isAssignmentTarget(node)) {
703
+ add('ArrayDeclaration', node, node.elements.length ? '[]' : '["Stryker was here"]');
704
+ } else if (ts.isObjectLiteralExpression(node) && node.properties.length && !isAssignmentTarget(node)) {
705
+ add('ObjectLiteral', node, '{}');
706
+ } else if (ts.isArrowFunction(node) && !ts.isBlock(node.body)) {
707
+ const body = strip(node.body);
708
+ if (!(ts.isIdentifier(body) && body.text === 'undefined')) add('ArrowFunction', node, '() => undefined');
709
+ } else if (ts.isBlock(node)) block(node);
710
+ else if (node.kind === K.TrueKeyword || node.kind === K.FalseKeyword) {
711
+ add('BooleanLiteral', node, node.kind === K.TrueKeyword ? 'false' : 'true');
712
+ } else if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) {
713
+ const operand = source(node.operand);
714
+ const prefix = ts.isPrefixUnaryExpression(node);
715
+ if (node.operator === K.PlusPlusToken || node.operator === K.MinusMinusToken) {
716
+ const swapped = node.operator === K.PlusPlusToken ? '--' : '++';
717
+ add('UpdateOperator', node, prefix ? swapped + operand : operand + swapped);
718
+ } else if (node.operator === K.ExclamationToken) add('BooleanLiteral', node, operand);
719
+ else if (node.operator === K.PlusToken) add('UnaryOperator', node, '- ' + operand);
720
+ else if (node.operator === K.MinusToken) add('UnaryOperator', node, '+ ' + operand);
721
+ else if (node.operator === K.TildeToken) add('UnaryOperator', node, operand);
722
+ } else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node)) literal(node);
723
+ else if (node.kind === K.RegularExpressionLiteral) {
724
+ const raw = source(node);
725
+ const close = raw.lastIndexOf('/');
726
+ // An empty pattern is written as an empty group: `//` would start a comment.
727
+ for (const pattern of mutatePattern(raw.slice(1, close), raw.slice(close + 1))) add('Regex', node, `/${pattern || '(?:)'}/${raw.slice(close + 1)}`);
728
+ } else if (ts.isCallExpression(node) || ts.isNewExpression(node)) call(node);
729
+ if ((isMember(node) || ts.isCallExpression(node)) && node.questionDotToken) withoutQuestionDot(node);
730
+ if (ts.isForStatement(node) && !node.condition && !ts.isLabeledStatement(node.parent)) {
731
+ const semicolon = node.getChildren(tree).find(child => child.kind === K.SemicolonToken);
732
+ const mutated = text.slice(begin(node), semicolon.end) + ' false' + text.slice(semicolon.end, node.end);
733
+ add('ConditionalExpression', node, mutated, { kind: 'statement', placement: [begin(node), node.end], mutated });
734
+ } else if ((ts.isCaseClause(node) || ts.isDefaultClause(node)) && node.statements.length && !node.statements.some(lexical)) {
735
+ const head = text.slice(begin(node), node.statements.pos);
736
+ add('ConditionalExpression', node, head, { kind: 'case', placement: [begin(node), node.end], bodyStart: node.statements.pos, mutated: head });
737
+ }
738
+ const own = mutations.length;
739
+ const liveBefore = live;
740
+ ts.forEachChild(node, visit);
741
+ // Removing a whole call or throw is kept only when nothing inside the statement is mutated on its own.
742
+ // Mutations that a comment ignores do not count, and a removal that is itself ignored is always listed.
743
+ const removalIgnored = () => ignoreReason('CallExpression', lineOf(begin(node)), ruleOnEntry) !== undefined;
744
+ if (own === before && (live === liveBefore || skips !== skipsBefore || removalIgnored())) {
745
+ if (ts.isExpressionStatement(node)) {
746
+ const expression = strip(node.expression);
747
+ if (ts.isCallExpression(expression) && !ts.isOptionalChain(expression) && expression.expression.kind !== K.SuperKeyword) {
748
+ statementMutation(node, ';', ';', ruleOnEntry);
749
+ }
750
+ } else if (ts.isThrowStatement(node) && ts.isNewExpression(strip(node.expression))) statementMutation(node, ';', ';', ruleOnEntry);
751
+ }
752
+ })(tree);
753
+
754
+ return mutations.sort((a, b) => a.start - b.start || b.end - a.end);
755
+ }