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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { mutatePattern } from './regex-mutations.mjs';
|
|
2
|
+
import { tmtIgnoreLines } from './baseline.mjs';
|
|
2
3
|
import { loadTypeScript } from './typescript-compiler.mjs';
|
|
3
4
|
|
|
4
5
|
// The built-in mutation set follows the StrykerJS mutators, found here in the TypeScript syntax tree.
|
|
@@ -39,7 +40,8 @@ const endSwaps = new Map([['find', 'findLast'], ['findLast', 'find'], ['findInde
|
|
|
39
40
|
['indexOf', 'lastIndexOf'], ['lastIndexOf', 'indexOf']]);
|
|
40
41
|
const ignoredValue = { '&&': 'true', '||': 'false', '??': 'undefined' };
|
|
41
42
|
|
|
42
|
-
export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, ts = loadTypeScript() } = {}) {
|
|
43
|
+
export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, excludeRules = [], ts = loadTypeScript() } = {}) {
|
|
44
|
+
const excludedRuleSet = new Set((excludeRules ?? []).map(r => String(r).trim()).filter(Boolean));
|
|
43
45
|
const kind = dialect === 'tsx' ? ts.ScriptKind.TSX : dialect === 'ts' ? ts.ScriptKind.TS : undefined;
|
|
44
46
|
const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
|
|
45
47
|
const K = ts.SyntaxKind;
|
|
@@ -114,6 +116,7 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
|
|
|
114
116
|
// that node's line. The newest matching rule decides.
|
|
115
117
|
const directive = /^\s?Stryker (disable|restore)(?: (next-line))? ([a-zA-Z, ]+)(?::(.+)?)?/;
|
|
116
118
|
const hasDirectives = text.includes('Stryker ');
|
|
119
|
+
const tmtIgnored = tmtIgnoreLines(text, ts);
|
|
117
120
|
let rule = null;
|
|
118
121
|
let directivesReadTo = 0;
|
|
119
122
|
function readDirectives(node) {
|
|
@@ -130,6 +133,7 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
|
|
|
130
133
|
}
|
|
131
134
|
}
|
|
132
135
|
function ignoreReason(name, line, from = rule) {
|
|
136
|
+
if (tmtIgnored.has(line)) return tmtIgnored.get(line);
|
|
133
137
|
for (let current = from; current; current = current.previous) {
|
|
134
138
|
if ((current.line === undefined || current.line === line) && (current.names.includes(name.toLowerCase()) || current.names.includes('all'))) {
|
|
135
139
|
return current.reason;
|
|
@@ -143,6 +147,7 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
|
|
|
143
147
|
// Code that a probe does not evaluate again (the index in `list[list.length - 1]`) holds no edit of its own.
|
|
144
148
|
const unprobed = [];
|
|
145
149
|
function add(name, node, replacement, placement, extra, from) {
|
|
150
|
+
if (excludedRuleSet.has(name)) return;
|
|
146
151
|
const start = begin(node);
|
|
147
152
|
if (extra?.targeted && unprobed.some(([from, to]) => from <= start && node.end <= to)) return;
|
|
148
153
|
for (let line = lineOf(start); line <= lineOf(node.end); line++) if (!selected(line + 1)) return;
|
|
@@ -250,6 +255,52 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
|
|
|
250
255
|
return inner.kind === K.NullKeyword ? 'null' : ts.isIdentifier(inner) && inner.text === 'undefined' ? 'undefined' : undefined;
|
|
251
256
|
};
|
|
252
257
|
|
|
258
|
+
function isSimplePath(node) {
|
|
259
|
+
node = strip(node);
|
|
260
|
+
// Restrict to bare identifiers so property getters that may return different values on
|
|
261
|
+
// re-evaluation (e.g. `typeof o.value === "object" && o.value !== null`) are never skipped.
|
|
262
|
+
return Boolean(node && ts.isIdentifier(node));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function isTypeofObjectCheck(term, targetText) {
|
|
266
|
+
term = strip(term);
|
|
267
|
+
if (!ts.isBinaryExpression(term)) return false;
|
|
268
|
+
const op = operatorOf(term);
|
|
269
|
+
if (op !== '===' && op !== '==') return false;
|
|
270
|
+
const check = (typeNode, strNode) => {
|
|
271
|
+
typeNode = strip(typeNode);
|
|
272
|
+
strNode = strip(strNode);
|
|
273
|
+
return ts.isTypeOfExpression(typeNode) &&
|
|
274
|
+
ts.isStringLiteralLike(strNode) && strNode.text === 'object' &&
|
|
275
|
+
source(strip(typeNode.expression)) === targetText;
|
|
276
|
+
};
|
|
277
|
+
return check(term.left, term.right) || check(term.right, term.left);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function isGuardedTypeofObject(node, subjectNode) {
|
|
281
|
+
if (!isSimplePath(subjectNode)) return false;
|
|
282
|
+
const targetText = source(subjectNode);
|
|
283
|
+
let current = node;
|
|
284
|
+
let [parent] = up(current);
|
|
285
|
+
while (parent && isLogical(parent) && operatorOf(parent) === '&&') {
|
|
286
|
+
current = parent;
|
|
287
|
+
[parent] = up(current);
|
|
288
|
+
}
|
|
289
|
+
if (current === node) return false;
|
|
290
|
+
let guarded = false;
|
|
291
|
+
(function scanAnd(expr) {
|
|
292
|
+
if (guarded) return;
|
|
293
|
+
expr = strip(expr);
|
|
294
|
+
if (isLogical(expr) && operatorOf(expr) === '&&') {
|
|
295
|
+
scanAnd(expr.left);
|
|
296
|
+
scanAnd(expr.right);
|
|
297
|
+
} else if (expr !== node && isTypeofObjectCheck(expr, targetText)) {
|
|
298
|
+
guarded = true;
|
|
299
|
+
}
|
|
300
|
+
})(current);
|
|
301
|
+
return guarded;
|
|
302
|
+
}
|
|
303
|
+
|
|
253
304
|
// An edit of one expression that a probe can stand for. `operands` are the parts the probe evaluates, in order.
|
|
254
305
|
function probed(node, operator, operands, shared = {}) {
|
|
255
306
|
// The probe stands where the expression stands, inside its own parentheses: what encloses them (a template
|
|
@@ -287,7 +338,11 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
|
|
|
287
338
|
if ((written[0] === undefined) === (written[1] === undefined)) return;
|
|
288
339
|
const literalSide = written[0] === undefined ? 1 : 0;
|
|
289
340
|
const other = written[literalSide] === 'null' ? 'undefined' : 'null';
|
|
341
|
+
const subjectNode = strip(literalSide ? node.left : node.right);
|
|
290
342
|
const subject = literalSide ? left : right;
|
|
343
|
+
// In `typeof x === "object" && x !== null` (or reversed), `x` cannot be `undefined`, so
|
|
344
|
+
// relaxing `!== null` / `=== null` to loose equality is an unreachable equivalent mutant.
|
|
345
|
+
if (written[literalSide] === 'null' && isGuardedTypeofObject(node, subjectNode)) return;
|
|
291
346
|
if (operator.length === 3) {
|
|
292
347
|
edit(targetedRules.nullish, 'loose', swapToken(node, token, operator.slice(0, 2)), { literalSide, differsFor: other, subject });
|
|
293
348
|
} else {
|
package/src/builtin-switches.mjs
CHANGED
|
@@ -409,7 +409,7 @@ function ${see}(i, l, r, r2) {
|
|
|
409
409
|
} else if (!isProxy || !isProxy(l)) {
|
|
410
410
|
try {
|
|
411
411
|
var proto = scope.Object.getPrototypeOf(l);
|
|
412
|
-
if (proto === scope.Object.prototype
|
|
412
|
+
if (proto === scope.Object.prototype) entry.realCopy = true; else entry.nonPlain = true;
|
|
413
413
|
} catch (error) { /* leave unclassified */ }
|
|
414
414
|
}
|
|
415
415
|
}
|
|
@@ -619,9 +619,10 @@ export function renderBuiltinSwitches(input, file, selected = () => true, option
|
|
|
619
619
|
export const boundarySwap = (mutation, text) => mutation.shift !== undefined || (mutation.operator !== undefined &&
|
|
620
620
|
['>', '>=', '<', '<='].includes(mutation.operator[1]) && text[mutation.operator[0]] === mutation.operator[1][0]);
|
|
621
621
|
|
|
622
|
-
// The boundary swaps that a `// Stryker disable` comment covers, as `offset:replacement` keys in UTF-8 bytes.
|
|
622
|
+
// The boundary swaps that a `// Stryker disable` or `// tmt:ignore` comment covers, as `offset:replacement` keys in UTF-8 bytes.
|
|
623
623
|
export function ignoredSwaps(input, file, options = {}) {
|
|
624
|
-
|
|
624
|
+
const text = Buffer.isBuffer(input) ? input.toString('utf8') : String(input);
|
|
625
|
+
if (!text.includes('Stryker ') && !/tmt:ignore/i.test(text)) return new Set();
|
|
625
626
|
return new Set(renderBuiltinSwitches(input, file, () => true, { ...options, keep: boundarySwap }).mutants
|
|
626
627
|
.filter(mutant => mutant.status === 'ignored' && mutant.operatorSwap).map(mutant => mutant.operatorSwap.join(':')));
|
|
627
628
|
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, truncateSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const CHECKPOINT_VERSION = 1;
|
|
6
|
+
const REUSABLE_STATUSES = new Set(['killed', 'survived', 'timeout', 'unreached']);
|
|
7
|
+
const CONTEXT_SKIP_DIRS = new Set(['.git', '.worktree', '.worktrees', 'node_modules', 'dist', 'build', 'coverage', 'docs.local', '.stryker-tmp']);
|
|
8
|
+
const CONTEXT_FILE_RE = /(?:\.(?:[cm]?[jt]s|[jt]sx|json)|^(?:package\.json|tsconfig(?:\.[^.]+)?\.json|(?:vite|vitest|playwright)(?:\.[^.]+)*\.config\.[cm]?[jt]s))$/;
|
|
9
|
+
|
|
10
|
+
function collectProjectContextFiles(root, dir = root, out = []) {
|
|
11
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
12
|
+
if (CONTEXT_SKIP_DIRS.has(entry.name) || entry.name.startsWith('.tmt-')) continue;
|
|
13
|
+
const full = resolve(dir, entry.name);
|
|
14
|
+
if (entry.isDirectory()) {
|
|
15
|
+
collectProjectContextFiles(root, full, out);
|
|
16
|
+
} else if (entry.isFile() && CONTEXT_FILE_RE.test(entry.name)) {
|
|
17
|
+
const size = statSync(full, { throwIfNoEntry: false })?.size ?? 0;
|
|
18
|
+
if (size <= 2 * 1024 * 1024) {
|
|
19
|
+
out.push(relative(root, full));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Hash all relevant source, test, and config files plus execution options so any edit to tests,
|
|
27
|
+
// dependencies, or runner configs invalidates cached checkpoint outcomes.
|
|
28
|
+
export function computeCampaignContext(targets, options = {}, root = null) {
|
|
29
|
+
const hash = createHash('sha256');
|
|
30
|
+
if (root && existsSync(root)) {
|
|
31
|
+
const projectFiles = collectProjectContextFiles(root).sort();
|
|
32
|
+
for (const rel of projectFiles) {
|
|
33
|
+
hash.update(rel.replaceAll(sep, '/'));
|
|
34
|
+
hash.update('\0');
|
|
35
|
+
hash.update(readFileSync(resolve(root, rel)));
|
|
36
|
+
hash.update('\0');
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
const sortedTargets = [...targets].sort((a, b) => a.file.localeCompare(b.file));
|
|
40
|
+
for (const target of sortedTargets) {
|
|
41
|
+
hash.update(target.file);
|
|
42
|
+
hash.update('\0');
|
|
43
|
+
hash.update(target.input);
|
|
44
|
+
hash.update('\0');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
hash.update(JSON.stringify({
|
|
48
|
+
mutators: options.mutators ?? 'targeted',
|
|
49
|
+
runner: options.runner ?? 'vitest',
|
|
50
|
+
config: options.config ?? null,
|
|
51
|
+
test: options.test ?? null,
|
|
52
|
+
lines: options.lines ?? null,
|
|
53
|
+
since: options.since ?? null,
|
|
54
|
+
shard: options.shard ?? null,
|
|
55
|
+
sharding: options.sharding ?? 'slice',
|
|
56
|
+
deterministic: !!options.deterministic,
|
|
57
|
+
displaceThresholds: !!options['displace-thresholds'],
|
|
58
|
+
excludeRules: options['exclude-rule'] ?? null,
|
|
59
|
+
timeout: options.timeout ?? null,
|
|
60
|
+
copyExclude: options['copy-exclude'] ?? null,
|
|
61
|
+
isolatedTrials: !!options['isolated-trials'],
|
|
62
|
+
}));
|
|
63
|
+
return hash.digest('hex');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function checkpointKeyForTrial(trial) {
|
|
67
|
+
const file = trial.site?.location?.file ?? trial.location?.file ?? '';
|
|
68
|
+
const edit = trial.edit ?? [];
|
|
69
|
+
const rule = trial.rule ?? trial.mutatorName ?? '';
|
|
70
|
+
const replacement = trial.replacement ?? '';
|
|
71
|
+
return `${file}:${edit[0]}:${edit[1]}:${rule}:${replacement}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function openCheckpoint(path, context, metadata = {}) {
|
|
75
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
76
|
+
const stored = new Map();
|
|
77
|
+
let reused = 0;
|
|
78
|
+
let recorded = 0;
|
|
79
|
+
let matched = false;
|
|
80
|
+
|
|
81
|
+
if (existsSync(path)) {
|
|
82
|
+
const raw = readFileSync(path, 'utf8');
|
|
83
|
+
if (raw.length > 0) {
|
|
84
|
+
const lines = raw.split('\n');
|
|
85
|
+
let validByteLength = 0;
|
|
86
|
+
let sawFormat = false;
|
|
87
|
+
let logContext = null;
|
|
88
|
+
let truncated = false;
|
|
89
|
+
let missingTrailingNewline = !raw.endsWith('\n');
|
|
90
|
+
const candidateOutcomes = new Map();
|
|
91
|
+
|
|
92
|
+
for (let i = 0; i < lines.length; i++) {
|
|
93
|
+
const line = lines[i];
|
|
94
|
+
const isLast = i === lines.length - 1;
|
|
95
|
+
if (!line.length && isLast) break;
|
|
96
|
+
let parsed;
|
|
97
|
+
try {
|
|
98
|
+
parsed = JSON.parse(line);
|
|
99
|
+
} catch {
|
|
100
|
+
if (isLast && sawFormat) {
|
|
101
|
+
truncated = true;
|
|
102
|
+
missingTrailingNewline = false;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
throw new Error(`Refusing to overwrite non-checkpoint file at ${path}`);
|
|
106
|
+
}
|
|
107
|
+
validByteLength += Buffer.byteLength(line, 'utf8') + (isLast ? 0 : 1);
|
|
108
|
+
if (i === 0) {
|
|
109
|
+
if (parsed.event !== 'format' || parsed.version !== CHECKPOINT_VERSION) {
|
|
110
|
+
throw new Error(`Refusing to overwrite non-checkpoint file at ${path}`);
|
|
111
|
+
}
|
|
112
|
+
sawFormat = true;
|
|
113
|
+
} else if (parsed.event === 'campaign_started' && typeof parsed.context === 'string') {
|
|
114
|
+
logContext = parsed.context;
|
|
115
|
+
} else if (parsed.event === 'outcome' && typeof parsed.key === 'string' && parsed.outcome && REUSABLE_STATUSES.has(parsed.outcome.status)) {
|
|
116
|
+
candidateOutcomes.set(parsed.key, parsed.outcome);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (sawFormat && logContext === context) {
|
|
121
|
+
matched = true;
|
|
122
|
+
if (truncated) {
|
|
123
|
+
truncateSync(path, validByteLength);
|
|
124
|
+
} else if (missingTrailingNewline) {
|
|
125
|
+
appendFileSync(path, '\n', 'utf8');
|
|
126
|
+
}
|
|
127
|
+
for (const [k, v] of candidateOutcomes) {
|
|
128
|
+
stored.set(k, v);
|
|
129
|
+
}
|
|
130
|
+
reused = stored.size;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (!matched) {
|
|
136
|
+
const header = [
|
|
137
|
+
JSON.stringify({ event: 'format', version: CHECKPOINT_VERSION }),
|
|
138
|
+
JSON.stringify({ event: 'campaign_started', context, metadata }),
|
|
139
|
+
].join('\n') + '\n';
|
|
140
|
+
writeFileSync(path, header, 'utf8');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
path,
|
|
145
|
+
context,
|
|
146
|
+
matched,
|
|
147
|
+
get reused() { return reused; },
|
|
148
|
+
get recorded() { return recorded; },
|
|
149
|
+
get(key) {
|
|
150
|
+
return stored.get(key);
|
|
151
|
+
},
|
|
152
|
+
record(key, outcome, diagnostic = undefined) {
|
|
153
|
+
if (!outcome || !REUSABLE_STATUSES.has(outcome.status)) return false;
|
|
154
|
+
if (stored.has(key)) return false;
|
|
155
|
+
const sanitized = {
|
|
156
|
+
status: outcome.status,
|
|
157
|
+
...(outcome.tests ? { tests: outcome.tests } : {}),
|
|
158
|
+
...(outcome.evidence ? { evidence: outcome.evidence } : {}),
|
|
159
|
+
...(diagnostic ? { diagnostic } : {}),
|
|
160
|
+
};
|
|
161
|
+
appendFileSync(path, JSON.stringify({ event: 'outcome', key, outcome: sanitized }) + '\n', 'utf8');
|
|
162
|
+
stored.set(key, sanitized);
|
|
163
|
+
recorded++;
|
|
164
|
+
return true;
|
|
165
|
+
},
|
|
166
|
+
complete() {
|
|
167
|
+
appendFileSync(path, JSON.stringify({ event: 'campaign_completed' }) + '\n', 'utf8');
|
|
168
|
+
},
|
|
169
|
+
summary() {
|
|
170
|
+
return { path, reused, recorded, resumed: matched };
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
package/src/cli-output.mjs
CHANGED
|
@@ -13,6 +13,10 @@ Scope (analyze):
|
|
|
13
13
|
--undo-changes With --since: also put each change back as it was at REV and run the suite.
|
|
14
14
|
A change the tests pass without is reported as UNTESTED CHANGE.
|
|
15
15
|
--copy-exclude PATH Leave a project path out of the temporary copies. Repeatable.
|
|
16
|
+
--copy-exclude-gitignore Also exclude gitignored paths (except node_modules) from temporary copies.
|
|
17
|
+
--exclude-rule RULE Exclude a mutation rule (e.g. nullish-equality/v1). Repeatable.
|
|
18
|
+
--no-config Ignore targeted-mutation.config.{json,mjs} and package.json#targetedMutation.
|
|
19
|
+
--progress Print lightweight progress updates to stderr.
|
|
16
20
|
|
|
17
21
|
Profiles (analyze):
|
|
18
22
|
--mutators targeted|full targeted (default) edits comparison boundaries and integer thresholds
|
|
@@ -25,6 +29,10 @@ Profiles (analyze):
|
|
|
25
29
|
without requiring any external instrumenter package.
|
|
26
30
|
--witnesses Search for edits that survive and confirm a distinguishing test.
|
|
27
31
|
--spec FILE Specification with expected thresholds or witness plans.
|
|
32
|
+
--list Preview scoped mutation candidates without running tests.
|
|
33
|
+
--shard K/N Run zero-based shard K of N total shards.
|
|
34
|
+
--sharding slice|round-robin Candidate distribution across shards (default: slice).
|
|
35
|
+
--checkpoint [FILE] Record and resume completed mutant outcomes via a JSONL checkpoint file.
|
|
28
36
|
--deterministic Declare a deterministic suite so recorded comparisons can decide a trial.
|
|
29
37
|
--audit Re-run predicted trials against the rewritten source.
|
|
30
38
|
--displace-thresholds Also try displaced thresholds (Vitest only).
|
|
@@ -42,8 +50,11 @@ Runner (analyze):
|
|
|
42
50
|
--timeout SECONDS Time limit for one run of the suite (default: 60).
|
|
43
51
|
--project NAME Playwright project. Repeatable.
|
|
44
52
|
|
|
45
|
-
Output:
|
|
46
|
-
--format text|json
|
|
53
|
+
Output & Baselines:
|
|
54
|
+
--format text|json|jsonl|sarif
|
|
55
|
+
Output format (analyze defaults to text on a terminal and json otherwise).
|
|
56
|
+
--baseline FILE Suppress findings already recorded in FILE.
|
|
57
|
+
--write-baseline FILE Write this run's findings to FILE for future --baseline runs.
|
|
47
58
|
--mode script|module extract: parse goal.
|
|
48
59
|
--dialect ts|tsx extract: source dialect.
|
|
49
60
|
-h, --help Show this help.
|
|
@@ -51,7 +62,9 @@ Output:
|
|
|
51
62
|
|
|
52
63
|
export function chooseFormat(requested, terminal) {
|
|
53
64
|
if (requested === undefined) return terminal ? 'text' : 'json';
|
|
54
|
-
if (
|
|
65
|
+
if (!['text', 'json', 'jsonl', 'sarif'].includes(requested)) {
|
|
66
|
+
throw new Error('Expected --format text|json|jsonl|sarif');
|
|
67
|
+
}
|
|
55
68
|
return requested;
|
|
56
69
|
}
|
|
57
70
|
|
|
@@ -70,6 +83,17 @@ function describeEdit(mutant) {
|
|
|
70
83
|
}
|
|
71
84
|
|
|
72
85
|
function describeBaseline(baseline = {}) {
|
|
86
|
+
if (baseline.status === 'timeout') {
|
|
87
|
+
const limit = baseline.timeoutSeconds !== undefined ? ` after ${baseline.timeoutSeconds}s` : '';
|
|
88
|
+
const lines = [
|
|
89
|
+
`The baseline test suite timed out${limit} before any edit.`,
|
|
90
|
+
' Try increasing the limit with --timeout <seconds> or narrowing the suite with --test <file|glob>.',
|
|
91
|
+
];
|
|
92
|
+
if (baseline.output?.trim()) {
|
|
93
|
+
lines.push(...printable(baseline.output).trim().split('\n').slice(-10).map(line => ` ${line}`));
|
|
94
|
+
}
|
|
95
|
+
return lines;
|
|
96
|
+
}
|
|
73
97
|
const lines = [`The test suite did not pass before any edit (baseline ${baseline.status ?? 'unknown'}). Fix it and run again.`];
|
|
74
98
|
for (const failed of baseline.failedTests ?? []) {
|
|
75
99
|
lines.push(` FAILED ${printable(failed.file)} > ${printable(failed.name)}`);
|
|
@@ -121,6 +145,9 @@ function describeGap(gap) {
|
|
|
121
145
|
`it gives ${printable(gap.strengthens.original)}, and ${printable(gap.strengthens.edited)} with the edit`);
|
|
122
146
|
}
|
|
123
147
|
if (gap.suggestedTest) lines.push(` suggested test: ${printable(gap.suggestedTest)}`);
|
|
148
|
+
if (gap.weakened) {
|
|
149
|
+
lines.push(` the tests as they were at ${printable(String(gap.weakened.since).slice(0, 12))} caught this: a change to the tests lets it through`);
|
|
150
|
+
}
|
|
124
151
|
if (gap.seed) lines.push(` based on: ${printable(gap.seed.file)} > ${printable(gap.seed.test)}`);
|
|
125
152
|
if (gap.requirement) lines.push(` requirement: ${firstLine(gap.requirement)}`);
|
|
126
153
|
if (gap.suggestedTestFile) lines.push(` suggested test file: ${printable(gap.suggestedTestFile)}`);
|
|
@@ -161,6 +188,8 @@ export function renderText(report) {
|
|
|
161
188
|
const size = Array.isArray(tests) ? tests.length : tests;
|
|
162
189
|
lines.push(`${report.runner}${size === undefined ? '' : `, ${size} baseline tests`}: ` +
|
|
163
190
|
`${mutants.length} edits (${tally}), ${gaps.length} test gaps` +
|
|
191
|
+
(report.suppressed?.baseline ? `, ${report.suppressed.baseline} suppressed by baseline` : '') +
|
|
192
|
+
(report.shard ? `, shard ${report.shard.index}/${report.shard.total}` : '') +
|
|
164
193
|
(report.evaluation === 'evaluated' ? '' : `, evaluation ${report.evaluation}`));
|
|
165
194
|
return lines.join('\n');
|
|
166
195
|
}
|
package/src/conventional.mjs
CHANGED
|
@@ -6,6 +6,8 @@ import { resolve } from 'node:path';
|
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { prepareBuiltinSwitches, targetedOrBoundary } from './builtin-switches.mjs';
|
|
8
8
|
import { targetedGap } from './targeted-gaps.mjs';
|
|
9
|
+
import { checkpointKeyForTrial } from './checkpoint.mjs';
|
|
10
|
+
import { candidateKey } from './shard.mjs';
|
|
9
11
|
import { selectScope } from './scope.mjs';
|
|
10
12
|
import { inside, runnerPackage, withCopy } from './vitest.mjs';
|
|
11
13
|
|
|
@@ -51,6 +53,7 @@ export async function analyzeConventional(project, files, options) {
|
|
|
51
53
|
const { sources, mutants: prepared } = prepareBuiltinSwitches(targets, {
|
|
52
54
|
dialect: options.dialect,
|
|
53
55
|
shifts: awaitsExtras,
|
|
56
|
+
excludeRules: options['exclude-rule'],
|
|
54
57
|
...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
|
|
55
58
|
});
|
|
56
59
|
const report = {
|
|
@@ -59,10 +62,40 @@ export async function analyzeConventional(project, files, options) {
|
|
|
59
62
|
selection: { config: options.config, tests: options.test, copyExclude: options['copy-exclude'] },
|
|
60
63
|
};
|
|
61
64
|
// Shift switches belong to the session and not to the report.
|
|
62
|
-
const
|
|
63
|
-
const
|
|
65
|
+
const shardKeys = options.shardKeys;
|
|
66
|
+
const inShard = mutant => !shardKeys || mutant.parametric || shardKeys.has(candidateKey({
|
|
67
|
+
location: mutant.location,
|
|
68
|
+
rule: profile === 'full' ? mutant.mutatorName : mutant.mutatorName,
|
|
69
|
+
replacement: mutant.replacement,
|
|
70
|
+
}));
|
|
71
|
+
const mutants = prepared.filter(mutant => !mutant.parametric && inShard(mutant));
|
|
72
|
+
const ckpt = options.checkpointStore;
|
|
73
|
+
const cachedById = new Map();
|
|
74
|
+
if (ckpt) {
|
|
75
|
+
for (const mutant of mutants) {
|
|
76
|
+
if (mutant.status !== undefined) continue;
|
|
77
|
+
const hit = ckpt.get(checkpointKeyForTrial(mutant));
|
|
78
|
+
if (hit) cachedById.set(mutant.id, hit);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const runnable = prepared.filter(mutant => mutant.status === undefined && inShard(mutant) && !cachedById.has(mutant.id));
|
|
64
82
|
if (!mutants.length) return report;
|
|
65
|
-
if (!runnable.length)
|
|
83
|
+
if (!runnable.length) {
|
|
84
|
+
const cachedDiagnostics = [];
|
|
85
|
+
const mapped = mutants.map(({ targeted: _rule, ...mutant }) => {
|
|
86
|
+
const cached = cachedById.get(mutant.id);
|
|
87
|
+
if (cached?.diagnostic) cachedDiagnostics.push(cached.diagnostic);
|
|
88
|
+
if (!cached) return mutant;
|
|
89
|
+
const { diagnostic: _diag, ...outcome } = cached;
|
|
90
|
+
return { ...mutant, ...outcome, evidence: outcome.evidence ?? 'checkpoint' };
|
|
91
|
+
});
|
|
92
|
+
return {
|
|
93
|
+
...report,
|
|
94
|
+
evaluation: 'evaluated',
|
|
95
|
+
mutants: mapped,
|
|
96
|
+
diagnostics: cachedDiagnostics,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
66
99
|
|
|
67
100
|
return withCopy(root, async (workspace, temp) => {
|
|
68
101
|
runnerPackage(workspace, 'vitest');
|
|
@@ -156,17 +189,32 @@ export async function analyzeConventional(project, files, options) {
|
|
|
156
189
|
return nowRuns.length || noLongerRuns.length ? { ...gap, effects: { nowRuns, noLongerRuns } } : gap;
|
|
157
190
|
};
|
|
158
191
|
const judged = mutants.map(mutant => {
|
|
192
|
+
const cached = cachedById.get(mutant.id);
|
|
193
|
+
if (cached) {
|
|
194
|
+
const { diagnostic: _diag, ...outcome } = cached;
|
|
195
|
+
return { ...mutant, ...outcome, evidence: outcome.evidence ?? 'checkpoint', _cachedDiagnostic: cached.diagnostic };
|
|
196
|
+
}
|
|
159
197
|
const result = results.get(mutant.id);
|
|
160
198
|
// An edit the session left out was not run.
|
|
161
199
|
if (result?.status === 'ignored') return { ...mutant, ...result };
|
|
162
|
-
if (result)
|
|
200
|
+
if (result) {
|
|
201
|
+
return { ...mutant, ...result, evidence: result.evidence ?? (result.status === 'unreached' ? 'coverage' : 'reexecuted') };
|
|
202
|
+
}
|
|
163
203
|
return mutant.status ? mutant : { ...mutant, status: 'unevaluated', statusReason: error || 'Mutation session ended early' };
|
|
164
204
|
});
|
|
205
|
+
const diagnostics = [];
|
|
206
|
+
for (const mutant of judged) {
|
|
207
|
+
const gap = mutant._cachedDiagnostic ?? withEffects(targetedGap(mutant, observed[mutant.id]), mutant);
|
|
208
|
+
if (gap) diagnostics.push(gap);
|
|
209
|
+
if (ckpt && !cachedById.has(mutant.id) && results.has(mutant.id)) {
|
|
210
|
+
ckpt.record(checkpointKeyForTrial(mutant), mutant, gap ?? undefined);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
165
213
|
return {
|
|
166
214
|
...report, baseline, evaluation: completed ? 'evaluated' : 'incomplete', trials: events.find(event => event.trials)?.trials,
|
|
167
215
|
...(awaitsExtras ? { extras: events.filter(event => event.extra !== undefined) } : {}),
|
|
168
|
-
mutants: judged.map(({ targeted: _rule, effects: _effects, ...mutant }) => mutant),
|
|
169
|
-
diagnostics
|
|
216
|
+
mutants: judged.map(({ targeted: _rule, effects: _effects, _cachedDiagnostic: _cd, ...mutant }) => mutant),
|
|
217
|
+
diagnostics,
|
|
170
218
|
};
|
|
171
219
|
}, { exclude: options['copy-exclude'] });
|
|
172
220
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const ENCLOSING_LOGICAL_RULES = new Set([
|
|
2
|
+
'ignored-operand/v1',
|
|
3
|
+
'equality-constant/v1',
|
|
4
|
+
'nullish-fallback/v1',
|
|
5
|
+
]);
|
|
6
|
+
|
|
7
|
+
function hasSpan(diagnostic) {
|
|
8
|
+
return diagnostic?.location &&
|
|
9
|
+
typeof diagnostic.location.file === 'string' &&
|
|
10
|
+
typeof diagnostic.location.start === 'number' &&
|
|
11
|
+
typeof diagnostic.location.end === 'number';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function strictlyEncloses(outer, inner) {
|
|
15
|
+
return outer.location.file === inner.location.file &&
|
|
16
|
+
outer.location.start <= inner.location.start &&
|
|
17
|
+
inner.location.end <= outer.location.end &&
|
|
18
|
+
(outer.location.start < inner.location.start || inner.location.end < outer.location.end);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isConstantInnerGap(diagnostic) {
|
|
22
|
+
if (diagnostic?.kind !== 'INPUT GAP') return false;
|
|
23
|
+
const rule = diagnostic.rule ?? diagnostic.mutations?.[0]?.rule;
|
|
24
|
+
return rule === 'equality-constant/v1';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isRedundantOuterGap(diagnostic) {
|
|
28
|
+
if (diagnostic?.kind !== 'INPUT GAP') return false;
|
|
29
|
+
const rule = diagnostic.rule ?? diagnostic.mutations?.[0]?.rule;
|
|
30
|
+
if (rule !== 'ignored-operand/v1') return false;
|
|
31
|
+
// Only suppress left-operand drop `(a, b)` when the inner left comparison is already reported as always-constant.
|
|
32
|
+
// Never suppress right-operand drop `a && (b, true)` since that represents an independent test obligation.
|
|
33
|
+
const replacement = String(diagnostic.mutations?.[0]?.replacement ?? '');
|
|
34
|
+
return !replacement.includes('&&') && !replacement.includes('||') && !replacement.includes('??');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Suppress duplicate outer `ignored-operand/v1` (left-drop) INPUT GAP when an inner expression
|
|
38
|
+
// strictly inside its span is already reported as an `equality-constant/v1` INPUT GAP.
|
|
39
|
+
export function suppressEnclosingDiagnostics(diagnostics) {
|
|
40
|
+
if (!Array.isArray(diagnostics) || diagnostics.length < 2) return diagnostics;
|
|
41
|
+
const innerConstantGaps = diagnostics.filter(d => isConstantInnerGap(d) && hasSpan(d));
|
|
42
|
+
if (!innerConstantGaps.length) return diagnostics;
|
|
43
|
+
|
|
44
|
+
return diagnostics.filter(outer => {
|
|
45
|
+
if (!isRedundantOuterGap(outer) || !hasSpan(outer)) return true;
|
|
46
|
+
return !innerConstantGaps.some(inner => inner !== outer && strictlyEncloses(outer, inner));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -1,5 +1,11 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
1
2
|
import { analyze, baselineRunSymbol, completeAnalysis, prepareAnalysis } from './analysis.mjs';
|
|
3
|
+
import { checkpointKeyForTrial, computeCampaignContext, openCheckpoint } from './checkpoint.mjs';
|
|
2
4
|
import { analyzeConventional } from './conventional.mjs';
|
|
5
|
+
import { suppressEnclosingDiagnostics } from './enclosing-suppression.mjs';
|
|
6
|
+
import { selectScope } from './scope.mjs';
|
|
7
|
+
import { computeShardSelection } from './shard.mjs';
|
|
8
|
+
import { inside } from './vitest.mjs';
|
|
3
9
|
|
|
4
10
|
const order = (a, b) => a.location.file.localeCompare(b.location.file) || a.location.start - b.location.start ||
|
|
5
11
|
b.location.end - a.location.end;
|
|
@@ -67,6 +73,9 @@ async function besideSession(project, files, options, run, profile, stopsSession
|
|
|
67
73
|
mutators: profile, lines: options.lines, since: options.since, config: options.config, test: options.test,
|
|
68
74
|
'copy-exclude': options['copy-exclude'], dialect: options.dialect, 'isolated-trials': options['isolated-trials'],
|
|
69
75
|
concurrency: options.concurrency, 'verify-trials': options['verify-trials'], timeout: options.timeout, signal: stop.signal, extras,
|
|
76
|
+
...(options.shardKeys ? { shardKeys: options.shardKeys } : {}),
|
|
77
|
+
...(options.checkpointStore ? { checkpointStore: options.checkpointStore } : {}),
|
|
78
|
+
...(options['exclude-rule'] ? { 'exclude-rule': options['exclude-rule'] } : {}),
|
|
70
79
|
}).then(report => ({ report }), error => ({ error }));
|
|
71
80
|
let prepared;
|
|
72
81
|
try {
|
|
@@ -94,30 +103,62 @@ async function besideSession(project, files, options, run, profile, stopsSession
|
|
|
94
103
|
// Playwright, --audit, and Vitest setups the session cannot drive rewrite the source for each mutation instead.
|
|
95
104
|
export async function analyzeOperators(project, files, options, run = { analyze, prepareAnalysis, completeAnalysis, analyzeConventional }) {
|
|
96
105
|
const profile = options.mutators ?? 'targeted';
|
|
106
|
+
const shardSelection = options.shard ? computeShardSelection(project, files, { ...options, mutators: profile }) : null;
|
|
107
|
+
let checkpointStore = null;
|
|
108
|
+
if (options.checkpoint) {
|
|
109
|
+
const root = realpathSync(project);
|
|
110
|
+
const targets = selectScope(root, files, options).map(subject => ({
|
|
111
|
+
...subject, input: readFileSync(inside(root, subject.file)),
|
|
112
|
+
}));
|
|
113
|
+
const context = computeCampaignContext(targets, { ...options, mutators: profile }, root);
|
|
114
|
+
checkpointStore = openCheckpoint(options.checkpoint, context, { mutators: profile });
|
|
115
|
+
}
|
|
116
|
+
const runOptions = {
|
|
117
|
+
...options,
|
|
118
|
+
...(shardSelection ? { shardKeys: shardSelection.keys } : {}),
|
|
119
|
+
...(checkpointStore ? { checkpointStore } : {}),
|
|
120
|
+
};
|
|
121
|
+
const finalize = report => {
|
|
122
|
+
let out = shardSelection?.meta ? { ...report, shard: shardSelection.meta } : report;
|
|
123
|
+
if (checkpointStore) {
|
|
124
|
+
if (out.evaluation === 'evaluated') checkpointStore.complete();
|
|
125
|
+
out = { ...out, checkpoint: checkpointStore.summary() };
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
};
|
|
97
129
|
const rewriting = () => {
|
|
98
|
-
const out = run.analyze(project, files, { ...
|
|
99
|
-
return carryBaseline({ ...out, mutators: profile, operatorExecution: 'source-rewrite' }, out);
|
|
130
|
+
const out = run.analyze(project, files, { ...runOptions, mutators: profile });
|
|
131
|
+
return carryBaseline(finalize({ ...out, mutators: profile, operatorExecution: 'source-rewrite' }), out);
|
|
100
132
|
};
|
|
101
|
-
if (
|
|
102
|
-
const { prepared, ended, stopped, extras, report: session, error } = await besideSession(project, files,
|
|
133
|
+
if (runOptions.runner === 'playwright' || runOptions.audit) return rewriting();
|
|
134
|
+
const { prepared, ended, stopped, extras, report: session, error } = await besideSession(project, files, runOptions, run, profile,
|
|
103
135
|
report => report.evaluation === 'baseline_error' || report.extraction.some(file => file.path === 'diagnostic'));
|
|
104
|
-
if (stopped) return carryBaseline({ ...ended, mutators: profile }, ended);
|
|
136
|
+
if (stopped) return carryBaseline(finalize({ ...ended, mutators: profile }), ended);
|
|
105
137
|
if (error) throw error;
|
|
106
138
|
if (session.evaluation === 'baseline_error') return rewriting();
|
|
107
|
-
const
|
|
139
|
+
const baseSettled = sessionVerdicts(session, extras);
|
|
140
|
+
const settled = checkpointStore
|
|
141
|
+
? trial => checkpointStore.get(checkpointKeyForTrial(trial)) ?? baseSettled(trial)
|
|
142
|
+
: baseSettled;
|
|
143
|
+
const completed = ended ?? run.completeAnalysis(prepared, settled);
|
|
144
|
+
if (checkpointStore) {
|
|
145
|
+
for (const mutant of completed.mutants ?? []) {
|
|
146
|
+
checkpointStore.record(checkpointKeyForTrial(mutant), mutant);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
108
149
|
const focused = carryBaseline({ ...completed, mutators: profile }, completed);
|
|
109
|
-
if (session.evaluation === 'no_sites') return carryBaseline({ ...focused, operatorExecution: 'session' }, focused);
|
|
150
|
+
if (session.evaluation === 'no_sites') return carryBaseline(finalize({ ...focused, operatorExecution: 'session' }), focused);
|
|
110
151
|
// A comparison boundary appears in both parts. The focused result carries the missing input, so it is the one kept.
|
|
111
152
|
const boundaries = new Set(focused.mutants.map(mutant => `${mutant.location.file}:${mutant.edit[0]}:${mutant.replacement}`));
|
|
112
153
|
const added = session.mutants.filter(mutant => !(mutant.operatorSwap &&
|
|
113
154
|
boundaries.has(`${mutant.location.file}:${mutant.operatorSwap.join(':')}`)));
|
|
114
|
-
return carryBaseline({
|
|
155
|
+
return carryBaseline(finalize({
|
|
115
156
|
...focused,
|
|
116
157
|
operatorExecution: 'session',
|
|
117
158
|
trials: session.trials,
|
|
118
159
|
baseline: focused.baseline ?? session.baseline,
|
|
119
160
|
evaluation: session.evaluation === 'incomplete' || focused.evaluation === 'incomplete' ? 'incomplete' : 'evaluated',
|
|
120
161
|
mutants: [...focused.mutants, ...added.map(mutant => fromSession(mutant, profile))].sort(order),
|
|
121
|
-
diagnostics: [...focused.diagnostics, ...(session.diagnostics ?? [])],
|
|
122
|
-
}, focused);
|
|
162
|
+
diagnostics: suppressEnclosingDiagnostics([...focused.diagnostics, ...(session.diagnostics ?? [])]),
|
|
163
|
+
}), focused);
|
|
123
164
|
}
|