2 // Unused import checking
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
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.
11 // Checking for unused imports is split into three steps:
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
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
23 // - `check_crate` finally emits the diagnostics based on the data generated
26 use std::ops::{Deref, DerefMut};
29 use crate::resolve_imports::ImportDirectiveSubclass;
31 use rustc::util::nodemap::NodeMap;
32 use rustc::{lint, ty};
33 use rustc_data_structures::fx::FxHashSet;
35 use syntax::visit::{self, Visitor};
36 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
38 struct UnusedImport<'a> {
39 use_tree: &'a ast::UseTree,
40 use_tree_id: ast::NodeId,
42 unused: FxHashSet<ast::NodeId>,
45 impl<'a> UnusedImport<'a> {
46 fn add(&mut self, id: ast::NodeId) {
47 self.unused.insert(id);
51 struct UnusedImportCheckVisitor<'a, 'b> {
52 resolver: &'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>,
60 // Deref and DerefMut impls allow treating UnusedImportCheckVisitor as Resolver.
61 impl<'a, 'b> Deref for UnusedImportCheckVisitor<'a, 'b> {
62 type Target = Resolver<'b>;
64 fn deref<'c>(&'c self) -> &'c Resolver<'b> {
69 impl<'a, 'b> DerefMut for UnusedImportCheckVisitor<'a, 'b> {
70 fn deref_mut<'c>(&'c mut self) -> &'c mut Resolver<'b> {
75 impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> {
76 // We have information about whether `use` (import) directives are actually
77 // used now. If an import is not used at all, we signal a lint error.
78 fn check_import(&mut self, id: ast::NodeId) {
80 self.per_ns(|this, ns| used |= this.used_imports.contains(&(id, ns)));
82 if self.maybe_unused_trait_imports.contains(&id) {
86 self.unused_import(self.base_id).add(id);
88 // This trait import is definitely used, in a way other than
90 self.maybe_unused_trait_imports.remove(&id);
91 if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
97 fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> {
98 let use_tree_id = self.base_id;
99 let use_tree = self.base_use_tree.unwrap();
100 let item_span = self.item_span;
104 .or_insert_with(|| UnusedImport {
108 unused: FxHashSet::default(),
113 impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> {
114 fn visit_item(&mut self, item: &'a ast::Item) {
115 self.item_span = item.span;
117 // Ignore is_public import statements because there's no way to be sure
118 // whether they're used or not. Also ignore imports with a dummy span
119 // because this means that they were generated in some fashion by the
120 // compiler and we don't need to consider them.
121 if let ast::ItemKind::Use(..) = item.node {
122 if item.vis.node.is_pub() || item.span.is_dummy() {
127 visit::walk_item(self, item);
130 fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) {
131 // Use the base UseTree's NodeId as the item id
132 // This allows the grouping of all the lints in the same item
135 self.base_use_tree = Some(use_tree);
138 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
139 if items.is_empty() {
140 self.unused_import(self.base_id).add(id);
143 self.check_import(id);
146 visit::walk_use_tree(self, use_tree, id);
150 enum UnusedSpanResult {
152 FlatUnused(Span, Span),
153 NestedFullUnused(Vec<Span>, Span),
154 NestedPartialUnused(Vec<Span>, Vec<Span>),
157 fn calc_unused_spans(
158 unused_import: &UnusedImport<'_>,
159 use_tree: &ast::UseTree,
160 use_tree_id: ast::NodeId,
161 ) -> UnusedSpanResult {
162 // The full span is the whole item's span if this current tree is not nested inside another
163 // This tells rustfix to remove the whole item if all the imports are unused
164 let full_span = if unused_import.use_tree.span == use_tree.span {
165 unused_import.item_span
169 match use_tree.kind {
170 ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
171 if unused_import.unused.contains(&use_tree_id) {
172 UnusedSpanResult::FlatUnused(use_tree.span, full_span)
174 UnusedSpanResult::Used
177 ast::UseTreeKind::Nested(ref nested) => {
178 if nested.len() == 0 {
179 return UnusedSpanResult::FlatUnused(use_tree.span, full_span);
182 let mut unused_spans = Vec::new();
183 let mut to_remove = Vec::new();
184 let mut all_nested_unused = true;
185 let mut previous_unused = false;
186 for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
187 let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
188 UnusedSpanResult::Used => {
189 all_nested_unused = false;
192 UnusedSpanResult::FlatUnused(span, remove) => {
193 unused_spans.push(span);
196 UnusedSpanResult::NestedFullUnused(mut spans, remove) => {
197 unused_spans.append(&mut spans);
200 UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => {
201 all_nested_unused = false;
202 unused_spans.append(&mut spans);
203 to_remove.append(&mut to_remove_extra);
207 if let Some(remove) = remove {
208 let remove_span = if nested.len() == 1 {
210 } else if pos == nested.len() - 1 || !all_nested_unused {
211 // Delete everything from the end of the last import, to delete the
213 nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
215 // Delete everything until the next import, to delete the trailing commas
216 use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
219 // Try to collapse adjacent spans into a single one. This prevents all cases of
220 // overlapping removals, which are not supported by rustfix
221 if previous_unused && !to_remove.is_empty() {
222 let previous = to_remove.pop().unwrap();
223 to_remove.push(previous.to(remove_span));
225 to_remove.push(remove_span);
228 previous_unused = remove.is_some();
230 if unused_spans.is_empty() {
231 UnusedSpanResult::Used
232 } else if all_nested_unused {
233 UnusedSpanResult::NestedFullUnused(unused_spans, full_span)
235 UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove)
241 pub fn check_crate(resolver: &mut Resolver<'_>, krate: &ast::Crate) {
242 for directive in resolver.potentially_unused_imports.iter() {
243 match directive.subclass {
244 _ if directive.used.get() ||
245 directive.vis.get() == ty::Visibility::Public ||
246 directive.span.is_dummy() => {
247 if let ImportDirectiveSubclass::MacroUse = directive.subclass {
248 if !directive.span.is_dummy() {
249 resolver.session.buffer_lint(
250 lint::builtin::MACRO_USE_EXTERN_CRATE,
253 "deprecated `#[macro_use]` directive used to \
254 import macros should be replaced at use sites \
255 with a `use` statement to import the macro \
261 ImportDirectiveSubclass::ExternCrate { .. } => {
262 resolver.maybe_unused_extern_crates.push((directive.id, directive.span));
264 ImportDirectiveSubclass::MacroUse => {
265 let lint = lint::builtin::UNUSED_IMPORTS;
266 let msg = "unused `#[macro_use]` import";
267 resolver.session.buffer_lint(lint, directive.id, directive.span, msg);
273 for (id, span) in resolver.unused_labels.iter() {
274 resolver.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
277 let mut visitor = UnusedImportCheckVisitor {
279 unused_imports: Default::default(),
281 base_id: ast::DUMMY_NODE_ID,
284 visit::walk_crate(&mut visitor, krate);
286 for unused in visitor.unused_imports.values() {
287 let mut fixes = Vec::new();
288 let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) {
289 UnusedSpanResult::Used => continue,
290 UnusedSpanResult::FlatUnused(span, remove) => {
291 fixes.push((remove, String::new()));
294 UnusedSpanResult::NestedFullUnused(spans, remove) => {
295 fixes.push((remove, String::new()));
298 UnusedSpanResult::NestedPartialUnused(spans, remove) => {
300 fixes.push((*fix, String::new()));
306 let len = spans.len();
308 let ms = MultiSpan::from_spans(spans.clone());
309 let mut span_snippets = spans.iter()
311 match visitor.session.source_map().span_to_snippet(*s) {
312 Ok(s) => Some(format!("`{}`", s)),
315 }).collect::<Vec<String>>();
316 span_snippets.sort();
317 let msg = format!("unused import{}{}",
318 if len > 1 { "s" } else { "" },
319 if !span_snippets.is_empty() {
320 format!(": {}", span_snippets.join(", "))
325 let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span {
326 "remove the whole `use` item"
327 } else if spans.len() > 1 {
328 "remove the unused imports"
330 "remove the unused import"
333 visitor.session.buffer_lint_with_diagnostic(
334 lint::builtin::UNUSED_IMPORTS,
338 lint::builtin::BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes),