diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 6bd45925..b9b1c74d 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -174,7 +174,7 @@ import uuid from task_bench.tasks import Asked, Bench, BUG, check_made, committed, Kind, KINDS, on_disk, Planned, SHIPPED, Task, tests_in_copy from task_bench.planted_mutant import bug_at_sides, Mutant -from task_bench.rust_test_modules import modules +from task_bench.rust_test_modules import tells_apart from claude_code.reply import Claude from task_bench.bench_folder import clear_left, held from task_bench.runs import closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK @@ -492,7 +492,7 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None: return sources bugs = bug_at_sides(mutant, diff, sources) # The check keeps a Rust file's test modules as planted, which it can only do where it tells them apart. - if bugs is None or (mutant.path.endswith(".rs") and any(modules(source.decode("utf-8", "surrogateescape")) is None for source in bugs.values())): + if bugs is None or not all(tells_apart(mutant.path, source) for source in bugs.values()): return None trees: dict[Side, str] = {} messages: dict[Side, str] = {} diff --git a/bin/task_bench/runs.py b/bin/task_bench/runs.py index 7a638d8a..aba3dc63 100644 --- a/bin/task_bench/runs.py +++ b/bin/task_bench/runs.py @@ -196,9 +196,8 @@ def keep_rust_tests(planted_file: str, target: str) -> None: Raises OSError where a file cannot be read or written.""" if os.path.islink(planted_file) or os.path.islink(target) or not os.path.isfile(planted_file): return - # A Rust file is UTF-8; a byte that isn't survives the round trip. - planted, copied = (pathlib.Path(file).read_bytes().decode("utf-8", "surrogateescape") for file in (planted_file, target)) - pathlib.Path(target).write_bytes(with_tests_of(planted, copied).encode("utf-8", "surrogateescape")) + planted, copied = (pathlib.Path(file).read_bytes() for file in (planted_file, target)) + pathlib.Path(target).write_bytes(with_tests_of(planted, copied)) def of_tests(path: str) -> bool: diff --git a/bin/task_bench/rust_test_modules.py b/bin/task_bench/rust_test_modules.py index b36fe084..e950801a 100644 --- a/bin/task_bench/rust_test_modules.py +++ b/bin/task_bench/rust_test_modules.py @@ -1,75 +1,79 @@ """The `#[cfg(test)]` modules of a Rust file, which stand in the file of the code they test: where each is, and a file with the modules -of another file put in place of its own.""" +of another file put in place of its own. A file is bytes, since a Rust file is UTF-8 and a module is found by ASCII text alone.""" import re -# What the scan steps over or stops at, in the order Rust's own lexer tries them. A string, a char and a comment may hold a brace. +# What the scan steps over or stops at. A string, a char and a comment may hold a brace. SCAN = re.compile( - r"""//[^\n]*""" - r"""|/\*""" - r"""|(?\#*)\"""" - r"""|\"""" - r"""|'(?:\\(?:u\{[0-9a-fA-F_]+\}|x[0-9a-fA-F]{2}|.)|[^\\'\n])'""" - r"""|[{}]""" - r"""|\#\[cfg\(test\)\]""", + rb"""//[^\n]*""" + rb"""|/\*""" + rb"""|(?\#*)\"""" + rb"""|\"""" + rb"""|'(?:\\(?:u\{[0-9a-fA-F_]+\}|x[0-9a-fA-F]{2}|.)|[^\\'\n])'""" + rb"""|[{}]""" + rb"""|\#\[cfg\(test\)\]""", re.DOTALL, ) -COMMENT_EDGE = re.compile(r"/\*|\*/") +COMMENT_EDGE = re.compile(rb"/\*|\*/") # What must follow the attribute for it to start an inline module: other attributes, a visibility, then `mod name {`. -MODULE = re.compile(r"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P\w+)\s*\{") +MODULE = re.compile(rb"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P\w+)\s*\{") -def modules(source: str) -> dict[str, tuple[int, int]] | None: +def tells_apart(path: str, source: bytes) -> bool: + """Whether source, the file at path, is no Rust file or has test modules that `modules` tells apart.""" + return not path.endswith(".rs") or modules(source) is not None + + +def modules(source: bytes) -> dict[bytes, tuple[int, int]] | None: """Each inline `#[cfg(test)] mod name { ... }` of source by its name, as the offsets from its attribute to its closing brace. A - module inside another is not listed. None where the modules cannot be told apart: two hold one name, or a brace, string or + module inside a test module is not listed. None where the modules cannot be told apart: two hold one name, or a brace, string or comment is never closed. A `#[cfg(test)]` on anything but an inline module is not listed.""" - found: dict[str, tuple[int, int]] = {} - depth, open_at, start, name = 0, 0, -1, "" - position = 0 - while match := SCAN.search(source, position): + found: dict[bytes, tuple[int, int]] = {} + depth = 0 + # The module being read: its name, the offset of its attribute and the depth outside it. + inside: tuple[bytes, int, int] | None = None + position: int | None = 0 + while position is not None and (match := SCAN.search(source, position)): token, position = match.group(), match.end() - if token == "/*": + if token == b"/*": position = after_comment(source, position) - elif token == '"': - position = after_string(source, position, '"') + elif token == b'"': + position = after_string(source, position, b'"') elif match.group("hashes") is not None: - position = after_string(source, position, '"' + match.group("hashes"), raw=True) - elif token == "{": + position = after_string(source, position, b'"' + match.group("hashes"), raw=True) + elif token == b"{": depth += 1 - elif token == "}": + elif token == b"}": depth -= 1 - if start >= 0 and depth == open_at: - if name in found: + if inside and depth == inside[2]: + if inside[0] in found: return None - found[name], start = (start, position), -1 - elif start < 0 and (module := MODULE.match(source, position)): - start, name, open_at = match.start(), module.group("name"), depth - position = module.end() + found[inside[0]], inside = (inside[1], position), None + elif token.startswith(b"#[") and inside is None and (module := MODULE.match(source, position)): + inside, position = (module.group("name"), match.start(), depth), module.end() depth += 1 - if position < 0: - return None - return found if depth == 0 and start < 0 else None + return found if position is not None and depth == 0 and inside is None else None -def after_comment(source: str, position: int) -> int: - """The offset after the block comment whose `/*` ends at position, -1 where it is never closed. Block comments nest in Rust.""" +def after_comment(source: bytes, position: int) -> int | None: + """The offset after the block comment whose `/*` ends at position, None where it is never closed. Block comments nest in Rust.""" level = 1 while level and (match := COMMENT_EDGE.search(source, position)): - level += 1 if match.group() == "/*" else -1 + level += 1 if match.group() == b"/*" else -1 position = match.end() - return position if level == 0 else -1 + return position if level == 0 else None -def after_string(source: str, position: int, closing: str, raw: bool = False) -> int: - """The offset after the string whose opening quote ends at position, -1 where it is never closed. A raw string has no escapes.""" +def after_string(source: bytes, position: int, closing: bytes, raw: bool = False) -> int | None: + """The offset after the string whose opening quote ends at position, None where it is never closed. A raw string has no escapes.""" while (found := source.find(closing, position)) >= 0: - backslashes = len(source[position:found]) - len(source[position:found].rstrip("\\")) - if raw or backslashes % 2 == 0: + between = source[position:found] + if raw or (len(between) - len(between.rstrip(b"\\"))) % 2 == 0: return found + len(closing) position = found + 1 - return -1 + return None -def with_tests_of(planted: str, copy: str) -> str: +def with_tests_of(planted: bytes, copy: bytes) -> bytes: """copy with each test module as planted holds it, and each test module planted lacks left out. So a test a fix changed, removed or added doesn't count. @@ -80,8 +84,8 @@ def with_tests_of(planted: str, copy: str) -> str: return copy if after is None or before.keys() - after.keys(): return planted - text = copy - for name, (start, end) in sorted(after.items(), key=lambda item: -item[1][0]): - was = planted[before[name][0]:before[name][1]] if name in before else "" - text = text[:start] + was + text[end:] - return text + text, last = b"", 0 + for (start, end), name in sorted((span, name) for name, span in after.items()): + text += copy[last:start] + (planted[before[name][0]:before[name][1]] if name in before else b"") + last = end + return text + copy[last:] diff --git a/bin/task_bench/test_rust_test_modules.py b/bin/task_bench/test_rust_test_modules.py index e5a47817..d1f9630e 100644 --- a/bin/task_bench/test_rust_test_modules.py +++ b/bin/task_bench/test_rust_test_modules.py @@ -6,7 +6,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from task_bench.rust_test_modules import modules, with_tests_of +from task_bench import rust_test_modules +from task_bench.rust_test_modules import tells_apart LIB = textwrap.dedent("""\ pub fn add(a: i32, b: i32) -> i32 { @@ -25,9 +26,17 @@ LIB = textwrap.dedent("""\ """) +def modules(source: str) -> dict[bytes, tuple[int, int]] | None: + return rust_test_modules.modules(source.encode()) + + +def with_tests_of(planted: str, copy: str) -> str: + return rust_test_modules.with_tests_of(planted.encode(), copy.encode()).decode() + + def spelt(source: str) -> dict[str, str] | None: found = modules(source) - return None if found is None else {name: source[start:end] for name, (start, end) in found.items()} + return None if found is None else {name.decode(): source[start:end] for name, (start, end) in found.items()} class ModulesTest(unittest.TestCase): @@ -64,6 +73,26 @@ class ModulesTest(unittest.TestCase): """) self.assertEqual(spelt(source), {"tests": source[:source.index("}\nfn after")+1]}) + def test_reads_a_string_that_ends_in_backslashes_or_in_an_escaped_quote(self): + source = textwrap.dedent("""\ + #[cfg(test)] + mod tests { + const A: &str = r"\\"; + const B: &str = "\\\\"; + const C: &str = "a\\""; + const D: &str = "\\}\\}"; + } + fn after() {} + """) + self.assertEqual(spelt(source), {"tests": source[:source.index("}\nfn after") + 1]}) + + def test_leaves_out_a_module_a_comment_or_a_char_stands_before(self): + self.assertEqual(modules("// helpers\nmod util {}\nfn a() { let c = 'x'; }\nmod more {}\n"), {}) + + def test_lists_a_test_module_inside_a_module_that_is_no_test(self): + source = "mod outer {\n #[cfg(test)]\n mod inner {}\n fn after() {}\n}\n" + self.assertEqual(spelt(source), {"inner": "#[cfg(test)]\n mod inner {}"}) + def test_cannot_tell_the_modules_apart_where_two_hold_one_name(self): self.assertIsNone(modules("#[cfg(test)]\nmod tests {}\nfn a() { #[cfg(test)] mod tests {} }\n")) @@ -73,6 +102,14 @@ class ModulesTest(unittest.TestCase): self.assertIsNone(modules(source)) +class TellsApartTest(unittest.TestCase): + def test_tells_a_rust_file_apart_where_its_modules_can_be(self): + self.assertEqual([tells_apart("lib.rs", b"fn a() {}"), tells_apart("lib.rs", b"fn a() {")], [True, False]) + + def test_takes_a_file_of_another_language_whatever_it_holds(self): + self.assertTrue(tells_apart("calc.go", b"func a() {")) + + class WithTestsOfTest(unittest.TestCase): def test_takes_the_code_as_fixed_and_the_tests_as_planted(self): planted = LIB.replace("a + b", "a - b") @@ -94,6 +131,11 @@ class WithTestsOfTest(unittest.TestCase): fixed = "fn a() { 2 }\n#[cfg(test)]\nmod y { fn changed() {} }\n#[cfg(test)]\nmod x { fn changed() {} }\nfn c() {}\n" self.assertEqual(with_tests_of(planted, fixed), "fn a() { 2 }\n#[cfg(test)]\nmod y { fn u() {} }\n#[cfg(test)]\nmod x { fn t() {} }\nfn c() {}\n") + def test_puts_the_planted_modules_in_where_their_names_sort_in_file_order(self): + planted = "#[cfg(test)]\nmod a { 1 }\n#[cfg(test)]\nmod b { 22 }\nfn code() {}\n" + fixed = "#[cfg(test)]\nmod a { 333 }\n#[cfg(test)]\nmod b { 4444444 }\nfn fixed() {}\n" + self.assertEqual(with_tests_of(planted, fixed), "#[cfg(test)]\nmod a { 1 }\n#[cfg(test)]\nmod b { 22 }\nfn fixed() {}\n") + def test_takes_the_file_as_fixed_where_the_planted_modules_cannot_be_told_apart(self): self.assertEqual(with_tests_of("#[cfg(test)]\nmod tests {\n", "fixed {}"), "fixed {}") diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index afef522f..7bd3766b 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -735,6 +735,13 @@ class CheckedTreeTest(unittest.TestCase): checked_tree(planted, copy, str(self.root / "check")) self.assertEqual(self.held("check"), {"src/lib.rs": "fn a() { 1 }\n#[cfg(test)]\nmod tests { fn t() {} }\n"}) + def test_leaves_a_rust_link_as_a_link_whatever_it_points_at(self): + planted = self.tree("planted", {"lib.rs": "fn a() {}\n#[cfg(test)]\nmod tests {}\n", "real.txt": "text"}) + copy = self.tree("copy", {"real.txt": "text"}) + os.symlink("real.txt", os.path.join(copy, "lib.rs")) + checked_tree(planted, copy, str(self.root / "check")) + self.assertEqual((os.readlink(self.root / "check/lib.rs"), self.held("check")["real.txt"]), ("real.txt", "text")) + def test_copies_a_link_as_a_link(self): planted = self.tree("planted", {"calc.go": "bug"}) copy = self.tree("copy", {"calc.go": "fixed"})