File size: 6,934 Bytes
e6f16da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"""Inject one realistic bug into a verified solution by editing the exact source span found through the AST (comments
and formatting stay intact). Each mutation records the line, the old and new text and its kind, so the debugging
explanation can name the line and the cause."""
from __future__ import annotations

import ast
import random
from dataclasses import dataclass

CMP_FLIP = {"<": "<=", "<=": "<", ">": ">=", ">=": ">", "==": "!=", "!=": "=="}


@dataclass
class Mutation:
    kind: str
    line: int              # 1-based line in the ORIGINAL source
    old: str               # original text span
    new: str               # replacement text
    start: int             # absolute offsets in the original source
    end: int
    detail: dict


def _offsets(src: str):
    starts, pos = [], 0
    for line in src.splitlines(keepends=True):
        starts.append(pos)
        pos += len(line)
    return starts


def candidates(src: str) -> list[Mutation]:
    tree = ast.parse(src)
    lines = src.splitlines(keepends=True)
    off = _offsets(src)
    abs_ = lambda ln, col: off[ln - 1] + col  # noqa: E731
    out: list[Mutation] = []

    def between(a, b, token_set):
        """Find an operator token in the source between node a's end and node b's start (same line only)."""
        if a.end_lineno != b.lineno:
            return None
        seg = lines[a.end_lineno - 1][a.end_col_offset:b.col_offset]
        for tok in sorted(token_set, key=len, reverse=True):
            i = seg.find(tok)
            if i >= 0:
                s = abs_(a.end_lineno, a.end_col_offset + i)
                return s, s + len(tok), tok
        return None

    for node in ast.walk(tree):
        if isinstance(node, ast.Compare) and len(node.ops) == 1:
            hit = between(node.left, node.comparators[0], CMP_FLIP)
            if hit:
                s, e, tok = hit
                out.append(Mutation("cmp_flip", node.lineno, tok, CMP_FLIP[tok], s, e, {}))
        elif isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
            hit = between(node.left, node.right, {"+", "-"})
            if hit:
                s, e, tok = hit
                out.append(Mutation("arith_flip", node.lineno, tok, "-" if tok == "+" else "+", s, e, {}))
        elif isinstance(node, ast.BoolOp) and len(node.values) == 2:
            word = "and" if isinstance(node.op, ast.And) else "or"
            hit = between(node.values[0], node.values[1], {f" {word} "})
            if hit:
                s, e, tok = hit
                out.append(Mutation("bool_flip", node.lineno, tok, " or " if word == "and" else " and ", s, e, {}))
        elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in ("min", "max"):
            f = node.func
            s, e = abs_(f.lineno, f.col_offset), abs_(f.end_lineno, f.end_col_offset)
            out.append(Mutation("minmax_swap", f.lineno, f.id, "max" if f.id == "min" else "min", s, e, {}))
        elif isinstance(node, ast.Name) and node.id in ("bisect_left", "bisect_right"):
            s, e = abs_(node.lineno, node.col_offset), abs_(node.end_lineno, node.end_col_offset)
            other = "bisect_right" if node.id == "bisect_left" else "bisect_left"
            out.append(Mutation("bisect_swap", node.lineno, node.id, other, s, e, {}))
        elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "range":
            for arg in node.args:
                if isinstance(arg, ast.Constant) and isinstance(arg.value, int) and arg.value in (0, 1, -1):
                    s, e = abs_(arg.lineno, arg.col_offset), abs_(arg.end_lineno, arg.end_col_offset)
                    nv = {0: "1", 1: "0", -1: "0"}[arg.value] if arg.value != -1 else "-2"
                    out.append(Mutation("off_by_one", arg.lineno, src[s:e], nv, s, e, {"where": "range"}))
                elif isinstance(arg, ast.BinOp) and isinstance(arg.op, (ast.Add, ast.Sub)) and \
                        isinstance(arg.right, ast.Constant) and arg.right.value == 1:
                    s, e = abs_(arg.lineno, arg.col_offset), abs_(arg.end_lineno, arg.end_col_offset)
                    keep = ast.get_source_segment(src, arg.left)
                    out.append(Mutation("off_by_one", arg.lineno, src[s:e], keep, s, e, {"where": "range"}))
        elif isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Constant) and node.slice.value in (0, -1):
            sl = node.slice
            s, e = abs_(sl.lineno, sl.col_offset), abs_(sl.end_lineno, sl.end_col_offset)
            out.append(Mutation("index_swap", sl.lineno, src[s:e], "0" if sl.value == -1 else "-1", s, e, {}))
        elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub) and \
                isinstance(node.operand, (ast.Name, ast.Subscript, ast.Call)):
            s, e = abs_(node.lineno, node.col_offset), abs_(node.end_lineno, node.end_col_offset)
            inner = ast.get_source_segment(src, node.operand)
            out.append(Mutation("neg_drop", node.lineno, src[s:e], inner, s, e, {}))
        elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and node.value.value in (0, 1) \
                and isinstance(node.value.value, int) and not isinstance(node.value.value, bool):
            v = node.value
            s, e = abs_(v.lineno, v.col_offset), abs_(v.end_lineno, v.end_col_offset)
            out.append(Mutation("init_change", v.lineno, src[s:e], "1" if v.value == 0 else "0", s, e, {}))
    # dropped statements: a single-line statement inside a loop body that changes state
    for node in ast.walk(tree):
        if isinstance(node, (ast.For, ast.While)):
            body = node.body
            if len(body) < 2:
                continue
            for st in body:
                if st.lineno == st.end_lineno and isinstance(st, (ast.AugAssign, ast.Expr, ast.Assign)) and \
                        not (isinstance(st, ast.Expr) and isinstance(st.value, ast.Constant)):
                    s, e = off[st.lineno - 1], off[st.lineno - 1] + len(lines[st.lineno - 1])
                    out.append(Mutation("drop_stmt", st.lineno, lines[st.lineno - 1], "", s, e,
                                        {"stmt": lines[st.lineno - 1].strip()}))
    return out


def apply(src: str, m: Mutation) -> str:
    return src[:m.start] + m.new + src[m.end:]


def line_text(src: str, line: int) -> str:
    return src.splitlines()[line - 1]


def pick_mutations(src: str, rng: random.Random, k: int = 6) -> list[Mutation]:
    cands = candidates(src)
    rng.shuffle(cands)
    seen, out = set(), []
    for m in cands:                       # spread over kinds first
        if m.kind not in seen:
            seen.add(m.kind)
            out.append(m)
    for m in cands:
        if len(out) >= k:
            break
        if m not in out:
            out.append(m)
    return out[:k]