Skip to main content

charon_driver/translate/
translate_predicates.rs

1use super::translate_crate::VirtualImplKind;
2use super::translate_ctx::*;
3use crate::hax;
4use charon_lib::{ast::*, ids::IndexVec};
5
6impl<'tcx> TranslateCtx<'tcx> {
7    pub fn recognize_builtin_impl(
8        &self,
9        trait_data: &hax::BuiltinTraitData,
10    ) -> Option<BuiltinImplData> {
11        Some(match trait_data {
12            hax::BuiltinTraitData::Destruct(x) => {
13                match x {
14                    hax::DestructData::Noop => BuiltinImplData::NoopDestruct,
15                    hax::DestructData::Implicit => BuiltinImplData::UntrackedDestruct,
16                    // This is unconditionally replaced by a `TraitImpl` earlier.
17                    hax::DestructData::Glue { .. } => unreachable!(),
18                }
19            }
20            hax::BuiltinTraitData::Alias => unreachable!(),
21            hax::BuiltinTraitData::Auto => BuiltinImplData::Auto,
22            hax::BuiltinTraitData::Other(item) => {
23                use hax::SolverTraitLangItem;
24                // The ones for which we return `None` are those I don't think would show up in a
25                // builtin impl.
26                match item {
27                    SolverTraitLangItem::AsyncFn => BuiltinImplData::AsyncFn,
28                    SolverTraitLangItem::AsyncFnKindHelper => return None,
29                    SolverTraitLangItem::AsyncFnMut => BuiltinImplData::AsyncFnMut,
30                    SolverTraitLangItem::AsyncFnOnce => BuiltinImplData::AsyncFnOnce,
31                    SolverTraitLangItem::AsyncIterator => return None,
32                    SolverTraitLangItem::BikeshedGuaranteedNoDrop => return None,
33                    SolverTraitLangItem::Clone => BuiltinImplData::Clone,
34                    SolverTraitLangItem::Copy => BuiltinImplData::Copy,
35                    SolverTraitLangItem::Coroutine => BuiltinImplData::Coroutine,
36                    SolverTraitLangItem::Debug => return None,
37                    SolverTraitLangItem::Destruct => BuiltinImplData::UntrackedDestruct,
38                    SolverTraitLangItem::DiscriminantKind => BuiltinImplData::DiscriminantKind,
39                    SolverTraitLangItem::Drop => return None,
40                    SolverTraitLangItem::Eq => return None,
41                    SolverTraitLangItem::Field => return None,
42                    SolverTraitLangItem::Fn => BuiltinImplData::Fn,
43                    SolverTraitLangItem::FnAddrTrait => BuiltinImplData::FnAddr,
44                    SolverTraitLangItem::FnMut => BuiltinImplData::FnMut,
45                    SolverTraitLangItem::FnOnce => BuiltinImplData::FnOnce,
46                    SolverTraitLangItem::FnPtrTrait => BuiltinImplData::FnPtr,
47                    SolverTraitLangItem::Freeze => BuiltinImplData::Auto,
48                    SolverTraitLangItem::FusedIterator => return None,
49                    SolverTraitLangItem::Future => BuiltinImplData::Future,
50                    SolverTraitLangItem::Iterator => return None,
51                    SolverTraitLangItem::MetaSized => BuiltinImplData::MetaSized,
52                    SolverTraitLangItem::Move => BuiltinImplData::Auto,
53                    SolverTraitLangItem::PointeeSized => BuiltinImplData::PointeeSized,
54                    SolverTraitLangItem::PointeeTrait => BuiltinImplData::Pointee,
55                    SolverTraitLangItem::Send => BuiltinImplData::Auto,
56                    SolverTraitLangItem::Sized => BuiltinImplData::Sized,
57                    SolverTraitLangItem::Sync => BuiltinImplData::Auto,
58                    SolverTraitLangItem::TransmuteTrait => BuiltinImplData::Transmute,
59                    SolverTraitLangItem::TrivialClone => BuiltinImplData::Auto,
60                    SolverTraitLangItem::TryAsDyn => BuiltinImplData::TryAsDynCompatible,
61                    SolverTraitLangItem::Tuple => BuiltinImplData::Tuple,
62                    SolverTraitLangItem::Unpin => BuiltinImplData::Auto,
63                    SolverTraitLangItem::Unsize => BuiltinImplData::Unsize,
64                }
65            }
66        })
67    }
68}
69
70impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
71    /// If this trait proof is a built-in impl for which we generate a trait impl, return
72    /// the item the impl is attached to and the impl's kind.
73    pub fn recognize_generated_impl_proof(
74        &self,
75        trait_proof: &hax::TraitProof<'tcx>,
76    ) -> Option<(hax::ItemRef<'tcx>, VirtualImplKind)> {
77        let hax::TraitProofKind::Builtin { trait_data, .. } = &trait_proof.kind else {
78            return None;
79        };
80        match trait_data {
81            hax::BuiltinTraitData::Destruct(hax::DestructData::Glue { ty }) => {
82                let item = match ty.kind() {
83                    hax::TyKind::Adt(adt) => &adt.item,
84                    hax::TyKind::Closure(closure) => &closure.item,
85                    hax::TyKind::Array(array) => &array.item,
86                    hax::TyKind::Slice(slice) => &slice.item,
87                    hax::TyKind::Tuple(tuple) => &tuple.item,
88                    _ => return None,
89                };
90                Some((item.clone(), VirtualImplKind::Destruct))
91            }
92            hax::BuiltinTraitData::Other(lang_item) => {
93                let kind = match lang_item {
94                    hax::SolverTraitLangItem::FnOnce => ClosureKind::FnOnce,
95                    hax::SolverTraitLangItem::FnMut => ClosureKind::FnMut,
96                    hax::SolverTraitLangItem::Fn => ClosureKind::Fn,
97                    _ => return None,
98                };
99                // We skip the binder and erase regions to avoid bound vars escaping.
100                let callable_ty = trait_proof
101                    .pred
102                    .hax_skip_binder_ref()
103                    .generic_args
104                    .first()?
105                    .as_type()?;
106                let item = callable_ty.callable_item()?;
107                let item = item.erase(self.hax_state_with_id());
108                Some((item, VirtualImplKind::Callable(kind)))
109            }
110            _ => None,
111        }
112    }
113
114    /// Translates the given predicates and stores them as resuired preciates of the innermost
115    /// binder.
116    ///
117    /// This function should be called **after** we translated the generics (type parameters,
118    /// regions...).
119    pub(crate) fn register_predicates(
120        &mut self,
121        preds: &hax::GenericPredicates<'tcx>,
122        origin: PredicateOrigin,
123    ) -> Result<(), Error> {
124        self.translate_predicates(preds, origin, None)?;
125        Ok(())
126    }
127
128    /// Translates the given predicates. This function should be called **after** we translated the
129    /// generics (type parameters, regions...).
130    pub(crate) fn translate_predicates(
131        &mut self,
132        preds: &hax::GenericPredicates<'tcx>,
133        origin: PredicateOrigin,
134        // Either put clauses there or in the innermost binder.
135        mut trait_clauses: Option<&mut IndexVec<TraitClauseId, TraitParam>>,
136    ) -> Result<(), Error> {
137        if trait_clauses.is_none() {
138            // Register the mapping from trait preds to their id early on, as these can be mentioned
139            // while translating any other predicate including themselves. Each trait pred gives rise
140            // to exactly one trait clause inserted into `trait_clauses`, which we use to compute
141            // clause ids.
142            let next_clause_id = self.innermost_generics_mut().trait_clauses.next_idx();
143            for (i, pred) in preds
144                .predicates
145                .iter()
146                .filter(|pred| {
147                    matches!(
148                        pred.clause.kind.hax_skip_binder_ref(),
149                        hax::ClauseKind::Trait(_)
150                    )
151                })
152                .enumerate()
153            {
154                self.innermost_binder_mut().trait_preds.insert(
155                    pred.id.clone(),
156                    (next_clause_id + i, pred.clause.kind.bound_vars.len()),
157                );
158            }
159        }
160
161        for pred in &preds.predicates {
162            self.translate_predicate(pred, origin.clone(), trait_clauses.as_deref_mut())?;
163        }
164        Ok(())
165    }
166
167    pub(crate) fn translate_poly_trait_ref(
168        &mut self,
169        span: Span,
170        bound_trait_ref: &hax::Binder<hax::TraitRef<'tcx>>,
171    ) -> Result<PolyTraitDeclRef, Error> {
172        self.translate_region_binder(span, bound_trait_ref, move |ctx, trait_ref| {
173            ctx.translate_trait_ref(span, trait_ref)
174        })
175    }
176
177    pub(crate) fn translate_trait_predicate(
178        &mut self,
179        span: Span,
180        trait_pred: &hax::TraitPredicate<'tcx>,
181    ) -> Result<TraitDeclRef, Error> {
182        // we don't handle negative trait predicates.
183        assert!(trait_pred.is_positive);
184        self.translate_trait_ref(span, &trait_pred.trait_ref)
185    }
186
187    pub(crate) fn translate_trait_ref(
188        &mut self,
189        span: Span,
190        trait_ref: &hax::TraitRef<'tcx>,
191    ) -> Result<TraitDeclRef, Error> {
192        self.translate_trait_decl_ref(span, trait_ref)
193    }
194
195    pub(crate) fn translate_predicate(
196        &mut self,
197        pred: &hax::GenericPredicate<'tcx>,
198        mut origin: PredicateOrigin,
199        // Either put clauses there or in the innermost binder.
200        mut trait_clauses: Option<&mut IndexVec<TraitClauseId, TraitParam>>,
201    ) -> Result<(), Error> {
202        use crate::hax::ClauseKind;
203        let clause = &pred.clause;
204        trace!("{:?}", clause);
205        let span = self.translate_span(&pred.span);
206        match clause.kind.hax_skip_binder_ref() {
207            ClauseKind::Trait(trait_pred) => {
208                if matches!(pred.id, hax::GenericPredicateId::TraitSelf) {
209                    origin = PredicateOrigin::TraitSelf;
210                }
211                let trait_pred = self.translate_region_binder(span, &clause.kind, |ctx, _| {
212                    ctx.translate_trait_predicate(span, trait_pred)
213                })?;
214                let clause_id = trait_clauses
215                    .as_deref_mut()
216                    .unwrap_or(&mut self.innermost_generics_mut().trait_clauses)
217                    .push_with(|clause_id| TraitParam {
218                        clause_id,
219                        origin,
220                        span: Some(span),
221                        trait_: trait_pred,
222                    });
223
224                if trait_clauses.is_none() {
225                    // Sanity check.
226                    let expected_clause_id = self
227                        .innermost_binder_mut()
228                        .trait_preds
229                        .get(&pred.id)
230                        .unwrap();
231                    debug_assert_eq!(clause_id, expected_clause_id.0);
232                }
233            }
234            ClauseKind::RegionOutlives(p) => {
235                let pred = self.translate_region_binder(span, &clause.kind, |ctx, _| {
236                    let r0 = ctx.translate_region(span, &p.lhs)?;
237                    let r1 = ctx.translate_region(span, &p.rhs)?;
238                    Ok(OutlivesPred(r0, r1))
239                })?;
240                self.innermost_generics_mut().outlives.push(pred);
241            }
242            ClauseKind::TypeOutlives(p) => {
243                let pred = self.translate_region_binder(span, &clause.kind, |ctx, _| {
244                    let ty = ctx.translate_ty(span, &p.lhs)?;
245                    let r = ctx.translate_region(span, &p.rhs)?;
246                    Ok(OutlivesPred(Region::Lub(ty), r))
247                })?;
248                self.innermost_generics_mut().outlives.push(pred);
249            }
250            ClauseKind::Projection(p) => {
251                // This is used to express constraints over associated types.
252                // For instance:
253                // ```
254                // T : Foo<S = String>
255                //         ^^^^^^^^^^
256                // ```
257                let pred = self.translate_region_binder(span, &clause.kind, |ctx, _| {
258                    let trait_ref = ctx.translate_trait_proof(span, &p.trait_proof)?.erase();
259                    let ty = ctx.translate_ty(span, &p.ty)?;
260                    let type_id =
261                        ctx.translate_assoc_type_id(trait_ref.trait_id(), &p.assoc_item.def_id)?;
262                    Ok(TraitTypeConstraint {
263                        trait_ref,
264                        type_id,
265                        ty,
266                    })
267                })?;
268                self.innermost_generics_mut()
269                    .trait_type_constraints
270                    .push(pred);
271            }
272            ClauseKind::ConstArgHasType(..) => {
273                // These are used for trait resolution to get access to the type of const generics.
274                // We don't need them.
275            }
276            ClauseKind::HostEffect(..) => {
277                // These are used for `const Trait` clauses. Part of the `const_traits` unstable
278                // features. We ignore them for now.
279            }
280            ClauseKind::WellFormed(..) | ClauseKind::ConstEvaluatable(..) => {
281                // This is e.g. a clause `[(); N+1]:` (without anything after the `:`). This is
282                // used to require that the fallible `N+1` expression succeeds, so that it can be
283                // used at the type level. Part of the `generic_const_exprs` unstable feature.
284            }
285            ClauseKind::UnstableFeature(..) => {
286                // Unclear what this means, related to stability markers which we don't care about.
287            }
288            #[expect(unreachable_patterns)]
289            kind => raise_error!(self, span, "Unsupported clause: {:?}", kind),
290        }
291        Ok(())
292    }
293
294    pub(crate) fn translate_trait_proofs(
295        &mut self,
296        span: Span,
297        impl_sources: &[hax::TraitProof<'tcx>],
298    ) -> Result<IndexVec<TraitClauseId, PolyTraitRef>, Error> {
299        impl_sources
300            .iter()
301            .map(|x| self.translate_trait_proof(span, x))
302            .try_collect()
303    }
304
305    #[tracing::instrument(skip(self, span, trait_proof))]
306    pub(crate) fn translate_trait_proof(
307        &mut self,
308        span: Span,
309        trait_proof: &hax::TraitProof<'tcx>,
310    ) -> Result<PolyTraitRef, Error> {
311        let trait_decl_ref = self.translate_poly_trait_ref(span, &trait_proof.pred)?;
312
313        match self.translate_trait_proof_aux(span, trait_proof, trait_decl_ref.clone()) {
314            Ok(res) => Ok(res),
315            Err(err) => {
316                register_error!(self, span, "Error during trait resolution: {}", &err.msg);
317                Ok(PolyTraitRef::new(
318                    TraitRefKind::Unknown(err.msg),
319                    trait_decl_ref,
320                ))
321            }
322        }
323    }
324
325    pub(crate) fn translate_trait_proof_aux(
326        &mut self,
327        span: Span,
328        impl_source: &hax::TraitProof<'tcx>,
329        trait_decl_ref: PolyTraitDeclRef,
330    ) -> Result<PolyTraitRef, Error> {
331        trace!("trait_proof: {:#?}", impl_source);
332        use crate::hax::TraitProofKind;
333
334        let kind = match &impl_source.kind {
335            TraitProofKind::Concrete(item) => {
336                let impl_ref =
337                    self.translate_trait_impl_ref(span, item, TransImplSource::Normal)?;
338                TraitRefKind::TraitImpl(impl_ref)
339            }
340            TraitProofKind::SelfProof => TraitRefKind::SelfId,
341            TraitProofKind::LocalBound(id) => match self.lookup_clause_var(span, id) {
342                Ok((var, region_count)) => {
343                    TraitRefKind::Clause(var, self.translate_erased_region_args(region_count))
344                }
345                Err(err) => TraitRefKind::Unknown(err.msg),
346            },
347            TraitProofKind::Derived {
348                base,
349                path: path_elem,
350            } => {
351                let trait_ref = self.translate_trait_proof(span, base)?.erase();
352                match path_elem {
353                    hax::TraitProofImpliedPredicate::AssocItem {
354                        item,
355                        index,
356                        bound_region_count,
357                    } => {
358                        let assoc_type_id =
359                            self.translate_assoc_type_id(trait_ref.trait_id(), &item.def_id)?;
360                        let generics = self.translate_generic_args(span, item)?;
361                        TraitRefKind::ItemClause {
362                            trait_ref,
363                            type_id: assoc_type_id,
364                            generics,
365                            clause_id: TraitClauseId::new(*index),
366                            clause_args: self.translate_erased_region_args(*bound_region_count),
367                        }
368                    }
369                    hax::TraitProofImpliedPredicate::Parent {
370                        index,
371                        bound_region_count,
372                    } => TraitRefKind::ParentClause(
373                        trait_ref,
374                        TraitClauseId::new(*index),
375                        self.translate_erased_region_args(*bound_region_count),
376                    ),
377                }
378            }
379            TraitProofKind::Dyn(proof) => {
380                // Translate the proof in the context of the clauses bound by the dyn type.
381                let bound_proof = self.translate_dyn_binder(span, proof, |ctx, _, proof| {
382                    ctx.translate_trait_proof(span, proof)
383                })?;
384
385                // Instantiate the fake type with the actual `dyn Trait` and a `TraitRefKind::Dyn`
386                // for each base clause. That way, `TraitRefKind::Dyn` is only used for clauses
387                // directly in the `dyn Trait1 + Trait2` type.
388                let args = {
389                    let dyn_ty = trait_decl_ref.clone().erase().generics.types[0].clone();
390                    assert!(dyn_ty.is_dyn_trait());
391                    let mut args = GenericArgs::new_types([dyn_ty].into());
392                    args.trait_refs = bound_proof
393                        .params
394                        .trait_clauses
395                        .clone()
396                        .substitute(&args)
397                        .map(|clause| PolyTraitRef::new(TraitRefKind::Dyn, clause.trait_));
398                    args
399                };
400                let trait_ref = bound_proof.apply(&args).erase();
401                assert_eq!(trait_ref.trait_id(), trait_decl_ref.skip_binder.id);
402                trait_ref.kind.clone()
403            }
404            TraitProofKind::Builtin {
405                trait_data,
406                proofs: trait_proofs,
407                types,
408                ..
409            } => {
410                let tref = &impl_source.pred;
411                let trait_def = self.poly_hax_def(&tref.hax_skip_binder_ref().def_id)?;
412                match trait_data {
413                    hax::BuiltinTraitData::Alias => {
414                        // We reuse the same `def_id` to generate a blanket impl for the trait.
415                        let mut impl_ref: TraitImplRef = self.translate_item(
416                            span,
417                            &tref.hax_skip_binder_ref().erase(self.hax_state_with_id()),
418                            TransItemSourceKind::TraitImpl(TransImplSource::TraitAlias),
419                        )?;
420                        assert!(
421                            impl_ref.generics.trait_refs.is_empty(),
422                            "found trait alias with non-empty required predicates"
423                        );
424                        impl_ref.generics.trait_refs =
425                            self.translate_trait_proofs(span, trait_proofs)?;
426                        TraitRefKind::TraitImpl(impl_ref)
427                    }
428                    _ if let Some((item, kind)) =
429                        self.recognize_generated_impl_proof(impl_source) =>
430                    {
431                        TraitRefKind::TraitImpl(self.translate_trait_impl_ref(
432                            span,
433                            &item,
434                            TransImplSource::Virtual(kind),
435                        )?)
436                    }
437                    _ if let Some(builtin_data) = self.recognize_builtin_impl(trait_data) => {
438                        let parent_trait_refs = self.translate_trait_proofs(span, trait_proofs)?;
439                        let types: IndexMap<AssocTypeId, _> = if self.monomorphize() {
440                            IndexMap::new()
441                        } else {
442                            let tdecl_id = trait_decl_ref.skip_binder.id;
443                            let mut type_map = IndexMap::new();
444                            for (def_id, ty, trait_proofs) in types {
445                                let assoc_type_id =
446                                    self.translate_assoc_type_id(tdecl_id, def_id)?;
447                                let assoc_ty = TraitAssocTyImpl {
448                                    value: self.translate_ty(span, ty)?,
449                                    implied_trait_refs: self
450                                        .translate_trait_proofs(span, trait_proofs)?,
451                                };
452                                type_map.set_slot_extend(assoc_type_id, assoc_ty);
453                            }
454                            type_map
455                        };
456                        let vtable = self.translate_region_binder(span, tref, |ctx, tref| {
457                            ctx.translate_vtable_instance_ref_no_enqueue(
458                                span,
459                                tref,
460                                tref,
461                                TransImplSource::Marker,
462                            )
463                        })?;
464                        let vtable = self.erase_region_binder(vtable);
465                        TraitRefKind::BuiltinOrAuto {
466                            builtin_data,
467                            parent_trait_refs,
468                            types,
469                            vtable,
470                        }
471                    }
472                    _ => raise_error!(
473                        self,
474                        span,
475                        "found a built-in trait impl we did not recognize: \
476                        {:?} (lang_item={:?})",
477                        trait_def.def_id(),
478                        trait_def.lang_item,
479                    ),
480                }
481            }
482            TraitProofKind::Error(msg) => {
483                if self.error_on_trait_proof_error {
484                    register_error!(self, span, "Error during trait resolution: {}", msg);
485                }
486                TraitRefKind::Unknown(msg.clone())
487            }
488        };
489        Ok(PolyTraitRef::new(kind, trait_decl_ref))
490    }
491}