1 use crate::utils::{match_type, paths, span_lint_and_help};
2 use if_chain::if_chain;
3 use rustc_hir::{Expr, ExprKind, QPath};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 /// **What it does:** Checks for use of File::read_to_end and File::read_to_string.
10 /// **Why is this bad?** `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
11 /// 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)
13 /// **Known problems:** None.
18 /// # use std::io::Read;
19 /// # use std::fs::File;
20 /// let mut f = File::open("foo.txt").unwrap();
21 /// let mut bytes = Vec::new();
22 /// f.read_to_end(&mut bytes).unwrap();
24 /// Can be written more concisely as
27 /// let mut bytes = fs::read("foo.txt").unwrap();
29 pub VERBOSE_FILE_READS,
31 "use of `File::read_to_end` or `File::read_to_string`"
34 declare_lint_pass!(VerboseFileReads => [VERBOSE_FILE_READS]);
36 impl<'tcx> LateLintPass<'tcx> for VerboseFileReads {
37 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
38 if is_file_read_to_end(cx, expr) {
43 "use of `File::read_to_end`",
45 "consider using `fs::read` instead",
47 } else if is_file_read_to_string(cx, expr) {
52 "use of `File::read_to_string`",
54 "consider using `fs::read_to_string` instead",
60 fn is_file_read_to_end<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
62 if let ExprKind::MethodCall(method_name, _, exprs, _) = expr.kind;
63 if method_name.ident.as_str() == "read_to_end";
64 if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind;
65 let ty = cx.tables().expr_ty(&exprs[0]);
66 if match_type(cx, ty, &paths::FILE);
74 fn is_file_read_to_string<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
76 if let ExprKind::MethodCall(method_name, _, exprs, _) = expr.kind;
77 if method_name.ident.as_str() == "read_to_string";
78 if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind;
79 let ty = cx.tables().expr_ty(&exprs[0]);
80 if match_type(cx, ty, &paths::FILE);