|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use rustc_hir::{def::Res, Item, ItemKind}; |
| 3 | +use rustc_lint::{LateContext, LateLintPass, Lint}; |
| 4 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 5 | +use rustc_span::{sym, Symbol}; |
| 6 | + |
| 7 | +declare_clippy_lint! { |
| 8 | + /// ### What it does |
| 9 | + /// |
| 10 | + /// ### Why is this bad? |
| 11 | + /// |
| 12 | + /// ### Example |
| 13 | + /// ```rust |
| 14 | + /// // example code where clippy issues a warning |
| 15 | + /// ``` |
| 16 | + /// Use instead: |
| 17 | + /// ```rust |
| 18 | + /// // example code which does not raise clippy warning |
| 19 | + /// ``` |
| 20 | + #[clippy::version = "1.64.0"] |
| 21 | + pub STD_INSTEAD_OF_CORE, |
| 22 | + nursery, |
| 23 | + "default lint description" |
| 24 | +} |
| 25 | +// TODO: Make multi pass: see DropForgetRef |
| 26 | +declare_lint_pass!(StdReexports => [STD_INSTEAD_OF_CORE]); |
| 27 | + |
| 28 | +impl<'tcx> LateLintPass<'tcx> for StdReexports { |
| 29 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &Item<'tcx>) { |
| 30 | + // std_instead_of_core |
| 31 | + run_lint(cx, item, sym::core, sym::std, STD_INSTEAD_OF_CORE); |
| 32 | + // std_instead_of_alloc |
| 33 | + run_lint(cx, item, sym::alloc, sym::std, STD_INSTEAD_OF_CORE); |
| 34 | + // alloc_instead_of_core |
| 35 | + run_lint(cx, item, sym::core, sym::alloc, STD_INSTEAD_OF_CORE); |
| 36 | + } |
| 37 | + |
| 38 | + // TODO: Fully qualified items |
| 39 | + // - `std::vec::Vec::<u32>::new()` |
| 40 | +} |
| 41 | + |
| 42 | +fn run_lint( |
| 43 | + cx: &LateContext<'_>, |
| 44 | + item: &Item<'_>, |
| 45 | + item_crate_name: Symbol, |
| 46 | + use_crate_segment_name: Symbol, |
| 47 | + lint: &'static Lint, |
| 48 | +) { |
| 49 | + if_chain! { |
| 50 | + if let ItemKind::Use(path, _) = item.kind; |
| 51 | + if let Res::Def(_, def_id) = path.res; |
| 52 | + // check if the resolved path is in the crate |
| 53 | + if item_crate_name == cx.tcx.crate_name(def_id.krate); |
| 54 | + |
| 55 | + // check if the first segment of the path is from std or |
| 56 | + if let Some(path_root_segment) = path.segments.first(); |
| 57 | + |
| 58 | + // and check that the first segment of the import refers crate we lint for. |
| 59 | + if use_crate_segment_name == path_root_segment.ident.name; |
| 60 | + |
| 61 | + then { |
| 62 | + span_lint_and_help( |
| 63 | + cx, |
| 64 | + lint, |
| 65 | + path.span, |
| 66 | + &format!("used `{}` import instead of `{}`", use_crate_segment_name, item_crate_name), |
| 67 | + None, |
| 68 | + &format!("consider importing from `{}`", item_crate_name), |
| 69 | + ); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments