Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions tests/test_semantic_mutants.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,64 @@ 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


class Tables(unittest.TestCase):
def test_entry_takes_the_other_values_of_its_table(self):
Expand Down
80 changes: 80 additions & 0 deletions tools/semantic_mutants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)))
Expand Down Expand Up @@ -140,16 +142,94 @@ 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 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:
seen.add((i, new))
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("#"):
Expand Down
Loading