4 use syntax::ast::LitKind;
6 use crate::utils::paths;
7 use crate::utils::{in_macro, is_expn_of, last_path_segment, match_def_path, match_type, opt_def_id, resolve_node, snippet, span_lint_and_then, walk_ptrs_ty};
9 /// **What it does:** Checks for the use of `format!("string literal with no
10 /// argument")` and `format!("{}", foo)` where `foo` is a string.
12 /// **Why is this bad?** There is no point of doing that. `format!("too")` can
13 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
14 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
15 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
18 /// **Known problems:** None.
23 /// format!("{}", foo)
25 declare_clippy_lint! {
28 "useless use of `format!`"
31 #[derive(Copy, Clone, Debug)]
34 impl LintPass for Pass {
35 fn get_lints(&self) -> LintArray {
36 lint_array![USELESS_FORMAT]
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
42 if let Some(span) = is_expn_of(expr.span, "format") {
48 // `format!("{}", foo)` expansion
49 ExprCall(ref fun, ref args) => {
51 if let ExprPath(ref qpath) = fun.node;
53 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
54 if match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1FORMATTED);
55 if check_single_piece(&args[0]);
56 if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
57 if check_unformatted(&args[2]);
59 let sugg = format!("{}.to_string()", snippet(cx, format_arg, "<arg>").into_owned());
60 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
61 db.span_suggestion(expr.span, "consider using .to_string()", sugg);
66 // `format!("foo")` expansion contains `match () { () => [], }`
67 ExprMatch(ref matchee, _, _) => if let ExprTup(ref tup) = matchee.node {
69 let sugg = format!("{}.to_string()", snippet(cx, expr.span, "<expr>").into_owned());
70 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
71 db.span_suggestion(span, "consider using .to_string()", sugg);
81 /// Checks if the expressions matches `&[""]`
82 fn check_single_piece(expr: &Expr) -> bool {
84 if let ExprAddrOf(_, ref expr) = expr.node; // &[""]
85 if let ExprArray(ref exprs) = expr.node; // [""]
87 if let ExprLit(ref lit) = exprs[0].node;
88 if let LitKind::Str(ref lit, _) = lit.node;
90 return lit.as_str().is_empty();
97 /// Checks if the expressions matches
99 /// &match (&"arg",) {
100 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
101 /// ::std::fmt::Display::fmt)],
104 /// and that type of `__arg0` is `&str` or `String`
105 /// then returns the span of first element of the matched tuple
106 fn get_single_string_arg(cx: &LateContext, expr: &Expr) -> Option<Span> {
108 if let ExprAddrOf(_, ref expr) = expr.node;
109 if let ExprMatch(ref match_expr, ref arms, _) = expr.node;
111 if arms[0].pats.len() == 1;
112 if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
114 if let ExprArray(ref exprs) = arms[0].body.node;
116 if let ExprCall(_, ref args) = exprs[0].node;
118 if let ExprPath(ref qpath) = args[1].node;
119 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, args[1].hir_id));
120 if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
122 let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
123 if ty.sty == ty::TyStr || match_type(cx, ty, &paths::STRING) {
124 if let ExprTup(ref values) = match_expr.node {
125 return Some(values[0].span);
134 /// Checks if the expression matches
138 /// width: _::Implied,
144 fn check_unformatted(expr: &Expr) -> bool {
146 if let ExprAddrOf(_, ref expr) = expr.node;
147 if let ExprArray(ref exprs) = expr.node;
149 if let ExprStruct(_, ref fields, _) = exprs[0].node;
150 if let Some(format_field) = fields.iter().find(|f| f.ident.name == "format");
151 if let ExprStruct(_, ref fields, _) = format_field.expr.node;
152 if let Some(align_field) = fields.iter().find(|f| f.ident.name == "width");
153 if let ExprPath(ref qpath) = align_field.expr.node;
154 if last_path_segment(qpath).name == "Implied";