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_try, match_qpath, match_trait_method, paths, span_lint};
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::{declare_tool_lint, lint_array};
15 /// **What it does:** Checks for unused written/read amount.
17 /// **Why is this bad?** `io::Write::write` and `io::Read::read` are not
19 /// process the entire buffer. They return how many bytes were processed, which
21 /// than a given buffer's length. If you don't need to deal with
22 /// partial-write/read, use
23 /// `write_all`/`read_exact` instead.
25 /// **Known problems:** Detects only common patterns.
30 /// fn foo<W: io::Write>(w: &mut W) -> io::Result<()> {
31 /// // must be `w.write_all(b"foo")?;`
36 declare_clippy_lint! {
39 "unused written/read amount"
42 pub struct UnusedIoAmount;
44 impl LintPass for UnusedIoAmount {
45 fn get_lints(&self) -> LintArray {
46 lint_array!(UNUSED_IO_AMOUNT)
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedIoAmount {
51 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
52 let expr = match s.node {
53 hir::StmtKind::Semi(ref expr, _) | hir::StmtKind::Expr(ref expr, _) => &**expr,
58 hir::ExprKind::Match(ref res, _, _) if is_try(expr).is_some() => {
59 if let hir::ExprKind::Call(ref func, ref args) = res.node {
60 if let hir::ExprKind::Path(ref path) = func.node {
61 if match_qpath(path, &paths::TRY_INTO_RESULT) && args.len() == 1 {
62 check_method_call(cx, &args[0], expr);
66 check_method_call(cx, res, expr);
70 hir::ExprKind::MethodCall(ref path, _, ref args) => match &*path.ident.as_str() {
71 "expect" | "unwrap" | "unwrap_or" | "unwrap_or_else" => {
72 check_method_call(cx, &args[0], expr);
82 fn check_method_call(cx: &LateContext<'_, '_>, call: &hir::Expr, expr: &hir::Expr) {
83 if let hir::ExprKind::MethodCall(ref path, _, _) = call.node {
84 let symbol = &*path.ident.as_str();
85 if match_trait_method(cx, call, &paths::IO_READ) && symbol == "read" {
90 "handle read amount returned or use `Read::read_exact` instead",
92 } else if match_trait_method(cx, call, &paths::IO_WRITE) && symbol == "write" {
97 "handle written amount returned or use `Write::write_all` instead",