]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/needless_option_as_deref.rs
Rollup merge of #92802 - compiler-errors:deduplicate-stack-trace, r=oli-obk
[rust.git] / src / tools / clippy / clippy_lints / src / needless_option_as_deref.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::symbol::sym;
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for no-op uses of Option::{as_deref,as_deref_mut},
13     /// for example, `Option<&T>::as_deref()` returns the same type.
14     ///
15     /// ### Why is this bad?
16     /// Redundant code and improving readability.
17     ///
18     /// ### Example
19     /// ```rust
20     /// let a = Some(&1);
21     /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
22     /// ```
23     /// Could be written as:
24     /// ```rust
25     /// let a = Some(&1);
26     /// let b = a;
27     /// ```
28     #[clippy::version = "1.57.0"]
29     pub NEEDLESS_OPTION_AS_DEREF,
30     complexity,
31     "no-op use of `deref` or `deref_mut` method to `Option`."
32 }
33
34 declare_lint_pass!(OptionNeedlessDeref=> [
35     NEEDLESS_OPTION_AS_DEREF,
36 ]);
37
38 impl<'tcx> LateLintPass<'tcx> for OptionNeedlessDeref {
39     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
40         if expr.span.from_expansion() {
41             return;
42         }
43         let typeck = cx.typeck_results();
44         let outer_ty = typeck.expr_ty(expr);
45
46         if_chain! {
47             if is_type_diagnostic_item(cx,outer_ty,sym::Option);
48             if let ExprKind::MethodCall(path, [sub_expr], _) = expr.kind;
49             let symbol = path.ident.as_str();
50             if symbol == "as_deref" || symbol == "as_deref_mut";
51             if outer_ty == typeck.expr_ty(sub_expr);
52             then{
53                 span_lint_and_sugg(
54                     cx,
55                     NEEDLESS_OPTION_AS_DEREF,
56                     expr.span,
57                     "derefed type is same as origin",
58                     "try this",
59                     snippet_opt(cx,sub_expr.span).unwrap(),
60                     Applicability::MachineApplicable
61                 );
62             }
63         }
64     }
65 }