do not lint on indexing inside const contexts

This commit is contained in:
Lzu Tao 2024-05-24 03:25:58 +00:00
parent b161dc659c
commit 2c61b45576
3 changed files with 9 additions and 16 deletions

View file

@ -1,7 +1,9 @@
use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::has_drop;
use clippy_utils::{any_parent_is_automatically_derived, is_lint_allowed, path_to_local, peel_blocks};
use clippy_utils::{
any_parent_is_automatically_derived, is_inside_always_const_context, is_lint_allowed, path_to_local, peel_blocks,
};
use rustc_errors::Applicability;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{
@ -265,6 +267,9 @@ fn check_unnecessary_operation(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
&& reduced.iter().all(|e| e.span.ctxt() == ctxt)
{
if let ExprKind::Index(..) = &expr.kind {
if is_inside_always_const_context(cx.tcx, expr.hir_id) {
return;
}
let snippet =
if let (Some(arr), Some(func)) = (snippet_opt(cx, reduced[0].span), snippet_opt(cx, reduced[1].span)) {
format!("assert!({}.len() > {});", &arr, &func)

View file

@ -114,12 +114,12 @@ fn main() {
break 'label
};
let () = const {
assert!([42, 55].len() > get_usize());
[42, 55][get_usize()];
};
}
const _: () = {
assert!([42, 55].len() > get_usize());
[42, 55][get_usize()];
};
const fn foo() {

View file

@ -119,23 +119,11 @@ LL | | s: String::from("blah"),
LL | | };
| |______^ help: statement can be reduced to: `String::from("blah");`
error: unnecessary operation
--> tests/ui/unnecessary_operation.rs:121:9
|
LL | [42, 55][get_usize()];
| ^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([42, 55].len() > get_usize());`
error: unnecessary operation
--> tests/ui/unnecessary_operation.rs:126:5
|
LL | [42, 55][get_usize()];
| ^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([42, 55].len() > get_usize());`
error: unnecessary operation
--> tests/ui/unnecessary_operation.rs:130:5
|
LL | [42, 55][get_usize()];
| ^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([42, 55].len() > get_usize());`
error: aborting due to 22 previous errors
error: aborting due to 20 previous errors