Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
84 changes: 84 additions & 0 deletions crates/sourceorigin-standard/src/rules/inline_limits.rs
Original file line number Diff line number Diff line change
@@ -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<Finding>,
}

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<String> = 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<Finding> {
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
}
}
12 changes: 11 additions & 1 deletion crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod comments;
mod config_comments;
mod fix;
mod generated_lints;
mod inline_limits;
mod inline_tests;
mod level;
mod modules;
Expand All @@ -19,6 +20,7 @@ mod test_code;
#[cfg(test)]
mod tests;
mod unsafe_modules;
mod walk;
mod workspace_lints;

use std::fmt;
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions crates/sourceorigin-standard/src/rules/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
37 changes: 32 additions & 5 deletions crates/sourceorigin-standard/src/rules/test_code.rs
Original file line number Diff line number Diff line change
@@ -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] {
Expand All @@ -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;
}

Expand All @@ -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")
)
}
}
}
}
58 changes: 58 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/inline_limits.rs
Original file line number Diff line number Diff line change
@@ -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"),
]
);
}
1 change: 1 addition & 0 deletions crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
105 changes: 105 additions & 0 deletions crates/sourceorigin-standard/src/rules/walk.rs
Original file line number Diff line number Diff line change
@@ -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::<Expr, Token![,]>::parse_terminated)
{
for argument in &arguments {
self.visit_expr(argument);
}
}
}
}