2021-12-06 05:33:31 -06:00
|
|
|
use clippy_utils::consts::{constant, Constant};
|
|
|
|
use clippy_utils::diagnostics::span_lint_and_then;
|
|
|
|
use clippy_utils::higher::IfLet;
|
2022-12-01 11:29:38 -06:00
|
|
|
use clippy_utils::msrvs::{self, Msrv};
|
2021-12-06 05:33:31 -06:00
|
|
|
use clippy_utils::ty::is_copy;
|
2022-12-01 11:29:38 -06:00
|
|
|
use clippy_utils::{is_expn_of, is_lint_allowed, path_to_local};
|
2021-12-06 05:33:31 -06:00
|
|
|
use if_chain::if_chain;
|
2022-01-07 19:56:13 -06:00
|
|
|
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
|
2021-12-06 05:33:31 -06:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir as hir;
|
2022-01-15 16:07:52 -06:00
|
|
|
use rustc_hir::intravisit::{self, Visitor};
|
2021-12-04 09:09:15 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2022-01-15 16:07:52 -06:00
|
|
|
use rustc_middle::hir::nested_filter;
|
2021-12-06 05:33:31 -06:00
|
|
|
use rustc_middle::ty;
|
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
|
|
|
use rustc_span::{symbol::Ident, Span};
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
|
|
|
/// ### What it does
|
|
|
|
/// The lint checks for slice bindings in patterns that are only used to
|
|
|
|
/// access individual slice values.
|
|
|
|
///
|
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Accessing slice values using indices can lead to panics. Using refutable
|
|
|
|
/// patterns can avoid these. Binding to individual values also improves the
|
|
|
|
/// readability as they can be named.
|
|
|
|
///
|
|
|
|
/// ### Limitations
|
|
|
|
/// This lint currently only checks for immutable access inside `if let`
|
|
|
|
/// patterns.
|
|
|
|
///
|
|
|
|
/// ### Example
|
|
|
|
/// ```rust
|
|
|
|
/// let slice: Option<&[u32]> = Some(&[1, 2, 3]);
|
|
|
|
///
|
|
|
|
/// if let Some(slice) = slice {
|
|
|
|
/// println!("{}", slice[0]);
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// let slice: Option<&[u32]> = Some(&[1, 2, 3]);
|
|
|
|
///
|
|
|
|
/// if let Some(&[first, ..]) = slice {
|
|
|
|
/// println!("{}", first);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2022-06-16 10:39:06 -05:00
|
|
|
#[clippy::version = "1.59.0"]
|
2021-12-06 05:33:31 -06:00
|
|
|
pub INDEX_REFUTABLE_SLICE,
|
2022-12-01 11:29:38 -06:00
|
|
|
pedantic,
|
2021-12-06 05:33:31 -06:00
|
|
|
"avoid indexing on slices which could be destructed"
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct IndexRefutableSlice {
|
|
|
|
max_suggested_slice: u64,
|
2022-12-01 11:29:38 -06:00
|
|
|
msrv: Msrv,
|
2021-12-06 05:33:31 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
impl IndexRefutableSlice {
|
2022-12-01 11:29:38 -06:00
|
|
|
pub fn new(max_suggested_slice_pattern_length: u64, msrv: Msrv) -> Self {
|
2021-12-06 05:33:31 -06:00
|
|
|
Self {
|
|
|
|
max_suggested_slice: max_suggested_slice_pattern_length,
|
|
|
|
msrv,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(IndexRefutableSlice => [INDEX_REFUTABLE_SLICE]);
|
|
|
|
|
2022-01-13 06:18:19 -06:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for IndexRefutableSlice {
|
2021-12-06 05:33:31 -06:00
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
|
|
|
|
if_chain! {
|
|
|
|
if !expr.span.from_expansion() || is_expn_of(expr.span, "if_chain").is_some();
|
|
|
|
if let Some(IfLet {let_pat, if_then, ..}) = IfLet::hir(cx, expr);
|
|
|
|
if !is_lint_allowed(cx, INDEX_REFUTABLE_SLICE, expr.hir_id);
|
2022-12-01 11:29:38 -06:00
|
|
|
if self.msrv.meets(msrvs::SLICE_PATTERNS);
|
2021-12-06 05:33:31 -06:00
|
|
|
|
|
|
|
let found_slices = find_slice_values(cx, let_pat);
|
|
|
|
if !found_slices.is_empty();
|
|
|
|
let filtered_slices = filter_lintable_slices(cx, found_slices, self.max_suggested_slice, if_then);
|
|
|
|
if !filtered_slices.is_empty();
|
|
|
|
then {
|
|
|
|
for slice in filtered_slices.values() {
|
|
|
|
lint_slice(cx, slice);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extract_msrv_attr!(LateContext);
|
|
|
|
}
|
|
|
|
|
2022-01-07 19:56:13 -06:00
|
|
|
fn find_slice_values(cx: &LateContext<'_>, pat: &hir::Pat<'_>) -> FxIndexMap<hir::HirId, SliceLintInformation> {
|
2021-12-06 05:33:31 -06:00
|
|
|
let mut removed_pat: FxHashSet<hir::HirId> = FxHashSet::default();
|
2022-01-07 19:56:13 -06:00
|
|
|
let mut slices: FxIndexMap<hir::HirId, SliceLintInformation> = FxIndexMap::default();
|
2021-12-06 05:33:31 -06:00
|
|
|
pat.walk_always(|pat| {
|
2022-08-30 17:36:53 -05:00
|
|
|
// We'll just ignore mut and ref mut for simplicity sake right now
|
|
|
|
if let hir::PatKind::Binding(
|
|
|
|
hir::BindingAnnotation(by_ref, hir::Mutability::Not),
|
|
|
|
value_hir_id,
|
|
|
|
ident,
|
|
|
|
sub_pat,
|
|
|
|
) = pat.kind
|
|
|
|
{
|
2021-12-06 05:33:31 -06:00
|
|
|
// This block catches bindings with sub patterns. It would be hard to build a correct suggestion
|
|
|
|
// for them and it's likely that the user knows what they are doing in such a case.
|
|
|
|
if removed_pat.contains(&value_hir_id) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if sub_pat.is_some() {
|
|
|
|
removed_pat.insert(value_hir_id);
|
|
|
|
slices.remove(&value_hir_id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let bound_ty = cx.typeck_results().node_type(pat.hir_id);
|
|
|
|
if let ty::Slice(inner_ty) | ty::Array(inner_ty, _) = bound_ty.peel_refs().kind() {
|
|
|
|
// The values need to use the `ref` keyword if they can't be copied.
|
2022-05-05 09:12:52 -05:00
|
|
|
// This will need to be adjusted if the lint want to support mutable access in the future
|
2022-08-30 17:36:53 -05:00
|
|
|
let src_is_ref = bound_ty.is_ref() && by_ref != hir::ByRef::Yes;
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-24 21:13:38 -06:00
|
|
|
let needs_ref = !(src_is_ref || is_copy(cx, *inner_ty));
|
2021-12-06 05:33:31 -06:00
|
|
|
|
|
|
|
let slice_info = slices
|
|
|
|
.entry(value_hir_id)
|
|
|
|
.or_insert_with(|| SliceLintInformation::new(ident, needs_ref));
|
|
|
|
slice_info.pattern_spans.push(pat.span);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
slices
|
|
|
|
}
|
|
|
|
|
|
|
|
fn lint_slice(cx: &LateContext<'_>, slice: &SliceLintInformation) {
|
|
|
|
let used_indices = slice
|
|
|
|
.index_use
|
|
|
|
.iter()
|
|
|
|
.map(|(index, _)| *index)
|
|
|
|
.collect::<FxHashSet<_>>();
|
|
|
|
|
2022-10-06 02:44:38 -05:00
|
|
|
let value_name = |index| format!("{}_{index}", slice.ident.name);
|
2021-12-06 05:33:31 -06:00
|
|
|
|
|
|
|
if let Some(max_index) = used_indices.iter().max() {
|
|
|
|
let opt_ref = if slice.needs_ref { "ref " } else { "" };
|
|
|
|
let pat_sugg_idents = (0..=*max_index)
|
|
|
|
.map(|index| {
|
|
|
|
if used_indices.contains(&index) {
|
2022-10-06 02:44:38 -05:00
|
|
|
format!("{opt_ref}{}", value_name(index))
|
2021-12-06 05:33:31 -06:00
|
|
|
} else {
|
|
|
|
"_".to_string()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
let pat_sugg = format!("[{}, ..]", pat_sugg_idents.join(", "));
|
|
|
|
|
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
INDEX_REFUTABLE_SLICE,
|
|
|
|
slice.ident.span,
|
|
|
|
"this binding can be a slice pattern to avoid indexing",
|
|
|
|
|diag| {
|
|
|
|
diag.multipart_suggestion(
|
|
|
|
"try using a slice pattern here",
|
|
|
|
slice
|
|
|
|
.pattern_spans
|
|
|
|
.iter()
|
|
|
|
.map(|span| (*span, pat_sugg.clone()))
|
|
|
|
.collect(),
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
);
|
|
|
|
|
|
|
|
diag.multipart_suggestion(
|
|
|
|
"and replace the index expressions here",
|
|
|
|
slice
|
|
|
|
.index_use
|
|
|
|
.iter()
|
|
|
|
.map(|(index, span)| (*span, value_name(*index)))
|
|
|
|
.collect(),
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
);
|
|
|
|
|
|
|
|
// The lint message doesn't contain a warning about the removed index expression,
|
|
|
|
// since `filter_lintable_slices` will only return slices where all access indices
|
|
|
|
// are known at compile time. Therefore, they can be removed without side effects.
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct SliceLintInformation {
|
|
|
|
ident: Ident,
|
|
|
|
needs_ref: bool,
|
|
|
|
pattern_spans: Vec<Span>,
|
|
|
|
index_use: Vec<(u64, Span)>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SliceLintInformation {
|
|
|
|
fn new(ident: Ident, needs_ref: bool) -> Self {
|
|
|
|
Self {
|
|
|
|
ident,
|
|
|
|
needs_ref,
|
|
|
|
pattern_spans: Vec::new(),
|
|
|
|
index_use: Vec::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-21 13:34:47 -06:00
|
|
|
fn filter_lintable_slices<'tcx>(
|
|
|
|
cx: &LateContext<'tcx>,
|
2022-01-07 19:56:13 -06:00
|
|
|
slice_lint_info: FxIndexMap<hir::HirId, SliceLintInformation>,
|
2021-12-06 05:33:31 -06:00
|
|
|
max_suggested_slice: u64,
|
|
|
|
scope: &'tcx hir::Expr<'tcx>,
|
2022-01-07 19:56:13 -06:00
|
|
|
) -> FxIndexMap<hir::HirId, SliceLintInformation> {
|
2021-12-06 05:33:31 -06:00
|
|
|
let mut visitor = SliceIndexLintingVisitor {
|
|
|
|
cx,
|
|
|
|
slice_lint_info,
|
|
|
|
max_suggested_slice,
|
|
|
|
};
|
|
|
|
|
|
|
|
intravisit::walk_expr(&mut visitor, scope);
|
|
|
|
|
|
|
|
visitor.slice_lint_info
|
|
|
|
}
|
|
|
|
|
|
|
|
struct SliceIndexLintingVisitor<'a, 'tcx> {
|
|
|
|
cx: &'a LateContext<'tcx>,
|
2022-01-07 19:56:13 -06:00
|
|
|
slice_lint_info: FxIndexMap<hir::HirId, SliceLintInformation>,
|
2021-12-06 05:33:31 -06:00
|
|
|
max_suggested_slice: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for SliceIndexLintingVisitor<'a, 'tcx> {
|
2022-01-15 16:07:52 -06:00
|
|
|
type NestedFilter = nested_filter::OnlyBodies;
|
2021-12-06 05:33:31 -06:00
|
|
|
|
2022-01-15 16:07:52 -06:00
|
|
|
fn nested_visit_map(&mut self) -> Self::Map {
|
|
|
|
self.cx.tcx.hir()
|
2021-12-06 05:33:31 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
|
|
|
|
if let Some(local_id) = path_to_local(expr) {
|
|
|
|
let Self {
|
|
|
|
cx,
|
|
|
|
ref mut slice_lint_info,
|
|
|
|
max_suggested_slice,
|
|
|
|
} = *self;
|
|
|
|
|
|
|
|
if_chain! {
|
|
|
|
// Check if this is even a local we're interested in
|
|
|
|
if let Some(use_info) = slice_lint_info.get_mut(&local_id);
|
|
|
|
|
|
|
|
let map = cx.tcx.hir();
|
|
|
|
|
|
|
|
// Checking for slice indexing
|
2023-01-03 01:31:04 -06:00
|
|
|
let parent_id = map.parent_id(expr.hir_id);
|
2021-12-06 05:33:31 -06:00
|
|
|
if let Some(hir::Node::Expr(parent_expr)) = map.find(parent_id);
|
|
|
|
if let hir::ExprKind::Index(_, index_expr) = parent_expr.kind;
|
|
|
|
if let Some((Constant::Int(index_value), _)) = constant(cx, cx.typeck_results(), index_expr);
|
|
|
|
if let Ok(index_value) = index_value.try_into();
|
|
|
|
if index_value < max_suggested_slice;
|
|
|
|
|
|
|
|
// Make sure that this slice index is read only
|
2023-01-03 01:31:04 -06:00
|
|
|
let maybe_addrof_id = map.parent_id(parent_id);
|
2021-12-06 05:33:31 -06:00
|
|
|
if let Some(hir::Node::Expr(maybe_addrof_expr)) = map.find(maybe_addrof_id);
|
|
|
|
if let hir::ExprKind::AddrOf(_kind, hir::Mutability::Not, _inner_expr) = maybe_addrof_expr.kind;
|
|
|
|
then {
|
|
|
|
use_info.index_use.push((index_value, map.span(parent_expr.hir_id)));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// The slice was used for something other than indexing
|
|
|
|
self.slice_lint_info.remove(&local_id);
|
|
|
|
}
|
|
|
|
intravisit::walk_expr(self, expr);
|
|
|
|
}
|
|
|
|
}
|