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