]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/open_options.rs
Auto merge of #82760 - WaffleLapkin:unleak_extend_from_within, r=kennytm
[rust.git] / src / tools / clippy / clippy_lints / src / open_options.rs
1 use crate::utils::{match_type, paths, span_lint};
2 use rustc_ast::ast::LitKind;
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::source_map::{Span, Spanned};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for duplicate open options as well as combinations
10     /// that make no sense.
11     ///
12     /// **Why is this bad?** In the best case, the code will be harder to read than
13     /// necessary. I don't know the worst case.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// use std::fs::OpenOptions;
20     ///
21     /// OpenOptions::new().read(true).truncate(true);
22     /// ```
23     pub NONSENSICAL_OPEN_OPTIONS,
24     correctness,
25     "nonsensical combination of options for opening a file"
26 }
27
28 declare_lint_pass!(OpenOptions => [NONSENSICAL_OPEN_OPTIONS]);
29
30 impl<'tcx> LateLintPass<'tcx> for OpenOptions {
31     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
32         if let ExprKind::MethodCall(ref path, _, ref arguments, _) = e.kind {
33             let obj_ty = cx.typeck_results().expr_ty(&arguments[0]).peel_refs();
34             if path.ident.name == sym!(open) && match_type(cx, obj_ty, &paths::OPEN_OPTIONS) {
35                 let mut options = Vec::new();
36                 get_open_options(cx, &arguments[0], &mut options);
37                 check_open_options(cx, &options, e.span);
38             }
39         }
40     }
41 }
42
43 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
44 enum Argument {
45     True,
46     False,
47     Unknown,
48 }
49
50 #[derive(Debug)]
51 enum OpenOption {
52     Write,
53     Read,
54     Truncate,
55     Create,
56     Append,
57 }
58
59 fn get_open_options(cx: &LateContext<'_>, argument: &Expr<'_>, options: &mut Vec<(OpenOption, Argument)>) {
60     if let ExprKind::MethodCall(ref path, _, ref arguments, _) = argument.kind {
61         let obj_ty = cx.typeck_results().expr_ty(&arguments[0]).peel_refs();
62
63         // Only proceed if this is a call on some object of type std::fs::OpenOptions
64         if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 2 {
65             let argument_option = match arguments[1].kind {
66                 ExprKind::Lit(ref span) => {
67                     if let Spanned {
68                         node: LitKind::Bool(lit),
69                         ..
70                     } = *span
71                     {
72                         if lit { Argument::True } else { Argument::False }
73                     } else {
74                         // The function is called with a literal which is not a boolean literal.
75                         // This is theoretically possible, but not very likely.
76                         return;
77                     }
78                 },
79                 _ => Argument::Unknown,
80             };
81
82             match &*path.ident.as_str() {
83                 "create" => {
84                     options.push((OpenOption::Create, argument_option));
85                 },
86                 "append" => {
87                     options.push((OpenOption::Append, argument_option));
88                 },
89                 "truncate" => {
90                     options.push((OpenOption::Truncate, argument_option));
91                 },
92                 "read" => {
93                     options.push((OpenOption::Read, argument_option));
94                 },
95                 "write" => {
96                     options.push((OpenOption::Write, argument_option));
97                 },
98                 _ => (),
99             }
100
101             get_open_options(cx, &arguments[0], options);
102         }
103     }
104 }
105
106 fn check_open_options(cx: &LateContext<'_>, options: &[(OpenOption, Argument)], span: Span) {
107     let (mut create, mut append, mut truncate, mut read, mut write) = (false, false, false, false, false);
108     let (mut create_arg, mut append_arg, mut truncate_arg, mut read_arg, mut write_arg) =
109         (false, false, false, false, false);
110     // This code is almost duplicated (oh, the irony), but I haven't found a way to
111     // unify it.
112
113     for option in options {
114         match *option {
115             (OpenOption::Create, arg) => {
116                 if create {
117                     span_lint(
118                         cx,
119                         NONSENSICAL_OPEN_OPTIONS,
120                         span,
121                         "the method `create` is called more than once",
122                     );
123                 } else {
124                     create = true
125                 }
126                 create_arg = create_arg || (arg == Argument::True);
127             },
128             (OpenOption::Append, arg) => {
129                 if append {
130                     span_lint(
131                         cx,
132                         NONSENSICAL_OPEN_OPTIONS,
133                         span,
134                         "the method `append` is called more than once",
135                     );
136                 } else {
137                     append = true
138                 }
139                 append_arg = append_arg || (arg == Argument::True);
140             },
141             (OpenOption::Truncate, arg) => {
142                 if truncate {
143                     span_lint(
144                         cx,
145                         NONSENSICAL_OPEN_OPTIONS,
146                         span,
147                         "the method `truncate` is called more than once",
148                     );
149                 } else {
150                     truncate = true
151                 }
152                 truncate_arg = truncate_arg || (arg == Argument::True);
153             },
154             (OpenOption::Read, arg) => {
155                 if read {
156                     span_lint(
157                         cx,
158                         NONSENSICAL_OPEN_OPTIONS,
159                         span,
160                         "the method `read` is called more than once",
161                     );
162                 } else {
163                     read = true
164                 }
165                 read_arg = read_arg || (arg == Argument::True);
166             },
167             (OpenOption::Write, arg) => {
168                 if write {
169                     span_lint(
170                         cx,
171                         NONSENSICAL_OPEN_OPTIONS,
172                         span,
173                         "the method `write` is called more than once",
174                     );
175                 } else {
176                     write = true
177                 }
178                 write_arg = write_arg || (arg == Argument::True);
179             },
180         }
181     }
182
183     if read && truncate && read_arg && truncate_arg && !(write && write_arg) {
184         span_lint(
185             cx,
186             NONSENSICAL_OPEN_OPTIONS,
187             span,
188             "file opened with `truncate` and `read`",
189         );
190     }
191     if append && truncate && append_arg && truncate_arg {
192         span_lint(
193             cx,
194             NONSENSICAL_OPEN_OPTIONS,
195             span,
196             "file opened with `append` and `truncate`",
197         );
198     }
199 }