Skip to main content

rustc_hir_analysis/
delegation.rs

1//! Support inheriting generic parameters and predicates for function delegation.
2//!
3//! For more information about delegation design, see the tracking issue #118212.
4
5use std::debug_assert_matches;
6
7use rustc_data_structures::fx::FxHashMap;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_hir::{HirId, PathSegment};
11use rustc_middle::ty::{
12    self, EarlyBinder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
13};
14use rustc_span::{ErrorGuaranteed, Span, kw};
15
16use crate::collect::ItemCtxt;
17use crate::hir_ty_lowering::{GenericArgPosition, HirTyLowerer};
18
19type RemapTable = FxHashMap<u32, u32>;
20
21struct ParamIndexRemapper<'tcx> {
22    tcx: TyCtxt<'tcx>,
23    remap_table: RemapTable,
24}
25
26impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ParamIndexRemapper<'tcx> {
27    fn cx(&self) -> TyCtxt<'tcx> {
28        self.tcx
29    }
30
31    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
32        if !ty.has_param() {
33            return ty;
34        }
35
36        if let ty::Param(param) = ty.kind()
37            && let Some(index) = self.remap_table.get(&param.index)
38        {
39            return Ty::new_param(self.tcx, *index, param.name);
40        }
41        ty.super_fold_with(self)
42    }
43
44    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
45        if let ty::ReEarlyParam(param) = r.kind()
46            && let Some(index) = self.remap_table.get(&param.index).copied()
47        {
48            return ty::Region::new_early_param(
49                self.tcx,
50                ty::EarlyParamRegion { index, name: param.name },
51            );
52        }
53        r
54    }
55
56    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
57        if let ty::ConstKind::Param(param) = ct.kind()
58            && let Some(idx) = self.remap_table.get(&param.index)
59        {
60            let param = ty::ParamConst::new(*idx, param.name);
61            return ty::Const::new_param(self.tcx, param);
62        }
63        ct.super_fold_with(self)
64    }
65}
66
67enum SelfPositionKind {
68    AfterLifetimes,
69    Zero,
70    None,
71}
72
73fn create_self_position_kind(caller_kind: FnKind, callee_kind: FnKind) -> SelfPositionKind {
74    match (caller_kind, callee_kind) {
75        (FnKind::AssocInherentImpl, FnKind::AssocTrait)
76        | (FnKind::AssocTraitImpl, FnKind::AssocTrait)
77        | (FnKind::AssocTrait, FnKind::AssocTrait)
78        | (FnKind::AssocTrait, FnKind::Free) => SelfPositionKind::Zero,
79
80        (FnKind::Free, FnKind::AssocTrait) => SelfPositionKind::AfterLifetimes,
81
82        _ => SelfPositionKind::None,
83    }
84}
85
86#[derive(#[automatically_derived]
impl ::core::clone::Clone for FnKind {
    #[inline]
    fn clone(&self) -> FnKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FnKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for FnKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                FnKind::Free => "Free",
                FnKind::AssocInherentImpl => "AssocInherentImpl",
                FnKind::AssocTrait => "AssocTrait",
                FnKind::AssocTraitImpl => "AssocTraitImpl",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for FnKind {
    #[inline]
    fn eq(&self, other: &FnKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
87enum FnKind {
88    Free,
89    AssocInherentImpl,
90    AssocTrait,
91    AssocTraitImpl,
92}
93
94fn fn_kind<'tcx>(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> FnKind {
95    let def_id = def_id.into();
96
97    if true {
    match tcx.def_kind(def_id) {
        DefKind::Fn | DefKind::AssocFn => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "DefKind::Fn | DefKind::AssocFn",
                ::core::option::Option::None);
        }
    };
};debug_assert_matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn);
98
99    let parent = tcx.parent(def_id);
100    match tcx.def_kind(parent) {
101        DefKind::Trait => FnKind::AssocTrait,
102        DefKind::Impl { of_trait: true } => FnKind::AssocTraitImpl,
103        DefKind::Impl { of_trait: false } => FnKind::AssocInherentImpl,
104        _ => FnKind::Free,
105    }
106}
107
108/// Given the current context(caller and callee `FnKind`), it specifies
109/// the policy of predicates and generic parameters inheritance.
110#[derive(#[automatically_derived]
impl ::core::clone::Clone for InheritanceKind {
    #[inline]
    fn clone(&self) -> InheritanceKind {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for InheritanceKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InheritanceKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            InheritanceKind::WithParent(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "WithParent", &__self_0),
            InheritanceKind::Own =>
                ::core::fmt::Formatter::write_str(f, "Own"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for InheritanceKind {
    #[inline]
    fn eq(&self, other: &InheritanceKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (InheritanceKind::WithParent(__self_0),
                    InheritanceKind::WithParent(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
111enum InheritanceKind {
112    /// Copying all predicates and parameters, including those of the parent
113    /// container.
114    ///
115    /// Boolean value defines whether the `Self` parameter or `Self: Trait`
116    /// predicate are copied. It's always equal to `false` except when
117    /// delegating from a free function to a trait method.
118    ///
119    /// FIXME(fn_delegation): This often leads to type inference
120    /// errors. Support providing generic arguments or restrict use sites.
121    WithParent(bool),
122    /// The trait implementation should be compatible with the original trait.
123    /// Therefore, for trait implementations only the method's own parameters
124    /// and predicates are copied.
125    Own,
126}
127
128/// Maps sig generics into generic args of delegation. Delegation generics has the following pattern:
129///
130/// [SELF | maybe self in the beginning]
131/// [PARENT | args of delegation parent]
132/// [SIG PARENT LIFETIMES]
133/// [SIG LIFETIMES]
134/// [SELF | maybe self after lifetimes, when we reuse trait fn in free context]
135/// [SIG PARENT TYPES/CONSTS]
136/// [SIG TYPES/CONSTS]
137fn create_mapping<'tcx>(
138    tcx: TyCtxt<'tcx>,
139    sig_id: DefId,
140    def_id: LocalDefId,
141) -> FxHashMap<u32, u32> {
142    let mut mapping: FxHashMap<u32, u32> = Default::default();
143
144    let (caller_kind, callee_kind) = (fn_kind(tcx, def_id), fn_kind(tcx, sig_id));
145    let self_pos_kind = create_self_position_kind(caller_kind, callee_kind);
146    let is_self_at_zero = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
    SelfPositionKind::Zero => true,
    _ => false,
}matches!(self_pos_kind, SelfPositionKind::Zero);
147
148    // Is self at zero? If so insert mapping, self in sig parent is always at 0.
149    if is_self_at_zero {
150        mapping.insert(0, 0);
151    }
152
153    let mut args_index = 0;
154
155    args_index += is_self_at_zero as usize;
156    args_index += get_delegation_parent_args_count_without_self(tcx, def_id, sig_id);
157
158    let sig_generics = tcx.generics_of(sig_id);
159    let process_sig_parent_generics = #[allow(non_exhaustive_omitted_patterns)] match callee_kind {
    FnKind::AssocTrait => true,
    _ => false,
}matches!(callee_kind, FnKind::AssocTrait);
160
161    if process_sig_parent_generics {
162        for i in (sig_generics.has_self as usize)..sig_generics.parent_count {
163            let param = sig_generics.param_at(i, tcx);
164            if !param.kind.is_ty_or_const() {
165                mapping.insert(param.index, args_index as u32);
166                args_index += 1;
167            }
168        }
169    }
170
171    for param in &sig_generics.own_params {
172        if !param.kind.is_ty_or_const() {
173            mapping.insert(param.index, args_index as u32);
174            args_index += 1;
175        }
176    }
177
178    // If self after lifetimes insert mapping, relying that self is at 0 in sig parent.
179    if #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
    SelfPositionKind::AfterLifetimes => true,
    _ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes) {
180        mapping.insert(0, args_index as u32);
181        args_index += 1;
182    }
183
184    if process_sig_parent_generics {
185        for i in (sig_generics.has_self as usize)..sig_generics.parent_count {
186            let param = sig_generics.param_at(i, tcx);
187            if param.kind.is_ty_or_const() {
188                mapping.insert(param.index, args_index as u32);
189                args_index += 1;
190            }
191        }
192    }
193
194    for param in &sig_generics.own_params {
195        if param.kind.is_ty_or_const() {
196            mapping.insert(param.index, args_index as u32);
197            args_index += 1;
198        }
199    }
200
201    mapping
202}
203
204fn get_delegation_parent_args_count_without_self<'tcx>(
205    tcx: TyCtxt<'tcx>,
206    delegation_id: LocalDefId,
207    sig_id: DefId,
208) -> usize {
209    let delegation_parent_args_count = tcx.generics_of(delegation_id).parent_count;
210
211    match (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id)) {
212        (FnKind::Free, FnKind::Free)
213        | (FnKind::Free, FnKind::AssocTrait)
214        | (FnKind::AssocTraitImpl, FnKind::AssocTrait) => 0,
215
216        (FnKind::AssocInherentImpl, FnKind::Free)
217        | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
218            delegation_parent_args_count /* No Self in AssocInherentImpl */
219        }
220
221        (FnKind::AssocTrait, FnKind::Free) | (FnKind::AssocTrait, FnKind::AssocTrait) => {
222            delegation_parent_args_count - 1 /* Without Self */
223        }
224
225        // For trait impl's `sig_id` is always equal to the corresponding trait method.
226        // For inherent methods delegation is not yet supported.
227        (FnKind::AssocTraitImpl, _)
228        | (_, FnKind::AssocTraitImpl)
229        | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
230    }
231}
232
233fn get_parent_and_inheritance_kind<'tcx>(
234    tcx: TyCtxt<'tcx>,
235    def_id: LocalDefId,
236    sig_id: DefId,
237) -> (Option<DefId>, InheritanceKind) {
238    match (fn_kind(tcx, def_id), fn_kind(tcx, sig_id)) {
239        (FnKind::Free, FnKind::Free) | (FnKind::Free, FnKind::AssocTrait) => {
240            (None, InheritanceKind::WithParent(true))
241        }
242
243        (FnKind::AssocTraitImpl, FnKind::AssocTrait) => {
244            (Some(tcx.parent(def_id.to_def_id())), InheritanceKind::Own)
245        }
246
247        (FnKind::AssocInherentImpl, FnKind::AssocTrait)
248        | (FnKind::AssocTrait, FnKind::AssocTrait)
249        | (FnKind::AssocInherentImpl, FnKind::Free)
250        | (FnKind::AssocTrait, FnKind::Free) => {
251            (Some(tcx.parent(def_id.to_def_id())), InheritanceKind::WithParent(false))
252        }
253
254        // For trait impl's `sig_id` is always equal to the corresponding trait method.
255        // For inherent methods delegation is not yet supported.
256        (FnKind::AssocTraitImpl, _)
257        | (_, FnKind::AssocTraitImpl)
258        | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
259    }
260}
261
262fn get_delegation_self_ty<'tcx>(tcx: TyCtxt<'tcx>, delegation_id: LocalDefId) -> Option<Ty<'tcx>> {
263    let sig_id = tcx.hir_opt_delegation_sig_id(delegation_id).expect("Delegation must have sig_id");
264    let (caller_kind, callee_kind) = (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id));
265
266    match (caller_kind, callee_kind) {
267        (FnKind::Free, FnKind::AssocTrait)
268        | (FnKind::AssocInherentImpl, FnKind::Free)
269        | (FnKind::Free, FnKind::Free)
270        | (FnKind::AssocTrait, FnKind::Free)
271        | (FnKind::AssocTrait, FnKind::AssocTrait) => {
272            match create_self_position_kind(caller_kind, callee_kind) {
273                SelfPositionKind::None => None,
274                SelfPositionKind::AfterLifetimes => {
275                    // Both sig parent and child lifetimes are in included in this count.
276                    Some(tcx.generics_of(delegation_id).own_counts().lifetimes)
277                }
278                SelfPositionKind::Zero => Some(0),
279            }
280            .map(|self_index| Ty::new_param(tcx, self_index as u32, kw::SelfUpper))
281        }
282
283        (FnKind::AssocTraitImpl, FnKind::AssocTrait)
284        | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
285            Some(tcx.type_of(tcx.local_parent(delegation_id)).instantiate_identity())
286        }
287
288        // For trait impl's `sig_id` is always equal to the corresponding trait method.
289        // For inherent methods delegation is not yet supported.
290        (FnKind::AssocTraitImpl, _)
291        | (_, FnKind::AssocTraitImpl)
292        | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
293    }
294}
295
296/// Creates generic arguments for further delegation signature and predicates instantiation.
297/// Arguments can be user-specified (in this case they are in `parent_args` and `child_args`)
298/// or propagated. User can specify either both `parent_args` and `child_args`, one of them or none,
299/// that is why we firstly create generic arguments from generic params and then adjust them with
300/// user-specified args.
301///
302/// The order of produced list is important, it must be of this pattern:
303///
304/// [SELF | maybe self in the beginning]
305/// [PARENT | args of delegation parent]
306/// [SIG PARENT LIFETIMES] <- `lifetimes_end_pos`
307/// [SIG LIFETIMES]
308/// [SELF | maybe self after lifetimes, when we reuse trait fn in free context]
309/// [SIG PARENT TYPES/CONSTS]
310/// [SIG TYPES/CONSTS]
311fn create_generic_args<'tcx>(
312    tcx: TyCtxt<'tcx>,
313    sig_id: DefId,
314    delegation_id: LocalDefId,
315    mut parent_args: &[ty::GenericArg<'tcx>],
316    child_args: &[ty::GenericArg<'tcx>],
317) -> Vec<ty::GenericArg<'tcx>> {
318    let (caller_kind, callee_kind) = (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id));
319
320    let delegation_args = ty::GenericArgs::identity_for_item(tcx, delegation_id);
321    let delegation_parent_args_count = tcx.generics_of(delegation_id).parent_count;
322
323    let deleg_parent_args_without_self_count =
324        get_delegation_parent_args_count_without_self(tcx, delegation_id, sig_id);
325
326    let args = match (caller_kind, callee_kind) {
327        (FnKind::Free, FnKind::Free)
328        | (FnKind::Free, FnKind::AssocTrait)
329        | (FnKind::AssocInherentImpl, FnKind::Free)
330        | (FnKind::AssocTrait, FnKind::Free)
331        | (FnKind::AssocTrait, FnKind::AssocTrait) => delegation_args,
332
333        (FnKind::AssocTraitImpl, FnKind::AssocTrait) => {
334            // Special case, as user specifies Trait args in trait impl header, we want to treat
335            // them as parent args. We always generate a function whose generics match
336            // child generics in trait.
337            let parent = tcx.local_parent(delegation_id);
338            parent_args = tcx.impl_trait_header(parent).trait_ref.instantiate_identity().args;
339
340            if !child_args.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("Child args can not be used in trait impl case"));
    }
};assert!(child_args.is_empty(), "Child args can not be used in trait impl case");
341
342            tcx.mk_args(&delegation_args[delegation_parent_args_count..])
343        }
344
345        (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
346            let self_ty = tcx.type_of(tcx.local_parent(delegation_id)).instantiate_identity();
347
348            tcx.mk_args_from_iter(
349                std::iter::once(ty::GenericArg::from(self_ty)).chain(delegation_args.iter()),
350            )
351        }
352
353        // For trait impl's `sig_id` is always equal to the corresponding trait method.
354        // For inherent methods delegation is not yet supported.
355        (FnKind::AssocTraitImpl, _)
356        | (_, FnKind::AssocTraitImpl)
357        | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
358    };
359
360    let mut new_args = ::alloc::vec::Vec::new()vec![];
361
362    let self_pos_kind = create_self_position_kind(caller_kind, callee_kind);
363    let mut lifetimes_end_pos;
364
365    if !parent_args.is_empty() {
366        let parent_args_lifetimes_count =
367            parent_args.iter().filter(|a| a.as_region().is_some()).count();
368
369        match self_pos_kind {
370            SelfPositionKind::AfterLifetimes => {
371                new_args.extend(&parent_args[1..1 + parent_args_lifetimes_count]);
372
373                lifetimes_end_pos = parent_args_lifetimes_count;
374
375                new_args.push(parent_args[0]);
376
377                new_args.extend(&parent_args[1 + parent_args_lifetimes_count..]);
378            }
379            SelfPositionKind::Zero => {
380                lifetimes_end_pos = 1 /* Self */ + parent_args_lifetimes_count;
381                new_args.extend_from_slice(parent_args);
382
383                for i in 0..deleg_parent_args_without_self_count {
384                    new_args.insert(1 + i, args[1 + i]);
385                }
386
387                lifetimes_end_pos += deleg_parent_args_without_self_count;
388            }
389            // If we have parent args then we obtained them from trait, then self must be somewhere
390            SelfPositionKind::None => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
391        };
392    } else {
393        let self_impact = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
    SelfPositionKind::Zero => true,
    _ => false,
}matches!(self_pos_kind, SelfPositionKind::Zero) as usize;
394
395        lifetimes_end_pos = self_impact
396            + deleg_parent_args_without_self_count
397            + &args[self_impact + deleg_parent_args_without_self_count..]
398                .iter()
399                .filter(|a| a.as_region().is_some())
400                .count();
401
402        new_args.extend_from_slice(args);
403    }
404
405    if !child_args.is_empty() {
406        let child_lifetimes_count = child_args.iter().filter(|a| a.as_region().is_some()).count();
407
408        for i in 0..child_lifetimes_count {
409            new_args.insert(lifetimes_end_pos + i, child_args[i]);
410        }
411
412        new_args.extend_from_slice(&child_args[child_lifetimes_count..]);
413    } else if !parent_args.is_empty() {
414        let child_args = &delegation_args[delegation_parent_args_count..];
415
416        let child_lifetimes_count =
417            child_args.iter().take_while(|a| a.as_region().is_some()).count();
418
419        for i in 0..child_lifetimes_count {
420            new_args.insert(lifetimes_end_pos + i, child_args[i]);
421        }
422
423        let skip_self = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
    SelfPositionKind::AfterLifetimes => true,
    _ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes);
424        new_args.extend(&child_args[child_lifetimes_count + skip_self as usize..]);
425    }
426
427    new_args
428}
429
430pub(crate) fn inherit_predicates_for_delegation_item<'tcx>(
431    tcx: TyCtxt<'tcx>,
432    def_id: LocalDefId,
433    sig_id: DefId,
434) -> ty::GenericPredicates<'tcx> {
435    struct PredicatesCollector<'tcx> {
436        tcx: TyCtxt<'tcx>,
437        preds: Vec<(ty::Clause<'tcx>, Span)>,
438        args: Vec<ty::GenericArg<'tcx>>,
439        folder: ParamIndexRemapper<'tcx>,
440    }
441
442    impl<'tcx> PredicatesCollector<'tcx> {
443        fn with_own_preds(
444            mut self,
445            f: impl Fn(DefId) -> ty::GenericPredicates<'tcx>,
446            def_id: DefId,
447        ) -> Self {
448            let preds = f(def_id);
449            let args = self.args.as_slice();
450
451            for pred in preds.predicates {
452                let new_pred = pred.0.fold_with(&mut self.folder);
453                self.preds.push((EarlyBinder::bind(new_pred).instantiate(self.tcx, args), pred.1));
454            }
455
456            self
457        }
458
459        fn with_preds(
460            mut self,
461            f: impl Fn(DefId) -> ty::GenericPredicates<'tcx> + Copy,
462            def_id: DefId,
463        ) -> Self {
464            let preds = f(def_id);
465            if let Some(parent_def_id) = preds.parent {
466                self = self.with_own_preds(f, parent_def_id);
467            }
468
469            self.with_own_preds(f, def_id)
470        }
471    }
472
473    let (parent_args, child_args) = get_delegation_user_specified_args(tcx, def_id);
474    let (folder, args) = create_folder_and_args(tcx, def_id, sig_id, parent_args, child_args);
475    let collector = PredicatesCollector { tcx, preds: ::alloc::vec::Vec::new()vec![], args, folder };
476
477    let (parent, inh_kind) = get_parent_and_inheritance_kind(tcx, def_id, sig_id);
478
479    // `explicit_predicates_of` is used here to avoid copying `Self: Trait` predicate.
480    // Note: `predicates_of` query can also add inferred outlives predicates, but that
481    // is not the case here as `sig_id` is either a trait or a function.
482    let preds = match inh_kind {
483        InheritanceKind::WithParent(false) => {
484            collector.with_preds(|def_id| tcx.explicit_predicates_of(def_id), sig_id)
485        }
486        InheritanceKind::WithParent(true) => {
487            collector.with_preds(|def_id| tcx.predicates_of(def_id), sig_id)
488        }
489        InheritanceKind::Own => {
490            collector.with_own_preds(|def_id| tcx.predicates_of(def_id), sig_id)
491        }
492    }
493    .preds;
494
495    ty::GenericPredicates { parent, predicates: tcx.arena.alloc_from_iter(preds) }
496}
497
498fn create_folder_and_args<'tcx>(
499    tcx: TyCtxt<'tcx>,
500    def_id: LocalDefId,
501    sig_id: DefId,
502    parent_args: &'tcx [ty::GenericArg<'tcx>],
503    child_args: &'tcx [ty::GenericArg<'tcx>],
504) -> (ParamIndexRemapper<'tcx>, Vec<ty::GenericArg<'tcx>>) {
505    let args = create_generic_args(tcx, sig_id, def_id, parent_args, child_args);
506    let remap_table = create_mapping(tcx, sig_id, def_id);
507
508    (ParamIndexRemapper { tcx, remap_table }, args)
509}
510
511fn check_constraints<'tcx>(
512    tcx: TyCtxt<'tcx>,
513    def_id: LocalDefId,
514    sig_id: DefId,
515) -> Result<(), ErrorGuaranteed> {
516    let mut ret = Ok(());
517
518    let mut emit = |descr| {
519        ret = Err(tcx.dcx().emit_err(crate::errors::UnsupportedDelegation {
520            span: tcx.def_span(def_id),
521            descr,
522            callee_span: tcx.def_span(sig_id),
523        }));
524    };
525
526    if tcx.fn_sig(sig_id).skip_binder().skip_binder().c_variadic {
527        // See issue #127443 for explanation.
528        emit("delegation to C-variadic functions is not allowed");
529    }
530
531    ret
532}
533
534pub(crate) fn inherit_sig_for_delegation_item<'tcx>(
535    tcx: TyCtxt<'tcx>,
536    def_id: LocalDefId,
537) -> &'tcx [Ty<'tcx>] {
538    let sig_id = tcx.hir_opt_delegation_sig_id(def_id).expect("Delegation must have sig_id");
539    let caller_sig = tcx.fn_sig(sig_id);
540
541    if let Err(err) = check_constraints(tcx, def_id, sig_id) {
542        let sig_len = caller_sig.instantiate_identity().skip_binder().inputs().len() + 1;
543        let err_type = Ty::new_error(tcx, err);
544        return tcx.arena.alloc_from_iter((0..sig_len).map(|_| err_type));
545    }
546
547    let (parent_args, child_args) = get_delegation_user_specified_args(tcx, def_id);
548    let (mut folder, args) = create_folder_and_args(tcx, def_id, sig_id, parent_args, child_args);
549    let caller_sig = EarlyBinder::bind(caller_sig.skip_binder().fold_with(&mut folder));
550
551    let sig = caller_sig.instantiate(tcx, args.as_slice()).skip_binder();
552    let sig_iter = sig.inputs().iter().cloned().chain(std::iter::once(sig.output()));
553    tcx.arena.alloc_from_iter(sig_iter)
554}
555
556// Creates user-specified generic arguments from delegation path,
557// they will be used during delegation signature and predicates inheritance.
558// Example: reuse Trait::<'static, i32, 1>::foo::<A, B>
559// we want to extract [Self, 'static, i32, 1] for parent and [A, B] for child.
560fn get_delegation_user_specified_args<'tcx>(
561    tcx: TyCtxt<'tcx>,
562    delegation_id: LocalDefId,
563) -> (&'tcx [ty::GenericArg<'tcx>], &'tcx [ty::GenericArg<'tcx>]) {
564    let info = tcx
565        .hir_node(tcx.local_def_id_to_hir_id(delegation_id))
566        .fn_sig()
567        .expect("Lowering delegation")
568        .decl
569        .opt_delegation_generics()
570        .expect("Lowering delegation");
571
572    let get_segment = |hir_id: HirId| -> Option<(&'tcx PathSegment<'tcx>, DefId)> {
573        let segment = tcx.hir_node(hir_id).expect_path_segment();
574        segment.res.opt_def_id().map(|def_id| (segment, def_id))
575    };
576
577    let ctx = ItemCtxt::new(tcx, delegation_id);
578    let lowerer = ctx.lowerer();
579
580    let parent_args = info.parent_args_segment_id.and_then(get_segment).map(|(segment, def_id)| {
581        let self_ty = get_delegation_self_ty(tcx, delegation_id);
582
583        lowerer
584            .lower_generic_args_of_path(
585                segment.ident.span,
586                def_id,
587                &[],
588                segment,
589                self_ty,
590                GenericArgPosition::Type,
591            )
592            .0
593            .as_slice()
594    });
595
596    let child_args = info
597        .child_args_segment_id
598        .and_then(get_segment)
599        .filter(|(_, def_id)| #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(*def_id) {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(tcx.def_kind(*def_id), DefKind::Fn | DefKind::AssocFn))
600        .map(|(segment, def_id)| {
601            let parent_args = if let Some(parent_args) = parent_args {
602                parent_args
603            } else {
604                let parent = tcx.parent(def_id);
605                if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(parent) {
    DefKind::Trait => true,
    _ => false,
}matches!(tcx.def_kind(parent), DefKind::Trait) {
606                    ty::GenericArgs::identity_for_item(tcx, parent).as_slice()
607                } else {
608                    &[]
609                }
610            };
611
612            let args = lowerer
613                .lower_generic_args_of_path(
614                    segment.ident.span,
615                    def_id,
616                    parent_args,
617                    segment,
618                    None,
619                    GenericArgPosition::Value,
620                )
621                .0;
622
623            &args[parent_args.len()..]
624        });
625
626    (parent_args.unwrap_or_default(), child_args.unwrap_or_default())
627}