From 5f007a88b4d650068525d4300aa9d773a572de11 Mon Sep 17 00:00:00 2001 From: Philipp Hansch Date: Sat, 24 Nov 2018 12:17:43 +0100 Subject: [PATCH] Extract method --- clippy_lints/src/explicit_write.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/clippy_lints/src/explicit_write.rs b/clippy_lints/src/explicit_write.rs index e2b643c4de6..996dc126ec1 100644 --- a/clippy_lints/src/explicit_write.rs +++ b/clippy_lints/src/explicit_write.rs @@ -51,15 +51,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { if unwrap_args.len() > 0; if let ExprKind::MethodCall(ref write_fun, _, ref write_args) = unwrap_args[0].node; - // Obtain the string that should be printed - if write_args.len() > 1; - if let ExprKind::Call(_, ref output_args) = write_args[1].node; - if output_args.len() > 0; - if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node; - if let ExprKind::Array(ref string_exprs) = output_string_expr.node; - if string_exprs.len() > 0; - if let ExprKind::Lit(ref lit) = string_exprs[0].node; - if let LitKind::Str(ref write_output, _) = lit.node; if write_fun.ident.name == "write_fmt"; // match calls to std::io::stdout() / std::io::stderr () if write_args.len() > 0; @@ -94,7 +85,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { // We need to remove the last trailing newline from the string because the // underlying `fmt::write` function doesn't know wether `println!` or `print!` was // used. - let mut write_output: String = write_output.to_string(); + let mut write_output: String = write_output_string(write_args).unwrap(); if write_output.ends_with('\n') { write_output.truncate(write_output.len() - 1) } @@ -125,3 +116,22 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { } } } + +// Extract the output string from the given `write_args`. +fn write_output_string(write_args: &HirVec) -> Option { + if_chain! { + // Obtain the string that should be printed + if write_args.len() > 1; + if let ExprKind::Call(_, ref output_args) = write_args[1].node; + if output_args.len() > 0; + if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node; + if let ExprKind::Array(ref string_exprs) = output_string_expr.node; + if string_exprs.len() > 0; + if let ExprKind::Lit(ref lit) = string_exprs[0].node; + if let LitKind::Str(ref write_output, _) = lit.node; + then { + return Some(write_output.to_string()) + } + } + None +}