Skip to content

Commit fffb33d

Browse files
committed
Auto merge of rust-lang#137124 - matthiaskrgr:rollup-0yymflu, r=matthiaskrgr
Rollup of 9 pull requests Successful merges: - rust-lang#125087 (Optimize `Seek::stream_len` impl for `File`) - rust-lang#136986 (Apply unsafe_op_in_unsafe_fn to the standard library) - rust-lang#137012 (add docs and ut for bootstrap util cc-detect) - rust-lang#137072 (Load all builtin targets at once instead of one by one in check-cfg) - rust-lang#137102 (Rework `name_regions` to not rely on reverse scc graph for non-member-constrain usages) - rust-lang#137112 (Don't project into `NonNull` when dropping a `Box`) - rust-lang#137114 (Add an example for `std::error::Error`) - rust-lang#137117 (Fix test that relies on error language) - rust-lang#137119 (fix broken `x {doc, build} core`) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 23032f3 + 29e62d4 commit fffb33d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+833
-192
lines changed

compiler/rustc_borrowck/src/diagnostics/region_errors.rs

+24-6
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ use rustc_infer::infer::{NllRegionVariableOrigin, RelateParamBound};
1414
use rustc_middle::bug;
1515
use rustc_middle::hir::place::PlaceBase;
1616
use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
17-
use rustc_middle::ty::{self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeVisitor};
17+
use rustc_middle::ty::fold::fold_regions;
18+
use rustc_middle::ty::{
19+
self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor,
20+
};
1821
use rustc_span::{Ident, Span, kw};
1922
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
2023
use rustc_trait_selection::error_reporting::infer::nice_region_error::{
@@ -183,6 +186,17 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
183186
}
184187
}
185188

189+
/// Map the regions in the type to named regions, where possible.
190+
fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
191+
where
192+
T: TypeFoldable<TyCtxt<'tcx>>,
193+
{
194+
fold_regions(tcx, ty, |region, _| match *region {
195+
ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
196+
_ => region,
197+
})
198+
}
199+
186200
/// Returns `true` if a closure is inferred to be an `FnMut` closure.
187201
fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
188202
if let Some(ty::ReLateParam(late_param)) = self.to_error_region(fr).as_deref()
@@ -314,7 +328,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
314328
let type_test_span = type_test.span;
315329

316330
if let Some(lower_bound_region) = lower_bound_region {
317-
let generic_ty = self.regioncx.name_regions(
331+
let generic_ty = self.name_regions(
318332
self.infcx.tcx,
319333
type_test.generic_kind.to_ty(self.infcx.tcx),
320334
);
@@ -323,7 +337,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
323337
self.body.source.def_id().expect_local(),
324338
type_test_span,
325339
Some(origin),
326-
self.regioncx.name_regions(self.infcx.tcx, type_test.generic_kind),
340+
self.name_regions(self.infcx.tcx, type_test.generic_kind),
327341
lower_bound_region,
328342
));
329343
} else {
@@ -354,9 +368,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
354368
}
355369

356370
RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, key, member_region } => {
357-
let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
358-
let named_key = self.regioncx.name_regions(self.infcx.tcx, key);
359-
let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
371+
let named_ty =
372+
self.regioncx.name_regions_for_member_constraint(self.infcx.tcx, hidden_ty);
373+
let named_key =
374+
self.regioncx.name_regions_for_member_constraint(self.infcx.tcx, key);
375+
let named_region = self
376+
.regioncx
377+
.name_regions_for_member_constraint(self.infcx.tcx, member_region);
360378
let diag = unexpected_hidden_region_diagnostic(
361379
self.infcx,
362380
self.mir_def_id(),

compiler/rustc_borrowck/src/region_infer/opaque_types.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,13 @@ impl<'tcx> RegionInferenceContext<'tcx> {
204204
/// that the regions produced are in fact equal to the named region they are
205205
/// replaced with. This is fine because this function is only to improve the
206206
/// region names in error messages.
207-
pub(crate) fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
207+
///
208+
/// This differs from `MirBorrowckCtxt::name_regions` since it is particularly
209+
/// lax with mapping region vids that are *shorter* than a universal region to
210+
/// that universal region. This is useful for member region constraints since
211+
/// we want to suggest a universal region name to capture even if it's technically
212+
/// not equal to the error region.
213+
pub(crate) fn name_regions_for_member_constraint<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
208214
where
209215
T: TypeFoldable<TyCtxt<'tcx>>,
210216
{

compiler/rustc_middle/src/mir/tcx.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,14 @@ impl<'tcx> PlaceTy<'tcx> {
8686
}
8787
}
8888

89+
pub fn multi_projection_ty(
90+
self,
91+
tcx: TyCtxt<'tcx>,
92+
elems: &[PlaceElem<'tcx>],
93+
) -> PlaceTy<'tcx> {
94+
elems.iter().fold(self, |place_ty, &elem| place_ty.projection_ty(tcx, elem))
95+
}
96+
8997
/// Convenience wrapper around `projection_ty_core` for
9098
/// `PlaceElem`, where we can just use the `Ty` that is already
9199
/// stored inline on field projection elems.
@@ -167,11 +175,7 @@ impl<'tcx> Place<'tcx> {
167175
where
168176
D: HasLocalDecls<'tcx>,
169177
{
170-
projection
171-
.iter()
172-
.fold(PlaceTy::from_ty(local_decls.local_decls()[local].ty), |place_ty, &elem| {
173-
place_ty.projection_ty(tcx, elem)
174-
})
178+
PlaceTy::from_ty(local_decls.local_decls()[local].ty).multi_projection_ty(tcx, projection)
175179
}
176180

177181
pub fn ty<D: ?Sized>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>

compiler/rustc_mir_transform/src/elaborate_drop.rs

+26-4
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
8989

9090
// Accessors
9191

92+
fn patch_ref(&self) -> &MirPatch<'tcx>;
9293
fn patch(&mut self) -> &mut MirPatch<'tcx>;
9394
fn body(&self) -> &'a Body<'tcx>;
9495
fn tcx(&self) -> TyCtxt<'tcx>;
@@ -180,7 +181,14 @@ where
180181
{
181182
#[instrument(level = "trace", skip(self), ret)]
182183
fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
183-
place.ty(self.elaborator.body(), self.tcx()).ty
184+
if place.local < self.elaborator.body().local_decls.next_index() {
185+
place.ty(self.elaborator.body(), self.tcx()).ty
186+
} else {
187+
// We don't have a slice with all the locals, since some are in the patch.
188+
tcx::PlaceTy::from_ty(self.elaborator.patch_ref().local_ty(place.local))
189+
.multi_projection_ty(self.elaborator.tcx(), place.projection)
190+
.ty
191+
}
184192
}
185193

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

411419
let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
412420
let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
413-
let ptr_place = self.tcx().mk_place_field(nonnull_place, FieldIdx::ZERO, ptr_ty);
414-
let interior = self.tcx().mk_place_deref(ptr_place);
415421

422+
let ptr_local = self.new_temp(ptr_ty);
423+
424+
let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
416425
let interior_path = self.elaborator.deref_subpath(self.path);
417426

418-
self.drop_subpath(interior, interior_path, succ, unwind)
427+
let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind);
428+
429+
let setup_bbd = BasicBlockData {
430+
statements: vec![self.assign(
431+
Place::from(ptr_local),
432+
Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
433+
)],
434+
terminator: Some(Terminator {
435+
kind: TerminatorKind::Goto { target: do_drop_bb },
436+
source_info: self.source_info,
437+
}),
438+
is_cleanup: unwind.is_cleanup(),
439+
};
440+
self.elaborator.patch().new_block(setup_bbd)
419441
}
420442

421443
#[instrument(level = "debug", ret)]

compiler/rustc_mir_transform/src/elaborate_drops.rs

+4
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,10 @@ impl InitializationData<'_, '_> {
138138
impl<'a, 'tcx> DropElaborator<'a, 'tcx> for ElaborateDropsCtxt<'a, 'tcx> {
139139
type Path = MovePathIndex;
140140

141+
fn patch_ref(&self) -> &MirPatch<'tcx> {
142+
&self.patch
143+
}
144+
141145
fn patch(&mut self) -> &mut MirPatch<'tcx> {
142146
&mut self.patch
143147
}

compiler/rustc_mir_transform/src/patch.rs

+8
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,14 @@ impl<'tcx> MirPatch<'tcx> {
166166
Local::new(index)
167167
}
168168

169+
/// Returns the type of a local that's newly-added in the patch.
170+
pub(crate) fn local_ty(&self, local: Local) -> Ty<'tcx> {
171+
let local = local.as_usize();
172+
assert!(local < self.next_local);
173+
let new_local_idx = self.new_locals.len() - (self.next_local - local);
174+
self.new_locals[new_local_idx].ty
175+
}
176+
169177
pub(crate) fn new_block(&mut self, data: BasicBlockData<'tcx>) -> BasicBlock {
170178
let block = BasicBlock::new(self.patch_map.len());
171179
debug!("MirPatch: new_block: {:?}: {:?}", block, data);

compiler/rustc_mir_transform/src/shim.rs

+3
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,9 @@ impl fmt::Debug for DropShimElaborator<'_, '_> {
350350
impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
351351
type Path = ();
352352

353+
fn patch_ref(&self) -> &MirPatch<'tcx> {
354+
&self.patch
355+
}
353356
fn patch(&mut self) -> &mut MirPatch<'tcx> {
354357
&mut self.patch
355358
}

compiler/rustc_session/src/config/cfg.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
2929
use rustc_lint_defs::BuiltinLintDiag;
3030
use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS;
3131
use rustc_span::{Symbol, sym};
32-
use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTuple};
32+
use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, Target};
3333

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

435-
for target in TARGETS
436-
.iter()
437-
.map(|target| Target::expect_builtin(&TargetTuple::from_tuple(target)))
438-
.chain(iter::once(current_target.clone()))
439-
{
435+
for target in Target::builtins().chain(iter::once(current_target.clone())) {
440436
values_target_abi.insert(Symbol::intern(&target.options.abi));
441437
values_target_arch.insert(Symbol::intern(&target.arch));
442438
values_target_endian.insert(Symbol::intern(target.options.endian.as_str()));

compiler/rustc_target/src/spec/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -1658,6 +1658,14 @@ macro_rules! supported_targets {
16581658
Some(t)
16591659
}
16601660

1661+
fn load_all_builtins() -> impl Iterator<Item = Target> {
1662+
[
1663+
$( targets::$module::target, )+
1664+
]
1665+
.into_iter()
1666+
.map(|f| f())
1667+
}
1668+
16611669
#[cfg(test)]
16621670
mod tests {
16631671
// Cannot put this into a separate file without duplication, make an exception.
@@ -3360,6 +3368,11 @@ impl Target {
33603368
}
33613369
}
33623370

3371+
/// Load all built-in targets
3372+
pub fn builtins() -> impl Iterator<Item = Target> {
3373+
load_all_builtins()
3374+
}
3375+
33633376
/// Search for a JSON file specifying the given target tuple.
33643377
///
33653378
/// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the

library/core/src/alloc/global.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ use crate::{cmp, ptr};
7070
/// {
7171
/// return null_mut();
7272
/// };
73-
/// self.arena.get().cast::<u8>().add(allocated)
73+
/// unsafe { self.arena.get().cast::<u8>().add(allocated) }
7474
/// }
7575
/// unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
7676
/// }

library/core/src/error.rs

+24
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,30 @@ use crate::fmt::{self, Debug, Display, Formatter};
2222
/// accessing that error via [`Error::source()`]. This makes it possible for the
2323
/// high-level module to provide its own errors while also revealing some of the
2424
/// implementation for debugging.
25+
///
26+
/// # Example
27+
///
28+
/// Implementing the `Error` trait only requires that `Debug` and `Display` are implemented too.
29+
///
30+
/// ```
31+
/// use std::error::Error;
32+
/// use std::fmt;
33+
/// use std::path::PathBuf;
34+
///
35+
/// #[derive(Debug)]
36+
/// struct ReadConfigError {
37+
/// path: PathBuf
38+
/// }
39+
///
40+
/// impl fmt::Display for ReadConfigError {
41+
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42+
/// let path = self.path.display();
43+
/// write!(f, "unable to read configuration at {path}")
44+
/// }
45+
/// }
46+
///
47+
/// impl Error for ReadConfigError {}
48+
/// ```
2549
#[stable(feature = "rust1", since = "1.0.0")]
2650
#[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
2751
#[rustc_has_incoherent_inherent_impls]

library/core/src/hint.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ use crate::{intrinsics, ub_checks};
5252
/// // Safety: `divisor` can't be zero because of `prepare_inputs`,
5353
/// // but the compiler does not know about this. We *promise*
5454
/// // that we always call `prepare_inputs`.
55-
/// std::hint::unreachable_unchecked()
55+
/// unsafe { std::hint::unreachable_unchecked() }
5656
/// }
5757
/// // The compiler would normally introduce a check here that prevents
5858
/// // a division by zero. However, if `divisor` was zero, the branch

library/core/src/intrinsics/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1703,12 +1703,12 @@ pub const fn forget<T: ?Sized>(_: T) {
17031703
/// ```
17041704
/// struct R<'a>(&'a i32);
17051705
/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
1706-
/// std::mem::transmute::<R<'b>, R<'static>>(r)
1706+
/// unsafe { std::mem::transmute::<R<'b>, R<'static>>(r) }
17071707
/// }
17081708
///
17091709
/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
17101710
/// -> &'b mut R<'c> {
1711-
/// std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r)
1711+
/// unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) }
17121712
/// }
17131713
/// ```
17141714
///
@@ -4498,11 +4498,11 @@ pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: us
44984498
///
44994499
/// // SAFETY: Our precondition ensures the source is aligned and valid,
45004500
/// // and `Vec::with_capacity` ensures that we have usable space to write them.
4501-
/// ptr::copy(ptr, dst.as_mut_ptr(), elts);
4501+
/// unsafe { ptr::copy(ptr, dst.as_mut_ptr(), elts); }
45024502
///
45034503
/// // SAFETY: We created it with this much capacity earlier,
45044504
/// // and the previous `copy` has initialized these elements.
4505-
/// dst.set_len(elts);
4505+
/// unsafe { dst.set_len(elts); }
45064506
/// dst
45074507
/// }
45084508
/// ```

library/core/src/mem/maybe_uninit.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ use crate::{fmt, intrinsics, ptr, slice};
9898
///
9999
/// unsafe fn make_vec(out: *mut Vec<i32>) {
100100
/// // `write` does not drop the old contents, which is important.
101-
/// out.write(vec![1, 2, 3]);
101+
/// unsafe { out.write(vec![1, 2, 3]); }
102102
/// }
103103
///
104104
/// let mut v = MaybeUninit::uninit();
@@ -844,7 +844,7 @@ impl<T> MaybeUninit<T> {
844844
/// # #![allow(unexpected_cfgs)]
845845
/// use std::mem::MaybeUninit;
846846
///
847-
/// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
847+
/// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { unsafe { *buf = [0; 1024] } }
848848
/// # #[cfg(FALSE)]
849849
/// extern "C" {
850850
/// /// Initializes *all* the bytes of the input buffer.

library/core/src/mem/transmutability.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy};
3232
/// src: ManuallyDrop::new(src),
3333
/// };
3434
///
35-
/// let dst = transmute.dst;
35+
/// let dst = unsafe { transmute.dst };
3636
///
3737
/// ManuallyDrop::into_inner(dst)
3838
/// }

library/core/src/ptr/const_ptr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -724,13 +724,13 @@ impl<T: ?Sized> *const T {
724724
/// that their safety preconditions are met:
725725
/// ```rust
726726
/// # #![feature(ptr_sub_ptr)]
727-
/// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool {
727+
/// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool { unsafe {
728728
/// ptr.sub_ptr(origin) == count
729729
/// # &&
730730
/// origin.add(count) == ptr
731731
/// # &&
732732
/// ptr.sub(count) == origin
733-
/// # }
733+
/// # } }
734734
/// ```
735735
///
736736
/// # Safety

library/core/src/ptr/mut_ptr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -896,13 +896,13 @@ impl<T: ?Sized> *mut T {
896896
/// that their safety preconditions are met:
897897
/// ```rust
898898
/// # #![feature(ptr_sub_ptr)]
899-
/// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
899+
/// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool { unsafe {
900900
/// ptr.sub_ptr(origin) == count
901901
/// # &&
902902
/// origin.add(count) == ptr
903903
/// # &&
904904
/// ptr.sub(count) == origin
905-
/// # }
905+
/// # } }
906906
/// ```
907907
///
908908
/// # Safety

library/core/src/ptr/non_null.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -857,13 +857,13 @@ impl<T: ?Sized> NonNull<T> {
857857
/// that their safety preconditions are met:
858858
/// ```rust
859859
/// # #![feature(ptr_sub_ptr)]
860-
/// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool {
860+
/// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
861861
/// ptr.sub_ptr(origin) == count
862862
/// # &&
863863
/// origin.add(count) == ptr
864864
/// # &&
865865
/// ptr.sub(count) == origin
866-
/// # }
866+
/// # } }
867867
/// ```
868868
///
869869
/// # Safety

0 commit comments

Comments
 (0)