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)
12 /// **Known problems:** None.
17 /// # use std::io::Read;
18 /// # use std::fs::File;
19 /// let mut f = File::open("foo.txt").unwrap();
20 /// let mut bytes = Vec::new();
21 /// f.read_to_end(&mut bytes).unwrap();
23 /// Can be written more concisely as
26 /// let mut bytes = fs::read("foo.txt").unwrap();
28 pub VERBOSE_FILE_READS,
30 "use of `File::read_to_end` or `File::read_to_string`"
33 declare_lint_pass!(VerboseFileReads => [VERBOSE_FILE_READS]);
35 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VerboseFileReads {
36 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
37 if is_file_read_to_end(cx, expr) {
42 "use of `File::read_to_end`",
44 "consider using `fs::read` instead",
46 } else if is_file_read_to_string(cx, expr) {
51 "use of `File::read_to_string`",
53 "consider using `fs::read_to_string` instead",
59 fn is_file_read_to_end<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
61 if let ExprKind::MethodCall(method_name, _, exprs) = expr.kind;
62 if method_name.ident.as_str() == "read_to_end";
63 if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind;
64 let ty = cx.tables.expr_ty(&exprs[0]);
65 if match_type(cx, ty, &paths::FILE);
73 fn is_file_read_to_string<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
75 if let ExprKind::MethodCall(method_name, _, exprs) = expr.kind;
76 if method_name.ident.as_str() == "read_to_string";
77 if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind;
78 let ty = cx.tables.expr_ty(&exprs[0]);
79 if match_type(cx, ty, &paths::FILE);