4 use syntax::ast::LitKind;
6 use utils::{is_expn_of, match_def_path, match_type, resolve_node, span_lint, walk_ptrs_ty, opt_def_id};
8 /// **What it does:** Checks for the use of `format!("string literal with no
9 /// argument")` and `format!("{}", foo)` where `foo` is a string.
11 /// **Why is this bad?** There is no point of doing that. `format!("too")` can
12 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
13 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
14 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
17 /// **Known problems:** None.
22 /// format!("{}", foo)
27 "useless use of `format!`"
30 #[derive(Copy, Clone, Debug)]
33 impl LintPass for Pass {
34 fn get_lints(&self) -> LintArray {
35 lint_array![USELESS_FORMAT]
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
40 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
41 if let Some(span) = is_expn_of(expr.span, "format") {
43 // `format!("{}", foo)` expansion
44 ExprCall(ref fun, ref args) => {
46 if let ExprPath(ref qpath) = fun.node;
48 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
49 if match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1);
50 // ensure the format string is `"{..}"` with only one argument and no text
51 if check_static_str(&args[0]);
52 // ensure the format argument is `{}` ie. Display with no fancy option
53 // and that the argument is a string
54 if check_arg_is_display(cx, &args[1]);
56 span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
60 // `format!("foo")` expansion contains `match () { () => [], }`
61 ExprMatch(ref matchee, _, _) => if let ExprTup(ref tup) = matchee.node {
63 span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
72 /// Checks if the expressions matches `&[""]`
73 fn check_static_str(expr: &Expr) -> bool {
75 if let ExprAddrOf(_, ref expr) = expr.node; // &[""]
76 if let ExprArray(ref exprs) = expr.node; // [""]
78 if let ExprLit(ref lit) = exprs[0].node;
79 if let LitKind::Str(ref lit, _) = lit.node;
81 return lit.as_str().is_empty();
88 /// Checks if the expressions matches
91 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
92 /// ::std::fmt::Display::fmt)],
95 fn check_arg_is_display(cx: &LateContext, expr: &Expr) -> bool {
97 if let ExprAddrOf(_, ref expr) = expr.node;
98 if let ExprMatch(_, ref arms, _) = expr.node;
100 if arms[0].pats.len() == 1;
101 if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
103 if let ExprArray(ref exprs) = arms[0].body.node;
105 if let ExprCall(_, ref args) = exprs[0].node;
107 if let ExprPath(ref qpath) = args[1].node;
108 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, args[1].hir_id));
109 if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
111 let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
113 return ty.sty == ty::TyStr || match_type(cx, ty, &paths::STRING);