1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher::FormatExpn;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use rustc_errors::Applicability;
7 use rustc_lint::LateContext;
9 use rustc_span::source_map::Span;
10 use rustc_span::symbol::sym;
13 use super::EXPECT_FUN_CALL;
15 /// Checks for the `EXPECT_FUN_CALL` lint.
16 #[allow(clippy::too_many_lines)]
17 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, method_span: Span, name: &str, args: &[hir::Expr<'_>]) {
18 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
20 fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
21 let mut arg_root = arg;
23 arg_root = match &arg_root.kind {
24 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
25 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
26 if call_args.len() == 1
27 && (method_name.ident.name == sym::as_str || method_name.ident.name == sym!(as_ref))
29 let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
30 let base_type = arg_type.peel_refs();
31 *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym::string_type)
45 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
46 // converted to string.
47 fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
48 let arg_ty = cx.typeck_results().expr_ty(arg);
49 if is_type_diagnostic_item(cx, arg_ty, sym::string_type) {
52 if let ty::Ref(_, ty, ..) = arg_ty.kind() {
53 if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
60 // Check if an expression could have type `&'static str`, knowing that it
61 // has type `&str` for some lifetime.
62 fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
64 hir::ExprKind::Lit(_) => true,
65 hir::ExprKind::Call(fun, _) => {
66 if let hir::ExprKind::Path(ref p) = fun.kind {
67 match cx.qpath_res(p, fun.hir_id) {
68 hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
69 cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
70 ty::Ref(ty::ReStatic, ..)
78 hir::ExprKind::MethodCall(..) => {
80 .type_dependent_def_id(arg.hir_id)
81 .map_or(false, |method_id| {
83 cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
84 ty::Ref(ty::ReStatic, ..)
88 hir::ExprKind::Path(ref p) => matches!(
89 cx.qpath_res(p, arg.hir_id),
90 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
96 fn is_call(node: &hir::ExprKind<'_>) -> bool {
98 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
101 hir::ExprKind::Call(..)
102 | hir::ExprKind::MethodCall(..)
103 // These variants are debatable or require further examination
104 | hir::ExprKind::If(..)
105 | hir::ExprKind::Match(..)
106 | hir::ExprKind::Block{ .. } => true,
111 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
115 let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
116 let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::option_type) {
118 } else if is_type_diagnostic_item(cx, receiver_type, sym::result_type) {
124 let arg_root = get_arg_root(cx, &args[1]);
126 let span_replace_word = method_span.with_hi(expr.span.hi());
128 let mut applicability = Applicability::MachineApplicable;
130 //Special handling for `format!` as arg_root
131 if let Some(format_expn) = FormatExpn::parse(arg_root) {
132 let span = match *format_expn.format_args.value_args {
133 [] => format_expn.format_args.format_string_span,
134 [.., last] => format_expn.format_args.format_string_span.to(last.span),
136 let sugg = snippet_with_applicability(cx, span, "..", &mut applicability);
141 &format!("use of `{}` followed by a function call", name),
143 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
149 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
150 if requires_to_string(cx, arg_root) {
151 arg_root_snippet.to_mut().push_str(".to_string()");
158 &format!("use of `{}` followed by a function call", name),
161 "unwrap_or_else({} {{ panic!(\"{{}}\", {}) }})",
162 closure_args, arg_root_snippet