xtask/tasks/fmt/lints/
unused_deps.rs1use super::Lint;
36use super::LintCtx;
37use super::Lintable;
38use grep_regex::RegexMatcher;
39use std::collections::BTreeMap;
40use std::collections::BTreeSet;
41use toml_edit::DocumentMut;
42
43pub struct UnusedDeps {
44 workspace_deps: BTreeSet<String>,
46 workspace_found_deps: BTreeSet<String>,
48
49 crate_deps: BTreeSet<String>,
51 crate_found_deps: BTreeSet<String>,
53
54 dep_matchers: BTreeMap<String, RegexMatcher>,
58
59 only_diffed: bool,
62
63 searcher: grep_searcher::Searcher,
65}
66
67impl Lint for UnusedDeps {
68 fn new(ctx: &LintCtx) -> Self {
69 UnusedDeps {
70 workspace_deps: BTreeSet::new(),
71 workspace_found_deps: BTreeSet::new(),
72 crate_deps: BTreeSet::new(),
73 crate_found_deps: BTreeSet::new(),
74 dep_matchers: BTreeMap::new(),
75 only_diffed: ctx.only_diffed,
76 searcher: grep_searcher::SearcherBuilder::new()
77 .line_number(false)
78 .build(),
79 }
80 }
81
82 fn enter_workspace(&mut self, content: &Lintable<DocumentMut>) {
83 if let Some(deps) = content
85 .get("workspace")
86 .and_then(|w| w.get("dependencies"))
87 .and_then(|d| d.as_table_like())
88 {
89 for (dep_name, _) in deps.iter() {
91 self.workspace_deps.insert(dep_name.to_string());
92 self.dep_matchers
93 .insert(dep_name.to_string(), compile_matcher(dep_name));
94 }
95 }
96 }
97
98 fn enter_crate(&mut self, content: &Lintable<DocumentMut>) {
99 const DEP_TABLE_NAMES: &[&str] =
100 &["dependencies", "build-dependencies", "dev-dependencies"];
101
102 self.crate_deps.clear();
103 self.crate_found_deps.clear();
104
105 for dep_table in DEP_TABLE_NAMES
106 .iter()
107 .flat_map(|s| content.get(s).map(|d| d.as_table_like().unwrap()))
108 {
109 for (dep_name, _) in dep_table.iter() {
110 self.crate_deps.insert(dep_name.to_string());
111 if !self.dep_matchers.contains_key(dep_name) {
112 self.dep_matchers
113 .insert(dep_name.to_string(), compile_matcher(dep_name));
114 }
115 }
116 }
117
118 if let Some(target) = content.get("target").map(|t| t.as_table_like().unwrap()) {
120 for target_table in target.iter().map(|(_, t)| t.as_table_like().unwrap()) {
121 for dep_table in DEP_TABLE_NAMES
122 .iter()
123 .flat_map(|s| target_table.get(s).map(|d| d.as_table_like().unwrap()))
124 {
125 for (dep_name, _) in dep_table.iter() {
126 self.crate_deps.insert(dep_name.to_string());
127 if !self.dep_matchers.contains_key(dep_name) {
128 self.dep_matchers
129 .insert(dep_name.to_string(), compile_matcher(dep_name));
130 }
131 }
132 }
133 }
134 }
135 }
136
137 fn visit_file(&mut self, content: &mut Lintable<String>) {
138 if self.crate_found_deps.len() == self.crate_deps.len() {
139 return;
140 }
141
142 let unfound = self.crate_deps.difference(&self.crate_found_deps);
143 let mut found = Vec::new();
144 for looking in unfound {
145 let needle = looking.replace('-', "_");
146 if !content.contains(&needle) {
148 continue;
149 }
150 let mut sink = StopAfterFirstMatch::new();
152 self.searcher
153 .search_slice(
154 &self.dep_matchers[&**looking],
155 content.as_bytes(),
156 &mut sink,
157 )
158 .unwrap();
159 if sink.found {
160 found.push(looking.clone());
161 }
162 }
163
164 self.crate_found_deps.extend(found.iter().cloned());
165 self.workspace_found_deps.extend(found);
166 }
167
168 fn exit_crate(&mut self, content: &mut Lintable<DocumentMut>) {
169 self.workspace_found_deps.extend(
171 content
172 .get("package")
173 .and_then(|p| p.get("metadata"))
174 .and_then(|m| m.get("xtask"))
175 .and_then(|x| x.get("unused-deps"))
176 .and_then(|u| u.get("ignored"))
177 .and_then(|i| i.as_array())
178 .into_iter()
179 .flatten()
180 .map(|dep| dep.as_str().unwrap().to_owned())
181 .filter(|dep| self.crate_deps.contains(dep)),
182 );
183 exit_toml(content, &self.crate_deps, &self.crate_found_deps, false);
184 }
185
186 fn exit_workspace(&mut self, content: &mut Lintable<DocumentMut>) {
187 if self.only_diffed {
191 return;
192 }
193
194 exit_toml(
195 content,
196 &self.workspace_deps,
197 &self.workspace_found_deps,
198 true,
199 );
200 }
201}
202
203fn exit_toml(
204 content: &mut Lintable<DocumentMut>,
205 deps: &BTreeSet<String>,
206 found_deps: &BTreeSet<String>,
207 is_workspace: bool,
208) {
209 let top_key = if is_workspace { "workspace" } else { "package" };
210 let ignored: BTreeSet<_> = content
212 .get(top_key)
213 .and_then(|p| p.get("metadata"))
214 .and_then(|m| m.get("xtask"))
215 .and_then(|x| x.get("unused-deps"))
216 .and_then(|u| u.get("ignored"))
217 .and_then(|i| i.as_array())
218 .into_iter()
219 .flatten()
220 .map(|dep| dep.as_str().unwrap().to_owned())
221 .collect();
222
223 for ign in &ignored {
224 if !deps.contains(ign) {
225 let msg = format!("{ign} is ignored, but it's not being depended on");
226 content.fix(&msg, |doc| remove_from_ignored(doc, ign, is_workspace));
227 }
228 }
229
230 for dep in deps {
231 let found = found_deps.contains(&**dep);
232 let ignored = ignored.contains(&**dep);
233
234 match (found, ignored) {
235 (false, false) => {
236 content.fix(&format!("{dep} is unused"), |doc| {
237 remove_from_deps(doc, dep, is_workspace)
238 });
239 }
240 (true, true) => {
241 content.fix(&format!("{dep} is ignored, but being used"), |doc| {
242 remove_from_ignored(doc, dep, is_workspace)
243 });
244 }
245 _ => {}
246 }
247 }
248}
249
250fn compile_matcher(dep: &str) -> RegexMatcher {
251 let name = dep.replace('-', "_");
252 let regex =
265 format!(r#"use (::)?{name}(::|;| as)|(?:[^:]|^|\W::)\b{name}::|extern crate {name}( |;)"#);
266 RegexMatcher::new_line_matcher(®ex).unwrap()
267}
268
269fn remove_from_deps(doc: &mut DocumentMut, dep_name: &str, is_workspace: bool) {
271 const DEP_TABLE_NAMES: &[&str] = &["dependencies", "build-dependencies", "dev-dependencies"];
272
273 if is_workspace {
274 let deps = doc["workspace"]["dependencies"]
276 .as_table_like_mut()
277 .unwrap();
278 deps.remove(dep_name);
279 } else {
280 for table_name in DEP_TABLE_NAMES {
282 if let Some(deps) = doc.get_mut(table_name).and_then(|d| d.as_table_like_mut()) {
283 deps.remove(dep_name);
284 }
285 }
286
287 if let Some(target) = doc.get_mut("target").and_then(|t| t.as_table_like_mut()) {
289 let keys: Vec<String> = target.iter().map(|(k, _)| k.to_string()).collect();
290 for key in keys {
291 if let Some(target_table) = target.get_mut(&key).and_then(|t| t.as_table_like_mut())
292 {
293 for table_name in DEP_TABLE_NAMES {
294 if let Some(deps) = target_table
295 .get_mut(table_name)
296 .and_then(|d| d.as_table_like_mut())
297 {
298 deps.remove(dep_name);
299 }
300 }
301 }
302 }
303 }
304
305 if let Some(features) = doc.get_mut("features").and_then(|f| f.as_table_like_mut()) {
307 let dep_enable = format!("dep:{dep_name}");
308 let dep_feature_prefix = format!("{dep_name}/");
309 let feature_keys: Vec<String> = features.iter().map(|(k, _)| k.to_string()).collect();
310 for feature_key in feature_keys {
311 if let Some(arr) = features
312 .get_mut(&feature_key)
313 .and_then(|v| v.as_array_mut())
314 {
315 arr.retain(|v| {
316 if let Some(s) = v.as_str() {
317 s != dep_enable && !s.starts_with(&dep_feature_prefix)
318 } else {
319 true
320 }
321 });
322 }
323 }
324 }
325 }
326}
327
328fn remove_from_ignored(doc: &mut DocumentMut, dep_name: &str, is_workspace: bool) {
330 let top_key = if is_workspace { "workspace" } else { "package" };
331 let ignored_array = doc[top_key]["metadata"]["xtask"]["unused-deps"]["ignored"]
332 .as_array_mut()
333 .unwrap();
334 ignored_array.retain(|v| v.as_str() != Some(dep_name));
335}
336
337struct StopAfterFirstMatch {
338 found: bool,
339}
340
341impl StopAfterFirstMatch {
342 fn new() -> Self {
343 Self { found: false }
344 }
345}
346
347impl grep_searcher::Sink for StopAfterFirstMatch {
348 type Error = Box<dyn std::error::Error>;
349
350 fn matched(
351 &mut self,
352 _searcher: &grep_searcher::Searcher,
353 mat: &grep_searcher::SinkMatch<'_>,
354 ) -> Result<bool, Self::Error> {
355 let mat = mat.bytes().trim_ascii();
356
357 if mat.starts_with(b"//")
358 && !(mat.starts_with(b"/// # use")
359 || mat.starts_with(b"/// use")
360 || mat.starts_with(b"//! # use")
361 || mat.starts_with(b"//! use"))
362 {
363 return Ok(true);
370 }
371
372 self.found = true;
375 Ok(false)
376 }
377}