crossexamdev 0.2.0 → 0.3.0

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/src/mutate.js ADDED
@@ -0,0 +1,443 @@
1
+ // Mutation operators: plant small, deterministic defects in changed code.
2
+ //
3
+ // Pure functions, no I/O. The engine works on a "masked" copy of the source
4
+ // in which strings, template literals, comments and regex literals are blanked
5
+ // out (same length, newlines kept), so an operator never fires inside text and
6
+ // every offset in the masked copy is also an offset in the original.
7
+
8
+ export const CODE_EXT = /\.(?:py|go|rs|java|kt|kts|rb|swift|cs|php|c|cc|cpp|h|hpp|scala|ex|exs|dart|vue|svelte|lua|r|jl)$/i;
9
+ export const JS_EXT = /\.(?:[cm]?jsx?|[cm]?tsx?)$/i;
10
+ export const TEST_FILE = /(?:^|[\\/])(?:__tests__|__mocks__|tests?|spec|e2e|fixtures?)[\\/]|[._-](?:test|spec)\.[cm]?[jt]sx?$/i;
11
+ const SKIP_FILE = /(?:^|[\\/])(?:node_modules|dist|build|out|coverage|\.next|\.nuxt|vendor)[\\/]|\.d\.[cm]?ts$|\.min\.js$|(?:^|[\\/])(?:vite|vitest|jest|webpack|rollup|babel|eslint|prettier|tailwind|postcss|next|svelte)\.config\.[cm]?[jt]s$/i;
12
+
13
+ /** Why a file is or isn't mutated. */
14
+ export function classifyFile(file) {
15
+ if (TEST_FILE.test(file)) return { ok: false, reason: 'test file' };
16
+ if (SKIP_FILE.test(file)) return { ok: false, reason: 'generated, vendored or config' };
17
+ if (!JS_EXT.test(file)) return CODE_EXT.test(file) ? { ok: false, reason: 'language not supported yet' } : { ok: false, reason: 'not source code', quiet: true };
18
+ return { ok: true, language: /tsx?$/i.test(file) ? 'typescript' : 'javascript' };
19
+ }
20
+
21
+ // ---------- masking ----------
22
+
23
+ const REGEX_BEFORE = /[(,=:[!&|?{};+\-*%<>~^]$/;
24
+ const REGEX_KEYWORD = /\b(?:return|typeof|case|in|of|new|delete|void|throw|yield|await|else|do)$/;
25
+
26
+ /** Blank out strings, templates, comments and regex literals (JS/TS). */
27
+ export function maskJs(src) {
28
+ const out = src.split('');
29
+ const n = src.length;
30
+ const blank = (a, b) => {
31
+ for (let k = a; k < b && k < n; k++) if (out[k] !== '\n') out[k] = ' ';
32
+ };
33
+ let i = 0;
34
+ // Last significant (unmasked, non-space) text, to tell regex from division.
35
+ const prevSig = (at) => {
36
+ let k = at - 1;
37
+ while (k >= 0 && /\s/.test(out[k])) k--;
38
+ return out.slice(Math.max(0, k - 12), k + 1).join('');
39
+ };
40
+
41
+ const skipTemplate = (start) => {
42
+ // start is at the opening backtick; returns index after the closing one.
43
+ let k = start + 1;
44
+ while (k < n) {
45
+ const ch = src[k];
46
+ if (ch === '\\') k += 2;
47
+ else if (ch === '`') return k + 1;
48
+ else if (ch === '$' && src[k + 1] === '{') {
49
+ k = skipExpr(k + 2);
50
+ } else k++;
51
+ }
52
+ return n;
53
+ };
54
+ const skipQuoted = (start, q) => {
55
+ let k = start + 1;
56
+ while (k < n && src[k] !== q && src[k] !== '\n') k += src[k] === '\\' ? 2 : 1;
57
+ return Math.min(n, k + 1);
58
+ };
59
+ const skipExpr = (start) => {
60
+ // inside ${ … }: balance braces, honouring nested strings and templates.
61
+ let depth = 1;
62
+ let k = start;
63
+ while (k < n && depth > 0) {
64
+ const ch = src[k];
65
+ if (ch === '{') depth++;
66
+ else if (ch === '}') depth--;
67
+ else if (ch === '`') {
68
+ k = skipTemplate(k);
69
+ continue;
70
+ } else if (ch === '"' || ch === "'") {
71
+ k = skipQuoted(k, ch);
72
+ continue;
73
+ }
74
+ k++;
75
+ }
76
+ return k;
77
+ };
78
+
79
+ while (i < n) {
80
+ const ch = src[i];
81
+ const nx = src[i + 1];
82
+ if (ch === '/' && nx === '/') {
83
+ const e = src.indexOf('\n', i);
84
+ const end = e < 0 ? n : e;
85
+ blank(i, end);
86
+ i = end;
87
+ } else if (ch === '/' && nx === '*') {
88
+ const e = src.indexOf('*/', i + 2);
89
+ const end = e < 0 ? n : e + 2;
90
+ blank(i, end);
91
+ i = end;
92
+ } else if (ch === '"' || ch === "'") {
93
+ const end = skipQuoted(i, ch);
94
+ blank(i, end);
95
+ i = end;
96
+ } else if (ch === '`') {
97
+ const end = skipTemplate(i);
98
+ blank(i, end);
99
+ i = end;
100
+ } else if (ch === '/') {
101
+ const before = prevSig(i);
102
+ if (before === '' || REGEX_BEFORE.test(before) || REGEX_KEYWORD.test(before)) {
103
+ let k = i + 1;
104
+ let cls = false;
105
+ while (k < n && src[k] !== '\n') {
106
+ if (src[k] === '\\') k += 2;
107
+ else if (src[k] === '[') (cls = true), k++;
108
+ else if (src[k] === ']') (cls = false), k++;
109
+ else if (src[k] === '/' && !cls) break;
110
+ else k++;
111
+ }
112
+ if (src[k] === '/') {
113
+ k++;
114
+ while (k < n && /[a-z]/i.test(src[k])) k++;
115
+ blank(i, k);
116
+ i = k;
117
+ } else i++;
118
+ } else i++;
119
+ } else i++;
120
+ }
121
+ return out.join('');
122
+ }
123
+
124
+ // ---------- lines ----------
125
+
126
+ export function lineStarts(src) {
127
+ const starts = [0];
128
+ for (let i = 0; i < src.length; i++) if (src[i] === '\n') starts.push(i + 1);
129
+ return starts;
130
+ }
131
+
132
+ export function lineOf(starts, offset) {
133
+ let lo = 0;
134
+ let hi = starts.length - 1;
135
+ while (lo < hi) {
136
+ const mid = (lo + hi + 1) >> 1;
137
+ if (starts[mid] <= offset) lo = mid;
138
+ else hi = mid - 1;
139
+ }
140
+ return lo + 1;
141
+ }
142
+
143
+ // ---------- functions ----------
144
+
145
+ const NOT_A_NAME = new Set(['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'with', 'constructor', 'super', 'typeof', 'new', 'await', 'import', 'export']);
146
+
147
+ function matchClose(masked, open) {
148
+ const pair = { '(': ')', '{': '}', '[': ']' }[masked[open]];
149
+ let depth = 0;
150
+ for (let k = open; k < masked.length; k++) {
151
+ const ch = masked[k];
152
+ if (ch === masked[open]) depth++;
153
+ else if (ch === pair && --depth === 0) return k;
154
+ }
155
+ return -1;
156
+ }
157
+
158
+ /**
159
+ * Named function-like ranges in JS/TS. Lexical, not a full parser: good enough
160
+ * to say which function a changed line belongs to.
161
+ * @returns {{name: string, line: number, start: number, end: number}[]}
162
+ */
163
+ export function findFunctions(masked) {
164
+ const starts = lineStarts(masked);
165
+ const found = [];
166
+ const add = (name, at, bodyFrom) => {
167
+ if (!name || NOT_A_NAME.has(name)) return;
168
+ const range = bodyRange(masked, bodyFrom);
169
+ if (range) found.push({ name, line: lineOf(starts, at), start: at, end: range });
170
+ };
171
+
172
+ // function foo(…) { async function* foo<T>(…) {
173
+ for (const m of masked.matchAll(/\b(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>{]*>)?\s*\(/g)) {
174
+ add(m[1], m.index, m.index + m[0].length - 1);
175
+ }
176
+ // const foo = (…) => … const foo = async x => … const foo = function (…) {
177
+ for (const m of masked.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:async\s+)?(?=function\b|\(|[A-Za-z_$][\w$]*\s*=>|<)/g)) {
178
+ add(m[1], m.index, m.index + m[0].length);
179
+ }
180
+ // foo: (…) => … foo: function (…) {
181
+ for (const m of masked.matchAll(/(?<![\w$.?])([A-Za-z_$][\w$]*)\s*:\s*(?:async\s+)?(?=function\b|\([^()]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/g)) {
182
+ add(m[1], m.index, m.index + m[0].length);
183
+ }
184
+ // class / object methods: async foo(…) { static get bar() { foo<T>(…): Type {
185
+ for (const m of masked.matchAll(/^[ \t]*(?:(?:public|private|protected|static|async|override|readonly|get|set|abstract)\s+)*\*?\s*([A-Za-z_$#][\w$]*)\s*(?:<[^>\n]*>)?\s*\(/gm)) {
186
+ const open = m.index + m[0].length - 1;
187
+ const close = matchClose(masked, open);
188
+ if (close < 0) continue;
189
+ // Only a method if a body brace follows the parameter list (allowing a return type).
190
+ const tail = masked.slice(close + 1, close + 200).match(/^\s*(?::\s*[^{;]+?)?\s*\{/);
191
+ if (tail) add(m[1], m.index + m[0].indexOf(m[1]), open);
192
+ }
193
+
194
+ // Dedupe by start, innermost-first lookups come from sorting by size.
195
+ const byStart = new Map();
196
+ for (const f of found) if (!byStart.has(f.start) || byStart.get(f.start).end < f.end) byStart.set(f.start, f);
197
+ return [...byStart.values()].sort((a, b) => a.start - b.start);
198
+ }
199
+
200
+ /** From somewhere in a function header, find where its body ends. */
201
+ function bodyRange(masked, from) {
202
+ let k = from;
203
+ // Skip a parameter list if we're on one.
204
+ while (k < masked.length && /\s/.test(masked[k])) k++;
205
+ if (masked.startsWith('function', k)) {
206
+ const p = masked.indexOf('(', k);
207
+ if (p < 0) return null;
208
+ k = p;
209
+ }
210
+ if (masked[k] === '<') {
211
+ // generic arrow: <T,>(…) =>
212
+ const p = masked.indexOf('(', k);
213
+ if (p < 0) return null;
214
+ k = p;
215
+ }
216
+ if (masked[k] === '(') {
217
+ const close = matchClose(masked, k);
218
+ if (close < 0) return null;
219
+ k = close + 1;
220
+ } else {
221
+ // single-parameter arrow: x => …
222
+ const m = masked.slice(k).match(/^[A-Za-z_$][\w$]*\s*/);
223
+ if (m) k += m[0].length;
224
+ }
225
+ // Return type annotation, arrow, then the body.
226
+ const rest = masked.slice(k, k + 400);
227
+ const arrow = rest.match(/^\s*(?::\s*[^={;]+?)?\s*=>\s*/);
228
+ if (arrow) {
229
+ k += arrow[0].length;
230
+ if (masked[k] === '{') return matchClose(masked, k);
231
+ return expressionEnd(masked, k);
232
+ }
233
+ const brace = rest.match(/^\s*(?::\s*[^{;]+?)?\s*\{/);
234
+ if (brace) {
235
+ const open = k + brace[0].length - 1;
236
+ return matchClose(masked, open);
237
+ }
238
+ return null;
239
+ }
240
+
241
+ function expressionEnd(masked, from) {
242
+ let depth = 0;
243
+ for (let k = from; k < masked.length; k++) {
244
+ const ch = masked[k];
245
+ if ('([{'.includes(ch)) depth++;
246
+ else if (')]}'.includes(ch)) {
247
+ if (depth === 0) return k;
248
+ depth--;
249
+ } else if (depth === 0 && (ch === ';' || ch === ',')) return k;
250
+ else if (depth === 0 && ch === '\n' && !/^\s*[.?:+\-*/&|]/.test(masked.slice(k + 1, k + 40))) {
251
+ // a newline ends the expression unless the next line continues it
252
+ const before = masked.slice(from, k).trim();
253
+ if (before && !/[=(,:?+\-*/&|]$/.test(before)) return k;
254
+ }
255
+ }
256
+ return masked.length;
257
+ }
258
+
259
+ export function enclosingFunction(fns, offset) {
260
+ let best = null;
261
+ for (const f of fns) if (f.start <= offset && offset <= f.end && (!best || f.end - f.start < best.end - best.start)) best = f;
262
+ return best;
263
+ }
264
+
265
+ // ---------- operators ----------
266
+
267
+ const SWAP = (map) => (s) => map[s];
268
+
269
+ export const OPERATORS = [
270
+ {
271
+ id: 'boundary',
272
+ label: 'boundary',
273
+ re: /(?<=\s)(<=|>=|<|>)(?=\s)/g,
274
+ swap: SWAP({ '<': '<=', '<=': '<', '>': '>=', '>=': '>' }),
275
+ why: 'no test sits exactly on the boundary',
276
+ },
277
+ {
278
+ id: 'equality',
279
+ label: 'equality',
280
+ re: /(?<=\s)(===|!==|==|!=)(?=\s)/g,
281
+ swap: SWAP({ '===': '!==', '!==': '===', '==': '!=', '!=': '==' }),
282
+ why: 'the outcome of this comparison is never asserted',
283
+ },
284
+ {
285
+ id: 'logical',
286
+ label: 'logical',
287
+ re: /(?<=\s)(&&|\|\|)(?=\s)/g,
288
+ swap: SWAP({ '&&': '||', '||': '&&' }),
289
+ why: 'the two conditions are never tested apart',
290
+ },
291
+ {
292
+ id: 'remove-not',
293
+ label: 'negation',
294
+ re: /(?<![!=\w$)\]])(!)(?=[\w$(])/g,
295
+ swap: () => '',
296
+ why: 'the negated case is not tested',
297
+ },
298
+ {
299
+ id: 'boolean',
300
+ label: 'boolean',
301
+ re: /(?<![.\w$])(true|false)(?![\w$])/g,
302
+ swap: SWAP({ true: 'false', false: 'true' }),
303
+ why: 'this flag or return value is never asserted',
304
+ },
305
+ {
306
+ id: 'arithmetic',
307
+ label: 'arithmetic',
308
+ re: /(?<=\s)([+\-*/%])(?=\s)/g,
309
+ swap: SWAP({ '+': '-', '-': '+', '*': '/', '/': '*', '%': '*' }),
310
+ why: 'the computed value is not checked exactly',
311
+ },
312
+ {
313
+ id: 'update',
314
+ label: 'update',
315
+ re: /(?<![+\-])(\+\+|--)(?![+\-=])|(?<=\s)(\+=|-=)(?=\s)/g,
316
+ swap: SWAP({ '++': '--', '--': '++', '+=': '-=', '-=': '+=' }),
317
+ why: 'the counter or running total is not checked',
318
+ },
319
+ ];
320
+
321
+ const NEGATE = { id: 'negate-condition', label: 'condition', why: 'neither branch of this condition is pinned down by a test' };
322
+ export const OPERATOR_WHY = Object.fromEntries([...OPERATORS, NEGATE].map((o) => [o.id, o.why]));
323
+
324
+ // Lines where an operator-looking token isn't an operator.
325
+ const NOT_CODE_LINE = /^\s*(?:import\b|export\s+(?:\*|\{[^}]*\}\s+from)|\/\/|\*|type\s+\w+\s*=|interface\b|@)/;
326
+
327
+ /**
328
+ * Every mutant on the given lines of one file.
329
+ * @param {string} file
330
+ * @param {string} src
331
+ * @param {Set<number>|null} lines 1-based line numbers to mutate (null = all)
332
+ */
333
+ export function generateMutants(file, src, lines) {
334
+ const masked = maskJs(src);
335
+ const starts = lineStarts(src);
336
+ const fns = findFunctions(masked);
337
+ const srcLines = src.split('\n');
338
+ const mutants = [];
339
+ const seen = new Set();
340
+
341
+ const push = (operator, start, end, replacement) => {
342
+ const original = src.slice(start, end);
343
+ if (original === replacement) return;
344
+ const line = lineOf(starts, start);
345
+ const col = start - starts[line - 1] + 1;
346
+ const id = `${file}:${line}:${col}:${operator}`;
347
+ if (seen.has(id)) return;
348
+ seen.add(id);
349
+ const mutated = src.slice(0, start) + replacement + src.slice(end);
350
+ const fn = enclosingFunction(fns, start);
351
+ const lineEnd = (n) => {
352
+ const s = mutated.split('\n');
353
+ return s.slice(line - 1, line - 1 + n).join('\n');
354
+ };
355
+ const spanLines = src.slice(start, end).split('\n').length;
356
+ mutants.push({
357
+ id,
358
+ file,
359
+ line,
360
+ col,
361
+ operator,
362
+ original,
363
+ replacement,
364
+ start,
365
+ end,
366
+ function: fn ? fn.name : null,
367
+ functionLine: fn ? fn.line : null,
368
+ before: srcLines.slice(line - 1, line - 1 + spanLines).join('\n').trim(),
369
+ after: lineEnd(spanLines + (replacement.split('\n').length - spanLines)).trim(),
370
+ });
371
+ };
372
+
373
+ for (let ln = 1; ln <= starts.length; ln++) {
374
+ if (lines && !lines.has(ln)) continue;
375
+ const a = starts[ln - 1];
376
+ const b = ln < starts.length ? starts[ln] - 1 : src.length;
377
+ const mline = masked.slice(a, b);
378
+ if (!mline.trim() || NOT_CODE_LINE.test(mline)) continue;
379
+
380
+ for (const op of OPERATORS) {
381
+ op.re.lastIndex = 0;
382
+ for (const m of mline.matchAll(op.re)) {
383
+ const tok = m[1] ?? m[2];
384
+ const at = a + m.index;
385
+ const rep = op.swap(tok);
386
+ if (rep === undefined) continue;
387
+ push(op.id, at, at + tok.length, rep);
388
+ }
389
+ }
390
+ // if (cond) → if (!(cond))
391
+ for (const m of mline.matchAll(/\b(?:if|while)\s*\(/g)) {
392
+ const open = a + m.index + m[0].length - 1;
393
+ const close = matchClose(masked, open);
394
+ if (close < 0) continue;
395
+ const cond = src.slice(open + 1, close);
396
+ // `if (!x)` is already covered by remove-not; `!(!x)` would be the same mutant twice.
397
+ if (!cond.trim() || /^\s*!\s*(?:[\w$.]+|\([^()]*\))\s*$/.test(cond)) continue;
398
+ push(NEGATE.id, open + 1, close, `!(${cond})`);
399
+ }
400
+ }
401
+ return mutants;
402
+ }
403
+
404
+ /**
405
+ * Pick which mutants to run: spread across functions first, then operators,
406
+ * so a cap still touches every changed function. Deterministic.
407
+ */
408
+ export function prioritize(mutants) {
409
+ const byFn = new Map();
410
+ for (const m of [...mutants].sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.col - y.col)) {
411
+ const k = `${m.file}#${m.function ?? '(top level)'}`;
412
+ if (!byFn.has(k)) byFn.set(k, new Map());
413
+ const ops = byFn.get(k);
414
+ if (!ops.has(m.operator)) ops.set(m.operator, []);
415
+ ops.get(m.operator).push(m);
416
+ }
417
+ // Within a function: round-robin across operators.
418
+ const queues = [...byFn.values()].map((ops) => {
419
+ const lists = [...ops.values()];
420
+ const q = [];
421
+ for (let i = 0; lists.some((l) => l.length > i); i++) for (const l of lists) if (l[i]) q.push(l[i]);
422
+ return q;
423
+ });
424
+ const out = [];
425
+ for (let i = 0; queues.some((q) => q.length > i); i++) for (const q of queues) if (q[i]) out.push(q[i]);
426
+ return out;
427
+ }
428
+
429
+ export function applyMutant(src, m) {
430
+ return src.slice(0, m.start) + m.replacement + src.slice(m.end);
431
+ }
432
+
433
+ /** One sentence on what a surviving mutant says about the tests. */
434
+ export function explain(m) {
435
+ const where = m.function ? `\`${m.function}\`` : 'top-level code';
436
+ const change = m.operator === 'negate-condition' ? `inverting \`${clip(m.original)}\`` : m.operator === 'remove-not' ? `dropping the \`!\`` : `\`${m.original}\` → \`${m.replacement}\``;
437
+ return `In ${where}, ${change} still passed every test: ${OPERATOR_WHY[m.operator]}.`;
438
+ }
439
+
440
+ const clip = (s) => {
441
+ const one = s.replace(/\s+/g, ' ').trim();
442
+ return one.length > 48 ? one.slice(0, 45) + '…' : one;
443
+ };