1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{is_try, match_trait_method, paths};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 /// Checks for unused written/read amount.
11 /// ### Why is this bad?
12 /// `io::Write::write(_vectored)` and
13 /// `io::Read::read(_vectored)` are not guaranteed to
14 /// process the entire buffer. They return how many bytes were processed, which
16 /// than a given buffer's length. If you don't need to deal with
17 /// partial-write/read, use
18 /// `write_all`/`read_exact` instead.
20 /// ### Known problems
21 /// Detects only common patterns.
26 /// fn foo<W: io::Write>(w: &mut W) -> io::Result<()> {
27 /// // must be `w.write_all(b"foo")?;`
32 #[clippy::version = "pre 1.29.0"]
35 "unused written/read amount"
38 declare_lint_pass!(UnusedIoAmount => [UNUSED_IO_AMOUNT]);
40 impl<'tcx> LateLintPass<'tcx> for UnusedIoAmount {
41 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
42 let expr = match s.kind {
43 hir::StmtKind::Semi(expr) | hir::StmtKind::Expr(expr) => expr,
48 hir::ExprKind::Match(res, _, _) if is_try(cx, expr).is_some() => {
49 if let hir::ExprKind::Call(func, [ref arg_0, ..]) = res.kind {
52 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::TryTraitBranch, _))
54 check_map_error(cx, arg_0, expr);
57 check_map_error(cx, res, expr);
60 hir::ExprKind::MethodCall(path, _, [ref arg_0, ..], _) => match &*path.ident.as_str() {
61 "expect" | "unwrap" | "unwrap_or" | "unwrap_or_else" => {
62 check_map_error(cx, arg_0, expr);
71 fn check_map_error(cx: &LateContext<'_>, call: &hir::Expr<'_>, expr: &hir::Expr<'_>) {
73 while let hir::ExprKind::MethodCall(path, _, args, _) = call.kind {
74 if matches!(&*path.ident.as_str(), "or" | "or_else" | "ok") {
80 check_method_call(cx, call, expr);
83 fn check_method_call(cx: &LateContext<'_>, call: &hir::Expr<'_>, expr: &hir::Expr<'_>) {
84 if let hir::ExprKind::MethodCall(path, _, _, _) = call.kind {
85 let symbol = &*path.ident.as_str();
86 let read_trait = match_trait_method(cx, call, &paths::IO_READ);
87 let write_trait = match_trait_method(cx, call, &paths::IO_WRITE);
89 match (read_trait, write_trait, symbol) {
90 (true, _, "read") => span_lint(
94 "read amount is not handled. Use `Read::read_exact` instead",
96 (true, _, "read_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr.span, "read amount is not handled"),
97 (_, true, "write") => span_lint(
101 "written amount is not handled. Use `Write::write_all` instead",
103 (_, true, "write_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr.span, "written amount is not handled"),