1 use crate::utils::{is_expn_of, match_def_path, paths, resolve_node, span_lint, span_lint_and_sugg};
2 use if_chain::if_chain;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6 use rustc_errors::Applicability;
7 use syntax::ast::LitKind;
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 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
20 /// writeln!(&mut io::stderr(), "foo: {:?}", bar).unwrap();
24 "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
27 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
29 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitWrite {
30 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
32 // match call to unwrap
33 if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
34 if unwrap_fun.ident.name == sym!(unwrap);
35 // match call to write_fmt
36 if unwrap_args.len() > 0;
37 if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
39 if write_fun.ident.name == sym!(write_fmt);
40 // match calls to std::io::stdout() / std::io::stderr ()
41 if write_args.len() > 0;
42 if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
43 if let ExprKind::Path(ref qpath) = dest_fun.node;
44 if let Some(dest_fun_id) = resolve_node(cx, qpath, dest_fun.hir_id).opt_def_id();
45 if let Some(dest_name) = if match_def_path(cx, dest_fun_id, &paths::STDOUT) {
47 } else if match_def_path(cx, dest_fun_id, &paths::STDERR) {
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: &HirVec<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].node;
138 if output_args.len() > 0;
139 if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node;
140 if let ExprKind::Array(ref string_exprs) = output_string_expr.node;
141 if string_exprs.len() > 0;
142 if let ExprKind::Lit(ref lit) = string_exprs[0].node;
143 if let LitKind::Str(ref write_output, _) = lit.node;
145 return Some(write_output.to_string())