stern4rust/
unit_test_finder.rs1use proc_macro2::TokenTree;
6use quote::ToTokens;
7use syn::Attribute;
8use syn::Item;
9use syn::spanned::Spanned;
10
11use crate::source_file::SourceFile;
12use crate::unit_test_site::UnitTestSite;
13
14pub struct UnitTestFinder;
27
28impl UnitTestFinder {
29 pub fn sites(file: &SourceFile) -> Option<Vec<UnitTestSite>> {
31 let syntax = syn::parse_file(&file.contents()).ok()?;
32 Some(Self::in_items(file, &syntax.items))
33 }
34
35 fn in_items(file: &SourceFile, items: &[Item]) -> Vec<UnitTestSite> {
40 let mut sites = Vec::new();
41 for item in items {
42 if let Some(site) = Self::site_of(file, item) {
43 sites.push(site);
44 continue;
45 }
46 if let Item::Mod(module) = item {
47 if let Some((_, inner)) = &module.content {
48 sites.extend(Self::in_items(file, inner));
49 }
50 }
51 }
52 sites
53 }
54
55 fn site_of(file: &SourceFile, item: &Item) -> Option<UnitTestSite> {
56 let line = item.span().start().line.max(1);
57 let attrs = Self::attributes(item);
58 let subject = Self::describe(file, item, line);
59 let mirror = Self::mirror_of(file.relative_path());
60
61 if attrs.iter().any(Self::is_cfg_attr_test) {
62 return Some(UnitTestSite::new(
63 line,
64 &format!("the `#[cfg_attr(test, ...)]` on the {subject}"),
65 &format!(
66 "apply the attribute unconditionally, or move what it guards into {mirror}"
67 ),
68 ));
69 }
70 if attrs.iter().any(Self::is_cfg_test) {
71 return Some(UnitTestSite::new(
72 line,
73 &format!("the `#[cfg(test)]` {subject}"),
74 &format!("move the tests to {mirror} and delete this from the source tree"),
75 ));
76 }
77 if attrs.iter().any(Self::is_test) {
78 return Some(UnitTestSite::new(
79 line,
80 &format!("the test {subject}"),
81 &format!("move the tests to {mirror} and delete this from the source tree"),
82 ));
83 }
84 None
85 }
86
87 fn is_cfg_attr_test(attr: &Attribute) -> bool {
92 attr.path().is_ident("cfg_attr") && Self::mentions_test(attr)
93 }
94
95 fn is_cfg_test(attr: &Attribute) -> bool {
98 attr.path().is_ident("cfg") && Self::mentions_test(attr)
99 }
100
101 fn is_test(attr: &Attribute) -> bool {
103 attr.path()
104 .segments
105 .last()
106 .is_some_and(|segment| segment.ident == "test")
107 }
108
109 fn mentions_test(attr: &Attribute) -> bool {
113 Self::has_test_ident(attr.meta.to_token_stream())
114 }
115
116 fn has_test_ident(stream: proc_macro2::TokenStream) -> bool {
117 stream.into_iter().any(|tree| match tree {
118 TokenTree::Ident(ident) => ident == "test",
119 TokenTree::Group(group) => Self::has_test_ident(group.stream()),
120 _ => false,
121 })
122 }
123
124 fn mirror_of(relative_path: &str) -> String {
128 let without_root = relative_path.strip_prefix("src/").unwrap_or(relative_path);
129 let stem = without_root.strip_suffix(".rs").unwrap_or(without_root);
130 format!("tests/{stem}_tests.rs")
131 }
132
133 fn describe(file: &SourceFile, item: &Item, line: usize) -> String {
134 match item {
135 Item::Const(inner) => format!("constant `{}`", inner.ident),
136 Item::Enum(inner) => format!("enum `{}`", inner.ident),
137 Item::Fn(inner) => format!("function `{}`", inner.sig.ident),
138 Item::Mod(inner) => format!("module `{}`", inner.ident),
139 Item::Static(inner) => format!("static `{}`", inner.ident),
140 Item::Struct(inner) => format!("struct `{}`", inner.ident),
141 Item::Trait(inner) => format!("trait `{}`", inner.ident),
142 Item::Type(inner) => format!("type alias `{}`", inner.ident),
143 _ => format!("`{}`", Self::source_line(file, line)),
144 }
145 }
146
147 fn source_line(file: &SourceFile, line: usize) -> String {
148 file.lines()
149 .get(line.saturating_sub(1))
150 .map_or_else(String::new, |text| text.trim().to_string())
151 }
152
153 fn attributes(item: &Item) -> &[Attribute] {
154 match item {
155 Item::Const(inner) => &inner.attrs,
156 Item::Enum(inner) => &inner.attrs,
157 Item::ExternCrate(inner) => &inner.attrs,
158 Item::Fn(inner) => &inner.attrs,
159 Item::ForeignMod(inner) => &inner.attrs,
160 Item::Impl(inner) => &inner.attrs,
161 Item::Macro(inner) => &inner.attrs,
162 Item::Mod(inner) => &inner.attrs,
163 Item::Static(inner) => &inner.attrs,
164 Item::Struct(inner) => &inner.attrs,
165 Item::Trait(inner) => &inner.attrs,
166 Item::TraitAlias(inner) => &inner.attrs,
167 Item::Type(inner) => &inner.attrs,
168 Item::Union(inner) => &inner.attrs,
169 Item::Use(inner) => &inner.attrs,
170 _ => &[],
171 }
172 }
173}