From a8a09903b4662717b9d81fe32ee8225310dcca6c Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Mon, 23 Nov 2026 23:04:38 +0200 Subject: [PATCH 1/3] semantic_mutants: leave docstrings alone, so their op names are not reported as surviving mutants mutants_for treated any line that starts with a quote as code (meant for `f"... OpIAdd ..."` emit lines), so a docstring that names an opcode or GLSL op produced mutants that can never fail a test and were always reported SURVIVED: `--function nminmax_f32` listed 5 mutants, 4 of them in its docstring, and 47 across rdna2spirv.py. Tokenize the mutated range (dedented) and skip strings that stand alone as a statement; a range that does not tokenize keeps the old behaviour. Co-Authored-By: Claude Opus 5.5 --- tests/test_semantic_mutants.py | 22 ++++++++++++++++++++++ tools/semantic_mutants.py | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py index 42ac9917aa..fb0ebad483 100644 --- a/tests/test_semantic_mutants.py +++ b/tests/test_semantic_mutants.py @@ -80,6 +80,28 @@ 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) + 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..7eb8627478 100644 --- a/tools/semantic_mutants.py +++ b/tools/semantic_mutants.py @@ -27,7 +27,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__))) @@ -140,9 +142,32 @@ 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): + after = next((t for t in tokens[i + 1:] if t.type not in (tokenize.COMMENT, tokenize.NL)), None) + if after is None or after.type in (tokenize.NEWLINE, tokenize.ENDMARKER): + out.update(range(tok.start[0] - 1, tok.end[0])) + if tok.type not in (tokenize.COMMENT, tokenize.NL): + prev = tok.type + return out + + 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. + span = textwrap.dedent("\n".join(lines[first:last + 1])).split("\n") + docs = {first + 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 +175,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("#"): From dc2931044b0cf89bccab7c149b0fcda99cb4cc99 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Mon, 23 Nov 2026 23:10:27 +0200 Subject: [PATCH 2/3] semantic_mutants: a --lines range that starts inside a docstring is widened to the whole string Review on ItsNotRexed/Leonida#9432 (Gevroska): `--lines 595-595` falls inside u16_half's docstring, so the tokenized slice had no opening delimiter and the text was mutated as code. Widen the tokenized span to whole triple-quoted strings, counting delimiters from the enclosing def or class (a text scan, cheap inside the long dispatch method). Every one of the translator's 1,049 docstring lines now gives 0 mutants as a one-line range. Co-Authored-By: Claude Opus 5.5 --- tests/test_semantic_mutants.py | 6 ++++++ tools/semantic_mutants.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py index fb0ebad483..e2bc1c80a6 100644 --- a/tests/test_semantic_mutants.py +++ b/tests/test_semantic_mutants.py @@ -101,6 +101,12 @@ def multi(self, x): 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]) class Tables(unittest.TestCase): diff --git a/tools/semantic_mutants.py b/tools/semantic_mutants.py index 7eb8627478..2deae101ba 100644 --- a/tools/semantic_mutants.py +++ b/tools/semantic_mutants.py @@ -162,12 +162,36 @@ def docstring_lines(lines: list[str]) -> set[int]: return out +TRIPLE_QUOTE = re.compile(r'"""|\'\'\'') + + +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 counted 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 + start = first + for i in range(top, first): + for _ in TRIPLE_QUOTE.finditer(lines[i]): + start = first if start != first else i # an odd count before `first`: it opens at line i + end, open_ = last, False + for i in range(start, len(lines)): + open_ ^= len(TRIPLE_QUOTE.findall(lines[i])) % 2 == 1 + if i >= last and not open_: + end = i + break + return start, end + + 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. - span = textwrap.dedent("\n".join(lines[first:last + 1])).split("\n") - docs = {first + i for i in docstring_lines(span)} + 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: From ea10ffd572c9af0298a98f6427209e2bde402b7c Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Tue, 24 Nov 2026 15:11:57 +0200 Subject: [PATCH 3/3] semantic_mutants: a """ in a comment and adjacent string literals no longer hide or split a docstring Review on #660 (lixonik): a comment holding `"""` before a docstring flipped the delimiter count, so a --lines range inside the docstring was mutated as code, and a docstring written as adjacent literals ("a " "b") was not recognised. Follow triple-quote delimiters with a small scanner that skips comments, one-line strings and escaped delimiters, and take a run of adjacent string tokens ending the statement as one docstring. A literal that is read by the code after it stays code. Co-Authored-By: Claude Opus 5.5 --- tests/test_semantic_mutants.py | 30 ++++++++++++++++++++++ tools/semantic_mutants.py | 47 +++++++++++++++++++++++++++------- 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py index e2bc1c80a6..363065f536 100644 --- a/tests/test_semantic_mutants.py +++ b/tests/test_semantic_mutants.py @@ -108,6 +108,36 @@ def multi(self, x): 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 + 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 2deae101ba..8a42ed2767 100644 --- a/tools/semantic_mutants.py +++ b/tools/semantic_mutants.py @@ -154,31 +154,60 @@ def docstring_lines(lines: list[str]) -> set[int]: return out for i, tok in enumerate(tokens): if tok.type == tokenize.STRING and prev in (tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT): - after = next((t for t in tokens[i + 1:] if t.type not in (tokenize.COMMENT, tokenize.NL)), None) + # 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, tok.end[0])) + out.update(range(tok.start[0] - 1, end.end[0])) if tok.type not in (tokenize.COMMENT, tokenize.NL): prev = tok.type return out -TRIPLE_QUOTE = re.compile(r'"""|\'\'\'') +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 counted from the enclosing def or class, + --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 - start = first + open_, opened_at = None, first for i in range(top, first): - for _ in TRIPLE_QUOTE.finditer(lines[i]): - start = first if start != first else i # an odd count before `first`: it opens at line i - end, open_ = last, False + 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_ ^= len(TRIPLE_QUOTE.findall(lines[i])) % 2 == 1 + open_ = open_triple_quote(lines[i], open_) if i >= last and not open_: end = i break