From f1f4399958d5c1980c9809458feb81bc6768abe1 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 21:29:01 +0100 Subject: [PATCH] feat: inline-limits makes Durations with literals named constants Duration::from_* with a number, or arithmetic on numbers, sits only in a const or static item, a const fn or test code. A shared walk over each file's expressions tracks those scopes; test code spans test attributes, cfgs requiring test or a feature named for tests, and the files the module walk reaches only as test code. --- crates/sourceorigin-standard/README.md | 3 +- .../src/rules/inline_limits.rs | 84 ++++++++++++++ crates/sourceorigin-standard/src/rules/mod.rs | 12 +- .../src/rules/modules.rs | 5 +- .../src/rules/test_code.rs | 37 +++++- .../src/rules/tests/inline_limits.rs | 58 ++++++++++ .../src/rules/tests/mod.rs | 1 + .../sourceorigin-standard/src/rules/walk.rs | 105 ++++++++++++++++++ 8 files changed, 296 insertions(+), 9 deletions(-) create mode 100644 crates/sourceorigin-standard/src/rules/inline_limits.rs create mode 100644 crates/sourceorigin-standard/src/rules/tests/inline_limits.rs create mode 100644 crates/sourceorigin-standard/src/rules/walk.rs diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index b4cbe98..8f17679 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -38,7 +38,8 @@ 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;`. +- `inline-tests`: An inline `#[cfg(test)] mod … { }` (or one whose `cfg` requires a feature named for tests) 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;`. +- `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. Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and diff --git a/crates/sourceorigin-standard/src/rules/inline_limits.rs b/crates/sourceorigin-standard/src/rules/inline_limits.rs new file mode 100644 index 0000000..e20da73 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/inline_limits.rs @@ -0,0 +1,84 @@ +//! `inline-limits`: limits, timeouts and sizes are named constants. + +use std::path::Path; + +use syn::{Expr, ExprCall, Lit}; + +use super::walk::{Inspect, Scope, Walk}; +use super::{Finding, Repository}; + +/// The inline `Duration`s of one file. +struct Durations<'a> { + path: &'a Path, + findings: Vec, +} + +impl Inspect for Durations<'_> { + fn call(&mut self, call: &ExprCall, scope: Scope) { + if scope.test || scope.constant { + return; + } + let Expr::Path(function) = &*call.func else { + return; + }; + let segments: Vec = function + .path + .segments + .iter() + .map(|segment| segment.ident.to_string()) + .collect(); + let [.., ty, constructor] = segments.as_slice() else { + return; + }; + if ty != "Duration" + || !constructor.starts_with("from_") + || !call.args.iter().all(Self::is_literal) + { + return; + } + self.findings.push(Finding { + path: self.path.to_owned(), + line: function + .path + .segments + .first() + .map_or(1, |segment| segment.ident.span().start().line), + message: format!( + "`Duration::{constructor}` with a literal is an inline limit: make it a \ + named `const` with a doc comment" + ), + }); + } +} + +impl Durations<'_> { + /// Whether `expr` is a number, or arithmetic on numbers. + fn is_literal(expr: &Expr) -> bool { + match expr { + Expr::Lit(literal) => matches!(literal.lit, Lit::Int(_) | Lit::Float(_)), + Expr::Binary(binary) => { + Self::is_literal(&binary.left) && Self::is_literal(&binary.right) + } + Expr::Unary(unary) => Self::is_literal(&unary.expr), + Expr::Paren(paren) => Self::is_literal(&paren.expr), + _ => false, + } + } +} + +impl Repository { + /// Each `Duration::from_*` with a literal outside a `const` or + /// `static` item, a `const fn` and test code. + pub(super) fn inline_limits(&self) -> Vec { + let mut findings = Vec::new(); + for source in self.sources.iter().filter(|source| !source.generated) { + let mut durations = Durations { + path: &source.path, + findings: Vec::new(), + }; + Walk::file(source, self.modules.is_test(&source.path), &mut durations); + findings.extend(durations.findings); + } + findings + } +} diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index c99b02e..0165842 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -10,6 +10,7 @@ mod comments; mod config_comments; mod fix; mod generated_lints; +mod inline_limits; mod inline_tests; mod level; mod modules; @@ -19,6 +20,7 @@ mod test_code; #[cfg(test)] mod tests; mod unsafe_modules; +mod walk; mod workspace_lints; use std::fmt; @@ -122,10 +124,18 @@ 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 + /// An inline `#[cfg(test)] mod … { }` (or one whose `cfg` requires a + /// feature named for tests) 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, + /// `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. + InlineLimits = "inline-limits" => inline_limits, } /// 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 8f53869..efe459e 100644 --- a/crates/sourceorigin-standard/src/rules/modules.rs +++ b/crates/sourceorigin-standard/src/rules/modules.rs @@ -72,8 +72,9 @@ impl Modules { } /// 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. + /// part of an integration test or benchmark, or a module whose `cfg` + /// holds only in tests, such as `#[cfg(test)]`, 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) } diff --git a/crates/sourceorigin-standard/src/rules/test_code.rs b/crates/sourceorigin-standard/src/rules/test_code.rs index 44c0d57..6504d28 100644 --- a/crates/sourceorigin-standard/src/rules/test_code.rs +++ b/crates/sourceorigin-standard/src/rules/test_code.rs @@ -1,13 +1,21 @@ -//! Test code, which several rules exempt: what `#[cfg(test)]` marks. +//! Test code, which several rules exempt: what `#[cfg(test)]` or a test +//! attribute marks. The module walk reads it for the files that are test +//! code as a whole. 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. + /// Whether a `cfg` among them holds only in tests: it requires `test` + /// or a feature named for tests, as `#[cfg(test)]`, + /// `#[cfg(all(test, unix))]` and + /// `#[cfg(any(test, feature = "test-util"))]` do. fn cfg_test(&self) -> bool; + + /// Whether they mark test code: [`cfg_test`](Self::cfg_test), or a test + /// attribute such as `#[test]` or `#[tokio::test]`. + fn test(&self) -> bool; } impl TestAttributes for [Attribute] { @@ -19,11 +27,23 @@ impl TestAttributes for [Attribute] { .is_ok_and(|meta| meta.requires_test()) }) } + + fn test(&self) -> bool { + self.cfg_test() + || self.iter().any(|attribute| { + attribute + .path() + .segments + .last() + .is_some_and(|segment| segment.ident == "test") + }) + } } /// A `cfg` predicate. trait Predicate { - /// Whether it holds only when `test` does. + /// Whether it holds only when `test` or a feature whose name holds + /// `test` does. fn requires_test(&self) -> bool; } @@ -45,7 +65,14 @@ impl Predicate for Meta { false } } - Self::NameValue(_) => false, + Self::NameValue(feature) => { + feature.path.is_ident("feature") + && matches!( + &feature.value, + syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(name), .. }) + if name.value().contains("test") + ) + } } } } diff --git a/crates/sourceorigin-standard/src/rules/tests/inline_limits.rs b/crates/sourceorigin-standard/src/rules/tests/inline_limits.rs new file mode 100644 index 0000000..44e57a5 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/inline_limits.rs @@ -0,0 +1,58 @@ +use super::{Fixture, INHERITS}; +use crate::rules::Rule; + +/// A crate root with `Duration`s in every scope; lines 11, 12 and 15 hold +/// inline ones. +const LIB: &str = r#"use std::time::Duration; +mod support; +#[cfg(test)] +mod tests; +/// Named. +const TIMEOUT: Duration = Duration::from_secs(5); +static TICK: Duration = Duration::from_millis(10); +const fn limit() -> Duration { Duration::from_secs(1) } +fn wait(timeout: Duration) -> Duration { timeout } +fn run() { + wait(Duration::from_secs(30)); + wait(Duration::from_secs(2 * 60)); + wait(TIMEOUT); + wait(Duration::from_secs(u64::from(limit_secs()))); + println!("{:?}", std::time::Duration::from_millis(5)); +} +#[tokio::test] +async fn waits() { wait(Duration::from_secs(1)); } +#[cfg(feature = "test-util")] +fn fixture() -> Duration { Duration::from_secs(3) } +"#; + +/// A `Duration` with a literal. +const INLINE: &str = "fn f() { let _ = std::time::Duration::from_secs(1); }\n"; + +#[test] +fn durations_with_literals_sit_in_constants_or_test_code() { + let fixture = Fixture::new(); + fixture + .add_crate("core", INHERITS) + .write("crates/core/src/lib.rs", LIB) + .write("crates/core/src/tests.rs", INLINE) + .write( + "crates/core/src/support.rs", + "#[cfg(any(test, feature = \"test-util\"))]\nmod helpers;\n", + ) + .write("crates/core/src/support/helpers.rs", INLINE) + .write("crates/core/tests/it.rs", INLINE); + let message = |line: usize, constructor: &str| { + format!( + "crates/core/src/lib.rs:{line}: `Duration::{constructor}` with a literal is an \ + inline limit: make it a named `const` with a doc comment (inline-limits)" + ) + }; + assert_eq!( + fixture.violations(Rule::InlineLimits), + [ + message(11, "from_secs"), + message(12, "from_secs"), + message(15, "from_millis"), + ] + ); +} diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index 7a7adc6..1e5cb83 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_limits; mod inline_tests; mod report; mod unsafe_modules; diff --git a/crates/sourceorigin-standard/src/rules/walk.rs b/crates/sourceorigin-standard/src/rules/walk.rs new file mode 100644 index 0000000..52da820 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/walk.rs @@ -0,0 +1,105 @@ +//! A walk over a file's expressions that knows where each sits: in test +//! code, or in a `const` or `static` item or `const fn`. The rules over +//! expressions inspect files through it. + +use syn::punctuated::Punctuated; +use syn::visit::{self, Visit}; +use syn::{Expr, Token}; + +use super::source::Source; +use super::test_code::TestAttributes; + +/// Where an expression sits. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Scope { + /// In test code: a file of tests, or an item `#[cfg(test)]` or a test + /// attribute marks. + pub(super) test: bool, + /// In a `const` or `static` item, or a `const fn`. + pub(super) constant: bool, +} + +/// What a rule inspects as a [`Walk`] passes it. Each method sees every +/// node of its kind, in the macros whose arguments parse as expressions too. +pub(super) trait Inspect { + /// A function call, such as `Duration::from_secs(5)`. + fn call(&mut self, _call: &syn::ExprCall, _scope: Scope) {} + + /// A method call, such as `router.route("/", get(index))`. + fn method_call(&mut self, _call: &syn::ExprMethodCall, _scope: Scope) {} + + /// A macro invocation, such as `json!({})`. + fn macro_call(&mut self, _call: &syn::Macro, _scope: Scope) {} +} + +/// A walk over one file, passing its nodes to an [`Inspect`]. +pub(super) struct Walk<'a, I> { + inspect: &'a mut I, + scope: Scope, +} + +impl<'a, I: Inspect> Walk<'a, I> { + /// Passes the nodes of `source` to `inspect`, the whole file test code + /// when `test`. + pub(super) fn file(source: &Source, test: bool, inspect: &'a mut I) { + let mut walk = Self { + inspect, + scope: Scope { + test: test || source.syntax.attrs.test(), + constant: false, + }, + }; + walk.visit_file(&source.syntax); + } +} + +/// Visits each item kind in the scope its attributes set, and in a +/// constant scope where `constant` holds of it. +macro_rules! scoped { + ($($visit:ident($node:ty) $(=> $constant:expr)?;)*) => { + $( + fn $visit(&mut self, node: &'ast $node) { + let outer = self.scope; + self.scope.test |= node.attrs.test(); + $(self.scope.constant |= $constant(node);)? + visit::$visit(self, node); + self.scope = outer; + } + )* + }; +} + +impl<'ast, I: Inspect> Visit<'ast> for Walk<'_, I> { + scoped! { + 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; + } + + fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) { + self.inspect.call(call, self.scope); + visit::visit_expr_call(self, call); + } + + fn visit_expr_method_call(&mut self, call: &'ast syn::ExprMethodCall) { + self.inspect.method_call(call, self.scope); + visit::visit_expr_method_call(self, call); + } + + fn visit_macro(&mut self, call: &'ast syn::Macro) { + self.inspect.macro_call(call, self.scope); + if let Ok(arguments) = call.parse_body_with(Punctuated::::parse_terminated) + { + for argument in &arguments { + self.visit_expr(argument); + } + } + } +}