Skip to main content

flux_infer/
projections.rs

1use std::iter;
2
3use flux_common::{bug, iter::IterExt, tracked_span_bug};
4use flux_middle::{
5    global_env::GlobalEnv,
6    queries::{QueryErr, QueryResult},
7    query_bug,
8    rty::{
9        self, AliasKind, AliasReft, AliasTerm, AliasTy, BaseTy, Binder, Clause, ClauseKind, Const,
10        ConstKind, EarlyBinder, Expr, ExprKind, GenericArg, List, ProjectionPredicate, RefineArgs,
11        Region, Sort, SubsetTy, SubsetTyCtor, Ty, TyKind, TyOrBase,
12        fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable, TypeVisitable},
13        refining::Refiner,
14        subst::{GenericsSubstDelegate, GenericsSubstFolder},
15    },
16};
17use flux_rustc_bridge::{ToRustc, lowering::Lower};
18use itertools::izip;
19use rustc_hir::def_id::DefId;
20use rustc_infer::traits::{BuiltinImplSource, Obligation};
21use rustc_middle::{
22    traits::{ImplSource, ObligationCause},
23    ty::{TyCtxt, Variance},
24};
25use rustc_trait_selection::{
26    solve::deeply_normalize,
27    traits::{FulfillmentError, SelectionContext},
28};
29use rustc_type_ir::TypeVisitableExt;
30
31use crate::{
32    fixpoint_encoding::KVarEncoding,
33    infer::{InferCtxtAt, InferResult},
34    refine_tree::Scope,
35};
36
37pub trait NormalizeExt: TypeFoldable {
38    fn deeply_normalize(&self, infcx: &mut InferCtxtAt) -> QueryResult<Self>;
39
40    /// Deeply normalize projections but only inside sorts
41    fn deeply_normalize_sorts<'tcx>(
42        &self,
43        def_id: DefId,
44        genv: GlobalEnv<'_, 'tcx>,
45        infcx: &rustc_infer::infer::InferCtxt<'tcx>,
46    ) -> QueryResult<Self>;
47}
48
49impl<T: TypeFoldable> NormalizeExt for T {
50    fn deeply_normalize(&self, infcx: &mut InferCtxtAt) -> QueryResult<Self> {
51        let span = infcx.span;
52        let infcx_orig = &mut infcx.infcx;
53        let mut infcx = infcx_orig.branch();
54        let infcx = infcx.at(span);
55        let mut normalizer = Normalizer::new(infcx)?;
56        self.erase_regions().try_fold_with(&mut normalizer)
57    }
58
59    fn deeply_normalize_sorts<'tcx>(
60        &self,
61        def_id: DefId,
62        genv: GlobalEnv<'_, 'tcx>,
63        infcx: &rustc_infer::infer::InferCtxt<'tcx>,
64    ) -> QueryResult<Self> {
65        let mut normalizer = SortNormalizer::new(def_id, genv, infcx);
66        self.erase_regions().try_fold_with(&mut normalizer)
67    }
68}
69
70struct Normalizer<'a, 'infcx, 'genv, 'tcx> {
71    infcx: InferCtxtAt<'a, 'infcx, 'genv, 'tcx>,
72    selcx: SelectionContext<'infcx, 'tcx>,
73    param_env: List<Clause>,
74    scope: Scope,
75}
76
77impl<'a, 'infcx, 'genv, 'tcx> Normalizer<'a, 'infcx, 'genv, 'tcx> {
78    fn new(infcx: InferCtxtAt<'a, 'infcx, 'genv, 'tcx>) -> QueryResult<Self> {
79        let predicates = infcx.genv.predicates_of(infcx.def_id)?;
80        let param_env = predicates.instantiate_identity().predicates.clone();
81        let selcx = SelectionContext::new(infcx.region_infcx);
82        let scope = infcx.cursor().marker().scope().unwrap();
83        Ok(Normalizer { infcx, selcx, param_env, scope })
84    }
85
86    fn normalize_projection_ty(
87        &mut self,
88        obligation: &AliasTerm,
89    ) -> QueryResult<(bool, SubsetTyCtor)> {
90        // First we must recursively (i.e., deeply) normalize projection types before proceeding.
91        // For example, in `issue-1449.rs` when normalizing `<<MyChoice as Choice>::Session as FromState>::Role`
92        // we first recursively normalize to get `<End<B> as FromState>::Role`
93        let obligation = &obligation.try_fold_with(self)?;
94
95        let mut candidates = vec![];
96        self.assemble_candidates_from_param_env(obligation, &mut candidates);
97        self.assemble_candidates_from_trait_def(obligation, &mut candidates)
98            .unwrap_or_else(|err| tracked_span_bug!("{err:?}"));
99        self.assemble_candidates_from_impls(obligation, &mut candidates)?;
100        if candidates.is_empty() {
101            // TODO: This is a temporary hack that uses rustc's trait selection when FLUX fails;
102            //       The correct thing, e.g for `trait09.rs` is to make sure FLUX's param_env mirrors RUSTC,
103            //       by suitably chasing down the super-trait predicates,
104            //       see https://github.com/flux-rs/flux/issues/737
105            let (changed, ty_ctor) = normalize_projection_ty_with_rustc(
106                self.genv(),
107                self.def_id(),
108                self.infcx.region_infcx,
109                obligation,
110            )?;
111            return Ok((changed, ty_ctor));
112        }
113        if candidates.len() > 1 {
114            bug!("ambiguity when resolving `{obligation:?}` in {:?}", self.def_id());
115        }
116        let ctor = self.confirm_candidate(candidates.pop().unwrap(), obligation)?;
117        Ok((true, ctor))
118    }
119
120    fn find_resolved_predicates(
121        &self,
122        subst: &mut TVarSubst,
123        preds: Vec<EarlyBinder<ProjectionPredicate>>,
124    ) -> (Vec<ProjectionPredicate>, Vec<EarlyBinder<ProjectionPredicate>>) {
125        let mut resolved = vec![];
126        let mut unresolved = vec![];
127        for pred in preds {
128            let term = pred.clone().skip_binder().term;
129            let alias_term = pred.clone().map(|p| p.projection_term);
130            match subst.instantiate_partial(alias_term) {
131                Some(projection_term) => {
132                    let pred = ProjectionPredicate { projection_term, term };
133                    resolved.push(pred);
134                }
135                None => unresolved.push(pred.clone()),
136            }
137        }
138        (resolved, unresolved)
139    }
140
141    // See issue-829*.rs for an example of what this function is for.
142    fn resolve_projection_predicates(
143        &mut self,
144        subst: &mut TVarSubst,
145        impl_def_id: DefId,
146    ) -> QueryResult {
147        let mut projection_preds: Vec<_> = self
148            .genv()
149            .predicates_of(impl_def_id)?
150            .skip_binder()
151            .predicates
152            .iter()
153            .filter_map(|pred| {
154                if let ClauseKind::Projection(pred) = pred.kind_skipping_binder() {
155                    Some(EarlyBinder(pred.clone()))
156                } else {
157                    None
158                }
159            })
160            .collect();
161
162        while !projection_preds.is_empty() {
163            let (resolved, unresolved) = self.find_resolved_predicates(subst, projection_preds);
164
165            if resolved.is_empty() {
166                break; // failed: there is some unresolved projection pred!
167            }
168            for p in resolved {
169                let (_, ctor) = self.normalize_projection_ty(&p.projection_term)?;
170                subst.subset_tys(&p.term, &ctor);
171            }
172            projection_preds = unresolved;
173        }
174        Ok(())
175    }
176
177    fn confirm_candidate(
178        &mut self,
179        candidate: Candidate,
180        obligation: &AliasTerm,
181    ) -> QueryResult<SubsetTyCtor> {
182        let tcx = self.tcx();
183        match candidate {
184            Candidate::ParamEnv(pred) | Candidate::TraitDef(pred) => {
185                let rustc_obligation = obligation.to_rustc(tcx);
186                let parent_id = rustc_obligation.trait_ref(tcx).def_id;
187                // Do fn-subtyping if the candidate was a fn-trait
188                if tcx.is_fn_trait(parent_id) {
189                    let res = self
190                        .fn_subtype_projection_ty(pred, obligation)
191                        .unwrap_or_else(|err| tracked_span_bug!("{err:?}"));
192                    Ok(res)
193                } else {
194                    Ok(pred.skip_binder().term)
195                }
196            }
197            Candidate::UserDefinedImpl(impl_def_id) => {
198                // Given a projection obligation
199                //     <IntoIter<{v. i32[v] | v > 0}, Global> as Iterator>::Item
200                // and the id of a rust impl block
201                //     impl<T, A: Allocator> Iterator for IntoIter<T, A>
202
203                // 1. MATCH the self type of the rust impl block and the flux self type of the obligation
204                //    to infer a substitution
205                //        IntoIter<{v. i32[v] | v > 0}, Global> MATCH IntoIter<T, A>
206                //            => {T -> {v. i32[v] | v > 0}, A -> Global}
207
208                let impl_trait_ref = self.genv().impl_trait_ref(impl_def_id)?.skip_binder();
209
210                let generics = self.tcx().generics_of(impl_def_id);
211
212                let mut subst = TVarSubst::new(generics);
213                for (a, b) in iter::zip(&impl_trait_ref.args, &obligation.args) {
214                    subst.generic_args(a, b);
215                }
216
217                // 2. Gather the ProjectionPredicates and solve them see issue-808.rs
218                self.resolve_projection_predicates(&mut subst, impl_def_id)?;
219
220                let args = subst.finish(self.tcx(), generics)?;
221
222                // 3. Get the associated type in the impl block and apply the substitution to it
223                let assoc_type_id = tcx
224                    .associated_items(impl_def_id)
225                    .in_definition_order()
226                    .find(|item| item.trait_item_def_id() == Some(obligation.def_id()))
227                    .map(|item| item.def_id)
228                    .ok_or_else(|| {
229                        query_bug!("no associated type for {obligation:?} in impl {impl_def_id:?}")
230                    })?;
231                Ok(self
232                    .genv()
233                    .type_of(assoc_type_id)?
234                    .instantiate(tcx, &args, &[])
235                    .expect_subset_ty_ctor())
236            }
237        }
238    }
239
240    fn fn_subtype_projection_ty(
241        &mut self,
242        actual: Binder<ProjectionPredicate>,
243        oblig: &AliasTerm,
244    ) -> InferResult<SubsetTyCtor> {
245        // Step 1: bs <- unpack(b1...)
246        let obligs: Vec<_> = oblig
247            .args
248            .iter()
249            .map(|arg| {
250                match arg {
251                    GenericArg::Ty(ty) => GenericArg::Ty(self.infcx.unpack(ty)),
252                    GenericArg::Base(ctor) => GenericArg::Ty(self.infcx.unpack(&ctor.to_ty())),
253                    _ => arg.clone(),
254                }
255            })
256            .collect();
257
258        let span = self.infcx.span;
259        let mut infcx = self.infcx.at(span);
260
261        let actual = infcx.ensure_resolved_evars(|infcx| {
262            // Step 2: as <- fresh(a1...)
263            let actual = actual
264                .replace_bound_vars(
265                    |_| rty::ReErased,
266                    |sort, mode, _| infcx.fresh_infer_var(sort, mode),
267                )
268                .deeply_normalize(infcx)?;
269
270            let actuals = actual.projection_term.args.iter().map(|arg| {
271                match arg {
272                    GenericArg::Base(ctor) => GenericArg::Ty(ctor.to_ty()),
273                    _ => arg.clone(),
274                }
275            });
276
277            // Step 3: bs <: as
278            for (a, b) in izip!(actuals.skip(1), obligs.iter().skip(1)) {
279                infcx.subtyping_generic_args(
280                    Variance::Contravariant,
281                    &a,
282                    b,
283                    crate::infer::ConstrReason::Predicate,
284                )?;
285            }
286            Ok(actual)
287        })?;
288        // Step 4: check all evars are solved, plug back into ProjectionPredicate
289        let actual = infcx.fully_resolve_evars(&actual);
290
291        // Step 5: generate "fresh" type for actual.term,
292        let oblig_term = actual.term.with_holes().replace_holes(|binders, kind| {
293            assert!(kind == rty::HoleKind::Pred);
294            let scope = &self.scope;
295            infcx.fresh_kvar_in_scope(binders, scope, KVarEncoding::Conj)
296        });
297
298        // Step 6: subtyping obligation on output
299        infcx.subtyping(
300            &actual.term.to_ty(),
301            &oblig_term.to_ty(),
302            crate::infer::ConstrReason::Predicate,
303        )?;
304        // Ok(ProjectionPredicate { projection_ty: actual.projection_ty, term: oblig_term })
305        Ok(oblig_term)
306    }
307
308    fn assemble_candidates_from_predicates(
309        &mut self,
310        predicates: &List<Clause>,
311        obligation: &AliasTerm,
312        ctor: fn(Binder<ProjectionPredicate>) -> Candidate,
313        candidates: &mut Vec<Candidate>,
314    ) {
315        let tcx = self.tcx();
316        let rustc_obligation = obligation.to_rustc(tcx);
317
318        for predicate in predicates {
319            if let Some(pred) = predicate.as_projection_clause()
320                && pred.skip_binder_ref().projection_term.to_rustc(tcx) == rustc_obligation
321            {
322                candidates.push(ctor(pred));
323            }
324        }
325    }
326
327    fn assemble_candidates_from_param_env(
328        &mut self,
329        obligation: &AliasTerm,
330        candidates: &mut Vec<Candidate>,
331    ) {
332        let predicates = self.param_env.clone();
333        self.assemble_candidates_from_predicates(
334            &predicates,
335            obligation,
336            Candidate::ParamEnv,
337            candidates,
338        );
339    }
340
341    fn assemble_candidates_from_trait_def(
342        &mut self,
343        obligation: &AliasTerm,
344        candidates: &mut Vec<Candidate>,
345    ) -> InferResult {
346        if let GenericArg::Base(ctor) = &obligation.args[0]
347            && let BaseTy::Alias(alias_ty @ AliasTy { kind: AliasKind::Opaque { def_id }, .. }) =
348                ctor.as_bty_skipping_binder()
349        {
350            debug_assert!(!alias_ty.has_escaping_bvars());
351            let bounds = self.genv().item_bounds(*def_id)?.instantiate(
352                self.tcx(),
353                &alias_ty.args,
354                &alias_ty.refine_args,
355            );
356            self.assemble_candidates_from_predicates(
357                &bounds,
358                obligation,
359                Candidate::TraitDef,
360                candidates,
361            );
362        }
363        Ok(())
364    }
365
366    fn assemble_candidates_from_impls(
367        &mut self,
368        obligation: &AliasTerm,
369        candidates: &mut Vec<Candidate>,
370    ) -> QueryResult {
371        let trait_ref = obligation.to_rustc(self.tcx()).trait_ref(self.tcx());
372        let trait_ref = self.tcx().erase_and_anonymize_regions(trait_ref);
373        let trait_pred = Obligation::new(
374            self.tcx(),
375            ObligationCause::dummy(),
376            self.rustc_param_env(),
377            trait_ref,
378        );
379        // FIXME(nilehmann) This is a patch to not panic inside rustc so we are
380        // able to catch the bug
381        if trait_pred.has_escaping_bound_vars() {
382            tracked_span_bug!();
383        }
384        match self.selcx.select(&trait_pred) {
385            Ok(Some(ImplSource::UserDefined(impl_data))) => {
386                candidates.push(Candidate::UserDefinedImpl(impl_data.impl_def_id));
387            }
388            Ok(_) => (),
389            Err(e) => bug!("error selecting {trait_pred:?}: {e:?}"),
390        }
391        Ok(())
392    }
393
394    fn def_id(&self) -> DefId {
395        self.infcx.def_id
396    }
397
398    fn genv(&self) -> GlobalEnv<'genv, 'tcx> {
399        self.infcx.genv
400    }
401
402    fn tcx(&self) -> TyCtxt<'tcx> {
403        self.selcx.tcx()
404    }
405
406    fn rustc_param_env(&self) -> rustc_middle::ty::ParamEnv<'tcx> {
407        self.selcx.tcx().param_env(self.def_id())
408    }
409}
410
411impl FallibleTypeFolder for Normalizer<'_, '_, '_, '_> {
412    type Error = QueryErr;
413
414    fn try_fold_sort(&mut self, sort: &Sort) -> Result<Sort, Self::Error> {
415        match sort {
416            Sort::Alias(AliasTy { kind: AliasKind::Free { def_id }, args, refine_args }) => {
417                self.genv()
418                    .normalize_free_alias_sort(*def_id, args, refine_args)?
419                    .try_fold_with(self)
420            }
421            Sort::Alias(alias_ty @ AliasTy { kind: AliasKind::Projection { .. }, .. }) => {
422                let (changed, ctor) = self.normalize_projection_ty(&alias_ty.to_alias_term())?;
423                let sort = ctor.sort();
424                if changed { sort.try_fold_with(self) } else { Ok(sort) }
425            }
426            _ => sort.try_super_fold_with(self),
427        }
428    }
429
430    // As shown in https://github.com/flux-rs/flux/issues/711 one round of `normalize_projections`
431    // can replace one projection e.g. `<Rev<Iter<[i32]> as Iterator>::Item` with another e.g.
432    // `<Iter<[i32]> as Iterator>::Item` We want to compute a "fixpoint" i.e. keep going until no
433    // change, so that e.g. the above is normalized all the way to `i32`, which is what the `changed`
434    // is for.
435    fn try_fold_ty(&mut self, ty: &Ty) -> Result<Ty, Self::Error> {
436        match ty.kind() {
437            TyKind::Indexed(
438                BaseTy::Alias(AliasTy { kind: AliasKind::Free { def_id }, args, refine_args }),
439                idx,
440            ) => {
441                Ok(self
442                    .genv()
443                    .type_of(*def_id)?
444                    .instantiate(self.tcx(), args, refine_args)
445                    .expect_ctor()
446                    .replace_bound_reft(idx))
447            }
448            TyKind::Indexed(
449                BaseTy::Alias(alias_ty @ AliasTy { kind: AliasKind::Projection { .. }, .. }),
450                idx,
451            ) => {
452                let (changed, ctor) = self.normalize_projection_ty(&alias_ty.to_alias_term())?;
453                let ty = ctor.replace_bound_reft(idx).to_ty();
454                if changed { ty.try_fold_with(self) } else { Ok(ty) }
455            }
456            _ => ty.try_super_fold_with(self),
457        }
458    }
459
460    fn try_fold_subset_ty(&mut self, sty: &SubsetTy) -> Result<SubsetTy, Self::Error> {
461        match &sty.bty {
462            BaseTy::Alias(AliasTy { kind: AliasKind::Free { .. }, .. }) => {
463                // Weak aliases are always expanded during conversion. We could in theory normalize
464                // them here but we don't guaranatee that type aliases expand to a subset ty. If we
465                // ever stop expanding aliases during conv we would need to guarantee that aliases
466                // used as a generic base expand to a subset type.
467                tracked_span_bug!()
468            }
469            BaseTy::Alias(alias_ty @ AliasTy { kind: AliasKind::Projection { .. }, .. }) => {
470                let (changed, ctor) = self.normalize_projection_ty(&alias_ty.to_alias_term())?;
471                let ty = ctor.replace_bound_reft(&sty.idx).strengthen(&sty.pred);
472                if changed { ty.try_fold_with(self) } else { Ok(ty) }
473            }
474            _ => sty.try_super_fold_with(self),
475        }
476    }
477
478    fn try_fold_expr(&mut self, expr: &Expr) -> Result<Expr, Self::Error> {
479        if let ExprKind::Alias(alias_pred, refine_args) = expr.kind() {
480            let (changed, e) = normalize_alias_reft(
481                self.genv(),
482                self.def_id(),
483                self.selcx.infcx,
484                alias_pred,
485                refine_args,
486            )?;
487            if changed { e.try_fold_with(self) } else { Ok(e) }
488        } else {
489            expr.try_super_fold_with(self)
490        }
491    }
492
493    fn try_fold_const(&mut self, c: &Const) -> Result<Const, Self::Error> {
494        let c = c.to_rustc(self.tcx());
495        rustc_trait_selection::traits::evaluate_const(self.selcx.infcx, c, self.rustc_param_env())
496            .lower(self.tcx())
497            .map_err(|e| QueryErr::unsupported(self.def_id(), e.into_err()))
498    }
499}
500
501#[derive(Debug)]
502pub enum Candidate {
503    UserDefinedImpl(DefId),
504    ParamEnv(Binder<ProjectionPredicate>),
505    TraitDef(Binder<ProjectionPredicate>),
506}
507
508#[derive(Debug)]
509struct TVarSubst {
510    args: Vec<Option<GenericArg>>,
511}
512
513impl GenericsSubstDelegate for &TVarSubst {
514    type Error = ();
515
516    fn ty_for_param(&mut self, param_ty: rustc_middle::ty::ParamTy) -> Result<Ty, Self::Error> {
517        match self.args.get(param_ty.index as usize) {
518            Some(Some(GenericArg::Ty(ty))) => Ok(ty.clone()),
519            Some(None) => Err(()),
520            arg => tracked_span_bug!("expected type for generic parameter, found `{arg:?}`"),
521        }
522    }
523
524    fn sort_for_param(&mut self, param_ty: rustc_middle::ty::ParamTy) -> Result<Sort, Self::Error> {
525        match self.args.get(param_ty.index as usize) {
526            Some(Some(GenericArg::Base(ctor))) => Ok(ctor.sort()),
527            Some(None) => Err(()),
528            arg => tracked_span_bug!("expected type for generic parameter, found `{arg:?}`"),
529        }
530    }
531
532    fn ctor_for_param(
533        &mut self,
534        param_ty: rustc_middle::ty::ParamTy,
535    ) -> Result<SubsetTyCtor, Self::Error> {
536        match self.args.get(param_ty.index as usize) {
537            Some(Some(GenericArg::Base(ctor))) => Ok(ctor.clone()),
538            Some(None) => Err(()),
539            arg => tracked_span_bug!("expected type for generic parameter, found `{arg:?}`"),
540        }
541    }
542
543    fn region_for_param(
544        &mut self,
545        ebr: rustc_middle::ty::EarlyParamRegion,
546    ) -> Result<Region, Self::Error> {
547        match self.args.get(ebr.index as usize) {
548            Some(Some(GenericArg::Lifetime(region))) => Ok(*region),
549            Some(None) => Err(()),
550            arg => tracked_span_bug!("expected region for generic parameter, found `{arg:?}`"),
551        }
552    }
553
554    fn expr_for_param_const(&self, _param_const: rustc_middle::ty::ParamConst) -> Expr {
555        tracked_span_bug!()
556    }
557
558    fn const_for_param(&mut self, _param: &Const) -> Const {
559        tracked_span_bug!()
560    }
561}
562
563struct SortNormalizer<'infcx, 'genv, 'tcx> {
564    def_id: DefId,
565    infcx: &'infcx rustc_infer::infer::InferCtxt<'tcx>,
566    genv: GlobalEnv<'genv, 'tcx>,
567}
568
569impl<'infcx, 'genv, 'tcx> SortNormalizer<'infcx, 'genv, 'tcx> {
570    fn new(
571        def_id: DefId,
572        genv: GlobalEnv<'genv, 'tcx>,
573        infcx: &'infcx rustc_infer::infer::InferCtxt<'tcx>,
574    ) -> Self {
575        Self { def_id, infcx, genv }
576    }
577}
578
579impl FallibleTypeFolder for SortNormalizer<'_, '_, '_> {
580    type Error = QueryErr;
581    fn try_fold_sort(&mut self, sort: &Sort) -> Result<Sort, Self::Error> {
582        match sort {
583            Sort::Alias(AliasTy { kind: AliasKind::Free { def_id }, args, refine_args }) => {
584                self.genv
585                    .normalize_free_alias_sort(*def_id, args, refine_args)?
586                    .try_fold_with(self)
587            }
588            Sort::Alias(alias_ty @ AliasTy { kind: AliasKind::Projection { .. }, .. }) => {
589                let (changed, ctor) = normalize_projection_ty_with_rustc(
590                    self.genv,
591                    self.def_id,
592                    self.infcx,
593                    &alias_ty.to_alias_term(),
594                )?;
595                let sort = ctor.sort();
596                if changed { sort.try_fold_with(self) } else { Ok(sort) }
597            }
598            _ => sort.try_super_fold_with(self),
599        }
600    }
601}
602
603impl TVarSubst {
604    fn new(generics: &rustc_middle::ty::Generics) -> Self {
605        Self { args: vec![None; generics.count()] }
606    }
607
608    fn instantiate_partial<T: TypeFoldable>(&mut self, pred: EarlyBinder<T>) -> Option<T> {
609        let mut folder = GenericsSubstFolder::new(&*self, &[]);
610        pred.skip_binder().try_fold_with(&mut folder).ok()
611    }
612
613    fn finish<'tcx>(
614        self,
615        tcx: TyCtxt<'tcx>,
616        generics: &'tcx rustc_middle::ty::Generics,
617    ) -> QueryResult<Vec<GenericArg>> {
618        self.args
619            .into_iter()
620            .enumerate()
621            .map(|(idx, arg)| {
622                if let Some(arg) = arg {
623                    Ok(arg)
624                } else {
625                    let param = generics.param_at(idx, tcx);
626                    Err(QueryErr::bug(
627                        None,
628                        format!("cannot infer substitution for {param:?} at index {idx}"),
629                    ))
630                }
631            })
632            .try_collect_vec()
633    }
634
635    fn generic_args(&mut self, a: &GenericArg, b: &GenericArg) {
636        match (a, b) {
637            (GenericArg::Ty(a), GenericArg::Ty(b)) => self.tys(a, b),
638            (GenericArg::Lifetime(a), GenericArg::Lifetime(b)) => self.regions(*a, *b),
639            (GenericArg::Base(a), GenericArg::Base(b)) => {
640                self.subset_tys(a, b);
641            }
642            (GenericArg::Const(a), GenericArg::Const(b)) => self.consts(a, b),
643            _ => {}
644        }
645    }
646
647    fn tys(&mut self, a: &Ty, b: &Ty) {
648        if let TyKind::Param(param_ty) = a.kind() {
649            if !b.has_escaping_bvars() {
650                self.insert_generic_arg(param_ty.index, GenericArg::Ty(b.clone()));
651            }
652        } else {
653            let a = a.shallow_canonicalize().as_ty_or_base();
654            let b = b.shallow_canonicalize().as_ty_or_base();
655            if let (TyOrBase::Base(a_ctor), TyOrBase::Base(b_ctor)) = (a, b) {
656                self.subset_tys(&a_ctor, &b_ctor);
657            }
658        }
659    }
660
661    fn subset_tys(&mut self, a: &SubsetTyCtor, b: &SubsetTyCtor) {
662        let bty_a = a.as_bty_skipping_binder();
663        let bty_b = b.as_bty_skipping_binder();
664        if let BaseTy::Param(param_ty) = bty_a {
665            if !b.has_escaping_bvars() {
666                self.insert_generic_arg(param_ty.index, GenericArg::Base(b.clone()));
667            }
668        } else {
669            self.btys(bty_a, bty_b);
670        }
671    }
672
673    fn btys(&mut self, a: &BaseTy, b: &BaseTy) {
674        match (a, b) {
675            (BaseTy::Param(param_ty), _) => {
676                if !b.has_escaping_bvars() {
677                    let sort = b.sort();
678                    let ctor =
679                        Binder::bind_with_sort(SubsetTy::trivial(b.clone(), Expr::nu()), sort);
680                    self.insert_generic_arg(param_ty.index, GenericArg::Base(ctor));
681                }
682            }
683            (BaseTy::Adt(_, a_args), BaseTy::Adt(_, b_args)) => {
684                debug_assert_eq!(a_args.len(), b_args.len());
685                for (a_arg, b_arg) in iter::zip(a_args, b_args) {
686                    self.generic_args(a_arg, b_arg);
687                }
688            }
689            (BaseTy::Array(a_ty, a_n), BaseTy::Array(b_ty, b_n)) => {
690                self.tys(a_ty, b_ty);
691                self.consts(a_n, b_n);
692            }
693            (BaseTy::Tuple(a_tys), BaseTy::Tuple(b_tys)) => {
694                debug_assert_eq!(a_tys.len(), b_tys.len());
695                for (a_ty, b_ty) in iter::zip(a_tys, b_tys) {
696                    self.tys(a_ty, b_ty);
697                }
698            }
699            (BaseTy::Ref(a_re, a_ty, _), BaseTy::Ref(b_re, b_ty, _)) => {
700                self.regions(*a_re, *b_re);
701                self.tys(a_ty, b_ty);
702            }
703            (BaseTy::Slice(a_ty), BaseTy::Slice(b_ty)) => {
704                self.tys(a_ty, b_ty);
705            }
706            _ => {}
707        }
708    }
709
710    fn regions(&mut self, a: Region, b: Region) {
711        if let Region::ReEarlyParam(ebr) = a {
712            self.insert_generic_arg(ebr.index, GenericArg::Lifetime(b));
713        }
714    }
715
716    fn consts(&mut self, a: &Const, b: &Const) {
717        if let ConstKind::Param(param_const) = a.kind {
718            self.insert_generic_arg(param_const.index, GenericArg::Const(b.clone()));
719        }
720    }
721
722    fn insert_generic_arg(&mut self, idx: u32, arg: GenericArg) {
723        if let Some(old) = &self.args[idx as usize]
724            && old != &arg
725        {
726            tracked_span_bug!("ambiguous substitution: old=`{old:?}`, new: `{arg:?}`");
727        }
728        self.args[idx as usize].replace(arg);
729    }
730}
731
732/// Normalize an [`rty::AliasTy`] by converting it to rustc, normalizing it using rustc api, and
733/// then mapping the result back to `rty`. This will lose refinements and it should only be used
734/// to normalize sorts because they should only contain unrefined types. However, we are also using
735/// it as a hack to normalize types in cases where we fail to collect a candidate, this is unsound
736/// and should be removed.
737///
738/// [`rty::AliasTy`]: AliasTy
739fn normalize_projection_ty_with_rustc<'tcx>(
740    genv: GlobalEnv<'_, 'tcx>,
741    def_id: DefId,
742    infcx: &rustc_infer::infer::InferCtxt<'tcx>,
743    obligation: &AliasTerm,
744) -> QueryResult<(bool, SubsetTyCtor)> {
745    let tcx = genv.tcx();
746    let projection_ty = obligation.to_rustc(tcx).expect_ty();
747    let projection_ty = tcx.erase_and_anonymize_regions(projection_ty);
748    let cause = ObligationCause::dummy();
749    let param_env = tcx.param_env(def_id);
750
751    let pre_ty = projection_ty.to_ty(tcx, rustc_middle::ty::IsRigid::No);
752    let at = infcx.at(&cause, param_env);
753    let ty = deeply_normalize::<rustc_middle::ty::Ty<'tcx>, FulfillmentError>(
754        at,
755        rustc_middle::ty::Unnormalized::new(pre_ty),
756    )
757    .map_err(|err| query_bug!("{err:?}"))?;
758
759    // `deeply_normalize` marks aliases it couldn't reduce as `IsRigid::Yes`. Since `IsRigid` is
760    // part of `TyKind::Alias`, comparing the types directly would always report a change for rigid
761    // projections, so reset the flag on both sides before comparing.
762    let changed = rustc_middle::ty::set_aliases_to_non_rigid(tcx, ty).skip_normalization()
763        != rustc_middle::ty::set_aliases_to_non_rigid(tcx, pre_ty).skip_normalization();
764    let rustc_ty = ty.lower(tcx).map_err(|reason| query_bug!("{reason:?}"))?;
765
766    Ok((
767        changed,
768        Refiner::default_for_item(genv, def_id)?
769            .refine_ty_or_base(&rustc_ty)?
770            .expect_base(),
771    ))
772}
773
774/// Do one step of normalization, unfolding associated refinements if they are concrete.
775///
776/// Use this if you are about to match structurally on an [`ExprKind`] and you need associated
777/// refinements to be normalized.
778pub fn structurally_normalize_expr<'tcx>(
779    genv: GlobalEnv<'_, 'tcx>,
780    def_id: DefId,
781    infcx: &rustc_infer::infer::InferCtxt<'tcx>,
782    expr: &Expr,
783) -> QueryResult<Expr> {
784    if let ExprKind::Alias(alias_pred, refine_args) = expr.kind() {
785        let (_, e) = normalize_alias_reft(genv, def_id, infcx, alias_pred, refine_args)?;
786        Ok(e)
787    } else {
788        Ok(expr.clone())
789    }
790}
791
792/// Normalizes an [`AliasReft`]. This uses the trait solver to find the [`ImplSourceUserDefinedData`]
793/// and uses the `args` there, which we map back to Flux via refining. This loses refinements,
794/// but that's fine because [`AliasReft`] should not rely on refinements for trait solving.
795fn normalize_alias_reft<'tcx>(
796    genv: GlobalEnv<'_, 'tcx>,
797    def_id: DefId,
798    infcx: &rustc_infer::infer::InferCtxt<'tcx>,
799    alias_reft: &AliasReft,
800    refine_args: &RefineArgs,
801) -> QueryResult<(bool, Expr)> {
802    let tcx = genv.tcx();
803
804    let is_final = genv.assoc_refinement(alias_reft.assoc_id)?.final_;
805    if is_final {
806        let e = genv
807            .default_assoc_refinement_body(alias_reft.assoc_id)?
808            .unwrap_or_else(|| {
809                bug!("final associated refinement without body - should be caught in desugar")
810            })
811            .instantiate(genv.tcx(), &alias_reft.args, &[])
812            .apply(refine_args);
813        return Ok((true, e));
814    }
815
816    // Get impl source
817    let mut selcx = SelectionContext::new(infcx);
818    let param_env = tcx.param_env(def_id);
819    let trait_ref = alias_reft.to_rustc_trait_ref(tcx);
820    let trait_ref = tcx.erase_and_anonymize_regions(trait_ref);
821    let trait_pred = Obligation::new(tcx, ObligationCause::dummy(), param_env, trait_ref);
822
823    let impl_source = selcx
824        .select(&trait_pred)
825        .map_err(|e| query_bug!("error selecting {trait_pred:?}: {e:?}"))?;
826
827    match impl_source {
828        Some(ImplSource::UserDefined(impl_data)) => {
829            let impl_def_id = impl_data.impl_def_id;
830            let args = Refiner::default_for_item(genv, def_id)?.refine_generic_args(
831                impl_def_id,
832                &impl_data
833                    .args
834                    .lower(tcx)
835                    .map_err(|reason| query_bug!("{reason:?}"))?,
836            )?;
837            let e = genv
838                .assoc_refinement_body_for_impl(alias_reft.assoc_id, impl_def_id)?
839                .instantiate(tcx, &args, &[])
840                .apply(refine_args);
841            Ok((true, e))
842        }
843        Some(ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, _)) => {
844            let e = genv
845                .builtin_assoc_reft_body(infcx.typing_env(param_env), alias_reft)
846                .apply(refine_args);
847            Ok((true, e))
848        }
849        _ => Ok((false, Expr::alias(alias_reft.clone(), refine_args.clone()))),
850    }
851}