Skip to main content

charon_driver/frontend/
traits.rs

1use rustc_middle::ty;
2use rustc_span::def_id::DefId as RDefId;
3
4pub use rustc_trait_elaboration as elaboration;
5pub use rustc_trait_elaboration::{
6    AssocItemResolution, ElaborationCtx, ItemId, ItemPredicate, ItemPredicateId, ItemPredicates,
7    PredicateDirection, ToPolyTraitRef, erase_and_norm, erase_free_regions, normalize,
8    self_predicate,
9};
10
11use crate::frontend::prelude::*;
12use rustc_data_structures::intern::Interned;
13use std::ops::Deref;
14
15pub type PredicateSearcher<'tcx> = elaboration::PredicateSearcher<'tcx, DefId>;
16
17#[derive(AdtInto)]
18#[args(< S: UnderOwnerState<'tcx> >, from: elaboration::ImpliedPredicate<'tcx, DefId>, state: S as s)]
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub enum TraitProofImpliedPredicate<'tcx> {
21    AssocItem {
22        /// Reference to the item, with generics (for GATs), e.g. the `T` and proof for `T: Clone`
23        /// in the following example:
24        /// ```ignore
25        /// trait Foo {
26        ///     type Type<T: Clone>: Debug;
27        /// }
28        /// ```
29        item: ItemRef<'tcx>,
30        /// The index of this predicate among the trait predicates returned by `ItemPredicates::Implied`.
31        index: usize,
32        /// Number of regions bound by the corresponding clause.
33        bound_region_count: usize,
34    },
35    Parent {
36        /// The index of this predicate among the trait predicates returned by `ItemPredicates::Implied`.
37        index: usize,
38        /// Number of regions bound by the corresponding clause.
39        bound_region_count: usize,
40    },
41}
42
43/// The source of a particular trait implementation. Most often this is either `Concrete` for a
44/// concrete `impl Trait for Type {}` item, or `LocalBound` for a context-bound `where T: Trait`.
45#[derive(AdtInto)]
46#[args(< S: UnderOwnerState<'tcx> >, from: elaboration::TraitProofKind<'tcx, DefId>, state: S as s)]
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48pub enum TraitProofKind<'tcx> {
49    /// A concrete `impl Trait for Type {}` item.
50    Concrete(ItemRef<'tcx>),
51    /// A context-bound clause like `where T: Trait`.
52    LocalBound(GenericPredicateId),
53    /// The implicit `Self: Trait` clause present inside a `trait Trait {}` item.
54    // TODO: should we also get that clause for trait impls?
55    SelfProof,
56    /// `dyn Trait` is a wrapped value with a virtual table for trait
57    /// `Trait`.  In other words, a value `dyn Trait` is a dependent
58    /// triple that gathers a type τ, a value of type τ and an
59    /// instance of type `Trait`.
60    /// `dyn Trait` implements `Trait` using a built-in implementation; this refers to that
61    /// built-in implementation.
62    /// The proof describes how to prove the current predicate in the context of the `dyn Trait`
63    /// self type, e.g. for `<dyn Trait as Supertrait>`.
64    Dyn(DynBinder<'tcx, TraitProof<'tcx>>),
65    /// A built-in trait whose implementation is computed by the compiler, such as `FnMut`. This
66    /// morally points to an invisible `impl` block; as such it contains the information we may
67    /// need from one.
68    Builtin {
69        /// Extra data for the given trait.
70        trait_data: BuiltinTraitData<'tcx>,
71        /// The trait proofs required to satisfy the implied predicates on the trait declaration.
72        /// E.g. since `FnMut: FnOnce`, a built-in `T: FnMut` impl would have a proof for
73        /// `T: FnOnce`.
74        proofs: Vec<TraitProof<'tcx>>,
75        /// The values of the associated types for this trait.
76        types: Vec<(DefId, Ty<'tcx>, Vec<TraitProof<'tcx>>)>,
77    },
78    /// A predicate implied by `base` by following `path`.
79    Derived {
80        base: TraitProof<'tcx>,
81        path: TraitProofImpliedPredicate<'tcx>,
82    },
83    /// An error happened while resolving traits.
84    Error(String),
85}
86
87impl<'tcx> TraitProofKind<'tcx> {
88    /// Returns `true` if this is an error proof.
89    pub fn is_error(&self) -> bool {
90        matches!(self, TraitProofKind::Error(_))
91    }
92}
93
94#[derive(AdtInto)]
95#[args(< S: UnderOwnerState<'tcx> >, from: elaboration::BuiltinTraitData<'tcx>, state: S as s)]
96#[append(FROM_TYPE::Alias => unreachable!("trait aliases use their blanket impl"),)]
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub enum BuiltinTraitData<'tcx> {
99    /// A virtual `Destruct` implementation.
100    /// `Destruct` is implemented automatically for all types. For our purposes, we chose to attach
101    /// the information about `drop_glue` to that trait. This data tells us what kind of
102    /// `drop_glue` the target type has.
103    Destruct(DestructData<'tcx>),
104    /// An auto-trait.
105    Auto,
106    /// Some other builtin trait.
107    Other(SolverTraitLangItem),
108}
109
110sinto_reexport!(rustc_middle::ty::lang_items::SolverTraitLangItem);
111
112#[derive(AdtInto)]
113#[args(< S: UnderOwnerState<'tcx> >, from: elaboration::DestructData<'tcx>, state: S as s)]
114#[derive(Debug, Clone, PartialEq, Eq, Hash)]
115pub enum DestructData<'tcx> {
116    /// A drop that does nothing, e.g. for scalars and pointers.
117    Noop,
118    /// An implicit `Destruct` local clause, if the `resolve_destruct_bounds` option is `false`. If
119    /// that option is `true`, we'll add `Destruct` bounds to every type param, and use that to
120    /// resolve `Destruct` impls of generics. If it's `false`, we use this variant to indicate that
121    /// the clause comes from a generic or associated type.
122    Implicit,
123    /// The `drop_glue` is known and non-trivial.
124    Glue {
125        /// The type we're generating glue for.
126        ty: Ty<'tcx>,
127    },
128}
129
130/// A `TraitProof` describes the full data of a trait implementation. Because of generics, this may
131/// need to combine several concrete trait implementation items. For example, `((1u8, 2u8),
132/// "hello").clone()` combines the generic implementation of `Clone` for `(A, B)` with the
133/// concrete implementations for `u8` and `&str`, represented as a tree.
134#[derive(Debug, Clone, PartialEq, Eq, Hash)]
135pub struct TraitProof<'tcx> {
136    contents: Interned<'tcx, TraitProofContents<'tcx>>,
137}
138
139impl<'tcx> Deref for TraitProof<'tcx> {
140    type Target = TraitProofContents<'tcx>;
141
142    fn deref(&self) -> &Self::Target {
143        &self.contents
144    }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Hash)]
148pub struct TraitProofContents<'tcx> {
149    /// The trait predicate this is an impl for.
150    pub pred: Binder<TraitRef<'tcx>>,
151    /// The kind of implemention of the root of the tree.
152    pub kind: TraitProofKind<'tcx>,
153}
154
155impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, TraitProof<'tcx>>
156    for elaboration::TraitProof<'tcx, DefId>
157{
158    fn sinto(&self, s: &S) -> TraitProof<'tcx> {
159        let kind = match &self.kind {
160            elaboration::TraitProofKind::Builtin {
161                trait_data: elaboration::BuiltinTraitData::Alias,
162                ..
163            } => {
164                let trait_ref = elaboration::erase_binder(s.base().tcx, self.pred);
165                let impl_id = trait_ref
166                    .def_id
167                    .sinto(s)
168                    .make_derived(DerivedItemKind::TraitAliasImpl);
169                TraitProofKind::Concrete(ItemRef::translate_from_frontend_def_id(
170                    s,
171                    impl_id,
172                    trait_ref.args,
173                ))
174            }
175            kind => kind.sinto(s),
176        };
177        TraitProof {
178            contents: s.base().trait_proof_interner.intern(TraitProofContents {
179                pred: self.pred.sinto(s),
180                kind,
181            }),
182        }
183    }
184}
185
186/// Given a clause `clause` in the context of some impl block `impl_did`, susbts correctly `Self`
187/// from `clause` and (1) derive a `Clause` and (2) resolve a `TraitProof`.
188pub fn super_clause_to_clause_and_trait_proof<'tcx, S: UnderOwnerState<'tcx>>(
189    s: &S,
190    impl_did: rustc_span::def_id::DefId,
191    clause: rustc_middle::ty::Clause<'tcx>,
192    span: rustc_span::Span,
193) -> Option<(Clause<'tcx>, TraitProof<'tcx>, Span)> {
194    let tcx = s.base().tcx;
195    if !matches!(
196        tcx.def_kind(impl_did),
197        rustc_hir::def::DefKind::Impl { of_trait: true }
198    ) {
199        return None;
200    }
201    let impl_trait_ref = rustc_middle::ty::Binder::dummy(
202        tcx.impl_trait_ref(impl_did)
203            .instantiate_identity()
204            .skip_normalization(),
205    );
206    let new_clause = clause.instantiate_supertrait(tcx, impl_trait_ref);
207    let trait_proof = solve_trait(
208        s,
209        new_clause
210            .as_predicate()
211            .as_trait_clause()?
212            .to_poly_trait_ref(),
213    );
214    let new_clause = new_clause.sinto(s);
215    Some((new_clause, trait_proof, span.sinto(s)))
216}
217
218/// This is the entrypoint of the solving.
219#[tracing::instrument(level = "trace", skip(s))]
220pub fn solve_trait<'tcx, S: UnderOwnerState<'tcx>>(
221    s: &S,
222    trait_ref: rustc_middle::ty::PolyTraitRef<'tcx>,
223) -> TraitProof<'tcx> {
224    if let Some(trait_proof) = s.with_cache(|cache| cache.trait_proofs.get(&trait_ref).cloned()) {
225        return trait_proof;
226    }
227    let trait_proof = s.with_predicate_searcher(|pred_searcher, elab_ctx| {
228        pred_searcher.resolve(elab_ctx, &trait_ref)
229    });
230    let trait_proof: TraitProof = trait_proof.sinto(s);
231    s.with_cache(|cache| cache.trait_proofs.insert(trait_ref, trait_proof.clone()));
232    trait_proof
233}
234
235/// Translate a reference to an item, resolving the appropriate trait clauses as needed.
236#[tracing::instrument(level = "trace", skip(s), ret)]
237pub fn translate_item_ref<'tcx, S: UnderOwnerState<'tcx>>(
238    s: &S,
239    def_id: RDefId,
240    generics: ty::GenericArgs<'tcx>,
241) -> ItemRef<'tcx> {
242    ItemRef::translate(s, def_id, generics)
243}
244
245/// Solve the trait obligations for implementing a trait (or for trait associated type bounds) in
246/// the current context.
247#[tracing::instrument(level = "trace", skip(s), ret)]
248pub fn solve_item_implied_traits<'tcx, S: UnderOwnerState<'tcx>>(
249    s: &S,
250    def_id: DefId,
251    generics: ty::GenericArgs<'tcx>,
252) -> Vec<TraitProof<'tcx>> {
253    let predicates = ItemPredicates::implied(s.base().elab_ctx, &s.base_state(), def_id);
254    solve_item_traits_inner(s, generics, predicates)
255}
256
257/// Apply the given generics to the provided clauses and resolve the trait references in the
258/// current context.
259fn solve_item_traits_inner<'tcx, S: UnderOwnerState<'tcx>>(
260    s: &S,
261    generics: ty::GenericArgs<'tcx>,
262    predicates: ItemPredicates<'tcx, DefId>,
263) -> Vec<TraitProof<'tcx>> {
264    let tcx = s.base().tcx;
265    let typing_env = s.typing_env();
266    predicates
267        .iter_trait_clauses()
268        // Substitute the item generics
269        .map(|(_, trait_ref)| ty::EarlyBinder::bind(tcx, trait_ref).instantiate(tcx, generics))
270        .map(|trait_ref| normalize(tcx, typing_env, trait_ref))
271        // Resolve
272        .map(|trait_ref| solve_trait(s, trait_ref))
273        .collect()
274}
275
276/// Retrieve the `Self: Trait` clause for a trait associated item.
277pub fn self_clause_for_item<'tcx, S: UnderOwnerState<'tcx>>(
278    s: &S,
279    def_id: RDefId,
280    generics: rustc_middle::ty::GenericArgs<'tcx>,
281) -> Option<TraitProof<'tcx>> {
282    let tcx = s.base().tcx;
283
284    let tr_def_id = tcx.trait_of_assoc(def_id)?;
285    // The "self" predicate in the context of the trait.
286    let self_pred = self_predicate(tcx, tr_def_id);
287    // Substitute to be in the context of the current item.
288    let generics = generics.truncate_to(tcx, tcx.generics_of(tr_def_id));
289    let self_pred = ty::EarlyBinder::bind(tcx, self_pred)
290        .instantiate(tcx, generics)
291        .skip_normalization();
292
293    // Resolve
294    Some(solve_trait(s, self_pred))
295}
296
297/// Solve the `T: Sized` predicate.
298pub fn solve_sized<'tcx, S: UnderOwnerState<'tcx>>(s: &S, ty: ty::Ty<'tcx>) -> TraitProof<'tcx> {
299    let tcx = s.base().tcx;
300    let sized_trait = tcx.lang_items().sized_trait().unwrap();
301    let ty = erase_free_regions(tcx, ty);
302    let tref = ty::Binder::dummy(ty::TraitRef::new(tcx, sized_trait, [ty]));
303    solve_trait(s, tref)
304}
305
306/// Solve the `T: Copy` predicate.
307pub fn solve_copy<'tcx, S: UnderOwnerState<'tcx>>(
308    s: &S,
309    ty: ty::Ty<'tcx>,
310) -> Option<TraitProof<'tcx>> {
311    let tcx = s.base().tcx;
312    let copy_trait = tcx.lang_items().copy_trait().unwrap();
313    let ty = erase_free_regions(tcx, ty);
314    let tref = ty::Binder::dummy(ty::TraitRef::new(tcx, copy_trait, [ty]));
315    let proof = solve_trait(s, tref);
316    (!proof.kind.is_error()).then_some(proof)
317}
318
319/// Solve the `T: Destruct` predicate.
320pub fn solve_destruct<'tcx, S: UnderOwnerState<'tcx>>(s: &S, ty: ty::Ty<'tcx>) -> TraitProof<'tcx> {
321    let tcx = s.base().tcx;
322    let destruct_trait = tcx.lang_items().destruct_trait().unwrap();
323    let tref = ty::Binder::dummy(ty::TraitRef::new(tcx, destruct_trait, [ty]));
324    solve_trait(s, tref)
325}