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