1 use crate::utils::paths;
3 is_expn_of, last_path_segment, match_def_path, match_function_call, match_type, snippet, span_lint_and_then,
6 use if_chain::if_chain;
7 use rustc::declare_lint_pass;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
10 use rustc_errors::Applicability;
11 use rustc_session::declare_tool_lint;
12 use syntax::ast::LitKind;
13 use syntax::source_map::Span;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for the use of `format!("string literal with no
17 /// argument")` and `format!("{}", foo)` where `foo` is a string.
19 /// **Why is this bad?** There is no point of doing that. `format!("foo")` can
20 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
21 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
22 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
25 /// **Known problems:** None.
29 /// # let foo = "foo";
31 /// format!("{}", foo);
35 "useless use of `format!`"
38 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessFormat {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
42 let span = match is_expn_of(expr.span, "format") {
43 Some(s) if !s.from_expansion() => s,
47 // Operate on the only argument of `alloc::fmt::format`.
48 if let Some(sugg) = on_new_v1(cx, expr) {
49 span_useless_format(cx, span, "consider using .to_string()", sugg);
50 } else if let Some(sugg) = on_new_v1_fmt(cx, expr) {
51 span_useless_format(cx, span, "consider using .to_string()", sugg);
56 fn span_useless_format<T: LintContext>(cx: &T, span: Span, help: &str, mut sugg: String) {
57 let to_replace = span.source_callsite();
59 // The callsite span contains the statement semicolon for some reason.
60 let snippet = snippet(cx, to_replace, "..");
61 if snippet.ends_with(';') {
65 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
70 Applicability::MachineApplicable, // snippet
75 fn on_argumentv1_new<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, arms: &'tcx [Arm]) -> Option<String> {
77 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref format_args) = expr.kind;
78 if let ExprKind::Array(ref elems) = arms[0].body.kind;
80 if let Some(args) = match_function_call(cx, &elems[0], &paths::FMT_ARGUMENTV1_NEW);
81 // matches `core::fmt::Display::fmt`
83 if let ExprKind::Path(ref qpath) = args[1].kind;
84 if let Some(did) = cx.tables.qpath_res(qpath, args[1].hir_id).opt_def_id();
85 if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD);
86 // check `(arg0,)` in match block
87 if let PatKind::Tuple(ref pats, None) = arms[0].pat.kind;
90 let ty = walk_ptrs_ty(cx.tables.pat_ty(&pats[0]));
91 if ty.kind != rustc::ty::Str && !match_type(cx, ty, &paths::STRING) {
94 if let ExprKind::Lit(ref lit) = format_args.kind {
95 if let LitKind::Str(ref s, _) = lit.node {
96 return Some(format!("{:?}.to_string()", s.as_str()));
99 let snip = snippet(cx, format_args.span, "<arg>");
100 if let ExprKind::MethodCall(ref path, _, _) = format_args.kind {
101 if path.ident.name == sym!(to_string) {
102 return Some(format!("{}", snip));
104 } else if let ExprKind::Binary(..) = format_args.kind {
105 return Some(format!("{}", snip));
107 return Some(format!("{}.to_string()", snip));
114 fn on_new_v1<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<String> {
116 if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1);
118 // Argument 1 in `new_v1()`
119 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arr) = args[0].kind;
120 if let ExprKind::Array(ref pieces) = arr.kind;
121 if pieces.len() == 1;
122 if let ExprKind::Lit(ref lit) = pieces[0].kind;
123 if let LitKind::Str(ref s, _) = lit.node;
124 // Argument 2 in `new_v1()`
125 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arg1) = args[1].kind;
126 if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.kind;
128 if let ExprKind::Tup(ref tup) = matchee.kind;
130 // `format!("foo")` expansion contains `match () { () => [], }`
132 return Some(format!("{:?}.to_string()", s.as_str()));
133 } else if s.as_str().is_empty() {
134 return on_argumentv1_new(cx, &tup[0], arms);
141 fn on_new_v1_fmt<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<String> {
143 if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
145 if check_unformatted(&args[2]);
146 // Argument 1 in `new_v1_formatted()`
147 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arr) = args[0].kind;
148 if let ExprKind::Array(ref pieces) = arr.kind;
149 if pieces.len() == 1;
150 if let ExprKind::Lit(ref lit) = pieces[0].kind;
151 if let LitKind::Str(..) = lit.node;
152 // Argument 2 in `new_v1_formatted()`
153 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arg1) = args[1].kind;
154 if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.kind;
156 if let ExprKind::Tup(ref tup) = matchee.kind;
158 return on_argumentv1_new(cx, &tup[0], arms);
164 /// Checks if the expression matches
168 /// width: _::Implied,
169 /// precision: _::Implied,
175 fn check_unformatted(expr: &Expr) -> bool {
177 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) = expr.kind;
178 if let ExprKind::Array(ref exprs) = expr.kind;
180 // struct `core::fmt::rt::v1::Argument`
181 if let ExprKind::Struct(_, ref fields, _) = exprs[0].kind;
182 if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym!(format));
183 // struct `core::fmt::rt::v1::FormatSpec`
184 if let ExprKind::Struct(_, ref fields, _) = format_field.expr.kind;
185 if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym!(precision));
186 if let ExprKind::Path(ref precision_path) = precision_field.expr.kind;
187 if last_path_segment(precision_path).ident.name == sym!(Implied);
188 if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym!(width));
189 if let ExprKind::Path(ref width_qpath) = width_field.expr.kind;
190 if last_path_segment(width_qpath).ident.name == sym!(Implied);