"""The bugs task-bench plants in Rust: the mutants cargo-mutants reports as caught, each read from the diff it writes, and the message cargo test prints when a test panics on one.""" import json import re from failure import Failure from mutate_changes import in_diff_tools from task_bench.planted_mutant import Mutant from mutate_changes.tool_process import remove, Run, scratch_folder # What cargo-mutants 27.1.0 writes after the code it put in, as in `sum -= /* ~ changed by cargo-mutants ~ */ item;`. A planted # bug leaves it out, since it would show Haiku the line. MARK = b" /* ~ changed by cargo-mutants ~ */" HUNK = re.compile(rb"@@ -(\d+)") # The heading of what a failed test printed, in cargo test's output: `---- tests::adds stdout ----`. SECTION = re.compile(r"^---- (\S+) std(?:out|err) ----$") # The line before a panic's message: `thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:`. An older Rust prints no # thread id. PANICKED = re.compile(r"^thread '.*' (?:\(\d+\) )?panicked at .*:$") # What follows a panic's message: a hint to ask for a backtrace, or the backtrace. AFTER_MESSAGE = ("note: run with `RUST_BACKTRACE", "stack backtrace:") # The heading cargo test prints twice: before the first failed test's section, and before the list of the failed tests' names. FAILED_TESTS = "failures:" def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure: """The mutants in `files` that the tests of the tree at top kill, as cargo-mutants finds them there, each under the name cargo-mutants gives it. One whose diff holds no change, or more than one hunk, is left out.""" scratch = scratch_folder(top) if isinstance(scratch, Failure): return scratch try: out = in_diff_tools.cargo_mutants_out(top, scratch, [argument for path in files for argument in ("--file", path)], run, jobs) if isinstance(out, Failure): return out # cargo-mutants writes no outcomes where it finds no mutant, as in a file that holds only types. outcomes = json.loads(listed.read_bytes())["outcomes"] if (listed := out / "outcomes.json").is_file() else [] # The run of the unmutated tree is an outcome too. Its scenario is the text `Baseline`, which holds no mutant, so the summary is # checked first. caught = [(mutant, outcome["diff_path"]) for outcome in outcomes if outcome["summary"] == "CaughtMutant" and (mutant := outcome["scenario"]["Mutant"])["file"] in files] lines = [(mutant, changed((out / diff).read_bytes())) for mutant, diff in caught] return [Mutant(mutant["file"], found[0], mutant["name"], found[1], found[2]) for mutant, found in lines if found] except (OSError, ValueError, KeyError, TypeError) as failure: return Failure(f"could not read cargo-mutants' outcomes in {scratch}: {failure}") finally: remove(scratch) def changed(diff: bytes) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None: """The lines a mutant changes, from the diff cargo-mutants writes for it: the number of the first, from 1, those lines as the tree has them, and what the mutant has in their place, without MARK. An unchanged line between two changed ones is in both. None where the diff holds no change, or more than one hunk.""" header, *hunks = HUNK.split(diff) if len(hunks) != 2: return None # A line that starts with a backslash says the file ends without a line end. body = [line for line in hunks[1].split(b"\n")[1:] if not line.startswith(b"\\")] at = [index for index, line in enumerate(body) if line[:1] in (b"-", b"+")] if not at: return None # Each line before the first changed one is a line of the tree. first = int(hunks[0]) + at[0] span = body[at[0]:at[-1] + 1] was = tuple(line[1:] for line in span if not line.startswith(b"+")) now = tuple(line[1:].replace(MARK, b"") for line in span if not line.startswith(b"-")) return first, was, now def task_text(output: str) -> str | None: """What Haiku is told of a planted bug: the message of the first panic in a failed test's section of cargo test's output, without the test's name or the file and line that panicked, so it says what goes wrong and not where. None where no failed test's section holds a panic with a message, as on a passing run or a build that broke, or where the message only names the test.""" test, within = "", False message: list[str] = [] for line in output.splitlines(): heading = SECTION.match(line) if message and (heading or line == FAILED_TESTS): break if heading: test, within = heading[1], False elif line == FAILED_TESTS: test, within = "", False elif test and not message and PANICKED.match(line): within = True elif within and line.startswith(AFTER_MESSAGE): within = False elif within: message.append(line.strip()) # A test in a module has the module's name before its own, as `tests::adds`; a message may name the whole or the test alone. A Rust test's own # name is often a plain word, such as `big`, so a longer identifier that holds it, such as `is_big`, doesn't name the test. names = [re.compile(rf"(?