3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
6 use syntax::ast::LitKind;
8 use crate::utils::paths;
9 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};
11 /// **What it does:** Checks for the use of `format!("string literal with no
12 /// argument")` and `format!("{}", foo)` where `foo` is a string.
14 /// **Why is this bad?** There is no point of doing that. `format!("too")` can
15 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
16 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
17 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
20 /// **Known problems:** None.
25 /// format!("{}", foo)
27 declare_clippy_lint! {
30 "useless use of `format!`"
33 #[derive(Copy, Clone, Debug)]
36 impl LintPass for Pass {
37 fn get_lints(&self) -> LintArray {
38 lint_array![USELESS_FORMAT]
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
43 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
44 if let Some(span) = is_expn_of(expr.span, "format") {
50 // `format!("{}", foo)` expansion
51 ExprKind::Call(ref fun, ref args) => {
53 if let ExprKind::Path(ref qpath) = fun.node;
55 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
56 if match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1FORMATTED);
57 if check_single_piece(&args[0]);
58 if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
59 if check_unformatted(&args[2]);
61 let sugg = format!("{}.to_string()", snippet(cx, format_arg, "<arg>").into_owned());
62 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
63 db.span_suggestion(expr.span, "consider using .to_string()", sugg);
68 // `format!("foo")` expansion contains `match () { () => [], }`
69 ExprKind::Match(ref matchee, _, _) => if let ExprKind::Tup(ref tup) = matchee.node {
71 let sugg = format!("{}.to_string()", snippet(cx, expr.span, "<expr>").into_owned());
72 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
73 db.span_suggestion(span, "consider using .to_string()", sugg);
83 /// Checks if the expressions matches `&[""]`
84 fn check_single_piece(expr: &Expr) -> bool {
86 if let ExprKind::AddrOf(_, ref expr) = expr.node; // &[""]
87 if let ExprKind::Array(ref exprs) = expr.node; // [""]
89 if let ExprKind::Lit(ref lit) = exprs[0].node;
90 if let LitKind::Str(ref lit, _) = lit.node;
92 return lit.as_str().is_empty();
99 /// Checks if the expressions matches
101 /// &match (&"arg",) {
102 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
103 /// ::std::fmt::Display::fmt)],
106 /// and that type of `__arg0` is `&str` or `String`
107 /// then returns the span of first element of the matched tuple
108 fn get_single_string_arg(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Span> {
110 if let ExprKind::AddrOf(_, ref expr) = expr.node;
111 if let ExprKind::Match(ref match_expr, ref arms, _) = expr.node;
113 if arms[0].pats.len() == 1;
114 if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
116 if let ExprKind::Array(ref exprs) = arms[0].body.node;
118 if let ExprKind::Call(_, ref args) = exprs[0].node;
120 if let ExprKind::Path(ref qpath) = args[1].node;
121 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, args[1].hir_id));
122 if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
124 let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
125 if ty.sty == ty::TyStr || match_type(cx, ty, &paths::STRING) {
126 if let ExprKind::Tup(ref values) = match_expr.node {
127 return Some(values[0].span);
136 /// Checks if the expression matches
140 /// width: _::Implied,
146 fn check_unformatted(expr: &Expr) -> bool {
148 if let ExprKind::AddrOf(_, ref expr) = expr.node;
149 if let ExprKind::Array(ref exprs) = expr.node;
151 if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
152 if let Some(format_field) = fields.iter().find(|f| f.ident.name == "format");
153 if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
154 if let Some(align_field) = fields.iter().find(|f| f.ident.name == "width");
155 if let ExprKind::Path(ref qpath) = align_field.expr.node;
156 if last_path_segment(qpath).ident.name == "Implied";