Skip to content
Merged
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
68 changes: 65 additions & 3 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ use rustc_middle::span_bug;
use rustc_middle::ty::{Asyncness, PerOwnerResolverData};
use rustc_span::def_id::{DefId, LocalDefId};
use rustc_span::symbol::kw;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, sym};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::diagnostics::{
Expand Down Expand Up @@ -661,11 +661,34 @@ impl<'hir> LoweringContext<'_, 'hir> {

let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
let args = self.arena.alloc_from_iter(args);
let call = self.arena.alloc(self.mk_expr(hir::ExprKind::Call(callee_path, args), span));
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 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);

// FIXME(fn_delegation): add default `..` for all other fields.
let initializer = hir::ExprKind::Struct(
self.arena.alloc(path),
self.arena.alloc_slice(&[hir::ExprField {
hir_id: self.next_id(),
is_shorthand: false,
ident: Ident::new(sym::integer(0), span),
expr: self.arena.alloc(call),
span,
}]),
hir::StructTailExpr::None,
);

self.arena.alloc(self.mk_expr(initializer, span))
} else {
self.arena.alloc(call)
};

let block = self.arena.alloc(hir::Block {
stmts,
expr: Some(call),
expr: Some(expr),
hir_id: self.next_id(),
rules: hir::BlockCheckMode::DefaultBlock,
span,
Expand All @@ -675,6 +698,45 @@ 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)> {
// Heuristic: don't do wrapping if there is no target expression.
if delegation.body.is_none() {
return None;
}

let tcx = self.tcx;
let parent = tcx.local_parent(self.owner.def_id);
let parent_kind = tcx.def_kind(parent);

// Apply wrapping for delegations inside
// 1) Trait impls, as the return type of both signature function
// and generated delegation has `Self` generic param returned
// (checked below).
// FIXME(fn_delegation): think of enabling wrapping in more scenarios:
// trait-(impl)-to-free
// trait-(impl)-to-inherent
// inherent-to-free
// 2) Inherent methods when delegating to trait, as we change the type of
// `Self` to type of struct or enum we delegate from.
if !matches!(tcx.def_kind(parent), DefKind::Impl { .. }) {
return None;
}

let is_trait_impl = parent_kind == DefKind::Impl { of_trait: true };

// Check that delegation path resolves to a trait AssocFn, not to a free method.
Some((parent, is_trait_impl)).filter(|_| {
self.get_resolution_id(delegation.id).is_some_and(|id| {
tcx.def_kind(id) == DefKind::AssocFn
// Check that the return type of the callee is `Self` param.
// 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 process_segment(
&mut self,
span: Span,
Expand Down
13 changes: 11 additions & 2 deletions compiler/rustc_ast_lowering/src/delegation/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,18 +581,27 @@ impl<'hir> LoweringContext<'_, 'hir> {
p.def_id.to_def_id(),
);

self.create_resolved_path(res, p.name.ident(), p.span)
}

pub(super) fn create_resolved_path(
&mut self,
res: Res,
ident: Ident,
span: Span,
) -> hir::QPath<'hir> {
hir::QPath::Resolved(
None,
self.arena.alloc(hir::Path {
segments: self.arena.alloc_slice(&[hir::PathSegment {
args: None,
hir_id: self.next_id(),
ident: p.name.ident(),
ident,
infer_args: false,
res,
}]),
res,
span: p.span,
span,
}),
)
}
Expand Down
44 changes: 44 additions & 0 deletions tests/pretty/delegation/self-mapping-output.pp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#![attr = Feature([fn_delegation#0])]
extern crate std;
#[attr = PreludeImport]
use ::std::prelude::rust_2015::*;
//@ pretty-compare-only
//@ pretty-mode:hir
//@ pp-exact:self-mapping-output.pp


trait Trait {
fn method(&self)
-> Self;
fn r#static()
-> Self;
fn raw_S(&self) -> S { S }
}

struct S;
impl Trait for S {
fn method(&self) -> S { S }
fn r#static() -> S { S }
}

struct W(S);
impl Trait for W {
#[attr = Inline(Hint)]
fn method(self: _) -> _ { Self { 0: Trait::method(self.0) } }
#[attr = Inline(Hint)]
fn r#static() -> _ { Trait::r#static() }
//~^ WARN: function cannot return without recursing [unconditional_recursion]
#[attr = Inline(Hint)]
fn raw_S(self: _) -> _ { Trait::raw_S(self.0) }
}

impl W {
#[attr = Inline(Hint)]
fn method(self: _) -> _ { Self { 0: Trait::method(self.0) } }
#[attr = Inline(Hint)]
fn r#static() -> _ { Trait::r#static() }
#[attr = Inline(Hint)]
fn raw_S(self: _) -> _ { Trait::raw_S(self.0) }
}

fn main() { }
33 changes: 33 additions & 0 deletions tests/pretty/delegation/self-mapping-output.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//@ pretty-compare-only
//@ pretty-mode:hir
//@ pp-exact:self-mapping-output.pp

#![feature(fn_delegation)]

trait Trait {
fn method(&self) -> Self;
fn r#static() -> Self;
fn raw_S(&self) -> S { S }
}

struct S;
impl Trait for S {
fn method(&self) -> S { S }
fn r#static() -> S { S }
}

struct W(S);
impl Trait for W {
reuse Trait::method { self.0 }
reuse Trait::r#static;
//~^ WARN: function cannot return without recursing [unconditional_recursion]
reuse Trait::raw_S { self.0 }
}

impl W {
reuse Trait::method { self.0 }
reuse Trait::r#static;
reuse Trait::raw_S { self.0 }
}

fn main() {}
28 changes: 28 additions & 0 deletions tests/ui/delegation/self-mapping-output-privacy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#![feature(fn_delegation)]

trait Trait {
fn method(&self) -> Self;
}

pub struct S;
impl Trait for S {
fn method(&self) -> S {
S
}
}

mod private {
pub struct W(super::S);
}

impl Trait for private::W {
reuse Trait::method { S }
//~^ ERROR: field `0` of struct `W` is private
}

impl private::W {
reuse Trait::method { S }
//~^ ERROR: field `0` of struct `W` is private
}

fn main() {}
15 changes: 15 additions & 0 deletions tests/ui/delegation/self-mapping-output-privacy.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
error[E0451]: field `0` of struct `W` is private
--> $DIR/self-mapping-output-privacy.rs:19:18
|
LL | reuse Trait::method { S }
| ^^^^^^ private field

error[E0451]: field `0` of struct `W` is private
--> $DIR/self-mapping-output-privacy.rs:24:18
|
LL | reuse Trait::method { S }
| ^^^^^^ private field

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0451`.
Loading
Loading