1 use crate::utils::{is_expn_of, match_function_call, paths};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
3 use if_chain::if_chain;
4 use rustc_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BorrowKind, 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(ref unwrap_fun, _, ref unwrap_args, _) = expr.kind;
38 if unwrap_fun.ident.name == sym::unwrap;
39 // match call to write_fmt
40 if !unwrap_args.is_empty();
41 if let ExprKind::MethodCall(ref write_fun, _, write_args, _) =
43 if write_fun.ident.name == sym!(write_fmt);
44 // match calls to std::io::stdout() / std::io::stderr ()
45 if !write_args.is_empty();
46 if let Some(dest_name) = if match_function_call(cx, &write_args[0], &paths::STDOUT).is_some() {
48 } else if match_function_call(cx, &write_args[0], &paths::STDERR).is_some() {
54 let write_span = unwrap_args[0].span;
56 // ordering is important here, since `writeln!` uses `write!` internally
57 if is_expn_of(write_span, "writeln").is_some() {
59 } else if is_expn_of(write_span, "write").is_some() {
64 let prefix = if dest_name == "stderr" {
70 // We need to remove the last trailing newline from the string because the
71 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
73 if let Some(mut write_output) = write_output_string(write_args) {
74 if write_output.ends_with('\n') {
78 if let Some(macro_name) = calling_macro {
84 "use of `{}!({}(), ...).unwrap()`",
89 format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
90 Applicability::MachineApplicable
97 &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
99 format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
100 Applicability::MachineApplicable
104 // We don't have a proper suggestion
105 if let Some(macro_name) = calling_macro {
111 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
115 macro_name.replace("write", "print")
123 &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
133 // Extract the output string from the given `write_args`.
134 fn write_output_string(write_args: &[Expr<'_>]) -> Option<String> {
136 // Obtain the string that should be printed
137 if write_args.len() > 1;
138 if let ExprKind::Call(_, ref output_args) = write_args[1].kind;
139 if !output_args.is_empty();
140 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref output_string_expr) = output_args[0].kind;
141 if let ExprKind::Array(ref string_exprs) = output_string_expr.kind;
142 // we only want to provide an automatic suggestion for simple (non-format) strings
143 if string_exprs.len() == 1;
144 if let ExprKind::Lit(ref lit) = string_exprs[0].kind;
145 if let LitKind::Str(ref write_output, _) = lit.node;
147 return Some(write_output.to_string())