1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::higher::FormatArgsExpn;
3 use clippy_utils::{is_expn_of, match_function_call, paths};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
12 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
13 /// replaced with `(e)print!()` / `(e)println!()`
15 /// **Why is this bad?** Using `(e)println! is clearer and more concise
17 /// **Known problems:** None.
21 /// # use std::io::Write;
22 /// # let bar = "furchtbar";
23 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
24 /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
28 "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
31 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
33 impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
34 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
36 // match call to unwrap
37 if let ExprKind::MethodCall(unwrap_fun, _, [write_call], _) = expr.kind;
38 if unwrap_fun.ident.name == sym::unwrap;
39 // match call to write_fmt
40 if let ExprKind::MethodCall(write_fun, _, [write_recv, write_arg], _) = write_call.kind;
41 if write_fun.ident.name == sym!(write_fmt);
42 // match calls to std::io::stdout() / std::io::stderr ()
43 if let Some(dest_name) = if match_function_call(cx, write_recv, &paths::STDOUT).is_some() {
45 } else if match_function_call(cx, write_recv, &paths::STDERR).is_some() {
50 if let Some(format_args) = FormatArgsExpn::parse(write_arg);
53 // ordering is important here, since `writeln!` uses `write!` internally
54 if is_expn_of(write_call.span, "writeln").is_some() {
56 } else if is_expn_of(write_call.span, "write").is_some() {
61 let prefix = if dest_name == "stderr" {
67 // We need to remove the last trailing newline from the string because the
68 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
70 let (used, sugg_mac) = if let Some(macro_name) = calling_macro {
72 format!("{}!({}(), ...)", macro_name, dest_name),
73 macro_name.replace("write", "print"),
77 format!("{}().write_fmt(...)", dest_name),
81 let msg = format!("use of `{}.unwrap()`", used);
82 if let [write_output] = *format_args.format_string_symbols {
83 let mut write_output = write_output.to_string();
84 if write_output.ends_with('\n') {
88 let sugg = format!("{}{}!(\"{}\")", prefix, sugg_mac, write_output.escape_default());
96 Applicability::MachineApplicable
99 // We don't have a proper suggestion
100 let help = format!("consider using `{}{}!` instead", prefix, sugg_mac);
101 span_lint_and_help(cx, EXPLICIT_WRITE, expr.span, &msg, None, &help);