targeted-mutation 0.1.1 → 0.2.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.
- package/README.md +8 -2
- package/bin/tmt.mjs +88 -30
- package/docs/analysis.md +1 -1
- package/package.json +5 -5
- package/src/analysis.mjs +53 -13
- package/src/baseline.mjs +184 -0
- package/src/builtin-mutations.mjs +56 -1
- package/src/builtin-switches.mjs +4 -3
- package/src/checkpoint.mjs +173 -0
- package/src/cli-output.mjs +32 -3
- package/src/conventional.mjs +54 -6
- package/src/enclosing-suppression.mjs +48 -0
- package/src/operator-analysis.mjs +51 -10
- package/src/project-config.mjs +183 -0
- package/src/reachability.mjs +335 -0
- package/src/sarif.mjs +156 -0
- package/src/shard.mjs +137 -0
- package/src/standard-plan.mjs +9 -1
- package/src/weakened-tests.mjs +178 -0
- package/src/witness-rules.mjs +129 -1
package/src/shard.mjs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { collectComparisons } from './analysis.mjs';
|
|
3
|
+
import { prepareBuiltinSwitches, targetedOrBoundary } from './builtin-switches.mjs';
|
|
4
|
+
import { selectScope } from './scope.mjs';
|
|
5
|
+
import { inside } from './vitest.mjs';
|
|
6
|
+
|
|
7
|
+
export function parseShard(spec) {
|
|
8
|
+
if (spec === undefined) return undefined;
|
|
9
|
+
const match = /^(\d+)\/(\d+)$/.exec(String(spec).trim());
|
|
10
|
+
if (!match) throw new Error(`Expected --shard K/N (0-based index / positive total), got: ${spec}`);
|
|
11
|
+
const index = Number(match[1]);
|
|
12
|
+
const total = Number(match[2]);
|
|
13
|
+
if (!Number.isSafeInteger(index) || !Number.isSafeInteger(total) || total < 1 || index < 0 || index >= total) {
|
|
14
|
+
throw new Error(`Invalid --shard ${spec}: require 0 <= K < N and N >= 1`);
|
|
15
|
+
}
|
|
16
|
+
return { index, total };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function parseShardingStrategy(strategy) {
|
|
20
|
+
if (strategy === undefined) return 'slice';
|
|
21
|
+
if (strategy !== 'slice' && strategy !== 'round-robin') {
|
|
22
|
+
throw new Error(`Expected --sharding slice|round-robin, got: ${strategy}`);
|
|
23
|
+
}
|
|
24
|
+
return strategy;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function selectShard(items, shard, strategy = 'slice') {
|
|
28
|
+
if (!shard) return { selected: items, meta: undefined };
|
|
29
|
+
const { index, total } = shard;
|
|
30
|
+
let selected;
|
|
31
|
+
if (strategy === 'round-robin') {
|
|
32
|
+
selected = items.filter((_, i) => i % total === index);
|
|
33
|
+
} else {
|
|
34
|
+
const base = Math.floor(items.length / total);
|
|
35
|
+
const rem = items.length % total;
|
|
36
|
+
const start = index * base + Math.min(index, rem);
|
|
37
|
+
const size = base + (index < rem ? 1 : 0);
|
|
38
|
+
selected = items.slice(start, start + size);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
selected,
|
|
42
|
+
meta: {
|
|
43
|
+
index,
|
|
44
|
+
total,
|
|
45
|
+
strategy,
|
|
46
|
+
totalCandidates: items.length,
|
|
47
|
+
selectedCandidates: selected.length,
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function candidateKey(candidate) {
|
|
53
|
+
const file = String(candidate.location?.file ?? '');
|
|
54
|
+
const start = candidate.location?.start ?? candidate.edit?.[0] ?? 0;
|
|
55
|
+
const end = candidate.location?.end ?? candidate.edit?.[1] ?? 0;
|
|
56
|
+
const rule = String(candidate.rule ?? candidate.mutatorName ?? '');
|
|
57
|
+
const replacement = String(candidate.replacement ?? '');
|
|
58
|
+
return `${file}:${start}:${end}:${rule}:${replacement}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function candidateOrder(a, b) {
|
|
62
|
+
return String(a.location?.file ?? '').localeCompare(String(b.location?.file ?? '')) ||
|
|
63
|
+
(a.location?.start ?? 0) - (b.location?.start ?? 0) ||
|
|
64
|
+
(b.location?.end ?? 0) - (a.location?.end ?? 0) ||
|
|
65
|
+
String(a.rule ?? a.mutatorName ?? '').localeCompare(String(b.rule ?? b.mutatorName ?? '')) ||
|
|
66
|
+
String(a.replacement ?? '').localeCompare(String(b.replacement ?? ''));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Preview all scoped mutation candidates without executing any test runner.
|
|
70
|
+
export function listCandidates(project, files, options = {}) {
|
|
71
|
+
const root = realpathSync(project);
|
|
72
|
+
const profile = options.mutators ?? 'targeted';
|
|
73
|
+
const shard = parseShard(options.shard);
|
|
74
|
+
const strategy = parseShardingStrategy(options.sharding);
|
|
75
|
+
|
|
76
|
+
const { subjects, extraction } = collectComparisons(root, files, { ...options, mutators: undefined });
|
|
77
|
+
const boundaryKeys = new Set();
|
|
78
|
+
const candidates = [];
|
|
79
|
+
for (const subject of subjects) {
|
|
80
|
+
for (const site of subject.sites) {
|
|
81
|
+
boundaryKeys.add(`${site.location.file}:${site.edit[0]}:${site.replacement}`);
|
|
82
|
+
candidates.push({
|
|
83
|
+
site: site.id,
|
|
84
|
+
rule: site.rule,
|
|
85
|
+
location: site.location,
|
|
86
|
+
operator: site.operator,
|
|
87
|
+
edit: site.edit,
|
|
88
|
+
replacement: site.replacement,
|
|
89
|
+
status: 'listed',
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const targets = selectScope(root, files, options).map(subject => ({
|
|
95
|
+
...subject,
|
|
96
|
+
input: readFileSync(inside(root, subject.file)),
|
|
97
|
+
}));
|
|
98
|
+
const { mutants: prepared } = prepareBuiltinSwitches(targets, {
|
|
99
|
+
dialect: options.dialect,
|
|
100
|
+
excludeRules: options['exclude-rule'],
|
|
101
|
+
...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
|
|
102
|
+
});
|
|
103
|
+
for (const mutant of prepared) {
|
|
104
|
+
if (mutant.parametric) continue;
|
|
105
|
+
if (mutant.operatorSwap && boundaryKeys.has(`${mutant.location.file}:${mutant.operatorSwap.join(':')}`)) continue;
|
|
106
|
+
const { source: _source, operatorSwap: _swap, targeted: _targeted, ...rest } = mutant;
|
|
107
|
+
candidates.push({
|
|
108
|
+
...(profile === 'full' ? rest : { site: rest.id, rule: rest.mutatorName, ...rest, id: undefined, mutatorName: undefined }),
|
|
109
|
+
status: mutant.status ?? 'listed',
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
candidates.sort(candidateOrder);
|
|
114
|
+
const { selected, meta } = selectShard(candidates, shard, strategy);
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
schemaVersion: 1,
|
|
118
|
+
runner: options.runner ?? 'vitest',
|
|
119
|
+
mutators: profile,
|
|
120
|
+
extraction,
|
|
121
|
+
mutants: selected,
|
|
122
|
+
diagnostics: [],
|
|
123
|
+
evaluation: selected.length ? 'listed' : 'no_sites',
|
|
124
|
+
selection: { config: options.config, tests: options.test, copyExclude: options['copy-exclude'] },
|
|
125
|
+
...(meta ? { shard: meta } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function computeShardSelection(project, files, options = {}) {
|
|
130
|
+
const shard = typeof options.shard === 'string' ? parseShard(options.shard) : options.shard;
|
|
131
|
+
if (!shard) return null;
|
|
132
|
+
const listed = listCandidates(project, files, { ...options, shard: `${shard.index}/${shard.total}` });
|
|
133
|
+
return {
|
|
134
|
+
keys: new Set(listed.mutants.map(candidateKey)),
|
|
135
|
+
meta: listed.shard,
|
|
136
|
+
};
|
|
137
|
+
}
|
package/src/standard-plan.mjs
CHANGED
|
@@ -136,7 +136,15 @@ export function assessTrial(trial, expectedTests, hitLimit) {
|
|
|
136
136
|
if (hitCount > hitLimit || failed.some(test => test.timeout)) {
|
|
137
137
|
return { status: 'timeout', statusReason: hitCount > hitLimit ? 'Mutation hit limit reached' : 'Vitest test timeout' };
|
|
138
138
|
}
|
|
139
|
-
if (errors.length)
|
|
139
|
+
if (errors.length) {
|
|
140
|
+
if (hitCount > 0) {
|
|
141
|
+
const killerTests = failed.length
|
|
142
|
+
? failed.map(({ id, name, file, project }) => ({ id, name, file, project }))
|
|
143
|
+
: [...expectedTests.values()].map(({ id, name, file, project }) => ({ id, name, file, project }));
|
|
144
|
+
return { status: 'killed', killedBy: 'unhandled-error', tests: killerTests, statusReason: errors.join('\n') };
|
|
145
|
+
}
|
|
146
|
+
return { status: 'error', statusReason: errors.join('\n') };
|
|
147
|
+
}
|
|
140
148
|
if (hitCount > 0 && ['failed', 'interrupted'].includes(reason) && failed.length &&
|
|
141
149
|
failed.every(test => expectedTests.has(test.id)) && [...expectedTests].every(([id, test]) =>
|
|
142
150
|
registered.has(id) || reason === 'interrupted' && !collectedModules.has(moduleKey(test)))) {
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { availableParallelism } from 'node:os';
|
|
4
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { verdict } from './analysis.mjs';
|
|
6
|
+
import { inParallel } from './in-parallel.mjs';
|
|
7
|
+
import { rewrite } from './probe.mjs';
|
|
8
|
+
import { copyPathIsExcluded, inside, resolveCopyExclusions, runVitestAsync, withCopy } from './vitest.mjs';
|
|
9
|
+
|
|
10
|
+
const TEST_FILE_RE = /\.(?:test|spec)\.(?:[cm]?[jt]s|[jt]sx)$/;
|
|
11
|
+
const MAX_WEAKENED_TRIALS = 32;
|
|
12
|
+
|
|
13
|
+
function git(root, args) {
|
|
14
|
+
return execFileSync('git', ['--literal-pathspecs', '-C', root, ...args], {
|
|
15
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
16
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function toGitPath(file) {
|
|
21
|
+
return sep === '/' ? file : file.replaceAll(sep, '/');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fromGitPath(file) {
|
|
25
|
+
return sep === '/' ? file : file.replaceAll('/', sep);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function resolveRevision(root, revision) {
|
|
29
|
+
try {
|
|
30
|
+
return git(root, ['rev-parse', '--verify', `${revision}^{commit}`]).toString('utf8').trim();
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Find test files modified since `revision` that also existed at `revision`.
|
|
37
|
+
export function changedTestFiles(root, revision) {
|
|
38
|
+
const rev = resolveRevision(root, revision);
|
|
39
|
+
if (!rev) return { revision: null, files: [] };
|
|
40
|
+
const raw = git(root, ['diff', '--name-only', '--relative', '--no-renames', '-z', rev, '--']);
|
|
41
|
+
const paths = raw.toString('utf8').split('\0').filter(Boolean);
|
|
42
|
+
const files = [];
|
|
43
|
+
for (const gitPath of paths) {
|
|
44
|
+
if (!TEST_FILE_RE.test(gitPath)) continue;
|
|
45
|
+
try {
|
|
46
|
+
const oldContent = git(root, ['show', `${rev}:${gitPath}`]);
|
|
47
|
+
files.push({ file: fromGitPath(gitPath), gitPath, oldContent });
|
|
48
|
+
} catch {
|
|
49
|
+
// Newly added test file since `rev` has no older version to replay.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { revision: rev, files };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function mutantKey(mutant) {
|
|
56
|
+
const file = mutant.location?.file ?? '';
|
|
57
|
+
const edit = mutant.edit ?? [];
|
|
58
|
+
return `${file}:${edit[0]}:${edit[1]}:${mutant.replacement ?? ''}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isReplayableSurvivor(mutant) {
|
|
62
|
+
return mutant?.status === 'survived' &&
|
|
63
|
+
mutant.since === undefined &&
|
|
64
|
+
mutant.location?.file &&
|
|
65
|
+
Array.isArray(mutant.edit) && mutant.edit.length === 2 &&
|
|
66
|
+
typeof mutant.replacement === 'string';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Re-run surviving mutants against the test files as they were at `options.since`.
|
|
70
|
+
// Any survivor killed by the old tests is marked with `weakened: { since, killedByOldTests }`.
|
|
71
|
+
export async function detectWeakenedTests(project, report, options = {}) {
|
|
72
|
+
if (!options.since || report?.evaluation !== 'evaluated' || report?.runner !== 'vitest') {
|
|
73
|
+
return report;
|
|
74
|
+
}
|
|
75
|
+
const root = realpathSync(project);
|
|
76
|
+
const { revision, files: rawOldTests } = changedTestFiles(root, options.since);
|
|
77
|
+
const exclusions = resolveCopyExclusions(root, options['copy-exclude'] ?? []);
|
|
78
|
+
const oldTests = rawOldTests.filter(entry => !copyPathIsExcluded(root, resolve(root, entry.file), exclusions));
|
|
79
|
+
if (!revision || !oldTests.length) return report;
|
|
80
|
+
|
|
81
|
+
const survivors = (report.mutants ?? []).filter(isReplayableSurvivor).slice(0, MAX_WEAKENED_TRIALS);
|
|
82
|
+
if (!survivors.length) return report;
|
|
83
|
+
|
|
84
|
+
const safeWorkspaceTarget = (workspace, relFile) => {
|
|
85
|
+
const realWorkspace = realpathSync(workspace);
|
|
86
|
+
const target = resolve(realWorkspace, relFile);
|
|
87
|
+
const fromRoot = relative(realWorkspace, target);
|
|
88
|
+
if (!fromRoot || isAbsolute(fromRoot) || fromRoot === '..' || fromRoot.startsWith('..' + sep)) {
|
|
89
|
+
throw new Error(`Path escapes the workspace: ${relFile}`);
|
|
90
|
+
}
|
|
91
|
+
// Walk every path segment to ensure no existing parent or target is a symlink escaping the workspace.
|
|
92
|
+
const parts = fromRoot.split(sep);
|
|
93
|
+
let cursor = realWorkspace;
|
|
94
|
+
for (let i = 0; i < parts.length; i++) {
|
|
95
|
+
cursor = resolve(cursor, parts[i]);
|
|
96
|
+
if (existsSync(cursor)) {
|
|
97
|
+
const st = lstatSync(cursor);
|
|
98
|
+
if (st.isSymbolicLink()) {
|
|
99
|
+
throw new Error(`Refusing to write through symbolic link in workspace: ${relFile}`);
|
|
100
|
+
}
|
|
101
|
+
const realCursor = realpathSync(cursor);
|
|
102
|
+
const relCheck = relative(realWorkspace, realCursor);
|
|
103
|
+
if (relCheck === '..' || relCheck.startsWith('..' + sep) || isAbsolute(relCheck)) {
|
|
104
|
+
throw new Error(`Path escapes the workspace: ${relFile}`);
|
|
105
|
+
}
|
|
106
|
+
} else if (i < parts.length - 1) {
|
|
107
|
+
mkdirSync(cursor);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return target;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const runWithOldTests = mutant => withCopy(root, async (workspace, temp) => {
|
|
114
|
+
for (const entry of oldTests) {
|
|
115
|
+
writeFileSync(safeWorkspaceTarget(workspace, entry.file), entry.oldContent);
|
|
116
|
+
}
|
|
117
|
+
if (mutant) {
|
|
118
|
+
const targetPath = inside(workspace, mutant.location.file);
|
|
119
|
+
const originalBytes = readFileSync(targetPath);
|
|
120
|
+
const edit = mutant.source?.edit ?? mutant.edit;
|
|
121
|
+
const replacement = mutant.source?.replacement ?? mutant.replacement;
|
|
122
|
+
writeFileSync(targetPath, rewrite(originalBytes, edit, replacement));
|
|
123
|
+
}
|
|
124
|
+
return runVitestAsync(workspace, temp, {
|
|
125
|
+
product: true,
|
|
126
|
+
config: options.config,
|
|
127
|
+
testFiles: options.test,
|
|
128
|
+
...(options.timeout ? { timeout: options.timeout * 1000 } : {}),
|
|
129
|
+
});
|
|
130
|
+
}, { exclude: options['copy-exclude'] });
|
|
131
|
+
|
|
132
|
+
// Verify old tests compile and pass on the current production code before attributing weakened tests.
|
|
133
|
+
const oldBaseline = await runWithOldTests(null);
|
|
134
|
+
if (oldBaseline.status !== 'passed') {
|
|
135
|
+
return report;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const concurrency = Math.max(1, Math.min(options.concurrency ?? Math.max(1, availableParallelism() - 1), 8));
|
|
139
|
+
const weakenedByKey = new Map();
|
|
140
|
+
const weakenedBySite = new Map();
|
|
141
|
+
|
|
142
|
+
await inParallel(survivors, concurrency, async mutant => {
|
|
143
|
+
const run = await runWithOldTests(mutant);
|
|
144
|
+
if (verdict(run, oldBaseline) === 'killed') {
|
|
145
|
+
const killedByOldTests = (run.tests ?? [])
|
|
146
|
+
.filter(t => t.status === 'failed')
|
|
147
|
+
.map(t => `${t.file} > ${t.name}`);
|
|
148
|
+
const info = { since: revision, killedByOldTests };
|
|
149
|
+
weakenedByKey.set(mutantKey(mutant), info);
|
|
150
|
+
if (mutant.site) weakenedBySite.set(mutant.site, info);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
if (!weakenedByKey.size) return report;
|
|
155
|
+
|
|
156
|
+
const mutants = (report.mutants ?? []).map(mutant => {
|
|
157
|
+
const info = weakenedByKey.get(mutantKey(mutant));
|
|
158
|
+
return info ? { ...mutant, weakened: info } : mutant;
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const diagnostics = (report.diagnostics ?? []).map(diag => {
|
|
162
|
+
const byMutation = (diag.mutations ?? [])
|
|
163
|
+
.map(m => weakenedByKey.get(`${diag.location?.file ?? ''}:${m.edit?.[0]}:${m.edit?.[1]}:${m.replacement ?? ''}`))
|
|
164
|
+
.find(Boolean);
|
|
165
|
+
return byMutation ? { ...diag, weakened: byMutation } : diag;
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
...report,
|
|
170
|
+
mutants,
|
|
171
|
+
diagnostics,
|
|
172
|
+
weakened: {
|
|
173
|
+
since: revision,
|
|
174
|
+
count: weakenedByKey.size,
|
|
175
|
+
changedTests: oldTests.map(entry => entry.file),
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
package/src/witness-rules.mjs
CHANGED
|
@@ -224,6 +224,132 @@ function lengthRule(parameters, expression) {
|
|
|
224
224
|
};
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
+
function roundingRule(parameters, expression) {
|
|
228
|
+
if (!ts.isCallExpression(expression) || expression.questionDotToken || expression.arguments.length !== 1 ||
|
|
229
|
+
!ts.isPropertyAccessExpression(expression.expression) || expression.expression.questionDotToken ||
|
|
230
|
+
!ts.isIdentifier(expression.expression.expression) || expression.expression.expression.text !== 'Math') return null;
|
|
231
|
+
const method = expression.expression.name.text;
|
|
232
|
+
if (method !== 'floor' && method !== 'trunc') return null;
|
|
233
|
+
const div = bare(expression.arguments[0]);
|
|
234
|
+
if (!div || !ts.isBinaryExpression(div) || div.operatorToken.kind !== ts.SyntaxKind.SlashToken) return null;
|
|
235
|
+
const divisor = integer(div.right);
|
|
236
|
+
if (divisor === undefined || divisor < 2) return null;
|
|
237
|
+
const mul = bare(div.left);
|
|
238
|
+
if (!mul || !ts.isBinaryExpression(mul) || mul.operatorToken.kind !== ts.SyntaxKind.AsteriskToken) return null;
|
|
239
|
+
const first = reference(mul.left, parameters);
|
|
240
|
+
const second = reference(mul.right, parameters);
|
|
241
|
+
if (!first?.node || !second?.node || first.field !== undefined || second.field !== undefined || first.index === second.index) return null;
|
|
242
|
+
const roundFn = method === 'floor' ? Math.floor : Math.trunc;
|
|
243
|
+
return {
|
|
244
|
+
rule: 'divide-before-multiply/v1',
|
|
245
|
+
node: expression,
|
|
246
|
+
replacement: `Math.${method}(${first.text} / ${divisor}) * ${second.text}`,
|
|
247
|
+
propose(args) {
|
|
248
|
+
const a0 = read(args, first);
|
|
249
|
+
const b0 = read(args, second);
|
|
250
|
+
if (!Number.isSafeInteger(a0) || !Number.isSafeInteger(b0) || !Number.isSafeInteger(a0 * b0)) return [];
|
|
251
|
+
if (roundFn((a0 * b0) / divisor) !== roundFn(a0 / divisor) * b0) return [];
|
|
252
|
+
const candidates = new Set();
|
|
253
|
+
const limit = Math.min(divisor - 1, 64);
|
|
254
|
+
for (let delta = 1; delta <= limit; delta++) candidates.add(delta);
|
|
255
|
+
if (b0 !== 0) {
|
|
256
|
+
const step = Math.ceil(divisor / Math.abs(b0));
|
|
257
|
+
if (step >= 1 && step < divisor) candidates.add(step);
|
|
258
|
+
if (step + 1 >= 1 && step + 1 < divisor) candidates.add(step + 1);
|
|
259
|
+
}
|
|
260
|
+
for (const delta of [...candidates].sort((x, y) => x - y)) {
|
|
261
|
+
const a1 = a0 + delta;
|
|
262
|
+
if (!Number.isSafeInteger(a1) || !Number.isSafeInteger(a1 * b0)) continue;
|
|
263
|
+
const original = roundFn((a1 * b0) / divisor);
|
|
264
|
+
const mutant = roundFn(a1 / divisor) * b0;
|
|
265
|
+
if (Number.isSafeInteger(original) && Number.isSafeInteger(mutant) && original !== mutant) {
|
|
266
|
+
return [{ path: [first.index], next: a1, original, mutant, append: true }];
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return [];
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function templateKeyRules(parameters, expression) {
|
|
275
|
+
if (!ts.isTemplateExpression(expression) || expression.templateSpans.length < 2) return [];
|
|
276
|
+
const parts = [];
|
|
277
|
+
for (const span of expression.templateSpans) {
|
|
278
|
+
const expr = bare(span.expression);
|
|
279
|
+
if (!ts.isIdentifier(expr)) return [];
|
|
280
|
+
const index = parameters.findIndex(p => p.name === expr.text && (p.shape === 'string' || p.shape === 'number'));
|
|
281
|
+
if (index < 0) return [];
|
|
282
|
+
parts.push({ index, shape: parameters[index].shape, literalText: span.literal.text });
|
|
283
|
+
}
|
|
284
|
+
const headText = expression.head.text;
|
|
285
|
+
const render = (args, omitPos) => {
|
|
286
|
+
let out = headText;
|
|
287
|
+
for (let i = 0; i < parts.length; i++) {
|
|
288
|
+
if (i !== omitPos) out += String(args[parts[i].index]);
|
|
289
|
+
out += parts[i].literalText;
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
};
|
|
293
|
+
return parts.map((part, omitPos) => {
|
|
294
|
+
const span = expression.templateSpans[omitPos];
|
|
295
|
+
// Replace `${param}` with empty string inside the template literal by editing the whole template.
|
|
296
|
+
let replacement = '`' + expression.head.rawText;
|
|
297
|
+
for (let i = 0; i < expression.templateSpans.length; i++) {
|
|
298
|
+
const s = expression.templateSpans[i];
|
|
299
|
+
if (i !== omitPos) replacement += '${' + s.expression.getText() + '}';
|
|
300
|
+
replacement += s.literal.rawText;
|
|
301
|
+
}
|
|
302
|
+
replacement += '`';
|
|
303
|
+
return {
|
|
304
|
+
rule: 'composite-key-omit/v1',
|
|
305
|
+
node: expression,
|
|
306
|
+
replacement,
|
|
307
|
+
propose(args) {
|
|
308
|
+
const current = args[part.index];
|
|
309
|
+
const next = part.shape === 'string' ? `${current}_alt` : current + 1;
|
|
310
|
+
if (part.shape === 'number' && !Number.isSafeInteger(next)) return [];
|
|
311
|
+
const mutatedArgs = args.map((v, idx) => (idx === part.index ? next : v));
|
|
312
|
+
const original = render(mutatedArgs, -1);
|
|
313
|
+
const mutant = render(mutatedArgs, omitPos);
|
|
314
|
+
return original === mutant ? [] : [{ path: [part.index], next, original, mutant, append: true }];
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function joinKeyRules(parameters, expression) {
|
|
321
|
+
if (!methodCall(expression, 'join', 1) || !ts.isStringLiteral(expression.arguments[0])) return [];
|
|
322
|
+
const arrayExpr = bare(expression.expression.expression);
|
|
323
|
+
if (!ts.isArrayLiteralExpression(arrayExpr) || arrayExpr.elements.length < 2) return [];
|
|
324
|
+
const sepText = expression.arguments[0].text;
|
|
325
|
+
const parts = [];
|
|
326
|
+
for (const el of arrayExpr.elements) {
|
|
327
|
+
const inner = bare(el);
|
|
328
|
+
if (!ts.isIdentifier(inner)) return [];
|
|
329
|
+
const index = parameters.findIndex(p => p.name === inner.text && (p.shape === 'string' || p.shape === 'number'));
|
|
330
|
+
if (index < 0) return [];
|
|
331
|
+
parts.push({ index, shape: parameters[index].shape, text: inner.text });
|
|
332
|
+
}
|
|
333
|
+
return parts.map((part, omitPos) => {
|
|
334
|
+
const remaining = parts.filter((_, i) => i !== omitPos).map(p => p.text).join(', ');
|
|
335
|
+
const replacement = `[${remaining}].join(${expression.arguments[0].getText()})`;
|
|
336
|
+
return {
|
|
337
|
+
rule: 'composite-key-omit/v1',
|
|
338
|
+
node: expression,
|
|
339
|
+
replacement,
|
|
340
|
+
propose(args) {
|
|
341
|
+
const current = args[part.index];
|
|
342
|
+
const next = part.shape === 'string' ? `${current}_alt` : current + 1;
|
|
343
|
+
if (part.shape === 'number' && !Number.isSafeInteger(next)) return [];
|
|
344
|
+
const mutatedArgs = args.map((v, idx) => (idx === part.index ? next : v));
|
|
345
|
+
const original = parts.map(p => String(mutatedArgs[p.index])).join(sepText);
|
|
346
|
+
const mutant = parts.filter((_, i) => i !== omitPos).map(p => String(mutatedArgs[p.index])).join(sepText);
|
|
347
|
+
return original === mutant ? [] : [{ path: [part.index], next, original, mutant, append: true }];
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
|
|
227
353
|
export function discoverWitnessRules(tree, sortConstraints = []) {
|
|
228
354
|
if (tree.parseDiagnostics.length) return [];
|
|
229
355
|
const javascript = tree.scriptKind === ts.ScriptKind.JS || tree.scriptKind === ts.ScriptKind.JSX;
|
|
@@ -245,8 +371,10 @@ export function discoverWitnessRules(tree, sortConstraints = []) {
|
|
|
245
371
|
if (parameters.some(param => !param.shape)) continue;
|
|
246
372
|
const rules = ts.isBinaryExpression(expression) ? [...comparisonRules(parameters, expression), maskRule(parameters, expression)].filter(Boolean)
|
|
247
373
|
: ts.isCallExpression(expression) ? [indexRule(parameters, expression), sumRule(parameters, expression),
|
|
374
|
+
roundingRule(parameters, expression), ...joinKeyRules(parameters, expression),
|
|
248
375
|
...orderRules(parameters, expression, sortConstraints.filter(entry => entry.function === name.text))].filter(Boolean)
|
|
249
|
-
:
|
|
376
|
+
: ts.isTemplateExpression(expression) ? templateKeyRules(parameters, expression)
|
|
377
|
+
: [lengthRule(parameters, expression)].filter(Boolean);
|
|
250
378
|
for (const rule of rules) result.push({ ...rule, name: name.text, parameters });
|
|
251
379
|
}
|
|
252
380
|
}
|