Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 7 pull requests #100395

Merged
merged 22 commits into from
Sep 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
847f461
Never inline Windows dtor access
ChrisDenton Aug 1, 2022
127b6c4
cleanup code w/ pointers in std a little
WaffleLapkin Aug 1, 2022
a7c45ec
improve documentation of `pointer::align_offset`
WaffleLapkin Aug 1, 2022
18a21e1
Remove duplicated temporaries creating during box derefs elaboration
tmiasko Aug 6, 2022
7d2131a
./x.py test --bless
tmiasko Aug 6, 2022
d52ed82
move an `assert!` to the right place
WaffleLapkin Aug 9, 2022
5938fd7
rustdoc: simplify highlight.rs
jsha Jul 16, 2022
16bcc18
Improve crate selection on rustdoc search results page
steffahn Jul 3, 2022
e957480
Two small improvements:
steffahn Jul 11, 2022
107e039
Add missing ID into the ID map
GuillaumeGomez Aug 10, 2022
ea05be2
Update GUI test
GuillaumeGomez Aug 10, 2022
e1e25a8
Generalize trait object generic param check to aliases.
cjgillot Aug 7, 2022
0df84ae
Ban indirect references to `Self` too.
cjgillot Aug 7, 2022
a3b84ad
Check if extern crate enum has non exhaustive variant when cast
Jan 10, 2022
dfb3713
Update error message to clarify that it's not the enum itself that's …
scottmcm Aug 10, 2022
23acd82
Rollup merge of #92744 - lambinoo:I-91161-non-exhaustive-foreign-vari…
Dylan-DPC Aug 11, 2022
72d0be4
Rollup merge of #99337 - jsha:simplify-highlight, r=GuillaumeGomez
Dylan-DPC Aug 11, 2022
5b2ad6e
Rollup merge of #100007 - ChrisDenton:dtor-inline-never, r=michaelwoe…
Dylan-DPC Aug 11, 2022
8bdb414
Rollup merge of #100030 - WaffleLapkin:nice_pointer_sis, r=scottmcm
Dylan-DPC Aug 11, 2022
58dc085
Rollup merge of #100192 - tmiasko:rm-duplicated-locals, r=nagisa
Dylan-DPC Aug 11, 2022
a9f3a27
Rollup merge of #100247 - cjgillot:verify-dyn-trait-alias-defaults, r…
Dylan-DPC Aug 11, 2022
5a5cd6b
Rollup merge of #100374 - GuillaumeGomez:improve_rustdoc_search_resul…
Dylan-DPC Aug 11, 2022
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
8 changes: 0 additions & 8 deletions compiler/rustc_mir_transform/src/elaborate_box_derefs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ impl<'tcx, 'a> MutVisitor<'tcx> for ElaborateBoxDerefVisitor<'tcx, 'a> {
build_ptr_tys(tcx, base_ty.boxed_ty(), self.unique_did, self.nonnull_did);

let ptr_local = self.patch.new_temp(ptr_ty, source_info.span);
self.local_decls.push(LocalDecl::new(ptr_ty, source_info.span));

self.patch.add_statement(location, StatementKind::StorageLive(ptr_local));

Expand Down Expand Up @@ -125,13 +124,6 @@ impl<'tcx> MirPass<'tcx> for ElaborateBoxDerefs {
index += 1;
}

if let Some(terminator) = terminator
&& !matches!(terminator.kind, TerminatorKind::Yield{..})
{
let location = Location { block, statement_index: index };
visitor.visit_terminator(terminator, location);
}

let location = Location { block, statement_index: index };
match terminator {
// yielding into a box is handled when lowering generators
Expand Down
156 changes: 77 additions & 79 deletions compiler/rustc_typeck/src/astconv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use rustc_trait_selection::traits::error_reporting::{
};
use rustc_trait_selection::traits::wf::object_region_bounds;

use smallvec::SmallVec;
use smallvec::{smallvec, SmallVec};
use std::collections::BTreeSet;
use std::slice;

Expand Down Expand Up @@ -367,36 +367,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
return (tcx.intern_substs(&[]), arg_count);
}

let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);

struct SubstsForAstPathCtxt<'a, 'tcx> {
astconv: &'a (dyn AstConv<'tcx> + 'a),
def_id: DefId,
generic_args: &'a GenericArgs<'a>,
span: Span,
missing_type_params: Vec<Symbol>,
inferred_params: Vec<Span>,
infer_args: bool,
is_object: bool,
}

impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> {
fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool {
let tcx = self.astconv.tcx();
if let GenericParamDefKind::Type { has_default, .. } = param.kind {
if self.is_object && has_default {
let default_ty = tcx.at(self.span).type_of(param.def_id);
let self_param = tcx.types.self_param;
if default_ty.walk().any(|arg| arg == self_param.into()) {
// There is no suitable inference default for a type parameter
// that references self, in an object type.
return true;
}
}
}

false
}
}

impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
Expand Down Expand Up @@ -499,41 +476,23 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
GenericParamDefKind::Type { has_default, .. } => {
if !infer_args && has_default {
// No type parameter provided, but a default exists.

// If we are converting an object type, then the
// `Self` parameter is unknown. However, some of the
// other type parameters may reference `Self` in their
// defaults. This will lead to an ICE if we are not
// careful!
if self.default_needs_object_self(param) {
self.missing_type_params.push(param.name);
tcx.ty_error().into()
} else {
// This is a default type parameter.
let substs = substs.unwrap();
if substs.iter().any(|arg| match arg.unpack() {
GenericArgKind::Type(ty) => ty.references_error(),
_ => false,
}) {
// Avoid ICE #86756 when type error recovery goes awry.
return tcx.ty_error().into();
}
self.astconv
.normalize_ty(
self.span,
EarlyBinder(tcx.at(self.span).type_of(param.def_id))
.subst(tcx, substs),
)
.into()
let substs = substs.unwrap();
if substs.iter().any(|arg| match arg.unpack() {
GenericArgKind::Type(ty) => ty.references_error(),
_ => false,
}) {
// Avoid ICE #86756 when type error recovery goes awry.
return tcx.ty_error().into();
}
self.astconv
.normalize_ty(
self.span,
EarlyBinder(tcx.at(self.span).type_of(param.def_id))
.subst(tcx, substs),
)
.into()
} else if infer_args {
// No type parameters were provided, we can infer all.
let param = if !self.default_needs_object_self(param) {
Some(param)
} else {
None
};
self.astconv.ty_infer(param, self.span).into()
self.astconv.ty_infer(Some(param), self.span).into()
} else {
// We've already errored above about the mismatch.
tcx.ty_error().into()
Expand Down Expand Up @@ -563,10 +522,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
def_id,
span,
generic_args,
missing_type_params: vec![],
inferred_params: vec![],
infer_args,
is_object,
};
let substs = Self::create_substs_for_generic_args(
tcx,
Expand All @@ -578,13 +535,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
&mut substs_ctx,
);

self.complain_about_missing_type_params(
substs_ctx.missing_type_params,
def_id,
span,
generic_args.args.is_empty(),
);

debug!(
"create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
generics, self_ty, substs
Expand Down Expand Up @@ -1489,23 +1439,71 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// Erase the `dummy_self` (`trait_object_dummy_self`) used above.
let existential_trait_refs = regular_traits.iter().map(|i| {
i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
if trait_ref.self_ty() != dummy_self {
// FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
// which picks up non-supertraits where clauses - but also, the object safety
// completely ignores trait aliases, which could be object safety hazards. We
// `delay_span_bug` here to avoid an ICE in stable even when the feature is
// disabled. (#66420)
tcx.sess.delay_span_bug(
DUMMY_SP,
&format!(
"trait_ref_to_existential called on {:?} with non-dummy Self",
trait_ref,
),
assert_eq!(trait_ref.self_ty(), dummy_self);

// Verify that `dummy_self` did not leak inside default type parameters. This
// could not be done at path creation, since we need to see through trait aliases.
let mut missing_type_params = vec![];
let mut references_self = false;
let generics = tcx.generics_of(trait_ref.def_id);
let substs: Vec<_> = trait_ref
.substs
.iter()
.enumerate()
.skip(1) // Remove `Self` for `ExistentialPredicate`.
.map(|(index, arg)| {
if let ty::GenericArgKind::Type(ty) = arg.unpack() {
debug!(?ty);
if ty == dummy_self {
let param = &generics.params[index];
missing_type_params.push(param.name);
tcx.ty_error().into()
} else if ty.walk().any(|arg| arg == dummy_self.into()) {
references_self = true;
tcx.ty_error().into()
} else {
arg
}
} else {
arg
}
})
.collect();
let substs = tcx.intern_substs(&substs[..]);

let span = i.bottom().1;
let empty_generic_args = trait_bounds.iter().any(|hir_bound| {
hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
&& hir_bound.span.contains(span)
});
self.complain_about_missing_type_params(
missing_type_params,
trait_ref.def_id,
span,
empty_generic_args,
);

if references_self {
let def_id = i.bottom().0.def_id();
let mut err = struct_span_err!(
tcx.sess,
i.bottom().1,
E0038,
"the {} `{}` cannot be made into an object",
tcx.def_kind(def_id).descr(def_id),
tcx.item_name(def_id),
);
err.note(
rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
.error_msg(),
);
err.emit();
}
ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)

ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs }
})
});

let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
bound.map_bound(|b| {
if b.projection_ty.self_ty() != dummy_self {
Expand Down
23 changes: 22 additions & 1 deletion compiler/rustc_typeck/src/check/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use super::FnCtxt;

use crate::hir::def_id::DefId;
use crate::type_error_struct;
use hir::def_id::LOCAL_CRATE;
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
use rustc_hir as hir;
use rustc_hir::lang_items::LangItem;
Expand All @@ -40,7 +41,7 @@ use rustc_middle::ty::adjustment::AllowTwoPhase;
use rustc_middle::ty::cast::{CastKind, CastTy};
use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitable};
use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitable, VariantDef};
use rustc_session::lint;
use rustc_session::Session;
use rustc_span::symbol::sym;
Expand Down Expand Up @@ -173,6 +174,7 @@ pub enum CastError {
/// or "a length". If this argument is None, then the metadata is unknown, for example,
/// when we're typechecking a type parameter with a ?Sized bound.
IntToFatCast(Option<&'static str>),
ForeignNonExhaustiveAdt,
}

impl From<ErrorGuaranteed> for CastError {
Expand Down Expand Up @@ -591,6 +593,17 @@ impl<'a, 'tcx> CastCheck<'tcx> {
}
err.emit();
}
CastError::ForeignNonExhaustiveAdt => {
make_invalid_casting_error(
fcx.tcx.sess,
self.span,
self.expr_ty,
self.cast_ty,
fcx,
)
.note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
.emit();
}
}
}

Expand Down Expand Up @@ -789,6 +802,14 @@ impl<'a, 'tcx> CastCheck<'tcx> {
_ => return Err(CastError::NonScalar),
};

if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
if adt_def.did().krate != LOCAL_CRATE {
if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
return Err(CastError::ForeignNonExhaustiveAdt);
}
}
}

match (t_from, t_cast) {
// These types have invariants! can't cast into them.
(_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
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 @@ -74,7 +74,7 @@ use crate::ptr;
/// {
/// return null_mut();
/// };
/// (self.arena.get() as *mut u8).add(allocated)
/// self.arena.get().cast::<u8>().add(allocated)
/// }
/// unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
/// }
Expand Down
17 changes: 9 additions & 8 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1267,20 +1267,21 @@ impl<T: ?Sized> *const T {
/// Accessing adjacent `u8` as `u16`
///
/// ```
/// # fn foo(n: usize) {
/// # use std::mem::align_of;
/// use std::mem::align_of;
///
/// # unsafe {
/// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
/// let ptr = x.as_ptr().add(n) as *const u8;
/// let x = [5_u8, 6, 7, 8, 9];
/// let ptr = x.as_ptr();
/// let offset = ptr.align_offset(align_of::<u16>());
/// if offset < x.len() - n - 1 {
/// let u16_ptr = ptr.add(offset) as *const u16;
/// assert_ne!(*u16_ptr, 500);
///
/// if offset < x.len() - 1 {
/// let u16_ptr = ptr.add(offset).cast::<u16>();
/// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
/// } else {
/// // while the pointer can be aligned via `offset`, it would point
/// // outside the allocation
/// }
/// # } }
/// # }
/// ```
#[stable(feature = "align_offset", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
Expand Down
19 changes: 11 additions & 8 deletions library/core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1545,20 +1545,23 @@ impl<T: ?Sized> *mut T {
/// Accessing adjacent `u8` as `u16`
///
/// ```
/// # fn foo(n: usize) {
/// # use std::mem::align_of;
/// use std::mem::align_of;
///
/// # unsafe {
/// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
/// let ptr = x.as_ptr().add(n) as *const u8;
/// let mut x = [5_u8, 6, 7, 8, 9];
/// let ptr = x.as_mut_ptr();
/// let offset = ptr.align_offset(align_of::<u16>());
/// if offset < x.len() - n - 1 {
/// let u16_ptr = ptr.add(offset) as *const u16;
/// assert_ne!(*u16_ptr, 500);
///
/// if offset < x.len() - 1 {
/// let u16_ptr = ptr.add(offset).cast::<u16>();
/// *u16_ptr = 0;
///
/// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
/// } else {
/// // while the pointer can be aligned via `offset`, it would point
/// // outside the allocation
/// }
/// # } }
/// # }
/// ```
#[stable(feature = "align_offset", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/slice/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl<'a, T> Iter<'a, T> {
assume(!ptr.is_null());

let end = if mem::size_of::<T>() == 0 {
(ptr as *const u8).wrapping_add(slice.len()) as *const T
ptr.wrapping_byte_add(slice.len())
} else {
ptr.add(slice.len())
};
Expand Down Expand Up @@ -228,7 +228,7 @@ impl<'a, T> IterMut<'a, T> {
assume(!ptr.is_null());

let end = if mem::size_of::<T>() == 0 {
(ptr as *mut u8).wrapping_add(slice.len()) as *mut T
ptr.wrapping_byte_add(slice.len())
} else {
ptr.add(slice.len())
};
Expand Down
Loading