]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/open_options.rs
e99d0317ba2e8ca1b6e3bcf5744ec4071931c1da
[rust.git] / clippy_lints / src / open_options.rs
1 use crate::utils::{match_type, paths, span_lint, walk_ptrs_ty};
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 = walk_ptrs_ty(cx.typeck_results().expr_ty(&arguments[0]));
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 = walk_ptrs_ty(cx.typeck_results().expr_ty(&arguments[0]));
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 {
73                             Argument::True
74                         } else {
75                             Argument::False
76                         }
77                     } else {
78                         return; // The function is called with a literal
79                                 // which is not a boolean literal. This is theoretically
80                                 // possible, but not very likely.
81                     }
82                 },
83                 _ => Argument::Unknown,
84             };
85
86             match &*path.ident.as_str() {
87                 "create" => {
88                     options.push((OpenOption::Create, argument_option));
89                 },
90                 "append" => {
91                     options.push((OpenOption::Append, argument_option));
92                 },
93                 "truncate" => {
94                     options.push((OpenOption::Truncate, argument_option));
95                 },
96                 "read" => {
97                     options.push((OpenOption::Read, argument_option));
98                 },
99                 "write" => {
100                     options.push((OpenOption::Write, argument_option));
101                 },
102                 _ => (),
103             }
104
105             get_open_options(cx, &arguments[0], options);
106         }
107     }
108 }
109
110 fn check_open_options(cx: &LateContext<'_>, options: &[(OpenOption, Argument)], span: Span) {
111     let (mut create, mut append, mut truncate, mut read, mut write) = (false, false, false, false, false);
112     let (mut create_arg, mut append_arg, mut truncate_arg, mut read_arg, mut write_arg) =
113         (false, false, false, false, false);
114     // This code is almost duplicated (oh, the irony), but I haven't found a way to
115     // unify it.
116
117     for option in options {
118         match *option {
119             (OpenOption::Create, arg) => {
120                 if create {
121                     span_lint(
122                         cx,
123                         NONSENSICAL_OPEN_OPTIONS,
124                         span,
125                         "the method `create` is called more than once",
126                     );
127                 } else {
128                     create = true
129                 }
130                 create_arg = create_arg || (arg == Argument::True);
131             },
132             (OpenOption::Append, arg) => {
133                 if append {
134                     span_lint(
135                         cx,
136                         NONSENSICAL_OPEN_OPTIONS,
137                         span,
138                         "the method `append` is called more than once",
139                     );
140                 } else {
141                     append = true
142                 }
143                 append_arg = append_arg || (arg == Argument::True);
144             },
145             (OpenOption::Truncate, arg) => {
146                 if truncate {
147                     span_lint(
148                         cx,
149                         NONSENSICAL_OPEN_OPTIONS,
150                         span,
151                         "the method `truncate` is called more than once",
152                     );
153                 } else {
154                     truncate = true
155                 }
156                 truncate_arg = truncate_arg || (arg == Argument::True);
157             },
158             (OpenOption::Read, arg) => {
159                 if read {
160                     span_lint(
161                         cx,
162                         NONSENSICAL_OPEN_OPTIONS,
163                         span,
164                         "the method `read` is called more than once",
165                     );
166                 } else {
167                     read = true
168                 }
169                 read_arg = read_arg || (arg == Argument::True);
170             },
171             (OpenOption::Write, arg) => {
172                 if write {
173                     span_lint(
174                         cx,
175                         NONSENSICAL_OPEN_OPTIONS,
176                         span,
177                         "the method `write` is called more than once",
178                     );
179                 } else {
180                     write = true
181                 }
182                 write_arg = write_arg || (arg == Argument::True);
183             },
184         }
185     }
186
187     if read && truncate && read_arg && truncate_arg && !(write && write_arg) {
188         span_lint(
189             cx,
190             NONSENSICAL_OPEN_OPTIONS,
191             span,
192             "file opened with `truncate` and `read`",
193         );
194     }
195     if append && truncate && append_arg && truncate_arg {
196         span_lint(
197             cx,
198             NONSENSICAL_OPEN_OPTIONS,
199             span,
200             "file opened with `append` and `truncate`",
201         );
202     }
203 }