diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index 3d795c8..e550bb2 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -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. Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and @@ -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. diff --git a/crates/sourceorigin-standard/src/config/mod.rs b/crates/sourceorigin-standard/src/config/mod.rs index 01a6816..20e5cc8 100644 --- a/crates/sourceorigin-standard/src/config/mod.rs +++ b/crates/sourceorigin-standard/src/config/mod.rs @@ -76,6 +76,8 @@ pub(crate) struct Config { pub(crate) unsafe_modules: Vec, /// The crates whose code outside tests uses no `json!`. pub(crate) no_json_macro: Vec, + /// The modules that own HTTP paths, such as `my_app::routes`. + pub(crate) route_modules: Vec, /// The `[comments]` table. pub(crate) comments: Comments, } @@ -226,6 +228,7 @@ struct File { check_changed: CheckChanged, unsafe_modules: Vec>, no_json_macro: Vec>, + route_modules: Vec>, comments: Comments, } @@ -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, }) } diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index 40d3e99..e36b4e0 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -16,6 +16,7 @@ mod level; mod modules; mod no_json_macro; mod report; +mod route_literals; mod source; mod test_code; #[cfg(test)] @@ -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. diff --git a/crates/sourceorigin-standard/src/rules/modules.rs b/crates/sourceorigin-standard/src/rules/modules.rs index efe459e..ddd9cda 100644 --- a/crates/sourceorigin-standard/src/rules/modules.rs +++ b/crates/sourceorigin-standard/src/rules/modules.rs @@ -19,10 +19,20 @@ use crate::metadata::{Metadata, TargetKind}; #[derive(Debug, Default)] 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, + /// What each file is to the targets reaching it. + codes: BTreeMap>, +} + +/// 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. @@ -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 { @@ -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 } @@ -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 @@ -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; @@ -114,7 +141,7 @@ impl Modules { file, dir, inline: false, - test, + code, }; self.items(sources, &source.syntax.items, module, &place); } @@ -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); @@ -170,7 +201,7 @@ impl Modules { &found, &child, &Self::child_dir(&found, false), - test, + code, ); } } diff --git a/crates/sourceorigin-standard/src/rules/route_literals.rs b/crates/sourceorigin-standard/src/rules/route_literals.rs new file mode 100644 index 0000000..99a6a9a --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/route_literals.rs @@ -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, +} + +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 { + 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::>() + }; + let mut findings: Vec = 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 + } +} diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index 51de029..26c6933 100644 --- a/crates/sourceorigin-standard/src/rules/tests/mod.rs +++ b/crates/sourceorigin-standard/src/rules/tests/mod.rs @@ -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; diff --git a/crates/sourceorigin-standard/src/rules/tests/route_literals.rs b/crates/sourceorigin-standard/src/rules/tests/route_literals.rs new file mode 100644 index 0000000..7c0c10d --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/route_literals.rs @@ -0,0 +1,72 @@ +use super::{Fixture, INHERITS}; +use crate::rules::Rule; + +/// A router and redirects, with literal paths on lines 3, 4 and 6. +const APP: &str = r#"fn router() -> Router { + Router::new() + .route("/settings", get(settings)) + .nest("/api", api()) + .route(routes::HOME, get(home)); + let _ = Redirect::to("/signed-out"); + let _ = Redirect::to("https://example.com/"); +} +#[test] +fn routes() { + Router::new().route("/test", get(ok)); +} +"#; + +#[test] +fn only_the_listed_route_modules_write_path_literals() { + let fixture = Fixture::new(); + fixture + .add_crate("app", INHERITS) + .write("crates/app/src/lib.rs", "mod handlers;\nmod routes;\n") + .write("crates/app/src/handlers.rs", APP) + .write( + "crates/app/src/routes.rs", + "mod admin;\nfn r() { Router::new().route(\"/\", get(home)); }\n", + ) + .write( + "crates/app/src/routes/admin.rs", + "fn r() { Router::new().nest(\"/admin\", admin()); }\n", + ) + .write( + "crates/app/examples/demo.rs", + "fn main() { Router::new().route(\"/\", get(home)); }\n", + ) + .write( + "standard.toml", + "route-modules = [\n \"app::routes\",\n \"app::paths\",\n]\n", + ); + let message = |line: usize, what: &str, path: &str| { + format!( + "crates/app/src/handlers.rs:{line}: `{what}` takes the path `{path}` as a literal: \ + name it in a module `route-modules` in standard.toml lists, and use that \ + (route-literals)" + ) + }; + assert_eq!( + fixture.violations(Rule::RouteLiterals), + [ + message(3, ".route", "/settings"), + message(4, ".nest", "/api"), + message(6, "Redirect::to", "/signed-out"), + "standard.toml:3: `app::paths` is in `route-modules`, but no file is that module: \ + remove it (route-literals)" + .to_owned(), + ] + ); +} + +#[test] +fn without_route_modules_paths_are_not_checked() { + let fixture = Fixture::new(); + fixture + .add_crate("app", INHERITS) + .write("crates/app/src/lib.rs", APP); + assert_eq!( + fixture.violations(Rule::RouteLiterals), + Vec::::new() + ); +}