Skip to main content

charon_lib/transform/add_missing_info/
infer_higher_ranked_args.rs

1//! Infer some erased higher-ranked clause arguments.
2use crate::ast::*;
3use crate::transform::{TransformCtx, ctx::TransformPass};
4
5#[derive(Visitor)]
6struct Infer<'a> {
7    traits: &'a IndexMap<TraitDeclId, TraitDecl>,
8    binders: BindingStack<GenericParams>,
9}
10
11impl VisitorWithBinderStack for Infer<'_> {
12    fn binder_stack_mut(&mut self) -> &mut BindingStack<GenericParams> {
13        &mut self.binders
14    }
15}
16
17impl Infer<'_> {
18    fn infer(&self, proof: &TraitRef) -> Option<TraitRef> {
19        let mut kind = proof.kind.clone();
20        // Retrieve the poly trait ref that this proof refers to, along with the provided
21        // arguments.
22        let (clause, args): (PolyTraitDeclRef, &mut RegionArgs) = match &mut kind {
23            TraitRefKind::Clause(var, args) => (
24                self.binders
25                    .get_var_and_shift(*var, |clause| clause.trait_.clone())?,
26                args,
27            ),
28            TraitRefKind::ParentClause(parent, id, args) => (
29                self.traits
30                    .get(parent.trait_id())?
31                    .implied_clauses
32                    .get(*id)?
33                    .trait_
34                    .clone()
35                    .try_substitute_with_tref(parent)
36                    .ok()?,
37                args,
38            ),
39            TraitRefKind::ItemClause {
40                trait_ref: parent,
41                type_id,
42                generics,
43                clause_id,
44                clause_args,
45            } => {
46                let assoc = self
47                    .traits
48                    .get(parent.trait_id())?
49                    .types
50                    .get(*type_id)?
51                    .clone()
52                    .try_substitute_with_tref(parent)
53                    .ok()?;
54                let clause = assoc
55                    .skip_binder
56                    .implied_clauses
57                    .get(*clause_id)?
58                    .trait_
59                    .clone()
60                    .try_substitute_with_self(generics, &parent.kind)
61                    .ok()?;
62                (clause, clause_args)
63            }
64            _ => return None,
65        };
66        if !args.regions.iter().any(Region::is_erased) {
67            return None;
68        }
69
70        // The predicate that this proof proves, this time the cached version.
71        let target = RegionBinder::empty(proof.trait_decl_ref.clone());
72        // By zipping the two predicates, get a list of args that if applied to `clause` would
73        // produce `target`.
74        let inferred: RegionArgs = clause.infer_region_mapping(&target)?.no_bound_vars();
75        if args.regions.len() != inferred.regions.len() {
76            return None;
77        }
78        // Replace the erased regions in our args with the inferred ones.
79        for (arg, inferred) in args.regions.iter_mut().zip(inferred.regions) {
80            if arg.is_erased() {
81                *arg = inferred;
82            }
83        }
84        // Matching is best-effort. Only retain a reconstruction if it proves exactly the cached
85        // predicate.
86        if clause.apply(args.clone()) != proof.trait_decl_ref {
87            return None;
88        }
89        Some(TraitRef::new(kind, proof.trait_decl_ref.clone()))
90    }
91}
92
93impl VisitAstMut for Infer<'_> {
94    fn visit<T: AstVisitable>(&mut self, value: &mut T) -> ControlFlow<Self::Break> {
95        VisitWithBinderStack::new(self).visit(value)
96    }
97
98    fn exit_trait_ref(&mut self, proof: &mut TraitRef) {
99        if let Some(recovered) = self.infer(proof) {
100            *proof = recovered;
101        }
102    }
103}
104
105pub struct Transform;
106
107impl TransformPass for Transform {
108    fn should_run(&self, options: &crate::options::TranslateOptions) -> bool {
109        !options.no_typecheck
110    }
111    fn transform_ctx(&self, ctx: &mut TransformCtx) {
112        ctx.for_each_item_mut(|ctx, mut item| {
113            item.drive_mut(&mut Infer {
114                traits: &ctx.translated.trait_decls,
115                binders: BindingStack::default(),
116            });
117        });
118    }
119}