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(&self) -> impl Iterator<Item = hir::GenericParam<'hir>> {
175        let parent = self.parent.generics.hir_generics_or_empty().params;
176        let child = self.child.generics.hir_generics_or_empty().params;
177
178        // Order generics, first we have parent and child lifetimes,
179        // then parent and child types and consts.
180        // `generics_of` in `rustc_hir_analysis` will order them anyway,
181        // however we want the order to be consistent in HIR too.
182        parent
183            .iter()
184            .filter(|p| p.is_lifetime())
185            .chain(child.iter().filter(|p| p.is_lifetime()))
186            .chain(parent.iter().filter(|p| !p.is_lifetime()))
187            .chain(child.iter().filter(|p| !p.is_lifetime()))
188            .copied()
189    }
190
191    /// As we add hack predicates(`'a: 'a`) for all lifetimes (see `uplift_delegation_generic_params`
192    /// and `generate_lifetime_predicate` functions) we need to add them to delegation generics.
193    /// Those predicates will not affect resulting predicate inheritance and folding
194    /// in `rustc_hir_analysis`, as we inherit all predicates from delegation signature.
195    pub(super) fn all_predicates(&self) -> impl Iterator<Item = hir::WherePredicate<'hir>> {
196        self.parent
197            .generics
198            .hir_generics_or_empty()
199            .predicates
200            .into_iter()
201            .chain(self.child.generics.hir_generics_or_empty().predicates)
202            .copied()
203    }
204}
205
206impl<'hir> LoweringContext<'_, 'hir> {
207    pub(super) fn uplift_delegation_generics(
208        &mut self,
209        delegation: &Delegation,
210        sig_id: DefId,
211        is_method: bool,
212    ) -> GenericsGenerationResults<'hir> {
213        let delegation_parent_kind = self.tcx.def_kind(self.tcx.local_parent(self.owner.def_id));
214
215        let segments = &delegation.path.segments;
216        let len = segments.len();
217        let child_user_specified = segments[len - 1].args.is_some();
218
219        let sig_params = &self.tcx.generics_of(sig_id).own_params[..];
220
221        // If we are in trait impl always generate function whose generics matches
222        // those that are defined in trait.
223        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 }) {
224            // Considering parent generics, during signature inheritance
225            // we will take those args that are in trait impl header trait ref.
226            let parent = DelegationGenerics::trait_impl(&[], true, GenericsPosition::Parent);
227            let parent = GenericsGenerationResult::new(parent);
228
229            let child = DelegationGenerics::trait_impl(
230                sig_params,
231                child_user_specified,
232                GenericsPosition::Child,
233            );
234
235            let child = GenericsGenerationResult::new(child);
236
237            return GenericsGenerationResults {
238                parent,
239                child,
240                self_ty_id: None,
241                propagate_self_ty: false,
242            };
243        }
244
245        let delegation_in_free_ctx =
246            !#[allow(non_exhaustive_omitted_patterns)] match delegation_parent_kind {
    DefKind::Trait | DefKind::Impl { .. } => true,
    _ => false,
}matches!(delegation_parent_kind, DefKind::Trait | DefKind::Impl { .. });
247
248        let sig_parent = self.tcx.parent(sig_id);
249        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);
250        let free_to_trait_delegation = delegation_in_free_ctx && sig_in_trait;
251        let generate_self = free_to_trait_delegation && is_method && delegation.qself.is_none();
252
253        let can_add_generics_to_parent = len >= 2
254            && self.get_resolution_id(segments[len - 2].id).is_some_and(|def_id| {
255                #[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)
256            });
257
258        let parent_generics = if can_add_generics_to_parent {
259            let sig_parent_params = &self.tcx.generics_of(sig_parent).own_params[..];
260
261            if segments[len - 2].args.is_some() {
262                if generate_self {
263                    // Take only first Self parameter, it is trait so Self must be present.
264                    DelegationGenerics {
265                        kind: DelegationGenericsKind::SelfAndUserSpecified,
266                        generics: &sig_parent_params[..1],
267                        pos: GenericsPosition::Parent,
268                    }
269                } else {
270                    DelegationGenerics::user_specified(&[], GenericsPosition::Parent)
271                }
272            } else {
273                let skip_self = usize::from(!generate_self);
274                DelegationGenerics::default(
275                    &sig_parent_params[skip_self..],
276                    GenericsPosition::Parent,
277                )
278            }
279        } else {
280            DelegationGenerics::default(&[], GenericsPosition::Parent)
281        };
282
283        let child_generics = if child_user_specified {
284            let synth_params_index =
285                sig_params.iter().position(|p| p.kind.is_synthetic()).unwrap_or(sig_params.len());
286
287            DelegationGenerics::user_specified(
288                &sig_params[synth_params_index..],
289                GenericsPosition::Child,
290            )
291        } else {
292            DelegationGenerics::default(sig_params, GenericsPosition::Child)
293        };
294
295        GenericsGenerationResults {
296            parent: GenericsGenerationResult::new(parent_generics),
297            child: GenericsGenerationResult::new(child_generics),
298            self_ty_id: None,
299            propagate_self_ty: free_to_trait_delegation && !generate_self,
300        }
301    }
302
303    fn uplift_delegation_generic_params(
304        &mut self,
305        span: Span,
306        params: &'hir [ty::GenericParamDef],
307        rename_self: bool,
308    ) -> &'hir hir::Generics<'hir> {
309        let params = self.arena.alloc_from_iter(params.iter().map(|p| {
310            let def_kind = match p.kind {
311                GenericParamDefKind::Lifetime => DefKind::LifetimeParam,
312                GenericParamDefKind::Type { .. } => DefKind::TyParam,
313                GenericParamDefKind::Const { .. } => DefKind::ConstParam,
314            };
315
316            // Rename Self generic param to This so it is properly propagated.
317            // If the user will create a function `fn foo<Self>() {}` with generic
318            // param "Self" then it will not be generated in HIR, the same thing
319            // applies to traits, `trait Trait<Self> {}` will be represented as
320            // `trait Trait {}` in HIR and "unexpected keyword `Self` in generic parameters"
321            // error will be emitted.
322            // Note that we do not rename `Self` to `This` after non-recursive reuse
323            // from Trait, in this case the `Self` should not be propagated
324            // (we rely that implicit `Self` generic param of a trait is named "Self")
325            // and it is OK to have Self generic param generated during lowering.
326            let param_name =
327                if rename_self && p.name == kw::SelfUpper { sym::This } else { p.name };
328
329            let param_ident = Ident::new(param_name, span);
330            let def_name = Some(param_ident.name);
331            let node_id = self.next_node_id();
332
333            let def_id = self.create_def(node_id, def_name, def_kind, span);
334
335            let kind = match p.kind {
336                GenericParamDefKind::Lifetime => {
337                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit }
338                }
339                GenericParamDefKind::Type { synthetic, .. } => {
340                    hir::GenericParamKind::Type { default: None, synthetic }
341                }
342                GenericParamDefKind::Const { .. } => {
343                    let hir_id = self.next_id();
344                    let kind = hir::TyKind::InferDelegation(hir::InferDelegation::DefId(p.def_id));
345
346                    hir::GenericParamKind::Const {
347                        ty: self.arena.alloc(hir::Ty { kind, hir_id, span }),
348                        default: None,
349                    }
350                }
351            };
352
353            // Important: we don't use `self.next_id()` as we want to execute
354            // `lower_node_id` routine so param's id is added to `self.children`.
355            let hir_id = self.lower_node_id(node_id);
356
357            hir::GenericParam {
358                hir_id,
359                colon_span: Some(span),
360                def_id,
361                kind,
362                name: hir::ParamName::Plain(param_ident),
363                pure_wrt_drop: p.pure_wrt_drop,
364                source: hir::GenericParamSource::Generics,
365                span,
366            }
367        }));
368
369        // HACK: for now we generate predicates such that all lifetimes are early bound,
370        // we can not not generate early-bound lifetimes, but we can't know which of them
371        // are late-bound at this level of compilation.
372        let predicates =
373            self.arena.alloc_from_iter(params.iter().filter_map(|p| {
374                p.is_lifetime().then(|| self.generate_lifetime_predicate(p, span))
375            }));
376
377        self.arena.alloc(hir::Generics {
378            params,
379            predicates,
380            has_where_clause_predicates: false,
381            where_clause_span: span,
382            span,
383        })
384    }
385
386    fn generate_lifetime_predicate(
387        &mut self,
388        p: &hir::GenericParam<'hir>,
389        span: Span,
390    ) -> hir::WherePredicate<'hir> {
391        let create_lifetime = |this: &mut Self| -> &'hir hir::Lifetime {
392            this.arena.alloc(hir::Lifetime {
393                hir_id: this.next_id(),
394                ident: p.name.ident(),
395                kind: hir::LifetimeKind::Param(p.def_id),
396                source: hir::LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
397                syntax: hir::LifetimeSyntax::ExplicitBound,
398            })
399        };
400
401        hir::WherePredicate {
402            hir_id: self.next_id(),
403            span,
404            kind: self.arena.alloc(hir::WherePredicateKind::RegionPredicate(
405                hir::WhereRegionPredicate {
406                    in_where_clause: true,
407                    lifetime: create_lifetime(self),
408                    bounds: self
409                        .arena
410                        .alloc_slice(&[hir::GenericBound::Outlives(create_lifetime(self))]),
411                },
412            )),
413        }
414    }
415
416    fn create_generics_args_from_params(
417        &mut self,
418        params: &[hir::GenericParam<'hir>],
419        add_lifetimes: bool,
420        span: Span,
421    ) -> &'hir hir::GenericArgs<'hir> {
422        self.arena.alloc(hir::GenericArgs {
423            args: self.arena.alloc_from_iter(params.iter().filter_map(|p| {
424                // Skip self generic arg, we do not need to propagate it.
425                if p.name.ident().name == kw::SelfUpper || p.is_impl_trait() {
426                    return None;
427                }
428
429                let create_path = |this: &mut Self| {
430                    let res = Res::Def(
431                        match p.kind {
432                            hir::GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
433                            hir::GenericParamKind::Type { .. } => DefKind::TyParam,
434                            hir::GenericParamKind::Const { .. } => DefKind::ConstParam,
435                        },
436                        p.def_id.to_def_id(),
437                    );
438
439                    hir::QPath::Resolved(
440                        None,
441                        self.arena.alloc(hir::Path {
442                            segments: this.arena.alloc_slice(&[hir::PathSegment {
443                                args: None,
444                                hir_id: this.next_id(),
445                                ident: p.name.ident(),
446                                infer_args: false,
447                                res,
448                            }]),
449                            res,
450                            span: p.span,
451                        }),
452                    )
453                };
454
455                match p.kind {
456                    hir::GenericParamKind::Lifetime { .. } => match add_lifetimes {
457                        true => Some(hir::GenericArg::Lifetime(self.arena.alloc(hir::Lifetime {
458                            hir_id: self.next_id(),
459                            ident: p.name.ident(),
460                            kind: hir::LifetimeKind::Param(p.def_id),
461                            source: hir::LifetimeSource::Path {
462                                angle_brackets: hir::AngleBrackets::Full,
463                            },
464                            syntax: hir::LifetimeSyntax::ExplicitBound,
465                        }))),
466                        false => None,
467                    },
468                    hir::GenericParamKind::Type { .. } => {
469                        Some(hir::GenericArg::Type(self.arena.alloc(hir::Ty {
470                            hir_id: self.next_id(),
471                            span: p.span,
472                            kind: hir::TyKind::Path(create_path(self)),
473                        })))
474                    }
475                    hir::GenericParamKind::Const { .. } => {
476                        Some(hir::GenericArg::Const(self.arena.alloc(hir::ConstArg {
477                            hir_id: self.next_id(),
478                            kind: hir::ConstArgKind::Path(create_path(self)),
479                            span: p.span,
480                        })))
481                    }
482                }
483            })),
484            constraints: &[],
485            parenthesized: hir::GenericArgsParentheses::No,
486            span_ext: span,
487        })
488    }
489}