2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use if_chain::if_chain;
5 use crate::utils::{is_expn_of, match_def_path, resolve_node, span_lint};
6 use crate::utils::opt_def_id;
8 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
9 /// replaced with `(e)print!()` / `(e)println!()`
11 /// **Why is this bad?** Using `(e)println! is clearer and more concise
13 /// **Known problems:** None.
17 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
18 /// writeln!(&mut io::stderr(), "foo: {:?}", bar).unwrap();
20 declare_clippy_lint! {
23 "using the `write!()` family of functions instead of the `print!()` family \
24 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)
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
37 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
39 // match call to unwrap
40 if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
41 if unwrap_fun.ident.name == "unwrap";
42 // match call to write_fmt
43 if unwrap_args.len() > 0;
44 if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
46 if write_fun.ident.name == "write_fmt";
47 // match calls to std::io::stdout() / std::io::stderr ()
48 if write_args.len() > 0;
49 if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
50 if let ExprKind::Path(ref qpath) = dest_fun.node;
51 if let Some(dest_fun_id) =
52 opt_def_id(resolve_node(cx, qpath, dest_fun.hir_id));
53 if let Some(dest_name) = if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stdout"]) {
55 } else if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stderr"]) {
61 let write_span = unwrap_args[0].span;
63 // ordering is important here, since `writeln!` uses `write!` internally
64 if is_expn_of(write_span, "writeln").is_some() {
66 } else if is_expn_of(write_span, "write").is_some() {
71 let prefix = if dest_name == "stderr" {
76 if let Some(macro_name) = calling_macro {
82 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
86 macro_name.replace("write", "print")
95 "use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead",