Files
leleka/scripts/dev/rustsplit_test.py
T
Pavlo Ratushnyi 95f768cfbf STRA-338 S12c: fns and impl blocks of 162 hot-path modules move into child modules (leleka-runtime, cuda-driver, deploy, cpu-sys)
The same lexer-based splitter as S12b, now with explicit re-exports: every moved free fn comes back to its module under its old name and old visibility (cfg attributes carried), so a name can never clash with another glob import. 162 module files of leleka-runtime (68), cuda-driver (84), deploy (10), cpu-sys, igpu and leleka-memory are split into groups of about 250 lines; types, constants, macros, nested modules and tests stay. Not touched: the files kar-off-ab edits, crate roots (lib.rs, main.rs, bin/*), and giant single impl blocks (next). This changes codegen-unit placement of engine code, so it is covered by the bitwise replay and the paired A/B on the 5090, not by a binary comparison.
2026-11-05 15:52:18 +01:00

145 lines
5.4 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_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()