Skip to main content

charon_driver/translate/
translate_generics.rs

1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2use std::fmt::Debug;
3use std::mem;
4
5use crate::frontend as front;
6use crate::frontend::{BaseState, SInto, Symbol};
7use rustc_middle::ty;
8
9use super::translate_ctx::ItemTransCtx;
10use charon_lib::ast::*;
11use charon_lib::utils::CycleDetector;
12
13/// A level of binding for type-level variables. Each item has a top-level binding level
14/// corresponding to the parameters and clauses to the items. We may then encounter inner binding
15/// levels in the following cases:
16/// - `for<..>` binders in predicates;
17/// - `fn<..>` function pointer types;
18/// - `dyn Trait` types, represented as `dyn<T: Trait>`;
19/// - types in a trait declaration or implementation block;
20/// - methods in a trait declaration or implementation block.
21///
22/// At each level, we store two things: a `GenericParams` that contains the parameters bound at
23/// this level, and various maps from the rustc-internal indices to our indices.
24#[derive(Debug, Default)]
25pub(crate) struct BindingLevel<'tcx> {
26    /// The parameters and predicates bound at this level.
27    pub params: GenericParams,
28    /// Whether this binding level exists in the frontend's De Bruijn indices. `dyn Trait` introduces an
29    /// existential binder in Charon that has no corresponding binder in rustc/frontend.
30    pub counts_for_de_bruijn: bool,
31
32    /// Rust makes the distinction between early and late-bound region parameters. We do not make
33    /// this distinction, and merge early and late bound regions. For details, see:
34    /// <https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/>
35    /// <https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/>
36    ///
37    /// The map of early regions bound at this binder.
38    pub early_region_vars: HashMap<front::EarlyParamRegion, RegionId>,
39    /// Extra early regions recovered by unerasing some regions that rustc keeps erased in args.
40    /// Relevant for closures and inline consts. The frontend represents these regions with placeholder
41    /// regions.
42    pub extra_early_region_vars: HashMap<front::PlaceholderRegion<'tcx>, RegionId>,
43    /// The map of named `ReLateParam` regions bound at this binder.
44    pub late_named_region_vars: HashMap<front::DefId, RegionId>,
45    /// The map of anon `ReLateParam` regions bound at this binder, indexed by the scope `DefId`
46    /// and variable index.
47    pub late_anon_region_vars: HashMap<front::DefId, Vec<RegionId>>,
48    /// The map of `ReBound` regions bound at this binder, indexed by their bound variable index.
49    pub bound_region_vars: Vec<RegionId>,
50    /// RPITIT can cause region names to be reused. To avoid clashes in our output, we rename
51    /// duplicate names.
52    pub used_region_names: HashSet<Symbol>,
53
54    /// The map from rust type variable indices to translated type variable indices. `None` marks
55    /// inference-only parameters, which the frontend should normally never give us.
56    pub type_vars: HashMap<u32, Option<TypeVarId>>,
57    /// The map from rust const generic variables to translated const generic variable indices.
58    pub const_generic_vars: HashMap<u32, ConstGenericVarId>,
59    /// The map from trait predicates to the translated trait clause indices, and the number of
60    /// bound higher-kinded regions.
61    pub trait_preds: HashMap<front::GenericPredicateId, (TraitClauseId, usize)>,
62
63    /// Cache the translation of types. This harnesses the deduplication of `Ty` that the frontend does.
64    // Important: we can't reuse type caches from earlier binders as the new binder may change what
65    // a given variable resolves to.
66    pub type_trans_cache: HashMap<front::Ty<'tcx>, Ty>,
67}
68
69/// Small helper: we ignore some region names (when they are equal to "'_")
70fn translate_region_name(s: front::Symbol) -> Option<String> {
71    let s = s.to_string();
72    if s == "'_" { None } else { Some(s) }
73}
74
75fn translate_variance(variance: Option<&front::Variance>) -> Variance {
76    match variance {
77        Some(front::Variance::Covariant) => Variance::Covariant,
78        Some(front::Variance::Invariant) => Variance::Invariant,
79        Some(front::Variance::Contravariant) => Variance::Contravariant,
80        Some(front::Variance::Bivariant) => Variance::Bivariant,
81        None => Variance::Unknown,
82    }
83}
84
85impl<'tcx> BindingLevel<'tcx> {
86    pub(crate) fn new() -> Self {
87        Self {
88            counts_for_de_bruijn: true,
89            ..Default::default()
90        }
91    }
92
93    pub(crate) fn new_dyn() -> Self {
94        let mut level = Self::new();
95        level.counts_for_de_bruijn = false;
96        level
97    }
98
99    /// Important: we must push all the early-bound regions before pushing any other region.
100    pub(crate) fn push_early_region(
101        &mut self,
102        region: front::EarlyParamRegion,
103        def_id: front::DefId,
104        variance: Variance,
105        mutability: LifetimeMutability,
106    ) -> RegionId {
107        let name = if self.used_region_names.insert(region.name) {
108            translate_region_name(region.name)
109        } else {
110            None
111        };
112        // Check that there are no late-bound regions
113        assert!(
114            self.bound_region_vars.is_empty(),
115            "Early regions must be translated before late ones"
116        );
117        let rid = self.params.regions.push_with(|index| RegionParam {
118            index,
119            name,
120            variance,
121            mutability,
122            late_bound: false,
123        });
124        self.early_region_vars.insert(region, rid);
125        // FIXME: is that used?
126        self.late_named_region_vars.insert(def_id, rid);
127        rid
128    }
129
130    /// Important: we must push all the early-bound regions before pushing any other region.
131    pub(crate) fn push_bound_region(
132        &mut self,
133        region: front::BoundRegionKind,
134        variance: Variance,
135        late_param_def_id: Option<&front::DefId>,
136    ) -> RegionId {
137        use crate::frontend::BoundRegionKind::*;
138        let (name, def_id) = match region {
139            Anon => (None, None),
140            NamedForPrinting(symbol) => (translate_region_name(symbol), None),
141            Named(def_id, symbol) => (translate_region_name(symbol), Some(def_id)),
142            ClosureEnv => (Some("env".to_owned()), None),
143        };
144        let rid = self
145            .params
146            .regions
147            .push_with(|index| RegionParam::new(index, name, variance));
148        if let Some(def_id) = def_id {
149            self.late_named_region_vars.insert(def_id, rid);
150        }
151        if let Some(def_id) = late_param_def_id {
152            self.late_anon_region_vars
153                .entry(def_id.clone())
154                .or_default()
155                .push(rid);
156        } else {
157            self.bound_region_vars.push(rid);
158        }
159        rid
160    }
161
162    /// Extra lifetimes unerased from the closure arguments. The frontend represents them with placeholder
163    /// regions; they are parameters of the closure struct.
164    pub fn push_unerased_region(&mut self, region: front::PlaceholderRegion<'tcx>) {
165        let region_id = self
166            .params
167            .regions
168            .push_with(|index| RegionParam::new(index, None, Variance::Unknown));
169        self.extra_early_region_vars.insert(region, region_id);
170    }
171
172    pub(crate) fn push_type_var(
173        &mut self,
174        rid: u32,
175        name: front::Symbol,
176        variance: Variance,
177    ) -> TypeVarId {
178        // Type vars comping from `impl Trait` arguments have as their name the whole `impl Trait`
179        // expression. We turn it into an identifier.
180        let mut name = name.to_string();
181        if name
182            .chars()
183            .any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
184        {
185            name = format!("T{rid}")
186        }
187        let var_id = self.params.types.push_with(|index| TypeParam {
188            index,
189            name,
190            variance,
191        });
192        self.type_vars.insert(rid, Some(var_id));
193        var_id
194    }
195
196    pub(crate) fn push_const_generic_var(&mut self, rid: u32, ty: Ty, name: front::Symbol) {
197        let var_id = self
198            .params
199            .const_generics
200            .push_with(|index| ConstGenericParam {
201                index,
202                name: name.to_string(),
203                ty,
204            });
205        self.const_generic_vars.insert(rid, var_id);
206    }
207
208    /// Add the binder's regions to this binding level. If `late_param_def_id` is `Some`, register
209    /// them for `ReLateParam` lookup; otherwise, register them as this level's `ReBound`
210    /// variables.
211    pub(crate) fn push_bound_params(
212        &mut self,
213        binder: &front::Binder<()>,
214        late_param_def_id: Option<&front::DefId>,
215    ) {
216        if late_param_def_id.is_none() {
217            assert!(
218                self.bound_region_vars.is_empty(),
219                "Trying to use two binders at the same binding level"
220            );
221        }
222        use crate::frontend::BoundVariableKind::*;
223        for p in &binder.bound_vars {
224            match p {
225                Region(region, variance) => {
226                    let variance = translate_variance(variance.as_ref());
227                    self.push_bound_region(region.clone(), variance, late_param_def_id);
228                }
229                Ty(_) => {
230                    panic!("Unexpected locally bound type variable");
231                }
232                Const => {
233                    panic!("Unexpected locally bound const generic variable");
234                }
235            }
236        }
237    }
238}
239
240impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
241    /// Get the only binding level. Panics if there are other binding levels.
242    pub(crate) fn the_only_binder(&self) -> &BindingLevel<'tcx> {
243        assert_eq!(self.binding_levels.len(), 1);
244        self.innermost_binder()
245    }
246    /// Get the only binding level. Panics if there are other binding levels.
247    pub(crate) fn the_only_binder_mut(&mut self) -> &mut BindingLevel<'tcx> {
248        assert_eq!(self.binding_levels.len(), 1);
249        self.innermost_binder_mut()
250    }
251
252    pub(crate) fn outermost_binder(&self) -> &BindingLevel<'tcx> {
253        self.binding_levels.outermost()
254    }
255    pub(crate) fn outermost_binder_mut(&mut self) -> &mut BindingLevel<'tcx> {
256        self.binding_levels.outermost_mut()
257    }
258    pub(crate) fn innermost_binder(&self) -> &BindingLevel<'tcx> {
259        self.binding_levels.innermost()
260    }
261    pub(crate) fn innermost_binder_mut(&mut self) -> &mut BindingLevel<'tcx> {
262        self.binding_levels.innermost_mut()
263    }
264
265    pub(crate) fn outermost_generics(&self) -> &GenericParams {
266        &self.outermost_binder().params
267    }
268    #[expect(dead_code)]
269    pub(crate) fn outermost_generics_mut(&mut self) -> &mut GenericParams {
270        &mut self.outermost_binder_mut().params
271    }
272    #[expect(dead_code)]
273    pub(crate) fn innermost_generics(&self) -> &GenericParams {
274        &self.innermost_binder().params
275    }
276    pub(crate) fn innermost_generics_mut(&mut self) -> &mut GenericParams {
277        &mut self.innermost_binder_mut().params
278    }
279
280    pub(crate) fn lookup_bound_region(
281        &mut self,
282        span: Span,
283        frontend_dbid: front::DebruijnIndex,
284        var: front::BoundVar,
285    ) -> Result<RegionDbVar, Error> {
286        if let Some((charon_dbid, level)) = self
287            .binding_levels
288            .iter_enumerated()
289            .filter(|(_, l)| l.counts_for_de_bruijn)
290            .nth(frontend_dbid.as_usize())
291            && let Some(rid) = level.bound_region_vars.get(var.as_usize())
292        {
293            Ok(DeBruijnVar::bound(charon_dbid, *rid))
294        } else {
295            raise_error!(
296                self,
297                span,
298                "Unexpected error: could not find region '{}_{}",
299                frontend_dbid.as_usize(),
300                var.as_usize()
301            )
302        }
303    }
304
305    pub(crate) fn lookup_param<T: TyVisitable>(
306        &mut self,
307        span: Span,
308        f: impl for<'a> Fn(&'a BindingLevel) -> Option<T>,
309        mk_err: impl FnOnce() -> String,
310    ) -> Result<T, Error> {
311        for (depth, bl) in self.binding_levels.iter_enumerated() {
312            if let Some(x) = f(bl) {
313                return Ok(x.move_under_binders(depth));
314            }
315        }
316        let err = mk_err();
317        raise_error!(self, span, "Unexpected error: could not find {}", err)
318    }
319
320    pub(crate) fn lookup_early_region(
321        &mut self,
322        span: Span,
323        region: &front::EarlyParamRegion,
324    ) -> Result<RegionDbVar, Error> {
325        self.lookup_param(
326            span,
327            |bl| {
328                bl.early_region_vars
329                    .get(region)
330                    .copied()
331                    .map(DeBruijnVar::new_at_zero)
332            },
333            || format!("the region variable {region:?}"),
334        )
335    }
336
337    pub(crate) fn lookup_late_param_region(
338        &mut self,
339        span: Span,
340        region: &ty::LateParamRegion<'tcx>,
341    ) -> Result<RegionDbVar, Error> {
342        use ty::LateParamRegionKind::*;
343        match &region.kind {
344            Anon(index) | NamedAnon(index, _) => {
345                let scope: front::DefId = region.scope.sinto(&self.frontend_state);
346                let Some((dbid, regions)) =
347                    self.binding_levels
348                        .iter_enumerated()
349                        .find_map(|(dbid, binder)| {
350                            Some((dbid, binder.late_anon_region_vars.get(&scope)?))
351                        })
352                else {
353                    raise_error!(
354                        self,
355                        span,
356                        "Unexpected error: could not find the binder for late-bound region {region:?}"
357                    )
358                };
359                let Some(region_id) = regions.get(*index as usize).copied() else {
360                    raise_error!(
361                        self,
362                        span,
363                        "Unexpected error: could not find the late-bound region variable {region:?}"
364                    )
365                };
366                Ok(DeBruijnVar::bound(dbid, region_id))
367            }
368            Named(def_id) => {
369                let def_id: front::DefId = def_id.sinto(&self.frontend_state);
370                self.lookup_param(
371                    span,
372                    |bl| {
373                        bl.late_named_region_vars
374                            .get(&def_id)
375                            .copied()
376                            .map(DeBruijnVar::new_at_zero)
377                    },
378                    || format!("the late-bound region variable {region:?}"),
379                )
380            }
381            ClosureEnv => {
382                raise_error!(self, span, "Unexpected late-bound region: {region:?}")
383            }
384        }
385    }
386
387    pub(crate) fn lookup_type_var(
388        &mut self,
389        span: Span,
390        param: &front::ParamTy,
391    ) -> Result<TypeDbVar, Error> {
392        let var = self.lookup_param(
393            span,
394            |bl| {
395                let var = *bl.type_vars.get(&param.index)?;
396                Some(var.map(DeBruijnVar::new_at_zero))
397            },
398            || format!("the type variable {}", param.name),
399        )?;
400        if let Some(var) = var {
401            Ok(var)
402        } else {
403            raise_error!(
404                self,
405                span,
406                "Inference parameter {param:?} should have been replaced \
407                with its known type before translation"
408            );
409        }
410    }
411
412    pub(crate) fn lookup_const_generic_var(
413        &mut self,
414        span: Span,
415        param: &front::ParamConst,
416    ) -> Result<ConstGenericDbVar, Error> {
417        self.lookup_param(
418            span,
419            |bl| {
420                bl.const_generic_vars
421                    .get(&param.index)
422                    .copied()
423                    .map(DeBruijnVar::new_at_zero)
424            },
425            || format!("the const generic variable {}", param.name),
426        )
427    }
428
429    pub(crate) fn lookup_clause_var(
430        &mut self,
431        span: Span,
432        id: &front::GenericPredicateId,
433    ) -> Result<(ClauseDbVar, usize), Error> {
434        self.lookup_param(
435            span,
436            |bl| {
437                let (id, regions) = bl.trait_preds.get(id).copied()?;
438                Some((DeBruijnVar::new_at_zero(id), regions))
439            },
440            || format!("the trait clause variable {id:?}"),
441        )
442    }
443
444    pub(crate) fn self_borrow_generic_args(&mut self) -> GenericArgs {
445        let mut generics = GenericArgs::empty();
446        generics.regions.push(self.translate_erased_region());
447        generics
448    }
449
450    pub(crate) fn self_borrow_params() -> GenericParams {
451        let mut params = GenericParams::empty();
452        params
453            .regions
454            .push_with(|index| RegionParam::new(index, None, Variance::Covariant));
455        params
456    }
457
458    pub(crate) fn push_generic_params(
459        &mut self,
460        generics: &front::TyGenerics<'tcx>,
461    ) -> Result<(), Error> {
462        for param in &generics.params {
463            self.push_generic_param(param)?;
464        }
465        Ok(())
466    }
467
468    pub(crate) fn push_generic_param(
469        &mut self,
470        param: &front::GenericParamDef<'tcx>,
471    ) -> Result<(), Error> {
472        let variance = translate_variance(param.variance.as_ref());
473        match &param.kind {
474            front::GenericParamDefKind::Lifetime => {
475                let region = front::EarlyParamRegion {
476                    index: param.index,
477                    name: param.name,
478                };
479                let mutability = self
480                    .t_ctx
481                    .lt_mutability_computer
482                    .compute_lifetime_mutability(
483                        &self.frontend_state,
484                        self.item_src.def_id(),
485                        param.index,
486                    );
487                let _ = self.innermost_binder_mut().push_early_region(
488                    region,
489                    param.def_id.clone(),
490                    variance,
491                    mutability,
492                );
493            }
494            front::GenericParamDefKind::Type {
495                inference_value: Some(_),
496                ..
497            } => {
498                // Inference-only type parameter, as used in closures and inline consts. We make
499                // sure to get rid of them in the frontend, and error if found in Charon.
500                self.innermost_binder_mut()
501                    .type_vars
502                    .insert(param.index, None);
503            }
504            front::GenericParamDefKind::Type {
505                inference_value: None,
506                ..
507            } => {
508                let _ =
509                    self.innermost_binder_mut()
510                        .push_type_var(param.index, param.name, variance);
511            }
512            front::GenericParamDefKind::Const { ty, .. } => {
513                let span = self.def_span(&param.def_id);
514                // The type should be primitive, meaning it shouldn't contain variables,
515                // non-primitive adts, etc. As a result, we can use an empty context.
516                let ty = self.translate_ty(span, ty)?;
517                self.innermost_binder_mut()
518                    .push_const_generic_var(param.index, ty, param.name);
519            }
520        }
521
522        Ok(())
523    }
524
525    /// Add the generics and predicates of this item and its parents to the current context.
526    #[tracing::instrument(skip(self, def))]
527    fn push_generics_for_def(
528        &mut self,
529        def: &front::FullDef<'tcx>,
530        is_current_item: bool,
531    ) -> Result<(), Error> {
532        if let Some(param_env) = def.param_env() {
533            // Add generics from the parent item, recursively.
534            if let Some(parent_item) = &param_env.soft_parent {
535                let parent_def = self.frontend_def(parent_item)?;
536                self.push_generics_for_def(&parent_def, false)?;
537            }
538            let origin = Self::predicate_origin_for_def(def);
539            self.push_param_env_without_parents(param_env, origin, is_current_item)?;
540        }
541        Ok(())
542    }
543
544    fn predicate_origin_for_def(def: &front::FullDef<'tcx>) -> PredicateOrigin {
545        use crate::frontend::FullDefKind;
546        match &def.kind {
547            FullDefKind::Adt(_)
548            | FullDefKind::Variant(_)
549            | FullDefKind::TyAlias(_)
550            | FullDefKind::AssocTy(_) => PredicateOrigin::WhereClauseOnType,
551            FullDefKind::Fn(_)
552            | FullDefKind::FnPtr(_)
553            | FullDefKind::AssocFn(_)
554            | FullDefKind::Ctor(_)
555            | FullDefKind::Closure(_)
556            | FullDefKind::Const(_)
557            | FullDefKind::AssocConst(_)
558            | FullDefKind::Static(_) => PredicateOrigin::WhereClauseOnFn,
559            FullDefKind::TraitImpl(_) | FullDefKind::InherentImpl(_) => {
560                PredicateOrigin::WhereClauseOnImpl
561            }
562            FullDefKind::Trait(_) | FullDefKind::TraitAlias(_) => {
563                PredicateOrigin::WhereClauseOnTrait
564            }
565            _ => panic!("Unexpected def: {:?}", def.def_id().kind),
566        }
567    }
568
569    fn push_param_env_without_parents(
570        &mut self,
571        param_env: &front::ParamEnv<'tcx>,
572        origin: PredicateOrigin,
573        is_current_item: bool,
574    ) -> Result<(), Error> {
575        self.push_generic_params(&param_env.generics)?;
576        for region in &param_env.extra_early_regions {
577            self.innermost_binder_mut().push_unerased_region(*region);
578        }
579        self.register_predicates(&param_env.predicates, origin)?;
580        if let Some(late_bound) = &param_env.late_bound {
581            let level = self.innermost_binder_mut();
582            level.push_bound_params(&late_bound.binder, Some(&late_bound.def_id));
583            if is_current_item {
584                // Make the variable available for lookup using debruijn indices too, which we use
585                // when translating signatures.
586                level.bound_region_vars = level
587                    .late_anon_region_vars
588                    .get(&late_bound.def_id)
589                    .cloned()
590                    .unwrap_or_default();
591                // Mark these as the late bound parameters of this item.
592                for region in &level.bound_region_vars {
593                    level.params.regions[*region].late_bound = true;
594                }
595            }
596        }
597        Ok(())
598    }
599
600    /// Translate the generics and predicates of this item and its parents. This adds generic
601    /// parameters and predicates to the current environment (as a binder in
602    /// `self.binding_levels`). The constructed `GenericParams` can be recovered at the end using
603    /// `self.into_generics()` and stored in the translated item.
604    pub fn translate_item_generics(
605        &mut self,
606        _span: Span,
607        def: &front::FullDef<'tcx>,
608    ) -> Result<(), Error> {
609        assert!(self.binding_levels.is_empty());
610        self.binding_levels.push(BindingLevel::new());
611        self.push_generics_for_def(def, true)?;
612
613        self.innermost_binder_mut().params.check_consistency();
614        Ok(())
615    }
616
617    /// Push a new binding level, run the provided function inside it, then return the bound value.
618    pub(crate) fn inside_binder<F, U>(&mut self, kind: BinderKind, f: F) -> Result<Binder<U>, Error>
619    where
620        F: FnOnce(&mut Self) -> Result<U, Error>,
621    {
622        self.binding_levels.push(BindingLevel::new());
623
624        // Call the continuation. Important: do not short-circuit on error here.
625        let res = f(self);
626
627        // Reset
628        let params = self.binding_levels.pop().unwrap().params;
629
630        // Return
631        res.map(|skip_binder| Binder {
632            kind,
633            params,
634            skip_binder,
635        })
636    }
637
638    /// Push a new binding level with the given generics, then return the bound value.
639    pub(crate) fn inside_item_binder<F, U>(
640        &mut self,
641        kind: BinderKind,
642        owner: &front::DefId,
643        param_env: &front::ParamEnv<'tcx>,
644        predicate_origin: PredicateOrigin,
645        f: F,
646    ) -> Result<Binder<U>, Error>
647    where
648        F: FnOnce(&mut Self) -> Result<U, Error>,
649    {
650        let inner_frontend_state = self.t_ctx.frontend_state.clone().with_frontend_owner(owner);
651        let outer_frontend_state = mem::replace(&mut self.frontend_state, inner_frontend_state);
652        let ret = self.inside_binder(kind, |this| {
653            this.push_param_env_without_parents(param_env, predicate_origin, true)?;
654            this.innermost_binder().params.check_consistency();
655            f(this)
656        });
657        self.frontend_state = outer_frontend_state;
658        ret
659    }
660
661    /// Push a new binding level corresponding to the provided `def` for the duration of the inner
662    /// function call.
663    pub(crate) fn translate_binder_for_def<F, U>(
664        &mut self,
665        _span: Span,
666        kind: BinderKind,
667        def: &front::FullDef<'tcx>,
668        f: F,
669    ) -> Result<Binder<U>, Error>
670    where
671        F: FnOnce(&mut Self) -> Result<U, Error>,
672    {
673        let param_env = def.param_env().unwrap();
674        let origin = Self::predicate_origin_for_def(def);
675        self.inside_item_binder(kind, def.def_id(), param_env, origin, |this| f(this))
676    }
677
678    /// Push a new binding level corresponding to the provided trait item binder for the duration
679    /// of the inner function call.
680    pub(crate) fn translate_trait_item_binder<F, T, U>(
681        &mut self,
682        _span: Span,
683        kind: BinderKind,
684        binder: &front::TraitItemBinder<'tcx, T>,
685        predicate_origin: PredicateOrigin,
686        f: F,
687    ) -> Result<Binder<U>, Error>
688    where
689        F: FnOnce(&mut Self, &T) -> Result<U, Error>,
690    {
691        self.inside_item_binder(
692            kind,
693            &binder.def_id,
694            &binder.param_env,
695            predicate_origin,
696            |this| f(this, &binder.skip_binder),
697        )
698    }
699
700    /// Push a group of bound regions and call the continuation.
701    /// We use this when diving into a `for<'a>`, or inside an arrow type (because
702    /// it contains universally quantified regions).
703    pub(crate) fn translate_region_binder<F, T, U>(
704        &mut self,
705        _span: Span,
706        binder: &front::Binder<T>,
707        f: F,
708    ) -> Result<RegionBinder<U>, Error>
709    where
710        F: FnOnce(&mut Self, &T) -> Result<U, Error>,
711    {
712        let binder = self.inside_binder(BinderKind::Other, |this| {
713            this.innermost_binder_mut()
714                .push_bound_params(&binder.rebind(()), None);
715            f(this, binder.frontend_skip_binder_ref())
716        })?;
717        // Convert to a region-only binder.
718        Ok(RegionBinder {
719            regions: binder.params.regions,
720            outlives: binder.params.outlives,
721            skip_binder: binder.skip_binder,
722        })
723    }
724
725    pub(crate) fn into_generics(mut self) -> GenericParams {
726        assert!(self.binding_levels.len() == 1);
727        self.binding_levels.pop().unwrap().params
728    }
729}
730
731/// Struct to compute the "mutability" of each lifetime.
732#[derive(Default)]
733pub struct LifetimeMutabilityComputer {
734    lt_mutability: HashMap<front::DefId, CycleDetector<HashSet<u32>>>,
735}
736
737impl LifetimeMutabilityComputer {
738    /// Compute the mutability of one lifetime.
739    pub(crate) fn compute_lifetime_mutability<'tcx>(
740        &mut self,
741        s: &impl BaseState<'tcx>,
742        item: &front::DefId,
743        index: u32,
744    ) -> LifetimeMutability {
745        match self.compute_lifetime_mutabilities(s, item) {
746            Some(set) => {
747                if set.contains(&index) {
748                    LifetimeMutability::Mutable
749                } else {
750                    LifetimeMutability::Shared
751                }
752            }
753            None => LifetimeMutability::Unknown,
754        }
755    }
756
757    /// Compute the "mutability" of each lifetime, i.e. whether this lifetime is used in a `&'a mut
758    /// T` type or not. Returns a set of the known-mutable lifetimes for this ADT.
759    fn compute_lifetime_mutabilities<'tcx>(
760        &mut self,
761        s: &impl BaseState<'tcx>,
762        item: &front::DefId,
763    ) -> Option<&HashSet<u32>> {
764        if !matches!(
765            item.kind,
766            front::DefKind::Struct
767                | front::DefKind::Enum
768                | front::DefKind::Union
769                | front::DefKind::FnPtr
770        ) {
771            return None;
772        }
773        // Derived items don't have a definition we can inspect.
774        if item.as_derived().is_some() {
775            return None;
776        }
777        if self
778            .lt_mutability
779            .entry(item.clone())
780            .or_default()
781            .start_processing()
782        {
783            use crate::frontend::SInto;
784            use ty::{TypeSuperVisitable, TypeVisitable};
785
786            struct LtMutabilityVisitor<'a, S> {
787                s: &'a S,
788                computer: &'a mut LifetimeMutabilityComputer,
789                set: HashSet<u32>,
790            }
791            impl<'tcx, S: BaseState<'tcx>> ty::TypeVisitor<ty::TyCtxt<'tcx>> for LtMutabilityVisitor<'_, S> {
792                fn visit_ty(&mut self, ty: ty::Ty<'tcx>) {
793                    match ty.kind() {
794                        ty::Ref(r, _, ty::Mutability::Mut)
795                            if let ty::RegionKind::ReEarlyParam(r) = r.kind() =>
796                        {
797                            self.set.insert(r.index);
798                        }
799                        ty::Adt(adt, args) => {
800                            let item = adt.did().sinto(self.s);
801                            if let Some(mutabilities) =
802                                self.computer.compute_lifetime_mutabilities(self.s, &item)
803                            {
804                                for arg in args.iter() {
805                                    if let Some(r) = arg.as_region()
806                                        && let ty::RegionKind::ReEarlyParam(r) = r.kind()
807                                        && mutabilities.contains(&r.index)
808                                    {
809                                        self.set.insert(r.index);
810                                    }
811                                }
812                            }
813                        }
814                        _ => {}
815                    }
816                    ty.super_visit_with(self)
817                }
818            }
819            let mut visitor = LtMutabilityVisitor {
820                s,
821                computer: self,
822                set: HashSet::default(),
823            };
824
825            let tcx = s.base().tcx;
826            if matches!(item.as_synthetic(s), Some(front::SyntheticItem::FnPtr(_))) {
827                item.type_of(s)
828                    .instantiate_identity()
829                    .skip_normalization()
830                    .visit_with(&mut visitor);
831            } else {
832                let def_id = item.real_rust_def_id();
833                let adt_def = tcx.adt_def(def_id);
834                let generics = item.identity_args(s);
835                for variant in adt_def.variants() {
836                    for field in &variant.fields {
837                        field.ty(tcx, generics).visit_with(&mut visitor);
838                    }
839                }
840            }
841            let set = visitor.set;
842
843            self.lt_mutability
844                .get_mut(item)
845                .unwrap()
846                .done_processing(set);
847        }
848        self.lt_mutability.get(item)?.as_processed()
849    }
850}