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 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
11 /// replaced with `(e)print!()` / `(e)println!()`
13 /// **Why is this bad?** Using `(e)println! is clearer and more concise
15 /// **Known problems:** None.
19 /// # use std::io::Write;
20 /// # let bar = "furchtbar";
21 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
22 /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
26 "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
29 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitWrite {
32 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
34 // match call to unwrap
35 if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.kind;
36 if unwrap_fun.ident.name == sym!(unwrap);
37 // match call to write_fmt
38 if !unwrap_args.is_empty();
39 if let ExprKind::MethodCall(ref write_fun, _, write_args) =
41 if write_fun.ident.name == sym!(write_fmt);
42 // match calls to std::io::stdout() / std::io::stderr ()
43 if !write_args.is_empty();
44 if let Some(dest_name) = if match_function_call(cx, &write_args[0], &paths::STDOUT).is_some() {
46 } else if match_function_call(cx, &write_args[0], &paths::STDERR).is_some() {
52 let write_span = unwrap_args[0].span;
54 // ordering is important here, since `writeln!` uses `write!` internally
55 if is_expn_of(write_span, "writeln").is_some() {
57 } else if is_expn_of(write_span, "write").is_some() {
62 let prefix = if dest_name == "stderr" {
68 // We need to remove the last trailing newline from the string because the
69 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
71 if let Some(mut write_output) = write_output_string(write_args) {
72 if write_output.ends_with('\n') {
76 if let Some(macro_name) = calling_macro {
82 "use of `{}!({}(), ...).unwrap()`",
87 format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
88 Applicability::MachineApplicable
95 &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
97 format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
98 Applicability::MachineApplicable
102 // We don't have a proper suggestion
103 if let Some(macro_name) = calling_macro {
109 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
113 macro_name.replace("write", "print")
121 &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
131 // Extract the output string from the given `write_args`.
132 fn write_output_string(write_args: &[Expr<'_>]) -> Option<String> {
134 // Obtain the string that should be printed
135 if write_args.len() > 1;
136 if let ExprKind::Call(_, ref output_args) = write_args[1].kind;
137 if !output_args.is_empty();
138 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref output_string_expr) = output_args[0].kind;
139 if let ExprKind::Array(ref string_exprs) = output_string_expr.kind;
140 // we only want to provide an automatic suggestion for simple (non-format) strings
141 if string_exprs.len() == 1;
142 if let ExprKind::Lit(ref lit) = string_exprs[0].kind;
143 if let LitKind::Str(ref write_output, _) = lit.node;
145 return Some(write_output.to_string())