Files
leleka/scripts/dev/rustsplit_test.py
T
Pavlo Ratushnyi cb790da36b STRA-338 S12d: long impl blocks are cut between methods and the remaining oversize modules split (53 files)
The splitter now cuts an inherent impl longer than its target into several impl blocks of the same type between associated items (the generics and where clause repeated, the doc comment kept on the first block), so the giant impls left by S12b/S12c (up to 2,000 lines) split too. 53 further module files of the cold and hot crates are split; the baseline drops to 127 oversize files holding 109,000 lines (329 files and 303,000 lines on main). Types, constants, macros, tests and the files kar-off-ab edits stay; crate roots and bins are untouched.
2026-11-05 16:16:36 +01:00

155 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""Proofs for the Rust module splitter on synthetic sources: lexing, item boundaries, visibility and path edits."""
import pathlib
import re
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from rustsplit.items import parse_items # noqa: E402
from rustsplit.lexer import tokenize # noqa: E402
from rustsplit.retarget import retarget # noqa: E402
from rustsplit.split import plan_split # noqa: E402
SOURCE = '''//! Module doc.
#![allow(dead_code)]
use std::fmt;
const LIMIT: usize = 4; // a semicolon item
/// A type.
pub struct Thing {
value: u32,
}
impl Thing {
fn private(&self) -> u32 {
let s = "}{;";
self.value + s.len() as u32 + super::outer()
}
pub fn open(&self) -> u32 {
self.private()
}
}
impl fmt::Display for Thing {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
fn helper() -> char {
'x'
}
pub(crate) fn shared<'a>(s: &'a str) -> &'a str {
s
}
#[cfg(test)]
mod tests;
'''
class Lexing(unittest.TestCase):
def test_tokens_tile_the_text(self):
text = "fn a<'a>() -> &'a str { r#\"}\"# } // end\n/* /* nested */ */ 'c' b\"x\" 1.5"
self.assertEqual("".join(t.text for t in tokenize(text)), text)
def test_braces_in_strings_and_chars_are_not_structure(self):
kinds = [t.kind for t in tokenize("let c = '}'; let s = \"{\";") if t.text in ("'}'", '"{"')]
self.assertEqual(kinds, ["char", "string"])
class Items(unittest.TestCase):
def test_item_kinds_and_names(self):
found = [(i.kind, i.name) for i in parse_items(SOURCE)]
self.assertEqual(found, [("other", "std"), ("other", "LIMIT"), ("other", "Thing"), ("impl", "Thing"),
("impl", "fmt_Display_for"), ("fn", "helper"), ("fn", "shared"), ("other", "tests")])
def test_inherent_impl_is_detected(self):
self.assertEqual([i.inherent for i in parse_items(SOURCE) if i.kind == "impl"], [True, False])
def test_module_doc_and_inner_attribute_are_not_part_of_an_item(self):
first = parse_items(SOURCE)[0]
self.assertTrue(SOURCE[:first.start].startswith("//! Module doc."))
self.assertIn("#![allow(dead_code)]", SOURCE[:first.start])
class Retargeting(unittest.TestCase):
def test_free_fn_gets_visibility_and_paths_shift(self):
out = retarget("fn f() { super::g(); self::h(); }", "fn", False)
self.assertEqual(out, "pub(super) fn f() { super::super::g(); super::h(); }")
def test_restricted_visibility_keeps_its_scope_one_level_down(self):
self.assertEqual(retarget("pub(super) fn f() {}", "fn", False), "pub(in super::super) fn f() {}")
self.assertEqual(retarget("pub(self) fn f() {}", "fn", False), "pub(in super) fn f() {}")
self.assertEqual(retarget("pub(in super::a) fn f() {}", "fn", False), "pub(in super::super::a) fn f() {}")
def test_relative_include_paths_go_one_level_up(self):
out = retarget('fn f() { include_str!("a/b.txt") }', "fn", False)
self.assertIn('"../a/b.txt"', out)
def test_existing_visibility_is_kept(self):
self.assertEqual(retarget("pub(crate) fn f() {}", "fn", False), "pub(crate) fn f() {}")
def test_inherent_impl_fns_become_visible_to_siblings(self):
source = "impl A {\n fn a(&self) {}\n pub fn b(&self) {}\n const C: u8 = 1;\n}"
expected = source.replace(" fn a", " pub(super) fn a").replace(" const C", " pub(super) const C")
self.assertEqual(retarget(source, "impl", True), expected)
def test_trait_impl_is_untouched(self):
text = "impl T for A {\n fn a(&self) {}\n}"
self.assertEqual(retarget(text, "impl", False), text)
def test_a_continued_path_is_not_shifted_twice(self):
self.assertEqual(retarget("fn f() { super::super::g(); }", "fn", False),
"pub(super) fn f() { super::super::super::g(); }")
class Planning(unittest.TestCase):
def test_fns_and_impls_move_and_the_rest_stays(self):
parent, children = plan_split(SOURCE, 8)
self.assertIn("pub struct Thing", parent)
self.assertIn("const LIMIT", parent)
self.assertNotIn("fn helper", parent)
self.assertEqual(sum(len(re.findall(r"fn \w+[(<]", text)) for text in children.values()), 5)
self.assertTrue(all("use super::*;" in text for text in children.values()))
for name in children:
self.assertIn(f"mod {name};", parent)
self.assertIn("use helper_fn::helper;", parent)
self.assertIn("pub(crate) use shared_fn::shared;", parent)
def test_cfg_attributes_follow_the_fn_to_its_use(self):
parent, _ = plan_split('#[cfg(unix)]\npub fn a() {}\n', 100)
self.assertIn('#[cfg(unix)]\n#[allow(unused_imports)]\npub use a_fn::a;', parent)
def test_a_long_inherent_impl_is_cut_between_its_methods(self):
methods = "".join(f" fn m{n}(&self) -> u32 {{\n {n}\n }}\n" for n in range(6))
source = f"/// Docs.\nimpl<T> Big<T>\nwhere\n T: Copy,\n{{\n{methods}}}\n"
parent, children = plan_split(source, 8)
text = "".join(children.values())
self.assertEqual(text.count("impl<T> Big<T>"), 3)
self.assertEqual(text.count("/// Docs."), 1)
self.assertEqual(len(re.findall(r"fn m\d", text)), 6)
self.assertEqual(text.count("{") , text.count("}"))
def test_nothing_to_move_gives_none(self):
self.assertIsNone(plan_split("use a::b;\nconst X: u8 = 1;\n", 100))
def test_test_functions_stay(self):
parent, children = plan_split("#[test]\nfn t() {}\nfn a() {}\n", 100)
self.assertIn("fn t()", parent)
self.assertNotIn("fn t()", "".join(children.values()))
def test_explicit_paths_are_written_for_path_loaded_files(self):
parent, _ = plan_split("fn a() {}\n", 100, explicit_dir="foo")
self.assertIn('#[path = "foo/a_fn.rs"]', parent)
if __name__ == "__main__":
unittest.main()