1 use crate::utils::paths;
3 in_macro_or_desugar, is_expn_of, last_path_segment, match_def_path, match_type, resolve_node, snippet,
4 span_lint_and_then, walk_ptrs_ty,
6 use if_chain::if_chain;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
9 use rustc::{declare_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::Span;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for the use of `format!("string literal with no
16 /// argument")` and `format!("{}", foo)` where `foo` is a string.
18 /// **Why is this bad?** There is no point of doing that. `format!("foo")` can
19 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
20 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
21 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
24 /// **Known problems:** None.
28 /// # let foo = "foo";
30 /// format!("{}", foo);
34 "useless use of `format!`"
37 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessFormat {
40 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
41 let span = match is_expn_of(expr.span, "format") {
42 Some(s) if !in_macro_or_desugar(s) => s,
46 // Operate on the only argument of `alloc::fmt::format`.
47 if let Some(sugg) = on_new_v1(cx, expr) {
48 span_useless_format(cx, span, "consider using .to_string()", sugg);
49 } else if let Some(sugg) = on_new_v1_fmt(cx, expr) {
50 span_useless_format(cx, span, "consider using .to_string()", sugg);
55 fn span_useless_format<T: LintContext>(cx: &T, span: Span, help: &str, mut sugg: String) {
56 let to_replace = span.source_callsite();
58 // The callsite span contains the statement semicolon for some reason.
59 let snippet = snippet(cx, to_replace, "..");
60 if snippet.ends_with(';') {
64 span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
69 Applicability::MachineApplicable, // snippet
74 fn on_argumentv1_new<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, arms: &'a [Arm]) -> Option<String> {
76 if let ExprKind::AddrOf(_, ref format_args) = expr.node;
77 if let ExprKind::Array(ref elems) = arms[0].body.node;
79 if let ExprKind::Call(ref fun, ref args) = elems[0].node;
80 if let ExprKind::Path(ref qpath) = fun.node;
81 if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
82 if match_def_path(cx, did, &paths::FMT_ARGUMENTV1_NEW);
83 // matches `core::fmt::Display::fmt`
85 if let ExprKind::Path(ref qpath) = args[1].node;
86 if let Some(did) = resolve_node(cx, qpath, args[1].hir_id).opt_def_id();
87 if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD);
88 if arms[0].pats.len() == 1;
89 // check `(arg0,)` in match block
90 if let PatKind::Tuple(ref pats, None) = arms[0].pats[0].node;
93 if let ExprKind::Lit(ref lit) = format_args.node {
94 if let LitKind::Str(ref s, _) = lit.node {
95 let snip = s.as_str().replace("{{}}", "{}");
96 let sugg = format!("\"{}\".to_string()", snip);
101 let snip = snippet(cx, format_args.span, "<arg>");
102 if let ExprKind::MethodCall(ref path, _, _) = format_args.node {
103 if path.ident.name == sym!(to_string) {
104 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 ExprKind::Call(ref fun, ref args) = expr.node;
118 if let ExprKind::Path(ref qpath) = fun.node;
119 if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
120 if match_def_path(cx, did, &paths::FMT_ARGUMENTS_NEW_V1);
121 // Argument 1 in `new_v1()`
122 if let ExprKind::AddrOf(_, ref arr) = args[0].node;
123 if let ExprKind::Array(ref pieces) = arr.node;
124 if pieces.len() == 1;
125 if let ExprKind::Lit(ref lit) = pieces[0].node;
126 if let LitKind::Str(ref s, _) = lit.node;
127 // Argument 2 in `new_v1()`
128 if let ExprKind::AddrOf(_, ref arg1) = args[1].node;
129 if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.node;
131 if let ExprKind::Tup(ref tup) = matchee.node;
133 // `format!("foo")` expansion contains `match () { () => [], }`
135 let snip = s.as_str().replace("{{}}", "{}");
136 let sugg = format!("\"{}\".to_string()", snip);
139 if s.as_str().is_empty() {
140 return on_argumentv1_new(cx, &tup[0], arms);
150 fn on_new_v1_fmt<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<String> {
152 if let ExprKind::Call(ref fun, ref args) = expr.node;
154 if let ExprKind::Path(ref qpath) = fun.node;
155 if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
156 if match_def_path(cx, did, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
157 if check_unformatted(&args[2]);
158 // Argument 1 in `new_v1_formatted()`
159 if let ExprKind::AddrOf(_, ref arr) = args[0].node;
160 if let ExprKind::Array(ref pieces) = arr.node;
161 if pieces.len() == 1;
162 if let ExprKind::Lit(ref lit) = pieces[0].node;
163 if let LitKind::Str(..) = lit.node;
164 // Argument 2 in `new_v1_formatted()`
165 if let ExprKind::AddrOf(_, ref arg1) = args[1].node;
166 if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.node;
168 if let ExprKind::Tup(ref tup) = matchee.node;
170 return on_argumentv1_new(cx, &tup[0], arms);
176 /// Checks if the expression matches
180 /// width: _::Implied,
181 /// precision: _::Implied,
187 fn check_unformatted(expr: &Expr) -> bool {
189 if let ExprKind::AddrOf(_, ref expr) = expr.node;
190 if let ExprKind::Array(ref exprs) = expr.node;
192 // struct `core::fmt::rt::v1::Argument`
193 if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
194 if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym!(format));
195 // struct `core::fmt::rt::v1::FormatSpec`
196 if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
197 if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym!(precision));
198 if let ExprKind::Path(ref precision_path) = precision_field.expr.node;
199 if last_path_segment(precision_path).ident.name == sym!(Implied);
200 if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym!(width));
201 if let ExprKind::Path(ref width_qpath) = width_field.expr.node;
202 if last_path_segment(width_qpath).ident.name == sym!(Implied);