1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::eager_or_lazy::switch_to_lazy_eval;
3 use clippy_utils::source::{snippet, snippet_with_macro_callsite};
4 use clippy_utils::ty::{implements_trait, match_type};
5 use clippy_utils::{contains_return, is_trait_item, last_path_segment, paths};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
9 use rustc_lint::LateContext;
10 use rustc_span::source_map::Span;
11 use rustc_span::symbol::{kw, sym};
14 use super::OR_FUN_CALL;
16 /// Checks for the `OR_FUN_CALL` lint.
17 #[allow(clippy::too_many_lines)]
18 pub(super) fn check<'tcx>(
19 cx: &LateContext<'tcx>,
23 receiver: &'tcx hir::Expr<'_>,
24 args: &'tcx [hir::Expr<'_>],
26 /// Checks for `unwrap_or(T::new())`, `unwrap_or(T::default())`,
27 /// `or_insert(T::new())` or `or_insert(T::default())`.
28 #[allow(clippy::too_many_arguments)]
29 fn check_unwrap_or_default(
38 let is_default_default = || is_trait_item(cx, fun, sym::Default);
40 let implements_default = |arg, default_trait_id| {
41 let arg_ty = cx.typeck_results().expr_ty(arg);
42 implements_trait(cx, arg_ty, default_trait_id, &[])
47 if let Some(sugg) = match name {
48 "unwrap_or" => Some("unwrap_or_default"),
49 "or_insert" => Some("or_default"),
52 if let hir::ExprKind::Path(ref qpath) = fun.kind;
53 if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
54 let path = last_path_segment(qpath).ident.name;
55 // needs to target Default::default in particular or be *::new and have a Default impl
57 if (matches!(path, kw::Default) && is_default_default())
58 || (matches!(path, sym::new) && implements_default(arg, default_trait_id));
64 method_span.with_hi(span.hi()),
65 &format!("use of `{name}` followed by a call to `{path}`"),
68 Applicability::MachineApplicable,
78 /// Checks for `*or(foo())`.
79 #[allow(clippy::too_many_arguments)]
80 fn check_general_case<'tcx>(
81 cx: &LateContext<'tcx>,
84 self_expr: &hir::Expr<'_>,
85 arg: &'tcx hir::Expr<'_>,
87 // None if lambda is required
88 fun_span: Option<Span>,
90 // (path, fn_has_argument, methods, suffix)
91 const KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
92 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
93 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
94 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
95 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
99 if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
101 if switch_to_lazy_eval(cx, arg);
102 if !contains_return(arg);
104 let self_ty = cx.typeck_results().expr_ty(self_expr);
106 if let Some(&(_, fn_has_arguments, poss, suffix)) =
107 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
109 if poss.contains(&name);
112 let macro_expanded_snipped;
113 let sugg: Cow<'_, str> = {
114 let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
115 (false, Some(fun_span)) => (fun_span, false),
116 _ => (arg.span, true),
119 let not_macro_argument_snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
120 if not_macro_argument_snippet == "vec![]" {
121 macro_expanded_snipped = snippet(cx, snippet_span, "..");
122 match macro_expanded_snipped.strip_prefix("$crate::vec::") {
123 Some(stripped) => Cow::from(stripped),
124 None => macro_expanded_snipped
128 not_macro_argument_snippet
133 let l_arg = if fn_has_arguments { "_" } else { "" };
134 format!("|{l_arg}| {snippet}").into()
139 let span_replace_word = method_span.with_hi(span.hi());
144 &format!("use of `{name}` followed by a function call"),
146 format!("{name}_{suffix}({sugg})"),
147 Applicability::HasPlaceholders,
153 if let [arg] = args {
154 let inner_arg = if let hir::ExprKind::Block(
167 match inner_arg.kind {
168 hir::ExprKind::Call(fun, or_args) => {
169 let or_has_args = !or_args.is_empty();
170 if !check_unwrap_or_default(cx, name, fun, arg, or_has_args, expr.span, method_span) {
171 let fun_span = if or_has_args { None } else { Some(fun.span) };
172 check_general_case(cx, name, method_span, receiver, arg, expr.span, fun_span);
175 hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
176 check_general_case(cx, name, method_span, receiver, arg, expr.span, None);