rust/clippy_lints/src/match_on_vec_items.rs

105 lines
3.1 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item};
2020-04-23 16:28:18 -05:00
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind, LangItem, MatchSource};
2020-04-23 16:28:18 -05:00
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
2020-04-23 16:28:18 -05:00
declare_clippy_lint! {
/// ### What it does
/// Checks for `match vec[idx]` or `match vec[n..m]`.
2020-04-23 16:28:18 -05:00
///
/// ### Why is this bad?
/// This can panic at runtime.
2020-04-23 16:28:18 -05:00
///
/// ### Example
2020-04-23 16:28:18 -05:00
/// ```rust, no_run
/// let arr = vec![0, 1, 2, 3];
/// let idx = 1;
///
/// // Bad
/// match arr[idx] {
/// 0 => println!("{}", 0),
/// 1 => println!("{}", 3),
/// _ => {},
/// }
/// ```
/// Use instead:
/// ```rust, no_run
/// let arr = vec![0, 1, 2, 3];
/// let idx = 1;
///
/// // Good
/// match arr.get(idx) {
/// Some(0) => println!("{}", 0),
/// Some(1) => println!("{}", 3),
/// _ => {},
/// }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "1.45.0"]
2020-04-25 03:33:40 -05:00
pub MATCH_ON_VEC_ITEMS,
pedantic,
2020-04-25 03:33:40 -05:00
"matching on vector elements can panic"
2020-04-23 16:28:18 -05:00
}
2020-04-25 03:33:40 -05:00
declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
2020-04-23 16:28:18 -05:00
impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
2020-04-23 16:28:18 -05:00
if_chain! {
if !in_external_macro(cx.sess(), expr.span);
if let ExprKind::Match(match_expr, _, MatchSource::Normal) = expr.kind;
if let Some(idx_expr) = is_vec_indexing(cx, match_expr);
if let ExprKind::Index(vec, idx) = idx_expr.kind;
2020-04-23 16:28:18 -05:00
then {
// FIXME: could be improved to suggest surrounding every pattern with Some(_),
// but only when `or_patterns` are stabilized.
span_lint_and_sugg(
2020-04-23 16:28:18 -05:00
cx,
2020-04-25 03:33:40 -05:00
MATCH_ON_VEC_ITEMS,
match_expr.span,
"indexing into a vector may panic",
"try this",
format!(
"{}.get({})",
snippet(cx, vec.span, ".."),
snippet(cx, idx.span, "..")
),
Applicability::MaybeIncorrect
2020-04-23 16:28:18 -05:00
);
}
}
}
}
fn is_vec_indexing<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2020-04-23 16:28:18 -05:00
if_chain! {
if let ExprKind::Index(array, index) = expr.kind;
if is_vector(cx, array);
if !is_full_range(cx, index);
2020-04-23 16:28:18 -05:00
then {
return Some(expr);
2020-04-23 16:28:18 -05:00
}
}
None
2020-04-23 16:28:18 -05:00
}
fn is_vector(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
2020-07-17 03:47:04 -05:00
let ty = cx.typeck_results().expr_ty(expr);
let ty = ty.peel_refs();
2021-10-02 18:51:01 -05:00
is_type_diagnostic_item(cx, ty, sym::Vec)
}
fn is_full_range(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
2020-07-17 03:47:04 -05:00
let ty = cx.typeck_results().expr_ty(expr);
let ty = ty.peel_refs();
is_type_lang_item(cx, ty, LangItem::RangeFull)
}