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.
- package/LICENSE +201 -0
- package/NOTICE +21 -0
- package/README.md +111 -2
- package/bin/tmt-compile.mjs +46 -0
- package/bin/tmt.mjs +117 -0
- package/build/typescript-syntax/LICENSE.txt +55 -0
- package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
- package/build/typescript-syntax/typescript-syntax.cjs +43 -0
- package/docs/analysis.md +218 -0
- package/docs/compiler.md +462 -0
- package/docs/development.md +61 -0
- package/docs/how-it-works.svg +188 -0
- package/docs/l1.md +94 -0
- package/docs/performance.md +647 -0
- package/docs/releasing.md +48 -0
- package/package.json +49 -4
- package/src/analysis.mjs +689 -0
- package/src/assertion-session.mjs +93 -0
- package/src/assertion-strength.mjs +795 -0
- package/src/builtin-mutations.mjs +755 -0
- package/src/builtin-switches.mjs +642 -0
- package/src/change-undone.mjs +524 -0
- package/src/cli-output.mjs +166 -0
- package/src/compiler-compat.cjs +108 -0
- package/src/compiler-maps.cjs +60 -0
- package/src/compiler-routes.cjs +391 -0
- package/src/compiler.cjs +98 -0
- package/src/compiler.mjs +1 -0
- package/src/conventional.mjs +172 -0
- package/src/displacement.mjs +19 -0
- package/src/extract.mjs +135 -0
- package/src/fallback-process.mjs +14 -0
- package/src/in-parallel.mjs +20 -0
- package/src/lean-replay.mjs +39 -0
- package/src/operator-analysis.mjs +123 -0
- package/src/playwright.mjs +139 -0
- package/src/probe-runtime.mjs +50 -0
- package/src/probe.mjs +170 -0
- package/src/prototype.mjs +230 -0
- package/src/regex-mutations.mjs +102 -0
- package/src/runner-process.mjs +59 -0
- package/src/runtime-binaries.mjs +50 -0
- package/src/scope.mjs +202 -0
- package/src/source-text.mjs +49 -0
- package/src/standard-plan.mjs +308 -0
- package/src/standard-runner.mjs +185 -0
- package/src/standard-session.mjs +362 -0
- package/src/standard-setup.mjs +20 -0
- package/src/targeted-gaps.mjs +85 -0
- package/src/threshold.mjs +185 -0
- package/src/trace-buffer.mjs +126 -0
- package/src/typescript-bindings.mjs +243 -0
- package/src/typescript-compiler.mjs +59 -0
- package/src/typescript-extraction.mjs +354 -0
- package/src/typescript-grammar.mjs +923 -0
- package/src/vitest-reporter.mjs +64 -0
- package/src/vitest.mjs +262 -0
- package/src/witness-analysis.mjs +234 -0
- package/src/witness-contracts.mjs +110 -0
- package/src/witness-discovery.mjs +239 -0
- package/src/witness-fixtures.mjs +149 -0
- package/src/witness-order.mjs +83 -0
- package/src/witness-rules.mjs +254 -0
package/src/probe.mjs
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, extname, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { withTypeScriptSyntax } from './typescript-compiler.mjs';
|
|
5
|
+
|
|
6
|
+
export function rewrite(source, edit, replacement) {
|
|
7
|
+
const [start, end] = edit;
|
|
8
|
+
return Buffer.concat([source.subarray(0, start), Buffer.from(replacement), source.subarray(end)]);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function sourceSpellings(source) {
|
|
12
|
+
return source.includes('\\u') ? source.toString().replace(/\\u(?:\{([\da-fA-F]+)\}|([\da-fA-F]{4}))/g,
|
|
13
|
+
(escape, braced, short) => {
|
|
14
|
+
const code = Number.parseInt(braced ?? short, 16);
|
|
15
|
+
return code < 128 ? String.fromCharCode(code) : escape;
|
|
16
|
+
}) : source;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function explicitPackageType(root, file) {
|
|
20
|
+
for (let directory = dirname(file); ; directory = dirname(directory)) {
|
|
21
|
+
const manifest = resolve(directory, 'package.json');
|
|
22
|
+
if (existsSync(manifest)) {
|
|
23
|
+
const contents = readFileSync(manifest, 'utf8').replace(/^\uFEFF/, '');
|
|
24
|
+
try { return JSON.parse(contents)?.type; }
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (directory === root || dirname(directory) === directory) return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const probeDirectory = '.tmt-probe';
|
|
35
|
+
const probeEntry = 'probe-runtime.mjs';
|
|
36
|
+
|
|
37
|
+
const commonJsWrapperNames = new Set(['require', 'module', 'exports', '__dirname', '__filename']);
|
|
38
|
+
|
|
39
|
+
function hasWrapperBinding(ts, name) {
|
|
40
|
+
if (ts.isIdentifier(name)) return commonJsWrapperNames.has(name.text);
|
|
41
|
+
return name.elements.some(element => ts.isBindingElement(element) && hasWrapperBinding(ts, element.name));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function ambient(ts, node) {
|
|
45
|
+
return node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DeclareKeyword);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readRuntimeModuleSyntax(ts, file, source) {
|
|
49
|
+
const parsed = ts.createSourceFile(file, source.toString(), ts.ScriptTarget.Latest, false);
|
|
50
|
+
if (parsed.statements.some(statement => {
|
|
51
|
+
if (ambient(ts, statement)) return false;
|
|
52
|
+
if (ts.isImportDeclaration(statement)) return !statement.importClause?.isTypeOnly;
|
|
53
|
+
if (ts.isExportDeclaration(statement)) return !statement.isTypeOnly;
|
|
54
|
+
if (ts.isExportAssignment(statement)) return !statement.isExportEquals;
|
|
55
|
+
if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) return false;
|
|
56
|
+
if (statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) return true;
|
|
57
|
+
if (ts.isClassDeclaration(statement) && statement.name && hasWrapperBinding(ts, statement.name)) return true;
|
|
58
|
+
return ts.isVariableStatement(statement) && (statement.declarationList.flags & ts.NodeFlags.BlockScoped) &&
|
|
59
|
+
statement.declarationList.declarations.some(declaration => hasWrapperBinding(ts, declaration.name));
|
|
60
|
+
})) return true;
|
|
61
|
+
|
|
62
|
+
const pending = [[parsed, true]];
|
|
63
|
+
while (pending.length) {
|
|
64
|
+
const [node, topLevel] = pending.pop();
|
|
65
|
+
if (ambient(ts, node) || ts.isTypeNode(node)) continue;
|
|
66
|
+
if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) return true;
|
|
67
|
+
if (topLevel && (ts.isAwaitExpression(node) || (ts.isForOfStatement(node) && node.awaitModifier))) return true;
|
|
68
|
+
const childTopLevel = topLevel && !ts.isFunctionLike(node) && !ts.isClassLike(node);
|
|
69
|
+
ts.forEachChild(node, child => { pending.push([child, childTopLevel]); });
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function hasRuntimeModuleSyntax(file, source) {
|
|
75
|
+
return withTypeScriptSyntax(ts => readRuntimeModuleSyntax(ts, file, source));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function probePreload(root, file, hasModuleSyntax) {
|
|
79
|
+
const extension = extname(file).toLowerCase();
|
|
80
|
+
if (extension === '.cjs' || extension === '.cts') return true;
|
|
81
|
+
if (extension !== '.js' && extension !== '.ts') return false;
|
|
82
|
+
const type = explicitPackageType(root, file);
|
|
83
|
+
if (type === 'module' || type === 'commonjs') return type === 'commonjs';
|
|
84
|
+
return !hasModuleSyntax();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function needsProbePreload(root, file, source) {
|
|
88
|
+
return probePreload(root, file, () => hasRuntimeModuleSyntax(file, source));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function createProbePreloadCheck(source) {
|
|
92
|
+
const byFilename = new Map();
|
|
93
|
+
return (root, file) => probePreload(root, file, () => {
|
|
94
|
+
const name = basename(file);
|
|
95
|
+
if (!byFilename.has(name)) byFilename.set(name, hasRuntimeModuleSyntax(name, source));
|
|
96
|
+
return byFilename.get(name);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function freshProbeBinding(sources) {
|
|
101
|
+
const spellings = sources.map(sourceSpellings);
|
|
102
|
+
let binding = '__tmtProbe_' + randomUUID().replaceAll('-', '');
|
|
103
|
+
while (spellings.some(source => source.includes(binding))) binding += '_';
|
|
104
|
+
return binding;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function instrument(root, file, source, sites, preloadedBinding, coverageSites) {
|
|
108
|
+
const runtime = resolve(root, probeDirectory, probeEntry);
|
|
109
|
+
const path = relative(dirname(resolve(root, file)), runtime).split(sep).join('/');
|
|
110
|
+
const spellings = sourceSpellings(source);
|
|
111
|
+
let alias = '__tmtCompare';
|
|
112
|
+
while (spellings.includes(alias)) alias += '_';
|
|
113
|
+
const comparison = preloadedBinding ? preloadedBinding + '.compare' : alias;
|
|
114
|
+
const recordHit = preloadedBinding ? preloadedBinding + '.hit' : alias + 'Hit';
|
|
115
|
+
const countHits = coverageSites && sites.some(site => coverageSites.has(site.id));
|
|
116
|
+
const sorted = sites.slice().sort((a, b) => a.left[0] - b.left[0] || b.right[1] - a.right[1]);
|
|
117
|
+
let index = 0;
|
|
118
|
+
|
|
119
|
+
function render(start, end) {
|
|
120
|
+
const chunks = [];
|
|
121
|
+
let from = start;
|
|
122
|
+
while (index < sorted.length && sorted[index].left[0] < end) {
|
|
123
|
+
const site = sorted[index++];
|
|
124
|
+
const [first, afterLeft] = site.left;
|
|
125
|
+
const [rightStart, last] = site.right;
|
|
126
|
+
if (first < from || last > end || afterLeft > site.edit[0] || rightStart < site.edit[1]) {
|
|
127
|
+
throw new Error('Overlapping probe spans');
|
|
128
|
+
}
|
|
129
|
+
const id = JSON.stringify(site.id);
|
|
130
|
+
const siteArgument = coverageSites?.has(site.id) ? recordHit + '(' + id + ')' : id;
|
|
131
|
+
chunks.push(source.subarray(from, first).toString(), comparison,
|
|
132
|
+
'(' + [siteArgument, JSON.stringify(site.operator), JSON.stringify(site.replacement)].join(',') + ',(',
|
|
133
|
+
render(first, afterLeft), source.subarray(afterLeft, site.edit[0]).toString(), '),(',
|
|
134
|
+
source.subarray(site.edit[1], rightStart).toString(), render(rightStart, last), '))');
|
|
135
|
+
from = last;
|
|
136
|
+
}
|
|
137
|
+
chunks.push(source.subarray(from, end).toString());
|
|
138
|
+
return chunks.join('');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const sourceText = render(0, source.length);
|
|
142
|
+
const specifier = JSON.stringify(path.startsWith('../') ? path : './' + path);
|
|
143
|
+
const ids = JSON.stringify(sites.map(site => site.id));
|
|
144
|
+
if (preloadedBinding) return sourceText + '\n' + preloadedBinding + '.loaded(' + ids + ');\n';
|
|
145
|
+
const coverageImport = countHits ? ', hit as ' + recordHit : '';
|
|
146
|
+
return sourceText + '\nimport { compare as ' + alias + ', loaded as ' + alias + 'Loaded' + coverageImport + ' } from ' +
|
|
147
|
+
specifier + ';\n' + alias + 'Loaded(' + ids + ');\n';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function installProbe(root, preloadedBinding) {
|
|
151
|
+
const directory = resolve(root, probeDirectory);
|
|
152
|
+
mkdirSync(directory);
|
|
153
|
+
copyFileSync(new URL('./probe-runtime.mjs', import.meta.url), resolve(directory, probeEntry), 1);
|
|
154
|
+
copyFileSync(new URL('./trace-buffer.mjs', import.meta.url), resolve(directory, 'trace-buffer.mjs'), 1);
|
|
155
|
+
if (!preloadedBinding) return;
|
|
156
|
+
const preload = resolve(root, '.tmt-probe-register.cjs');
|
|
157
|
+
writeFileSync(preload, `
|
|
158
|
+
'use strict';
|
|
159
|
+
let runtime;
|
|
160
|
+
const load = () => runtime ??= require('./${probeDirectory}/${probeEntry}');
|
|
161
|
+
Object.defineProperty(globalThis, ${JSON.stringify(preloadedBinding)}, {
|
|
162
|
+
value: {
|
|
163
|
+
compare: (...args) => load().compare(...args),
|
|
164
|
+
loaded: ids => load().loaded(ids),
|
|
165
|
+
hit: id => load().hit(id),
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
`, { flag: 'wx' });
|
|
169
|
+
return preload;
|
|
170
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, relative, resolve } from 'node:path';
|
|
4
|
+
import { thresholdGaps } from './threshold.mjs';
|
|
5
|
+
import { withTypeScriptSyntax } from './typescript-compiler.mjs';
|
|
6
|
+
import { inside, runVitest, withCopy } from './vitest.mjs';
|
|
7
|
+
|
|
8
|
+
function readThresholdSites(ts, source, file, operators) {
|
|
9
|
+
const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
|
|
10
|
+
if (tree.parseDiagnostics.length) {
|
|
11
|
+
return { error: ts.flattenDiagnosticMessageText(tree.parseDiagnostics[0].messageText, '\n') };
|
|
12
|
+
}
|
|
13
|
+
const sites = [];
|
|
14
|
+
const extractBody = fn => {
|
|
15
|
+
if (!fn.body) return null;
|
|
16
|
+
if (!ts.isBlock(fn.body)) return fn.body;
|
|
17
|
+
const [only] = fn.body.statements;
|
|
18
|
+
return fn.body.statements.length === 1 && ts.isReturnStatement(only) ? only.expression : null;
|
|
19
|
+
};
|
|
20
|
+
const inspectFunction = (nameNode, fn) => {
|
|
21
|
+
if (!ts.isIdentifier(nameNode) || fn.asteriskToken ||
|
|
22
|
+
fn.modifiers?.some(modifier => ![ts.SyntaxKind.ExportKeyword].includes(modifier.kind)) ||
|
|
23
|
+
fn.parameters.length !== 1) return;
|
|
24
|
+
|
|
25
|
+
const parameter = fn.parameters[0];
|
|
26
|
+
const comparison = extractBody(fn);
|
|
27
|
+
if (!ts.isIdentifier(parameter.name) || parameter.initializer || parameter.dotDotDotToken ||
|
|
28
|
+
!comparison || !ts.isBinaryExpression(comparison) || !ts.isIdentifier(comparison.left) ||
|
|
29
|
+
comparison.left.text !== parameter.name.text) return;
|
|
30
|
+
const operator = comparison.operatorToken.getText(tree);
|
|
31
|
+
if (!operators.has(operator)) return;
|
|
32
|
+
|
|
33
|
+
const literal = comparison.right;
|
|
34
|
+
const numeric = ts.isNumericLiteral(literal)
|
|
35
|
+
? literal : ts.isPrefixUnaryExpression(literal) && literal.operator === ts.SyntaxKind.MinusToken &&
|
|
36
|
+
ts.isNumericLiteral(literal.operand) ? literal.operand : undefined;
|
|
37
|
+
if (!numeric) return;
|
|
38
|
+
const value = Number(numeric.text);
|
|
39
|
+
const threshold = numeric === literal ? value : -value;
|
|
40
|
+
if (!Number.isSafeInteger(threshold)) return;
|
|
41
|
+
sites.push({
|
|
42
|
+
operator,
|
|
43
|
+
functionName: nameNode.getText(tree),
|
|
44
|
+
threshold,
|
|
45
|
+
operand: comparison.left.getText(tree),
|
|
46
|
+
from: comparison.getStart(tree),
|
|
47
|
+
to: comparison.end,
|
|
48
|
+
literalFrom: literal.getStart(tree),
|
|
49
|
+
literalTo: literal.end,
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
for (const statement of tree.statements) {
|
|
53
|
+
if (!statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue;
|
|
54
|
+
if (ts.isFunctionDeclaration(statement) && statement.name) {
|
|
55
|
+
inspectFunction(statement.name, statement);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
|
|
59
|
+
|
|
60
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
61
|
+
const arrow = declaration.initializer;
|
|
62
|
+
if (arrow && ts.isArrowFunction(arrow)) inspectFunction(declaration.name, arrow);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { sites };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function scanThresholdSites(source, file, operators) {
|
|
69
|
+
const { sites, error } = withTypeScriptSyntax(ts => readThresholdSites(ts, source, file, operators));
|
|
70
|
+
if (error !== undefined) throw new Error(error);
|
|
71
|
+
return sites;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const comparisonOperators = new Set(['<', '<=', '>', '>=']);
|
|
75
|
+
|
|
76
|
+
export function comparisonThresholdSites(source, file) {
|
|
77
|
+
return scanThresholdSites(source, file, comparisonOperators);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function thresholdSites(source, file, operator = '>=') {
|
|
81
|
+
return scanThresholdSites(source, file, new Set([operator])).map(({ operator: _, ...site }) => site);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function edit(source, start, end, replacement) {
|
|
85
|
+
return source.slice(0, start) + replacement + source.slice(end);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function moduleSpecifier(from, to) {
|
|
89
|
+
const path = relative(dirname(from), to);
|
|
90
|
+
return JSON.stringify(path.startsWith('../') ? path : './' + path);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function sourceIdentifiers(ts, source, target) {
|
|
94
|
+
const tree = ts.createSourceFile(target, source, ts.ScriptTarget.Latest, true);
|
|
95
|
+
const identifiers = new Set();
|
|
96
|
+
function visit(node) {
|
|
97
|
+
if (ts.isIdentifier(node)) identifiers.add(node.text);
|
|
98
|
+
ts.forEachChild(node, visit);
|
|
99
|
+
}
|
|
100
|
+
visit(tree);
|
|
101
|
+
return identifiers;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function instrument(source, sites, target, root) {
|
|
105
|
+
const identifiers = withTypeScriptSyntax(ts => sourceIdentifiers(ts, source, target));
|
|
106
|
+
let alias = '__tmtThreshold';
|
|
107
|
+
while (identifiers.has(alias)) alias += '_';
|
|
108
|
+
|
|
109
|
+
const runtime = resolve(root, `.tmt-observation-${randomUUID()}.mjs`);
|
|
110
|
+
writeFileSync(runtime, `import { appendFileSync } from 'node:fs';
|
|
111
|
+
export function record(site, value, threshold) {
|
|
112
|
+
const result = value >= threshold;
|
|
113
|
+
appendFileSync(process.env.TMT_TRACE, JSON.stringify([site, Number.isSafeInteger(value) ? value : null]) + '\\n');
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
`, { flag: 'wx' });
|
|
117
|
+
let result = source;
|
|
118
|
+
for (const site of sites.toReversed()) {
|
|
119
|
+
const literal = source.slice(site.literalFrom, site.literalTo);
|
|
120
|
+
result = edit(result, site.from, site.to, `${alias}(${site.from}, ${site.operand}, ${literal})`);
|
|
121
|
+
}
|
|
122
|
+
return result + `\nimport { record as ${alias} } from ${moduleSpecifier(target, runtime)};\n`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function inventory(run, without) {
|
|
126
|
+
return run.tests?.filter(test => test.file !== without).map(test => JSON.stringify([test.file, test.name, test.status])).sort().join('\n');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function verifyWitness(root, temp, target, site, gap, source, mutant, baseline) {
|
|
130
|
+
const dir = resolve(root, 'test');
|
|
131
|
+
mkdirSync(dir, { recursive: true });
|
|
132
|
+
const witnessFile = resolve(inside(root, dir), `tmt-witness-${randomUUID()}.test.ts`);
|
|
133
|
+
const file = relative(root, witnessFile);
|
|
134
|
+
const name = 'TMT generated threshold witness';
|
|
135
|
+
writeFileSync(witnessFile, `import { it, expect } from 'vitest';
|
|
136
|
+
import { ${site.functionName} as subject } from ${moduleSpecifier(witnessFile, target)};
|
|
137
|
+
it(${JSON.stringify(name)}, () => expect(subject(${gap.witness})).toBe(${gap.expected}));
|
|
138
|
+
`, { flag: 'wx' });
|
|
139
|
+
try {
|
|
140
|
+
writeFileSync(target, source);
|
|
141
|
+
const original = runVitest(root, temp);
|
|
142
|
+
writeFileSync(target, mutant);
|
|
143
|
+
const rewritten = runVitest(root, temp);
|
|
144
|
+
function outcome(run, expected) {
|
|
145
|
+
const tests = run.tests?.filter(test => test.file === file);
|
|
146
|
+
if (run.status === expected && tests?.length === 1 && tests[0].name === name && tests[0].status === expected &&
|
|
147
|
+
inventory(run, file) === inventory(baseline)) return expected;
|
|
148
|
+
return 'unconfirmed';
|
|
149
|
+
}
|
|
150
|
+
return { baselineWithWitness: outcome(original, 'passed'), rewriteWithWitness: outcome(rewritten, 'failed') };
|
|
151
|
+
} finally {
|
|
152
|
+
rmSync(witnessFile);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function expectPassing(run, phase) {
|
|
157
|
+
if (run.status !== 'passed') throw new Error(`${phase} Vitest run: ${run.status}\n${run.output}`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function location(source, file, site) {
|
|
161
|
+
const before = source.slice(0, site.literalFrom);
|
|
162
|
+
const lines = before.split(/\r\n|[\n\r\u2028\u2029]/);
|
|
163
|
+
return { file, line: lines.length, column: lines.at(-1).length + 1,
|
|
164
|
+
start: Buffer.byteLength(before), end: Buffer.byteLength(source.slice(0, site.literalTo)) };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function readTrace(path) {
|
|
168
|
+
if (!existsSync(path)) return [];
|
|
169
|
+
return readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function runPrototype(project, file, { spec } = {}) {
|
|
173
|
+
return withCopy(project, (root, temp) => {
|
|
174
|
+
const target = inside(root, file);
|
|
175
|
+
const name = relative(root, target);
|
|
176
|
+
const source = readFileSync(target, 'utf8');
|
|
177
|
+
const sites = thresholdSites(source, name);
|
|
178
|
+
if (!sites.length) return { diagnostics: [] };
|
|
179
|
+
|
|
180
|
+
const specification = spec ? JSON.parse(readFileSync(inside(root, spec), 'utf8')) : {};
|
|
181
|
+
const baseline = runVitest(root, temp);
|
|
182
|
+
expectPassing(baseline, 'Baseline');
|
|
183
|
+
|
|
184
|
+
const trace = resolve(temp, 'trace.jsonl');
|
|
185
|
+
writeFileSync(target, instrument(source, sites, target, root));
|
|
186
|
+
const instrumented = runVitest(root, temp, { trace });
|
|
187
|
+
expectPassing(instrumented, 'Instrumented baseline');
|
|
188
|
+
if (inventory(instrumented) !== inventory(baseline)) throw new Error('Instrumented baseline changed the test inventory');
|
|
189
|
+
const observations = readTrace(trace);
|
|
190
|
+
const diagnostics = [];
|
|
191
|
+
|
|
192
|
+
const candidates = sites.map(site => {
|
|
193
|
+
const observed = observations.filter(([id]) => id === site.from).map(([, value]) => value);
|
|
194
|
+
const contract = Object.hasOwn(specification, site.functionName) ? specification[site.functionName] : null;
|
|
195
|
+
const specified = contract?.operator === '>=' && contract.threshold === site.threshold && Boolean(contract.rationale?.trim());
|
|
196
|
+
return { site, specified, observed, request: {
|
|
197
|
+
threshold: site.threshold, observations: observed,
|
|
198
|
+
min: specified ? contract.min : undefined, max: specified ? contract.max : undefined,
|
|
199
|
+
} };
|
|
200
|
+
});
|
|
201
|
+
const gaps = thresholdGaps(candidates.map(candidate => candidate.request));
|
|
202
|
+
for (const [index, { site, specified, observed }] of candidates.entries()) {
|
|
203
|
+
const gap = gaps[index];
|
|
204
|
+
if (!gap) continue;
|
|
205
|
+
|
|
206
|
+
const mutant = edit(source, site.literalFrom, site.literalTo, String(gap.alternate));
|
|
207
|
+
writeFileSync(target, mutant);
|
|
208
|
+
const rewrite = runVitest(root, temp);
|
|
209
|
+
if (rewrite.status !== 'passed' || inventory(rewrite) !== inventory(baseline)) continue;
|
|
210
|
+
|
|
211
|
+
const verification = {
|
|
212
|
+
baseline: 'passed', instrumented: 'passed', rewrite: 'passed',
|
|
213
|
+
...verifyWitness(root, temp, target, site, gap, source, mutant, baseline),
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
diagnostics.push({
|
|
217
|
+
kind: 'INPUT GAP',
|
|
218
|
+
location: location(source, name, site),
|
|
219
|
+
mutation: { original: source.slice(site.from, site.to), source: mutant.slice(site.from, site.to + String(gap.alternate).length - (site.literalTo - site.literalFrom)) },
|
|
220
|
+
observedInputs: [...new Set(observed)].sort((a, b) => a - b),
|
|
221
|
+
feasibleThresholds: gap.interval,
|
|
222
|
+
witness: { input: gap.witness, original: gap.expected, mutant: gap.mutant, expectation: specified ? 'specification' : 'original' },
|
|
223
|
+
suggestedTest: `expect(${site.functionName}(${gap.witness})).toBe(${gap.expected})`,
|
|
224
|
+
verification,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return { diagnostics };
|
|
229
|
+
});
|
|
230
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// First-level regular expression mutations: anchors, class negation, quantifier removal and lookaround negation.
|
|
2
|
+
// Every result is compiled once, because an invalid literal would stop the whole module from loading.
|
|
3
|
+
const predefined = new Map([['d', 'D'], ['D', 'd'], ['s', 'S'], ['S', 's'], ['w', 'W'], ['W', 'w']]);
|
|
4
|
+
|
|
5
|
+
function quantifierEnd(pattern, at) {
|
|
6
|
+
const unit = pattern[at];
|
|
7
|
+
let end;
|
|
8
|
+
if (unit === '?' || unit === '*' || unit === '+') end = at + 1;
|
|
9
|
+
else if (unit === '{') {
|
|
10
|
+
const match = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(at));
|
|
11
|
+
if (!match) return -1;
|
|
12
|
+
end = at + match[0].length;
|
|
13
|
+
} else return -1;
|
|
14
|
+
return pattern[end] === '?' ? end + 1 : end;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function mutatePattern(pattern, flags = '') {
|
|
18
|
+
if (!pattern.length) return [];
|
|
19
|
+
const compiles = source => {
|
|
20
|
+
try {
|
|
21
|
+
new RegExp(source, flags);
|
|
22
|
+
return true;
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
if (!compiles(pattern)) return [];
|
|
28
|
+
const unicode = /[uv]/.test(flags);
|
|
29
|
+
const edits = [];
|
|
30
|
+
const replace = (start, end, text) => edits.push(pattern.slice(0, start) + text + pattern.slice(end));
|
|
31
|
+
let inClass = false;
|
|
32
|
+
let quantifiable = false;
|
|
33
|
+
for (let at = 0; at < pattern.length; at++) {
|
|
34
|
+
const unit = pattern[at];
|
|
35
|
+
if (unit === '\\') {
|
|
36
|
+
const next = pattern[at + 1];
|
|
37
|
+
if (predefined.has(next)) replace(at + 1, at + 2, predefined.get(next));
|
|
38
|
+
else if (unicode && (next === 'p' || next === 'P') && pattern[at + 2] === '{') replace(at + 1, at + 2, next === 'p' ? 'P' : 'p');
|
|
39
|
+
if (unicode && (next === 'p' || next === 'P' || next === 'u') && pattern[at + 2] === '{') at = pattern.indexOf('}', at);
|
|
40
|
+
else if (next === 'k' && pattern[at + 2] === '<') at = pattern.indexOf('>', at);
|
|
41
|
+
else if (next === 'c') at += 2;
|
|
42
|
+
else if (next === 'x') at += 3;
|
|
43
|
+
else if (next === 'u') at += 5;
|
|
44
|
+
else at++;
|
|
45
|
+
quantifiable = !inClass;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (inClass) {
|
|
49
|
+
if (unit === ']') {
|
|
50
|
+
inClass = false;
|
|
51
|
+
quantifiable = true;
|
|
52
|
+
}
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (unit === '[') {
|
|
56
|
+
if (pattern[at + 1] === '^') replace(at + 1, at + 2, '');
|
|
57
|
+
else replace(at + 1, at + 1, '^');
|
|
58
|
+
inClass = true;
|
|
59
|
+
// In JavaScript `[]` and `[^]` are complete classes: a closing bracket is never a literal first member.
|
|
60
|
+
if (pattern[at + 1] === '^') at++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (unit === '^') {
|
|
64
|
+
replace(at, at + 1, '');
|
|
65
|
+
quantifiable = false;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (unit === '$') {
|
|
69
|
+
replace(at, at + 1, '');
|
|
70
|
+
quantifiable = false;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (unit === '(') {
|
|
74
|
+
const look = /^\(\?(<?)([=!])/.exec(pattern.slice(at));
|
|
75
|
+
if (look) {
|
|
76
|
+
const sign = at + 2 + look[1].length;
|
|
77
|
+
replace(sign, sign + 1, look[2] === '=' ? '!' : '=');
|
|
78
|
+
at = sign;
|
|
79
|
+
} else if (pattern[at + 1] === '?') {
|
|
80
|
+
const named = /^\(\?<[^>]+>/.exec(pattern.slice(at));
|
|
81
|
+
at += named ? named[0].length - 1 : 2;
|
|
82
|
+
}
|
|
83
|
+
quantifiable = false;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (unit === '|') {
|
|
87
|
+
quantifiable = false;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (quantifiable) {
|
|
91
|
+
const end = quantifierEnd(pattern, at);
|
|
92
|
+
if (end > 0) {
|
|
93
|
+
replace(at, end, '');
|
|
94
|
+
at = end - 1;
|
|
95
|
+
quantifiable = false;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
quantifiable = true;
|
|
100
|
+
}
|
|
101
|
+
return [...new Set(edits)].filter(source => source !== pattern && compiles(source));
|
|
102
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { writeFileSync } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
const [pidReport, timeout, command, ...args] = process.argv.slice(2);
|
|
5
|
+
const parent = process.ppid;
|
|
6
|
+
const child = spawn(process.execPath, [command, ...args], { detached: process.platform !== 'win32', stdio: 'inherit' });
|
|
7
|
+
let closed = false;
|
|
8
|
+
let status;
|
|
9
|
+
let interrupted = false;
|
|
10
|
+
|
|
11
|
+
function signalChild(signal) {
|
|
12
|
+
if (!child.pid) return false;
|
|
13
|
+
try {
|
|
14
|
+
if (process.platform === 'win32') return child.kill(signal);
|
|
15
|
+
return process.kill(-child.pid, signal);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
// macOS answers EPERM for a group whose only member has exited and is not reaped yet.
|
|
18
|
+
if (error.code !== 'ESRCH' && error.code !== 'EPERM') throw error;
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function finish(code) {
|
|
24
|
+
if (closed) return;
|
|
25
|
+
closed = true;
|
|
26
|
+
clearTimeout(deadline);
|
|
27
|
+
clearInterval(parentWatch);
|
|
28
|
+
status = interrupted ? 124 : code;
|
|
29
|
+
if (!signalChild('SIGTERM')) {
|
|
30
|
+
process.exitCode = status;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
setTimeout(() => {
|
|
34
|
+
signalChild('SIGKILL');
|
|
35
|
+
process.exitCode = status;
|
|
36
|
+
}, 120);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const deadline = setTimeout(() => {
|
|
40
|
+
interrupted = true;
|
|
41
|
+
finish(124);
|
|
42
|
+
}, Number(timeout));
|
|
43
|
+
const parentWatch = process.platform === 'win32' ? null : setInterval(() => {
|
|
44
|
+
if (process.ppid === parent) return;
|
|
45
|
+
interrupted = true;
|
|
46
|
+
finish(124);
|
|
47
|
+
}, 200);
|
|
48
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
49
|
+
process.once(signal, () => {
|
|
50
|
+
interrupted = true;
|
|
51
|
+
finish(124);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
child.once('spawn', () => writeFileSync(pidReport, String(child.pid)));
|
|
55
|
+
child.once('exit', code => finish(code ?? 1));
|
|
56
|
+
child.once('error', error => {
|
|
57
|
+
console.error(error.message);
|
|
58
|
+
finish(1);
|
|
59
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
export const scope = '@targeted-mutation';
|
|
7
|
+
export const supportedTargets = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64'];
|
|
8
|
+
|
|
9
|
+
export function platformPackage(platform, arch) {
|
|
10
|
+
const target = `${platform}-${arch}`;
|
|
11
|
+
return supportedTargets.includes(target) ? `${scope}/tmt-${target}` : null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// A checkout's own build wins. An installed platform package must match this release exactly.
|
|
15
|
+
// `context.version` is read only when a platform package is installed: a bare copy of bin/ and src/ has no manifest.
|
|
16
|
+
export function locateBinary(name, context) {
|
|
17
|
+
const { host, localRoot, exists, resolvePackage } = context;
|
|
18
|
+
const local = join(localRoot, name);
|
|
19
|
+
if (exists(local)) return { path: local, source: 'local' };
|
|
20
|
+
const packageName = platformPackage(host.platform, host.arch);
|
|
21
|
+
if (!packageName) return null;
|
|
22
|
+
const installed = resolvePackage(packageName);
|
|
23
|
+
if (!installed || installed.version !== context.version) return null;
|
|
24
|
+
const path = join(installed.root, name);
|
|
25
|
+
return exists(path) ? { path, source: 'package' } : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const require = createRequire(import.meta.url);
|
|
29
|
+
const localRoot = fileURLToPath(new URL('../build/', import.meta.url));
|
|
30
|
+
let ownVersion;
|
|
31
|
+
|
|
32
|
+
export function installedPackage(name, resolver = require) {
|
|
33
|
+
try {
|
|
34
|
+
const manifest = resolver.resolve(`${name}/package.json`);
|
|
35
|
+
return { root: dirname(manifest), version: JSON.parse(readFileSync(manifest, 'utf8')).version };
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function packageVersion() {
|
|
42
|
+
ownVersion ??= JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
43
|
+
return ownVersion;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function binaryPath(name) {
|
|
47
|
+
return locateBinary(name, {
|
|
48
|
+
host: process, get version() { return packageVersion(); }, localRoot, exists: existsSync, resolvePackage: installedPackage,
|
|
49
|
+
})?.path ?? null;
|
|
50
|
+
}
|