Skip to main content

rustc_ast_lowering/delegation/
mod.rs

1//! This module implements expansion of delegation items with early resolved paths.
2//! It includes a delegation to a free functions:
3//!
4//! ```ignore (illustrative)
5//! reuse module::name { target_expr_template }
6//! ```
7//!
8//! And delegation to a trait methods:
9//!
10//! ```ignore (illustrative)
11//! reuse <Type as Trait>::name { target_expr_template }
12//! ```
13//!
14//! After expansion for both cases we get:
15//!
16//! ```ignore (illustrative)
17//! fn name(
18//!     arg0: InferDelegation(sig_id, Input(0)),
19//!     arg1: InferDelegation(sig_id, Input(1)),
20//!     ...,
21//!     argN: InferDelegation(sig_id, Input(N)),
22//! ) -> InferDelegation(sig_id, Output) {
23//!     callee_path(target_expr_template(arg0), arg1, ..., argN)
24//! }
25//! ```
26//!
27//! Where `callee_path` is a path in delegation item e.g. `<Type as Trait>::name`.
28//! `sig_id` is a id of item from which the signature is inherited. It may be a delegation
29//! item id (`item_id`) in case of impl trait or path resolution id (`path_id`) otherwise.
30//!
31//! Since we do not have a proper way to obtain function type information by path resolution
32//! in AST, we mark each function parameter type as `InferDelegation` and inherit it during
33//! HIR ty lowering.
34//!
35//! Similarly generics, predicates and header are set to the "default" values.
36//! In case of discrepancy with callee function the `UnsupportedDelegation` error will
37//! also be emitted during HIR ty lowering.
38
39use std::iter;
40
41use ast::visit::Visitor;
42use generics::GenericsGenerationResult;
43use hir::HirId;
44use hir::def::Res;
45use rustc_abi::ExternAbi;
46use rustc_ast as ast;
47use rustc_ast::*;
48use rustc_hir::{self as hir, FnDeclFlags};
49use rustc_middle::ty::Asyncness;
50use rustc_span::def_id::DefId;
51use rustc_span::symbol::kw;
52use rustc_span::{Ident, Span, Symbol, sym};
53
54use crate::delegation::generics::{GenericsGenerationResults, GenericsPosition};
55use crate::delegation::resolution::resolver::DelegationResolver;
56use crate::delegation::resolution::{DelegationResolution, ParamInfo};
57use crate::{
58    AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
59};
60
61mod attributes;
62mod generics;
63mod resolution;
64
65pub(crate) struct DelegationResults<'hir> {
66    pub body_id: hir::BodyId,
67    pub sig: hir::FnSig<'hir>,
68    pub ident: Ident,
69    pub generics: &'hir hir::Generics<'hir>,
70}
71
72impl<'hir> LoweringContext<'_, 'hir> {
73    pub(crate) fn lower_delegation(&mut self, delegation: &Delegation) -> DelegationResults<'hir> {
74        let span = self.lower_span(delegation.last_segment_span());
75
76        let resolver = DelegationResolver::new(self);
77        let Ok((res, mut generics)) = resolver.resolve_delegation(delegation, span) else {
78            return self.generate_delegation_error(span, delegation);
79        };
80
81        self.add_attrs_if_needed(&res);
82
83        let (body_id, call_expr_id, unused_target_expr) =
84            self.lower_delegation_body(delegation, &res, &mut generics);
85
86        let decl = self.lower_delegation_decl(&res, &generics, call_expr_id, unused_target_expr);
87
88        let sig = self.lower_delegation_sig(res.sig_id, decl, span);
89
90        let ident = self.lower_ident(delegation.ident);
91
92        let generics = self.arena.alloc(hir::Generics {
93            has_where_clause_predicates: false,
94            params: self.arena.alloc_from_iter(generics.all_params()),
95            predicates: self.arena.alloc_from_iter(generics.all_predicates()),
96            span,
97            where_clause_span: span,
98        });
99
100        DelegationResults { body_id, sig, ident, generics }
101    }
102
103    fn lower_delegation_decl(
104        &mut self,
105        res: &DelegationResolution,
106        generics: &GenericsGenerationResults<'hir>,
107        call_expr_id: HirId,
108        unused_target_expr: bool,
109    ) -> &'hir hir::FnDecl<'hir> {
110        let &DelegationResolution { source, call_path_res, span, sig_id, .. } = res;
111        let ParamInfo { param_count, c_variadic, splatted } = res.param_info;
112
113        // The last parameter in C variadic functions is skipped in the signature,
114        // like during regular lowering.
115        let decl_param_count = param_count - c_variadic as usize;
116        let inputs = self.arena.alloc_from_iter((0..decl_param_count).map(|arg| hir::Ty {
117            hir_id: self.next_id(),
118            kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
119                sig_id,
120                hir::InferDelegationSig::Input(arg),
121            )),
122            span,
123        }));
124
125        let output = self.arena.alloc(hir::Ty {
126            hir_id: self.next_id(),
127            kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
128                sig_id,
129                hir::InferDelegationSig::Output(self.arena.alloc(hir::DelegationInfo {
130                    call_expr_id,
131                    call_path_res,
132                    child_seg_id: generics.child.args_segment_id,
133                    child_seg_id_for_sig: generics.child.segment_id_for_sig(),
134                    parent_seg_id_for_sig: generics.parent.segment_id_for_sig(),
135                    self_ty_propagation_kind: generics.self_ty_propagation_kind,
136                    group_id: {
137                        let id = match source {
138                            DelegationSource::Single => None,
139                            DelegationSource::List(expn_id) => Some(expn_id),
140                            DelegationSource::Glob => {
141                                Some(self.tcx.expn_that_defined(self.owner.def_id).expect_local())
142                            }
143                        };
144
145                        id.map(|id| (id, unused_target_expr))
146                    },
147                })),
148            )),
149            span,
150        });
151
152        self.arena.alloc(hir::FnDecl {
153            inputs,
154            output: hir::FnRetTy::Return(output),
155            fn_decl_kind: FnDeclFlags::default()
156                .set_lifetime_elision_allowed(true)
157                .set_c_variadic(c_variadic)
158                .set_splatted(splatted, inputs.len())
159                .unwrap(),
160        })
161    }
162
163    fn lower_delegation_sig(
164        &mut self,
165        sig_id: DefId,
166        decl: &'hir hir::FnDecl<'hir>,
167        span: Span,
168    ) -> hir::FnSig<'hir> {
169        let sig = self.tcx.fn_sig(sig_id).skip_binder().skip_binder();
170        let asyncness = match self.tcx.asyncness(sig_id) {
171            Asyncness::Yes => hir::IsAsync::Async(span),
172            Asyncness::No => hir::IsAsync::NotAsync,
173        };
174
175        let header = hir::FnHeader {
176            safety: if self.tcx.codegen_fn_attrs(sig_id).safe_target_features {
177                hir::HeaderSafety::SafeTargetFeatures
178            } else {
179                hir::HeaderSafety::Normal(sig.safety())
180            },
181            constness: self.tcx.constness(sig_id),
182            asyncness,
183            abi: sig.abi(),
184        };
185
186        hir::FnSig { decl, header, span }
187    }
188
189    fn generate_param(
190        &mut self,
191        is_method: bool,
192        idx: usize,
193        span: Span,
194    ) -> (hir::Param<'hir>, NodeId) {
195        let pat_node_id = self.next_node_id();
196        let pat_id = self.lower_node_id(pat_node_id);
197        // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`.
198        let name = if is_method && idx == 0 {
199            kw::SelfLower
200        } else {
201            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", idx))
    })format!("arg{idx}"))
202        };
203        let ident = Ident::with_dummy_span(name);
204        let pat = self.arena.alloc(hir::Pat {
205            hir_id: pat_id,
206            kind: hir::PatKind::Binding(hir::BindingMode::NONE, pat_id, ident, None),
207            span,
208            default_binding_modes: false,
209        });
210
211        (hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }, pat_node_id)
212    }
213
214    fn generate_arg(
215        &mut self,
216        is_method: bool,
217        idx: usize,
218        param_id: HirId,
219        span: Span,
220    ) -> hir::Expr<'hir> {
221        // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`.
222        let name = if is_method && idx == 0 {
223            kw::SelfLower
224        } else {
225            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", idx))
    })format!("arg{idx}"))
226        };
227
228        let segments = self.arena.alloc_from_iter(iter::once(hir::PathSegment {
229            ident: Ident::with_dummy_span(name),
230            hir_id: self.next_id(),
231            res: Res::Local(param_id),
232            args: None,
233            infer_args: false,
234            delegation_child_segment: false,
235        }));
236
237        let path = self.arena.alloc(hir::Path { span, res: Res::Local(param_id), segments });
238        self.mk_expr(hir::ExprKind::Path(hir::QPath::Resolved(None, path)), span)
239    }
240
241    fn lower_delegation_body(
242        &mut self,
243        delegation: &Delegation,
244        res: &DelegationResolution,
245        generics: &mut GenericsGenerationResults<'hir>,
246    ) -> (hir::BodyId, HirId, bool) {
247        let block = delegation.body.as_deref();
248        let mut call_expr_id = HirId::INVALID;
249        let mut unused_target_expr = false;
250
251        let block_id = self.lower_body(|this| {
252            let &DelegationResolution {
253                param_info, span, should_generate_block, is_method, ..
254            } = res;
255
256            let ParamInfo { param_count, .. } = param_info;
257
258            let mut parameters: Vec<hir::Param<'_>> = Vec::with_capacity(param_count);
259            let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);
260            let mut stmts: &[hir::Stmt<'hir>] = &[];
261
262            // Consider non-specified target expression as generated,
263            // as we do not want to emit error when target expression is
264            // not specified.
265            unused_target_expr = block.is_some() && (param_count == 0 || !should_generate_block);
266
267            for idx in 0..param_count {
268                let (param, pat_node_id) = this.generate_param(is_method, idx, span);
269                parameters.push(param);
270
271                let generate_arg =
272                    |this: &mut Self| this.generate_arg(is_method, idx, param.pat.hir_id, span);
273
274                let arg = if let Some(block) = block
275                    && idx == 0
276                    && should_generate_block
277                {
278                    let mut self_resolver = SelfResolver {
279                        ctxt: this,
280                        path_id: delegation.id,
281                        self_param_id: pat_node_id,
282                    };
283                    self_resolver.visit_block(block);
284                    // Target expr needs to lower `self` path.
285                    this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id);
286
287                    // Lower with `HirId::INVALID` as we will use only expr and stmts.
288                    // FIXME(fn_delegation): Alternatives for target expression lowering:
289                    // https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2197170600.
290                    let block = this.lower_block_noalloc(HirId::INVALID, block, false);
291
292                    stmts = block.stmts;
293
294                    // The behavior of the delegation's target expression differs from the
295                    // behavior of the usual block, where if there is no final expression
296                    // the `()` is returned. In case of the similar situation in delegation
297                    // (no final expression) we propagate first argument instead of replacing
298                    // it with `()`.
299                    if let Some(&expr) = block.expr { expr } else { generate_arg(this) }
300                } else {
301                    generate_arg(this)
302                };
303
304                args.push(arg);
305            }
306
307            let (final_expr, hir_id) =
308                this.finalize_body_lowering(delegation, stmts, args, res, generics, span);
309
310            call_expr_id = hir_id;
311
312            (this.arena.alloc_from_iter(parameters), final_expr)
313        });
314
315        if true {
    {
        match (&call_expr_id, &HirId::INVALID) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(call_expr_id, HirId::INVALID);
316
317        (block_id, call_expr_id, unused_target_expr)
318    }
319
320    fn finalize_body_lowering(
321        &mut self,
322        delegation: &Delegation,
323        stmts: &'hir [hir::Stmt<'hir>],
324        args: Vec<hir::Expr<'hir>>,
325        res: &DelegationResolution,
326        generics: &mut GenericsGenerationResults<'hir>,
327        span: Span,
328    ) -> (hir::Expr<'hir>, HirId) {
329        let path = self.lower_qpath(
330            delegation.id,
331            &delegation.qself,
332            &delegation.path,
333            ParamMode::Optional,
334            AllowReturnTypeNotation::No,
335            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
336            None,
337        );
338
339        let new_path = match path {
340            hir::QPath::Resolved(ty, path) => {
341                let mut new_path = path.clone();
342                let len = new_path.segments.len();
343
344                new_path.segments = self.arena.alloc_from_iter(
345                    new_path.segments.iter().enumerate().map(|(idx, segment)| {
346                        if idx + 2 == len {
347                            self.process_segment(span, segment, &mut generics.parent)
348                        } else if idx + 1 == len {
349                            self.process_segment(span, segment, &mut generics.child)
350                        } else {
351                            segment.clone()
352                        }
353                    }),
354                );
355
356                // Explicitly create `Self` self-type in case of infers or static
357                // free-to-trait reuses.
358                let ty = match generics.self_ty_propagation_kind {
359                    Some(hir::DelegationSelfTyPropagationKind::SelfParam) => {
360                        let self_param = generics.parent.generics.find_self_param();
361                        let path = self.create_generic_arg_path(self_param);
362                        let kind = hir::TyKind::Path(path);
363
364                        let ty = match ty {
365                            Some(ty) => hir::Ty { kind, ..ty.clone() },
366                            None => hir::Ty { kind, hir_id: self.next_id(), span },
367                        };
368
369                        Some(&*self.arena.alloc(ty))
370                    }
371                    _ => ty,
372                };
373
374                hir::QPath::Resolved(ty, self.arena.alloc(new_path))
375            }
376            hir::QPath::TypeRelative(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("until inherent methods are supported")));
}unreachable!("until inherent methods are supported"),
377        };
378
379        if let Some(hir::DelegationSelfTyPropagationKind::SelfTy(id)) =
380            generics.self_ty_propagation_kind.as_mut()
381        {
382            *id = match new_path {
383                hir::QPath::Resolved(ty, _) => {
384                    ty.expect("must contain self type as `SelfTy` propagation kind is specified")
385                }
386                hir::QPath::TypeRelative(ty, _) => ty,
387            }
388            .hir_id;
389        }
390
391        let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
392        let args = self.arena.alloc_from_iter(args);
393        let call = self.mk_expr(hir::ExprKind::Call(callee_path, args), span);
394
395        let expr = if let Some((parent, of_trait)) = res.output_self_mapping {
396            let res = Res::SelfTyAlias { alias_to: parent.to_def_id(), is_trait_impl: of_trait };
397            let ident = Ident::new(kw::SelfUpper, span);
398            let path = self.create_resolved_path(res, ident, span);
399
400            // FIXME(fn_delegation): add default `..` for all other fields.
401            let initializer = hir::ExprKind::Struct(
402                self.arena.alloc(path),
403                self.arena.alloc_slice(&[hir::ExprField {
404                    hir_id: self.next_id(),
405                    is_shorthand: false,
406                    ident: Ident::new(sym::integer(0), span),
407                    expr: self.arena.alloc(call),
408                    span,
409                }]),
410                hir::StructTailExpr::None,
411            );
412
413            self.arena.alloc(self.mk_expr(initializer, span))
414        } else {
415            self.arena.alloc(call)
416        };
417
418        let block = self.arena.alloc(hir::Block {
419            stmts,
420            expr: Some(expr),
421            hir_id: self.next_id(),
422            rules: hir::BlockCheckMode::DefaultBlock,
423            span,
424            targeted_by_break: false,
425        });
426
427        (self.mk_expr(hir::ExprKind::Block(block, None), span), call.hir_id)
428    }
429
430    fn process_segment(
431        &mut self,
432        span: Span,
433        segment: &hir::PathSegment<'hir>,
434        result: &mut GenericsGenerationResult<'hir>,
435    ) -> hir::PathSegment<'hir> {
436        let infer_indices = result.generics.infer_indices();
437        result.generics.into_hir_generics(self, span);
438
439        let mut segment = segment.clone();
440        let mut args_iter = result.generics.create_args_iterator();
441
442        let new_args = segment
443            .args
444            .filter(|args| !args.is_empty())
445            .map(|args| {
446                self.arena.alloc_from_iter(args.args.iter().enumerate().map(|(idx, arg)| {
447                    if infer_indices.contains(&idx) {
448                        args_iter.next(self, |_| arg.hir_id()).expect("arg must exist for infer")
449                    } else {
450                        *arg
451                    }
452                }))
453            })
454            .unwrap_or_else(|| self.arena.alloc_from_iter(args_iter.consume_all(self)));
455
456        // Needed for better error messages (`trait-impl-wrong-args-count.rs` test).
457        segment.args = (!new_args.is_empty()).then(|| {
458            &*self.arena.alloc(hir::GenericArgs {
459                args: new_args,
460                constraints: &[],
461                parenthesized: hir::GenericArgsParentheses::No,
462                span_ext: segment.args.map_or(span, |args| args.span_ext),
463            })
464        });
465
466        result.args_segment_id = segment.hir_id;
467        result.use_for_sig_inheritance = !result.generics.is_trait_impl();
468
469        segment.delegation_child_segment = result.generics.pos() == GenericsPosition::Child;
470
471        segment
472    }
473
474    fn generate_delegation_error(
475        &mut self,
476        span: Span,
477        delegation: &Delegation,
478    ) -> DelegationResults<'hir> {
479        let decl = self.arena.alloc(hir::FnDecl::dummy(span));
480
481        let header = self.generate_header_error();
482        let sig = hir::FnSig { decl, header, span };
483
484        let ident = self.lower_ident(delegation.ident);
485
486        let body_id = self.lower_body(|this| {
487            let path = this.lower_qpath(
488                delegation.id,
489                &delegation.qself,
490                &delegation.path,
491                ParamMode::Optional,
492                AllowReturnTypeNotation::No,
493                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
494                None,
495            );
496
497            let callee_path = this.arena.alloc(this.mk_expr(hir::ExprKind::Path(path), span));
498            let args = if let Some(block) = &delegation.body {
499                this.arena.alloc_slice(&[this.lower_block_expr(block)])
500            } else {
501                &mut []
502            };
503
504            let call = this.arena.alloc(this.mk_expr(hir::ExprKind::Call(callee_path, args), span));
505
506            let block = this.arena.alloc(hir::Block {
507                stmts: &[],
508                expr: Some(call),
509                hir_id: this.next_id(),
510                rules: hir::BlockCheckMode::DefaultBlock,
511                span,
512                targeted_by_break: false,
513            });
514
515            (&[], this.mk_expr(hir::ExprKind::Block(block, None), span))
516        });
517
518        let generics = hir::Generics::empty();
519        DelegationResults { ident, generics, body_id, sig }
520    }
521
522    fn generate_header_error(&self) -> hir::FnHeader {
523        hir::FnHeader {
524            safety: hir::Safety::Safe.into(),
525            constness: hir::Constness::NotConst,
526            asyncness: hir::IsAsync::NotAsync,
527            abi: ExternAbi::Rust,
528        }
529    }
530
531    #[inline]
532    fn mk_expr(&mut self, kind: hir::ExprKind<'hir>, span: Span) -> hir::Expr<'hir> {
533        hir::Expr { hir_id: self.next_id(), kind, span }
534    }
535}
536
537struct SelfResolver<'a, 'b, 'hir> {
538    ctxt: &'a mut LoweringContext<'b, 'hir>,
539    path_id: NodeId,
540    self_param_id: NodeId,
541}
542
543impl SelfResolver<'_, '_, '_> {
544    fn try_replace_id(&mut self, id: NodeId) {
545        if let Some(res) = self.ctxt.get_partial_res(id)
546            && let Some(Res::Local(sig_id)) = res.full_res()
547            && sig_id == self.path_id
548        {
549            self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
550        }
551    }
552}
553
554impl<'ast> Visitor<'ast> for SelfResolver<'_, '_, '_> {
555    fn visit_id(&mut self, id: NodeId) {
556        self.try_replace_id(id);
557    }
558}