1 use crate::utils::{is_try, match_trait_method, paths, span_lint};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 /// **What it does:** Checks for unused written/read amount.
9 /// **Why is this bad?** `io::Write::write(_vectored)` and
10 /// `io::Read::read(_vectored)` are not guaranteed to
11 /// process the entire buffer. They return how many bytes were processed, which
13 /// than a given buffer's length. If you don't need to deal with
14 /// partial-write/read, use
15 /// `write_all`/`read_exact` instead.
17 /// **Known problems:** Detects only common patterns.
22 /// fn foo<W: io::Write>(w: &mut W) -> io::Result<()> {
23 /// // must be `w.write_all(b"foo")?;`
30 "unused written/read amount"
33 declare_lint_pass!(UnusedIoAmount => [UNUSED_IO_AMOUNT]);
35 impl<'tcx> LateLintPass<'tcx> for UnusedIoAmount {
36 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
37 let expr = match s.kind {
38 hir::StmtKind::Semi(ref expr) | hir::StmtKind::Expr(ref expr) => &**expr,
43 hir::ExprKind::Match(ref res, _, _) if is_try(expr).is_some() => {
44 if let hir::ExprKind::Call(ref func, ref args) = res.kind {
47 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::TryIntoResult, _))
49 check_method_call(cx, &args[0], expr);
52 check_method_call(cx, res, expr);
56 hir::ExprKind::MethodCall(ref path, _, ref args, _) => match &*path.ident.as_str() {
57 "expect" | "unwrap" | "unwrap_or" | "unwrap_or_else" => {
58 check_method_call(cx, &args[0], expr);
68 fn check_method_call(cx: &LateContext<'_>, call: &hir::Expr<'_>, expr: &hir::Expr<'_>) {
69 if let hir::ExprKind::MethodCall(ref path, _, _, _) = call.kind {
70 let symbol = &*path.ident.as_str();
71 let read_trait = match_trait_method(cx, call, &paths::IO_READ);
72 let write_trait = match_trait_method(cx, call, &paths::IO_WRITE);
74 match (read_trait, write_trait, symbol) {
75 (true, _, "read") => span_lint(
79 "read amount is not handled. Use `Read::read_exact` instead",
81 (true, _, "read_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr.span, "read amount is not handled"),
82 (_, true, "write") => span_lint(
86 "written amount is not handled. Use `Write::write_all` instead",
88 (_, true, "write_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr.span, "written amount is not handled"),