Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
171 lines
6.9 KiB
Python
171 lines
6.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", "Display_for_Thing"), ("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_module_names_say_what_they_hold_and_never_how_they_were_made(self):
|
|
_, children = plan_split(SOURCE, 8)
|
|
self.assertEqual(sorted(children), ["display_for_thing", "helper", "shared", "thing_methods"])
|
|
for name in children:
|
|
self.assertFalse(name.startswith("impl_") or name.endswith("_fn") or re.search(r"_[0-9]+$", name), name)
|
|
|
|
def test_a_cut_impl_names_its_continuation_after_its_first_method(self):
|
|
method = " fn m{n}(&self) {{\n let x = {n};\n }}\n"
|
|
source = "struct S;\nimpl S {\n" + "".join(method.format(n=n) for n in range(6)) + "}\n"
|
|
_, children = plan_split(source, 8)
|
|
self.assertTrue(any(name.startswith("s_methods_from_m") for name in children), sorted(children))
|
|
|
|
def test_a_taken_name_gets_a_word_not_a_number(self):
|
|
_, children = plan_split("fn a() {}\nfn a() {}\n", 1)
|
|
self.assertEqual(sorted(children), ["a", "a_more"])
|
|
|
|
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::helper;", parent)
|
|
self.assertIn("pub(crate) use shared::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::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.rs"]', parent)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|