1 use crate::utils::{is_expn_of, match_def_path, 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_tool_lint, lint_array};
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 #[derive(Copy, Clone, Debug)]
30 impl LintPass for Pass {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(EXPLICIT_WRITE)
35 fn name(&self) -> &'static str {
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
43 // match call to unwrap
44 if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
45 if unwrap_fun.ident.name == "unwrap";
46 // match call to write_fmt
47 if unwrap_args.len() > 0;
48 if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
50 if write_fun.ident.name == "write_fmt";
51 // match calls to std::io::stdout() / std::io::stderr ()
52 if write_args.len() > 0;
53 if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
54 if let ExprKind::Path(ref qpath) = dest_fun.node;
55 if let Some(dest_fun_id) =
56 resolve_node(cx, qpath, dest_fun.hir_id).opt_def_id();
57 if let Some(dest_name) = if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stdout"]) {
59 } else if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stderr"]) {
65 let write_span = unwrap_args[0].span;
67 // ordering is important here, since `writeln!` uses `write!` internally
68 if is_expn_of(write_span, "writeln").is_some() {
70 } else if is_expn_of(write_span, "write").is_some() {
75 let prefix = if dest_name == "stderr" {
81 // We need to remove the last trailing newline from the string because the
82 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
84 if let Some(mut write_output) = write_output_string(write_args) {
85 if write_output.ends_with('\n') {
89 if let Some(macro_name) = calling_macro {
95 "use of `{}!({}(), ...).unwrap()`",
100 format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
101 Applicability::MachineApplicable
108 &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
110 format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
111 Applicability::MachineApplicable
115 // We don't have a proper suggestion
116 if let Some(macro_name) = calling_macro {
122 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
126 macro_name.replace("write", "print")
134 &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
144 // Extract the output string from the given `write_args`.
145 fn write_output_string(write_args: &HirVec<Expr>) -> Option<String> {
147 // Obtain the string that should be printed
148 if write_args.len() > 1;
149 if let ExprKind::Call(_, ref output_args) = write_args[1].node;
150 if output_args.len() > 0;
151 if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node;
152 if let ExprKind::Array(ref string_exprs) = output_string_expr.node;
153 if string_exprs.len() > 0;
154 if let ExprKind::Lit(ref lit) = string_exprs[0].node;
155 if let LitKind::Str(ref write_output, _) = lit.node;
157 return Some(write_output.to_string())