Skip to main content

charon_driver/translate/
user_type_annotations.rs

1//! Recover the type annotations provided by the user inside a body.
2use itertools::Itertools;
3use rustc_hash::FxHashMap as HashMap;
4use rustc_middle::{mir, ty};
5
6use super::translate_crate::RustcItem;
7use super::translate_ctx::*;
8use crate::frontend as front;
9use charon_lib::ast::*;
10
11struct UserTypeAnnotation {
12    projections: HashMap<Vec<mir::ProjectionKind>, Ty>,
13}
14
15/// User-provided type annotations for this MIR body.
16pub(crate) struct UserTypeAnnotations {
17    annotations: rustc_index::IndexVec<ty::UserTypeAnnotationIndex, UserTypeAnnotation>,
18    pub outlives: Vec<OutlivesPred>,
19}
20
21impl UserTypeAnnotations {
22    /// Translate the annotations for this body. The returned value can then be used to fetch the
23    /// types of annotations.
24    pub(crate) fn new<'tcx>(
25        ctx: &mut ItemTransCtx<'tcx, '_>,
26        body: &mir::Body<'tcx>,
27    ) -> Result<Self, Error> {
28        use mir::visit::Visitor as _;
29        let body_owner = body.source.def_id();
30
31        let mut annotations = body.user_type_annotations.clone();
32        if let RustcItem::Mono(item) = &ctx.item_src.item {
33            // `CanonicalUserTypeAnnotation::user_ty` is deliberately not folded when rustc
34            // instantiates a MIR body, so do the item substitution explicitly.
35            let item = item.clone();
36            let args = item.rustc_args(ctx.frontend_state_with_id());
37            for annotation in &mut annotations {
38                annotation.user_ty.value = front::substitute(
39                    ctx.tcx,
40                    front::UnderOwnerState::typing_env(&ctx.frontend_state),
41                    Some(args),
42                    annotation.user_ty.value,
43                );
44            }
45        }
46
47        let mut recovered = Self {
48            annotations: Default::default(),
49            outlives: Vec::new(),
50        };
51        if annotations.is_empty() {
52            return Ok(recovered);
53        }
54
55        // Gather the projections on user annotations that are actually used. Unused annotation
56        // types can reference items like intrinsics that have already been lowered away.
57        struct CollectProjections(
58            rustc_index::IndexVec<
59                ty::UserTypeAnnotationIndex,
60                SeqHashSet<Vec<mir::ProjectionKind>>,
61            >,
62        );
63        impl<'tcx> mir::visit::Visitor<'tcx> for CollectProjections {
64            fn visit_user_type_projection(&mut self, projection: &mir::UserTypeProjection) {
65                self.0[projection.base].insert(projection.projs.clone());
66            }
67
68            fn visit_const_operand(
69                &mut self,
70                operand: &mir::ConstOperand<'tcx>,
71                location: mir::Location,
72            ) {
73                if let Some(base) = operand.user_ty {
74                    self.0[base].insert(vec![]);
75                }
76                self.super_const_operand(operand, location);
77            }
78
79            fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
80                if let mir::Rvalue::Aggregate(kind, _) = rvalue
81                    && let mir::AggregateKind::Adt(_, _, _, Some(base), _) = **kind
82                {
83                    self.0[base].insert(vec![]);
84                }
85                self.super_rvalue(rvalue, location);
86            }
87        }
88        let mut projections =
89            CollectProjections(annotations.iter().map(|_| SeqHashSet::default()).collect());
90        projections.visit_body(body);
91        for (base, projections) in projections.0.into_iter_enumerated() {
92            let annotation = &annotations[base];
93            let span = ctx.translate_span(&annotation.span);
94            let projections = projections.into_iter().collect_vec();
95            let (tys, outlives) =
96                translate_user_annotation(ctx, body_owner, span, annotation, &projections)?;
97            let annotation = UserTypeAnnotation {
98                projections: projections.into_iter().zip_eq(tys).collect(),
99            };
100            assert_eq!(recovered.annotations.push(annotation), base);
101            recovered.outlives.extend(outlives);
102        }
103        recovered.outlives.sort_unstable();
104        recovered.outlives.dedup();
105        Ok(recovered)
106    }
107
108    /// Get the type of this local and the constraints from its type annotations.
109    pub(crate) fn translate_local_ty<'tcx>(
110        &self,
111        ctx: &mut ItemTransCtx<'tcx, '_>,
112        span: Span,
113        local_id: LocalId,
114        decl: &mir::LocalDecl<'tcx>,
115    ) -> Result<(Ty, Vec<PlaceTypeConstraint>), Error> {
116        let ty = ctx.translate_rustc_ty(span, &decl.ty)?;
117        let mut constraints = Vec::new();
118        if let Some(user_tys) = &decl.user_ty
119            && user_tys.projections().len() != 0
120        {
121            let outer_ref = if decl.is_nonref_binding() {
122                None
123            } else {
124                // In `let ref x: T`, the annotation describes the pointer target. We grab the
125                // appropriate region by using the normal type of the local.
126                let TyKind::Ref(region, _, kind) = ty.kind() else {
127                    raise_error!(ctx, span, "ref binding has non-reference type");
128                };
129                Some((region.clone(), *kind))
130            };
131
132            let annotated_tys = user_tys
133                .projections()
134                .map(|pj| self.translate_projected_annotation(pj))
135                .map(|ty| {
136                    if let Some((region, kind)) = &outer_ref {
137                        TyKind::Ref(region.clone(), ty, *kind).into()
138                    } else {
139                        ty
140                    }
141                });
142            for annotated_ty in annotated_tys {
143                constraints.push(PlaceTypeConstraint {
144                    place: Place::new(local_id, ty.clone()),
145                    ty: annotated_ty,
146                    variance: Variance::Covariant,
147                });
148            }
149        }
150        Ok((ty, constraints))
151    }
152
153    /// Look up the (unprojected) type of an annotation.
154    pub(crate) fn translate_annotation(&self, index: ty::UserTypeAnnotationIndex) -> Option<Ty> {
155        if self.annotations.is_empty() {
156            None
157        } else {
158            Some(self.annotations[index].projections[&[][..]].clone())
159        }
160    }
161
162    /// Look up the type of an annotation.
163    pub(crate) fn translate_projected_annotation(
164        &self,
165        projection: &mir::UserTypeProjection,
166    ) -> Ty {
167        let annotation = &self.annotations[projection.base];
168        annotation.projections[projection.projs.as_slice()].clone()
169    }
170}
171
172/// Translate a user annotation and the outlives obligations needed to validate it.
173fn translate_user_annotation<'tcx>(
174    ctx: &mut ItemTransCtx<'tcx, '_>,
175    owner: front::RDefId,
176    span: Span,
177    annotation: &ty::CanonicalUserTypeAnnotation<'tcx>,
178    projections: &[front::rustc::UserAnnotationProj],
179) -> Result<(Vec<Ty>, Vec<OutlivesPred>), Error> {
180    let ty_constraints = front::rustc::translate_user_annotation(
181        ctx.tcx,
182        front::UnderOwnerState::typing_env(&ctx.frontend_state),
183        owner,
184        annotation,
185        projections,
186    );
187    let ty_constraints = match ty_constraints {
188        Ok(ty_constraints) => ty_constraints,
189        Err(message) => raise_error!(ctx, span, "{message}"),
190    };
191    let ty_constraints: front::Binder<(Vec<front::Ty<'tcx>>, Vec<front::Clause<'tcx>>)> =
192        ctx.catch_sinto(span, &ty_constraints)?;
193    let bound_constraints =
194        ctx.translate_region_binder(span, &ty_constraints, |ctx, (tys, clauses)| {
195            let tys: Vec<Ty> = tys
196                .iter()
197                .map(|ty| ctx.translate_ty(span, ty))
198                .try_collect()?;
199            let mut outlives = Vec::new();
200            for clause in clauses {
201                let pred = ctx.translate_region_binder(span, &clause.kind, |ctx, kind| {
202                    Ok(match kind {
203                        front::ClauseKind::RegionOutlives(p) => OutlivesPred(
204                            ctx.translate_region(span, &p.lhs)?,
205                            ctx.translate_region(span, &p.rhs)?,
206                        ),
207                        front::ClauseKind::TypeOutlives(p) => OutlivesPred(
208                            Region::Lub(ctx.translate_ty(span, &p.lhs)?),
209                            ctx.translate_region(span, &p.rhs)?,
210                        ),
211                        _ => unreachable!("recovered ascription contains a non-region constraint"),
212                    })
213                })?;
214                outlives.push(pred.no_bound_vars());
215            }
216            Ok((tys, outlives))
217        })?;
218    // Instantiate the binder with fresh body regions.
219    let (tys, outlives) = ctx.erase_region_binder(bound_constraints);
220    let outlives = outlives.iter().flat_map(|pred| pred.normalize()).collect();
221    Ok((tys, outlives))
222}