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 return Some(format!("{:?}.to_string()", s.as_str()));
98 let snip = snippet(cx, format_args.span, "<arg>");
99 if let ExprKind::MethodCall(ref path, _, _) = format_args.node {
100 if path.ident.name == sym!(to_string) {
101 return Some(format!("{}", snip));
104 return Some(format!("{}.to_string()", snip));
111 fn on_new_v1<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<String> {
113 if let ExprKind::Call(ref fun, ref args) = expr.node;
115 if let ExprKind::Path(ref qpath) = fun.node;
116 if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
117 if match_def_path(cx, did, &paths::FMT_ARGUMENTS_NEW_V1);
118 // Argument 1 in `new_v1()`
119 if let ExprKind::AddrOf(_, ref arr) = args[0].node;
120 if let ExprKind::Array(ref pieces) = arr.node;
121 if pieces.len() == 1;
122 if let ExprKind::Lit(ref lit) = pieces[0].node;
123 if let LitKind::Str(ref s, _) = lit.node;
124 // Argument 2 in `new_v1()`
125 if let ExprKind::AddrOf(_, ref arg1) = args[1].node;
126 if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.node;
128 if let ExprKind::Tup(ref tup) = matchee.node;
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 ExprKind::Call(ref fun, ref args) = expr.node;
145 if let ExprKind::Path(ref qpath) = fun.node;
146 if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
147 if match_def_path(cx, did, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
148 if check_unformatted(&args[2]);
149 // Argument 1 in `new_v1_formatted()`
150 if let ExprKind::AddrOf(_, ref arr) = args[0].node;
151 if let ExprKind::Array(ref pieces) = arr.node;
152 if pieces.len() == 1;
153 if let ExprKind::Lit(ref lit) = pieces[0].node;
154 if let LitKind::Str(..) = lit.node;
155 // Argument 2 in `new_v1_formatted()`
156 if let ExprKind::AddrOf(_, ref arg1) = args[1].node;
157 if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.node;
159 if let ExprKind::Tup(ref tup) = matchee.node;
161 return on_argumentv1_new(cx, &tup[0], arms);
167 /// Checks if the expression matches
171 /// width: _::Implied,
172 /// precision: _::Implied,
178 fn check_unformatted(expr: &Expr) -> bool {
180 if let ExprKind::AddrOf(_, ref expr) = expr.node;
181 if let ExprKind::Array(ref exprs) = expr.node;
183 // struct `core::fmt::rt::v1::Argument`
184 if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
185 if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym!(format));
186 // struct `core::fmt::rt::v1::FormatSpec`
187 if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
188 if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym!(precision));
189 if let ExprKind::Path(ref precision_path) = precision_field.expr.node;
190 if last_path_segment(precision_path).ident.name == sym!(Implied);
191 if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym!(width));
192 if let ExprKind::Path(ref width_qpath) = width_field.expr.node;
193 if last_path_segment(width_qpath).ident.name == sym!(Implied);