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