]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/check_unused.rs
Auto merge of #67732 - pietroalbini:fewer-apples, r=alexcrichton
[rust.git] / src / librustc_resolve / check_unused.rs
1 //
2 // Unused import checking
3 //
4 // Although this is mostly a lint pass, it lives in here because it depends on
5 // resolve data structures and because it finalises the privacy information for
6 // `use` directives.
7 //
8 // Unused trait imports can't be checked until the method resolution. We save
9 // candidates here, and do the actual check in librustc_typeck/check_unused.rs.
10 //
11 // Checking for unused imports is split into three steps:
12 //
13 //  - `UnusedImportCheckVisitor` walks the AST to find all the unused imports
14 //    inside of `UseTree`s, recording their `NodeId`s and grouping them by
15 //    the parent `use` item
16 //
17 //  - `calc_unused_spans` then walks over all the `use` items marked in the
18 //    previous step to collect the spans associated with the `NodeId`s and to
19 //    calculate the spans that can be removed by rustfix; This is done in a
20 //    separate step to be able to collapse the adjacent spans that rustfix
21 //    will remove
22 //
23 //  - `check_crate` finally emits the diagnostics based on the data generated
24 //    in the last step
25
26 use crate::imports::ImportDirectiveSubclass;
27 use crate::Resolver;
28
29 use errors::pluralize;
30 use rustc::{lint, ty};
31 use rustc_data_structures::fx::FxHashSet;
32 use rustc_session::node_id::NodeMap;
33 use rustc_span::{MultiSpan, Span, DUMMY_SP};
34 use syntax::ast;
35 use syntax::visit::{self, Visitor};
36
37 struct UnusedImport<'a> {
38     use_tree: &'a ast::UseTree,
39     use_tree_id: ast::NodeId,
40     item_span: Span,
41     unused: FxHashSet<ast::NodeId>,
42 }
43
44 impl<'a> UnusedImport<'a> {
45     fn add(&mut self, id: ast::NodeId) {
46         self.unused.insert(id);
47     }
48 }
49
50 struct UnusedImportCheckVisitor<'a, 'b> {
51     r: &'a mut Resolver<'b>,
52     /// All the (so far) unused imports, grouped path list
53     unused_imports: NodeMap<UnusedImport<'a>>,
54     base_use_tree: Option<&'a ast::UseTree>,
55     base_id: ast::NodeId,
56     item_span: Span,
57 }
58
59 impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> {
60     // We have information about whether `use` (import) directives are actually
61     // used now. If an import is not used at all, we signal a lint error.
62     fn check_import(&mut self, id: ast::NodeId) {
63         let mut used = false;
64         self.r.per_ns(|this, ns| used |= this.used_imports.contains(&(id, ns)));
65         if !used {
66             if self.r.maybe_unused_trait_imports.contains(&id) {
67                 // Check later.
68                 return;
69             }
70             self.unused_import(self.base_id).add(id);
71         } else {
72             // This trait import is definitely used, in a way other than
73             // method resolution.
74             self.r.maybe_unused_trait_imports.remove(&id);
75             if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
76                 i.unused.remove(&id);
77             }
78         }
79     }
80
81     fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> {
82         let use_tree_id = self.base_id;
83         let use_tree = self.base_use_tree.unwrap();
84         let item_span = self.item_span;
85
86         self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
87             use_tree,
88             use_tree_id,
89             item_span,
90             unused: FxHashSet::default(),
91         })
92     }
93 }
94
95 impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> {
96     fn visit_item(&mut self, item: &'a ast::Item) {
97         self.item_span = item.span;
98
99         // Ignore is_public import statements because there's no way to be sure
100         // whether they're used or not. Also ignore imports with a dummy span
101         // because this means that they were generated in some fashion by the
102         // compiler and we don't need to consider them.
103         if let ast::ItemKind::Use(..) = item.kind {
104             if item.vis.node.is_pub() || item.span.is_dummy() {
105                 return;
106             }
107         }
108
109         visit::walk_item(self, item);
110     }
111
112     fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) {
113         // Use the base UseTree's NodeId as the item id
114         // This allows the grouping of all the lints in the same item
115         if !nested {
116             self.base_id = id;
117             self.base_use_tree = Some(use_tree);
118         }
119
120         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
121             if items.is_empty() {
122                 self.unused_import(self.base_id).add(id);
123             }
124         } else {
125             self.check_import(id);
126         }
127
128         visit::walk_use_tree(self, use_tree, id);
129     }
130 }
131
132 enum UnusedSpanResult {
133     Used,
134     FlatUnused(Span, Span),
135     NestedFullUnused(Vec<Span>, Span),
136     NestedPartialUnused(Vec<Span>, Vec<Span>),
137 }
138
139 fn calc_unused_spans(
140     unused_import: &UnusedImport<'_>,
141     use_tree: &ast::UseTree,
142     use_tree_id: ast::NodeId,
143 ) -> UnusedSpanResult {
144     // The full span is the whole item's span if this current tree is not nested inside another
145     // This tells rustfix to remove the whole item if all the imports are unused
146     let full_span = if unused_import.use_tree.span == use_tree.span {
147         unused_import.item_span
148     } else {
149         use_tree.span
150     };
151     match use_tree.kind {
152         ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
153             if unused_import.unused.contains(&use_tree_id) {
154                 UnusedSpanResult::FlatUnused(use_tree.span, full_span)
155             } else {
156                 UnusedSpanResult::Used
157             }
158         }
159         ast::UseTreeKind::Nested(ref nested) => {
160             if nested.len() == 0 {
161                 return UnusedSpanResult::FlatUnused(use_tree.span, full_span);
162             }
163
164             let mut unused_spans = Vec::new();
165             let mut to_remove = Vec::new();
166             let mut all_nested_unused = true;
167             let mut previous_unused = false;
168             for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
169                 let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
170                     UnusedSpanResult::Used => {
171                         all_nested_unused = false;
172                         None
173                     }
174                     UnusedSpanResult::FlatUnused(span, remove) => {
175                         unused_spans.push(span);
176                         Some(remove)
177                     }
178                     UnusedSpanResult::NestedFullUnused(mut spans, remove) => {
179                         unused_spans.append(&mut spans);
180                         Some(remove)
181                     }
182                     UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => {
183                         all_nested_unused = false;
184                         unused_spans.append(&mut spans);
185                         to_remove.append(&mut to_remove_extra);
186                         None
187                     }
188                 };
189                 if let Some(remove) = remove {
190                     let remove_span = if nested.len() == 1 {
191                         remove
192                     } else if pos == nested.len() - 1 || !all_nested_unused {
193                         // Delete everything from the end of the last import, to delete the
194                         // previous comma
195                         nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
196                     } else {
197                         // Delete everything until the next import, to delete the trailing commas
198                         use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
199                     };
200
201                     // Try to collapse adjacent spans into a single one. This prevents all cases of
202                     // overlapping removals, which are not supported by rustfix
203                     if previous_unused && !to_remove.is_empty() {
204                         let previous = to_remove.pop().unwrap();
205                         to_remove.push(previous.to(remove_span));
206                     } else {
207                         to_remove.push(remove_span);
208                     }
209                 }
210                 previous_unused = remove.is_some();
211             }
212             if unused_spans.is_empty() {
213                 UnusedSpanResult::Used
214             } else if all_nested_unused {
215                 UnusedSpanResult::NestedFullUnused(unused_spans, full_span)
216             } else {
217                 UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove)
218             }
219         }
220     }
221 }
222
223 impl Resolver<'_> {
224     crate fn check_unused(&mut self, krate: &ast::Crate) {
225         for directive in self.potentially_unused_imports.iter() {
226             match directive.subclass {
227                 _ if directive.used.get()
228                     || directive.vis.get() == ty::Visibility::Public
229                     || directive.span.is_dummy() =>
230                 {
231                     if let ImportDirectiveSubclass::MacroUse = directive.subclass {
232                         if !directive.span.is_dummy() {
233                             self.lint_buffer.buffer_lint(
234                                 lint::builtin::MACRO_USE_EXTERN_CRATE,
235                                 directive.id,
236                                 directive.span,
237                                 "deprecated `#[macro_use]` directive used to \
238                                 import macros should be replaced at use sites \
239                                 with a `use` statement to import the macro \
240                                 instead",
241                             );
242                         }
243                     }
244                 }
245                 ImportDirectiveSubclass::ExternCrate { .. } => {
246                     self.maybe_unused_extern_crates.push((directive.id, directive.span));
247                 }
248                 ImportDirectiveSubclass::MacroUse => {
249                     let lint = lint::builtin::UNUSED_IMPORTS;
250                     let msg = "unused `#[macro_use]` import";
251                     self.lint_buffer.buffer_lint(lint, directive.id, directive.span, msg);
252                 }
253                 _ => {}
254             }
255         }
256
257         let mut visitor = UnusedImportCheckVisitor {
258             r: self,
259             unused_imports: Default::default(),
260             base_use_tree: None,
261             base_id: ast::DUMMY_NODE_ID,
262             item_span: DUMMY_SP,
263         };
264         visit::walk_crate(&mut visitor, krate);
265
266         for unused in visitor.unused_imports.values() {
267             let mut fixes = Vec::new();
268             let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) {
269                 UnusedSpanResult::Used => continue,
270                 UnusedSpanResult::FlatUnused(span, remove) => {
271                     fixes.push((remove, String::new()));
272                     vec![span]
273                 }
274                 UnusedSpanResult::NestedFullUnused(spans, remove) => {
275                     fixes.push((remove, String::new()));
276                     spans
277                 }
278                 UnusedSpanResult::NestedPartialUnused(spans, remove) => {
279                     for fix in &remove {
280                         fixes.push((*fix, String::new()));
281                     }
282                     spans
283                 }
284             };
285
286             let len = spans.len();
287             spans.sort();
288             let ms = MultiSpan::from_spans(spans.clone());
289             let mut span_snippets = spans
290                 .iter()
291                 .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) {
292                     Ok(s) => Some(format!("`{}`", s)),
293                     _ => None,
294                 })
295                 .collect::<Vec<String>>();
296             span_snippets.sort();
297             let msg = format!(
298                 "unused import{}{}",
299                 pluralize!(len),
300                 if !span_snippets.is_empty() {
301                     format!(": {}", span_snippets.join(", "))
302                 } else {
303                     String::new()
304                 }
305             );
306
307             let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span {
308                 "remove the whole `use` item"
309             } else if spans.len() > 1 {
310                 "remove the unused imports"
311             } else {
312                 "remove the unused import"
313             };
314
315             visitor.r.lint_buffer.buffer_lint_with_diagnostic(
316                 lint::builtin::UNUSED_IMPORTS,
317                 unused.use_tree_id,
318                 ms,
319                 &msg,
320                 lint::builtin::BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes),
321             );
322         }
323     }
324 }