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