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