"""The `#[cfg(test)]` modules of a Rust file, which stand in the file of the code they test or, as `mod name;` declares, in a file of their own. Here are where each inline one is, which modules a file declares and where their files may stand, and a file with the modules of another file put in place of its own. A file is bytes: a Rust file is UTF-8, and a module is found by ASCII text alone.""" import pathlib import re # What the scan steps over or stops at. A string, a char and a comment may hold a brace. SCAN = re.compile( rb"""//[^\n]*""" rb"""|/\*""" rb"""|(?\#*)\"""" rb"""|\"""" rb"""|'(?:\\(?:u\{[0-9a-fA-F_]+\}|x[0-9a-fA-F]{2}|.)|[^\\'\n])'""" rb"""|[{}]""" rb"""|\#\[cfg\(test\)\]""", re.DOTALL, ) STRING_BODY = re.compile(rb'(?:[^"\\]|\\.)*"', re.DOTALL) COMMENT_EDGE = re.compile(rb"/\*|\*/") # What follows the attribute that starts an inline module: any other attributes, an optional visibility, then `mod name {`. MODULE = re.compile(rb"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P\w+)\s*\{") # What follows the attribute that starts a module kept in a file of its own: any other attributes, an optional visibility, then `mod name;`. DECLARATION = re.compile(rb"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P\w+)\s*;") def tells_apart(path: str, source: bytes) -> bool: """Whether source, the file at path, is no Rust file, or holds test modules that `modules` can tell 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, with the offsets of its first byte, the attribute's, and of the byte after its closing brace. A module inside a test module and a `#[cfg(test)]` on anything but an inline module are not listed. None where the modules cannot be told apart: two share a name, or a brace, string or comment is never closed.""" 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 = 0 while match := SCAN.search(source, position): token = match.group() if (after := after_token(source, match)) is None: return None position = after if token == b"{": depth += 1 elif token == b"}": depth -= 1 if inside and depth == inside[2]: if inside[0] in found: return None 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 return found if depth == 0 and inside is None else None def declared(source: bytes) -> list[str] | None: """The name of each `#[cfg(test)] mod name;` of source, in the order they stand. The module's code is in a file of its own. None where a string or comment is never closed.""" names = [] position = 0 while match := SCAN.search(source, position): if (after := after_token(source, match)) is None: return None position = after if match.group() == b"#[cfg(test)]" and (declaration := DECLARATION.match(source, position)): names.append(declaration.group("name").decode()) return names def homes(path: str, name: str) -> list[str]: """Each place the file of the module `name`, declared in the Rust file at path, may stand, as paths from the same top: beside the declaring file, or in a folder named for it without `.rs`. Which of the two holds depends on the kind of file the declarer is, which this doesn't know, so both count.""" declaring = pathlib.PurePosixPath(path) return [str(folder / part) for folder in (declaring.parent, declaring.parent / declaring.stem) for part in (f"{name}.rs", f"{name}/mod.rs")] def after_token(source: bytes, match: re.Match[bytes]) -> int | None: """The offset after match, or after the comment, string or raw string that match opens; None where that is never closed.""" if match.group() == b"/*": return after_comment(source, match.end()) if match.group() == b'"': return after_string(source, match.end()) if match.group("hashes") is not None: return after_raw_string(source, match.end(), match.group("hashes")) return match.end() 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() == b"/*" else -1 position = match.end() return position if level == 0 else None def after_string(source: bytes, position: int) -> int | None: """The offset after the string whose opening quote ends at position, None where it is never closed. A backslash escapes the next byte.""" closed = STRING_BODY.match(source, position) return closed.end() if closed else None def after_raw_string(source: bytes, position: int, hashes: bytes) -> int | None: """The offset after the raw string, `r` or `br` then hashes and a quote, whose opening ends at position, None where it is never closed. It has no escapes.""" closed = re.compile(b'"' + hashes).search(source, position) return closed.end() if closed else None def with_tests_of(planted: bytes, copy: bytes) -> bytes: """copy with each of its test modules replaced by the one of that name in planted, and each that planted lacks left out. So a test a fix changed, removed or added doesn't count. Where copy lacks a `mod name;` declaration of planted's, or cannot have its declarations told apart, planted is returned: the file of that module stands as planted, and a fix that drops the declaration would leave its tests uncompiled. Otherwise, where planted's modules cannot be told apart, or planted has none and copy's cannot be told apart, copy is returned as it is. Where planted has some and copy's cannot be told apart, or copy lacks one of planted's, planted is returned: Haiku's file has no module to put them in.""" if not set(declared(planted) or []) <= set(declared(copy) or []): return planted before, after = modules(planted), modules(copy) # Haiku's file stands where planted's modules can't be told apart. The bench never plants a bug in such a file, and a guess at # which module is which could swap one test for another. Haiku's file is also what the check took before the bench put back # planted test modules, so a fix that passed then still passes. if before is None or (after is None and not before): return copy if after is None or before.keys() - after.keys(): return planted 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:]