Skip to content
Draft
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
123 changes: 90 additions & 33 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ use crate::diagnostics::{
};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
re_lowering,
};

mod generics;
Expand Down Expand Up @@ -248,6 +249,17 @@ impl<'hir> LoweringContext<'_, 'hir> {
return false;
}

// If there are definitions inside and we can't delete target expression, so report an error.
// FIXME(fn_delegation): support deletion of target expression with defs inside.
if !should_generate_block && self.any_defs_in_block(block) {
self.dcx().emit_err(DelegationAttemptedBlockWithDefsDeletion { span: block.span });
return false;
}

true
}

fn any_defs_in_block(&self, block: &Block) -> bool {
struct DefinitionsFinder<'a> {
all_owners: &'a NodeMap<PerOwnerResolverData<'a>>,
// `self.owner.node_id_to_def_id`
Expand Down Expand Up @@ -284,16 +296,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
nested_def_ids: &self.owner.node_id_to_def_id,
};

let contains_defs = collector.visit_block(block).is_break();

// If there are definitions inside and we can't delete target expression, so report an error.
// FIXME(fn_delegation): support deletion of target expression with defs inside.
if !should_generate_block && contains_defs {
self.dcx().emit_err(DelegationAttemptedBlockWithDefsDeletion { span: block.span });
return false;
}

true
collector.visit_block(block).is_break()
}

fn should_generate_block(
Expand Down Expand Up @@ -529,7 +532,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let block_id = self.lower_body(|this| {
let mut parameters: Vec<hir::Param<'_>> = Vec::with_capacity(param_count);
let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);
let mut stmts: &[hir::Stmt<'hir>] = &[];
let mut stmts = vec![];

let is_method = this.is_method(sig_id, span);
let should_generate_block = this.should_generate_block(delegation, sig_id, is_method);
Expand All @@ -546,25 +549,20 @@ impl<'hir> LoweringContext<'_, 'hir> {
let generate_arg =
|this: &mut Self| this.generate_arg(is_method, idx, param.pat.hir_id, span);

let param_local_id = param.pat.hir_id.local_id;
let arg = if let Some(block) = block
&& idx == 0
&& should_generate_block
&& (idx == 0 && should_generate_block
|| this.can_map_argument(delegation, sig_id, idx)
&& !this.any_defs_in_block(block))
{
let mut self_resolver = SelfResolver {
ctxt: this,
path_id: delegation.id,
self_param_id: pat_node_id,
};
self_resolver.visit_block(block);
// Target expr needs to lower `self` path.
this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id);

// Lower with `HirId::INVALID` as we will use only expr and stmts.
// FIXME(fn_delegation): Alternatives for target expression lowering:
// https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2197170600.
let block = this.lower_block_noalloc(HirId::INVALID, block, false);

stmts = block.stmts;
let block = this.lower_block_maybe_more_than_once(
block,
pat_node_id,
param_local_id,
delegation.id,
);

stmts.push(block.stmts);

// The behavior of the delegation's target expression differs from the
// behavior of the usual block, where if there is no final expression
Expand All @@ -579,8 +577,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
args.push(arg);
}

let (final_expr, hir_id) =
this.finalize_body_lowering(delegation, stmts, args, generics, span);
let (final_expr, hir_id) = this.finalize_body_lowering(
delegation,
sig_id,
this.arena.alloc_from_iter(stmts.into_iter().flatten().copied()),
args,
generics,
span,
);

call_expr_id = hir_id;

Expand All @@ -592,9 +596,50 @@ impl<'hir> LoweringContext<'_, 'hir> {
(block_id, call_expr_id, unused_target_expr)
}

fn can_map_argument(&self, delegation: &Delegation, sig_id: DefId, arg_index: usize) -> bool {
self.can_perform_mapping(delegation)
.filter(|_| {
self.tcx.fn_sig(sig_id).skip_binder().input(arg_index).skip_binder().is_param(0)
})
.is_some()
}

fn lower_block_maybe_more_than_once(
&mut self,
block: &Block,
pat_node_id: NodeId,
param_local_id: hir::ItemLocalId,
delegation_id: NodeId,
) -> hir::Block<'hir> {
let mut self_resolver = SelfResolver {
ctxt: self,
path_id: delegation_id,
self_param_id: pat_node_id,
overwrites: vec![],
};

self_resolver.visit_block(block);

let overwrites = self_resolver.overwrites;

// Target expr needs to lower `self` path.
self.ident_and_label_to_local_id.insert(pat_node_id, param_local_id);

let block = re_lowering::ReloweringChecker::allow_relowering(self, |this| {
this.lower_block_noalloc(HirId::INVALID, block, false)
});

for id in overwrites {
self.partial_res_overrides.remove(&id);
}

block
}

fn finalize_body_lowering(
&mut self,
delegation: &Delegation,
sig_id: DefId,
stmts: &'hir [hir::Stmt<'hir>],
args: Vec<hir::Expr<'hir>>,
generics: &mut GenericsGenerationResults<'hir>,
Expand Down Expand Up @@ -666,7 +711,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
let args = self.arena.alloc_from_iter(args);
let call = self.mk_expr(hir::ExprKind::Call(callee_path, args), span);

let expr = if let Some((parent, of_trait)) = self.should_wrap_return_value(delegation) {
let expr = if let Some((parent, of_trait)) =
self.should_wrap_return_value(delegation, sig_id)
{
let res = Res::SelfTyAlias { alias_to: parent.to_def_id(), is_trait_impl: of_trait };
let ident = Ident::new(kw::SelfUpper, span);
let path = self.create_resolved_path(res, ident, span);
Expand Down Expand Up @@ -701,7 +748,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
(self.mk_expr(hir::ExprKind::Block(block, None), span), call.hir_id)
}

fn should_wrap_return_value(&self, delegation: &Delegation) -> Option<(LocalDefId, bool)> {
fn can_perform_mapping(&self, delegation: &Delegation) -> Option<(LocalDefId, bool)> {
// Heuristic: don't do wrapping if there is no target expression.
if delegation.body.is_none() {
return None;
Expand Down Expand Up @@ -735,11 +782,19 @@ impl<'hir> LoweringContext<'_, 'hir> {
// After previous check we are sure that `sig_id` and `delegation.id`
// point to the same function.
&& tcx.def_kind(tcx.parent(id)) == DefKind::Trait
&& tcx.fn_sig(id).skip_binder().output().skip_binder().is_param(0)
})
})
}

fn should_wrap_return_value(
&self,
delegation: &Delegation,
sig_id: DefId,
) -> Option<(LocalDefId, bool)> {
self.can_perform_mapping(delegation)
.filter(|_| self.tcx.fn_sig(sig_id).skip_binder().output().skip_binder().is_param(0))
}

fn process_segment(
&mut self,
span: Span,
Expand Down Expand Up @@ -851,6 +906,7 @@ struct SelfResolver<'a, 'b, 'hir> {
ctxt: &'a mut LoweringContext<'b, 'hir>,
path_id: NodeId,
self_param_id: NodeId,
overwrites: Vec<NodeId>,
}

impl SelfResolver<'_, '_, '_> {
Expand All @@ -859,6 +915,7 @@ impl SelfResolver<'_, '_, '_> {
&& let Some(Res::Local(sig_id)) = res.full_res()
&& sig_id == self.path_id
{
self.overwrites.push(id);
self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
}
}
Expand Down
62 changes: 50 additions & 12 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,48 @@ pub fn provide(providers: &mut Providers) {
providers.lower_to_hir = lower_to_hir;
}

pub(crate) mod re_lowering {
use rustc_ast::NodeId;
use rustc_ast::node_id::NodeMap;
use rustc_hir::{self as hir};

use crate::LoweringContext;

#[derive(Debug, Default)]
pub(crate) struct ReloweringChecker {
node_id_to_local_id: NodeMap<hir::ItemLocalId>,
relowering_permissions_count: usize,
}

impl ReloweringChecker {
pub(crate) fn check(&mut self, ast_node_id: NodeId, local_id: hir::ItemLocalId) {
if self.relowering_permissions_count == 0 {
let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
assert_eq!(old, None);
}
}

pub(crate) fn allow_relowering<'a, 'hir, TRes>(
ctx: &mut LoweringContext<'a, 'hir>,
op: impl FnOnce(&mut LoweringContext<'a, 'hir>) -> TRes,
) -> TRes {
#[cfg(debug_assertions)]
{
ctx.relowering_checker.relowering_permissions_count += 1;
}

let res = op(ctx);

#[cfg(debug_assertions)]
{
ctx.relowering_checker.relowering_permissions_count -= 1;
}

res
}
}
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand Down Expand Up @@ -146,7 +188,7 @@ struct LoweringContext<'a, 'hir> {
ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
/// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
#[cfg(debug_assertions)]
node_id_to_local_id: NodeMap<hir::ItemLocalId>,
relowering_checker: re_lowering::ReloweringChecker,
/// The `NodeId` space is split in two.
/// `0..resolver.next_node_id` are created by the resolver on the AST.
/// The higher part `resolver.next_node_id..next_node_id` are created during lowering.
Expand Down Expand Up @@ -205,8 +247,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// and we never call `lower_node_id(owner)`.
item_local_id_counter: hir::ItemLocalId::new(1),
ident_and_label_to_local_id: Default::default(),

#[cfg(debug_assertions)]
node_id_to_local_id: Default::default(),
relowering_checker: Default::default(),

trait_map: Default::default(),
next_node_id: resolver.next_node_id,
node_id_to_def_id: NodeMap::default(),
Expand Down Expand Up @@ -808,7 +852,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let current_ident_and_label_to_local_id = mem::take(&mut self.ident_and_label_to_local_id);

#[cfg(debug_assertions)]
let current_node_id_to_local_id = mem::take(&mut self.node_id_to_local_id);
let current_relowering_checker = mem::take(&mut self.relowering_checker);
let current_trait_map = mem::take(&mut self.trait_map);
let current_owner = mem::replace(&mut self.current_hir_id_owner, owner_id);
let current_local_counter =
Expand All @@ -824,10 +868,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

// Always allocate the first `HirId` for the owner itself.
#[cfg(debug_assertions)]
{
let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
debug_assert_eq!(_old, None);
}
self.relowering_checker.check(owner, hir::ItemLocalId::ZERO);

let item = f(self);
assert_eq!(owner_id, item.def_id());
Expand All @@ -845,7 +886,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

#[cfg(debug_assertions)]
{
self.node_id_to_local_id = current_node_id_to_local_id;
self.relowering_checker = current_relowering_checker;
}
self.trait_map = current_trait_map;
self.current_hir_id_owner = current_owner;
Expand Down Expand Up @@ -936,10 +977,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

// Check whether the same `NodeId` is lowered more than once.
#[cfg(debug_assertions)]
{
let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
assert_eq!(old, None);
}
self.relowering_checker.check(ast_node_id, local_id);

hir_id
}
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/delegation/self-coercion-static-free.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ impl Trait for S {
reuse <F as Trait>::{static_value, static_mut_ref, static_ref} {
//~^ ERROR: mismatched types
//~| ERROR: mismatched types
//~| ERROR: mismatched types
//~| ERROR: unused target expression is specified for glob or list delegation
let _ = self;
S::static_self()
Expand All @@ -35,7 +34,6 @@ impl Trait for S1 {
reuse <F as Trait>::{static_value, static_mut_ref, static_ref} {
//~^ ERROR: mismatched types
//~| ERROR: mismatched types
//~| ERROR: mismatched types
//~| ERROR: unused target expression is specified for glob or list delegation
let _ = self;
S1::static_self()
Expand Down
Loading
Loading