3 use utils
::{is_expn_of, match_def_path, resolve_node, span_lint}
;
6 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
7 /// replaced with `(e)print!()` / `(e)println!()`
9 /// **Why is this bad?** Using `(e)println! is clearer and more concise
11 /// **Known problems:** None.
15 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
16 /// writeln!(&mut io::stderr(), "foo: {:?}", bar).unwrap();
21 "using the `write!()` family of functions instead of the `print!()` family \
22 of functions, when using the latter would work"
25 #[derive(Copy, Clone, Debug)]
28 impl LintPass
for Pass
{
29 fn get_lints(&self) -> LintArray
{
30 lint_array
!(EXPLICIT_WRITE
)
34 impl<'a
, 'tcx
> LateLintPass
<'a
, 'tcx
> for Pass
{
35 fn check_expr(&mut self, cx
: &LateContext
<'a
, 'tcx
>, expr
: &'tcx Expr
) {
37 // match call to unwrap
38 if let ExprMethodCall(ref unwrap_fun
, _
, ref unwrap_args
) = expr
.node
;
39 if unwrap_fun
.name
== "unwrap";
40 // match call to write_fmt
41 if unwrap_args
.len() > 0;
42 if let ExprMethodCall(ref write_fun
, _
, ref write_args
) =
44 if write_fun
.name
== "write_fmt";
45 // match calls to std::io::stdout() / std::io::stderr ()
46 if write_args
.len() > 0;
47 if let ExprCall(ref dest_fun
, _
) = write_args
[0].node
;
48 if let ExprPath(ref qpath
) = dest_fun
.node
;
49 if let Some(dest_fun_id
) =
50 opt_def_id(resolve_node(cx
, qpath
, dest_fun
.hir_id
));
51 if let Some(dest_name
) = if match_def_path(cx
.tcx
, dest_fun_id
, &["std", "io", "stdio", "stdout"]) {
53 } else if match_def_path(cx
.tcx
, dest_fun_id
, &["std", "io", "stdio", "stderr"]) {
59 let write_span
= unwrap_args
[0].span
;
61 // ordering is important here, since `writeln!` uses `write!` internally
62 if is_expn_of(write_span
, "writeln").is_some() {
64 } else if is_expn_of(write_span
, "write").is_some() {
69 let prefix
= if dest_name
== "stderr" {
74 if let Some(macro_name
) = calling_macro
{
80 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
84 macro_name
.replace("write", "print")
93 "use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead",