1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::paths;
3 use clippy_utils::ty::match_type;
4 use if_chain::if_chain;
5 use rustc_hir::{Expr, ExprKind, QPath};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 /// Checks for use of File::read_to_end and File::read_to_string.
13 /// ### Why is this bad?
14 /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
15 /// See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)
19 /// # use std::io::Read;
20 /// # use std::fs::File;
21 /// let mut f = File::open("foo.txt").unwrap();
22 /// let mut bytes = Vec::new();
23 /// f.read_to_end(&mut bytes).unwrap();
25 /// Can be written more concisely as
28 /// let mut bytes = fs::read("foo.txt").unwrap();
30 pub VERBOSE_FILE_READS,
32 "use of `File::read_to_end` or `File::read_to_string`"
35 declare_lint_pass!(VerboseFileReads => [VERBOSE_FILE_READS]);
37 impl<'tcx> LateLintPass<'tcx> for VerboseFileReads {
38 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
39 if is_file_read_to_end(cx, expr) {
44 "use of `File::read_to_end`",
46 "consider using `fs::read` instead",
48 } else if is_file_read_to_string(cx, expr) {
53 "use of `File::read_to_string`",
55 "consider using `fs::read_to_string` instead",
61 fn is_file_read_to_end<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
63 if let ExprKind::MethodCall(method_name, _, exprs, _) = expr.kind;
64 if method_name.ident.as_str() == "read_to_end";
65 if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind;
66 let ty = cx.typeck_results().expr_ty(&exprs[0]);
67 if match_type(cx, ty, &paths::FILE);
75 fn is_file_read_to_string<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
77 if let ExprKind::MethodCall(method_name, _, exprs, _) = expr.kind;
78 if method_name.ident.as_str() == "read_to_string";
79 if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind;
80 let ty = cx.typeck_results().expr_ty(&exprs[0]);
81 if match_type(cx, ty, &paths::FILE);