Skip to main content

charon_driver/frontend/
rustc_utils.rs

1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2
3use rustc_hir::def::DefKind as RDefKind;
4use rustc_middle::infer::canonical::QueryRegionConstraints;
5use rustc_middle::ty::relate::{
6    Relate, RelateResult, TypeRelation, relate_args_with_variances, structurally_relate_consts,
7    structurally_relate_tys,
8};
9use rustc_middle::{mir, ty};
10use rustc_span::kw;
11
12use crate::frontend::prelude::*;
13
14/// Collects the trait clauses needed to make a type alias well-formed, as Rust itself does not
15/// require type aliases to declare the clauses they use.
16pub fn type_alias_trait_clauses<'tcx>(
17    tcx: ty::TyCtxt<'tcx>,
18    alias_ty: ty::Ty<'tcx>,
19) -> Vec<ty::Clause<'tcx>> {
20    use ty::{TypeSuperVisitable, TypeVisitable, Upcast};
21
22    struct Collector<'tcx> {
23        tcx: ty::TyCtxt<'tcx>,
24        clauses: Vec<ty::Clause<'tcx>>,
25        seen: HashSet<ty::Clause<'tcx>>,
26        visited: HashSet<ty::Ty<'tcx>>,
27    }
28
29    impl<'tcx> Collector<'tcx> {
30        fn collect(&mut self, clause: ty::TraitClause<'tcx>) {
31            // Make a `for<...>` clause that binds all the regions that escape the clause.
32            let mut regions = HashMap::default();
33            let mut bound_vars = Vec::new();
34            let clause = ty::fold_regions(self.tcx, clause, |region, depth| {
35                let ty::ReBound(ty::BoundVarIndexKind::Bound(db), mut br) = region.kind() else {
36                    return region;
37                };
38                br.var = *regions
39                    .entry((db.shifted_out(depth.as_u32()), br))
40                    .or_insert_with(|| {
41                        let var = ty::BoundVar::from_usize(bound_vars.len());
42                        bound_vars.push(ty::BoundVariableKind::Region(br.kind));
43                        var
44                    });
45                ty::Region::new_bound(self.tcx, depth, br)
46            });
47            let clause =
48                ty::Binder::bind_with_vars(clause, self.tcx.mk_bound_variable_kinds(&bound_vars));
49            let key = self.tcx.anonymize_bound_vars(clause).upcast(self.tcx);
50            if self.seen.insert(key) {
51                self.clauses.push(clause.upcast(self.tcx));
52            }
53        }
54    }
55
56    impl<'tcx> ty::TypeVisitor<ty::TyCtxt<'tcx>> for Collector<'tcx> {
57        fn visit_ty(&mut self, ty: ty::Ty<'tcx>) {
58            if !self.visited.insert(ty) {
59                return;
60            }
61            ty.super_visit_with(self);
62            let (def_id, args) = match ty.kind() {
63                ty::Adt(adt, args) => (adt.did(), *args),
64                ty::Alias(_, alias) if matches!(alias.kind, ty::AliasTyKind::Projection { .. }) => {
65                    self.collect(ty::TraitClause {
66                        trait_ref: alias.trait_ref(self.tcx),
67                        polarity: ty::ClausePolarity::Positive,
68                    });
69                    (alias_ty_kind_def_id(alias.kind), alias.args)
70                }
71                _ => return,
72            };
73            // ADTs and associated types can have their own required trait clauses.
74            for (clause, _) in self.tcx.clauses_of(def_id).instantiate_own(self.tcx, args) {
75                if let Some(clause) = clause.skip_normalization().as_trait_clause() {
76                    self.collect(clause.skip_binder());
77                }
78            }
79        }
80    }
81
82    let mut collector = Collector {
83        tcx,
84        clauses: Vec::new(),
85        seen: HashSet::default(),
86        visited: HashSet::default(),
87    };
88    alias_ty.visit_with(&mut collector);
89    collector.clauses
90}
91
92/// The data of a user annotation, bound in an existentially-quantified binder.
93pub type UserAnnotation<'tcx> = ty::Binder<'tcx, UserAnnotationData<'tcx>>;
94/// The data of a user annotation: for each used projection we get the type of the corresponding
95/// place, and we record outlives predicates that must hold. The first vec matches the input list
96/// of projections, the second is free-form.
97pub type UserAnnotationData<'tcx> = (Vec<ty::Ty<'tcx>>, Vec<ty::Clause<'tcx>>);
98/// Denotes a subplace of a user annotation, e.g. in `let Foo { x, .. }: Self = ...;` the
99/// annotation will have a projection for `x`.
100pub type UserAnnotationProj = Vec<mir::ProjectionKind>;
101
102/// Convert a type annotation into data we can use, by fetching the types that rustc inferred and
103/// gathering the predicates that still need to be checked at borrowck time.
104pub fn translate_user_annotation<'tcx>(
105    tcx: ty::TyCtxt<'tcx>,
106    typing_env: ty::TypingEnv<'tcx>,
107    owner: RDefId,
108    annotation: &ty::CanonicalUserTypeAnnotation<'tcx>,
109    projections: &[UserAnnotationProj],
110) -> Result<UserAnnotation<'tcx>, String> {
111    use rustc_trait_selection::infer::{RegionVariableOrigin, TyCtxtInferExt};
112    use rustc_trait_selection::traits::query::type_op::{AscribeUserType, Normalize, TypeOp};
113    use ty::{TypeVisitableExt, Upcast};
114
115    let span = annotation.span;
116    let owner = tcx.typeck_root_def_id(owner).as_local().unwrap();
117    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
118
119    let (user_ty, _) = infcx.instantiate_canonical(span, &annotation.user_ty);
120    let user_ty = ty::fold_regions(tcx, user_ty, |r, _| {
121        if r.is_erased() {
122            infcx.next_region_var(RegionVariableOrigin::Misc(span))
123        } else {
124            r
125        }
126    });
127    let inferred_ty = ty::fold_regions(tcx, annotation.inferred_ty, |_, _| {
128        infcx.next_region_var(RegionVariableOrigin::Misc(span))
129    });
130
131    // Compute the inferred type of the place, and constraints needed to match it with the
132    // user-provided type.
133    let (projected_tys, constraints): (Vec<ty::Ty<'tcx>>, QueryRegionConstraints<'tcx>) = {
134        let mut all_constraints: Vec<Option<&'tcx QueryRegionConstraints<'tcx>>> = Vec::new();
135
136        // `AscribeUserType` needs a normalized type.
137        let normalized = param_env
138            .and(Normalize {
139                value: ty::set_opaques_to_non_rigid(tcx, inferred_ty),
140            })
141            .fully_perform(&infcx, owner, span)
142            .map_err(|_| "could not normalize inferred annotation type".to_owned())?;
143        let inferred_ty = normalized.output;
144        all_constraints.push(normalized.constraints);
145
146        let ascribe_result = param_env
147            .and(AscribeUserType {
148                mir_ty: inferred_ty,
149                user_ty,
150            })
151            .fully_perform(&infcx, owner, span)
152            .map_err(|_| "could not recover user type ascription".to_owned())?;
153        all_constraints.push(ascribe_result.constraints);
154
155        let mut projected_tys = Vec::new();
156        for projections in projections {
157            let mut projected_ty = mir::PlaceTy::from_ty(inferred_ty);
158            let mut iter = projections.iter();
159            loop {
160                let resolved = param_env
161                    .and(Normalize {
162                        value: ty::Unnormalized::new_wip(projected_ty.ty),
163                    })
164                    .fully_perform(&infcx, owner, span)
165                    .map_err(|_| "could not normalize user type projection".to_owned())?;
166                projected_ty.ty = resolved.output;
167                all_constraints.push(resolved.constraints);
168                let Some(projection) = iter.next() else { break };
169                if matches!(
170                    projection,
171                    mir::ProjectionElem::OpaqueCast(())
172                        | mir::ProjectionElem::UnwrapUnsafeBinder(())
173                ) {
174                    return Err("unsupported cast in user type projection".into());
175                }
176                projected_ty = projected_ty.projection_ty_core(
177                    tcx,
178                    projection,
179                    |ty, variant, field, ()| {
180                        mir::PlaceTy::field_ty(tcx, ty, variant, field).skip_normalization()
181                    },
182                    |()| unreachable!(),
183                );
184            }
185            projected_tys.push(projected_ty.ty);
186        }
187
188        // Merge the constraints we got from normalizing, relating and projecting.
189        let mut constraints: QueryRegionConstraints<'tcx> = Default::default();
190        for c in all_constraints.into_iter().flatten() {
191            constraints
192                .constraints
193                .extend(c.constraints.iter().copied());
194            constraints
195                .assumptions
196                .extend(c.assumptions.iter().copied());
197        }
198
199        (projected_tys, constraints)
200    };
201
202    // Apply the region equality constraints to remove redundant regions.
203    let (projected_tys, constraints) = {
204        let cause = rustc_middle::traits::ObligationCause::dummy_with_span(span);
205        for constraint in &constraints.constraints {
206            if let ty::RegionConstraint::Eq(eq @ ty::RegionEqPredicate(lhs, rhs)) =
207                constraint.constraint
208                && [lhs, rhs]
209                    .into_iter()
210                    .all(|r| infcx.universe_of_region(r) == ty::UniverseIndex::ROOT)
211            {
212                infcx.register_region_eq_constraint(eq, constraint.visible_for_leak_check, &cause);
213            }
214        }
215        infcx.deeply_resolve_via_unification_table((projected_tys, constraints))
216    };
217
218    // Turn the constraints into clauses.
219    let clauses: Vec<ty::Clause<'tcx>> = {
220        if !constraints.assumptions.is_empty() {
221            return Err("unsupported assumptions in user type ascription constraints".into());
222        }
223        let mut clauses = Vec::new();
224        let mut push_clause = |kind| clauses.push(ty::Binder::dummy(kind).upcast(tcx));
225        for constraint in constraints.constraints {
226            match constraint.constraint {
227                ty::RegionConstraint::Outlives(ty::OutlivesClause(lhs, rhs)) => {
228                    let clause = match lhs.kind() {
229                        ty::GenericArgKind::Lifetime(lhs) => {
230                            ty::ClauseKind::RegionOutlives(ty::OutlivesClause(lhs, rhs))
231                        }
232                        ty::GenericArgKind::Type(lhs) => {
233                            ty::ClauseKind::TypeOutlives(ty::OutlivesClause(lhs, rhs))
234                        }
235                        ty::GenericArgKind::Const(_) => {
236                            return Err("const outlives constraint in user type ascription".into());
237                        }
238                    };
239                    push_clause(clause);
240                }
241                ty::RegionConstraint::Eq(ty::RegionEqPredicate(lhs, rhs)) => {
242                    if lhs != rhs {
243                        // Equality is the conjunction of the two outlives relations.
244                        for (lhs, rhs) in [(lhs, rhs), (rhs, lhs)] {
245                            push_clause(ty::ClauseKind::RegionOutlives(ty::OutlivesClause(
246                                lhs, rhs,
247                            )));
248                        }
249                    }
250                }
251            }
252        }
253        clauses
254    };
255
256    // Bind all the inferred regions in a binder.
257    let bound = {
258        let value = (projected_tys, clauses);
259        if value.has_non_region_infer() || value.has_non_region_placeholders() {
260            return Err("unresolved type or const in user type ascription".into());
261        }
262        let mut regions = HashMap::default();
263        let mut bound_vars = Vec::new();
264        let mut unsupported_region = false;
265        let value = ty::fold_regions(tcx, value, |region, depth| match region.kind() {
266            ty::ReVar(_) if infcx.universe_of_region(region) == ty::UniverseIndex::ROOT => {
267                let var = *regions.entry(region).or_insert_with(|| {
268                    let var = ty::BoundVar::from_usize(bound_vars.len());
269                    bound_vars.push(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon));
270                    var
271                });
272                ty::Region::new_bound(
273                    tcx,
274                    depth,
275                    ty::BoundRegion {
276                        var,
277                        kind: ty::BoundRegionKind::Anon,
278                    },
279                )
280            }
281            ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => {
282                unsupported_region = true;
283                region
284            }
285            _ => region,
286        });
287        if unsupported_region {
288            return Err("unsupported region in user type ascription constraints".into());
289        }
290        ty::Binder::bind_with_vars(value, tcx.mk_bound_variable_kinds(&bound_vars))
291    };
292
293    Ok(bound)
294}
295
296/// Computes the variance of each region bound by `sig`.
297///
298/// This follows rustc's `FunctionalVariances` helper from the `impl_trait_overcaptures` lint.
299pub fn fn_sig_bound_region_variances<'tcx>(
300    tcx: ty::TyCtxt<'tcx>,
301    sig: ty::PolyFnSig<'tcx>,
302) -> HashMap<ty::BoundVar, ty::Variance> {
303    struct FunctionalVariances<'tcx> {
304        tcx: ty::TyCtxt<'tcx>,
305        variances: HashMap<ty::BoundVar, ty::Variance>,
306        ambient_variance: ty::Variance,
307        target_binder: ty::DebruijnIndex,
308    }
309
310    impl<'tcx> TypeRelation<ty::TyCtxt<'tcx>> for FunctionalVariances<'tcx> {
311        fn cx(&self) -> ty::TyCtxt<'tcx> {
312            self.tcx
313        }
314
315        fn relate_ty_args(
316            &mut self,
317            a_ty: ty::Ty<'tcx>,
318            _: ty::Ty<'tcx>,
319            def_id: rustc_hir::def_id::DefId,
320            a_args: ty::GenericArgs<'tcx>,
321            b_args: ty::GenericArgs<'tcx>,
322            _: impl FnOnce(ty::GenericArgs<'tcx>) -> ty::Ty<'tcx>,
323        ) -> RelateResult<'tcx, ty::Ty<'tcx>> {
324            relate_args_with_variances(self, self.tcx.variances_of(def_id), a_args, b_args)?;
325            Ok(a_ty)
326        }
327
328        fn relate_with_variance<T: Relate<ty::TyCtxt<'tcx>>>(
329            &mut self,
330            variance: ty::Variance,
331            _: ty::VarianceDiagInfo<ty::TyCtxt<'tcx>>,
332            a: T,
333            b: T,
334        ) -> RelateResult<'tcx, T> {
335            let old_variance = self.ambient_variance;
336            self.ambient_variance = self.ambient_variance.xform(variance);
337            let result = self.relate(a, b);
338            self.ambient_variance = old_variance;
339            result
340        }
341
342        fn tys(&mut self, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>) -> RelateResult<'tcx, ty::Ty<'tcx>> {
343            structurally_relate_tys(self, a, b)
344        }
345
346        fn regions(
347            &mut self,
348            a: ty::Region<'tcx>,
349            _: ty::Region<'tcx>,
350        ) -> RelateResult<'tcx, ty::Region<'tcx>> {
351            if let ty::ReBound(ty::BoundVarIndexKind::Bound(binder), ty::BoundRegion { var, .. }) =
352                a.kind()
353                && binder == self.target_binder
354            {
355                self.variances
356                    .entry(var)
357                    .and_modify(|old| *old = unify_variances(*old, self.ambient_variance))
358                    .or_insert(self.ambient_variance);
359            }
360            Ok(a)
361        }
362
363        fn consts(
364            &mut self,
365            a: ty::Const<'tcx>,
366            b: ty::Const<'tcx>,
367        ) -> RelateResult<'tcx, ty::Const<'tcx>> {
368            structurally_relate_consts(self, a, b)
369        }
370
371        fn binders<T>(
372            &mut self,
373            a: ty::Binder<'tcx, T>,
374            b: ty::Binder<'tcx, T>,
375        ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
376        where
377            T: Relate<ty::TyCtxt<'tcx>>,
378        {
379            let old_target_binder = self.target_binder;
380            self.target_binder = self.target_binder.shifted_in(1);
381            let result = self.relate(a.skip_binder(), b.skip_binder());
382            self.target_binder = old_target_binder;
383            result?;
384            Ok(a)
385        }
386    }
387
388    fn unify_variances(a: ty::Variance, b: ty::Variance) -> ty::Variance {
389        match (a, b) {
390            (ty::Bivariant, other) | (other, ty::Bivariant) => other,
391            (ty::Invariant, _) | (_, ty::Invariant) => ty::Invariant,
392            (ty::Contravariant, ty::Covariant) | (ty::Covariant, ty::Contravariant) => {
393                ty::Invariant
394            }
395            (ty::Contravariant, ty::Contravariant) => ty::Contravariant,
396            (ty::Covariant, ty::Covariant) => ty::Covariant,
397        }
398    }
399
400    let mut relation = FunctionalVariances {
401        tcx,
402        variances: HashMap::default(),
403        // `Relate for FnSig` makes inputs contravariant. We are computing the variance of the
404        // signature's own bound parameters, so cancel that outer function-type variance. Nested
405        // function types still introduce their own contravariance as usual.
406        ambient_variance: ty::Contravariant,
407        target_binder: ty::INNERMOST,
408    };
409    relation
410        .relate(sig.skip_binder(), sig.skip_binder())
411        .expect("a signature must relate to itself");
412
413    // A bound region that does not occur in the signature is bivariant.
414    for (index, var) in sig.bound_vars().iter().enumerate() {
415        if matches!(var, ty::BoundVariableKind::Region(_)) {
416            relation
417                .variances
418                .entry(ty::BoundVar::from_usize(index))
419                .or_insert(ty::Bivariant);
420        }
421    }
422    relation.variances
423}
424
425/// Instantiate this binder with the provided args. Use `None` if the args are known to be the
426/// identity args.
427pub fn inst_binder<'tcx, T>(
428    tcx: ty::TyCtxt<'tcx>,
429    typing_env: ty::TypingEnv<'tcx>,
430    args: Option<ty::GenericArgs<'tcx>>,
431    x: ty::EarlyBinder<'tcx, T>,
432) -> T
433where
434    T: ty::TypeFoldable<ty::TyCtxt<'tcx>> + Clone,
435{
436    match args {
437        None => x.instantiate_identity().skip_normalization(),
438        Some(args) => {
439            let x = x.instantiate(tcx, args).skip_normalization();
440            normalize(tcx, typing_env, ty::set_aliases_to_non_rigid(tcx, x))
441        }
442    }
443}
444
445/// Instantiate this value with the provided args. Use `None` if the args are known to be the
446/// identity args.
447pub fn substitute<'tcx, T>(
448    tcx: ty::TyCtxt<'tcx>,
449    typing_env: ty::TypingEnv<'tcx>,
450    args: Option<ty::GenericArgs<'tcx>>,
451    x: T,
452) -> T
453where
454    T: ty::TypeFoldable<ty::TyCtxt<'tcx>>,
455{
456    inst_binder(tcx, typing_env, args, ty::EarlyBinder::bind(tcx, x))
457}
458
459/// Closures and inline consts have special type params that are used as inference variables. After
460/// analysis, they can be computed from the rest of the args (modulo some erased regions). This
461/// computes the identity args for this `def_id` with the inference ars properly inferred.
462pub fn identity_args_with_inferred<'tcx>(
463    tcx: ty::TyCtxt<'tcx>,
464    def_id: RDefId,
465) -> ty::GenericArgs<'tcx> {
466    match tcx.def_kind(def_id) {
467        RDefKind::Closure | RDefKind::SyntheticCoroutineBody => {
468            let type_of = tcx
469                .type_of(def_id)
470                .instantiate_identity()
471                .skip_normalization();
472            let args = match *type_of.kind() {
473                ty::Closure(_, args) | ty::Coroutine(_, args) => args,
474                _ => unreachable!(),
475            };
476            // `type_of` erases too much; use the parent args as a base.
477            let parent = tcx.generics_of(def_id).parent.unwrap();
478            args.rebase_onto(tcx, parent, ty::GenericArgs::identity_for_item(tcx, parent))
479        }
480        RDefKind::AnonConst
481            if tcx.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline =>
482        {
483            // `tcx.type_of` fetches its result from the provided arguments, which circularly can't
484            // help us. We get the real type from the MIR body which is sad but works.
485            let get_ret_ty = |body: &mir::Body<'tcx>| body.local_decls[mir::Local::ZERO].ty;
486            let ret_ty = mir_kinds::CTFE::get_mir(tcx, def_id, get_ret_ty)
487                .or_else(|| mir_kinds::Optimized::get_mir(tcx, def_id, get_ret_ty))
488                .expect("could not compute the type of this inline const: {def_id:?}");
489            let mut args = ty::GenericArgs::identity_for_item(tcx, def_id)
490                .as_slice()
491                .to_vec();
492            *args
493                .last_mut()
494                .expect("inline const has a return type parameter") = ret_ty.into();
495            tcx.mk_args_from_iter(args.into_iter())
496        }
497        _ => ty::GenericArgs::identity_for_item(tcx, def_id),
498    }
499}
500
501/// Replace each erased region in this value with a fresh placeholder region.
502pub fn unerase_lifetimes<'tcx, T>(
503    s: &impl BaseState<'tcx>,
504    val: T,
505    new_region_name: Symbol,
506) -> (T, Vec<ty::PlaceholderRegion<'tcx>>)
507where
508    T: ty::TypeFoldable<ty::TyCtxt<'tcx>>,
509{
510    let tcx = s.base().tcx;
511    let mut extra_regions = Vec::new();
512    let val = ty::fold_regions(tcx, val, |region, _| {
513        if region.is_erased() {
514            let placeholder = ty::PlaceholderRegion::new(
515                ty::UniverseIndex::ROOT,
516                ty::BoundRegion {
517                    var: ty::BoundVar::from_usize(extra_regions.len()),
518                    kind: ty::BoundRegionKind::NamedForPrinting(new_region_name),
519                },
520            );
521            extra_regions.push(placeholder);
522            ty::Region::new_placeholder(tcx, placeholder)
523        } else {
524            region
525        }
526    });
527    (val, extra_regions)
528}
529
530/// Takes two values that differ only in their regions, where `template` has placeholder regions
531/// used each once in the places that they differ. Returns a mapping from those placeholders to the
532/// corresponding regions in `actual`.
533pub fn match_region_args<'tcx, T: Relate<ty::TyCtxt<'tcx>>>(
534    tcx: ty::TyCtxt<'tcx>,
535    template: T,
536    actual: T,
537) -> Result<HashMap<ty::PlaceholderRegion<'tcx>, ty::Region<'tcx>>, ty::error::TypeError<'tcx>> {
538    struct RegionMapping<'tcx> {
539        tcx: ty::TyCtxt<'tcx>,
540        args: HashMap<ty::PlaceholderRegion<'tcx>, ty::Region<'tcx>>,
541        depth: u32,
542    }
543
544    impl<'tcx> TypeRelation<ty::TyCtxt<'tcx>> for RegionMapping<'tcx> {
545        fn cx(&self) -> ty::TyCtxt<'tcx> {
546            self.tcx
547        }
548
549        fn regions(
550            &mut self,
551            source: ty::Region<'tcx>,
552            target: ty::Region<'tcx>,
553        ) -> RelateResult<'tcx, ty::Region<'tcx>> {
554            if let ty::RePlaceholder(placeholder) = source.kind() {
555                let target =
556                    if let ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) = target.kind() {
557                        if db.as_u32() < self.depth {
558                            return Err(ty::error::TypeError::RegionsPlaceholderMismatch);
559                        }
560                        ty::Region::new_bound(self.tcx, db.shifted_out(self.depth), br)
561                    } else {
562                        target
563                    };
564                let slot = self
565                    .args
566                    .entry(placeholder)
567                    .or_insert(self.tcx.lifetimes.re_erased);
568                if slot.is_erased() || *slot == target {
569                    *slot = target;
570                } else {
571                    return Err(ty::error::TypeError::RegionsPlaceholderMismatch);
572                }
573            }
574            Ok(source)
575        }
576
577        fn relate_with_variance<T: Relate<ty::TyCtxt<'tcx>>>(
578            &mut self,
579            _: ty::Variance,
580            _: ty::VarianceDiagInfo<ty::TyCtxt<'tcx>>,
581            a: T,
582            b: T,
583        ) -> RelateResult<'tcx, T> {
584            self.relate(a, b)
585        }
586
587        fn relate_ty_args(
588            &mut self,
589            a_ty: ty::Ty<'tcx>,
590            _: ty::Ty<'tcx>,
591            _: rustc_span::def_id::DefId,
592            a_args: ty::GenericArgs<'tcx>,
593            b_args: ty::GenericArgs<'tcx>,
594            _: impl FnOnce(ty::GenericArgs<'tcx>) -> ty::Ty<'tcx>,
595        ) -> RelateResult<'tcx, ty::Ty<'tcx>> {
596            self.relate(a_args, b_args)?;
597            Ok(a_ty)
598        }
599
600        fn tys(&mut self, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>) -> RelateResult<'tcx, ty::Ty<'tcx>> {
601            structurally_relate_tys(self, a, b)
602        }
603
604        fn consts(
605            &mut self,
606            a: ty::Const<'tcx>,
607            b: ty::Const<'tcx>,
608        ) -> RelateResult<'tcx, ty::Const<'tcx>> {
609            structurally_relate_consts(self, a, b)
610        }
611
612        fn binders<T>(
613            &mut self,
614            a: ty::Binder<'tcx, T>,
615            b: ty::Binder<'tcx, T>,
616        ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
617        where
618            T: Relate<ty::TyCtxt<'tcx>>,
619        {
620            if a.bound_vars().len() != b.bound_vars().len() {
621                return Err(ty::error::TypeError::Mismatch);
622            }
623            self.depth += 1;
624            let result = self.relate(a.skip_binder(), b.skip_binder());
625            self.depth -= 1;
626            result?;
627            Ok(a)
628        }
629    }
630
631    let mut mapping = RegionMapping {
632        tcx,
633        args: HashMap::default(),
634        depth: 0,
635    };
636    mapping.relate(template, actual)?;
637    Ok(mapping.args)
638}
639
640#[extension_traits::extension(pub trait SubstBinder)]
641impl<'tcx, T: ty::TypeFoldable<ty::TyCtxt<'tcx>>> ty::Binder<'tcx, T> {
642    fn subst(
643        self,
644        tcx: ty::TyCtxt<'tcx>,
645        generics: &[ty::GenericArg<'tcx>],
646    ) -> ty::Binder<'tcx, T> {
647        ty::EarlyBinder::bind(tcx, self)
648            .instantiate(tcx, generics)
649            .skip_normalization()
650    }
651}
652
653/// Whether the item can have generic parameters.
654pub(crate) fn can_have_generics(kind: &DefKind) -> bool {
655    use DefKind::*;
656    !matches!(
657        kind,
658        ConstParam
659            | ExternCrate
660            | ForeignMod
661            | GlobalAsm
662            | LifetimeParam
663            | Macro(..)
664            | Mod
665            | TyParam
666            | Use
667    )
668}
669
670pub(crate) fn get_variant_kind<'s, S: UnderOwnerState<'s>>(
671    adt_def: &ty::AdtDef<'s>,
672    variant_index: rustc_abi::VariantIdx,
673    _s: &S,
674) -> VariantKind {
675    if adt_def.is_struct() {
676        VariantKind::Struct
677    } else if adt_def.is_union() {
678        VariantKind::Union
679    } else {
680        let index = variant_index;
681        VariantKind::Enum { index }
682    }
683}
684
685/// Gets the children of a module.
686pub fn get_mod_children<'tcx>(
687    tcx: ty::TyCtxt<'tcx>,
688    def_id: RDefId,
689) -> Vec<(Option<rustc_span::Ident>, RDefId)> {
690    match def_id.as_local() {
691        Some(ldid) => match tcx.hir_node_by_def_id(ldid) {
692            rustc_hir::Node::Crate(m)
693            | rustc_hir::Node::Item(&rustc_hir::Item {
694                kind: rustc_hir::ItemKind::Mod(_, m),
695                ..
696            }) => m
697                .item_ids
698                .iter()
699                .map(|&item_id| {
700                    let opt_ident = tcx.hir_item(item_id).kind.ident();
701                    let def_id = item_id.owner_id.to_def_id();
702                    (opt_ident, def_id)
703                })
704                .collect(),
705            node => panic!("DefKind::Module is an unexpected node: {node:?}"),
706        },
707        None => tcx
708            .module_children(def_id)
709            .iter()
710            .filter_map(|child| Some((Some(child.ident), child.res.opt_def_id()?)))
711            .collect(),
712    }
713}
714
715/// Gets the children of an `extern` block. Empty if the block is not defined in the current crate.
716pub fn get_foreign_mod_children<'tcx>(tcx: ty::TyCtxt<'tcx>, def_id: RDefId) -> Vec<RDefId> {
717    match def_id.as_local() {
718        Some(ldid) => tcx
719            .hir_node_by_def_id(ldid)
720            .expect_item()
721            .expect_foreign_mod()
722            .1
723            .iter()
724            .map(|foreign_item_ref| foreign_item_ref.owner_id.to_def_id())
725            .collect(),
726        None => vec![],
727    }
728}
729
730/// The signature of a method impl may be a subtype of the one expected from the trait decl, as in
731/// the example below. For correctness, we must be able to map from the method generics declared in
732/// the trait to the actual method generics. Because this would require type inference, we instead
733/// simply return the declared signature. This will cause issues if it is possible to use such a
734/// more-specific implementation with its more-specific type, but we have a few other issues with
735/// lifetime-generic function pointers anyway so this is unlikely to cause problems.
736///
737/// ```ignore
738/// trait MyCompare<Other>: Sized {
739///     fn compare(self, other: Other) -> bool;
740/// }
741/// impl<'a> MyCompare<&'a ()> for &'a () {
742///     // This implementation is more general because it works for non-`'a` refs. Note that only
743///     // late-bound vars may differ in this way.
744///     // `<&'a () as MyCompare<&'a ()>>::compare` has type `fn<'b>(&'a (), &'b ()) -> bool`,
745///     // but type `fn(&'a (), &'a ()) -> bool` was expected from the trait declaration.
746///     fn compare<'b>(self, _other: &'b ()) -> bool {
747///         true
748///     }
749/// }
750/// ```
751pub fn get_method_sig<'tcx>(
752    tcx: ty::TyCtxt<'tcx>,
753    typing_env: ty::TypingEnv<'tcx>,
754    def_id: RDefId,
755    method_args: Option<ty::GenericArgs<'tcx>>,
756) -> ty::PolyFnSig<'tcx> {
757    let item = tcx.associated_item(def_id);
758    let ty::AssocContainer::TraitImpl(Ok(decl_method_id)) = item.container else {
759        return inst_binder(tcx, typing_env, method_args, tcx.fn_sig(def_id));
760    };
761    let declared_sig = tcx.fn_sig(decl_method_id);
762
763    let impl_def_id = item.container_id(tcx);
764    let method_args =
765        method_args.unwrap_or_else(|| ty::GenericArgs::identity_for_item(tcx, def_id));
766    // The trait predicate that is implemented by the surrounding impl block.
767    let implemented_trait_ref = tcx
768        .impl_trait_ref(impl_def_id)
769        .instantiate(tcx, method_args);
770    let implemented_trait_ref = normalize(tcx, typing_env, implemented_trait_ref);
771    // Construct arguments for the declared method generics in the context of the implemented
772    // method generics.
773    let decl_args = method_args.rebase_onto(tcx, impl_def_id, implemented_trait_ref.args);
774    let sig = declared_sig.instantiate(tcx, decl_args);
775    let sig = normalize(tcx, typing_env, sig);
776
777    if let container_named_lts = tcx
778        .generics_of(impl_def_id)
779        .own_params
780        .iter()
781        .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
782        .filter(|p| p.name != kw::UnderscoreLifetime)
783        .map(|p| p.name)
784        .collect::<HashSet<_>>()
785        && sig
786            .bound_vars()
787            .iter()
788            .map(|v| v.expect_region())
789            .filter_map(|v| v.get_name(tcx))
790            .any(|lt| container_named_lts.contains(&lt))
791    {
792        // Avoids using the same lifetime name twice in the same scope (once in impl parameters,
793        // second in the method declaration late-bound vars).
794        tcx.anonymize_bound_vars(sig)
795    } else {
796        sig
797    }
798}
799
800/// Generates a list of `<trait_ref>::Ty` type aliases for each non-gat associated type of the
801/// given trait and its parents, in a specific order.
802pub fn assoc_tys_for_trait<'tcx>(
803    tcx: ty::TyCtxt<'tcx>,
804    typing_env: ty::TypingEnv<'tcx>,
805    tref: ty::TraitRef<'tcx>,
806) -> Vec<ty::AliasTy<'tcx>> {
807    fn gather_assoc_tys<'tcx>(
808        tcx: ty::TyCtxt<'tcx>,
809        typing_env: ty::TypingEnv<'tcx>,
810        assoc_tys: &mut Vec<ty::AliasTy<'tcx>>,
811        tref: ty::TraitRef<'tcx>,
812    ) {
813        assoc_tys.extend(
814            tcx.associated_items(tref.def_id)
815                .in_definition_order()
816                .filter(|assoc| matches!(assoc.kind, ty::AssocKind::Type { .. }))
817                .filter(|assoc| {
818                    tcx.generics_of(assoc.def_id).own_params.is_empty()
819                        && tcx.clauses_of(assoc.def_id).clauses.is_empty()
820                })
821                .map(|assoc| {
822                    let alias_ty = ty::AliasTyKind::Projection {
823                        def_id: assoc.def_id,
824                    };
825                    ty::AliasTy::new(tcx, alias_ty, tref.args)
826                }),
827        );
828        for clause in tcx
829            .explicit_super_clauses_of(tref.def_id)
830            .map_bound(|clauses| clauses.iter().map(|(clause, _span)| *clause))
831            .iter_instantiated(tcx, tref.args)
832        {
833            if let Some(pred) = clause.as_trait_clause() {
834                let tref = erase_and_norm(tcx, typing_env, pred.map(|b| b.skip_binder().trait_ref));
835                gather_assoc_tys(tcx, typing_env, assoc_tys, tref);
836            }
837        }
838    }
839    let mut ret = vec![];
840    gather_assoc_tys(tcx, typing_env, &mut ret, tref);
841    ret
842}
843
844/// Generates a `dyn Trait<Args.., Ty = <Self as Trait>::Ty..>` type for the given trait ref.
845pub fn dyn_self_ty<'tcx>(
846    tcx: ty::TyCtxt<'tcx>,
847    typing_env: ty::TypingEnv<'tcx>,
848    tref: ty::TraitRef<'tcx>,
849) -> Option<ty::Ty<'tcx>> {
850    let re_erased = tcx.lifetimes.re_erased;
851    if !tcx.is_dyn_compatible(tref.def_id) {
852        return None;
853    }
854
855    // The main `Trait<Args>` predicate.
856    let main_pred = ty::Binder::dummy(ty::ExistentialPredicate::Trait(
857        ty::ExistentialTraitRef::erase_self_ty(tcx, tref),
858    ));
859
860    let ty_constraints = assoc_tys_for_trait(tcx, typing_env, tref)
861        .into_iter()
862        .map(|alias_ty| {
863            let proj = ty::ProjectionClause {
864                projection_term: alias_ty.into(),
865                term: ty::Ty::new_alias(tcx, ty::IsRigid::No, alias_ty).into(),
866            };
867            let proj = ty::ExistentialProjection::erase_self_ty(tcx, proj);
868            ty::Binder::dummy(ty::ExistentialPredicate::Projection(proj))
869        });
870
871    let preds = {
872        // Stable sort predicates to prevent platform-specific ordering issues
873        let mut preds: Vec<_> = [main_pred].into_iter().chain(ty_constraints).collect();
874        preds.sort_by(|a, b| {
875            use rustc_middle::ty::ExistentialPredicateStableCmpExt;
876            a.skip_binder().stable_cmp(tcx, &b.skip_binder())
877        });
878        tcx.mk_poly_existential_predicates(&preds)
879    };
880    let ty = tcx.mk_ty_from_kind(ty::Dynamic(preds, re_erased));
881    let ty = normalize(tcx, typing_env, ty::Unnormalized::new_wip(ty));
882    Some(ty)
883}
884
885pub fn drop_glue_shim<'tcx>(
886    s: &impl UnderOwnerState<'tcx>,
887    def_id: &DefId,
888    instantiate: Option<ty::GenericArgs<'tcx>>,
889) -> mir::Body<'tcx> {
890    let tcx = s.base().tcx;
891    let drop_glue = tcx.require_lang_item(rustc_attr_ir::LangItem::DropGlue, rustc_span::DUMMY_SP);
892    let ty = inst_binder(tcx, s.typing_env(), instantiate, def_id.type_of(s));
893    let mut body = rustc_mir_transform::build_drop_shim(tcx, drop_glue, Some(ty), s.typing_env());
894    // Set the mir phase so that charon knows the contained drops are precise.
895    body.phase = mir::MirPhase::Runtime(mir::RuntimePhase::Optimized);
896    body
897}