diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index e550bb2..213682a 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -42,6 +42,7 @@ A repository adopts the standard in four steps: - `inline-limits`: `Duration::from_*` with a number, or arithmetic on numbers, sits only in a `const` or `static` item, a `const fn` or test code: a limit, timeout or size is a named constant. Test code is what a test attribute such as `#[tokio::test]`, or a `cfg` requiring `test` or a feature named for tests (`test-util`), marks, the files such a module declares, and integration tests and benchmarks. - `no-json-macro`: Code outside tests, in the crates `standard.toml`'s `no-json-macro` lists, invokes no `json!`: it serializes structs. Each name there is a workspace crate. - `route-literals`: When `standard.toml`'s `route-modules` lists modules, such as `my_app::routes`, code outside them, tests and examples passes no string literal starting with `/` to `Router::route`, `route_service`, `nest` or `nest_service`, or to a `Redirect` constructor: it uses the paths those modules name. Each listed module is a file of a library or binary. +- `duplicate-items`: No function body outside test code with at least 50 tokens repeats another, token for token once identifiers are renamed in the order they appear. Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and diff --git a/crates/sourceorigin-standard/src/rules/duplicate_items.rs b/crates/sourceorigin-standard/src/rules/duplicate_items.rs new file mode 100644 index 0000000..6e86564 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/duplicate_items.rs @@ -0,0 +1,185 @@ +//! `duplicate-items`: a function body is written once. + +use std::collections::{BTreeMap, HashMap}; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::path::Path; + +use proc_macro2::{Delimiter, LineColumn, TokenStream, TokenTree}; + +use super::walk::{Inspect, Scope, Walk}; +use super::{Finding, Repository}; + +/// The fewest tokens a body holds for a copy of it to count: below 50, +/// piqueld's, sourceorigin's and DirkEngine's copies are boilerplate, such +/// as routers of two routes, rather than logic to share. +const MIN_TOKENS: usize = 50; + +/// The words the language reserves, which stay as written while other +/// identifiers are renamed. +const KEYWORDS: &[&str] = &[ + "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", + "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", + "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", + "unsafe", "use", "where", "while", +]; + +/// A token of a file, at its start. +struct Token { + at: LineColumn, + /// Whether it is an identifier other than a keyword, which a body's + /// shape renames. + renamed: bool, + /// The token as written, or its delimiter. + text: String, +} + +impl Token { + /// The tokens of `tokens` in order, delimiters included. + fn flatten(tokens: TokenStream, into: &mut Vec) { + for token in tokens { + match token { + TokenTree::Group(group) => { + let (open, close) = match group.delimiter() { + Delimiter::Parenthesis => ("(", ")"), + Delimiter::Brace => ("{", "}"), + Delimiter::Bracket => ("[", "]"), + Delimiter::None => ("", ""), + }; + into.push(Self::other(group.span_open().start(), open)); + Self::flatten(group.stream(), into); + into.push(Self::other(group.span_close().start(), close)); + } + TokenTree::Ident(ident) => { + let text = ident.to_string(); + let keyword = KEYWORDS.contains(&text.as_str()); + into.push(Self { + at: ident.span().start(), + renamed: !keyword, + text, + }); + } + TokenTree::Punct(punct) => { + into.push(Self::other( + punct.span().start(), + &punct.as_char().to_string(), + )); + } + TokenTree::Literal(literal) => { + into.push(Self::other(literal.span().start(), &literal.to_string())); + } + } + } + } + + fn other(at: LineColumn, text: &str) -> Self { + Self { + at, + renamed: false, + text: text.to_owned(), + } + } +} + +/// Where a body sits. +struct Occurrence<'a> { + path: &'a Path, + line: usize, + name: String, +} + +/// The function bodies of one file, by the hash of their shape: their +/// tokens, each identifier renamed by the order it first appears in. +struct Bodies<'a, 'b> { + path: &'a Path, + tokens: &'b [Token], + by_shape: &'b mut BTreeMap>>, +} + +impl Inspect for Bodies<'_, '_> { + fn function(&mut self, signature: &syn::Signature, body: &syn::Block, scope: Scope) { + if scope.test { + return; + } + let (open, close) = ( + body.brace_token.span.open().start(), + body.brace_token.span.close().start(), + ); + let position = |at: &LineColumn| (at.line, at.column); + let start = self + .tokens + .partition_point(|token| position(&token.at) <= position(&open)); + let end = self + .tokens + .partition_point(|token| position(&token.at) < position(&close)); + let Some(body) = self.tokens.get(start..end) else { + return; + }; + if body.len() < MIN_TOKENS { + return; + } + let mut names: HashMap<&str, usize> = HashMap::new(); + let mut shape = DefaultHasher::new(); + for token in body { + if token.renamed { + let next = names.len(); + Some(*names.entry(&token.text).or_insert(next)).hash(&mut shape); + } else { + None::.hash(&mut shape); + token.text.hash(&mut shape); + } + } + self.by_shape + .entry(shape.finish()) + .or_default() + .push(Occurrence { + path: self.path, + line: signature.ident.span().start().line, + name: signature.ident.to_string(), + }); + } +} + +impl Repository { + /// Each function body outside test code with at least [`MIN_TOKENS`] + /// tokens that repeats an earlier one, identifiers renamed in the order + /// they appear. + pub(super) fn duplicate_items(&self) -> Vec { + let mut by_shape = BTreeMap::new(); + let mut tokens = Vec::new(); + for source in self.sources.iter().filter(|source| !source.generated) { + tokens.clear(); + if let Ok(stream) = source.text.parse::() { + Token::flatten(stream, &mut tokens); + } + let mut bodies = Bodies { + path: &source.path, + tokens: &tokens, + by_shape: &mut by_shape, + }; + Walk::file(source, self.modules.is_test(&source.path), &mut bodies); + } + by_shape + .into_values() + .filter(|occurrences| occurrences.len() > 1) + .flat_map(|occurrences| { + let mut occurrences = occurrences.into_iter(); + let first = occurrences.next(); + occurrences.filter_map(move |occurrence| { + let first = first.as_ref()?; + Some(Finding { + path: occurrence.path.to_owned(), + line: occurrence.line, + message: format!( + "the body of `{}` repeats that of `{}` ({}:{}), names aside: \ + write it once, on the type that owns it, and call it", + occurrence.name, + first.name, + first.path.display(), + first.line + ), + }) + }) + }) + .collect() + } +} diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index e36b4e0..cde9f98 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -8,6 +8,7 @@ mod budget; mod childless_mod_rs; mod comments; mod config_comments; +mod duplicate_items; mod fix; mod generated_lints; mod inline_limits; @@ -149,6 +150,10 @@ rules! { /// paths those modules name. Each listed module is a file of a library /// or binary. RouteLiterals = "route-literals" => route_literals, + /// No function body outside test code with at least 50 tokens repeats + /// another, token for token once identifiers are renamed in the order + /// they appear. + DuplicateItems = "duplicate-items" => duplicate_items, } /// Why the rules couldn't be checked. diff --git a/crates/sourceorigin-standard/src/rules/tests/duplicate_items.rs b/crates/sourceorigin-standard/src/rules/tests/duplicate_items.rs new file mode 100644 index 0000000..46d4fa0 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/duplicate_items.rs @@ -0,0 +1,64 @@ +use super::{Fixture, INHERITS}; +use crate::rules::Rule; + +/// A function whose body holds 50 tokens. +const TOTAL: &str = "fn total(items: &[u32]) -> u32 { + let limit = items.len() as u32; + let mut total = 0; + for item in items { + if *item > 10 { + total += item * 2; + } else { + total += item + 1; + } + } + total + limit +} +"; + +/// `TOTAL` with every name changed. +const SUM: &str = "fn sum(values: &[u32]) -> u32 { + let count = values.len() as u32; + let mut sum = 0; + for value in values { + if *value > 10 { + sum += value * 2; + } else { + sum += value + 1; + } + } + sum + count +} +"; + +/// A function of fewer than 50 tokens, twice. +const SMALL: &str = + "fn a(x: u32) -> u32 {\n x * 2 + 1\n}\nfn b(y: u32) -> u32 {\n y * 2 + 1\n}\n"; + +#[test] +fn a_body_of_50_tokens_is_written_once() { + let fixture = Fixture::new(); + fixture + .add_crate("core", INHERITS) + .write( + "crates/core/src/lib.rs", + &format!("mod other;\n{TOTAL}{SMALL}"), + ) + .write("crates/core/src/other.rs", SUM) + .write( + "crates/core/tests/it.rs", + &format!( + "{}{}", + TOTAL.replace("total(", "copy("), + SUM.replace("sum(", "again(") + ), + ); + assert_eq!( + fixture.violations(Rule::DuplicateItems), + [ + "crates/core/src/other.rs:1: the body of `sum` repeats that of `total` \ + (crates/core/src/lib.rs:2), names aside: write it once, on the type that owns it, \ + and call it (duplicate-items)" + ] + ); +} diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index 26c6933..ef6e1b3 100644 --- a/crates/sourceorigin-standard/src/rules/tests/mod.rs +++ b/crates/sourceorigin-standard/src/rules/tests/mod.rs @@ -4,6 +4,7 @@ mod budget; mod childless_mod_rs; mod comments; mod config_comments; +mod duplicate_items; mod fix; mod framework; mod generated_lints; diff --git a/crates/sourceorigin-standard/src/rules/walk.rs b/crates/sourceorigin-standard/src/rules/walk.rs index 52da820..1cb0462 100644 --- a/crates/sourceorigin-standard/src/rules/walk.rs +++ b/crates/sourceorigin-standard/src/rules/walk.rs @@ -30,6 +30,9 @@ pub(super) trait Inspect { /// A macro invocation, such as `json!({})`. fn macro_call(&mut self, _call: &syn::Macro, _scope: Scope) {} + + /// A function or method with a body, before the nodes inside it. + fn function(&mut self, _signature: &syn::Signature, _body: &syn::Block, _scope: Scope) {} } /// A walk over one file, passing its nodes to an [`Inspect`]. @@ -53,15 +56,21 @@ impl<'a, I: Inspect> Walk<'a, I> { } } -/// Visits each item kind in the scope its attributes set, and in a -/// constant scope where `constant` holds of it. +/// Visits each item kind in the scope its attributes set, in a constant +/// scope where `const` holds of it, and passes the function `fn` finds in +/// it to [`Inspect::function`]. macro_rules! scoped { - ($($visit:ident($node:ty) $(=> $constant:expr)?;)*) => { + ($($visit:ident($node:ty) $(const $constant:expr)? $(, fn $function:expr)?;)*) => { $( fn $visit(&mut self, node: &'ast $node) { let outer = self.scope; self.scope.test |= node.attrs.test(); $(self.scope.constant |= $constant(node);)? + $( + if let Some((signature, body)) = $function(node) { + self.inspect.function(signature, body, self.scope); + } + )? visit::$visit(self, node); self.scope = outer; } @@ -74,13 +83,19 @@ impl<'ast, I: Inspect> Visit<'ast> for Walk<'_, I> { visit_item_mod(syn::ItemMod); visit_item_impl(syn::ItemImpl); visit_item_trait(syn::ItemTrait); - visit_item_fn(syn::ItemFn) => |node: &syn::ItemFn| node.sig.constness.is_some(); - visit_impl_item_fn(syn::ImplItemFn) => |node: &syn::ImplItemFn| node.sig.constness.is_some(); - visit_trait_item_fn(syn::TraitItemFn) => |node: &syn::TraitItemFn| node.sig.constness.is_some(); - visit_item_const(syn::ItemConst) => |_| true; - visit_item_static(syn::ItemStatic) => |_| true; - visit_impl_item_const(syn::ImplItemConst) => |_| true; - visit_trait_item_const(syn::TraitItemConst) => |_| true; + visit_item_fn(syn::ItemFn) + const |node: &syn::ItemFn| node.sig.constness.is_some(), + fn |node: &'ast syn::ItemFn| Some((&node.sig, &*node.block)); + visit_impl_item_fn(syn::ImplItemFn) + const |node: &syn::ImplItemFn| node.sig.constness.is_some(), + fn |node: &'ast syn::ImplItemFn| Some((&node.sig, &node.block)); + visit_trait_item_fn(syn::TraitItemFn) + const |node: &syn::TraitItemFn| node.sig.constness.is_some(), + fn |node: &'ast syn::TraitItemFn| node.default.as_ref().map(|body| (&node.sig, body)); + visit_item_const(syn::ItemConst) const |_| true; + visit_item_static(syn::ItemStatic) const |_| true; + visit_impl_item_const(syn::ImplItemConst) const |_| true; + visit_trait_item_const(syn::TraitItemConst) const |_| true; } fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) {