Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ mod opaque_hidden_inferred_bound;
mod passes;
mod precedence;
mod ptr_nulls;
mod raw_borrows_via_references;
mod redundant_semicolon;
mod reference_casting;
mod runtime_symbols;
Expand Down Expand Up @@ -117,6 +118,7 @@ use noop_method_call::*;
use opaque_hidden_inferred_bound::*;
use precedence::*;
use ptr_nulls::*;
use raw_borrows_via_references::*;
use redundant_semicolon::*;
use reference_casting::*;
use runtime_symbols::*;
Expand Down Expand Up @@ -273,6 +275,7 @@ late_lint_methods!(
InternalEqTraitMethodImpls: InternalEqTraitMethodImpls,
ImplicitProvenanceCasts: ImplicitProvenanceCasts,
CVoidReturns: CVoidReturns,
RawBorrowsViaReferences: RawBorrowsViaReferences,
]
]
);
Expand Down
26 changes: 26 additions & 0 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3037,3 +3037,29 @@ pub(crate) enum Ptr2IntSuggestion<'tcx> {
cast_span: Span,
},
}

#[derive(Diagnostic)]
#[diag(
"creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers"
)]
pub(crate) struct RawBorrowViaReference<'a> {
#[subdiagnostic]
pub suggestion: RawBorrowViaReferenceSuggestion<'a>,
}

#[derive(Subdiagnostic)]
pub(crate) enum RawBorrowViaReferenceSuggestion<'a> {
#[multipart_suggestion(
"consider using `&raw {$mutbl}` for a safer and more explicit raw pointer",
applicability = "machine-applicable"
)]
Spanful {
#[suggestion_part(code = "&raw {mutbl} ")]
left: Span,
#[suggestion_part(code = "")]
right: Span,
mutbl: &'a str,
},
#[help("consider using `&raw {$mutbl}` for a safer and more explicit raw pointer")]
Spanless { mutbl: &'a str },
}
83 changes: 83 additions & 0 deletions compiler/rustc_lint/src/raw_borrows_via_references.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use rustc_ast::BorrowKind;
use rustc_hir::{Expr, ExprKind, TyKind};
use rustc_session::{declare_lint, declare_lint_pass};

use crate::lints::{RawBorrowViaReference, RawBorrowViaReferenceSuggestion};
use crate::{LateContext, LateLintPass, LintContext};

declare_lint! {
/// The `raw_borrows_via_references` lint checks for references that decay immediately into raw borrows.
///
/// ### Example
///
/// ```rust
/// #![warn(raw_borrows_via_references)]
///
/// fn via_ref(x: *const (i32, i32)) -> *const i32 {
/// unsafe { &(*x).0 as *const i32 }
/// }
///
/// fn main() {
/// let x = (0, 1);
/// let _r = via_ref(&x);
/// }
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// Creating unnecessary references is discouraged because it makes code
/// less explicit and can lead to undefined behavior. Creating a reference
/// induces aliasing assumptions that the compiler relies on, so an
/// otherwise-pointless reference can cause undefined behavior even when the
/// reference is never read through. Avoiding them keeps the code more
/// explicit and easier to reason about.
///
/// See the [Reference] for the full set of validity requirements that
/// references must uphold.
///
/// [Reference]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// This lint is "allow" by default because it will trigger for a large
/// amount of existing Rust code.
/// Eventually it is desired for this to become warn-by-default.
pub RAW_BORROWS_VIA_REFERENCES,
// FIXME: This should eventually be `Warn`, see the "Explanation" above.
Allow,
"creating raw borrows via references is discouraged"
}

declare_lint_pass!(RawBorrowsViaReferences => [RAW_BORROWS_VIA_REFERENCES]);

impl<'tcx> LateLintPass<'tcx> for RawBorrowsViaReferences {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
if let ExprKind::Cast(exp, ty) = expr.kind
&& let ExprKind::AddrOf(BorrowKind::Ref, mutbl, addr_of_exp) = exp.kind
&& let TyKind::Ptr(_) = ty.kind
Comment thread
Urgau marked this conversation as resolved.
&& addr_of_exp.is_syntactic_place_expr()
{
let suggestion = if let Some(addr_of_span) =
addr_of_exp.span.find_ancestor_in_same_ctxt(expr.span)
&& let Some(ty_span) = ty.span.find_ancestor_in_same_ctxt(expr.span)
&& expr.span.can_be_used_for_suggestions()
&& addr_of_span.can_be_used_for_suggestions()
&& ty_span.can_be_used_for_suggestions()
{
RawBorrowViaReferenceSuggestion::Spanful {
left: expr.span.until(addr_of_span),
right: addr_of_span.shrink_to_hi().until(ty_span.shrink_to_hi()),
mutbl: mutbl.ptr_str(),
}
} else {
RawBorrowViaReferenceSuggestion::Spanless { mutbl: mutbl.ptr_str() }
};

cx.emit_span_lint(
RAW_BORROWS_VIA_REFERENCES,
expr.span,
RawBorrowViaReference { suggestion },
);
}
}
}
87 changes: 87 additions & 0 deletions tests/ui/lint/lint-raw-borrows-via-references.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//@ check-pass
//@ run-rustfix
//@ rustfix-only-machine-applicable

#![allow(dead_code, unused_variables)]
#![warn(raw_borrows_via_references)]

struct A {
a: i32,
b: u8,
}

fn via_ref(x: *const (i32, i32)) -> *const i32 {
unsafe { &raw const (*x).0 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn via_ref_struct(x: *const A) -> *const u8 {
unsafe { &raw const (*x).b }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn via_ref_mut(x: *mut (i32, i32)) -> *mut i32 {
unsafe { &raw mut (*x).0 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn via_ref_struct_mut(x: *mut A) -> *mut i32 {
unsafe { &raw mut (*x).a }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn multiple_casts(x: *const (i32, i32)) -> *const u8 {
unsafe { &raw const (*x).0 as *const u8 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn ret_i32() -> i32 {
0
}

fn temporaries() {
let _ = &1 as *const i32;
let _ = &(1 + 2) as *const i32;
let _ = &ret_i32() as *const i32;
let _ = &(1, 2) as *const (i32, i32);
let _ = &[1, 2, 3] as *const [i32; 3];
let _ = &A { a: 0, b: 0 } as *const A;
let _ = &mut 4 as *mut i32;
}

fn inner_blocks() {
let x = 0;
let _ = { &raw const x };
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]

let _ = {
let y = 0;
{ &raw const y }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
};

let _ = { &1 as *const i32 };
}

macro_rules! ref_cast {
($e:expr) => {
&$e as *const i32
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
};
}

fn from_macro(x: *const i32) -> *const i32 {
unsafe { ref_cast!(*x) }
}

fn main() {
let a = 0;
let a = &raw const a;
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]

let mut b = 0;
let b = &raw mut b;
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]

let i = &1 as *const i32;
}
87 changes: 87 additions & 0 deletions tests/ui/lint/lint-raw-borrows-via-references.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//@ check-pass
//@ run-rustfix
//@ rustfix-only-machine-applicable

#![allow(dead_code, unused_variables)]
#![warn(raw_borrows_via_references)]

struct A {
a: i32,
b: u8,
}

fn via_ref(x: *const (i32, i32)) -> *const i32 {
unsafe { &(*x).0 as *const i32 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn via_ref_struct(x: *const A) -> *const u8 {
unsafe { &(*x).b as *const u8 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn via_ref_mut(x: *mut (i32, i32)) -> *mut i32 {
unsafe { &mut (*x).0 as *mut i32 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn via_ref_struct_mut(x: *mut A) -> *mut i32 {
unsafe { &mut (*x).a as *mut i32 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn multiple_casts(x: *const (i32, i32)) -> *const u8 {
unsafe { &(*x).0 as *const i32 as *const u8 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
}

fn ret_i32() -> i32 {
0
}

fn temporaries() {
let _ = &1 as *const i32;
let _ = &(1 + 2) as *const i32;
let _ = &ret_i32() as *const i32;
let _ = &(1, 2) as *const (i32, i32);
let _ = &[1, 2, 3] as *const [i32; 3];
let _ = &A { a: 0, b: 0 } as *const A;
let _ = &mut 4 as *mut i32;
}

fn inner_blocks() {
let x = 0;
let _ = { &x as *const i32 };
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]

let _ = {
let y = 0;
{ &y as *const i32 }
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
};

let _ = { &1 as *const i32 };
}

macro_rules! ref_cast {
($e:expr) => {
&$e as *const i32
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]
};
}

fn from_macro(x: *const i32) -> *const i32 {
unsafe { ref_cast!(*x) }
}

fn main() {
let a = 0;
let a = &a as *const i32;
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]

let mut b = 0;
let b = &mut b as *mut i32;
//~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references]

let i = &1 as *const i32;
}
Loading
Loading