|
1 | 1 | #!/usr/bin/env python3 |
2 | | -"""Emit operator mutants for the changed lines of one Python file (ADR-15, #116). |
| 2 | +"""Emit operator and constant mutants for the changed lines of one Python file |
| 3 | +(ADR-15, #116; constants #149). |
3 | 4 |
|
4 | 5 | stdin: one JSON object {"path": str, "changed_lines": [int, ...]} |
5 | | -stdout: JSON list of {"line", "col", "endCol", "orig", "repl", "op"}, one per |
6 | | - mutable operator token found on a changed line. |
| 6 | +stdout: JSON list of {"line", "col", "endCol", "orig", "repl", "op", "kind"}, one |
| 7 | + per mutable token found on a changed line. `kind` is "operator" or |
| 8 | + "constant" so the runner can fill its budget operators-first (a constant |
| 9 | + must never evict a higher-signal operator mutant past the cap). |
| 10 | +
|
| 11 | +Tokenize, not regex or AST, for the mutation positions: token boundaries are |
| 12 | +exact, string and comment contents are separate token types and so are never |
| 13 | +mutated, and the operator's own position is what a swap needs (AST gives operand |
| 14 | +positions, not the operator). AST is used ONLY to locate docstrings (below), which |
| 15 | +tokenize cannot identify without reimplementing the grammar. |
7 | 16 |
|
8 | | -Tokenize, not regex or AST: token boundaries are exact, string and comment |
9 | | -contents are separate token types and so are never mutated, and the operator's |
10 | | -own position is what a swap needs (AST gives operand positions, not the operator). |
11 | 17 | A mutant that turns out syntactically invalid is the runner's problem, not ours: |
12 | | -it simply runs and is classified as killed, which is the fail-safe direction. |
| 18 | +it simply runs and is classified as killed, which is the fail-safe direction. The |
| 19 | +only failure mode a richer mutant set can add is a false SURVIVOR (an equivalent |
| 20 | +mutant), i.e. a false UNPROVEN, never a false SAFE, since mutation is |
| 21 | +downgrade-only. |
13 | 22 | """ |
| 23 | +import ast |
14 | 24 | import io |
15 | 25 | import json |
16 | 26 | import sys |
|
32 | 42 | "//": "/", |
33 | 43 | } |
34 | 44 | NAME_SWAP = {"and": "or", "or": "and"} |
| 45 | +# The keyword constants (#149). None -> True flips truthiness AND identity, so it |
| 46 | +# is caught by both a boolean use and an `is None` check. |
| 47 | +CONST_NAME_SWAP = {"True": "False", "False": "True", "None": "True"} |
| 48 | + |
| 49 | +# Tokens that begin a logical line. A constant whose previous significant token is |
| 50 | +# one of these AND whose next significant token is a NEWLINE is a standalone |
| 51 | +# expression statement (a bare string, a bare literal) — inert, so mutating it |
| 52 | +# manufactures a survivor no test can kill. Docstrings that are NOT this simple |
| 53 | +# shape (inline `def f(): "doc"`, implicit-concatenated `"a" "b"`) are caught by |
| 54 | +# the AST span check instead. |
| 55 | +_LINE_START = frozenset( |
| 56 | + {tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT, tokenize.ENCODING} |
| 57 | +) |
| 58 | + |
| 59 | + |
| 60 | +def _num_repl(s: str) -> str: |
| 61 | + """A different, valid numeric literal. Zero-valued literals (0, 0.0, 0x0, 0j) |
| 62 | + map to 1 rather than 0 so the mutant is never numerically equal to the |
| 63 | + original; everything else maps to 0.""" |
| 64 | + try: |
| 65 | + is_zero = ast.literal_eval(s) == 0 |
| 66 | + except Exception: |
| 67 | + is_zero = s == "0" |
| 68 | + return "1" if is_zero else "0" |
| 69 | + |
| 70 | + |
| 71 | +def _str_repl(s: str) -> str: |
| 72 | + """A different, valid string literal: empty string for a non-empty literal, a |
| 73 | + sentinel for an already-empty one. |
| 74 | +
|
| 75 | + Fail-safe imprecision, documented rather than special-cased: a bytes literal |
| 76 | + maps to a str (`b"x"` -> `""`), a cross-type mutant that is never equivalent |
| 77 | + (so no false UNPROVEN) but is usually killed on sight. An EMPTY f-string on |
| 78 | + Python < 3.12 (`f""`, one STRING token there) maps to `""`, which is |
| 79 | + behaviourally equal -> an equivalent mutant -> a false UNPROVEN; on 3.12+ an |
| 80 | + f-string is FSTRING_* tokens and is not mutated at all. Both are downgrade-only |
| 81 | + and rare.""" |
| 82 | + try: |
| 83 | + v = ast.literal_eval(s) |
| 84 | + empty = v == "" or v == b"" |
| 85 | + except Exception: |
| 86 | + empty = False |
| 87 | + return '"__mut__"' if empty else '""' |
| 88 | + |
| 89 | + |
| 90 | +def _docstring_spans(source: str) -> list: |
| 91 | + """(lineno, col, end_lineno, end_col) for every docstring, so the tokenize |
| 92 | + pass can skip string tokens that are (part of) one. A docstring is |
| 93 | + behaviour-inert, so mutating it manufactures a survivor no test could ever kill |
| 94 | + (a false UNPROVEN). AST identifies them exactly — inline, implicit-concatenated |
| 95 | + and multi-line alike — where a tokenize heuristic cannot. A parse failure |
| 96 | + yields no spans (the tokenize pass then also fails, or degrades fail-safe).""" |
| 97 | + try: |
| 98 | + tree = ast.parse(source) |
| 99 | + except (SyntaxError, ValueError): |
| 100 | + return [] |
| 101 | + spans = [] |
| 102 | + holders = (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) |
| 103 | + for node in ast.walk(tree): |
| 104 | + if not isinstance(node, holders): |
| 105 | + continue |
| 106 | + body = getattr(node, "body", None) |
| 107 | + if not body: |
| 108 | + continue |
| 109 | + first = body[0] |
| 110 | + if ( |
| 111 | + isinstance(first, ast.Expr) |
| 112 | + and isinstance(first.value, ast.Constant) |
| 113 | + and isinstance(first.value.value, (str, bytes)) |
| 114 | + ): |
| 115 | + c = first.value |
| 116 | + spans.append((c.lineno, c.col_offset, c.end_lineno, c.end_col_offset)) |
| 117 | + return spans |
| 118 | + |
| 119 | + |
| 120 | +def _in_docstring(spans: list, row: int, col: int) -> bool: |
| 121 | + for (l, c, el, ec) in spans: |
| 122 | + if l <= row <= el and (row > l or col >= c) and (row < el or col < ec): |
| 123 | + return True |
| 124 | + return False |
| 125 | + |
| 126 | + |
| 127 | +def _significant(toks: list, i: int, step: int): |
| 128 | + """Nearest token before (step -1) or after (step +1) index i that is not a |
| 129 | + comment or a non-logical newline.""" |
| 130 | + j = i + step |
| 131 | + while 0 <= j < len(toks): |
| 132 | + if toks[j].type not in (tokenize.COMMENT, tokenize.NL): |
| 133 | + return toks[j] |
| 134 | + j += step |
| 135 | + return None |
| 136 | + |
| 137 | + |
| 138 | +def _is_bare_stmt(toks: list, i: int) -> bool: |
| 139 | + prev = _significant(toks, i, -1) |
| 140 | + nxt = _significant(toks, i, +1) |
| 141 | + at_line_start = prev is None or prev.type in _LINE_START |
| 142 | + ends_stmt = nxt is not None and nxt.type == tokenize.NEWLINE |
| 143 | + return at_line_start and ends_stmt |
| 144 | + |
| 145 | + |
| 146 | +def _mutation_for(toks: list, i: int, spans: list): |
| 147 | + """(replacement, kind) for the token at index i, or None if it is not mutable. |
| 148 | + Constants are skipped when they are behaviour-inert (a bare expression |
| 149 | + statement, or any part of a docstring).""" |
| 150 | + tok = toks[i] |
| 151 | + if tok.type == tokenize.OP and tok.string in OP_SWAP: |
| 152 | + return OP_SWAP[tok.string], "operator" |
| 153 | + if tok.type == tokenize.NAME and tok.string in NAME_SWAP: |
| 154 | + return NAME_SWAP[tok.string], "operator" |
| 155 | + if tok.type == tokenize.NAME and tok.string in CONST_NAME_SWAP: |
| 156 | + if _is_bare_stmt(toks, i): |
| 157 | + return None |
| 158 | + return CONST_NAME_SWAP[tok.string], "constant" |
| 159 | + if tok.type == tokenize.NUMBER: |
| 160 | + if _is_bare_stmt(toks, i): |
| 161 | + return None |
| 162 | + return _num_repl(tok.string), "constant" |
| 163 | + if tok.type == tokenize.STRING: |
| 164 | + (row, col) = tok.start |
| 165 | + if _is_bare_stmt(toks, i) or _in_docstring(spans, row, col): |
| 166 | + return None |
| 167 | + return _str_repl(tok.string), "constant" |
| 168 | + return None |
35 | 169 |
|
36 | 170 |
|
37 | 171 | def mutants(source: str, changed: set) -> list: |
38 | | - out = [] |
39 | 172 | try: |
40 | | - toks = tokenize.generate_tokens(io.StringIO(source).readline) |
41 | | - for tok in toks: |
42 | | - (row, col) = tok.start |
43 | | - (erow, ecol) = tok.end |
44 | | - if row not in changed or row != erow: |
45 | | - continue |
46 | | - if tok.type == tokenize.OP and tok.string in OP_SWAP: |
47 | | - repl = OP_SWAP[tok.string] |
48 | | - elif tok.type == tokenize.NAME and tok.string in NAME_SWAP: |
49 | | - repl = NAME_SWAP[tok.string] |
50 | | - else: |
51 | | - continue |
52 | | - out.append( |
53 | | - { |
54 | | - "line": row, |
55 | | - "col": col, |
56 | | - "endCol": ecol, |
57 | | - "orig": tok.string, |
58 | | - "repl": repl, |
59 | | - "op": tok.string + "->" + repl, |
60 | | - } |
61 | | - ) |
| 173 | + toks = list(tokenize.generate_tokens(io.StringIO(source).readline)) |
62 | 174 | except (tokenize.TokenError, IndentationError, SyntaxError): |
63 | 175 | # A file we cannot tokenize yields no mutants rather than crashing the |
64 | 176 | # run. Mutation is opt-in evidence; its absence never grants SAFE. |
65 | 177 | return [] |
| 178 | + spans = _docstring_spans(source) |
| 179 | + out = [] |
| 180 | + for i, tok in enumerate(toks): |
| 181 | + (row, col) = tok.start |
| 182 | + (erow, ecol) = tok.end |
| 183 | + if row not in changed or row != erow: |
| 184 | + continue |
| 185 | + res = _mutation_for(toks, i, spans) |
| 186 | + if res is None: |
| 187 | + continue |
| 188 | + repl, kind = res |
| 189 | + if repl == tok.string: |
| 190 | + # A mutant equal to the original is a survivor no test could ever |
| 191 | + # kill; never emit one. |
| 192 | + continue |
| 193 | + out.append( |
| 194 | + { |
| 195 | + "line": row, |
| 196 | + "col": col, |
| 197 | + "endCol": ecol, |
| 198 | + "orig": tok.string, |
| 199 | + "repl": repl, |
| 200 | + "op": tok.string + "->" + repl, |
| 201 | + "kind": kind, |
| 202 | + } |
| 203 | + ) |
66 | 204 | return out |
67 | 205 |
|
68 | 206 |
|
|
0 commit comments