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