Skip to content

Commit

Permalink
Auto merge of rust-lang#126965 - matthiaskrgr:rollup-x3kamn8, r=matth…
Browse files Browse the repository at this point in the history
…iaskrgr

Rollup of 8 pull requests

Successful merges:

 - rust-lang#126302 (Detect unused structs which derived Default)
 - rust-lang#126885 (Remove internal `PathBuf::as_mut_vec`)
 - rust-lang#126916 (Specify target specific linker for `riscv64gc-gnu` job)
 - rust-lang#126926 (Tweak a confusing comment in `create_match_candidates`)
 - rust-lang#126927 (core: VaArgSafe is an unsafe trait)
 - rust-lang#126932 (Tweak `FlatPat::new` to avoid a temporarily-invalid state)
 - rust-lang#126946 (Add missing slash in `const_eval_select` doc comment)
 - rust-lang#126947 (Delegation: ast lowering refactor)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Jun 25, 2024
2 parents c290e9d + 4ebd69c commit fda509e
Show file tree
Hide file tree
Showing 19 changed files with 227 additions and 116 deletions.
107 changes: 49 additions & 58 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,18 @@ impl<'hir> LoweringContext<'_, 'hir> {
let Ok(sig_id) = sig_id else {
return false;
};
if let Some(local_sig_id) = sig_id.as_local() {
self.has_self(sig_id, span)
}

fn has_self(&self, def_id: DefId, span: Span) -> bool {
if let Some(local_sig_id) = def_id.as_local() {
// The value may be missing due to recursive delegation.
// Error will be emmited later during HIR ty lowering.
self.resolver.delegation_fn_sigs.get(&local_sig_id).map_or(false, |sig| sig.has_self)
} else {
match self.tcx.def_kind(sig_id) {
match self.tcx.def_kind(def_id) {
DefKind::Fn => false,
DefKind::AssocFn => self.tcx.associated_item(sig_id).fn_has_self_parameter,
DefKind::AssocFn => self.tcx.associated_item(def_id).fn_has_self_parameter,
_ => span_bug!(span, "unexpected DefKind for delegation item"),
}
}
Expand Down Expand Up @@ -107,12 +111,17 @@ impl<'hir> LoweringContext<'_, 'hir> {
span: Span,
) -> Result<DefId, ErrorGuaranteed> {
let sig_id = if self.is_in_trait_impl { item_id } else { path_id };
let sig_id =
self.resolver.get_partial_res(sig_id).and_then(|r| r.expect_full_res().opt_def_id());
sig_id.ok_or_else(|| {
self.tcx
.dcx()
.span_delayed_bug(span, "LoweringContext: couldn't resolve delegation item")
self.get_resolution_id(sig_id, span)
}

fn get_resolution_id(&self, node_id: NodeId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let def_id =
self.resolver.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id());
def_id.ok_or_else(|| {
self.tcx.dcx().span_delayed_bug(
span,
format!("LoweringContext: couldn't resolve node {:?} in delegation item", node_id),
)
})
}

Expand All @@ -122,7 +131,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
predicates: &[],
has_where_clause_predicates: false,
where_clause_span: span,
span: span,
span,
})
}

Expand Down Expand Up @@ -222,12 +231,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}));

let path = self.arena.alloc(hir::Path { span, res: Res::Local(param_id), segments });

hir::Expr {
hir_id: self.next_id(),
kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)),
span,
}
self.mk_expr(hir::ExprKind::Path(hir::QPath::Resolved(None, path)), span)
}

fn lower_delegation_body(
Expand All @@ -236,19 +240,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
param_count: usize,
span: Span,
) -> BodyId {
let path = self.lower_qpath(
delegation.id,
&delegation.qself,
&delegation.path,
ParamMode::Optional,
ImplTraitContext::Disallowed(ImplTraitPosition::Path),
None,
);
let block = delegation.body.as_deref();

self.lower_body(|this| {
let mut parameters: Vec<hir::Param<'_>> = Vec::new();
let mut args: Vec<hir::Expr<'hir>> = Vec::new();
let mut parameters: Vec<hir::Param<'_>> = Vec::with_capacity(param_count);
let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);

for idx in 0..param_count {
let (param, pat_node_id) = this.generate_param(span);
Expand All @@ -264,55 +260,49 @@ impl<'hir> LoweringContext<'_, 'hir> {
};
self_resolver.visit_block(block);
let block = this.lower_block(block, false);
hir::Expr {
hir_id: this.next_id(),
kind: hir::ExprKind::Block(block, None),
span: block.span,
}
this.mk_expr(hir::ExprKind::Block(block, None), block.span)
} else {
let pat_hir_id = this.lower_node_id(pat_node_id);
this.generate_arg(pat_hir_id, span)
};
args.push(arg);
}

let args = self.arena.alloc_from_iter(args);
let final_expr = this.generate_call(path, args);
let final_expr = this.finalize_body_lowering(delegation, args, span);
(this.arena.alloc_from_iter(parameters), final_expr)
})
}

fn generate_call(
// Generates fully qualified call for the resulting body.
fn finalize_body_lowering(
&mut self,
path: hir::QPath<'hir>,
args: &'hir [hir::Expr<'hir>],
delegation: &Delegation,
args: Vec<hir::Expr<'hir>>,
span: Span,
) -> hir::Expr<'hir> {
let callee = self.arena.alloc(hir::Expr {
hir_id: self.next_id(),
kind: hir::ExprKind::Path(path),
span: path.span(),
});
let path = self.lower_qpath(
delegation.id,
&delegation.qself,
&delegation.path,
ParamMode::Optional,
ImplTraitContext::Disallowed(ImplTraitPosition::Path),
None,
);

let expr = self.arena.alloc(hir::Expr {
hir_id: self.next_id(),
kind: hir::ExprKind::Call(callee, args),
span: path.span(),
});
let args = self.arena.alloc_from_iter(args);
let path_expr = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(path), span));
let call = self.arena.alloc(self.mk_expr(hir::ExprKind::Call(path_expr, args), span));

let block = self.arena.alloc(hir::Block {
stmts: &[],
expr: Some(expr),
expr: Some(call),
hir_id: self.next_id(),
rules: hir::BlockCheckMode::DefaultBlock,
span: path.span(),
span,
targeted_by_break: false,
});

hir::Expr {
hir_id: self.next_id(),
kind: hir::ExprKind::Block(block, None),
span: path.span(),
}
self.mk_expr(hir::ExprKind::Block(block, None), span)
}

fn generate_delegation_error(
Expand All @@ -333,11 +323,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let header = self.generate_header_error();
let sig = hir::FnSig { decl, header, span };

let body_id = self.lower_body(|this| {
let expr =
hir::Expr { hir_id: this.next_id(), kind: hir::ExprKind::Err(err), span: span };
(&[], expr)
});
let body_id = self.lower_body(|this| (&[], this.mk_expr(hir::ExprKind::Err(err), span)));
DelegationResults { generics, body_id, sig }
}

Expand All @@ -349,6 +335,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
abi: abi::Abi::Rust,
}
}

#[inline]
fn mk_expr(&mut self, kind: hir::ExprKind<'hir>, span: Span) -> hir::Expr<'hir> {
hir::Expr { hir_id: self.next_id(), kind, span }
}
}

struct SelfResolver<'a> {
Expand Down
40 changes: 27 additions & 13 deletions compiler/rustc_mir_build/src/build/matches/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,8 +358,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
where
'a: 'pat,
{
// Assemble a list of candidates: there is one candidate per pattern,
// which means there may be more than one candidate *per arm*.
// Assemble the initial list of candidates. These top-level candidates
// are 1:1 with the original match arms, but other parts of match
// lowering also introduce subcandidates (for subpatterns), and will
// also flatten candidates in some cases. So in general a list of
// candidates does _not_ necessarily correspond to a list of arms.
arms.iter()
.copied()
.map(|arm| {
Expand Down Expand Up @@ -1031,6 +1034,12 @@ impl<'tcx> PatternExtraData<'tcx> {
}

/// A pattern in a form suitable for generating code.
///
/// Here, "flat" indicates that the pattern's match pairs have been recursively
/// simplified by [`Builder::simplify_match_pairs`]. They are not necessarily
/// flat in an absolute sense.
///
/// Will typically be incorporated into a [`Candidate`].
#[derive(Debug, Clone)]
struct FlatPat<'pat, 'tcx> {
/// To match the pattern, all of these must be satisfied...
Expand All @@ -1042,23 +1051,25 @@ struct FlatPat<'pat, 'tcx> {
}

impl<'tcx, 'pat> FlatPat<'pat, 'tcx> {
/// Creates a `FlatPat` containing a simplified [`MatchPair`] list/forest
/// for the given pattern.
fn new(
place: PlaceBuilder<'tcx>,
pattern: &'pat Pat<'tcx>,
cx: &mut Builder<'_, 'tcx>,
) -> Self {
let is_never = pattern.is_never_pattern();
let mut flat_pat = FlatPat {
match_pairs: vec![MatchPair::new(place, pattern, cx)],
extra_data: PatternExtraData {
span: pattern.span,
bindings: Vec::new(),
ascriptions: Vec::new(),
is_never,
},
// First, recursively build a tree of match pairs for the given pattern.
let mut match_pairs = vec![MatchPair::new(place, pattern, cx)];
let mut extra_data = PatternExtraData {
span: pattern.span,
bindings: Vec::new(),
ascriptions: Vec::new(),
is_never: pattern.is_never_pattern(),
};
cx.simplify_match_pairs(&mut flat_pat.match_pairs, &mut flat_pat.extra_data);
flat_pat
// Partly-flatten and sort the match pairs, while recording extra data.
cx.simplify_match_pairs(&mut match_pairs, &mut extra_data);

Self { match_pairs, extra_data }
}
}

Expand Down Expand Up @@ -1104,9 +1115,12 @@ impl<'tcx, 'pat> Candidate<'pat, 'tcx> {
has_guard: bool,
cx: &mut Builder<'_, 'tcx>,
) -> Self {
// Use `FlatPat` to build simplified match pairs, then immediately
// incorporate them into a new candidate.
Self::from_flat_pat(FlatPat::new(place, pattern, cx), has_guard)
}

/// Incorporates an already-simplified [`FlatPat`] into a new candidate.
fn from_flat_pat(flat_pat: FlatPat<'pat, 'tcx>, has_guard: bool) -> Self {
Candidate {
match_pairs: flat_pat.match_pairs,
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_mir_build/src/build/matches/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
}

impl<'pat, 'tcx> MatchPair<'pat, 'tcx> {
/// Recursively builds a `MatchPair` tree for the given pattern and its
/// subpatterns.
pub(in crate::build) fn new(
mut place_builder: PlaceBuilder<'tcx>,
pattern: &'pat Pat<'tcx>,
Expand Down
25 changes: 25 additions & 0 deletions compiler/rustc_passes/src/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,31 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
return false;
}

// don't ignore impls for Enums and pub Structs whose methods don't have self receiver,
// cause external crate may call such methods to construct values of these types
if let Some(local_impl_of) = impl_of.as_local()
&& let Some(local_def_id) = def_id.as_local()
&& let Some(fn_sig) =
self.tcx.hir().fn_sig_by_hir_id(self.tcx.local_def_id_to_hir_id(local_def_id))
&& matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None)
&& let TyKind::Path(hir::QPath::Resolved(_, path)) =
self.tcx.hir().expect_item(local_impl_of).expect_impl().self_ty.kind
&& let Res::Def(def_kind, did) = path.res
{
match def_kind {
// for example, #[derive(Default)] pub struct T(i32);
// external crate can call T::default() to construct T,
// so that don't ignore impl Default for pub Enum and Structs
DefKind::Struct | DefKind::Union if self.tcx.visibility(did).is_public() => {
return false;
}
// don't ignore impl Default for Enums,
// cause we don't know which variant is constructed
DefKind::Enum => return false,
_ => (),
};
}

if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of)
&& self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads)
{
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/sync/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ fn show_arc() {

// Make sure deriving works with Arc<T>
#[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
struct Foo {
struct _Foo {
inner: Arc<i32>,
}

Expand Down
1 change: 1 addition & 0 deletions library/core/src/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ use crate::ascii::Char as AsciiChar;
/// ```
#[cfg_attr(not(test), rustc_diagnostic_item = "Default")]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(bootstrap), rustc_trivial_field_reads)]
pub trait Default: Sized {
/// Returns the "default value" for a type.
///
Expand Down
9 changes: 5 additions & 4 deletions library/core/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ mod sealed_trait {
all supported platforms",
issue = "44930"
)]
pub trait VaArgSafe {}
pub unsafe trait VaArgSafe {}
}

macro_rules! impl_va_arg_safe {
Expand All @@ -494,7 +494,7 @@ macro_rules! impl_va_arg_safe {
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
impl sealed_trait::VaArgSafe for $t {}
unsafe impl sealed_trait::VaArgSafe for $t {}
)+
}
}
Expand All @@ -509,14 +509,15 @@ impl_va_arg_safe! {f64}
all supported platforms",
issue = "44930"
)]
impl<T> sealed_trait::VaArgSafe for *mut T {}
unsafe impl<T> sealed_trait::VaArgSafe for *mut T {}

#[unstable(
feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930"
)]
impl<T> sealed_trait::VaArgSafe for *const T {}
unsafe impl<T> sealed_trait::VaArgSafe for *const T {}

#[unstable(
feature = "c_variadic",
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2579,7 +2579,7 @@ extern "rust-intrinsic" {
/// fn runtime() -> i32 { 1 }
/// const fn compiletime() -> i32 { 2 }
///
// // ⚠ This code violates the required equivalence of `compiletime`
/// // ⚠ This code violates the required equivalence of `compiletime`
/// // and `runtime`.
/// const_eval_select((), compiletime, runtime)
/// }
Expand Down
16 changes: 13 additions & 3 deletions library/std/src/ffi/os_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,10 +552,20 @@ impl OsString {
OsStr::from_inner_mut(self.inner.leak())
}

/// Part of a hack to make PathBuf::push/pop more efficient.
/// Provides plumbing to core `Vec::truncate`.
/// More well behaving alternative to allowing outer types
/// full mutable access to the core `Vec`.
#[inline]
pub(crate) fn as_mut_vec_for_path_buf(&mut self) -> &mut Vec<u8> {
self.inner.as_mut_vec_for_path_buf()
pub(crate) fn truncate(&mut self, len: usize) {
self.inner.truncate(len);
}

/// Provides plumbing to core `Vec::extend_from_slice`.
/// More well behaving alternative to allowing outer types
/// full mutable access to the core `Vec`.
#[inline]
pub(crate) fn extend_from_slice(&mut self, other: &[u8]) {
self.inner.extend_from_slice(other);
}
}

Expand Down
Loading

0 comments on commit fda509e

Please sign in to comment.