1 use crate::utils::{is_expn_of, match_function_call, paths, span_lint, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc_ast::ast::LitKind;
4 use rustc_errors::Applicability;
5 use rustc_hir::{BorrowKind, Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
12 /// replaced with `(e)print!()` / `(e)println!()`
14 /// **Why is this bad?** Using `(e)println! is clearer and more concise
16 /// **Known problems:** None.
20 /// # use std::io::Write;
21 /// # let bar = "furchtbar";
22 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
23 /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
27 "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
30 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
32 impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
33 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
35 // match call to unwrap
36 if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args, _) = expr.kind;
37 if unwrap_fun.ident.name == sym::unwrap;
38 // match call to write_fmt
39 if !unwrap_args.is_empty();
40 if let ExprKind::MethodCall(ref write_fun, _, write_args, _) =
42 if write_fun.ident.name == sym!(write_fmt);
43 // match calls to std::io::stdout() / std::io::stderr ()
44 if !write_args.is_empty();
45 if let Some(dest_name) = if match_function_call(cx, &write_args[0], &paths::STDOUT).is_some() {
47 } else if match_function_call(cx, &write_args[0], &paths::STDERR).is_some() {
53 let write_span = unwrap_args[0].span;
55 // ordering is important here, since `writeln!` uses `write!` internally
56 if is_expn_of(write_span, "writeln").is_some() {
58 } else if is_expn_of(write_span, "write").is_some() {
63 let prefix = if dest_name == "stderr" {
69 // We need to remove the last trailing newline from the string because the
70 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
72 if let Some(mut write_output) = write_output_string(write_args) {
73 if write_output.ends_with('\n') {
77 if let Some(macro_name) = calling_macro {
83 "use of `{}!({}(), ...).unwrap()`",
88 format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
89 Applicability::MachineApplicable
96 &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
98 format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
99 Applicability::MachineApplicable
103 // We don't have a proper suggestion
104 if let Some(macro_name) = calling_macro {
110 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
114 macro_name.replace("write", "print")
122 &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
132 // Extract the output string from the given `write_args`.
133 fn write_output_string(write_args: &[Expr<'_>]) -> Option<String> {
135 // Obtain the string that should be printed
136 if write_args.len() > 1;
137 if let ExprKind::Call(_, ref output_args) = write_args[1].kind;
138 if !output_args.is_empty();
139 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref output_string_expr) = output_args[0].kind;
140 if let ExprKind::Array(ref string_exprs) = output_string_expr.kind;
141 // we only want to provide an automatic suggestion for simple (non-format) strings
142 if string_exprs.len() == 1;
143 if let ExprKind::Lit(ref lit) = string_exprs[0].kind;
144 if let LitKind::Str(ref write_output, _) = lit.node;
146 return Some(write_output.to_string())