From 6c41b936610bb66d02875ec34d032a6eca8546dc Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 21:23:12 +0100 Subject: [PATCH] feat: inline-tests moves inline tests over 30% of their file to a file of their own An inline #[cfg(test)] module at a file's top level spans at most 30% of the file's lines, in files a target reaches outside test code. --fix moves a larger one's body to tests.rs, dedented except inside string literals, leaves mod tests; in its place, moves foo.rs to foo/mod.rs when it needs a directory, and points relative include paths one directory up. childless-mod-rs counts the tests it moves out as a child. Fix gains line-range and create edits beside TOML edits and moves. The module walk records which files only test code reaches, and where a module's children live. --- crates/sourceorigin-standard/README.md | 6 +- .../src/rules/childless_mod_rs.rs | 8 +- crates/sourceorigin-standard/src/rules/fix.rs | 106 +++++++- .../src/rules/inline_tests.rs | 237 ++++++++++++++++++ crates/sourceorigin-standard/src/rules/mod.rs | 6 + .../src/rules/modules.rs | 108 ++++++-- .../sourceorigin-standard/src/rules/source.rs | 2 + .../src/rules/test_code.rs | 51 ++++ .../src/rules/tests/inline_tests.rs | 80 ++++++ .../src/rules/tests/mod.rs | 1 + 10 files changed, 564 insertions(+), 41 deletions(-) create mode 100644 crates/sourceorigin-standard/src/rules/inline_tests.rs create mode 100644 crates/sourceorigin-standard/src/rules/test_code.rs create mode 100644 crates/sourceorigin-standard/src/rules/tests/inline_tests.rs diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index 9cdc747..b4cbe98 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -38,6 +38,7 @@ A repository adopts the standard in four steps: - `doc-length`: The prose of each item's or module's docs, in a file that isn't generated, spans at most `standard.toml`'s `[comments] doc-lines` lines (10 by default). Code blocks and a crate root's `//!` docs don't count. - `config-comments`: In every `Cargo.toml`, justfile (and `*.just`) and `.github` YAML file, each block of `#` comment lines spans at most `standard.toml`'s `[comments] block-lines` (6 by default), and the file holds at most `[comments] file-lines` comment lines (40 by default). - `childless-mod-rs`: A module is `foo/mod.rs` only when its directory holds another Rust file; otherwise it is `foo.rs`. A `mod.rs` beside an integration test's, benchmark's or example's root, such as `tests/common/mod.rs`, passes. +- `inline-tests`: An inline `#[cfg(test)] mod … { }` at the top level of a file a target reaches outside test code spans at most 30% of the file's lines; a larger one is a file of its own, `mod tests;`. Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and @@ -102,10 +103,11 @@ piqueld = 2 fixes that need no judgement and prints each: it adds `[lints] workspace = true`, makes a workspace lint at `deny` or `forbid` `warn` (never an `allow`), lowers a ceiling of `budget.toml` to what the - crate holds, moves a childless `foo/mod.rs` to `foo.rs`, and removes a + crate holds, moves a childless `foo/mod.rs` to `foo.rs`, moves inline + tests over their share of a file to a file of their own, and removes a stale deviation or entry of one. It edits each TOML file as a document, so its layout and comments stay, and leaves alone a file a deviation - excuses. + excuses. `cargo fmt` then reflows the lines a move made shorter. - `cargo xtask standard report` prints [`rules::report`] as JSON: each rule's violations and deviation, deviated or not, with the repository's `#[expect]` attributes by lint, its `// INVARIANT:` lines and the lints diff --git a/crates/sourceorigin-standard/src/rules/childless_mod_rs.rs b/crates/sourceorigin-standard/src/rules/childless_mod_rs.rs index 611f061..ba74733 100644 --- a/crates/sourceorigin-standard/src/rules/childless_mod_rs.rs +++ b/crates/sourceorigin-standard/src/rules/childless_mod_rs.rs @@ -5,7 +5,8 @@ use super::{Finding, Repository}; impl Repository { /// Each `mod.rs` whose directory holds no other Rust file, and the fix - /// moving it to `foo.rs`. A `mod.rs` beside an integration test's, + /// moving it to `foo.rs`. A `mod.rs` whose inline tests `inline-tests` + /// moves out keeps them as its child, and one beside an integration test's, /// benchmark's or example's root passes, since cargo would take `foo.rs` /// there for a target of its own. pub(super) fn childless_mod_rs(&self) -> Checked { @@ -20,7 +21,10 @@ impl Repository { }; let has_child = self .rust_files() - .any(|other| other != path && other.starts_with(dir)); + .any(|other| other != path && other.starts_with(dir)) + || self + .oversized_tests() + .any(|tests| tests.source.path == path); if has_child || dir .parent() diff --git a/crates/sourceorigin-standard/src/rules/fix.rs b/crates/sourceorigin-standard/src/rules/fix.rs index d48aa04..defdfa5 100644 --- a/crates/sourceorigin-standard/src/rules/fix.rs +++ b/crates/sourceorigin-standard/src/rules/fix.rs @@ -1,9 +1,10 @@ //! `--fix`: the edits that resolve a rule's mechanical violations. A TOML //! file is edited as a document, so it keeps its layout and comments; a -//! Rust file moves. +//! Rust file has lines replaced, is created or moves. use std::collections::{BTreeMap, BTreeSet}; use std::fmt; +use std::ops::RangeInclusive; use std::path::{Path, PathBuf}; use toml_edit::{DocumentMut, Item, Value}; @@ -31,6 +32,10 @@ type TomlEdit = Box; enum Edit { /// Edits it as a TOML document. Toml(TomlEdit), + /// Replaces these lines of it, from 1, with this text. + Lines(RangeInclusive, String), + /// Creates it with this text. + Create(String), /// Moves it here, from the repository's root, removing the directory /// it leaves empty. Move(PathBuf), @@ -43,22 +48,41 @@ impl Fix { what: String, edit: impl Fn(&mut DocumentMut) + 'static, ) -> Self { - let path = path.into(); - Self { - resolves: path.clone(), - path, - what, - edit: Edit::Toml(Box::new(edit)), - } + Self::of(path.into(), what, Edit::Toml(Box::new(edit))) } /// Moves `path` to `to`. pub(super) fn move_to(path: PathBuf, what: String, to: PathBuf) -> Self { + Self::of(path, what, Edit::Move(to)) + } + + /// Replaces `lines` of `path` with `text`. + pub(super) fn replace_lines( + path: PathBuf, + what: String, + lines: RangeInclusive, + text: String, + ) -> Self { + Self::of(path, what, Edit::Lines(lines, text)) + } + + /// Creates `path` with `text`. + pub(super) fn create(path: PathBuf, what: String, text: String) -> Self { + Self::of(path, what, Edit::Create(text)) + } + + /// The fix, resolving a violation in `resolves` rather than its own + /// file. + pub(super) fn resolving(self, resolves: PathBuf) -> Self { + Self { resolves, ..self } + } + + fn of(path: PathBuf, what: String, edit: Edit) -> Self { Self { resolves: path.clone(), path, what, - edit: Edit::Move(to), + edit, } } @@ -98,12 +122,20 @@ impl Fix { .iter() .filter_map(|fix| match &fix.edit { Edit::Toml(edit) => Some(edit), - Edit::Move(_) => None, + Edit::Lines(..) | Edit::Create(_) | Edit::Move(_) => None, }) .collect(); if !toml.is_empty() { Self::edit_toml(path, &file, &toml)?; } + let text: Vec<_> = fixes + .iter() + .map(|fix| &fix.edit) + .filter(|edit| matches!(edit, Edit::Lines(..) | Edit::Create(_))) + .collect(); + if !text.is_empty() { + Self::edit_text(&file, &text)?; + } for fix in fixes { if let Edit::Move(to) = &fix.edit { Self::move_file(&file, &root.join(to))?; @@ -139,6 +171,56 @@ impl Fix { }) } + /// Makes `edits`, each a [`Edit::Lines`] or [`Edit::Create`], to the + /// text of `file`, each against its lines as they were. + fn edit_text(file: &Path, edits: &[&Edit]) -> Result<(), Error> { + let created = edits.iter().find_map(|edit| match edit { + Edit::Create(text) => Some(text.clone()), + Edit::Toml(_) | Edit::Lines(..) | Edit::Move(_) => None, + }); + let written = if let Some(text) = created { + text + } else { + let text = std::fs::read_to_string(file).map_err(|source| Error::Read { + path: file.to_owned(), + source, + })?; + let mut lines: Vec> = + text.lines().map(|line| Some(line.to_owned())).collect(); + for edit in edits { + let Edit::Lines(range, new) = edit else { + continue; + }; + for line in range.clone() { + if let Some(slot) = line.checked_sub(1).and_then(|at| lines.get_mut(at)) { + *slot = (line == *range.start()).then(|| new.clone()); + } + } + } + lines + .into_iter() + .flatten() + .map(|line| line + "\n") + .collect() + }; + Self::create_parent(file)?; + std::fs::write(file, written).map_err(|source| Error::Write { + path: file.to_owned(), + source, + }) + } + + /// Creates the directory `file` goes in. + fn create_parent(file: &Path) -> Result<(), Error> { + let Some(dir) = file.parent() else { + return Ok(()); + }; + std::fs::create_dir_all(dir).map_err(|source| Error::Write { + path: dir.to_owned(), + source, + }) + } + /// Moves `from` to `to`, creating `to`'s directory and removing /// `from`'s once it is empty. fn move_file(from: &Path, to: &Path) -> Result<(), Error> { @@ -146,9 +228,7 @@ impl Fix { path: path.to_owned(), source, }; - if let Some(dir) = to.parent() { - std::fs::create_dir_all(dir).map_err(|source| write(dir, source))?; - } + Self::create_parent(to)?; std::fs::rename(from, to).map_err(|source| write(to, source))?; let Some(dir) = from.parent() else { return Ok(()); diff --git a/crates/sourceorigin-standard/src/rules/inline_tests.rs b/crates/sourceorigin-standard/src/rules/inline_tests.rs new file mode 100644 index 0000000..b75cbc3 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/inline_tests.rs @@ -0,0 +1,237 @@ +//! `inline-tests`: an inline test module that outgrows its share of a file +//! moves to a file of its own. + +use std::ops::RangeInclusive; +use std::path::{Path, PathBuf}; + +use proc_macro2::{TokenStream, TokenTree}; +use syn::spanned::Spanned; + +use super::fix::{Checked, Fix}; +use super::modules::Modules; +use super::source::Source; +use super::test_code::TestAttributes; +use super::{Finding, Repository}; + +/// The share of its file's lines, in percent, an inline test module may +/// make up. +const MAX_SHARE: usize = 30; + +/// An inline `#[cfg(test)]` module at a file's top level that makes up more +/// than [`MAX_SHARE`] of the file's lines. +pub(super) struct InlineTests<'a> { + pub(super) source: &'a Source, + item: &'a syn::ItemMod, + /// From its first attribute's line to its closing brace's, from 1. + lines: RangeInclusive, +} + +impl Repository { + /// Each inline test module over its share of its file, in a file a + /// target reaches outside test code. + pub(super) fn oversized_tests(&self) -> impl Iterator> { + self.sources + .iter() + .filter(|source| { + !source.generated + && !self.modules.of_file(&source.path).is_empty() + && !self.modules.is_test(&source.path) + }) + .flat_map(|source| { + let file_lines = source.text.lines().count(); + source.syntax.items.iter().filter_map(move |item| { + let syn::Item::Mod(item) = item else { + return None; + }; + let (brace, _) = item.content.as_ref()?; + if !item.attrs.cfg_test() { + return None; + } + let first = item.attrs.first().map_or_else( + || item.mod_token.span.start().line, + |attribute| attribute.span().start().line, + ); + let lines = first..=brace.span.close().start().line; + (lines.clone().count() * 100 > MAX_SHARE * file_lines).then_some(InlineTests { + source, + item, + lines, + }) + }) + }) + } + + /// Each inline test module over its share of its file, and the fix + /// moving it to a file of its own. + pub(super) fn inline_tests(&self) -> Checked { + let mut checked = Checked::default(); + for tests in self.oversized_tests() { + let child = self + .child_dir(&tests.source.path) + .map(|(dir, _)| dir.join(format!("{}.rs", tests.item.ident))); + let target = child.as_ref().map_or_else( + || format!("a file of its own, `mod {};`", tests.item.ident), + |child| format!("`{}`", child.display()), + ); + checked.findings.push(Finding { + path: tests.source.path.clone(), + line: *tests.lines.start(), + message: format!( + "the inline tests of `{}` span {} of the file's {} lines, over \ + {MAX_SHARE}%: move them to {target}", + tests.item.ident, + tests.lines.clone().count(), + tests.source.text.lines().count() + ), + }); + checked + .fixes + .extend(self.move_out(&tests).unwrap_or_default()); + } + checked + } + + /// The directory the child modules of the module at `path` live in, + /// and where the file moves first for it to have children, such as + /// `foo.rs` to `foo/mod.rs`. `None` for a crate root other than + /// `lib.rs` or `main.rs`, such as `src/bin/tool.rs`, whose child would + /// be a target of its own. + fn child_dir(&self, path: &Path) -> Option<(PathBuf, Option)> { + let name = path.file_name()?; + let root = self.metadata.is_crate_root(path); + let dir = Modules::child_dir(path, root); + if root { + return (name == "lib.rs" || name == "main.rs").then_some((dir, None)); + } + let moved = (name != "mod.rs").then(|| dir.join("mod.rs")); + Some((dir, moved)) + } + + /// The fixes moving `tests` to a file of its own, when its braces sit + /// alone at the ends of their lines and the file doesn't exist yet. + fn move_out(&self, tests: &InlineTests<'_>) -> Option> { + let source = tests.source; + let (brace, _) = tests.item.content.as_ref()?; + let (open, close) = (brace.span.open().start(), brace.span.close().start()); + let lines: Vec<&str> = source.text.lines().collect(); + let (open_line, close_line) = (lines.get(open.line - 1)?, lines.get(close.line - 1)?); + let header: String = open_line.chars().take(open.column).collect(); + let alone = |text: String| text.trim().is_empty(); + if tests.item.mod_token.span.start().line != open.line + || !alone(open_line.chars().skip(open.column + 1).collect()) + || !alone(close_line.chars().take(close.column).collect()) + || !alone(close_line.chars().skip(close.column + 1).collect()) + { + return None; + } + let (dir, moved) = self.child_dir(&source.path)?; + let ident = &tests.item.ident; + let child = dir.join(format!("{ident}.rs")); + if self.rust_files().any(|other| other == child) { + return None; + } + let body = Body(lines.get(open.line..close.line - 1)?); + let mut fixes = vec![ + Fix::replace_lines( + source.path.clone(), + format!("move the tests of `{ident}` to `{}`", child.display()), + open.line..=close.line, + format!("{};", header.trim_end()), + ), + Fix::create( + child, + format!("hold the tests of `{}`", source.path.display()), + body.text(moved.is_some()), + ) + .resolving(source.path.clone()), + ]; + if let Some(moved) = moved { + fixes.push(Fix::move_to( + source.path.clone(), + format!( + "move to `{}`, as it now has a child module", + moved.display() + ), + moved, + )); + } + Some(fixes) + } +} + +/// The lines between an inline module's braces. +struct Body<'a>(&'a [&'a str]); + +impl Body<'_> { + /// The macros that read a file relative to the one they are in. + const INCLUDES: [&str; 3] = ["include!(\"", "include_str!(\"", "include_bytes!(\""]; + + /// The text of the file the module moves to, `deeper` in a directory of + /// its own when its parent is `foo.rs`: the lines without the module's + /// indentation, and each relative path an include macro reads one + /// directory up when `deeper`. + fn text(&self, deeper: bool) -> String { + let mut text = self.dedented(); + if deeper { + for include in Self::INCLUDES { + text = text + .replace(include, &format!("{include}../")) + .replace(&format!("{include}..//"), &format!("{include}/")); + } + } + text + } + + /// The lines without the module's indentation, except those inside a + /// string literal, whose text the indentation is part of. + fn dedented(&self) -> String { + let literal = self.literal_lines(); + let kept = |at: &usize| !literal.contains(&(at + 1)); + let indent = self + .0 + .iter() + .enumerate() + .filter(|(at, line)| kept(at) && !line.trim().is_empty()) + .map(|(_, line)| line.len() - line.trim_start().len()) + .min() + .unwrap_or(0); + let lines: Vec<&str> = self + .0 + .iter() + .enumerate() + .map(|(at, line)| { + if !kept(&at) { + line + } else if line.trim().is_empty() { + "" + } else { + line.get(indent..).unwrap_or(line) + } + }) + .collect(); + lines.join("\n") + "\n" + } + + /// The lines, from 1, that continue a string literal started on an + /// earlier line. + fn literal_lines(&self) -> Vec { + let mut lines = Vec::new(); + if let Ok(tokens) = self.0.join("\n").parse::() { + Self::collect_literal_lines(tokens, &mut lines); + } + lines + } + + fn collect_literal_lines(tokens: TokenStream, lines: &mut Vec) { + for token in tokens { + match token { + TokenTree::Group(group) => Self::collect_literal_lines(group.stream(), lines), + TokenTree::Literal(literal) => { + let span = literal.span(); + lines.extend(span.start().line + 1..=span.end().line); + } + TokenTree::Ident(_) | TokenTree::Punct(_) => {} + } + } + } +} diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index a8e3b96..c99b02e 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -10,10 +10,12 @@ mod comments; mod config_comments; mod fix; mod generated_lints; +mod inline_tests; mod level; mod modules; mod report; mod source; +mod test_code; #[cfg(test)] mod tests; mod unsafe_modules; @@ -120,6 +122,10 @@ rules! { /// test's, benchmark's or example's root, such as `tests/common/mod.rs`, /// passes. ChildlessModRs = "childless-mod-rs" => childless_mod_rs, + /// An inline `#[cfg(test)] mod … { }` at the top level of a file a + /// target reaches outside test code spans at most 30% of the file's + /// lines; a larger one is a file of its own, `mod tests;`. + InlineTests = "inline-tests" => inline_tests, } /// Why the rules couldn't be checked. diff --git a/crates/sourceorigin-standard/src/rules/modules.rs b/crates/sourceorigin-standard/src/rules/modules.rs index c672dab..8f53869 100644 --- a/crates/sourceorigin-standard/src/rules/modules.rs +++ b/crates/sourceorigin-standard/src/rules/modules.rs @@ -1,14 +1,15 @@ //! Each Rust file's module paths, from walking every target's module tree //! as rustc does: from its root file through each `mod` item, `#[path]` -//! included. +//! included, and which files are test code. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Component, Path, PathBuf}; use syn::{Expr, Lit, Meta}; use super::source::Source; -use crate::metadata::Metadata; +use super::test_code::TestAttributes; +use crate::metadata::{Metadata, TargetKind}; /// The module paths of each Rust file a target reaches, such as /// `["my_crate", "ffi"]` for `src/ffi.rs`. A target's root module is its @@ -16,7 +17,26 @@ use crate::metadata::Metadata; /// `build_script_build` for a build script. A file a module tree shares, /// through `#[path]`, has several. #[derive(Debug, Default)] -pub(super) struct Modules(BTreeMap>>); +pub(super) struct Modules { + paths: BTreeMap>>, + /// The files some target reaches other than as test code: outside an + /// integration test or benchmark, and not through a `#[cfg(test)]` + /// module. + not_test: BTreeSet, +} + +/// Where a walk over `mod` items is. +#[derive(Clone, Copy)] +struct Place<'a> { + /// The file the items are in. + file: &'a Path, + /// Where the files of their child modules live. + dir: &'a Path, + /// Whether they are inside a `mod { … }`. + inline: bool, + /// Whether they are test code. + test: bool, +} impl Modules { /// The module trees of every target of `metadata`'s crates, over @@ -35,8 +55,12 @@ impl Modules { let Ok(root) = target.src_path.strip_prefix(&metadata.workspace_root) else { continue; }; - let dir = root.parent().map_or_else(PathBuf::new, Path::to_owned); - modules.walk(&sources, root, &[target.name.replace('-', "_")], &dir); + let test = target + .kind + .iter() + .all(|kind| matches!(kind, TargetKind::Test | TargetKind::Bench)); + let module = [target.name.replace('-', "_")]; + modules.walk(&sources, root, &module, &Self::child_dir(root, true), test); } modules } @@ -44,39 +68,63 @@ impl Modules { /// The module paths of `path`, from the repository's root: none for a /// file no target reaches. pub(super) fn of_file(&self, path: &Path) -> &[Vec] { - self.0.get(path).map_or(&[], Vec::as_slice) + self.paths.get(path).map_or(&[], Vec::as_slice) + } + + /// Whether every target reaching `path` reaches it as test code: it is + /// part of an integration test or benchmark, or a `#[cfg(test)]` module + /// declares it or a module above it. + pub(super) fn is_test(&self, path: &Path) -> bool { + self.paths.contains_key(path) && !self.not_test.contains(path) + } + + /// The directory the child modules of `file` live in: a target's + /// `root`'s or a `mod.rs`'s own, and `foo/` for `foo.rs`. + pub(super) fn child_dir(file: &Path, root: bool) -> PathBuf { + if root || file.file_name().is_some_and(|name| name == "mod.rs") { + file.parent().map_or_else(PathBuf::new, Path::to_owned) + } else { + file.with_extension("") + } } /// Records `file` as `module`, whose child modules' files live in - /// `dir`, and walks its `mod` items. + /// `dir`, test code when `test`, and walks its `mod` items. fn walk( &mut self, sources: &BTreeMap<&Path, &Source>, file: &Path, module: &[String], dir: &Path, + test: bool, ) { let Some(source) = sources.get(file) else { return; }; - let paths = self.0.entry(file.to_owned()).or_default(); + if !test { + self.not_test.insert(file.to_owned()); + } + let paths = self.paths.entry(file.to_owned()).or_default(); if paths.iter().any(|path| path == module) { return; } paths.push(module.to_vec()); - self.items(sources, &source.syntax.items, file, module, dir, false); + let place = Place { + file, + dir, + inline: false, + test, + }; + self.items(sources, &source.syntax.items, module, &place); } - /// Walks the `mod` items of `items`, in `file`, inside `module`, whose - /// child modules' files live in `dir`; `inline` inside a `mod { … }`. + /// Walks the `mod` items of `items`, inside `module`, at `place`. fn items( &mut self, sources: &BTreeMap<&Path, &Source>, items: &[syn::Item], - file: &Path, module: &[String], - dir: &Path, - inline: bool, + place: &Place<'_>, ) { for item in items { let syn::Item::Mod(item) = item else { @@ -85,15 +133,26 @@ impl Modules { let name = item.ident.to_string(); let mut child = module.to_vec(); child.push(name.clone()); + let test = place.test || item.attrs.cfg_test(); + let dir = place.dir; if let Some((_, items)) = &item.content { - self.items(sources, items, file, &child, &dir.join(&name), true); + let inner = Place { + dir: &dir.join(&name), + inline: true, + test, + ..*place + }; + self.items(sources, items, &child, &inner); continue; } let attribute = Self::path_attribute(&item.attrs).map(|path| { - let base = if inline { + let base = if place.inline { dir.to_owned() } else { - file.parent().map_or_else(PathBuf::new, Path::to_owned) + place + .file + .parent() + .map_or_else(PathBuf::new, Path::to_owned) }; Self::normalize(&base.join(path)) }); @@ -105,12 +164,13 @@ impl Modules { ]) .find(|candidate| sources.contains_key(candidate.as_path())); if let Some(found) = found { - let child_dir = if found.file_name().is_some_and(|file| file == "mod.rs") { - found.parent().map_or_else(PathBuf::new, Path::to_owned) - } else { - found.with_extension("") - }; - self.walk(sources, &found, &child, &child_dir); + self.walk( + sources, + &found, + &child, + &Self::child_dir(&found, false), + test, + ); } } } diff --git a/crates/sourceorigin-standard/src/rules/source.rs b/crates/sourceorigin-standard/src/rules/source.rs index 0f373fe..599dc8a 100644 --- a/crates/sourceorigin-standard/src/rules/source.rs +++ b/crates/sourceorigin-standard/src/rules/source.rs @@ -16,6 +16,7 @@ use crate::workspace::Workspace; pub(super) struct Source { /// From the repository's root. pub(super) path: PathBuf, + pub(super) text: String, pub(super) syntax: syn::File, /// Every lint attribute in it, inner and outer, at any depth. pub(super) lints: Vec, @@ -86,6 +87,7 @@ impl Source { lints.visit_file(&syntax); Ok(Self { path, + text: text.to_owned(), syntax, lints: lints.0, generated: false, diff --git a/crates/sourceorigin-standard/src/rules/test_code.rs b/crates/sourceorigin-standard/src/rules/test_code.rs new file mode 100644 index 0000000..44c0d57 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/test_code.rs @@ -0,0 +1,51 @@ +//! Test code, which several rules exempt: what `#[cfg(test)]` marks. + +use syn::punctuated::Punctuated; +use syn::{Attribute, Meta, Token}; + +/// An item's attributes, read for whether they mark test code. +pub(super) trait TestAttributes { + /// Whether a `cfg` among them requires `test`, as `#[cfg(test)]` and + /// `#[cfg(all(test, unix))]` do. + fn cfg_test(&self) -> bool; +} + +impl TestAttributes for [Attribute] { + fn cfg_test(&self) -> bool { + self.iter().any(|attribute| { + attribute.path().is_ident("cfg") + && attribute + .parse_args::() + .is_ok_and(|meta| meta.requires_test()) + }) + } +} + +/// A `cfg` predicate. +trait Predicate { + /// Whether it holds only when `test` does. + fn requires_test(&self) -> bool; +} + +impl Predicate for Meta { + fn requires_test(&self) -> bool { + match self { + Self::Path(path) => path.is_ident("test"), + Self::List(list) => { + let Ok(predicates) = + list.parse_args_with(Punctuated::::parse_terminated) + else { + return false; + }; + if list.path.is_ident("all") { + predicates.iter().any(Self::requires_test) + } else if list.path.is_ident("any") { + !predicates.is_empty() && predicates.iter().all(Self::requires_test) + } else { + false + } + } + Self::NameValue(_) => false, + } + } +} diff --git a/crates/sourceorigin-standard/src/rules/tests/inline_tests.rs b/crates/sourceorigin-standard/src/rules/tests/inline_tests.rs new file mode 100644 index 0000000..7341bd0 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/inline_tests.rs @@ -0,0 +1,80 @@ +use super::{Fixture, INHERITS}; +use crate::rules::{Rule, fix}; + +/// A module whose inline tests span 11 of its 15 lines, one of them inside a +/// string literal, and read a file beside it. +const BIG: &str = "pub fn one() -> u8 {\n 1\n}\n\n#[cfg(test)]\nmod tests {\n use \ + super::*;\n\n #[test]\n fn one_is_one() {\n assert_eq!(one(), \ + 1, \"{}\", \"a\n b\");\n }\n const DATA: &str = \ + include_str!(\"data.txt\");\n}\n"; + +#[test] +fn inline_tests_over_30_percent_of_their_file_move_to_a_file_of_their_own() { + let fixture = Fixture::new(); + fixture + .add_crate("core", INHERITS) + .write( + "crates/core/src/lib.rs", + "mod big;\nmod nested;\nmod small;\n#[cfg(all(test, unix))]\n\ + mod unix { #[test] fn runs() {} }\n", + ) + .write("crates/core/src/big.rs", BIG) + .write( + "crates/core/src/nested/mod.rs", + "#[cfg(test)]\nmod tests {\n #[test]\n fn runs() {}\n}\n", + ) + .write( + "crates/core/src/small.rs", + &format!( + "{}#[cfg(test)]\nmod tests {{}}\n", + "pub fn f() {}\n".repeat(5) + ), + ) + .write( + "crates/core/tests/it.rs", + "#[cfg(test)]\nmod tests {\n #[test]\n fn runs() {}\n}\n", + ); + assert_eq!( + fixture.violations(Rule::InlineTests), + [ + "crates/core/src/big.rs:5: the inline tests of `tests` span 11 of the file's 15 \ + lines, over 30%: move them to `crates/core/src/big/tests.rs` (inline-tests)", + "crates/core/src/lib.rs:4: the inline tests of `unix` span 2 of the file's 5 lines, \ + over 30%: move them to `crates/core/src/unix.rs` (inline-tests)", + "crates/core/src/nested/mod.rs:1: the inline tests of `tests` span 5 of the file's \ + 5 lines, over 30%: move them to `crates/core/src/nested/tests.rs` (inline-tests)", + ] + ); + assert_eq!( + fixture.violations(Rule::ChildlessModRs), + Vec::::new() + ); + + fix(fixture.0.root()).expect("the fixes are made"); + let read = |path: &str| { + std::fs::read_to_string(fixture.0.root().join("crates/core/src").join(path)) + .expect("the file is read") + }; + assert_eq!( + read("big/mod.rs"), + "pub fn one() -> u8 {\n 1\n}\n\n#[cfg(test)]\nmod tests;\n" + ); + assert_eq!( + read("big/tests.rs"), + "use super::*;\n\n#[test]\nfn one_is_one() {\n assert_eq!(one(), 1, \"{}\", \"a\n \ + b\");\n}\nconst DATA: &str = include_str!(\"../data.txt\");\n" + ); + assert_eq!(read("nested/mod.rs"), "#[cfg(test)]\nmod tests;\n"); + assert_eq!(read("nested/tests.rs"), "#[test]\nfn runs() {}\n"); + assert_eq!( + fixture.violations(Rule::InlineTests), + [ + "crates/core/src/lib.rs:4: the inline tests of `unix` span 2 of the file's 5 lines, \ + over 30%: move them to `crates/core/src/unix.rs` (inline-tests)" + ] + ); + assert_eq!( + fixture.violations(Rule::ChildlessModRs), + Vec::::new() + ); +} diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index 7e15534..7a7adc6 100644 --- a/crates/sourceorigin-standard/src/rules/tests/mod.rs +++ b/crates/sourceorigin-standard/src/rules/tests/mod.rs @@ -7,6 +7,7 @@ mod config_comments; mod fix; mod framework; mod generated_lints; +mod inline_tests; mod report; mod unsafe_modules; mod workspace_lints;