1 use clippy_utils::{diagnostics::span_lint_and_sugg, ty::is_type_lang_item};
2 use clippy_utils::{match_def_path, paths};
3 use if_chain::if_chain;
4 use rustc_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BorrowKind, Expr, ExprKind, LangItem, Mutability};
7 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
14 /// Detects cases of owned empty strings being passed as an argument to a function expecting `&str`
16 /// ### Why is this bad?
18 /// This results in longer and less readable code
22 /// vec!["1", "2", "3"].join(&String::new());
26 /// vec!["1", "2", "3"].join("");
28 #[clippy::version = "1.62.0"]
29 pub UNNECESSARY_OWNED_EMPTY_STRINGS,
31 "detects cases of references to owned empty strings being passed as an argument to a function expecting `&str`"
33 declare_lint_pass!(UnnecessaryOwnedEmptyStrings => [UNNECESSARY_OWNED_EMPTY_STRINGS]);
35 impl<'tcx> LateLintPass<'tcx> for UnnecessaryOwnedEmptyStrings {
36 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
38 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner_expr) = expr.kind;
39 if let ExprKind::Call(fun, args) = inner_expr.kind;
40 if let ExprKind::Path(ref qpath) = fun.kind;
41 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
42 if let ty::Ref(_, inner_str, _) = cx.typeck_results().expr_ty_adjusted(expr).kind();
43 if inner_str.is_str();
45 if match_def_path(cx, fun_def_id, &paths::STRING_NEW) {
48 UNNECESSARY_OWNED_EMPTY_STRINGS,
50 "usage of `&String::new()` for a function expecting a `&str` argument",
53 Applicability::MachineApplicable,
57 if Some(fun_def_id) == cx.tcx.lang_items().from_fn();
58 if let [.., last_arg] = args;
59 if let ExprKind::Lit(spanned) = &last_arg.kind;
60 if let LitKind::Str(symbol, _) = spanned.node;
62 let inner_expr_type = cx.typeck_results().expr_ty(inner_expr);
63 if is_type_lang_item(cx, inner_expr_type, LangItem::String);
67 UNNECESSARY_OWNED_EMPTY_STRINGS,
69 "usage of `&String::from(\"\")` for a function expecting a `&str` argument",
72 Applicability::MachineApplicable,