1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::utils::{is_expn_of, match_def_path, opt_def_id, resolve_node, span_lint, span_lint_and_sugg};
11 use if_chain::if_chain;
13 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use rustc::{declare_tool_lint, lint_array};
15 use rustc_errors::Applicability;
16 use syntax::ast::LitKind;
18 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
19 /// replaced with `(e)print!()` / `(e)println!()`
21 /// **Why is this bad?** Using `(e)println! is clearer and more concise
23 /// **Known problems:** None.
27 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
28 /// writeln!(&mut io::stderr(), "foo: {:?}", bar).unwrap();
30 declare_clippy_lint! {
33 "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
36 #[derive(Copy, Clone, Debug)]
39 impl LintPass for Pass {
40 fn get_lints(&self) -> LintArray {
41 lint_array!(EXPLICIT_WRITE)
45 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
46 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48 // match call to unwrap
49 if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
50 if unwrap_fun.ident.name == "unwrap";
51 // match call to write_fmt
52 if unwrap_args.len() > 0;
53 if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
55 if write_fun.ident.name == "write_fmt";
56 // match calls to std::io::stdout() / std::io::stderr ()
57 if write_args.len() > 0;
58 if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
59 if let ExprKind::Path(ref qpath) = dest_fun.node;
60 if let Some(dest_fun_id) =
61 opt_def_id(resolve_node(cx, qpath, dest_fun.hir_id));
62 if let Some(dest_name) = if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stdout"]) {
64 } else if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stderr"]) {
70 let write_span = unwrap_args[0].span;
72 // ordering is important here, since `writeln!` uses `write!` internally
73 if is_expn_of(write_span, "writeln").is_some() {
75 } else if is_expn_of(write_span, "write").is_some() {
80 let prefix = if dest_name == "stderr" {
86 // We need to remove the last trailing newline from the string because the
87 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
89 if let Some(mut write_output) = write_output_string(write_args) {
90 if write_output.ends_with('\n') {
94 if let Some(macro_name) = calling_macro {
100 "use of `{}!({}(), ...).unwrap()`",
105 format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
106 Applicability::MachineApplicable
113 &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
115 format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
116 Applicability::MachineApplicable
120 // We don't have a proper suggestion
121 if let Some(macro_name) = calling_macro {
127 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
131 macro_name.replace("write", "print")
139 &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
149 // Extract the output string from the given `write_args`.
150 fn write_output_string(write_args: &HirVec<Expr>) -> Option<String> {
152 // Obtain the string that should be printed
153 if write_args.len() > 1;
154 if let ExprKind::Call(_, ref output_args) = write_args[1].node;
155 if output_args.len() > 0;
156 if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node;
157 if let ExprKind::Array(ref string_exprs) = output_string_expr.node;
158 if string_exprs.len() > 0;
159 if let ExprKind::Lit(ref lit) = string_exprs[0].node;
160 if let LitKind::Str(ref write_output, _) = lit.node;
162 return Some(write_output.to_string())