diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py index 42ac9917aa..13743d267d 100644 --- a/tests/test_semantic_mutants.py +++ b/tests/test_semantic_mutants.py @@ -80,6 +80,133 @@ def test_comments_and_other_branches_are_left_alone(self): self.assertEqual(sum(1 for m in self.mutants if m.line == line and m.label == "OpIAdd -> OpISub"), 1) self.assertFalse(any(m.line == line and m.label == "OpISub -> OpIAdd" for m in self.mutants)) + def test_docstrings_are_left_alone(self): + # A docstring is text: an OpIAdd/UMin named there can't fail a test, so a mutant of it always "survives". + source = textwrap.dedent('''\ + class Gen: + def helper(self, x, y): + """Emit OpIAdd, then UMin with self.cu(31).""" + self.emit(f"{r} = OpIAdd %uint {x} {y}") + + def multi(self, x): + """First line. + + OpISub and NMin are named here too. + """ + self.emit(f"{t} = OpExtInst %uint %glsl UMin {x} {self.cu(31)}") + s = "OpISub in a plain string assignment is still code" + ''').split("\n") + for name, code_lines in (("helper", [4]), ("multi", [11, 12])): + first, last = sm.find_function(source, name) + lines = {m.line for m in sm.mutants_for(source, first, last)} + with self.subTest(function=name): + self.assertEqual(sorted(lines), code_lines) + # A --lines range can start or end inside a docstring, without its opening or closing delimiter. + inside = next(i for i, s in enumerate(source) if "OpISub and NMin" in s) # 0-based + for first, last in ((inside, inside), (inside, inside + 2), (inside - 3, inside)): + with self.subTest(lines=(first + 1, last + 1)): + lines = {m.line for m in sm.mutants_for(source, first, last)} + self.assertEqual(sorted(lines), [n for n in (11,) if first < n <= last + 1]) + + def test_docstring_after_a_comment_with_quotes_and_concatenated_docstring(self): + # Two forms ast.get_docstring() accepts (@lixonik on #660): a `"""` in a comment before the docstring is no + # delimiter, and adjacent literals ("a " "b") are one docstring. + source = textwrap.dedent('''\ + class Gen: + def f(self, x, y): + # a comment with """ in it, and one with \'\'\' too + """Start of the docstring. + + OpIAdd is named here. + """ + self.emit(f"{r} = OpIAdd %uint {x} {y}") + + def g(self, x, y): + "OpIAdd is an example. " "Emit an instruction." + self.emit(f"{r} = OpIAdd %uint {x} {y}") + + def h(self, x, y): + ("UMin is not a docstring here: the call reads it, so it is code. " + "OpISub") and self.emit(f"{r} = OpIAdd %uint {x} {y}") + ''').split("\n") + named = next(i for i, s in enumerate(source) if "OpIAdd is named here" in s) + self.assertEqual(sm.mutants_for(source, named, named), []) + for name, code_lines in (("f", [8]), ("g", [12])): + first, last = sm.find_function(source, name) + with self.subTest(function=name): + self.assertEqual(sorted({m.line for m in sm.mutants_for(source, first, last)}), code_lines) + first, last = sm.find_function(source, "h") + self.assertIn(16, {m.line for m in sm.mutants_for(source, first, last)}) # still code: mutated + + +LOGIC = textwrap.dedent('''\ + class Gen: + def op(self, op, a): + if op == "v_other": + pass + elif op in ("v_logic",): + seen, out = set(), [] + for r in a: + if r not in seen and r > 3: + out.append(r) + seen.update([r]) + n = 0 + n += 1 + n = len(out) + ok = n is None or not out + both = ok and n and out + flag = True + self.emit(f"{t} = OpIAdd %uint {x} {self.cu(0)}") + s = "a == b and c in d" # a comment: x == y and not z + return [x for x in out if x in seen] + ''').split("\n") + + +class PythonLogic(unittest.TestCase): + """The analysis code around the emission: comparisons, and/or, not, True/False, silent statements.""" + + def setUp(self): + self.first, self.last = sm.find_branch(LOGIC, "v_logic") + self.mutants = sm.mutants_for(LOGIC, self.first, self.last) + + def labels(self, text): + line = next(i for i, s in enumerate(LOGIC) if text in s) + 1 + return sorted(m.label for m in self.mutants if m.line == line) + + def test_comparisons_and_boolean_operators(self): + self.assertEqual(self.labels("if r not in seen"), ["> -> >=", "and -> or", "not in -> in"]) + self.assertEqual(self.labels("ok = n is None"), ["is -> is not", "not removed", "or -> and"]) + self.assertEqual(self.labels("both = ok"), ["and -> or #1", "and -> or #2"]) + self.assertEqual(self.labels("flag = True"), ["True -> False"]) + + def test_silent_statements_are_removed(self): + for text in ("out.append(r)", "seen.update([r])", "n += 1", "n = len(out)"): + with self.subTest(statement=text): + self.assertEqual(self.labels(text), ["statement removed"]) + removed = next(m for m in self.mutants if "out.append(r)" in m.old) + self.assertEqual(removed.new, removed.old[:len(removed.old) - len(removed.old.lstrip())] + "pass") + + def test_first_assignments_and_compound_lines_stay(self): + # Removing a first assignment is only a NameError; `for`, `return` and the emit are not simple statements. + self.assertEqual(self.labels("seen, out = set()"), []) + self.assertEqual(self.labels("n = 0"), []) + self.assertEqual(self.labels("for r in a"), []) + + def test_strings_comments_emit_and_branch_condition_are_left_alone(self): + self.assertEqual(self.labels('s = "a == b'), []) + self.assertEqual(self.labels("self.emit("), ["OpIAdd -> OpISub", "self.cu(0) -> self.cu(1)"]) + self.assertEqual(self.labels('elif op in ("v_logic",)'), []) + + def test_the_in_of_a_comprehension_loop_stays(self): + self.assertEqual(self.labels("return [x for x in out"), ["in -> not in"]) + + def test_every_mutant_still_compiles(self): + for m in self.mutants: + mutated = list(LOGIC) + mutated[m.line - 1] = m.new + with self.subTest(line=m.line, label=m.label): + compile("\n".join(mutated), "", "exec") + class Tables(unittest.TestCase): def test_entry_takes_the_other_values_of_its_table(self): diff --git a/tools/semantic_mutants.py b/tools/semantic_mutants.py index 2350e0b8b0..32be6525d2 100644 --- a/tools/semantic_mutants.py +++ b/tools/semantic_mutants.py @@ -9,7 +9,12 @@ mutants of that code with standard operators: swapped opcode pairs (OpIAdd/OpISub, OpBitwiseAnd/Or, shifts), swapped GLSL.std.450 pairs (UMin/UMax, SMin/UMin, NMin/FMin, Floor/Ceil, ...), comparisons made strict or non-strict or of the other signedness, small `self.cu(N)` constants moved by one, the two arms of an OpSelect swapped, and the last operand -of an emitted instruction replaced by the one before it. Each mutant is written into a private copy of tools/ (the +of an emitted instruction replaced by the one before it. The Python around the emission (register liveness, lane-mask +tracking, operand checks) gets mutants too: comparisons flipped (== / !=, < / <=, > / >=, in / not in, is / is not), +and / or swapped, a `not` dropped, True / False swapped, and a one-line statement that can fail silently replaced by +`pass` (a call that is not an emit, an augmented assignment, or a rebinding of a name assigned earlier in the range). +The branch's own `if op ...` condition is left alone: a mutant there only sends other ops through the branch. Each +mutant is written into a private copy of tools/ (the repository's own tools/ is never modified) and the test file is run against it through LEONIDA_TOOLS_DIR, as tests/semantic/test_mutations.py does. A mutant the test file still passes is reported as SURVIVED. @@ -27,7 +32,9 @@ import subprocess import sys import tempfile +import textwrap import time +import tokenize from dataclasses import dataclass ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -52,6 +59,14 @@ SELECT = re.compile(r"(OpSelect %\w+ \{[^}]+\} )(\{[^}]+\}|%\w+)( )(\{[^}]+\}|%\w+)") LAST_OPERAND = re.compile(r"(\{[A-Za-z_][\w\[\]]*\}) (\{[A-Za-z_][\w\[\]]*\})(\"\))") +# Python logic: comparison flips, and the statements whose removal is not a NameError or a syntax error. +COMPARE = {"==": "!=", "!=": "==", "<": "<=", "<=": "<", ">": ">=", ">=": ">"} +AUG_ASSIGN = {"+=", "-=", "*=", "/=", "//=", "%=", "&=", "|=", "^=", "<<=", ">>="} +NOT_SIMPLE = {"if", "elif", "else", "for", "while", "def", "class", "return", "raise", "try", "except", "finally", + "with", "yield", "break", "continue", "pass", "import", "from", "assert", "global", "nonlocal", "del", + "async", "await", "lambda", "match", "case"} +SKIPPED_TOKENS = (tokenize.NL, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT, tokenize.ENDMARKER) + @dataclass class Mutant: @@ -140,9 +155,215 @@ def find_function(lines: list[str], name: str) -> tuple[int, int]: raise LookupError(f"no method named {name}") +def docstring_lines(lines: list[str]) -> set[int]: + """0-based lines that belong to a string standing alone as a statement (a docstring): text, not code, so a + mutant there can never fail a test. Empty when the lines do not tokenize.""" + out: set[int] = set() + source = iter(line + "\n" for line in lines) + prev = tokenize.NEWLINE + try: + tokens = list(tokenize.generate_tokens(lambda: next(source, ""))) + except (tokenize.TokenError, SyntaxError): + return out + for i, tok in enumerate(tokens): + if tok.type == tokenize.STRING and prev in (tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT): + # Adjacent literals are one string ("a " "b"), so the statement may go on with more of them. + rest = (t for t in tokens[i + 1:] if t.type not in (tokenize.COMMENT, tokenize.NL)) + end, after = tok, next(rest, None) + while after is not None and after.type == tokenize.STRING: + end, after = after, next(rest, None) + if after is None or after.type in (tokenize.NEWLINE, tokenize.ENDMARKER): + out.update(range(tok.start[0] - 1, end.end[0])) + if tok.type not in (tokenize.COMMENT, tokenize.NL): + prev = tok.type + return out + + +def open_triple_quote(line: str, open_: str | None) -> str | None: + """The triple-quote delimiter still open at the end of `line` (None when none), given the one open at its start. + Quotes in a comment or inside a one-line string do not count, nor does an escaped delimiter.""" + i, n = 0, len(line) + while i < n: + if open_: + j = line.find(open_, i) + while j > 0 and (len(line[:j]) - len(line[:j].rstrip("\\"))) % 2 == 1: + j = line.find(open_, j + 1) # \""" inside the string + if j < 0: + return open_ + i, open_ = j + 3, None + elif line.startswith(('"""', "'''"), i): + open_, i = line[i:i + 3], i + 3 + elif line[i] == "#": + return None + elif line[i] in "\"'": + j = i + 1 + while j < n and line[j] != line[i]: + j += 2 if line[j] == "\\" else 1 + i = j + 1 + else: + i += 1 + return open_ + + +def string_context(lines: list[str], first: int, last: int) -> tuple[int, int]: + """Widen [first, last] to whole triple-quoted strings, so a range that starts or ends inside a docstring (a + --lines span) is tokenized with both of its delimiters. Delimiters are followed from the enclosing def or class, + a text scan that stays cheap inside the translator's long dispatch method.""" + top = first + while top > 0 and not re.match(r"\s*(async\s+def|def|class)\s", lines[top]): + top -= 1 + open_, opened_at = None, first + for i in range(top, first): + before, open_ = open_, open_triple_quote(lines[i], open_) + if open_ and not before: + opened_at = i # a string that is still open at `first` began here + start = opened_at if open_ else first + end, open_ = last, None + for i in range(start, len(lines)): + open_ = open_triple_quote(lines[i], open_) + if i >= last and not open_: + end = i + break + return start, end + + +def condition_lines(lines: list[str], first: int) -> set[int]: + """0-based lines of the `if op ...` / `elif op ...` condition that starts at `first`, empty when `first` does not + start one. It decides which ops run the branch at all, so mutating it only sends other ops through the code.""" + stripped = lines[first].lstrip() + if not re.match(r"(el)?if\b", stripped): + return set() + cond, j = lines[first], first + while not cond.rstrip().endswith(":") and j + 1 < len(lines): + j += 1 + cond += lines[j] + return set(range(first, j + 1)) if re.search(r"\bop\b", cond) and '"' in cond else set() + + +def logical_lines(span: list[str]) -> list[list[tokenize.TokenInfo]]: + """The tokens of each logical line of `span` (NL, comments, indents and dedents dropped). A span that stops + inside a bracket or a string keeps the lines that tokenized before it.""" + source = iter(s + "\n" for s in span) + out: list[list[tokenize.TokenInfo]] = [[]] + try: + for tok in tokenize.generate_tokens(lambda: next(source, "")): + if tok.type == tokenize.NEWLINE: + out.append([]) + elif tok.type not in SKIPPED_TOKENS: + out[-1].append(tok) + except (tokenize.TokenError, SyntaxError): + out[-1] = [] # the unfinished line + return [ll for ll in out if ll] + + +def logic_mutants(lines: list[str], first: int, last: int, start: int, span: list[str], + skip: set[int]) -> list[tuple[int, str, str]]: + """(0-based line, label, mutated line) for the Python logic in lines[first..last]; `span` is lines[start..] + dedented. Only names and operators are touched, so strings, f-strings (the emitted SPIR-V) and comments are + left alone; lines in `skip` (docstrings, the branch condition) get none.""" + out: list[tuple[int, str, str]] = [] + assigned: set[str] = set() + + def line_of(tok: tokenize.TokenInfo) -> int: + return start + tok.start[0] - 1 + + def in_range(i: int) -> bool: + return first <= i <= last and i not in skip + + def replace(tok_a: tokenize.TokenInfo, tok_b: tokenize.TokenInfo, text: str, label: str, a_end: bool = False, + b_end: bool = True) -> None: + # Replace lines[i] from tok_a's start (or end) to tok_b's end (or start) with `text`; both on line i. + i = line_of(tok_a) + if line_of(tok_b) != i or not in_range(i): + return + k = tok_a.start[0] - 1 + off = len(lines[i]) - len(span[k]) # the indentation dedent removed + a = (tok_a.end if a_end else tok_a.start)[1] + off + b = (tok_b.end if b_end else tok_b.start)[1] + off + out.append((i, label, lines[i][:a] + text + lines[i][b:])) + + for ll in logical_lines(span): + depth, fors, consumed = 0, [], set() + targets: list[str] = [] + top_eq = top_aug = False + for n, tok in enumerate(ll): + nxt = ll[n + 1] if n + 1 < len(ll) else None + if tok.type == tokenize.OP: + if tok.string in "([{": + depth += 1 + elif tok.string in ")]}": + depth -= 1 + elif tok.string in COMPARE: + replace(tok, tok, COMPARE[tok.string], f"{tok.string} -> {COMPARE[tok.string]}") + elif depth == 0 and tok.string == "=": + if not top_eq: + top_eq = True + names = [t for t in ll[:n] if not (t.type == tokenize.OP and t.string == ",")] + if all(t.type == tokenize.NAME for t in names): + targets = [t.string for t in names] + elif depth == 0 and tok.string in AUG_ASSIGN: + top_aug = True + continue + if tok.type != tokenize.NAME or n in consumed: + continue + word = tok.string + if word == "for": + fors.append(depth) + elif word in ("and", "or"): + other = "or" if word == "and" else "and" + replace(tok, tok, other, f"{word} -> {other}") + elif word in ("True", "False"): + other = "False" if word == "True" else "True" + replace(tok, tok, other, f"{word} -> {other}") + elif word == "not" and nxt is not None and nxt.type == tokenize.NAME and nxt.string == "in": + replace(tok, nxt, "", "not in -> in", b_end=False) + consumed.add(n + 1) + elif word == "not" and nxt is not None: + replace(tok, nxt, "", "not removed", b_end=False) + elif word == "in": + if fors and fors[-1] == depth: # the `in` of a for loop or a comprehension + fors.pop() + else: + replace(tok, tok, "not in", "in -> not in") + elif word == "is": + if nxt is not None and nxt.type == tokenize.NAME and nxt.string == "not": + replace(tok, nxt, "", "is not -> is", a_end=True) + consumed.add(n + 1) + else: + replace(tok, tok, "is not", "is -> is not") + # A one-line statement that can fail silently: a call that is not an emit, an augmented assignment, or a + # rebinding of a name the range assigned before. Removing a first assignment would only be a NameError. + i, head = line_of(ll[0]), ll[0] + one_line = line_of(ll[-1]) == i + simple = head.type == tokenize.NAME and head.string not in NOT_SIMPLE + call = (not top_eq and not top_aug and ll[-1].type == tokenize.OP and ll[-1].string == ")" + and not any(t.type == tokenize.NAME and t.string == "emit" for t in ll)) + rebind = top_eq and bool(targets) and all(t in assigned for t in targets) + if one_line and simple and in_range(i) and (call or top_aug or rebind): + indent = lines[i][:len(lines[i]) - len(lines[i].lstrip())] + out.append((i, "statement removed", indent + "pass")) + assigned.update(targets) + # The same flip twice on one line (`a and b and c`) gets "#1", "#2", ... from the left, so the report tells them apart. + count: dict[tuple[int, str], int] = {} + for i, label, _ in out: + count[(i, label)] = count.get((i, label), 0) + 1 + seen: dict[tuple[int, str], int] = {} + numbered = [] + for i, label, new in out: + if count[(i, label)] > 1: + seen[(i, label)] = seen.get((i, label), 0) + 1 + label = f"{label} #{seen[(i, label)]}" + numbered.append((i, label, new)) + return numbered + + def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]: out: list[Mutant] = [] seen: set[tuple[int, str]] = set() + # Only the mutated range is tokenized (the whole translator takes seconds); dedented, a branch or method tokenizes. + start, end = string_context(lines, first, last) + span = textwrap.dedent("\n".join(lines[start:end + 1])).split("\n") + docs = {start + i for i in docstring_lines(span)} def add(i: int, label: str, new: str) -> None: if new != lines[i] and (i, new) not in seen: @@ -150,6 +371,8 @@ def add(i: int, label: str, new: str) -> None: out.append(Mutant(i + 1, label, lines[i], new)) for i in range(first, last + 1): + if i in docs: + continue line = lines[i] code = line.split("#", 1)[0] if not line.lstrip().startswith(("f\"", "\"", "'")) else line if not code.strip() or code.lstrip().startswith("#"): @@ -178,6 +401,8 @@ def add(i: int, label: str, new: str) -> None: if m: add(i, f"last operand {m.group(2)} -> {m.group(1)}", line[:m.start()] + f"{m.group(1)} {m.group(1)}{m.group(3)}" + line[m.end():]) + for i, label, new in logic_mutants(lines, first, last, start, span, docs | condition_lines(lines, first)): + add(i, label, new) return out