]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ref_option_ref.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / ref_option_ref.rs
1 use crate::utils::{last_path_segment, 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:** It may be irrevelent to use this lint on
16     /// public API code as it will make a breaking change to apply it.
17     ///
18     /// **Example:**
19     ///
20     /// ```rust,ignore
21     /// let x: &Option<&u32> = &Some(&0u32);
22     /// ```
23     /// Use instead:
24     /// ```rust,ignore
25     /// let x: Option<&u32> = Some(&0u32);
26     /// ```
27     pub REF_OPTION_REF,
28     pedantic,
29     "use `Option<&T>` instead of `&Option<&T>`"
30 }
31
32 declare_lint_pass!(RefOptionRef => [REF_OPTION_REF]);
33
34 impl<'tcx> LateLintPass<'tcx> for RefOptionRef {
35     fn check_ty(&mut self, cx: &LateContext<'tcx>, ty: &'tcx Ty<'tcx>) {
36         if_chain! {
37             if let TyKind::Rptr(_, ref mut_ty) = ty.kind;
38             if mut_ty.mutbl == Mutability::Not;
39             if let TyKind::Path(ref qpath) = &mut_ty.ty.kind;
40             let last = last_path_segment(qpath);
41             if let Some(res) = last.res;
42             if let Some(def_id) = res.opt_def_id();
43
44             if cx.tcx.is_diagnostic_item(sym!(option_type), def_id);
45             if let Some(ref params) = last_path_segment(qpath).args ;
46             if !params.parenthesized;
47             if let Some(inner_ty) = params.args.iter().find_map(|arg| match arg {
48                 GenericArg::Type(inner_ty) => Some(inner_ty),
49                 _ => None,
50             });
51             if let TyKind::Rptr(_, _) = inner_ty.kind;
52
53             then {
54                 span_lint_and_sugg(
55                     cx,
56                     REF_OPTION_REF,
57                     ty.span,
58                     "since `&` implements the `Copy` trait, `&Option<&T>` can be simplified to `Option<&T>`",
59                     "try",
60                     format!("Option<{}>", &snippet(cx, inner_ty.span, "..")),
61                     Applicability::MaybeIncorrect,
62                 );
63             }
64         }
65     }
66 }