rustc_lint/
unqualified_local_imports.rs

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