]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/needless_option_take.rs
separate the receiver from arguments in HIR under /clippy
[rust.git] / clippy_lints / src / methods / needless_option_take.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::match_def_path;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use rustc_errors::Applicability;
6 use rustc_hir::Expr;
7 use rustc_lint::LateContext;
8 use rustc_span::sym;
9
10 use super::NEEDLESS_OPTION_TAKE;
11
12 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, recv: &'tcx Expr<'_>) {
13     // Checks if expression type is equal to sym::Option and if the expr is not a syntactic place
14     if !recv.is_syntactic_place_expr() && is_expr_option(cx, recv) && has_expr_as_ref_path(cx, recv) {
15         let mut applicability = Applicability::MachineApplicable;
16         span_lint_and_sugg(
17             cx,
18             NEEDLESS_OPTION_TAKE,
19             expr.span,
20             "called `Option::take()` on a temporary value",
21             "try",
22             format!(
23                 "{}",
24                 snippet_with_applicability(cx, recv.span, "..", &mut applicability)
25             ),
26             applicability,
27         );
28     }
29 }
30
31 fn is_expr_option(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
32     let expr_type = cx.typeck_results().expr_ty(expr);
33     is_type_diagnostic_item(cx, expr_type, sym::Option)
34 }
35
36 fn has_expr_as_ref_path(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
37     if let Some(ref_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
38         return match_def_path(cx, ref_id, &["core", "option", "Option", "as_ref"]);
39     }
40     false
41 }