|
| 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::implements_trait; |
| 5 | +use clippy_utils::{in_macro, is_expn_of, is_lint_allowed, meets_msrv, msrvs, path_to_local}; |
| 6 | +use if_chain::if_chain; |
| 7 | +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
| 8 | +use rustc_errors::Applicability; |
| 9 | +use rustc_hir as hir; |
| 10 | +use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; |
| 11 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 12 | +use rustc_middle::hir::map::Map; |
| 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 | +use std::convert::TryInto; |
| 18 | + |
| 19 | +declare_clippy_lint! { |
| 20 | + /// ### What it does |
| 21 | + /// The lint checks for slice bindings in patterns that are only used to |
| 22 | + /// access individual slice values. |
| 23 | + /// |
| 24 | + /// ### Why is this bad? |
| 25 | + /// Accessing slice values using indices can lead to panics. Using refutable |
| 26 | + /// patterns can avoid these. Binding to individual values also improves the |
| 27 | + /// readability as they can be named. |
| 28 | + /// |
| 29 | + /// ### Limitations |
| 30 | + /// This lint currently only checks for immutable access inside `if let` |
| 31 | + /// patterns. |
| 32 | + /// |
| 33 | + /// ### Example |
| 34 | + /// ```rust |
| 35 | + /// let slice: Option<&[u32]> = Some(&[1, 2, 3]); |
| 36 | + /// |
| 37 | + /// if let Some(slice) = slice { |
| 38 | + /// println!("{}", slice[0]); |
| 39 | + /// } |
| 40 | + /// ``` |
| 41 | + /// Use instead: |
| 42 | + /// ```rust |
| 43 | + /// let slice: Option<&[u32]> = Some(&[1, 2, 3]); |
| 44 | + /// |
| 45 | + /// if let Some(&[first, ..]) = slice { |
| 46 | + /// println!("{}", first); |
| 47 | + /// } |
| 48 | + /// ``` |
| 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 | + indexing_limit: 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 | + indexing_limit: max_suggested_slice_pattern_length - 1, |
| 64 | + msrv, |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl_lint_pass!(IndexRefutableSlice => [INDEX_REFUTABLE_SLICE]); |
| 70 | + |
| 71 | +impl LateLintPass<'_> for IndexRefutableSlice { |
| 72 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { |
| 73 | + if_chain! { |
| 74 | + if !in_macro(expr.span) || 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.as_ref(), &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.indexing_limit, 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<'_>) -> FxHashMap<hir::HirId, SliceLintInformation> { |
| 95 | + let mut removed_pat: FxHashSet<hir::HirId> = FxHashSet::default(); |
| 96 | + let mut slices: FxHashMap<hir::HirId, SliceLintInformation> = FxHashMap::default(); |
| 97 | + pat.walk_always(|pat| { |
| 98 | + if let hir::PatKind::Binding(binding, value_hir_id, ident, sub_pat) = pat.kind { |
| 99 | + // We'll just ignore mut and ref mut for simplicity sake right now |
| 100 | + if let hir::BindingAnnotation::Mutable | hir::BindingAnnotation::RefMut = binding { |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + // This block catches bindings with sub patterns. It would be hard to build a correct suggestion |
| 105 | + // for them and it's likely that the user knows what they are doing in such a case. |
| 106 | + if removed_pat.contains(&value_hir_id) { |
| 107 | + return; |
| 108 | + } |
| 109 | + if sub_pat.is_some() { |
| 110 | + removed_pat.insert(value_hir_id); |
| 111 | + slices.remove(&value_hir_id); |
| 112 | + return; |
| 113 | + } |
| 114 | + |
| 115 | + let bound_ty = cx.typeck_results().node_type(pat.hir_id); |
| 116 | + if let ty::Slice(inner_ty) | ty::Array(inner_ty, _) = bound_ty.peel_refs().kind() { |
| 117 | + // The values need to use the `ref` keyword if they can't be copied. |
| 118 | + // This will need to be adjusted if the lint want to support multable access in the future |
| 119 | + let src_is_ref = bound_ty.is_ref() && binding != hir::BindingAnnotation::Ref; |
| 120 | + let is_copy = cx |
| 121 | + .tcx |
| 122 | + .lang_items() |
| 123 | + .copy_trait() |
| 124 | + .map_or(false, |trait_id| implements_trait(cx, inner_ty, trait_id, &[])); |
| 125 | + let needs_ref = !(src_is_ref || is_copy); |
| 126 | + |
| 127 | + let slice_info = slices |
| 128 | + .entry(value_hir_id) |
| 129 | + .or_insert_with(|| SliceLintInformation::new(ident, needs_ref)); |
| 130 | + slice_info.pattern_spans.push(pat.span); |
| 131 | + } |
| 132 | + } |
| 133 | + }); |
| 134 | + |
| 135 | + slices |
| 136 | +} |
| 137 | + |
| 138 | +fn lint_slice(cx: &LateContext<'_>, slice: &SliceLintInformation) { |
| 139 | + let used_indices = slice |
| 140 | + .index_use |
| 141 | + .iter() |
| 142 | + .map(|(index, _)| *index) |
| 143 | + .collect::<FxHashSet<_>>(); |
| 144 | + |
| 145 | + let value_name = |index| format!("{}_{}", slice.ident.name, index); |
| 146 | + |
| 147 | + if let Some(max_index) = used_indices.iter().max() { |
| 148 | + let opt_ref = if slice.needs_ref { "ref " } else { "" }; |
| 149 | + let pat_sugg_idents = (0..=*max_index) |
| 150 | + .map(|index| { |
| 151 | + if used_indices.contains(&index) { |
| 152 | + format!("{}{}", opt_ref, value_name(index)) |
| 153 | + } else { |
| 154 | + "_".to_string() |
| 155 | + } |
| 156 | + }) |
| 157 | + .collect::<Vec<_>>(); |
| 158 | + let pat_sugg = format!("[{}, ..]", pat_sugg_idents.join(", ")); |
| 159 | + |
| 160 | + span_lint_and_then( |
| 161 | + cx, |
| 162 | + INDEX_REFUTABLE_SLICE, |
| 163 | + slice.ident.span, |
| 164 | + "this binding can be a slice pattern to avoid indexing", |
| 165 | + |diag| { |
| 166 | + diag.multipart_suggestion( |
| 167 | + "try using a slice pattern here", |
| 168 | + slice |
| 169 | + .pattern_spans |
| 170 | + .iter() |
| 171 | + .map(|span| (*span, pat_sugg.clone())) |
| 172 | + .collect(), |
| 173 | + Applicability::MaybeIncorrect, |
| 174 | + ); |
| 175 | + |
| 176 | + diag.multipart_suggestion( |
| 177 | + "and replace the index expressions here", |
| 178 | + slice |
| 179 | + .index_use |
| 180 | + .iter() |
| 181 | + .map(|(index, span)| (*span, value_name(*index))) |
| 182 | + .collect(), |
| 183 | + Applicability::MaybeIncorrect, |
| 184 | + ); |
| 185 | + |
| 186 | + // I thought about adding a note to the lint message to inform the user that these |
| 187 | + // refactorings will remove the index expression. However, I decided against this, |
| 188 | + // as `filter_lintable_slices` will only return slices where all access indices are |
| 189 | + // known at compile time. The removal should therefore not have any side effects. |
| 190 | + }, |
| 191 | + ); |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +#[derive(Debug)] |
| 196 | +struct SliceLintInformation { |
| 197 | + ident: Ident, |
| 198 | + needs_ref: bool, |
| 199 | + pattern_spans: Vec<Span>, |
| 200 | + index_use: Vec<(u64, Span)>, |
| 201 | +} |
| 202 | + |
| 203 | +impl SliceLintInformation { |
| 204 | + fn new(ident: Ident, needs_ref: bool) -> Self { |
| 205 | + Self { |
| 206 | + ident, |
| 207 | + needs_ref, |
| 208 | + pattern_spans: Vec::new(), |
| 209 | + index_use: Vec::new(), |
| 210 | + } |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +fn filter_lintable_slices<'a, 'tcx>( |
| 215 | + cx: &'a LateContext<'tcx>, |
| 216 | + slice_lint_info: FxHashMap<hir::HirId, SliceLintInformation>, |
| 217 | + index_limit: u64, |
| 218 | + scope: &'tcx hir::Expr<'tcx>, |
| 219 | +) -> FxHashMap<hir::HirId, SliceLintInformation> { |
| 220 | + let mut visitor = SliceIndexLintingVisitor { |
| 221 | + cx, |
| 222 | + slice_lint_info, |
| 223 | + index_limit, |
| 224 | + }; |
| 225 | + |
| 226 | + intravisit::walk_expr(&mut visitor, scope); |
| 227 | + |
| 228 | + visitor |
| 229 | + .slice_lint_info |
| 230 | + .retain(|_key, value| !value.index_use.is_empty()); |
| 231 | + visitor.slice_lint_info |
| 232 | +} |
| 233 | + |
| 234 | +struct SliceIndexLintingVisitor<'a, 'tcx> { |
| 235 | + cx: &'a LateContext<'tcx>, |
| 236 | + slice_lint_info: FxHashMap<hir::HirId, SliceLintInformation>, |
| 237 | + index_limit: u64, |
| 238 | +} |
| 239 | + |
| 240 | +impl<'a, 'tcx> Visitor<'tcx> for SliceIndexLintingVisitor<'a, 'tcx> { |
| 241 | + type Map = Map<'tcx>; |
| 242 | + |
| 243 | + fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
| 244 | + NestedVisitorMap::OnlyBodies(self.cx.tcx.hir()) |
| 245 | + } |
| 246 | + |
| 247 | + fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { |
| 248 | + if let Some(local_id) = path_to_local(expr) { |
| 249 | + let Self { |
| 250 | + cx, |
| 251 | + ref mut slice_lint_info, |
| 252 | + index_limit, |
| 253 | + } = *self; |
| 254 | + |
| 255 | + if_chain! { |
| 256 | + // Check if this is even a local we're interested in |
| 257 | + if let Some(use_info) = slice_lint_info.get_mut(&local_id); |
| 258 | + |
| 259 | + let map = cx.tcx.hir(); |
| 260 | + |
| 261 | + // Checking for slice indexing |
| 262 | + let parent_id = map.get_parent_node(expr.hir_id); |
| 263 | + if let Some(hir::Node::Expr(parent_expr)) = map.find(parent_id); |
| 264 | + if let hir::ExprKind::Index(_, index_expr) = parent_expr.kind; |
| 265 | + if let Some((Constant::Int(index_value), _)) = constant(cx, cx.typeck_results(), index_expr); |
| 266 | + if let Ok(index_value) = index_value.try_into(); |
| 267 | + if index_value <= index_limit; |
| 268 | + |
| 269 | + // Make sure that this slice index is read only |
| 270 | + let maybe_addrof_id = map.get_parent_node(parent_id); |
| 271 | + if let Some(hir::Node::Expr(maybe_addrof_expr)) = map.find(maybe_addrof_id); |
| 272 | + if let hir::ExprKind::AddrOf(_kind, hir::Mutability::Not, _inner_expr) = maybe_addrof_expr.kind; |
| 273 | + then { |
| 274 | + use_info.index_use.push((index_value, map.span(parent_expr.hir_id))); |
| 275 | + return; |
| 276 | + } |
| 277 | + } |
| 278 | + |
| 279 | + // The slice was used for something other than indexing |
| 280 | + self.slice_lint_info.remove(&local_id); |
| 281 | + } |
| 282 | + intravisit::walk_expr(self, expr); |
| 283 | + } |
| 284 | +} |
0 commit comments