]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ref_option_ref.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[rust.git] / clippy_lints / src / ref_option_ref.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::last_path_segment;
3 use clippy_utils::source::snippet;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{GenericArg, Mutability, Ty, TyKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::symbol::sym;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for usage of `&Option<&T>`.
13     ///
14     /// **Why is this bad?** Since `&` is Copy, it's useless to have a
15     /// reference on `Option<&T>`.
16     ///
17     /// **Known problems:** It may be irrelevant to use this lint on
18     /// public API code as it will make a breaking change to apply it.
19     ///
20     /// **Example:**
21     ///
22     /// ```rust,ignore
23     /// let x: &Option<&u32> = &Some(&0u32);
24     /// ```
25     /// Use instead:
26     /// ```rust,ignore
27     /// let x: Option<&u32> = Some(&0u32);
28     /// ```
29     pub REF_OPTION_REF,
30     pedantic,
31     "use `Option<&T>` instead of `&Option<&T>`"
32 }
33
34 declare_lint_pass!(RefOptionRef => [REF_OPTION_REF]);
35
36 impl<'tcx> LateLintPass<'tcx> for RefOptionRef {
37     fn check_ty(&mut self, cx: &LateContext<'tcx>, ty: &'tcx Ty<'tcx>) {
38         if_chain! {
39             if let TyKind::Rptr(_, ref mut_ty) = ty.kind;
40             if mut_ty.mutbl == Mutability::Not;
41             if let TyKind::Path(ref qpath) = &mut_ty.ty.kind;
42             let last = last_path_segment(qpath);
43             if let Some(res) = last.res;
44             if let Some(def_id) = res.opt_def_id();
45
46             if cx.tcx.is_diagnostic_item(sym::option_type, def_id);
47             if let Some(ref params) = last_path_segment(qpath).args ;
48             if !params.parenthesized;
49             if let Some(inner_ty) = params.args.iter().find_map(|arg| match arg {
50                 GenericArg::Type(inner_ty) => Some(inner_ty),
51                 _ => None,
52             });
53             if let TyKind::Rptr(_, _) = inner_ty.kind;
54
55             then {
56                 span_lint_and_sugg(
57                     cx,
58                     REF_OPTION_REF,
59                     ty.span,
60                     "since `&` implements the `Copy` trait, `&Option<&T>` can be simplified to `Option<&T>`",
61                     "try",
62                     format!("Option<{}>", &snippet(cx, inner_ty.span, "..")),
63                     Applicability::MaybeIncorrect,
64                 );
65             }
66         }
67     }
68 }