Skip to content

Commit

Permalink
Introduce small cache to avoid recomputing the same value twice
Browse files Browse the repository at this point in the history
  • Loading branch information
Urgau committed Dec 15, 2023
1 parent 1c14404 commit dbf8ac9
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions compiler/rustc_lint/src/reference_casting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,15 @@ impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
let init = cx.expr_or_init(e);
let orig_cast = if init.span != e.span { Some(init.span) } else { None };

// small cache to avoid recomputing needlesly computing peel_casts of init
let mut peel_casts = {
let mut peel_casts_cache = None;
move || *peel_casts_cache.get_or_insert_with(|| peel_casts(cx, init))
};

if matches!(pat, PatternKind::Borrow { mutbl: Mutability::Mut } | PatternKind::Assign)
&& let Some(ty_has_interior_mutability) = is_cast_from_ref_to_mut_ptr(cx, init)
&& let Some(ty_has_interior_mutability) =
is_cast_from_ref_to_mut_ptr(cx, init, &mut peel_casts)
{
let ty_has_interior_mutability = ty_has_interior_mutability.then_some(());

Expand All @@ -64,7 +71,8 @@ impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
);
}

if let Some((from_ty_layout, to_ty_layout)) = is_cast_to_bigger_memory_layout(cx, init)
if let Some((from_ty_layout, to_ty_layout)) =
is_cast_to_bigger_memory_layout(cx, init, &mut peel_casts)
{
cx.emit_spanned_lint(
INVALID_REFERENCE_CASTING,
Expand Down Expand Up @@ -141,6 +149,7 @@ fn borrow_or_assign<'tcx>(
fn is_cast_from_ref_to_mut_ptr<'tcx>(
cx: &LateContext<'tcx>,
orig_expr: &'tcx Expr<'tcx>,
mut peel_casts: impl FnMut() -> (&'tcx Expr<'tcx>, bool),
) -> Option<bool> {
let end_ty = cx.typeck_results().node_type(orig_expr.hir_id);

Expand All @@ -149,7 +158,7 @@ fn is_cast_from_ref_to_mut_ptr<'tcx>(
return None;
}

let (e, need_check_freeze) = peel_casts(cx, orig_expr);
let (e, need_check_freeze) = peel_casts();

let start_ty = cx.typeck_results().node_type(e.hir_id);
if let ty::Ref(_, inner_ty, Mutability::Not) = start_ty.kind() {
Expand All @@ -171,14 +180,15 @@ fn is_cast_from_ref_to_mut_ptr<'tcx>(
fn is_cast_to_bigger_memory_layout<'tcx>(
cx: &LateContext<'tcx>,
orig_expr: &'tcx Expr<'tcx>,
mut peel_casts: impl FnMut() -> (&'tcx Expr<'tcx>, bool),
) -> Option<(TyAndLayout<'tcx>, TyAndLayout<'tcx>)> {
let end_ty = cx.typeck_results().node_type(orig_expr.hir_id);

let ty::RawPtr(TypeAndMut { ty: inner_end_ty, mutbl: _ }) = end_ty.kind() else {
return None;
};

let (e, _) = peel_casts(cx, orig_expr);
let (e, _) = peel_casts();
let start_ty = cx.typeck_results().node_type(e.hir_id);

let ty::Ref(_, inner_start_ty, _) = start_ty.kind() else {
Expand Down

0 comments on commit dbf8ac9

Please sign in to comment.