Files
leleka/scripts/dev/rustsplit_test.py
T
Pavlo Ratushnyi 6b5fcd242e STRA-338 S12b: fns and impl blocks of 59 cold oversize modules move into child modules (model-format, gateway, desktop-core, leaf libraries)
scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/<name>.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits.

The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations.
2026-11-05 15:29:39 +01:00

139 lines
5.1 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};\n#[allow(unused_imports)]\npub use {name}::*;", 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.rs"]', parent)
if __name__ == "__main__":
unittest.main()