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
5 changes: 5 additions & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ A repository adopts the standard in four steps:
- `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.
- `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.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down Expand Up @@ -69,6 +70,10 @@ unsafe-modules = ["my_crate::ffi"]
# `json!`.
no-json-macro = ["my_protocol"]

# The modules that name the HTTP paths routers and redirects use; code
# elsewhere passes them no `/…` literal. Unset, paths aren't checked.
route-modules = ["my_app::routes"]

[comments]
# The most lines of prose an item's or module's docs may span, code blocks
# and a crate root's `//!` docs aside.
Expand Down
4 changes: 4 additions & 0 deletions crates/sourceorigin-standard/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ pub(crate) struct Config {
pub(crate) unsafe_modules: Vec<Listed>,
/// The crates whose code outside tests uses no `json!`.
pub(crate) no_json_macro: Vec<Listed>,
/// The modules that own HTTP paths, such as `my_app::routes`.
pub(crate) route_modules: Vec<Listed>,
/// The `[comments]` table.
pub(crate) comments: Comments,
}
Expand Down Expand Up @@ -226,6 +228,7 @@ struct File {
check_changed: CheckChanged,
unsafe_modules: Vec<Spanned<String>>,
no_json_macro: Vec<Spanned<String>>,
route_modules: Vec<Spanned<String>>,
comments: Comments,
}

Expand Down Expand Up @@ -355,6 +358,7 @@ impl Config {
check_changed: file.check_changed,
unsafe_modules: listed(file.unsafe_modules),
no_json_macro: listed(file.no_json_macro),
route_modules: listed(file.route_modules),
comments: file.comments,
})
}
Expand Down
8 changes: 8 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod level;
mod modules;
mod no_json_macro;
mod report;
mod route_literals;
mod source;
mod test_code;
#[cfg(test)]
Expand Down Expand Up @@ -141,6 +142,13 @@ rules! {
/// lists, invokes no `json!`: it serializes structs. Each name there is
/// a workspace crate.
NoJsonMacro = "no-json-macro" => no_json_macro,
/// 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.
RouteLiterals = "route-literals" => route_literals,
}

/// Why the rules couldn't be checked.
Expand Down
69 changes: 50 additions & 19 deletions crates/sourceorigin-standard/src/rules/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,20 @@ use crate::metadata::{Metadata, TargetKind};
#[derive(Debug, Default)]
pub(super) struct Modules {
paths: BTreeMap<PathBuf, Vec<Vec<String>>>,
/// 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<PathBuf>,
/// What each file is to the targets reaching it.
codes: BTreeMap<PathBuf, BTreeSet<Code>>,
}

/// What a file is to a target reaching it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Code {
/// Part of a library, binary or build script.
Production,
/// Part of an integration test or benchmark, or behind a module whose
/// `cfg` holds only in tests.
Test,
/// Part of an example.
Example,
}

/// Where a walk over `mod` items is.
Expand All @@ -34,8 +44,8 @@ struct Place<'a> {
dir: &'a Path,
/// Whether they are inside a `mod { … }`.
inline: bool,
/// Whether they are test code.
test: bool,
/// What they are to the target.
code: Code,
}

impl Modules {
Expand All @@ -55,12 +65,19 @@ impl Modules {
let Ok(root) = target.src_path.strip_prefix(&metadata.workspace_root) else {
continue;
};
let test = target
let code = if target
.kind
.iter()
.all(|kind| matches!(kind, TargetKind::Test | TargetKind::Bench));
.all(|kind| matches!(kind, TargetKind::Test | TargetKind::Bench))
{
Code::Test
} else if target.kind.contains(&TargetKind::Example) {
Code::Example
} else {
Code::Production
};
let module = [target.name.replace('-', "_")];
modules.walk(&sources, root, &module, &Self::child_dir(root, true), test);
modules.walk(&sources, root, &module, &Self::child_dir(root, true), code);
}
modules
}
Expand All @@ -76,7 +93,19 @@ impl Modules {
/// 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)
self.only(path, Code::Test)
}

/// Whether only examples reach `path`.
pub(super) fn is_example(&self, path: &Path) -> bool {
self.only(path, Code::Example)
}

/// Whether some target reaches `path`, and every one as `code`.
fn only(&self, path: &Path, code: Code) -> bool {
self.codes
.get(path)
.is_some_and(|codes| codes.iter().all(|&reached| reached == code))
}

/// The directory the child modules of `file` live in: a target's
Expand All @@ -90,21 +119,19 @@ impl Modules {
}

/// Records `file` as `module`, whose child modules' files live in
/// `dir`, test code when `test`, and walks its `mod` items.
/// `dir`, which is `code` to its target, and walks its `mod` items.
fn walk(
&mut self,
sources: &BTreeMap<&Path, &Source>,
file: &Path,
module: &[String],
dir: &Path,
test: bool,
code: Code,
) {
let Some(source) = sources.get(file) else {
return;
};
if !test {
self.not_test.insert(file.to_owned());
}
self.codes.entry(file.to_owned()).or_default().insert(code);
let paths = self.paths.entry(file.to_owned()).or_default();
if paths.iter().any(|path| path == module) {
return;
Expand All @@ -114,7 +141,7 @@ impl Modules {
file,
dir,
inline: false,
test,
code,
};
self.items(sources, &source.syntax.items, module, &place);
}
Expand All @@ -134,13 +161,17 @@ 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 code = if item.attrs.cfg_test() {
Code::Test
} else {
place.code
};
let dir = place.dir;
if let Some((_, items)) = &item.content {
let inner = Place {
dir: &dir.join(&name),
inline: true,
test,
code,
..*place
};
self.items(sources, items, &child, &inner);
Expand Down Expand Up @@ -170,7 +201,7 @@ impl Modules {
&found,
&child,
&Self::child_dir(&found, false),
test,
code,
);
}
}
Expand Down
123 changes: 123 additions & 0 deletions crates/sourceorigin-standard/src/rules/route_literals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
//! `route-literals`: the modules `standard.toml` lists own the HTTP paths.

use std::path::Path;

use syn::{Expr, Lit};

use super::walk::{Inspect, Scope, Walk};
use super::{Finding, Repository};
use crate::config;

/// The `Router` methods that take a path first.
const ROUTER_METHODS: [&str; 4] = ["route", "route_service", "nest", "nest_service"];

/// The path literals outside test code that route or redirect in one file.
struct RouteLiterals<'a> {
path: &'a Path,
findings: Vec<Finding>,
}

impl RouteLiterals<'_> {
/// Records `argument` as `what`'s path when it is a string literal
/// starting with `/`.
fn record(&mut self, argument: Option<&Expr>, what: &str) {
let Some(Expr::Lit(literal)) = argument else {
return;
};
let Lit::Str(text) = &literal.lit else {
return;
};
if !text.value().starts_with('/') {
return;
}
self.findings.push(Finding {
path: self.path.to_owned(),
line: text.span().start().line,
message: format!(
"`{what}` takes the path `{}` as a literal: name it in a module \
`route-modules` in {} lists, and use that",
text.value(),
config::PATH
),
});
}
}

impl Inspect for RouteLiterals<'_> {
fn method_call(&mut self, call: &syn::ExprMethodCall, scope: Scope) {
let method = call.method.to_string();
if !scope.test && ROUTER_METHODS.contains(&method.as_str()) {
self.record(call.args.first(), &format!(".{method}"));
}
}

fn call(&mut self, call: &syn::ExprCall, scope: Scope) {
let Expr::Path(function) = &*call.func else {
return;
};
let mut segments = function.path.segments.iter().rev();
let (Some(constructor), Some(ty)) = (segments.next(), segments.next()) else {
return;
};
if !scope.test && ty.ident == "Redirect" {
self.record(
call.args.first(),
&format!("Redirect::{}", constructor.ident),
);
}
}
}

impl Repository {
/// Each path literal passed to a `Router` method or a `Redirect`
/// outside test code, examples and the modules `route-modules` lists,
/// and each listed module that no file is. Nothing when the list is
/// empty.
pub(super) fn route_literals(&self) -> Vec<Finding> {
let listed = &self.config.route_modules;
if listed.is_empty() {
return Vec::new();
}
let modules = |path: &Path| {
self.modules
.of_file(path)
.iter()
.map(|module| module.join("::"))
.collect::<Vec<_>>()
};
let mut findings: Vec<Finding> = listed
.iter()
.filter(|entry| {
!self
.sources
.iter()
.any(|source| modules(&source.path).contains(&entry.value))
})
.map(|entry| Finding {
path: config::PATH.into(),
line: entry.line,
message: format!(
"`{}` is in `route-modules`, but no file is that module: remove it",
entry.value
),
})
.collect();
for source in &self.sources {
let owns_routes = modules(&source.path).iter().any(|module| {
listed.iter().any(|entry| {
*module == entry.value || module.starts_with(&format!("{}::", entry.value))
})
});
if owns_routes || source.generated || self.modules.is_example(&source.path) {
continue;
}
let mut literals = RouteLiterals {
path: &source.path,
findings: Vec::new(),
};
Walk::file(source, self.modules.is_test(&source.path), &mut literals);
findings.extend(literals.findings);
}
findings
}
}
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 @@ -11,6 +11,7 @@ mod inline_limits;
mod inline_tests;
mod no_json_macro;
mod report;
mod route_literals;
mod unsafe_modules;
mod workspace_lints;

Expand Down
Loading