Skip to content

Commit

Permalink
Auto merge of #137143 - matthiaskrgr:rollup-9hapmyd, r=matthiaskrgr
Browse files Browse the repository at this point in the history
Rollup of 8 pull requests

Successful merges:

 - #136986 (Apply unsafe_op_in_unsafe_fn to the standard library)
 - #137012 (add docs and ut for bootstrap util cc-detect)
 - #137072 (Load all builtin targets at once instead of one by one in check-cfg)
 - #137102 (Rework `name_regions` to not rely on reverse scc graph for non-member-constrain usages)
 - #137112 (Don't project into `NonNull` when dropping a `Box`)
 - #137114 (Add an example for `std::error::Error`)
 - #137117 (Fix test that relies on error language)
 - #137119 (fix broken `x {doc, build} core`)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Feb 16, 2025
2 parents 5bc6231 + e802a8c commit d1fb81e
Show file tree
Hide file tree
Showing 50 changed files with 748 additions and 181 deletions.
30 changes: 24 additions & 6 deletions compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use rustc_infer::infer::{NllRegionVariableOrigin, RelateParamBound};
use rustc_middle::bug;
use rustc_middle::hir::place::PlaceBase;
use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
use rustc_middle::ty::{self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeVisitor};
use rustc_middle::ty::fold::fold_regions;
use rustc_middle::ty::{
self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor,
};
use rustc_span::{Ident, Span, kw};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::error_reporting::infer::nice_region_error::{
Expand Down Expand Up @@ -183,6 +186,17 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
}

/// Map the regions in the type to named regions, where possible.
fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
where
T: TypeFoldable<TyCtxt<'tcx>>,
{
fold_regions(tcx, ty, |region, _| match *region {
ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
_ => region,
})
}

/// Returns `true` if a closure is inferred to be an `FnMut` closure.
fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
if let Some(ty::ReLateParam(late_param)) = self.to_error_region(fr).as_deref()
Expand Down Expand Up @@ -314,7 +328,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let type_test_span = type_test.span;

if let Some(lower_bound_region) = lower_bound_region {
let generic_ty = self.regioncx.name_regions(
let generic_ty = self.name_regions(
self.infcx.tcx,
type_test.generic_kind.to_ty(self.infcx.tcx),
);
Expand All @@ -323,7 +337,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
self.body.source.def_id().expect_local(),
type_test_span,
Some(origin),
self.regioncx.name_regions(self.infcx.tcx, type_test.generic_kind),
self.name_regions(self.infcx.tcx, type_test.generic_kind),
lower_bound_region,
));
} else {
Expand Down Expand Up @@ -354,9 +368,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}

RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, key, member_region } => {
let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
let named_key = self.regioncx.name_regions(self.infcx.tcx, key);
let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
let named_ty =
self.regioncx.name_regions_for_member_constraint(self.infcx.tcx, hidden_ty);
let named_key =
self.regioncx.name_regions_for_member_constraint(self.infcx.tcx, key);
let named_region = self
.regioncx
.name_regions_for_member_constraint(self.infcx.tcx, member_region);
let diag = unexpected_hidden_region_diagnostic(
self.infcx,
self.mir_def_id(),
Expand Down
8 changes: 7 additions & 1 deletion compiler/rustc_borrowck/src/region_infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,13 @@ impl<'tcx> RegionInferenceContext<'tcx> {
/// that the regions produced are in fact equal to the named region they are
/// replaced with. This is fine because this function is only to improve the
/// region names in error messages.
pub(crate) fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
///
/// This differs from `MirBorrowckCtxt::name_regions` since it is particularly
/// lax with mapping region vids that are *shorter* than a universal region to
/// that universal region. This is useful for member region constraints since
/// we want to suggest a universal region name to capture even if it's technically
/// not equal to the error region.
pub(crate) fn name_regions_for_member_constraint<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
where
T: TypeFoldable<TyCtxt<'tcx>>,
{
Expand Down
14 changes: 9 additions & 5 deletions compiler/rustc_middle/src/mir/tcx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ impl<'tcx> PlaceTy<'tcx> {
}
}

pub fn multi_projection_ty(
self,
tcx: TyCtxt<'tcx>,
elems: &[PlaceElem<'tcx>],
) -> PlaceTy<'tcx> {
elems.iter().fold(self, |place_ty, &elem| place_ty.projection_ty(tcx, elem))
}

/// Convenience wrapper around `projection_ty_core` for
/// `PlaceElem`, where we can just use the `Ty` that is already
/// stored inline on field projection elems.
Expand Down Expand Up @@ -167,11 +175,7 @@ impl<'tcx> Place<'tcx> {
where
D: HasLocalDecls<'tcx>,
{
projection
.iter()
.fold(PlaceTy::from_ty(local_decls.local_decls()[local].ty), |place_ty, &elem| {
place_ty.projection_ty(tcx, elem)
})
PlaceTy::from_ty(local_decls.local_decls()[local].ty).multi_projection_ty(tcx, projection)
}

pub fn ty<D: ?Sized>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
Expand Down
30 changes: 26 additions & 4 deletions compiler/rustc_mir_transform/src/elaborate_drop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {

// Accessors

fn patch_ref(&self) -> &MirPatch<'tcx>;
fn patch(&mut self) -> &mut MirPatch<'tcx>;
fn body(&self) -> &'a Body<'tcx>;
fn tcx(&self) -> TyCtxt<'tcx>;
Expand Down Expand Up @@ -180,7 +181,14 @@ where
{
#[instrument(level = "trace", skip(self), ret)]
fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
place.ty(self.elaborator.body(), self.tcx()).ty
if place.local < self.elaborator.body().local_decls.next_index() {
place.ty(self.elaborator.body(), self.tcx()).ty
} else {
// We don't have a slice with all the locals, since some are in the patch.
tcx::PlaceTy::from_ty(self.elaborator.patch_ref().local_ty(place.local))
.multi_projection_ty(self.elaborator.tcx(), place.projection)
.ty
}
}

fn tcx(&self) -> TyCtxt<'tcx> {
Expand Down Expand Up @@ -410,12 +418,26 @@ where

let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
let ptr_place = self.tcx().mk_place_field(nonnull_place, FieldIdx::ZERO, ptr_ty);
let interior = self.tcx().mk_place_deref(ptr_place);

let ptr_local = self.new_temp(ptr_ty);

let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
let interior_path = self.elaborator.deref_subpath(self.path);

self.drop_subpath(interior, interior_path, succ, unwind)
let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind);

let setup_bbd = BasicBlockData {
statements: vec![self.assign(
Place::from(ptr_local),
Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
)],
terminator: Some(Terminator {
kind: TerminatorKind::Goto { target: do_drop_bb },
source_info: self.source_info,
}),
is_cleanup: unwind.is_cleanup(),
};
self.elaborator.patch().new_block(setup_bbd)
}

#[instrument(level = "debug", ret)]
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_mir_transform/src/elaborate_drops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,10 @@ impl InitializationData<'_, '_> {
impl<'a, 'tcx> DropElaborator<'a, 'tcx> for ElaborateDropsCtxt<'a, 'tcx> {
type Path = MovePathIndex;

fn patch_ref(&self) -> &MirPatch<'tcx> {
&self.patch
}

fn patch(&mut self) -> &mut MirPatch<'tcx> {
&mut self.patch
}
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_mir_transform/src/patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@ impl<'tcx> MirPatch<'tcx> {
Local::new(index)
}

/// Returns the type of a local that's newly-added in the patch.
pub(crate) fn local_ty(&self, local: Local) -> Ty<'tcx> {
let local = local.as_usize();
assert!(local < self.next_local);
let new_local_idx = self.new_locals.len() - (self.next_local - local);
self.new_locals[new_local_idx].ty
}

pub(crate) fn new_block(&mut self, data: BasicBlockData<'tcx>) -> BasicBlock {
let block = BasicBlock::new(self.patch_map.len());
debug!("MirPatch: new_block: {:?}: {:?}", block, data);
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_mir_transform/src/shim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,9 @@ impl fmt::Debug for DropShimElaborator<'_, '_> {
impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
type Path = ();

fn patch_ref(&self) -> &MirPatch<'tcx> {
&self.patch
}
fn patch(&mut self) -> &mut MirPatch<'tcx> {
&mut self.patch
}
Expand Down
8 changes: 2 additions & 6 deletions compiler/rustc_session/src/config/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
use rustc_lint_defs::BuiltinLintDiag;
use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS;
use rustc_span::{Symbol, sym};
use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTuple};
use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, Target};

use crate::Session;
use crate::config::{CrateType, FmtDebug};
Expand Down Expand Up @@ -432,11 +432,7 @@ impl CheckCfg {
panic!("unable to get all the check-cfg values buckets");
};

for target in TARGETS
.iter()
.map(|target| Target::expect_builtin(&TargetTuple::from_tuple(target)))
.chain(iter::once(current_target.clone()))
{
for target in Target::builtins().chain(iter::once(current_target.clone())) {
values_target_abi.insert(Symbol::intern(&target.options.abi));
values_target_arch.insert(Symbol::intern(&target.arch));
values_target_endian.insert(Symbol::intern(target.options.endian.as_str()));
Expand Down
13 changes: 13 additions & 0 deletions compiler/rustc_target/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1658,6 +1658,14 @@ macro_rules! supported_targets {
Some(t)
}

fn load_all_builtins() -> impl Iterator<Item = Target> {
[
$( targets::$module::target, )+
]
.into_iter()
.map(|f| f())
}

#[cfg(test)]
mod tests {
// Cannot put this into a separate file without duplication, make an exception.
Expand Down Expand Up @@ -3360,6 +3368,11 @@ impl Target {
}
}

/// Load all built-in targets
pub fn builtins() -> impl Iterator<Item = Target> {
load_all_builtins()
}

/// Search for a JSON file specifying the given target tuple.
///
/// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/alloc/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ use crate::{cmp, ptr};
/// {
/// return null_mut();
/// };
/// self.arena.get().cast::<u8>().add(allocated)
/// unsafe { self.arena.get().cast::<u8>().add(allocated) }
/// }
/// unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
/// }
Expand Down
24 changes: 24 additions & 0 deletions library/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,30 @@ use crate::fmt::{self, Debug, Display, Formatter};
/// accessing that error via [`Error::source()`]. This makes it possible for the
/// high-level module to provide its own errors while also revealing some of the
/// implementation for debugging.
///
/// # Example
///
/// Implementing the `Error` trait only requires that `Debug` and `Display` are implemented too.
///
/// ```
/// use std::error::Error;
/// use std::fmt;
/// use std::path::PathBuf;
///
/// #[derive(Debug)]
/// struct ReadConfigError {
/// path: PathBuf
/// }
///
/// impl fmt::Display for ReadConfigError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// let path = self.path.display();
/// write!(f, "unable to read configuration at {path}")
/// }
/// }
///
/// impl Error for ReadConfigError {}
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
#[rustc_has_incoherent_inherent_impls]
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ use crate::{intrinsics, ub_checks};
/// // Safety: `divisor` can't be zero because of `prepare_inputs`,
/// // but the compiler does not know about this. We *promise*
/// // that we always call `prepare_inputs`.
/// std::hint::unreachable_unchecked()
/// unsafe { std::hint::unreachable_unchecked() }
/// }
/// // The compiler would normally introduce a check here that prevents
/// // a division by zero. However, if `divisor` was zero, the branch
Expand Down
8 changes: 4 additions & 4 deletions library/core/src/intrinsics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1703,12 +1703,12 @@ pub const fn forget<T: ?Sized>(_: T) {
/// ```
/// struct R<'a>(&'a i32);
/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
/// std::mem::transmute::<R<'b>, R<'static>>(r)
/// unsafe { std::mem::transmute::<R<'b>, R<'static>>(r) }
/// }
///
/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
/// -> &'b mut R<'c> {
/// std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r)
/// unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) }
/// }
/// ```
///
Expand Down Expand Up @@ -4498,11 +4498,11 @@ pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: us
///
/// // SAFETY: Our precondition ensures the source is aligned and valid,
/// // and `Vec::with_capacity` ensures that we have usable space to write them.
/// ptr::copy(ptr, dst.as_mut_ptr(), elts);
/// unsafe { ptr::copy(ptr, dst.as_mut_ptr(), elts); }
///
/// // SAFETY: We created it with this much capacity earlier,
/// // and the previous `copy` has initialized these elements.
/// dst.set_len(elts);
/// unsafe { dst.set_len(elts); }
/// dst
/// }
/// ```
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/mem/maybe_uninit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ use crate::{fmt, intrinsics, ptr, slice};
///
/// unsafe fn make_vec(out: *mut Vec<i32>) {
/// // `write` does not drop the old contents, which is important.
/// out.write(vec![1, 2, 3]);
/// unsafe { out.write(vec![1, 2, 3]); }
/// }
///
/// let mut v = MaybeUninit::uninit();
Expand Down Expand Up @@ -844,7 +844,7 @@ impl<T> MaybeUninit<T> {
/// # #![allow(unexpected_cfgs)]
/// use std::mem::MaybeUninit;
///
/// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
/// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { unsafe { *buf = [0; 1024] } }
/// # #[cfg(FALSE)]
/// extern "C" {
/// /// Initializes *all* the bytes of the input buffer.
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/mem/transmutability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy};
/// src: ManuallyDrop::new(src),
/// };
///
/// let dst = transmute.dst;
/// let dst = unsafe { transmute.dst };
///
/// ManuallyDrop::into_inner(dst)
/// }
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -724,13 +724,13 @@ impl<T: ?Sized> *const T {
/// that their safety preconditions are met:
/// ```rust
/// # #![feature(ptr_sub_ptr)]
/// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool {
/// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool { unsafe {
/// ptr.sub_ptr(origin) == count
/// # &&
/// origin.add(count) == ptr
/// # &&
/// ptr.sub(count) == origin
/// # }
/// # } }
/// ```
///
/// # Safety
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -896,13 +896,13 @@ impl<T: ?Sized> *mut T {
/// that their safety preconditions are met:
/// ```rust
/// # #![feature(ptr_sub_ptr)]
/// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
/// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool { unsafe {
/// ptr.sub_ptr(origin) == count
/// # &&
/// origin.add(count) == ptr
/// # &&
/// ptr.sub(count) == origin
/// # }
/// # } }
/// ```
///
/// # Safety
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -857,13 +857,13 @@ impl<T: ?Sized> NonNull<T> {
/// that their safety preconditions are met:
/// ```rust
/// # #![feature(ptr_sub_ptr)]
/// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool {
/// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
/// ptr.sub_ptr(origin) == count
/// # &&
/// origin.add(count) == ptr
/// # &&
/// ptr.sub(count) == origin
/// # }
/// # } }
/// ```
///
/// # Safety
Expand Down
Loading

0 comments on commit d1fb81e

Please sign in to comment.