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::def::DefKind;
49use rustc_hir::{self as hir, FnDeclFlags};
50use rustc_middle::ty::Asyncness;
51use rustc_span::def_id::DefId;
52use rustc_span::symbol::kw;
53use rustc_span::{Ident, Span, Symbol, sym};
54
55use crate::delegation::generics::{GenericsGenerationResults, GenericsPosition};
56use crate::delegation::resolution::resolver::DelegationResolver;
57use crate::delegation::resolution::{DelegationResolution, ParamInfo};
58use crate::{
59    AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
60};
61
62mod attributes;
63mod generics;
64mod resolution;
65
66pub(crate) struct DelegationResults<'hir> {
67    pub body_id: hir::BodyId,
68    pub sig: hir::FnSig<'hir>,
69    pub ident: Ident,
70    pub generics: &'hir hir::Generics<'hir>,
71}
72
73impl<'hir> LoweringContext<'_, 'hir> {
74    pub(crate) fn lower_delegation(&mut self, delegation: &Delegation) -> DelegationResults<'hir> {
75        let span = self.lower_span(delegation.last_segment_span());
76
77        let resolver = DelegationResolver::new(self);
78        let Ok((res, mut generics)) = resolver.resolve_delegation(delegation, span) else {
79            return self.generate_delegation_error(span, delegation);
80        };
81
82        self.add_attrs_if_needed(&res);
83
84        let (body_id, call_expr_id, unused_target_expr) =
85            self.lower_delegation_body(delegation, &res, &mut generics);
86
87        let decl = self.lower_delegation_decl(&res, &generics, call_expr_id, unused_target_expr);
88
89        let sig = self.lower_delegation_sig(res.sig_id, decl, span);
90
91        let ident = self.lower_ident(delegation.ident);
92
93        let generics = self.arena.alloc(hir::Generics {
94            has_where_clause_predicates: false,
95            params: self.arena.alloc_from_iter(generics.all_params()),
96            predicates: self.arena.alloc_from_iter(generics.all_predicates()),
97            span,
98            where_clause_span: span,
99        });
100
101        DelegationResults { body_id, sig, ident, generics }
102    }
103
104    fn lower_delegation_decl(
105        &mut self,
106        res: &DelegationResolution,
107        generics: &GenericsGenerationResults<'hir>,
108        call_expr_id: HirId,
109        unused_target_expr: bool,
110    ) -> &'hir hir::FnDecl<'hir> {
111        let &DelegationResolution { source, call_path_res, span, sig_id, .. } = res;
112        let ParamInfo { param_count, c_variadic, splatted } = res.param_info;
113
114        // The last parameter in C variadic functions is skipped in the signature,
115        // like during regular lowering.
116        let decl_param_count = param_count - c_variadic as usize;
117        let inputs = self.arena.alloc_from_iter((0..decl_param_count).map(|arg| hir::Ty {
118            hir_id: self.next_id(),
119            kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
120                sig_id,
121                hir::InferDelegationSig::Input(arg),
122            )),
123            span,
124        }));
125
126        let output = self.arena.alloc(hir::Ty {
127            hir_id: self.next_id(),
128            kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
129                sig_id,
130                hir::InferDelegationSig::Output(self.arena.alloc(hir::DelegationInfo {
131                    call_expr_id,
132                    call_path_res,
133                    arguments_to_map: res.sig_mapping.arguments_to_map.clone(),
134                    child_seg_id: generics.child.args_segment_id,
135                    child_seg_id_for_sig: generics.child.segment_id_for_sig(),
136                    parent_seg_id_for_sig: generics.parent.segment_id_for_sig(),
137                    self_ty_propagation_kind: generics.self_ty_propagation_kind,
138                    group_id: {
139                        let id = match source {
140                            DelegationSource::Single => None,
141                            DelegationSource::List(expn_id) => Some(expn_id),
142                            DelegationSource::Glob => {
143                                Some(self.tcx.expn_that_defined(self.owner.def_id).expect_local())
144                            }
145                        };
146
147                        id.map(|id| (id, unused_target_expr))
148                    },
149                })),
150            )),
151            span,
152        });
153
154        self.arena.alloc(hir::FnDecl {
155            inputs,
156            output: hir::FnRetTy::Return(output),
157            fn_decl_kind: FnDeclFlags::default()
158                .set_lifetime_elision_allowed(true)
159                .set_c_variadic(c_variadic)
160                .set_splatted(splatted, inputs.len())
161                .unwrap(),
162        })
163    }
164
165    fn lower_delegation_sig(
166        &mut self,
167        sig_id: DefId,
168        decl: &'hir hir::FnDecl<'hir>,
169        span: Span,
170    ) -> hir::FnSig<'hir> {
171        let sig = self.tcx.fn_sig(sig_id).skip_binder().skip_binder();
172        let asyncness = match self.tcx.asyncness(sig_id) {
173            Asyncness::Yes => hir::IsAsync::Async(span),
174            Asyncness::No => hir::IsAsync::NotAsync,
175        };
176
177        let header = hir::FnHeader {
178            safety: if self.tcx.codegen_fn_attrs(sig_id).safe_target_features {
179                hir::HeaderSafety::SafeTargetFeatures
180            } else {
181                hir::HeaderSafety::Normal(sig.safety())
182            },
183            constness: self.tcx.constness(sig_id),
184            asyncness,
185            abi: sig.abi(),
186        };
187
188        hir::FnSig { decl, header, span }
189    }
190
191    fn generate_param(
192        &mut self,
193        is_method: bool,
194        idx: usize,
195        span: Span,
196    ) -> (hir::Param<'hir>, NodeId) {
197        let pat_node_id = self.next_node_id();
198        let pat_id = self.lower_node_id(pat_node_id);
199        // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`.
200        let name = if is_method && idx == 0 {
201            kw::SelfLower
202        } else {
203            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", idx))
    })format!("arg{idx}"))
204        };
205        let ident = Ident::with_dummy_span(name);
206        let pat = self.arena.alloc(hir::Pat {
207            hir_id: pat_id,
208            kind: hir::PatKind::Binding(hir::BindingMode::NONE, pat_id, ident, None),
209            span,
210            default_binding_modes: false,
211        });
212
213        (hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }, pat_node_id)
214    }
215
216    fn generate_arg(
217        &mut self,
218        is_method: bool,
219        idx: usize,
220        param_id: HirId,
221        span: Span,
222    ) -> hir::Expr<'hir> {
223        // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`.
224        let name = if is_method && idx == 0 {
225            kw::SelfLower
226        } else {
227            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", idx))
    })format!("arg{idx}"))
228        };
229
230        let segments = self.arena.alloc_from_iter(iter::once(hir::PathSegment {
231            ident: Ident::with_dummy_span(name),
232            hir_id: self.next_id(),
233            res: Res::Local(param_id),
234            args: None,
235            infer_args: false,
236            delegation_child_segment: false,
237        }));
238
239        let path = self.arena.alloc(hir::Path { span, res: Res::Local(param_id), segments });
240        self.mk_expr(hir::ExprKind::Path(hir::QPath::Resolved(None, path)), span)
241    }
242
243    fn lower_delegation_body(
244        &mut self,
245        delegation: &Delegation,
246        res: &DelegationResolution,
247        generics: &mut GenericsGenerationResults<'hir>,
248    ) -> (hir::BodyId, HirId, bool) {
249        let block = delegation.body.as_deref();
250        let mut call_expr_id = HirId::INVALID;
251        let mut unused_target_expr = false;
252
253        let block_id = self.lower_body(|this| {
254            let &DelegationResolution { param_info, span, is_method, .. } = res;
255            let ParamInfo { param_count, .. } = param_info;
256            let arguments_to_map = &res.sig_mapping.arguments_to_map;
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 = ::alloc::vec::Vec::new()vec![];
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 =
266                block.is_some() && (param_count == 0 || arguments_to_map.is_empty());
267
268            for idx in 0..param_count {
269                let (param, pat_node_id) = this.generate_param(is_method, idx, span);
270                parameters.push(param);
271
272                let generate_arg =
273                    |this: &mut Self| this.generate_arg(is_method, idx, param.pat.hir_id, span);
274
275                let arg = block
276                    .filter(|_| arguments_to_map.contains(&idx))
277                    .and_then(|block| {
278                        let block = this.lower_block_maybe_more_than_once(
279                            block,
280                            pat_node_id,
281                            param.pat.hir_id.local_id,
282                            delegation.id,
283                        );
284
285                        stmts.push(block.stmts);
286
287                        // The behavior of the delegation's target expression differs from the
288                        // behavior of the usual block, where if there is no final expression
289                        // the `()` is returned. In case of the similar situation in delegation
290                        // (no final expression) we propagate first argument instead of replacing
291                        // it with `()`.
292                        block.expr.copied()
293                    })
294                    .unwrap_or_else(|| generate_arg(this));
295
296                args.push(arg);
297            }
298
299            let (final_expr, hir_id) = this.finalize_body_lowering(
300                delegation,
301                this.arena.alloc_from_iter(stmts.into_iter().flatten().copied()),
302                args,
303                res,
304                generics,
305                span,
306            );
307
308            call_expr_id = hir_id;
309
310            (this.arena.alloc_from_iter(parameters), final_expr)
311        });
312
313        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);
314
315        (block_id, call_expr_id, unused_target_expr)
316    }
317
318    fn lower_block_maybe_more_than_once(
319        &mut self,
320        block: &Block,
321        pat_node_id: NodeId,
322        param_local_id: hir::ItemLocalId,
323        delegation_id: NodeId,
324    ) -> hir::Block<'hir> {
325        let mut self_resolver = SelfResolver {
326            ctxt: self,
327            path_id: delegation_id,
328            self_param_id: pat_node_id,
329            overwrites: ::alloc::vec::Vec::new()vec![],
330        };
331
332        self_resolver.visit_block(block);
333
334        let overwrites = self_resolver.overwrites;
335
336        // Target expr needs to lower `self` path.
337        self.ident_and_label_to_local_id.insert(pat_node_id, param_local_id);
338
339        let block = cfg_select! {
340            debug_assertions => {
341                crate::re_lowering::ReloweringChecker::allow_relowering(self, |this| {
342                    this.lower_block_noalloc(HirId::INVALID, block, false)
343                })
344            },
345            _ => self.lower_block_noalloc(HirId::INVALID, block, false)
346        };
347
348        // Remove node ids for which we overwrote resolution to generated param
349        // before block lowering as block can be relowered. We need to do it because
350        // check in `SelfResolver` uses `get_partial_res` to decide whether to overwrite
351        // resolution, and if it is already overwritten from previous block lowering this
352        // check will not pass.
353        for id in overwrites {
354            self.partial_res_overrides.remove(&id);
355        }
356
357        block
358    }
359
360    fn finalize_body_lowering(
361        &mut self,
362        delegation: &Delegation,
363        stmts: &'hir [hir::Stmt<'hir>],
364        args: Vec<hir::Expr<'hir>>,
365        res: &DelegationResolution,
366        generics: &mut GenericsGenerationResults<'hir>,
367        span: Span,
368    ) -> (hir::Expr<'hir>, HirId) {
369        let path = self.lower_qpath(
370            delegation.id,
371            &delegation.qself,
372            &delegation.path,
373            ParamMode::Optional,
374            AllowReturnTypeNotation::No,
375            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
376            None,
377        );
378
379        let new_path = match path {
380            hir::QPath::Resolved(ty, path) => {
381                let mut new_path = path.clone();
382                let len = new_path.segments.len();
383
384                new_path.segments = self.arena.alloc_from_iter(
385                    new_path.segments.iter().enumerate().map(|(idx, segment)| {
386                        if idx + 2 == len {
387                            self.process_segment(span, segment, &mut generics.parent)
388                        } else if idx + 1 == len {
389                            self.process_segment(span, segment, &mut generics.child)
390                        } else {
391                            segment.clone()
392                        }
393                    }),
394                );
395
396                // Explicitly create `Self` self-type in case of infers or static
397                // free-to-trait reuses.
398                let ty = match generics.self_ty_propagation_kind {
399                    Some(hir::DelegationSelfTyPropagationKind::SelfParam) => {
400                        let self_param = generics.parent.generics.find_self_param();
401                        let path = self.create_generic_arg_path(self_param);
402                        let kind = hir::TyKind::Path(path);
403
404                        let ty = match ty {
405                            Some(ty) => hir::Ty { kind, ..ty.clone() },
406                            None => hir::Ty { kind, hir_id: self.next_id(), span },
407                        };
408
409                        Some(&*self.arena.alloc(ty))
410                    }
411                    _ => ty,
412                };
413
414                hir::QPath::Resolved(ty, self.arena.alloc(new_path))
415            }
416            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"),
417        };
418
419        if let Some(hir::DelegationSelfTyPropagationKind::SelfTy(id)) =
420            generics.self_ty_propagation_kind.as_mut()
421        {
422            *id = match new_path {
423                hir::QPath::Resolved(ty, _) => {
424                    ty.expect("must contain self type as `SelfTy` propagation kind is specified")
425                }
426                hir::QPath::TypeRelative(ty, _) => ty,
427            }
428            .hir_id;
429        }
430
431        let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
432        let args = self.arena.alloc_from_iter(args);
433        let call = self.mk_expr(hir::ExprKind::Call(callee_path, args), span);
434
435        let expr = if res.sig_mapping.map_return {
436            let res = Res::SelfTyAlias {
437                alias_to: res.parent.to_def_id(),
438                is_trait_impl: self.tcx.def_kind(res.parent) == DefKind::Impl { of_trait: true },
439            };
440
441            let ident = Ident::new(kw::SelfUpper, span);
442            let path = self.create_resolved_path(res, ident, span);
443
444            // FIXME(fn_delegation): add default `..` for all other fields.
445            let initializer = hir::ExprKind::Struct(
446                self.arena.alloc(path),
447                self.arena.alloc_slice(&[hir::ExprField {
448                    hir_id: self.next_id(),
449                    is_shorthand: false,
450                    ident: Ident::new(sym::integer(0), span),
451                    expr: self.arena.alloc(call),
452                    span,
453                }]),
454                hir::StructTailExpr::None,
455            );
456
457            self.arena.alloc(self.mk_expr(initializer, span))
458        } else {
459            self.arena.alloc(call)
460        };
461
462        let block = self.arena.alloc(hir::Block {
463            stmts,
464            expr: Some(expr),
465            hir_id: self.next_id(),
466            rules: hir::BlockCheckMode::DefaultBlock,
467            span,
468            targeted_by_break: false,
469        });
470
471        (self.mk_expr(hir::ExprKind::Block(block, None), span), call.hir_id)
472    }
473
474    fn process_segment(
475        &mut self,
476        span: Span,
477        segment: &hir::PathSegment<'hir>,
478        result: &mut GenericsGenerationResult<'hir>,
479    ) -> hir::PathSegment<'hir> {
480        let infer_indices = result.generics.infer_indices();
481        result.generics.into_hir_generics(self, span);
482
483        let mut segment = segment.clone();
484        let mut args_iter = result.generics.create_args_iterator();
485
486        let new_args = segment
487            .args
488            .filter(|args| !args.is_empty())
489            .map(|args| {
490                self.arena.alloc_from_iter(args.args.iter().enumerate().map(|(idx, arg)| {
491                    if infer_indices.contains(&idx) {
492                        args_iter.next(self, |_| arg.hir_id()).expect("arg must exist for infer")
493                    } else {
494                        *arg
495                    }
496                }))
497            })
498            .unwrap_or_else(|| self.arena.alloc_from_iter(args_iter.consume_all(self)));
499
500        // Do not omit constraints as there might be some and they must be present in HIR (#158812).
501        let has_constraints = segment.args.is_some_and(|a| !a.constraints.is_empty());
502
503        // Needed for better error messages (`trait-impl-wrong-args-count.rs` test).
504        segment.args = (has_constraints || !new_args.is_empty()).then(|| {
505            &*self.arena.alloc(hir::GenericArgs {
506                args: new_args,
507                constraints: segment.args.map(|a| a.constraints).unwrap_or(&[]),
508                parenthesized: hir::GenericArgsParentheses::No,
509                span_ext: segment.args.map_or(span, |args| args.span_ext),
510            })
511        });
512
513        result.args_segment_id = segment.hir_id;
514        result.use_for_sig_inheritance = !result.generics.is_trait_impl();
515
516        segment.delegation_child_segment = result.generics.pos() == GenericsPosition::Child;
517
518        segment
519    }
520
521    fn generate_delegation_error(
522        &mut self,
523        span: Span,
524        delegation: &Delegation,
525    ) -> DelegationResults<'hir> {
526        let decl = self.arena.alloc(hir::FnDecl::dummy(span));
527
528        let header = self.generate_header_error();
529        let sig = hir::FnSig { decl, header, span };
530
531        let ident = self.lower_ident(delegation.ident);
532
533        let body_id = self.lower_body(|this| {
534            let path = this.lower_qpath(
535                delegation.id,
536                &delegation.qself,
537                &delegation.path,
538                ParamMode::Optional,
539                AllowReturnTypeNotation::No,
540                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
541                None,
542            );
543
544            let callee_path = this.arena.alloc(this.mk_expr(hir::ExprKind::Path(path), span));
545            let args = if let Some(block) = &delegation.body {
546                this.arena.alloc_slice(&[this.lower_block_expr(block)])
547            } else {
548                &mut []
549            };
550
551            let call = this.arena.alloc(this.mk_expr(hir::ExprKind::Call(callee_path, args), span));
552
553            let block = this.arena.alloc(hir::Block {
554                stmts: &[],
555                expr: Some(call),
556                hir_id: this.next_id(),
557                rules: hir::BlockCheckMode::DefaultBlock,
558                span,
559                targeted_by_break: false,
560            });
561
562            (&[], this.mk_expr(hir::ExprKind::Block(block, None), span))
563        });
564
565        let generics = hir::Generics::empty();
566        DelegationResults { ident, generics, body_id, sig }
567    }
568
569    fn generate_header_error(&self) -> hir::FnHeader {
570        hir::FnHeader {
571            safety: hir::Safety::Safe.into(),
572            constness: hir::Constness::NotConst,
573            asyncness: hir::IsAsync::NotAsync,
574            abi: ExternAbi::Rust,
575        }
576    }
577
578    #[inline]
579    fn mk_expr(&mut self, kind: hir::ExprKind<'hir>, span: Span) -> hir::Expr<'hir> {
580        hir::Expr { hir_id: self.next_id(), kind, span }
581    }
582}
583
584struct SelfResolver<'a, 'b, 'hir> {
585    ctxt: &'a mut LoweringContext<'b, 'hir>,
586    path_id: NodeId,
587    self_param_id: NodeId,
588    overwrites: Vec<NodeId>,
589}
590
591impl SelfResolver<'_, '_, '_> {
592    fn try_replace_id(&mut self, id: NodeId) {
593        if let Some(res) = self.ctxt.get_partial_res(id)
594            && let Some(Res::Local(sig_id)) = res.full_res()
595            && sig_id == self.path_id
596        {
597            self.overwrites.push(id);
598            self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
599        }
600    }
601}
602
603impl<'ast> Visitor<'ast> for SelfResolver<'_, '_, '_> {
604    fn visit_id(&mut self, id: NodeId) {
605        self.try_replace_id(id);
606    }
607}