1 use crate::utils::paths;
3 in_macro, is_expn_of, last_path_segment, match_def_path, match_type, opt_def_id, resolve_node, snippet,
4 span_lint_and_then, walk_ptrs_ty,
6 use if_chain::if_chain;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::{declare_tool_lint, lint_array};
11 use rustc_errors::Applicability;
12 use syntax::ast::LitKind;
14 /// **What it does:** Checks for the use of `format!("string literal with no
15 /// argument")` and `format!("{}", foo)` where `foo` is a string.
17 /// **Why is this bad?** There is no point of doing that. `format!("foo")` can
18 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
19 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
20 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
23 /// **Known problems:** None.
28 /// format!("{}", foo)
30 declare_clippy_lint! {
33 "useless use of `format!`"
36 #[derive(Copy, Clone, Debug)]
39 impl LintPass for Pass {
40 fn get_lints(&self) -> LintArray {
41 lint_array![USELESS_FORMAT]
45 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
46 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
47 if let Some(span) = is_expn_of(expr.span, "format") {
52 // `format!("{}", foo)` expansion
53 ExprKind::Call(ref fun, ref args) => {
55 if let ExprKind::Path(ref qpath) = fun.node;
56 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
57 let new_v1 = match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1);
58 let new_v1_fmt = match_def_path(
61 &paths::FMT_ARGUMENTS_NEWV1FORMATTED
63 if new_v1 || new_v1_fmt;
64 if check_single_piece(&args[0]);
65 if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
66 if new_v1 || check_unformatted(&args[2]);
67 if let ExprKind::AddrOf(_, ref format_arg) = format_arg.node;
69 let (message, sugg) = if_chain! {
70 if let ExprKind::MethodCall(ref path, _, _) = format_arg.node;
71 if path.ident.as_interned_str() == "to_string";
73 ("`to_string()` is enough",
74 snippet(cx, format_arg.span, "<arg>").to_string())
76 ("consider using .to_string()",
77 format!("{}.to_string()", snippet(cx, format_arg.span, "<arg>")))
81 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
82 db.span_suggestion_with_applicability(
86 Applicability::MachineApplicable,
92 // `format!("foo")` expansion contains `match () { () => [], }`
93 ExprKind::Match(ref matchee, _, _) => {
94 if let ExprKind::Tup(ref tup) = matchee.node {
96 let sugg = format!("{}.to_string()", snippet(cx, expr.span, "<expr>").into_owned());
97 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
98 db.span_suggestion_with_applicability(
100 "consider using .to_string()",
102 Applicability::MachineApplicable, // snippet
114 /// Checks if the expressions matches `&[""]`
115 fn check_single_piece(expr: &Expr) -> bool {
117 if let ExprKind::AddrOf(_, ref expr) = expr.node; // &[""]
118 if let ExprKind::Array(ref exprs) = expr.node; // [""]
120 if let ExprKind::Lit(ref lit) = exprs[0].node;
121 if let LitKind::Str(ref lit, _) = lit.node;
123 return lit.as_str().is_empty();
130 /// Checks if the expressions matches
132 /// &match (&"arg",) {
133 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
134 /// ::std::fmt::Display::fmt)],
137 /// and that the type of `__arg0` is `&str` or `String`,
138 /// then returns the span of first element of the matched tuple.
139 fn get_single_string_arg<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<&'a Expr> {
141 if let ExprKind::AddrOf(_, ref expr) = expr.node;
142 if let ExprKind::Match(ref match_expr, ref arms, _) = expr.node;
144 if arms[0].pats.len() == 1;
145 if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
147 if let ExprKind::Array(ref exprs) = arms[0].body.node;
149 if let ExprKind::Call(_, ref args) = exprs[0].node;
151 if let ExprKind::Path(ref qpath) = args[1].node;
152 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, args[1].hir_id));
153 if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
155 let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
156 if ty.sty == ty::Str || match_type(cx, ty, &paths::STRING) {
157 if let ExprKind::Tup(ref values) = match_expr.node {
158 return Some(&values[0]);
167 /// Checks if the expression matches
171 /// width: _::Implied,
177 fn check_unformatted(expr: &Expr) -> bool {
179 if let ExprKind::AddrOf(_, ref expr) = expr.node;
180 if let ExprKind::Array(ref exprs) = expr.node;
182 if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
183 if let Some(format_field) = fields.iter().find(|f| f.ident.name == "format");
184 if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
185 if let Some(width_field) = fields.iter().find(|f| f.ident.name == "width");
186 if let ExprKind::Path(ref width_qpath) = width_field.expr.node;
187 if last_path_segment(width_qpath).ident.name == "Implied";
188 if let Some(precision_field) = fields.iter().find(|f| f.ident.name == "precision");
189 if let ExprKind::Path(ref precision_path) = precision_field.expr.node;
190 if last_path_segment(precision_path).ident.name == "Implied";