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_applicability, 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::emitter::MAX_SUGGESTION_HIGHLIGHT_LINES;
8 use rustc_errors::Applicability;
10 use rustc_lint::LateContext;
11 use rustc_span::source_map::Span;
12 use rustc_span::symbol::{kw, sym};
15 use super::OR_FUN_CALL;
17 /// Checks for the `OR_FUN_CALL` lint.
18 #[allow(clippy::too_many_lines)]
19 pub(super) fn check<'tcx>(
20 cx: &LateContext<'tcx>,
24 args: &'tcx [hir::Expr<'_>],
26 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
27 fn check_unwrap_or_default(
31 self_expr: &hir::Expr<'_>,
36 let is_default_default = || is_trait_item(cx, fun, sym::Default);
38 let implements_default = |arg, default_trait_id| {
39 let arg_ty = cx.typeck_results().expr_ty(arg);
40 implements_trait(cx, arg_ty, default_trait_id, &[])
45 if name == "unwrap_or";
46 if let hir::ExprKind::Path(ref qpath) = fun.kind;
47 if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
48 let path = last_path_segment(qpath).ident.name;
49 // needs to target Default::default in particular or be *::new and have a Default impl
51 if (matches!(path, kw::Default) && is_default_default())
52 || (matches!(path, sym::new) && implements_default(arg, default_trait_id));
55 let mut applicability = Applicability::MachineApplicable;
56 let hint = ".unwrap_or_default()";
57 let mut sugg: String = format!(
59 snippet_with_applicability(cx, self_expr.span, "..", &mut applicability),
63 if sugg.lines().count() > MAX_SUGGESTION_HIGHLIGHT_LINES {
64 sugg = hint.to_string();
71 &format!("use of `{}` followed by a call to `{}`", name, path),
84 /// Checks for `*or(foo())`.
85 #[allow(clippy::too_many_arguments)]
86 fn check_general_case<'tcx>(
87 cx: &LateContext<'tcx>,
90 self_expr: &hir::Expr<'_>,
91 arg: &'tcx hir::Expr<'_>,
93 // None if lambda is required
94 fun_span: Option<Span>,
96 // (path, fn_has_argument, methods, suffix)
97 static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
98 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
99 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
100 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
101 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
105 if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
107 if switch_to_lazy_eval(cx, arg);
108 if !contains_return(arg);
110 let self_ty = cx.typeck_results().expr_ty(self_expr);
112 if let Some(&(_, fn_has_arguments, poss, suffix)) =
113 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
115 if poss.contains(&name);
118 let macro_expanded_snipped;
119 let sugg: Cow<'_, str> = {
120 let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
121 (false, Some(fun_span)) => (fun_span, false),
122 _ => (arg.span, true),
125 let not_macro_argument_snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
126 if not_macro_argument_snippet == "vec![]" {
127 macro_expanded_snipped = snippet(cx, snippet_span, "..");
128 match macro_expanded_snipped.strip_prefix("$crate::vec::") {
129 Some(stripped) => Cow::from(stripped),
130 None => macro_expanded_snipped
134 not_macro_argument_snippet
139 let l_arg = if fn_has_arguments { "_" } else { "" };
140 format!("|{}| {}", l_arg, snippet).into()
145 let span_replace_word = method_span.with_hi(span.hi());
150 &format!("use of `{}` followed by a function call", name),
152 format!("{}_{}({})", name, suffix, sugg),
153 Applicability::HasPlaceholders,
159 if let [self_arg, arg] = args {
160 let inner_arg = if let hir::ExprKind::Block(
173 match inner_arg.kind {
174 hir::ExprKind::Call(fun, or_args) => {
175 let or_has_args = !or_args.is_empty();
176 if !check_unwrap_or_default(cx, name, fun, self_arg, arg, or_has_args, expr.span) {
177 let fun_span = if or_has_args { None } else { Some(fun.span) };
178 check_general_case(cx, name, method_span, self_arg, arg, expr.span, fun_span);
181 hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
182 check_general_case(cx, name, method_span, self_arg, arg, expr.span, None);