rustc_lint/
unqualified_local_imports.rs

1use rustc_hir::{self as hir};
2use rustc_session::{declare_lint, declare_lint_pass};
3use rustc_span::kw;
4
5use crate::{LateContext, LateLintPass, LintContext, lints};
6
7declare_lint! {
8    /// The `unqualified_local_imports` lint checks for `use` items that import a local item using a
9    /// path that does not start with `self::`, `super::`, or `crate::`.
10    ///
11    /// ### Example
12    ///
13    /// ```rust,edition2018
14    /// #![feature(unqualified_local_imports)]
15    /// #![warn(unqualified_local_imports)]
16    ///
17    /// mod localmod {
18    ///     pub struct S;
19    /// }
20    ///
21    /// use localmod::S;
22    /// # // We have to actually use `S`, or else the `unused` warnings suppress the lint we care about.
23    /// # pub fn main() {
24    /// #     let _x = S;
25    /// # }
26    /// ```
27    ///
28    /// {{produces}}
29    ///
30    /// ### Explanation
31    ///
32    /// This lint is meant to be used with the (unstable) rustfmt setting `group_imports = "StdExternalCrate"`.
33    /// That setting makes rustfmt group `self::`, `super::`, and `crate::` imports separately from those
34    /// referring to other crates. However, rustfmt cannot know whether `use c::S;` refers to a local module `c`
35    /// or an external crate `c`, so it always gets categorized as an import from another crate.
36    /// To ensure consistent grouping of imports from the local crate, all local imports must
37    /// start with `self::`, `super::`, or `crate::`. This lint can be used to enforce that style.
38    pub UNQUALIFIED_LOCAL_IMPORTS,
39    Allow,
40    "`use` of a local item without leading `self::`, `super::`, or `crate::`",
41    @feature_gate = unqualified_local_imports;
42}
43
44declare_lint_pass!(UnqualifiedLocalImports => [UNQUALIFIED_LOCAL_IMPORTS]);
45
46impl<'tcx> LateLintPass<'tcx> for UnqualifiedLocalImports {
47    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
48        let hir::ItemKind::Use(path, _kind) = item.kind else { return };
49        // Check the type and value namespace resolutions for a local crate.
50        let is_local_import = matches!(
51            path.res.type_ns,
52            Some(hir::def::Res::Def(_, def_id)) if def_id.is_local()
53        ) || matches!(
54            path.res.value_ns,
55            Some(hir::def::Res::Def(_, def_id)) if def_id.is_local()
56        );
57        if !is_local_import {
58            return;
59        }
60        // So this does refer to something local. Let's check whether it starts with `self`,
61        // `super`, or `crate`. If the path is empty, that means we have a `use *`, which is
62        // equivalent to `use crate::*` so we don't fire the lint in that case.
63        let Some(first_seg) = path.segments.first() else { return };
64        if matches!(first_seg.ident.name, kw::SelfLower | kw::Super | kw::Crate) {
65            return;
66        }
67
68        let encl_item_id = cx.tcx.hir_get_parent_item(item.hir_id());
69        let encl_item = cx.tcx.hir_node_by_def_id(encl_item_id.def_id);
70        if encl_item.fn_kind().is_some() {
71            // `use` in a method -- don't lint, that leads to too many undesirable lints
72            // when a function imports all variants of an enum.
73            return;
74        }
75
76        // This `use` qualifies for our lint!
77        cx.emit_span_lint(
78            UNQUALIFIED_LOCAL_IMPORTS,
79            first_seg.ident.span,
80            lints::UnqualifiedLocalImportsDiag {},
81        );
82    }
83}