Skip to main content

rustc_ast_lowering/delegation/
generics.rs

1use hir::HirId;
2use hir::def::{DefKind, Res};
3use rustc_ast::*;
4use rustc_hir as hir;
5use rustc_hir::def_id::DefId;
6use rustc_middle::ty::GenericParamDefKind;
7use rustc_middle::{bug, ty};
8use rustc_span::symbol::kw;
9use rustc_span::{Ident, Span, sym};
10
11use crate::LoweringContext;
12
13#[derive(#[automatically_derived]
impl ::core::clone::Clone for DelegationGenericsKind {
    #[inline]
    fn clone(&self) -> DelegationGenericsKind {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DelegationGenericsKind { }Copy)]
14pub(super) enum DelegationGenericsKind {
15    /// User-specified args are present: `reuse foo::<String>;`.
16    UserSpecified,
17    /// The default case when no user-specified args are present: `reuse Trait::foo;`.
18    Default,
19    /// In free-to-trait reuse, when user specified args for trait `reuse Trait::<i32>::foo;`
20    /// in this case we need to both generate `Self` and process user args.
21    SelfAndUserSpecified,
22    /// In delegations from trait impl to other entities like free functions or trait functions,
23    /// we want to generate a function whose generics matches generics of signature function
24    /// in trait.
25    TraitImpl(bool /* Has user-specified args */),
26}
27
28#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericsPosition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                GenericsPosition::Parent => "Parent",
                GenericsPosition::Child => "Child",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for GenericsPosition {
    #[inline]
    fn clone(&self) -> GenericsPosition { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for GenericsPosition { }Copy)]
29pub(super) enum GenericsPosition {
30    Parent,
31    Child,
32}
33
34pub(super) struct DelegationGenerics<T> {
35    generics: T,
36    kind: DelegationGenericsKind,
37    pos: GenericsPosition,
38}
39
40impl<'hir> DelegationGenerics<&'hir [ty::GenericParamDef]> {
41    fn default(generics: &'hir [ty::GenericParamDef], pos: GenericsPosition) -> Self {
42        DelegationGenerics { generics, pos, kind: DelegationGenericsKind::Default }
43    }
44
45    fn user_specified(generics: &'hir [ty::GenericParamDef], pos: GenericsPosition) -> Self {
46        DelegationGenerics { generics, pos, kind: DelegationGenericsKind::UserSpecified }
47    }
48
49    fn trait_impl(
50        generics: &'hir [ty::GenericParamDef],
51        user_specified: bool,
52        pos: GenericsPosition,
53    ) -> Self {
54        DelegationGenerics {
55            generics,
56            pos,
57            kind: DelegationGenericsKind::TraitImpl(user_specified),
58        }
59    }
60}
61
62/// Used for storing either ty generics or their uplifted HIR version. First we obtain
63/// ty generics. Next, at some point of generics processing we need to uplift those
64/// generics to HIR, for this purpose we use `into_hir_generics` that uplifts ty generics
65/// and replaces Ty variant with Hir. Such approach is useful as we can call this method
66/// at any time knowing that uplifting will occur at most only once. Then, in order to obtain generic
67/// params or args we use `hir_generics_or_empty` or `into_generic_args` functions.
68/// There also may be situations when we obtained ty generics but never uplifted them to HIR,
69/// meaning we did not propagate them and thus we do not need to generate generic params
70/// (i.e., method call scenarios), in such a case this approach helps
71/// a lot as if `into_hir_generics` will not be called then uplifting will not happen.
72pub(super) enum HirOrTyGenerics<'hir> {
73    Ty(DelegationGenerics<&'hir [ty::GenericParamDef]>),
74    Hir(DelegationGenerics<&'hir hir::Generics<'hir>>),
75}
76
77pub(super) struct GenericsGenerationResult<'hir> {
78    pub(super) generics: HirOrTyGenerics<'hir>,
79    pub(super) args_segment_id: Option<HirId>,
80}
81
82pub(super) struct GenericsGenerationResults<'hir> {
83    pub(super) parent: GenericsGenerationResult<'hir>,
84    pub(super) child: GenericsGenerationResult<'hir>,
85    pub(super) self_ty_id: Option<HirId>,
86    pub(super) propagate_self_ty: bool,
87}
88
89pub(super) struct GenericArgsPropagationDetails {
90    pub(super) should_propagate: bool,
91    pub(super) use_args_in_sig_inheritance: bool,
92}
93
94impl DelegationGenericsKind {
95    fn args_propagation_details(self) -> GenericArgsPropagationDetails {
96        match self {
97            DelegationGenericsKind::UserSpecified
98            | DelegationGenericsKind::SelfAndUserSpecified => GenericArgsPropagationDetails {
99                should_propagate: false,
100                use_args_in_sig_inheritance: true,
101            },
102            DelegationGenericsKind::TraitImpl(user_specified) => GenericArgsPropagationDetails {
103                should_propagate: !user_specified,
104                use_args_in_sig_inheritance: false,
105            },
106            DelegationGenericsKind::Default => GenericArgsPropagationDetails {
107                should_propagate: true,
108                use_args_in_sig_inheritance: false,
109            },
110        }
111    }
112}
113
114impl<'hir> HirOrTyGenerics<'hir> {
115    pub(super) fn into_hir_generics(
116        &mut self,
117        ctx: &mut LoweringContext<'_, 'hir>,
118        span: Span,
119    ) -> &mut HirOrTyGenerics<'hir> {
120        if let HirOrTyGenerics::Ty(ty) = self {
121            let rename_self = #[allow(non_exhaustive_omitted_patterns)] match ty.pos {
    GenericsPosition::Child => true,
    _ => false,
}matches!(ty.pos, GenericsPosition::Child);
122            let params = ctx.uplift_delegation_generic_params(span, ty.generics, rename_self);
123
124            *self = HirOrTyGenerics::Hir(DelegationGenerics {
125                generics: params,
126                kind: ty.kind,
127                pos: ty.pos,
128            });
129        }
130
131        self
132    }
133
134    fn hir_generics_or_empty(&self) -> &'hir hir::Generics<'hir> {
135        match self {
136            HirOrTyGenerics::Ty(_) => hir::Generics::empty(),
137            HirOrTyGenerics::Hir(hir) => hir.generics,
138        }
139    }
140
141    pub(super) fn into_generic_args(
142        &self,
143        ctx: &mut LoweringContext<'_, 'hir>,
144        span: Span,
145    ) -> &'hir hir::GenericArgs<'hir> {
146        match self {
147            HirOrTyGenerics::Ty(_) => {
148                ::rustc_middle::util::bug::bug_fmt(format_args!("Attempting to get generic args before uplifting to HIR"))bug!("Attempting to get generic args before uplifting to HIR")
149            }
150            HirOrTyGenerics::Hir(hir) => {
151                let add_lifetimes = #[allow(non_exhaustive_omitted_patterns)] match hir.pos {
    GenericsPosition::Parent => true,
    _ => false,
}matches!(hir.pos, GenericsPosition::Parent);
152                ctx.create_generics_args_from_params(hir.generics.params, add_lifetimes, span)
153            }
154        }
155    }
156
157    pub(super) fn args_propagation_details(&self) -> GenericArgsPropagationDetails {
158        match self {
159            HirOrTyGenerics::Ty(ty) => ty.kind.args_propagation_details(),
160            HirOrTyGenerics::Hir(hir) => hir.kind.args_propagation_details(),
161        }
162    }
163}
164
165impl<'hir> GenericsGenerationResult<'hir> {
166    fn new(
167        generics: DelegationGenerics<&'hir [ty::GenericParamDef]>,
168    ) -> GenericsGenerationResult<'hir> {
169        GenericsGenerationResult { generics: HirOrTyGenerics::Ty(generics), args_segment_id: None }
170    }
171}
172
173impl<'hir> GenericsGenerationResults<'hir> {
174    pub(super) fn all_params(
175        &mut self,
176        span: Span,
177        ctx: &mut LoweringContext<'_, 'hir>,
178    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
179        // Now we always call `into_hir_generics` both on child and parent,
180        // however in future we would not do that, when scenarios like
181        // method call will be supported (if HIR generics were not obtained
182        // then it means that we did not propagated them, thus we do not need
183        // to generate params).
184        let mut create_params = |result: &mut GenericsGenerationResult<'hir>| {
185            result.generics.into_hir_generics(ctx, span).hir_generics_or_empty().params
186        };
187
188        let parent = create_params(&mut self.parent);
189        let child = create_params(&mut self.child);
190
191        // Order generics, first we have parent and child lifetimes,
192        // then parent and child types and consts.
193        // `generics_of` in `rustc_hir_analysis` will order them anyway,
194        // however we want the order to be consistent in HIR too.
195        parent
196            .iter()
197            .filter(|p| p.is_lifetime())
198            .chain(child.iter().filter(|p| p.is_lifetime()))
199            .chain(parent.iter().filter(|p| !p.is_lifetime()))
200            .chain(child.iter().filter(|p| !p.is_lifetime()))
201            .copied()
202    }
203
204    /// As we add hack predicates(`'a: 'a`) for all lifetimes (see `uplift_delegation_generic_params`
205    /// and `generate_lifetime_predicate` functions) we need to add them to delegation generics.
206    /// Those predicates will not affect resulting predicate inheritance and folding
207    /// in `rustc_hir_analysis`, as we inherit all predicates from delegation signature.
208    pub(super) fn all_predicates(
209        &mut self,
210        span: Span,
211        ctx: &mut LoweringContext<'_, 'hir>,
212    ) -> impl Iterator<Item = hir::WherePredicate<'hir>> {
213        // Now we always call `into_hir_generics` both on child and parent,
214        // however in future we would not do that, when scenarios like
215        // method call will be supported (if HIR generics were not obtained
216        // then it means that we did not propagated them, thus we do not need
217        // to generate predicates).
218        let mut create_predicates = |result: &mut GenericsGenerationResult<'hir>| {
219            result.generics.into_hir_generics(ctx, span).hir_generics_or_empty().predicates
220        };
221
222        let parent = create_predicates(&mut self.parent);
223        let child = create_predicates(&mut self.child);
224
225        parent.into_iter().chain(child).copied()
226    }
227}
228
229impl<'hir> LoweringContext<'_, 'hir> {
230    pub(super) fn uplift_delegation_generics(
231        &mut self,
232        delegation: &Delegation,
233        sig_id: DefId,
234        is_method: bool,
235    ) -> GenericsGenerationResults<'hir> {
236        let delegation_parent_kind = self.tcx.def_kind(self.tcx.local_parent(self.owner.def_id));
237
238        let segments = &delegation.path.segments;
239        let len = segments.len();
240        let child_user_specified = segments[len - 1].args.is_some();
241
242        let sig_params = &self.tcx.generics_of(sig_id).own_params[..];
243
244        // If we are in trait impl always generate function whose generics matches
245        // those that are defined in trait.
246        if #[allow(non_exhaustive_omitted_patterns)] match delegation_parent_kind {
    DefKind::Impl { of_trait: true } => true,
    _ => false,
}matches!(delegation_parent_kind, DefKind::Impl { of_trait: true }) {
247            // Considering parent generics, during signature inheritance
248            // we will take those args that are in trait impl header trait ref.
249            let parent = DelegationGenerics::trait_impl(&[], true, GenericsPosition::Parent);
250            let parent = GenericsGenerationResult::new(parent);
251
252            let child = DelegationGenerics::trait_impl(
253                sig_params,
254                child_user_specified,
255                GenericsPosition::Child,
256            );
257
258            let child = GenericsGenerationResult::new(child);
259
260            return GenericsGenerationResults {
261                parent,
262                child,
263                self_ty_id: None,
264                propagate_self_ty: false,
265            };
266        }
267
268        let delegation_in_free_ctx =
269            !#[allow(non_exhaustive_omitted_patterns)] match delegation_parent_kind {
    DefKind::Trait | DefKind::Impl { .. } => true,
    _ => false,
}matches!(delegation_parent_kind, DefKind::Trait | DefKind::Impl { .. });
270
271        let sig_parent = self.tcx.parent(sig_id);
272        let sig_in_trait = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(sig_parent)
    {
    DefKind::Trait => true,
    _ => false,
}matches!(self.tcx.def_kind(sig_parent), DefKind::Trait);
273        let free_to_trait_delegation = delegation_in_free_ctx && sig_in_trait;
274        let generate_self = free_to_trait_delegation && is_method && delegation.qself.is_none();
275
276        let can_add_generics_to_parent = len >= 2
277            && self.get_resolution_id(segments[len - 2].id).is_some_and(|def_id| {
278                #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Trait | DefKind::TraitAlias => true,
    _ => false,
}matches!(self.tcx.def_kind(def_id), DefKind::Trait | DefKind::TraitAlias)
279            });
280
281        let parent_generics = if can_add_generics_to_parent {
282            let sig_parent_params = &self.tcx.generics_of(sig_parent).own_params[..];
283
284            if segments[len - 2].args.is_some() {
285                if generate_self {
286                    // Take only first Self parameter, it is trait so Self must be present.
287                    DelegationGenerics {
288                        kind: DelegationGenericsKind::SelfAndUserSpecified,
289                        generics: &sig_parent_params[..1],
290                        pos: GenericsPosition::Parent,
291                    }
292                } else {
293                    DelegationGenerics::user_specified(&[], GenericsPosition::Parent)
294                }
295            } else {
296                let skip_self = usize::from(!generate_self);
297                DelegationGenerics::default(
298                    &sig_parent_params[skip_self..],
299                    GenericsPosition::Parent,
300                )
301            }
302        } else {
303            DelegationGenerics::default(&[], GenericsPosition::Parent)
304        };
305
306        let child_generics = if child_user_specified {
307            let synth_params_index =
308                sig_params.iter().position(|p| p.kind.is_synthetic()).unwrap_or(sig_params.len());
309
310            DelegationGenerics::user_specified(
311                &sig_params[synth_params_index..],
312                GenericsPosition::Child,
313            )
314        } else {
315            DelegationGenerics::default(sig_params, GenericsPosition::Child)
316        };
317
318        GenericsGenerationResults {
319            parent: GenericsGenerationResult::new(parent_generics),
320            child: GenericsGenerationResult::new(child_generics),
321            self_ty_id: None,
322            propagate_self_ty: free_to_trait_delegation && !generate_self,
323        }
324    }
325
326    fn uplift_delegation_generic_params(
327        &mut self,
328        span: Span,
329        params: &'hir [ty::GenericParamDef],
330        rename_self: bool,
331    ) -> &'hir hir::Generics<'hir> {
332        let params = self.arena.alloc_from_iter(params.iter().map(|p| {
333            let def_kind = match p.kind {
334                GenericParamDefKind::Lifetime => DefKind::LifetimeParam,
335                GenericParamDefKind::Type { .. } => DefKind::TyParam,
336                GenericParamDefKind::Const { .. } => DefKind::ConstParam,
337            };
338
339            // Rename Self generic param to This so it is properly propagated.
340            // If the user will create a function `fn foo<Self>() {}` with generic
341            // param "Self" then it will not be generated in HIR, the same thing
342            // applies to traits, `trait Trait<Self> {}` will be represented as
343            // `trait Trait {}` in HIR and "unexpected keyword `Self` in generic parameters"
344            // error will be emitted.
345            // Note that we do not rename `Self` to `This` after non-recursive reuse
346            // from Trait, in this case the `Self` should not be propagated
347            // (we rely that implicit `Self` generic param of a trait is named "Self")
348            // and it is OK to have Self generic param generated during lowering.
349            let param_name =
350                if rename_self && p.name == kw::SelfUpper { sym::This } else { p.name };
351
352            let param_ident = Ident::new(param_name, span);
353            let def_name = Some(param_ident.name);
354            let node_id = self.next_node_id();
355
356            let def_id = self.create_def(node_id, def_name, def_kind, span);
357
358            let kind = match p.kind {
359                GenericParamDefKind::Lifetime => {
360                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit }
361                }
362                GenericParamDefKind::Type { synthetic, .. } => {
363                    hir::GenericParamKind::Type { default: None, synthetic }
364                }
365                GenericParamDefKind::Const { .. } => {
366                    let hir_id = self.next_id();
367                    let kind = hir::TyKind::InferDelegation(hir::InferDelegation::DefId(p.def_id));
368
369                    hir::GenericParamKind::Const {
370                        ty: self.arena.alloc(hir::Ty { kind, hir_id, span }),
371                        default: None,
372                    }
373                }
374            };
375
376            // Important: we don't use `self.next_id()` as we want to execute
377            // `lower_node_id` routine so param's id is added to `self.children`.
378            let hir_id = self.lower_node_id(node_id);
379
380            hir::GenericParam {
381                hir_id,
382                colon_span: Some(span),
383                def_id,
384                kind,
385                name: hir::ParamName::Plain(param_ident),
386                pure_wrt_drop: p.pure_wrt_drop,
387                source: hir::GenericParamSource::Generics,
388                span,
389            }
390        }));
391
392        // HACK: for now we generate predicates such that all lifetimes are early bound,
393        // we can not not generate early-bound lifetimes, but we can't know which of them
394        // are late-bound at this level of compilation.
395        let predicates =
396            self.arena.alloc_from_iter(params.iter().filter_map(|p| {
397                p.is_lifetime().then(|| self.generate_lifetime_predicate(p, span))
398            }));
399
400        self.arena.alloc(hir::Generics {
401            params,
402            predicates,
403            has_where_clause_predicates: false,
404            where_clause_span: span,
405            span,
406        })
407    }
408
409    fn generate_lifetime_predicate(
410        &mut self,
411        p: &hir::GenericParam<'hir>,
412        span: Span,
413    ) -> hir::WherePredicate<'hir> {
414        let create_lifetime = |this: &mut Self| -> &'hir hir::Lifetime {
415            this.arena.alloc(hir::Lifetime {
416                hir_id: this.next_id(),
417                ident: p.name.ident(),
418                kind: hir::LifetimeKind::Param(p.def_id),
419                source: hir::LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
420                syntax: hir::LifetimeSyntax::ExplicitBound,
421            })
422        };
423
424        hir::WherePredicate {
425            hir_id: self.next_id(),
426            span,
427            kind: self.arena.alloc(hir::WherePredicateKind::RegionPredicate(
428                hir::WhereRegionPredicate {
429                    in_where_clause: true,
430                    lifetime: create_lifetime(self),
431                    bounds: self
432                        .arena
433                        .alloc_slice(&[hir::GenericBound::Outlives(create_lifetime(self))]),
434                },
435            )),
436        }
437    }
438
439    fn create_generics_args_from_params(
440        &mut self,
441        params: &[hir::GenericParam<'hir>],
442        add_lifetimes: bool,
443        span: Span,
444    ) -> &'hir hir::GenericArgs<'hir> {
445        self.arena.alloc(hir::GenericArgs {
446            args: self.arena.alloc_from_iter(params.iter().filter_map(|p| {
447                // Skip self generic arg, we do not need to propagate it.
448                if p.name.ident().name == kw::SelfUpper || p.is_impl_trait() {
449                    return None;
450                }
451
452                let create_path = |this: &mut Self| {
453                    let res = Res::Def(
454                        match p.kind {
455                            hir::GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
456                            hir::GenericParamKind::Type { .. } => DefKind::TyParam,
457                            hir::GenericParamKind::Const { .. } => DefKind::ConstParam,
458                        },
459                        p.def_id.to_def_id(),
460                    );
461
462                    hir::QPath::Resolved(
463                        None,
464                        self.arena.alloc(hir::Path {
465                            segments: this.arena.alloc_slice(&[hir::PathSegment {
466                                args: None,
467                                hir_id: this.next_id(),
468                                ident: p.name.ident(),
469                                infer_args: false,
470                                res,
471                            }]),
472                            res,
473                            span: p.span,
474                        }),
475                    )
476                };
477
478                match p.kind {
479                    hir::GenericParamKind::Lifetime { .. } => match add_lifetimes {
480                        true => Some(hir::GenericArg::Lifetime(self.arena.alloc(hir::Lifetime {
481                            hir_id: self.next_id(),
482                            ident: p.name.ident(),
483                            kind: hir::LifetimeKind::Param(p.def_id),
484                            source: hir::LifetimeSource::Path {
485                                angle_brackets: hir::AngleBrackets::Full,
486                            },
487                            syntax: hir::LifetimeSyntax::ExplicitBound,
488                        }))),
489                        false => None,
490                    },
491                    hir::GenericParamKind::Type { .. } => {
492                        Some(hir::GenericArg::Type(self.arena.alloc(hir::Ty {
493                            hir_id: self.next_id(),
494                            span: p.span,
495                            kind: hir::TyKind::Path(create_path(self)),
496                        })))
497                    }
498                    hir::GenericParamKind::Const { .. } => {
499                        Some(hir::GenericArg::Const(self.arena.alloc(hir::ConstArg {
500                            hir_id: self.next_id(),
501                            kind: hir::ConstArgKind::Path(create_path(self)),
502                            span: p.span,
503                        })))
504                    }
505                }
506            })),
507            constraints: &[],
508            parenthesized: hir::GenericArgsParentheses::No,
509            span_ext: span,
510        })
511    }
512}