]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/index_refutable_slice.rs
Rollup merge of #101266 - LuisCardosoOliveira:translation-rustcsession-pt3, r=davidtwco
[rust.git] / src / tools / clippy / clippy_lints / src / index_refutable_slice.rs
1 use clippy_utils::consts::{constant, Constant};
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::higher::IfLet;
4 use clippy_utils::ty::is_copy;
5 use clippy_utils::{is_expn_of, is_lint_allowed, meets_msrv, msrvs, path_to_local};
6 use if_chain::if_chain;
7 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
8 use rustc_errors::Applicability;
9 use rustc_hir as hir;
10 use rustc_hir::intravisit::{self, Visitor};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::hir::nested_filter;
13 use rustc_middle::ty;
14 use rustc_semver::RustcVersion;
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_span::{symbol::Ident, Span};
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// The lint checks for slice bindings in patterns that are only used to
21     /// access individual slice values.
22     ///
23     /// ### Why is this bad?
24     /// Accessing slice values using indices can lead to panics. Using refutable
25     /// patterns can avoid these. Binding to individual values also improves the
26     /// readability as they can be named.
27     ///
28     /// ### Limitations
29     /// This lint currently only checks for immutable access inside `if let`
30     /// patterns.
31     ///
32     /// ### Example
33     /// ```rust
34     /// let slice: Option<&[u32]> = Some(&[1, 2, 3]);
35     ///
36     /// if let Some(slice) = slice {
37     ///     println!("{}", slice[0]);
38     /// }
39     /// ```
40     /// Use instead:
41     /// ```rust
42     /// let slice: Option<&[u32]> = Some(&[1, 2, 3]);
43     ///
44     /// if let Some(&[first, ..]) = slice {
45     ///     println!("{}", first);
46     /// }
47     /// ```
48     #[clippy::version = "1.59.0"]
49     pub INDEX_REFUTABLE_SLICE,
50     nursery,
51     "avoid indexing on slices which could be destructed"
52 }
53
54 #[derive(Copy, Clone)]
55 pub struct IndexRefutableSlice {
56     max_suggested_slice: u64,
57     msrv: Option<RustcVersion>,
58 }
59
60 impl IndexRefutableSlice {
61     pub fn new(max_suggested_slice_pattern_length: u64, msrv: Option<RustcVersion>) -> Self {
62         Self {
63             max_suggested_slice: max_suggested_slice_pattern_length,
64             msrv,
65         }
66     }
67 }
68
69 impl_lint_pass!(IndexRefutableSlice => [INDEX_REFUTABLE_SLICE]);
70
71 impl<'tcx> LateLintPass<'tcx> for IndexRefutableSlice {
72     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
73         if_chain! {
74             if !expr.span.from_expansion() || is_expn_of(expr.span, "if_chain").is_some();
75             if let Some(IfLet {let_pat, if_then, ..}) = IfLet::hir(cx, expr);
76             if !is_lint_allowed(cx, INDEX_REFUTABLE_SLICE, expr.hir_id);
77             if meets_msrv(self.msrv, msrvs::SLICE_PATTERNS);
78
79             let found_slices = find_slice_values(cx, let_pat);
80             if !found_slices.is_empty();
81             let filtered_slices = filter_lintable_slices(cx, found_slices, self.max_suggested_slice, if_then);
82             if !filtered_slices.is_empty();
83             then {
84                 for slice in filtered_slices.values() {
85                     lint_slice(cx, slice);
86                 }
87             }
88         }
89     }
90
91     extract_msrv_attr!(LateContext);
92 }
93
94 fn find_slice_values(cx: &LateContext<'_>, pat: &hir::Pat<'_>) -> FxIndexMap<hir::HirId, SliceLintInformation> {
95     let mut removed_pat: FxHashSet<hir::HirId> = FxHashSet::default();
96     let mut slices: FxIndexMap<hir::HirId, SliceLintInformation> = FxIndexMap::default();
97     pat.walk_always(|pat| {
98         // We'll just ignore mut and ref mut for simplicity sake right now
99         if let hir::PatKind::Binding(
100             hir::BindingAnnotation(by_ref, hir::Mutability::Not),
101             value_hir_id,
102             ident,
103             sub_pat,
104         ) = pat.kind
105         {
106             // This block catches bindings with sub patterns. It would be hard to build a correct suggestion
107             // for them and it's likely that the user knows what they are doing in such a case.
108             if removed_pat.contains(&value_hir_id) {
109                 return;
110             }
111             if sub_pat.is_some() {
112                 removed_pat.insert(value_hir_id);
113                 slices.remove(&value_hir_id);
114                 return;
115             }
116
117             let bound_ty = cx.typeck_results().node_type(pat.hir_id);
118             if let ty::Slice(inner_ty) | ty::Array(inner_ty, _) = bound_ty.peel_refs().kind() {
119                 // The values need to use the `ref` keyword if they can't be copied.
120                 // This will need to be adjusted if the lint want to support mutable access in the future
121                 let src_is_ref = bound_ty.is_ref() && by_ref != hir::ByRef::Yes;
122                 let needs_ref = !(src_is_ref || is_copy(cx, *inner_ty));
123
124                 let slice_info = slices
125                     .entry(value_hir_id)
126                     .or_insert_with(|| SliceLintInformation::new(ident, needs_ref));
127                 slice_info.pattern_spans.push(pat.span);
128             }
129         }
130     });
131
132     slices
133 }
134
135 fn lint_slice(cx: &LateContext<'_>, slice: &SliceLintInformation) {
136     let used_indices = slice
137         .index_use
138         .iter()
139         .map(|(index, _)| *index)
140         .collect::<FxHashSet<_>>();
141
142     let value_name = |index| format!("{}_{}", slice.ident.name, index);
143
144     if let Some(max_index) = used_indices.iter().max() {
145         let opt_ref = if slice.needs_ref { "ref " } else { "" };
146         let pat_sugg_idents = (0..=*max_index)
147             .map(|index| {
148                 if used_indices.contains(&index) {
149                     format!("{}{}", opt_ref, value_name(index))
150                 } else {
151                     "_".to_string()
152                 }
153             })
154             .collect::<Vec<_>>();
155         let pat_sugg = format!("[{}, ..]", pat_sugg_idents.join(", "));
156
157         span_lint_and_then(
158             cx,
159             INDEX_REFUTABLE_SLICE,
160             slice.ident.span,
161             "this binding can be a slice pattern to avoid indexing",
162             |diag| {
163                 diag.multipart_suggestion(
164                     "try using a slice pattern here",
165                     slice
166                         .pattern_spans
167                         .iter()
168                         .map(|span| (*span, pat_sugg.clone()))
169                         .collect(),
170                     Applicability::MaybeIncorrect,
171                 );
172
173                 diag.multipart_suggestion(
174                     "and replace the index expressions here",
175                     slice
176                         .index_use
177                         .iter()
178                         .map(|(index, span)| (*span, value_name(*index)))
179                         .collect(),
180                     Applicability::MaybeIncorrect,
181                 );
182
183                 // The lint message doesn't contain a warning about the removed index expression,
184                 // since `filter_lintable_slices` will only return slices where all access indices
185                 // are known at compile time. Therefore, they can be removed without side effects.
186             },
187         );
188     }
189 }
190
191 #[derive(Debug)]
192 struct SliceLintInformation {
193     ident: Ident,
194     needs_ref: bool,
195     pattern_spans: Vec<Span>,
196     index_use: Vec<(u64, Span)>,
197 }
198
199 impl SliceLintInformation {
200     fn new(ident: Ident, needs_ref: bool) -> Self {
201         Self {
202             ident,
203             needs_ref,
204             pattern_spans: Vec::new(),
205             index_use: Vec::new(),
206         }
207     }
208 }
209
210 fn filter_lintable_slices<'a, 'tcx>(
211     cx: &'a LateContext<'tcx>,
212     slice_lint_info: FxIndexMap<hir::HirId, SliceLintInformation>,
213     max_suggested_slice: u64,
214     scope: &'tcx hir::Expr<'tcx>,
215 ) -> FxIndexMap<hir::HirId, SliceLintInformation> {
216     let mut visitor = SliceIndexLintingVisitor {
217         cx,
218         slice_lint_info,
219         max_suggested_slice,
220     };
221
222     intravisit::walk_expr(&mut visitor, scope);
223
224     visitor.slice_lint_info
225 }
226
227 struct SliceIndexLintingVisitor<'a, 'tcx> {
228     cx: &'a LateContext<'tcx>,
229     slice_lint_info: FxIndexMap<hir::HirId, SliceLintInformation>,
230     max_suggested_slice: u64,
231 }
232
233 impl<'a, 'tcx> Visitor<'tcx> for SliceIndexLintingVisitor<'a, 'tcx> {
234     type NestedFilter = nested_filter::OnlyBodies;
235
236     fn nested_visit_map(&mut self) -> Self::Map {
237         self.cx.tcx.hir()
238     }
239
240     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
241         if let Some(local_id) = path_to_local(expr) {
242             let Self {
243                 cx,
244                 ref mut slice_lint_info,
245                 max_suggested_slice,
246             } = *self;
247
248             if_chain! {
249                 // Check if this is even a local we're interested in
250                 if let Some(use_info) = slice_lint_info.get_mut(&local_id);
251
252                 let map = cx.tcx.hir();
253
254                 // Checking for slice indexing
255                 let parent_id = map.get_parent_node(expr.hir_id);
256                 if let Some(hir::Node::Expr(parent_expr)) = map.find(parent_id);
257                 if let hir::ExprKind::Index(_, index_expr) = parent_expr.kind;
258                 if let Some((Constant::Int(index_value), _)) = constant(cx, cx.typeck_results(), index_expr);
259                 if let Ok(index_value) = index_value.try_into();
260                 if index_value < max_suggested_slice;
261
262                 // Make sure that this slice index is read only
263                 let maybe_addrof_id = map.get_parent_node(parent_id);
264                 if let Some(hir::Node::Expr(maybe_addrof_expr)) = map.find(maybe_addrof_id);
265                 if let hir::ExprKind::AddrOf(_kind, hir::Mutability::Not, _inner_expr) = maybe_addrof_expr.kind;
266                 then {
267                     use_info.index_use.push((index_value, map.span(parent_expr.hir_id)));
268                     return;
269                 }
270             }
271
272             // The slice was used for something other than indexing
273             self.slice_lint_info.remove(&local_id);
274         }
275         intravisit::walk_expr(self, expr);
276     }
277 }