Skip to content

Commit cdc59f4

Browse files
committed
borrow_deref_ref
1 parent d422baa commit cdc59f4

29 files changed

+497
-58
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3294,6 +3294,7 @@ Released 2018-09-13
32943294
[`bool_assert_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_assert_comparison
32953295
[`bool_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison
32963296
[`borrow_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_as_ptr
3297+
[`borrow_deref_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_deref_ref
32973298
[`borrow_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const
32983299
[`borrowed_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrowed_box
32993300
[`box_collection`]: https://rust-lang.github.io/rust-clippy/master/index.html#box_collection

clippy_lints/src/borrow_deref_ref.rs

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
use crate::reference::DEREF_ADDROF;
2+
use clippy_utils::diagnostics::span_lint_and_then;
3+
use clippy_utils::source::snippet_opt;
4+
use clippy_utils::ty::implements_trait;
5+
use clippy_utils::{get_parent_expr, is_lint_allowed};
6+
use rustc_hir::{ExprKind, UnOp};
7+
use rustc_lint::{LateContext, LateLintPass};
8+
use rustc_middle::mir::Mutability;
9+
use rustc_middle::ty;
10+
use rustc_session::{declare_lint_pass, declare_tool_lint};
11+
12+
declare_clippy_lint! {
13+
/// ### What it does
14+
/// Checks for `&*(&T)`.
15+
///
16+
/// ### Why is this bad?
17+
/// When people deref on an immutable reference `&T`, they may expect return `&U`.
18+
/// Accutually `&* (&T)` is still `&T`.
19+
/// if you want to deref explicitly, `&** (&T)` is what you need.
20+
/// If you want to reborrow, `&T` is enough (`&T` is Copy).
21+
///
22+
/// ### Known problems
23+
/// false negative on such code:
24+
/// ```
25+
/// let x = &12;
26+
/// let addr_x = &x as *const _ as usize;
27+
/// let addr_y = &&*x as *const _ as usize; // assert ok now, and lint triggerd.
28+
/// // But if we fix it, assert will fail.
29+
/// assert_ne!(addr_x, addr_y);
30+
/// ```
31+
///
32+
/// ### Example
33+
/// ```rust
34+
/// let s = &String::new();
35+
///
36+
/// // Bad
37+
/// let a: &String = &* s;
38+
/// foo(&*s);
39+
///
40+
/// // Good
41+
/// let a: &String = s;
42+
/// foo(&**s);
43+
///
44+
/// fn foo(_: &str){ }
45+
/// ```
46+
#[clippy::version = "1.59.0"]
47+
pub BORROW_DEREF_REF,
48+
complexity,
49+
"deref on an immutable reference returns the same type as itself"
50+
}
51+
52+
declare_lint_pass!(BorrowDerefRef => [BORROW_DEREF_REF]);
53+
54+
impl LateLintPass<'_> for BorrowDerefRef {
55+
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx rustc_hir::Expr<'_>) {
56+
if_chain! {
57+
if !e.span.from_expansion();
58+
if let ExprKind::AddrOf(_, Mutability::Not, addrof_target) = e.kind;
59+
if !addrof_target.span.from_expansion();
60+
if let ExprKind::Unary(UnOp::Deref, deref_target) = addrof_target.kind;
61+
if !deref_target.span.from_expansion();
62+
if !matches!(deref_target.kind, ExprKind::Unary(UnOp::Deref, ..) );
63+
let ref_ty = cx.typeck_results().expr_ty(deref_target);
64+
if let ty::Ref(_, inner_ty, Mutability::Not) = ref_ty.kind();
65+
then{
66+
67+
if let Some(parent_expr) = get_parent_expr(cx, e){
68+
if matches!(deref_target.kind, ExprKind::Path(..) | ExprKind::Field(..)) {
69+
if matches!(parent_expr.kind, ExprKind::AddrOf(_, Mutability::Mut, _)) {
70+
return;
71+
}
72+
if matches!(parent_expr.kind, ExprKind::Unary(UnOp::Deref, ..)) &&
73+
!is_lint_allowed(cx, DEREF_ADDROF, parent_expr.hir_id) {
74+
return;
75+
}
76+
}
77+
}
78+
79+
span_lint_and_then(
80+
cx,
81+
BORROW_DEREF_REF,
82+
e.span,
83+
"deref on an immutable reference",
84+
|diag| {
85+
diag.help(
86+
&format!(
87+
"consider using `{}` if you would like to reborrow",
88+
&snippet_opt(cx, deref_target.span).unwrap(),
89+
)
90+
);
91+
92+
// has deref trait -> give 2 help
93+
// doesn't have deref trait -> give 1 help
94+
if let Some(deref_trait_id) = cx.tcx.lang_items().deref_trait(){
95+
if !implements_trait(cx, inner_ty, deref_trait_id, &[]) {
96+
return;
97+
}
98+
}
99+
100+
diag.help(
101+
&format!(
102+
"consider using `&**{}` if you would like to deref",
103+
&snippet_opt(cx, deref_target.span).unwrap(),
104+
)
105+
);
106+
107+
}
108+
);
109+
110+
}
111+
}
112+
}
113+
}

clippy_lints/src/checked_conversions.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function:
319319
if let QPath::TypeRelative(ty, path) = &path;
320320
if path.ident.name.as_str() == function;
321321
if let TyKind::Path(QPath::Resolved(None, tp)) = &ty.kind;
322-
if let [int] = &*tp.segments;
322+
if let [int] = tp.segments;
323323
then {
324324
let name = int.ident.name.as_str();
325325
candidates.iter().find(|c| &name == *c).copied()
@@ -333,7 +333,7 @@ fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function:
333333
fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
334334
if_chain! {
335335
if let QPath::Resolved(_, path) = *path;
336-
if let [ty] = &*path.segments;
336+
if let [ty] = path.segments;
337337
then {
338338
let name = ty.ident.name.as_str();
339339
INTS.iter().find(|c| &name == *c).copied()

clippy_lints/src/eval_order_dependence.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
120120
self.visit_expr(if_expr);
121121
}
122122
// make sure top level arm expressions aren't linted
123-
self.maybe_walk_expr(&*arm.body);
123+
self.maybe_walk_expr(arm.body);
124124
}
125125
},
126126
_ => walk_expr(self, e),

clippy_lints/src/let_if_seq.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
6868
if let hir::ExprKind::If(hir::Expr { kind: hir::ExprKind::DropTemps(cond), ..}, then, else_) = if_.kind;
6969
if !is_local_used(cx, *cond, canonical_id);
7070
if let hir::ExprKind::Block(then, _) = then.kind;
71-
if let Some(value) = check_assign(cx, canonical_id, &*then);
71+
if let Some(value) = check_assign(cx, canonical_id, then);
7272
if !is_local_used(cx, value, canonical_id);
7373
then {
7474
let span = stmt.span.to(if_.span);

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
2424
LintId::of(bool_assert_comparison::BOOL_ASSERT_COMPARISON),
2525
LintId::of(booleans::LOGIC_BUG),
2626
LintId::of(booleans::NONMINIMAL_BOOL),
27+
LintId::of(borrow_deref_ref::BORROW_DEREF_REF),
2728
LintId::of(bytes_count_to_len::BYTES_COUNT_TO_LEN),
2829
LintId::of(casts::CAST_ABS_TO_UNSIGNED),
2930
LintId::of(casts::CAST_ENUM_CONSTRUCTOR),

clippy_lints/src/lib.register_complexity.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec![
66
LintId::of(attrs::DEPRECATED_CFG_ATTR),
77
LintId::of(booleans::NONMINIMAL_BOOL),
8+
LintId::of(borrow_deref_ref::BORROW_DEREF_REF),
89
LintId::of(bytes_count_to_len::BYTES_COUNT_TO_LEN),
910
LintId::of(casts::CHAR_LIT_AS_U8),
1011
LintId::of(casts::UNNECESSARY_CAST),

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ store.register_lints(&[
6464
booleans::LOGIC_BUG,
6565
booleans::NONMINIMAL_BOOL,
6666
borrow_as_ptr::BORROW_AS_PTR,
67+
borrow_deref_ref::BORROW_DEREF_REF,
6768
bytecount::NAIVE_BYTECOUNT,
6869
bytes_count_to_len::BYTES_COUNT_TO_LEN,
6970
cargo::CARGO_COMMON_METADATA,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ mod blocks_in_if_conditions;
183183
mod bool_assert_comparison;
184184
mod booleans;
185185
mod borrow_as_ptr;
186+
mod borrow_deref_ref;
186187
mod bytecount;
187188
mod bytes_count_to_len;
188189
mod cargo;
@@ -634,6 +635,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
634635
store.register_late_pass(|| Box::new(mutex_atomic::Mutex));
635636
store.register_late_pass(|| Box::new(needless_update::NeedlessUpdate));
636637
store.register_late_pass(|| Box::new(needless_borrowed_ref::NeedlessBorrowedRef));
638+
store.register_late_pass(|| Box::new(borrow_deref_ref::BorrowDerefRef));
637639
store.register_late_pass(|| Box::new(no_effect::NoEffect));
638640
store.register_late_pass(|| Box::new(temporary_assignment::TemporaryAssignment));
639641
store.register_late_pass(|| Box::new(transmute::Transmute));

clippy_lints/src/loops/never_loop.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
146146
if arms.is_empty() {
147147
e
148148
} else {
149-
let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
149+
let arms = never_loop_expr_branch(&mut arms.iter().map(|a| a.body), main_loop_id);
150150
combine_seq(e, arms)
151151
}
152152
},

0 commit comments

Comments
 (0)